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

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 (197) hide show
  1. package/README.md +12 -4
  2. package/dist/ort-wasm-simd-threaded.jsep.mjs +24 -24
  3. package/dist/transformers.js +2189 -1015
  4. package/dist/transformers.min.js +16 -16
  5. package/dist/transformers.node.cjs +2234 -1029
  6. package/dist/transformers.node.min.cjs +20 -20
  7. package/dist/transformers.node.min.mjs +20 -20
  8. package/dist/transformers.node.mjs +2194 -1017
  9. package/dist/transformers.web.js +2175 -1001
  10. package/dist/transformers.web.min.js +18 -18
  11. package/package.json +4 -4
  12. package/src/backends/onnx.js +77 -58
  13. package/src/backends/utils/cacheWasm.js +22 -43
  14. package/src/cache_utils.js +62 -0
  15. package/src/configs.js +32 -5
  16. package/src/env.js +36 -6
  17. package/src/image_processors_utils.js +3 -3
  18. package/src/models/auto/modeling_auto.js +14 -1
  19. package/src/models/chatterbox/modeling_chatterbox.js +1 -1
  20. package/src/models/detr/image_processing_detr.js +1 -1
  21. package/src/models/feature_extractors.js +2 -0
  22. package/src/models/gemma3n/modeling_gemma3n.js +2 -0
  23. package/src/models/granite_speech/feature_extraction_granite_speech.js +58 -0
  24. package/src/models/granite_speech/modeling_granite_speech.js +5 -0
  25. package/src/models/granite_speech/processing_granite_speech.js +62 -0
  26. package/src/models/grounding_dino/image_processing_grounding_dino.js +1 -1
  27. package/src/models/idefics3/modeling_idefics3.js +5 -32
  28. package/src/models/image_processors.js +1 -0
  29. package/src/models/lfm2_vl/image_processing_lfm2_vl.js +305 -0
  30. package/src/models/lfm2_vl/modeling_lfm2_vl.js +13 -0
  31. package/src/models/lfm2_vl/processing_lfm2_vl.js +77 -0
  32. package/src/models/llava/modeling_llava.js +1 -1
  33. package/src/models/mistral3/modeling_mistral3.js +2 -2
  34. package/src/models/modeling_utils.js +234 -292
  35. package/src/models/models.js +9 -0
  36. package/src/models/olmo_hybrid/modeling_olmo_hybrid.js +5 -0
  37. package/src/models/paligemma/modeling_paligemma.js +2 -25
  38. package/src/models/processors.js +3 -0
  39. package/src/models/qwen2_5_vl/modeling_qwen2_5_vl.js +5 -1
  40. package/src/models/qwen2_moe/modeling_qwen2_moe.js +5 -0
  41. package/src/models/qwen2_vl/image_processing_qwen2_vl.js +1 -41
  42. package/src/models/qwen2_vl/modeling_qwen2_vl.js +36 -3
  43. package/src/models/qwen3_5/modeling_qwen3_5.js +1 -0
  44. package/src/models/qwen3_5_moe/modeling_qwen3_5_moe.js +2 -1
  45. package/src/models/qwen3_moe/modeling_qwen3_moe.js +5 -0
  46. package/src/models/qwen3_next/modeling_qwen3_next.js +5 -0
  47. package/src/models/qwen3_vl/modeling_qwen3_vl.js +2 -1
  48. package/src/models/qwen3_vl_moe/modeling_qwen3_vl_moe.js +4 -0
  49. package/src/models/registry.js +39 -4
  50. package/src/models/sam/image_processing_sam.js +1 -1
  51. package/src/models/session.js +17 -6
  52. package/src/models/smolvlm/modeling_smolvlm.js +7 -0
  53. package/src/models/ultravox/modeling_ultravox.js +1 -3
  54. package/src/models/voxtral/modeling_voxtral.js +3 -0
  55. package/src/models/voxtral_realtime/feature_extraction_voxtral_realtime.js +71 -0
  56. package/src/models/voxtral_realtime/modeling_voxtral_realtime.js +239 -0
  57. package/src/models/voxtral_realtime/processing_voxtral_realtime.js +113 -0
  58. package/src/models/whisper/feature_extraction_whisper.js +2 -12
  59. package/src/pipelines/index.js +2 -84
  60. package/src/pipelines.js +40 -77
  61. package/src/transformers.js +2 -0
  62. package/src/utils/audio.js +18 -2
  63. package/src/utils/cache/CrossOriginStorageCache.js +251 -0
  64. package/src/utils/cache/FileCache.js +128 -0
  65. package/src/utils/cache/cross-origin-storage.d.ts +38 -0
  66. package/src/utils/cache.js +8 -3
  67. package/src/utils/hub/{files.js → FileResponse.js} +0 -105
  68. package/src/utils/hub/utils.js +35 -1
  69. package/src/utils/hub.js +6 -5
  70. package/src/utils/image.js +12 -13
  71. package/src/utils/lru_cache.js +67 -0
  72. package/src/utils/memoize_promise.js +45 -0
  73. package/src/utils/model_registry/ModelRegistry.js +70 -23
  74. package/src/utils/model_registry/get_file_metadata.js +14 -2
  75. package/src/utils/model_registry/get_model_files.js +63 -78
  76. package/src/utils/model_registry/get_pipeline_files.js +15 -24
  77. package/src/utils/model_registry/is_cached.js +81 -4
  78. package/src/utils/tensor.js +18 -2
  79. package/types/backends/onnx.d.ts.map +1 -1
  80. package/types/backends/utils/cacheWasm.d.ts +3 -17
  81. package/types/backends/utils/cacheWasm.d.ts.map +1 -1
  82. package/types/cache_utils.d.ts +29 -0
  83. package/types/cache_utils.d.ts.map +1 -0
  84. package/types/configs.d.ts.map +1 -1
  85. package/types/env.d.ts +18 -3
  86. package/types/env.d.ts.map +1 -1
  87. package/types/image_processors_utils.d.ts +17 -1
  88. package/types/image_processors_utils.d.ts.map +1 -1
  89. package/types/models/auto/modeling_auto.d.ts +6 -0
  90. package/types/models/auto/modeling_auto.d.ts.map +1 -1
  91. package/types/models/detr/image_processing_detr.d.ts +1 -1
  92. package/types/models/feature_extractors.d.ts +2 -0
  93. package/types/models/gemma3n/modeling_gemma3n.d.ts +2 -0
  94. package/types/models/gemma3n/modeling_gemma3n.d.ts.map +1 -1
  95. package/types/models/granite_speech/feature_extraction_granite_speech.d.ts +16 -0
  96. package/types/models/granite_speech/feature_extraction_granite_speech.d.ts.map +1 -0
  97. package/types/models/granite_speech/modeling_granite_speech.d.ts +4 -0
  98. package/types/models/granite_speech/modeling_granite_speech.d.ts.map +1 -0
  99. package/types/models/granite_speech/processing_granite_speech.d.ts +19 -0
  100. package/types/models/granite_speech/processing_granite_speech.d.ts.map +1 -0
  101. package/types/models/grounding_dino/image_processing_grounding_dino.d.ts +1 -1
  102. package/types/models/idefics3/modeling_idefics3.d.ts +2 -18
  103. package/types/models/idefics3/modeling_idefics3.d.ts.map +1 -1
  104. package/types/models/image_processors.d.ts +1 -0
  105. package/types/models/lfm2_vl/image_processing_lfm2_vl.d.ts +41 -0
  106. package/types/models/lfm2_vl/image_processing_lfm2_vl.d.ts.map +1 -0
  107. package/types/models/lfm2_vl/modeling_lfm2_vl.d.ts +4 -0
  108. package/types/models/lfm2_vl/modeling_lfm2_vl.d.ts.map +1 -0
  109. package/types/models/lfm2_vl/processing_lfm2_vl.d.ts +18 -0
  110. package/types/models/lfm2_vl/processing_lfm2_vl.d.ts.map +1 -0
  111. package/types/models/mistral3/modeling_mistral3.d.ts +2 -2
  112. package/types/models/mistral3/modeling_mistral3.d.ts.map +1 -1
  113. package/types/models/modeling_utils.d.ts +44 -24
  114. package/types/models/modeling_utils.d.ts.map +1 -1
  115. package/types/models/models.d.ts +9 -0
  116. package/types/models/olmo_hybrid/modeling_olmo_hybrid.d.ts +8 -0
  117. package/types/models/olmo_hybrid/modeling_olmo_hybrid.d.ts.map +1 -0
  118. package/types/models/paligemma/modeling_paligemma.d.ts +2 -8
  119. package/types/models/paligemma/modeling_paligemma.d.ts.map +1 -1
  120. package/types/models/processors.d.ts +3 -0
  121. package/types/models/qwen2_5_vl/modeling_qwen2_5_vl.d.ts +3 -0
  122. package/types/models/qwen2_5_vl/modeling_qwen2_5_vl.d.ts.map +1 -1
  123. package/types/models/qwen2_moe/modeling_qwen2_moe.d.ts +8 -0
  124. package/types/models/qwen2_moe/modeling_qwen2_moe.d.ts.map +1 -0
  125. package/types/models/qwen2_vl/image_processing_qwen2_vl.d.ts.map +1 -1
  126. package/types/models/qwen2_vl/modeling_qwen2_vl.d.ts +2 -0
  127. package/types/models/qwen2_vl/modeling_qwen2_vl.d.ts.map +1 -1
  128. package/types/models/qwen3_5/modeling_qwen3_5.d.ts +2 -0
  129. package/types/models/qwen3_5/modeling_qwen3_5.d.ts.map +1 -1
  130. package/types/models/qwen3_5_moe/modeling_qwen3_5_moe.d.ts +3 -0
  131. package/types/models/qwen3_5_moe/modeling_qwen3_5_moe.d.ts.map +1 -1
  132. package/types/models/qwen3_moe/modeling_qwen3_moe.d.ts +8 -0
  133. package/types/models/qwen3_moe/modeling_qwen3_moe.d.ts.map +1 -0
  134. package/types/models/qwen3_next/modeling_qwen3_next.d.ts +8 -0
  135. package/types/models/qwen3_next/modeling_qwen3_next.d.ts.map +1 -0
  136. package/types/models/qwen3_vl/modeling_qwen3_vl.d.ts +3 -0
  137. package/types/models/qwen3_vl/modeling_qwen3_vl.d.ts.map +1 -1
  138. package/types/models/qwen3_vl_moe/modeling_qwen3_vl_moe.d.ts +7 -0
  139. package/types/models/qwen3_vl_moe/modeling_qwen3_vl_moe.d.ts.map +1 -0
  140. package/types/models/registry.d.ts +2 -1
  141. package/types/models/registry.d.ts.map +1 -1
  142. package/types/models/sam/image_processing_sam.d.ts +1 -1
  143. package/types/models/session.d.ts +3 -2
  144. package/types/models/session.d.ts.map +1 -1
  145. package/types/models/smolvlm/modeling_smolvlm.d.ts +8 -0
  146. package/types/models/smolvlm/modeling_smolvlm.d.ts.map +1 -0
  147. package/types/models/ultravox/modeling_ultravox.d.ts +0 -2
  148. package/types/models/ultravox/modeling_ultravox.d.ts.map +1 -1
  149. package/types/models/voxtral/modeling_voxtral.d.ts +4 -0
  150. package/types/models/voxtral/modeling_voxtral.d.ts.map +1 -0
  151. package/types/models/voxtral_realtime/feature_extraction_voxtral_realtime.d.ts +28 -0
  152. package/types/models/voxtral_realtime/feature_extraction_voxtral_realtime.d.ts.map +1 -0
  153. package/types/models/voxtral_realtime/modeling_voxtral_realtime.d.ts +17 -0
  154. package/types/models/voxtral_realtime/modeling_voxtral_realtime.d.ts.map +1 -0
  155. package/types/models/voxtral_realtime/processing_voxtral_realtime.d.ts +44 -0
  156. package/types/models/voxtral_realtime/processing_voxtral_realtime.d.ts.map +1 -0
  157. package/types/models/whisper/feature_extraction_whisper.d.ts.map +1 -1
  158. package/types/pipelines/index.d.ts +0 -34
  159. package/types/pipelines/index.d.ts.map +1 -1
  160. package/types/pipelines.d.ts.map +1 -1
  161. package/types/transformers.d.ts +1 -0
  162. package/types/transformers.d.ts.map +1 -1
  163. package/types/utils/audio.d.ts +5 -2
  164. package/types/utils/audio.d.ts.map +1 -1
  165. package/types/utils/cache/CrossOriginStorageCache.d.ts +120 -0
  166. package/types/utils/cache/CrossOriginStorageCache.d.ts.map +1 -0
  167. package/types/utils/cache/FileCache.d.ts +39 -0
  168. package/types/utils/cache/FileCache.d.ts.map +1 -0
  169. package/types/utils/cache.d.ts +4 -4
  170. package/types/utils/cache.d.ts.map +1 -1
  171. package/types/utils/dtypes.d.ts +1 -1
  172. package/types/utils/hub/{files.d.ts → FileResponse.d.ts} +1 -38
  173. package/types/utils/hub/FileResponse.d.ts.map +1 -0
  174. package/types/utils/hub/utils.d.ts +17 -2
  175. package/types/utils/hub/utils.d.ts.map +1 -1
  176. package/types/utils/hub.d.ts +7 -7
  177. package/types/utils/hub.d.ts.map +1 -1
  178. package/types/utils/image.d.ts +1 -1
  179. package/types/utils/image.d.ts.map +1 -1
  180. package/types/utils/lru_cache.d.ts +38 -0
  181. package/types/utils/lru_cache.d.ts.map +1 -0
  182. package/types/utils/memoize_promise.d.ts +14 -0
  183. package/types/utils/memoize_promise.d.ts.map +1 -0
  184. package/types/utils/model_registry/ModelRegistry.d.ts +66 -6
  185. package/types/utils/model_registry/ModelRegistry.d.ts.map +1 -1
  186. package/types/utils/model_registry/get_file_metadata.d.ts.map +1 -1
  187. package/types/utils/model_registry/get_model_files.d.ts +1 -0
  188. package/types/utils/model_registry/get_model_files.d.ts.map +1 -1
  189. package/types/utils/model_registry/get_pipeline_files.d.ts +2 -1
  190. package/types/utils/model_registry/get_pipeline_files.d.ts.map +1 -1
  191. package/types/utils/model_registry/is_cached.d.ts +47 -4
  192. package/types/utils/model_registry/is_cached.d.ts.map +1 -1
  193. package/types/utils/tensor.d.ts.map +1 -1
  194. package/src/utils/data-structures.js +0 -572
  195. package/types/utils/data-structures.d.ts +0 -294
  196. package/types/utils/data-structures.d.ts.map +0 -1
  197. package/types/utils/hub/files.d.ts.map +0 -1
@@ -1,16 +1,16 @@
1
- var QS=Object.defineProperty;var ds=(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 ms=(t,e)=>{for(var r in e)QS(t,r,{get:e[r],enumerable:!0})};var Et={};var Bt={};var Iv={};var JS="4.0.0-next.5",Ys=!Uv(Et),Lv=!Uv(Bt),kl=typeof self<"u"&&"caches"in self,ZS=typeof globalThis.Deno<"u",lN=typeof globalThis.Bun<"u",Nv=ZS&&kl&&!Ys,zv=typeof process<"u",Rv=zv&&process?.release?.name==="node"&&!Nv,$v=typeof window<"u"&&typeof window.document<"u",Dv=typeof self<"u"&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),eO=Rv||typeof navigator<"u"&&"gpu"in navigator,tO=typeof navigator<"u"&&"ml"in navigator,rO=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",sO=()=>{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},nO=sO(),ge=Object.freeze({IS_BROWSER_ENV:$v,IS_WEBWORKER_ENV:Dv,IS_WEB_CACHE_AVAILABLE:kl,IS_WEBGPU_AVAILABLE:eO,IS_WEBNN_AVAILABLE:tO,IS_SAFARI:nO,IS_PROCESS_AVAILABLE:zv,IS_NODE_ENV:Rv,IS_FS_AVAILABLE:Ys,IS_PATH_AVAILABLE:Lv,IS_CRYPTO_AVAILABLE:rO}),Bp=Ys&&Lv,El="./";if(Bp){let t=Object(import.meta).url;t?El=Bt.dirname(Bt.dirname(Iv.fileURLToPath(t))):typeof __dirname<"u"&&(El=Bt.dirname(__dirname))}var oO=Bp?Bt.join(El,"/.cache/"):null,Cv="/models/",aO=Bp?Bt.join(El,Cv):Cv,iO=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,It=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),Pv=It.WARNING,de={version:JS,backends:{onnx:{}},get logLevel(){return Pv},set logLevel(t){Pv=t,de.backends.onnx?.setLogLevel?.(t)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!($v||Dv||Nv),localModelPath:aO,useFS:Ys,useBrowserCache:kl,useFSCache:Ys,cacheDir:oO,useCustomCache:!1,customCache:null,useWasmCache:kl||Ys,cacheKey:"transformers-cache",fetch:iO};function Uv(t){return Object.keys(t).length===0}function Er(t,e){t&&t(e)}function Bv(t){return Number.isInteger(t)||typeof t=="bigint"}function Fp(t){return t==null||t===-1}function jp(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 Fv(...t){return t.reduce((e,r)=>e.flatMap(s=>r.map(n=>[s,n])))}function Qs(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 jv(t,e){let r=0;for(let s of t)s===e&&++r;return r}var Q={error(...t){de.logLevel<=It.ERROR&&console.error(...t)},warn(...t){de.logLevel<=It.WARNING&&console.warn(...t)},info(...t){de.logLevel<=It.INFO&&console.log(...t)},debug(...t){de.logLevel<=It.DEBUG&&console.log(...t)},log(...t){this.info(...t)}};var lO=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}},Gv=lO,cO=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}},uO=cO,Yv=(()=>{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]]))})(),pO=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),fO=pO(Yv),qv=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",dO=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|[${qv}])]+`,` ?[^\\s${qv}]+`]]),Al="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",qp=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"),Tl=(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 dO)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=mO(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},mO=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),hO=(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},_O=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,gO=t=>Number.isInteger(t)||typeof t=="bigint",wO=t=>{let e=0;for(let r of t)++e;return e},xO=t=>Qv(t.toLowerCase()),Qt=(...t)=>Array.prototype.concat.apply([],t),Wp=t=>new Map(Object.entries(t)),yO=(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,""),Wv=(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},bO=t=>t.match(/\S+/g)||[],vO=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},Hn=vO,kO=class extends Hn{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},Ar=kO,EO=class extends Ar{tokenize_chinese_chars(t){let e=[];for(let r=0;r<t.length;++r){let s=t[r],n=s.charCodeAt(0);_O(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=EO,TO=class extends Ar{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}},MO=TO,SO=class extends Ar{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>Jv(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},OO=SO,IO=class extends Ar{normalize(t){let e=Tl(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},CO=IO,PO=class extends Ar{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},Ml=PO,LO=class extends Ml{constructor(){super(...arguments),this.form="NFC"}},NO=LO,zO=class extends Ml{constructor(){super(...arguments),this.form="NFD"}},RO=zO,$O=class extends Ml{constructor(){super(...arguments),this.form="NFKC"}},DO=$O,UO=class extends Ml{constructor(){super(...arguments),this.form="NFKD"}},BO=UO,FO=class extends Ar{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}},jO=FO,GO=class extends Ar{normalize(t){return Qv(t)}},qO=GO,WO=class extends Ar{normalize(t){return t.toLowerCase()}},VO=WO,HO=class extends Ar{normalize(t){return t=this.config.prepend+t,t}},XO=HO;function KO(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new AO(t);case"Precompiled":return new MO(t);case"Sequence":return new OO(t);case"Replace":return new CO(t);case"NFC":return new NO(t);case"NFD":return new RO(t);case"NFKC":return new DO(t);case"NFKD":return new BO(t);case"Strip":return new jO(t);case"StripAccents":return new qO(t);case"Lowercase":return new VO(t);case"Prepend":return new XO(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var Jv=KO,YO=class extends Hn{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)}},Jt=YO,QO=class extends Jt{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=Yv,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(""))}},JO=QO,ZO=class extends Jt{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},eI=ZO,tI=class extends Jt{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]}},rI=tI,sI=class extends Jt{constructor(t){super(),this.config=t,this.pattern=Tl(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):yO(t,this.pattern)}},nI=sI,oI=class extends Jt{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Al}]+|[${Al}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},aI=oI,iI=class extends Jt{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)||[]}},lI=iI,cI=class extends Jt{constructor(){super(),this.pattern=new RegExp(`[^\\s${Al}]+|[${Al}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},uI=cI,pI=class extends Jt{constructor(t){super(),this.config=t,this.pattern=Tl(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},fI=pI,dI=class extends Jt{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>Zv(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,e):r,[t])}},mI=dI,hI=class extends Jt{pre_tokenize_text(t){return bO(t)}},_I=hI,gI=class extends Jt{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}},wI=gI;function xI(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new uI;case"Sequence":return new mI(t);case"Whitespace":return new eI;case"WhitespaceSplit":return new _I;case"Metaspace":return new rI(t);case"ByteLevel":return new JO(t);case"Split":return new nI(t);case"Punctuation":return new aI(t);case"Digits":return new lI(t);case"Replace":return new fI(t);case"FixedLength":return new wI(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var Zv=xI,yI=class extends Hn{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=hO(e,this.tokens_to_ids,this.unk_token_id)),e}},Sl=yI,bI=class extends Sl{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=Wp(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 c=s.slice(o,i).join("");if(o>0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){l=c;break}--i}if(l===null){n=!0;break}a.push(l),o=i}n?e.push(this.unk_token):e.push(...a)}return e}},Vv=bI,Hv=class ek{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new ek(!1,new Map)}},vI=class{constructor(){this.root=Hv.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=Hv.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)}}},kI=vI,Gp=class tk{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 tk(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},EI=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 Gp(this.bos_token_id??0,0,0,0,0),n=new Gp(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 Gp(s,n,t,e,r);this.begin_nodes[t].push(o),this.end_nodes[t+e].push(o),this.nodes.push(o)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let a of this.begin_nodes[e]){a.prev=null;let i=0,l=null;for(let c of this.end_nodes[e]){let p=c.backtrace_score+a.score;(l===null||p>i)&&(l=c.clone(),i=p)}if(l!==null)a.prev=l,a.backtrace_score=i;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let o=n.clone();for(;o.prev!==null;)r.push(o.clone()),o=o.clone().prev.clone();return r.reverse(),r}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},AI=EI;function TI(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 MI=class extends Sl{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=TI(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new kI,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 c=this.tokens_to_ids.get(l),p=this.scores[c],f=wO(l);t.insert(s,f,p,c),!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}},Xv=MI,SI=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}},OI=SI,II=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()}},CI=II,PI=class extends Sl{constructor(t){super(t),this.tokens_to_ids=Wp(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 CI(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 OI((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 c={...i.prev};i.prev.deleted=!0,i.prev=c,c.prev?c.prev.next=c:o=c}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}},Kv=PI,LI=class extends Sl{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=Wp(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}},NI=LI;function zI(t,e){switch(t.type){case"WordPiece":return new Vv(t);case"Unigram":return new Xv(t,e.eos_token);case"BPE":return new Kv(t);default:if(t.vocab)return Array.isArray(t.vocab)?new Xv(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new Kv(t):new Vv(t):new NI(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 RI=zI,$I=class extends Hn{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},Xn=$I,DI=class extends Xn{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=Qt(n,t),o=Qt(o,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(n=Qt(n,e),o=Qt(o,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:n,token_type_ids:o}}},UI=DI,BI=class extends Xn{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},FI=BI,jI=class extends Xn{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Qt([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=Qt(t,n,e,o),s=Qt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},GI=jI,qI=class extends Xn{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Qt([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=Qt(t,n,e,o),s=Qt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},WI=qI,VI=class extends Xn{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>rk(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}},HI=VI;function XI(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new UI(t);case"ByteLevel":return new FI(t);case"BertProcessing":return new GI(t);case"RobertaProcessing":return new WI(t);case"Sequence":return new HI(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var rk=XI,KI=class extends Hn{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},Ft=KI,YI=class extends Ft{constructor(t){super(t),this.byte_decoder=fO,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}},QI=YI,JI=class extends Ft{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,r)=>{if(r!==0){let s=this.config.prefix;s&&e.startsWith(s)?e=e.replace(s,""):e=" "+e}return this.cleanup&&(e=qp(e)),e})}},ZI=JI,eC=class extends Ft{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}},tC=eC,rC=class extends Ft{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,r)=>e.replaceAll(this.suffix,r===t.length-1?"":" "))}},sC=rC,nC=class extends Ft{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let n=1;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=qp(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(t){return[this.convert_tokens_to_string(t)]}},oC=nC,aC=class extends Ft{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>sk(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},iC=aC,lC=class extends Ft{decode_chain(t){let e=Tl(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(s=>s.replaceAll(e,r))}},cC=lC,uC=class extends Ft{decode_chain(t){return[t.join("")]}},pC=uC,fC=class extends Ft{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let r=0;for(let n=0;n<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)})}},dC=fC,mC=class extends Ft{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}},hC=mC;function _C(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new QI(t);case"WordPiece":return new ZI(t);case"Metaspace":return new tC(t);case"BPEDecoder":return new sC(t);case"CTC":return new oC(t);case"Sequence":return new iC(t);case"Replace":return new cC(t);case"Fuse":return new pC(t);case"Strip":return new dC(t);case"ByteFallback":return new hC(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var sk=_C,gC=class{constructor(t,e){let r=Wv(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let s=Wv(e,"Config");if(s)throw new Error(s);this.tokenizer=t,this.config=e,this.normalizer=Jv(this.tokenizer.normalizer),this.pre_tokenizer=Zv(this.tokenizer.pre_tokenizer),this.model=RI(this.tokenizer.model,this.config),this.post_processor=rk(this.tokenizer.post_processor),this.decoder=sk(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 uO(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 Gv(n),this.splitter_normalized=new Gv(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||!gO(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=qp(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=xO(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:Qt(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}},nk=gC;var R=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"}),jt=class{constructor(t,e){this.value=t,this.type=e}};function ok(t){return/\w/.test(t)}function Kn(t){return/[0-9]/.test(t)}function ak(t){return/\s/.test(t)}var wC=[["{%",R.OpenStatement],["%}",R.CloseStatement],["{{",R.OpenExpression],["}}",R.CloseExpression],["(",R.OpenParen],[")",R.CloseParen],["{",R.OpenCurlyBracket],["}",R.CloseCurlyBracket],["[",R.OpenSquareBracket],["]",R.CloseSquareBracket],[",",R.Comma],[".",R.Dot],[":",R.Colon],["|",R.Pipe],["<=",R.ComparisonBinaryOperator],[">=",R.ComparisonBinaryOperator],["==",R.ComparisonBinaryOperator],["!=",R.ComparisonBinaryOperator],["<",R.ComparisonBinaryOperator],[">",R.ComparisonBinaryOperator],["+",R.AdditiveBinaryOperator],["-",R.AdditiveBinaryOperator],["~",R.AdditiveBinaryOperator],["*",R.MultiplicativeBinaryOperator],["/",R.MultiplicativeBinaryOperator],["%",R.MultiplicativeBinaryOperator],["=",R.Equals]],xC=new Map([["n",`
3
- `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function yC(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 bC(t,e={}){let r=[],s=yC(t,e),n=0,o=0,a=c=>{let p="";for(;c(s[n]);){if(s[n]==="\\"){if(++n,n>=s.length)throw new SyntaxError("Unexpected end of input");let f=s[n++],m=xC.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 c=r.at(-1);c&&c.type===R.Text&&(c.value=c.value.trimEnd(),c.value===""&&r.pop())},l=()=>{for(;n<s.length&&ak(s[n]);)++n};e:for(;n<s.length;){let c=r.at(-1)?.type;if(c===void 0||c===R.CloseStatement||c===R.CloseExpression||c===R.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 jt(f,R.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 jt(m,R.Comment)),n+=2,h&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new jt("{%",R.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new jt("{{",R.OpenExpression)),o=0,n+=3;continue}if(a(ak),s.slice(n,n+3)==="-%}"){r.push(new jt("%}",R.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new jt("}}",R.CloseExpression)),n+=3,l();continue}let p=s[n];if(p==="-"||p==="+"){let f=r.at(-1)?.type;if(f===R.Text||f===void 0)throw new SyntaxError(`Unexpected character: ${p}`);switch(f){case R.Identifier:case R.NumericLiteral:case R.StringLiteral:case R.CloseParen:case R.CloseSquareBracket:break;default:{++n;let m=a(Kn);r.push(new jt(`${p}${m}`,m.length>0?R.NumericLiteral:R.UnaryOperator));continue}}}for(let[f,m]of wC){if(f==="}}"&&o>0)continue;if(s.slice(n,n+f.length)===f){r.push(new jt(f,m)),m===R.OpenExpression?o=0:m===R.OpenCurlyBracket?++o:m===R.CloseCurlyBracket&&--o,n+=f.length;continue e}}if(p==="'"||p==='"'){++n;let f=a(m=>m!==p);r.push(new jt(f,R.StringLiteral)),++n;continue}if(Kn(p)){let f=a(Kn);if(s[n]==="."&&Kn(s[n+1])){++n;let m=a(Kn);f=`${f}.${m}`}r.push(new jt(f,R.NumericLiteral));continue}if(ok(p)){let f=a(ok);r.push(new jt(f,R.Identifier));continue}throw new SyntaxError(`Unexpected character: ${p}`)}return r}var er=class{type="Statement"},vC=class extends er{constructor(t){super(),this.body=t}type="Program"},kC=class extends er{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r}type="If"},EC=class extends er{constructor(t,e,r,s){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=s}type="For"},AC=class extends er{type="Break"},TC=class extends er{type="Continue"},MC=class extends er{constructor(t,e,r){super(),this.assignee=t,this.value=e,this.body=r}type="Set"},SC=class extends er{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r}type="Macro"},OC=class extends er{constructor(t){super(),this.value=t}type="Comment"},Nt=class extends er{type="Expression"},IC=class extends Nt{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r}type="MemberExpression"},ik=class extends Nt{constructor(t,e){super(),this.callee=t,this.args=e}type="CallExpression"},Js=class extends Nt{constructor(t){super(),this.value=t}type="Identifier"},Zs=class extends Nt{constructor(t){super(),this.value=t}type="Literal"},CC=class extends Zs{type="IntegerLiteral"},PC=class extends Zs{type="FloatLiteral"},lk=class extends Zs{type="StringLiteral"},LC=class extends Zs{type="ArrayLiteral"},ck=class extends Zs{type="TupleLiteral"},NC=class extends Zs{type="ObjectLiteral"},Yn=class extends Nt{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r}type="BinaryExpression"},zC=class extends Nt{constructor(t,e){super(),this.operand=t,this.filter=e}type="FilterExpression"},RC=class extends er{constructor(t,e){super(),this.filter=t,this.body=e}type="FilterStatement"},$C=class extends Nt{constructor(t,e){super(),this.lhs=t,this.test=e}type="SelectExpression"},DC=class extends Nt{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r}type="TestExpression"},UC=class extends Nt{constructor(t,e){super(),this.operator=t,this.argument=e}type="UnaryExpression"},BC=class extends Nt{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r}type="SliceExpression"},FC=class extends Nt{constructor(t,e){super(),this.key=t,this.value=e}type="KeywordArgumentExpression"},jC=class extends Nt{constructor(t){super(),this.argument=t}type="SpreadExpression"},GC=class extends er{constructor(t,e,r){super(),this.call=t,this.callerArgs=e,this.body=r}type="CallStatement"},qC=class extends Nt{constructor(t,e,r){super(),this.condition=t,this.trueExpr=e,this.falseExpr=r}type="Ternary"};function WC(t){let e=new vC([]),r=0;function s(I,N){let $=t[r++];if(!$||$.type!==I)throw new Error(`Parser Error: ${N}. ${$.type} !== ${I}.`);return $}function n(I){if(!l(I))throw new SyntaxError(`Expected ${I}`);++r}function o(){switch(t[r].type){case R.Comment:return new OC(t[r++].value);case R.Text:return c();case R.OpenStatement:return p();case R.OpenExpression:return f();default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}}function a(...I){return r+I.length<=t.length&&I.every((N,$)=>N===t[r+$].type)}function i(...I){return t[r]?.type===R.OpenStatement&&t[r+1]?.type===R.Identifier&&I.includes(t[r+1]?.value)}function l(...I){return r+I.length<=t.length&&I.every((N,$)=>t[r+$].type==="Identifier"&&N===t[r+$].value)}function c(){return new lk(s(R.Text,"Expected text token").value)}function p(){if(s(R.OpenStatement,"Expected opening statement token"),t[r].type!==R.Identifier)throw new SyntaxError(`Unknown statement, got ${t[r].type}`);let I=t[r].value,N;switch(I){case"set":++r,N=m();break;case"if":++r,N=h(),s(R.OpenStatement,"Expected {% token"),n("endif"),s(R.CloseStatement,"Expected %} token");break;case"macro":++r,N=w(),s(R.OpenStatement,"Expected {% token"),n("endmacro"),s(R.CloseStatement,"Expected %} token");break;case"for":++r,N=b(),s(R.OpenStatement,"Expected {% token"),n("endfor"),s(R.CloseStatement,"Expected %} token");break;case"call":{++r;let $=null;a(R.OpenParen)&&($=V());let te=ae();if(te.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let pe=V();s(R.CloseStatement,"Expected closing statement token");let Fe=[];for(;!i("endcall");)Fe.push(o());s(R.OpenStatement,"Expected '{%'"),n("endcall"),s(R.CloseStatement,"Expected closing statement token");let Pe=new ik(te,pe);N=new GC(Pe,$,Fe);break}case"break":++r,s(R.CloseStatement,"Expected closing statement token"),N=new AC;break;case"continue":++r,s(R.CloseStatement,"Expected closing statement token"),N=new TC;break;case"filter":{++r;let $=ae();$ instanceof Js&&a(R.OpenParen)&&($=H($)),s(R.CloseStatement,"Expected closing statement token");let te=[];for(;!i("endfilter");)te.push(o());s(R.OpenStatement,"Expected '{%'"),n("endfilter"),s(R.CloseStatement,"Expected '%}'"),N=new RC($,te);break}default:throw new SyntaxError(`Unknown statement type: ${I}`)}return N}function f(){s(R.OpenExpression,"Expected opening expression token");let I=E();return s(R.CloseExpression,"Expected closing expression token"),I}function m(){let I=x(),N=null,$=[];if(a(R.Equals))++r,N=x();else{for(s(R.CloseStatement,"Expected %} token");!i("endset");)$.push(o());s(R.OpenStatement,"Expected {% token"),n("endset")}return s(R.CloseStatement,"Expected closing statement token"),new MC(I,N,$)}function h(){let I=E();s(R.CloseStatement,"Expected closing statement token");let N=[],$=[];for(;!i("elif","else","endif");)N.push(o());if(i("elif")){++r,++r;let te=h();$.push(te)}else if(i("else"))for(++r,++r,s(R.CloseStatement,"Expected closing statement token");!i("endif");)$.push(o());return new kC(I,N,$)}function w(){let I=ae();if(I.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let N=V();s(R.CloseStatement,"Expected closing statement token");let $=[];for(;!i("endmacro");)$.push(o());return new SC(I,N,$)}function x(I=!1){let N=I?ae:E,$=[N()],te=a(R.Comma);for(;te&&(++r,$.push(N()),!!a(R.Comma)););return te?new ck($):$[0]}function b(){let I=x(!0);if(!(I instanceof Js||I instanceof ck))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 N=E();s(R.CloseStatement,"Expected closing statement token");let $=[];for(;!i("endfor","else");)$.push(o());let te=[];if(i("else"))for(++r,++r,s(R.CloseStatement,"Expected closing statement token");!i("endfor");)te.push(o());return new EC(I,N,$,te)}function E(){return A()}function A(){let I=S();if(l("if")){++r;let N=S();if(l("else")){++r;let $=A();return new qC(N,I,$)}else return new $C(I,N)}return I}function S(){let I=M();for(;l("or");){let N=t[r];++r;let $=M();I=new Yn(N,I,$)}return I}function M(){let I=C();for(;l("and");){let N=t[r];++r;let $=C();I=new Yn(N,I,$)}return I}function C(){let I;for(;l("not");){let N=t[r];++r;let $=C();I=new UC(N,$)}return I??P()}function P(){let I=k();for(;;){let N;if(l("not","in"))N=new jt("not in",R.Identifier),r+=2;else if(l("in"))N=t[r++];else if(a(R.ComparisonBinaryOperator))N=t[r++];else break;let $=k();I=new Yn(N,I,$)}return I}function k(){let I=U();for(;a(R.AdditiveBinaryOperator);){let N=t[r];++r;let $=U();I=new Yn(N,I,$)}return I}function F(){let I=Y(ae());return a(R.OpenParen)?H(I):I}function H(I){let N=new ik(I,V());return N=Y(N),a(R.OpenParen)&&(N=H(N)),N}function V(){s(R.OpenParen,"Expected opening parenthesis for arguments list");let I=J();return s(R.CloseParen,"Expected closing parenthesis for arguments list"),I}function J(){let I=[];for(;!a(R.CloseParen);){let N;if(t[r].type===R.MultiplicativeBinaryOperator&&t[r].value==="*"){++r;let $=E();N=new jC($)}else if(N=E(),a(R.Equals)){if(++r,!(N instanceof Js))throw new SyntaxError("Expected identifier for keyword argument");let $=E();N=new FC(N,$)}I.push(N),a(R.Comma)&&++r}return I}function X(){let I=[],N=!1;for(;!a(R.CloseSquareBracket);)a(R.Colon)?(I.push(void 0),++r,N=!0):(I.push(E()),a(R.Colon)&&(++r,N=!0));if(I.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(N){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(R.Dot)||a(R.OpenSquareBracket);){let N=t[r];++r;let $,te=N.type===R.OpenSquareBracket;if(te)$=X(),s(R.CloseSquareBracket,"Expected closing square bracket");else if($=ae(),$.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");I=new IC(I,$,te)}return I}function U(){let I=L();for(;a(R.MultiplicativeBinaryOperator);){let N=t[r++],$=L();I=new Yn(N,I,$)}return I}function L(){let I=ne();for(;l("is");){++r;let N=l("not");N&&++r;let $=ae();if(!($ instanceof Js))throw new SyntaxError("Expected identifier for the test");I=new DC(I,N,$)}return I}function ne(){let I=F();for(;a(R.Pipe);){++r;let N=ae();if(!(N instanceof Js))throw new SyntaxError("Expected identifier for the filter");a(R.OpenParen)&&(N=H(N)),I=new zC(I,N)}return I}function ae(){let I=t[r++];switch(I.type){case R.NumericLiteral:{let N=I.value;return N.includes(".")?new PC(Number(N)):new CC(Number(N))}case R.StringLiteral:{let N=I.value;for(;a(R.StringLiteral);)N+=t[r++].value;return new lk(N)}case R.Identifier:return new Js(I.value);case R.OpenParen:{let N=x();return s(R.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),N}case R.OpenSquareBracket:{let N=[];for(;!a(R.CloseSquareBracket);)N.push(E()),a(R.Comma)&&++r;return++r,new LC(N)}case R.OpenCurlyBracket:{let N=new Map;for(;!a(R.CloseCurlyBracket);){let $=E();s(R.Colon,"Expected colon between key and value in object literal");let te=E();N.set($,te),a(R.Comma)&&++r}return++r,new NC(N)}default:throw new SyntaxError(`Unexpected token: ${I.type}`)}}for(;r<t.length;)e.body.push(o());return e}function VC(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 uk(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 HC(t){return t.replace(/\b\w/g,e=>e.toUpperCase())}function XC(t){return KC(new Date,t)}function KC(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 YC(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function QC(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(YC(e),"gu");return t.replaceAll(o,a=>n>0?(--n,r):a)}var pk=class extends Error{},fk=class extends Error{},lr=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 lr{type="IntegerValue"},Ye=class extends lr{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},ee=class extends lr{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(HC(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(QC(this.value,e.value,r.value,s.value))})]])},ce=class extends lr{type="BooleanValue"},JC=/[\x7f-\uffff]/g;function dk(t){return t.replace(JC,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function _s(t,e={},r=0,s=!0){let{indent:n=null,ensureAscii:o=!1,separators:a=null,sortKeys:i=!1}=e,l,c;switch(a?[l,c]=a:n?(l=",",c=": "):(l=", ",c=": "),t.type){case"NullValue":return"null";case"UndefinedValue":return s?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(t.value);case"StringValue":{let p=JSON.stringify(t.value);return o&&(p=dk(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=>_s(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],[b])=>x.localeCompare(b)));let w=h.map(([x,b])=>{let E=JSON.stringify(x);o&&(E=dk(E));let A=`${E}${c}${_s(b,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 wt=class extends lr{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 Qn?(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 c=n.value==="key"?0:1,p=i.value[c],f=l.value[c],m=Vp(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 _s(this,{},0,!1)}},Qn=class extends wt{type="KeywordArgumentsValue"},ve=class extends lr{type="ArrayValue";builtins=new Map([["length",new me(this.value.length)]]);__bool__(){return new ce(this.value.length>0)}toString(){return _s(this,{},0,!1)}},mk=class extends ve{type="TupleValue"},Ge=class extends lr{type="FunctionValue"},We=class extends lr{type="NullValue"},je=class extends lr{type="UndefinedValue"},hs=class{constructor(t){this.parent=t}variables=new Map([["namespace",new Ge(t=>{if(t.length===0)return new wt(new Map);if(t.length!==1||!(t[0]instanceof wt))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,Ol(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 ZC(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",VC),t.set("strftime_now",XC),t.set("True",!0),t.set("False",!1),t.set("None",null)}function hk(t,e){let r=e.split("."),s=t;for(let n of r)if(s instanceof wt)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 Vp(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 eP=class{global;constructor(t){this.global=t??new hs}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 wt)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(_s(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)=>Vp(n,o,!1)));case"join":return new ee(t.value.map(n=>n.value).join(""));case"string":return new ee(_s(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(`
1
+ var jO=Object.defineProperty;var ms=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var hs=(t,e)=>{for(var r in e)jO(t,r,{get:e[r],enumerable:!0})};var wt={};var Ut={};var _k={};var qO="4.0.0-next.7",rf=typeof self<"u",rn=!vk(wt),xk=!vk(Ut),Ul=rf&&"caches"in self,WO=typeof globalThis.Deno<"u",_z=typeof globalThis.Bun<"u",Gl=WO&&Ul&&!rn,yk=typeof process<"u",bk=yk&&process?.release?.name==="node"&&!Gl,sf=typeof window<"u"&&typeof window.document<"u",nf=rf&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),VO=sf||nf||Gl,HO=bk||typeof navigator<"u"&&"gpu"in navigator,XO=typeof navigator<"u"&&"ml"in navigator,KO=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",YO=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",QO=typeof ServiceWorkerGlobalScope<"u"&&rf&&self instanceof ServiceWorkerGlobalScope,JO=()=>{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},ZO=JO(),ie=Object.freeze({IS_BROWSER_ENV:sf,IS_WEBWORKER_ENV:nf,IS_WEB_ENV:VO,IS_SERVICE_WORKER_ENV:QO,IS_DENO_WEB_RUNTIME:Gl,IS_WEB_CACHE_AVAILABLE:Ul,IS_WEBGPU_AVAILABLE:HO,IS_WEBNN_AVAILABLE:XO,IS_SAFARI:ZO,IS_PROCESS_AVAILABLE:yk,IS_NODE_ENV:bk,IS_FS_AVAILABLE:rn,IS_PATH_AVAILABLE:xk,IS_CRYPTO_AVAILABLE:KO,IS_CHROME_AVAILABLE:YO}),of=rn&&xk,Fl="./";if(of){let t=Object(import.meta).url;t?Fl=Ut.dirname(Ut.dirname(_k.fileURLToPath(t))):typeof __dirname<"u"&&(Fl=Ut.dirname(__dirname))}var eI=of?Ut.join(Fl,"/.cache/"):null,gk="/models/",tI=of?Ut.join(Fl,gk):gk,rI=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,Ct=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),wk=Ct.WARNING,me={version:qO,backends:{onnx:{}},get logLevel(){return wk},set logLevel(t){wk=t,me.backends.onnx?.setLogLevel?.(t)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(sf||nf||Gl),localModelPath:tI,useFS:rn,useBrowserCache:Ul,useFSCache:rn,cacheDir:eI,useCustomCache:!1,customCache:null,useWasmCache:Ul||rn,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:rI};function vk(t){return Object.keys(t).length===0}function vr(t,e){t&&t(e)}function kk(t){return Number.isInteger(t)||typeof t=="bigint"}function af(t){return t==null||t===-1}function lf(t){let e=[],r=t;for(;Array.isArray(r);)e.push(r.length),r=r[0];return e}function xt(...t){return Array.prototype.concat.apply([],t)}function Ek(...t){return t.reduce((e,r)=>e.flatMap(s=>r.map(n=>[s,n])))}function sn(t,e){return Math.abs((t+e)%(2*e)-e)}function Ye(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}function Ak(t,e){let r=0;for(let s of t)s===e&&++r;return r}var Z={error(...t){me.logLevel<=Ct.ERROR&&console.error(...t)},warn(...t){me.logLevel<=Ct.WARNING&&console.warn(...t)},info(...t){me.logLevel<=Ct.INFO&&console.log(...t)},debug(...t){me.logLevel<=Ct.DEBUG&&console.log(...t)},log(...t){this.info(...t)}};var sI=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}},Tk=sI,nI=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}},oI=nI,Lk=(()=>{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]]))})(),aI=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),iI=aI(Lk),Mk=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",lI=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|[${Mk}])]+`,` ?[^\\s${Mk}]+`]]),jl="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",uf=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"),ql=(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 lI)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=cI(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},cI=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),uI=(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},pI=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,fI=t=>Number.isInteger(t)||typeof t=="bigint",dI=t=>{let e=0;for(let r of t)++e;return e},mI=t=>Nk(t.toLowerCase()),Qt=(...t)=>Array.prototype.concat.apply([],t),pf=t=>new Map(Object.entries(t)),hI=(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},Nk=t=>t.replace(/\p{M}/gu,""),Sk=(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},_I=t=>t.match(/\S+/g)||[],gI=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},oo=gI,wI=class extends oo{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},kr=wI,xI=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);pI(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}},yI=xI,bI=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}},vI=bI,kI=class extends kr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>zk(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},EI=kI,AI=class extends kr{normalize(t){let e=ql(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},TI=AI,MI=class extends kr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},Wl=MI,SI=class extends Wl{constructor(){super(...arguments),this.form="NFC"}},OI=SI,II=class extends Wl{constructor(){super(...arguments),this.form="NFD"}},CI=II,PI=class extends Wl{constructor(){super(...arguments),this.form="NFKC"}},LI=PI,NI=class extends Wl{constructor(){super(...arguments),this.form="NFKD"}},zI=NI,RI=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}},$I=RI,DI=class extends kr{normalize(t){return Nk(t)}},BI=DI,UI=class extends kr{normalize(t){return t.toLowerCase()}},FI=UI,GI=class extends kr{normalize(t){return t=this.config.prepend+t,t}},jI=GI;function qI(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new yI(t);case"Precompiled":return new vI(t);case"Sequence":return new EI(t);case"Replace":return new TI(t);case"NFC":return new OI(t);case"NFD":return new CI(t);case"NFKC":return new LI(t);case"NFKD":return new zI(t);case"Strip":return new $I(t);case"StripAccents":return new BI(t);case"Lowercase":return new FI(t);case"Prepend":return new jI(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var zk=qI,WI=class extends oo{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)}},Jt=WI,VI=class extends Jt{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=Lk,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(""))}},HI=VI,XI=class extends Jt{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},KI=XI,YI=class extends Jt{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]}},QI=YI,JI=class extends Jt{constructor(t){super(),this.config=t,this.pattern=ql(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):hI(t,this.pattern)}},ZI=JI,eC=class extends Jt{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${jl}]+|[${jl}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},tC=eC,rC=class extends Jt{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)||[]}},sC=rC,nC=class extends Jt{constructor(){super(),this.pattern=new RegExp(`[^\\s${jl}]+|[${jl}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},oC=nC,aC=class extends Jt{constructor(t){super(),this.config=t,this.pattern=ql(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},iC=aC,lC=class extends Jt{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>Rk(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,e):r,[t])}},cC=lC,uC=class extends Jt{pre_tokenize_text(t){return _I(t)}},pC=uC,fC=class extends Jt{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}},dC=fC;function mC(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new oC;case"Sequence":return new cC(t);case"Whitespace":return new KI;case"WhitespaceSplit":return new pC;case"Metaspace":return new QI(t);case"ByteLevel":return new HI(t);case"Split":return new ZI(t);case"Punctuation":return new tC(t);case"Digits":return new sC(t);case"Replace":return new iC(t);case"FixedLength":return new dC(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var Rk=mC,hC=class extends oo{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=uI(e,this.tokens_to_ids,this.unk_token_id)),e}},Vl=hC,_C=class extends Vl{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=pf(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 c=s.slice(o,i).join("");if(o>0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){l=c;break}--i}if(l===null){n=!0;break}a.push(l),o=i}n?e.push(this.unk_token):e.push(...a)}return e}},Ok=_C,Ik=class $k{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new $k(!1,new Map)}},gC=class{constructor(){this.root=Ik.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=Ik.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)}}},wC=gC,cf=class Dk{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 Dk(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},xC=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 cf(this.bos_token_id??0,0,0,0,0),n=new cf(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 cf(s,n,t,e,r);this.begin_nodes[t].push(o),this.end_nodes[t+e].push(o),this.nodes.push(o)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let a of this.begin_nodes[e]){a.prev=null;let i=0,l=null;for(let c of this.end_nodes[e]){let p=c.backtrace_score+a.score;(l===null||p>i)&&(l=c.clone(),i=p)}if(l!==null)a.prev=l,a.backtrace_score=i;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let o=n.clone();for(;o.prev!==null;)r.push(o.clone()),o=o.clone().prev.clone();return r.reverse(),r}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},yC=xC;function bC(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 vC=class extends Vl{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=bC(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new wC,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 c=this.tokens_to_ids.get(l),p=this.scores[c],f=dI(l);t.insert(s,f,p,c),!n&&f===r&&(n=!0)}n||t.insert(s,r,this.unk_score,this.unk_token_id),s+=r}}tokenize(t){let e=new yC(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}},Ck=vC,kC=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}},EC=kC,AC=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()}},TC=AC,MC=class extends Vl{constructor(t){super(t),this.tokens_to_ids=pf(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 TC(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 EC((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 c={...i.prev};i.prev.deleted=!0,i.prev=c,c.prev?c.prev.next=c:o=c}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}},Pk=MC,SC=class extends Vl{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=pf(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}},OC=SC;function IC(t,e){switch(t.type){case"WordPiece":return new Ok(t);case"Unigram":return new Ck(t,e.eos_token);case"BPE":return new Pk(t);default:if(t.vocab)return Array.isArray(t.vocab)?new Ck(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new Pk(t):new Ok(t):new OC(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 CC=IC,PC=class extends oo{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},ao=PC,LC=class extends ao{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=Qt(n,t),o=Qt(o,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(n=Qt(n,e),o=Qt(o,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:n,token_type_ids:o}}},NC=LC,zC=class extends ao{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},RC=zC,$C=class extends ao{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Qt([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=Qt(t,n,e,o),s=Qt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},DC=$C,BC=class extends ao{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Qt([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=Qt(t,n,e,o),s=Qt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},UC=BC,FC=class extends ao{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>Bk(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}},GC=FC;function jC(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new NC(t);case"ByteLevel":return new RC(t);case"BertProcessing":return new DC(t);case"RobertaProcessing":return new UC(t);case"Sequence":return new GC(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var Bk=jC,qC=class extends oo{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},Ft=qC,WC=class extends Ft{constructor(t){super(t),this.byte_decoder=iI,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}},VC=WC,HC=class extends Ft{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,r)=>{if(r!==0){let s=this.config.prefix;s&&e.startsWith(s)?e=e.replace(s,""):e=" "+e}return this.cleanup&&(e=uf(e)),e})}},XC=HC,KC=class extends Ft{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}},YC=KC,QC=class extends Ft{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,r)=>e.replaceAll(this.suffix,r===t.length-1?"":" "))}},JC=QC,ZC=class extends Ft{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let n=1;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=uf(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(t){return[this.convert_tokens_to_string(t)]}},eP=ZC,tP=class extends Ft{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>Uk(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},rP=tP,sP=class extends Ft{decode_chain(t){let e=ql(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(s=>s.replaceAll(e,r))}},nP=sP,oP=class extends Ft{decode_chain(t){return[t.join("")]}},aP=oP,iP=class extends Ft{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let r=0;for(let n=0;n<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)})}},lP=iP,cP=class extends Ft{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}},uP=cP;function pP(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new VC(t);case"WordPiece":return new XC(t);case"Metaspace":return new YC(t);case"BPEDecoder":return new JC(t);case"CTC":return new eP(t);case"Sequence":return new rP(t);case"Replace":return new nP(t);case"Fuse":return new aP(t);case"Strip":return new lP(t);case"ByteFallback":return new uP(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var Uk=pP,fP=class{constructor(t,e){let r=Sk(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let s=Sk(e,"Config");if(s)throw new Error(s);this.tokenizer=t,this.config=e,this.normalizer=zk(this.tokenizer.normalizer),this.pre_tokenizer=Rk(this.tokenizer.pre_tokenizer),this.model=CC(this.tokenizer.model,this.config),this.post_processor=Bk(this.tokenizer.post_processor),this.decoder=Uk(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 oI(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 Tk(n),this.splitter_normalized=new Tk(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||!fI(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=uf(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=mI(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:Qt(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}},Fk=fP;var D=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"}),Gt=class{constructor(t,e){this.value=t,this.type=e}};function Gk(t){return/\w/.test(t)}function io(t){return/[0-9]/.test(t)}function jk(t){return/\s/.test(t)}var dP=[["{%",D.OpenStatement],["%}",D.CloseStatement],["{{",D.OpenExpression],["}}",D.CloseExpression],["(",D.OpenParen],[")",D.CloseParen],["{",D.OpenCurlyBracket],["}",D.CloseCurlyBracket],["[",D.OpenSquareBracket],["]",D.CloseSquareBracket],[",",D.Comma],[".",D.Dot],[":",D.Colon],["|",D.Pipe],["<=",D.ComparisonBinaryOperator],[">=",D.ComparisonBinaryOperator],["==",D.ComparisonBinaryOperator],["!=",D.ComparisonBinaryOperator],["<",D.ComparisonBinaryOperator],[">",D.ComparisonBinaryOperator],["+",D.AdditiveBinaryOperator],["-",D.AdditiveBinaryOperator],["~",D.AdditiveBinaryOperator],["*",D.MultiplicativeBinaryOperator],["/",D.MultiplicativeBinaryOperator],["%",D.MultiplicativeBinaryOperator],["=",D.Equals]],mP=new Map([["n",`
3
+ `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function hP(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 _P(t,e={}){let r=[],s=hP(t,e),n=0,o=0,a=c=>{let p="";for(;c(s[n]);){if(s[n]==="\\"){if(++n,n>=s.length)throw new SyntaxError("Unexpected end of input");let f=s[n++],m=mP.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 c=r.at(-1);c&&c.type===D.Text&&(c.value=c.value.trimEnd(),c.value===""&&r.pop())},l=()=>{for(;n<s.length&&jk(s[n]);)++n};e:for(;n<s.length;){let c=r.at(-1)?.type;if(c===void 0||c===D.CloseStatement||c===D.CloseExpression||c===D.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 Gt(f,D.Text));continue}}if(s[n]==="{"&&s[n+1]==="#"){n+=2;let f=s[n]==="-";f&&++n;let m="";for(;s[n]!=="#"||s[n+1]!=="}";){if(n+2>=s.length)throw new SyntaxError("Missing end of comment tag");m+=s[n++]}let h=m.endsWith("-");h&&(m=m.slice(0,-1)),f&&i(),r.push(new Gt(m,D.Comment)),n+=2,h&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new Gt("{%",D.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new Gt("{{",D.OpenExpression)),o=0,n+=3;continue}if(a(jk),s.slice(n,n+3)==="-%}"){r.push(new Gt("%}",D.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new Gt("}}",D.CloseExpression)),n+=3,l();continue}let p=s[n];if(p==="-"||p==="+"){let f=r.at(-1)?.type;if(f===D.Text||f===void 0)throw new SyntaxError(`Unexpected character: ${p}`);switch(f){case D.Identifier:case D.NumericLiteral:case D.StringLiteral:case D.CloseParen:case D.CloseSquareBracket:break;default:{++n;let m=a(io);r.push(new Gt(`${p}${m}`,m.length>0?D.NumericLiteral:D.UnaryOperator));continue}}}for(let[f,m]of dP){if(f==="}}"&&o>0)continue;if(s.slice(n,n+f.length)===f){r.push(new Gt(f,m)),m===D.OpenExpression?o=0:m===D.OpenCurlyBracket?++o:m===D.CloseCurlyBracket&&--o,n+=f.length;continue e}}if(p==="'"||p==='"'){++n;let f=a(m=>m!==p);r.push(new Gt(f,D.StringLiteral)),++n;continue}if(io(p)){let f=a(io);if(s[n]==="."&&io(s[n+1])){++n;let m=a(io);f=`${f}.${m}`}r.push(new Gt(f,D.NumericLiteral));continue}if(Gk(p)){let f=a(Gk);r.push(new Gt(f,D.Identifier));continue}throw new SyntaxError(`Unexpected character: ${p}`)}return r}var er=class{type="Statement"},gP=class extends er{constructor(t){super(),this.body=t}type="Program"},wP=class extends er{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r}type="If"},xP=class extends er{constructor(t,e,r,s){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=s}type="For"},yP=class extends er{type="Break"},bP=class extends er{type="Continue"},vP=class extends er{constructor(t,e,r){super(),this.assignee=t,this.value=e,this.body=r}type="Set"},kP=class extends er{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r}type="Macro"},EP=class extends er{constructor(t){super(),this.value=t}type="Comment"},Nt=class extends er{type="Expression"},AP=class extends Nt{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r}type="MemberExpression"},qk=class extends Nt{constructor(t,e){super(),this.callee=t,this.args=e}type="CallExpression"},nn=class extends Nt{constructor(t){super(),this.value=t}type="Identifier"},on=class extends Nt{constructor(t){super(),this.value=t}type="Literal"},TP=class extends on{type="IntegerLiteral"},MP=class extends on{type="FloatLiteral"},Wk=class extends on{type="StringLiteral"},SP=class extends on{type="ArrayLiteral"},Vk=class extends on{type="TupleLiteral"},OP=class extends on{type="ObjectLiteral"},lo=class extends Nt{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r}type="BinaryExpression"},IP=class extends Nt{constructor(t,e){super(),this.operand=t,this.filter=e}type="FilterExpression"},CP=class extends er{constructor(t,e){super(),this.filter=t,this.body=e}type="FilterStatement"},PP=class extends Nt{constructor(t,e){super(),this.lhs=t,this.test=e}type="SelectExpression"},LP=class extends Nt{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r}type="TestExpression"},NP=class extends Nt{constructor(t,e){super(),this.operator=t,this.argument=e}type="UnaryExpression"},zP=class extends Nt{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r}type="SliceExpression"},RP=class extends Nt{constructor(t,e){super(),this.key=t,this.value=e}type="KeywordArgumentExpression"},$P=class extends Nt{constructor(t){super(),this.argument=t}type="SpreadExpression"},DP=class extends er{constructor(t,e,r){super(),this.call=t,this.callerArgs=e,this.body=r}type="CallStatement"},BP=class extends Nt{constructor(t,e,r){super(),this.condition=t,this.trueExpr=e,this.falseExpr=r}type="Ternary"};function UP(t){let e=new gP([]),r=0;function s(P,N){let $=t[r++];if(!$||$.type!==P)throw new Error(`Parser Error: ${N}. ${$.type} !== ${P}.`);return $}function n(P){if(!l(P))throw new SyntaxError(`Expected ${P}`);++r}function o(){switch(t[r].type){case D.Comment:return new EP(t[r++].value);case D.Text:return c();case D.OpenStatement:return p();case D.OpenExpression:return f();default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}}function a(...P){return r+P.length<=t.length&&P.every((N,$)=>N===t[r+$].type)}function i(...P){return t[r]?.type===D.OpenStatement&&t[r+1]?.type===D.Identifier&&P.includes(t[r+1]?.value)}function l(...P){return r+P.length<=t.length&&P.every((N,$)=>t[r+$].type==="Identifier"&&N===t[r+$].value)}function c(){return new Wk(s(D.Text,"Expected text token").value)}function p(){if(s(D.OpenStatement,"Expected opening statement token"),t[r].type!==D.Identifier)throw new SyntaxError(`Unknown statement, got ${t[r].type}`);let P=t[r].value,N;switch(P){case"set":++r,N=m();break;case"if":++r,N=h(),s(D.OpenStatement,"Expected {% token"),n("endif"),s(D.CloseStatement,"Expected %} token");break;case"macro":++r,N=w(),s(D.OpenStatement,"Expected {% token"),n("endmacro"),s(D.CloseStatement,"Expected %} token");break;case"for":++r,N=v(),s(D.OpenStatement,"Expected {% token"),n("endfor"),s(D.CloseStatement,"Expected %} token");break;case"call":{++r;let $=null;a(D.OpenParen)&&($=U());let J=le();if(J.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let Ie=U();s(D.CloseStatement,"Expected closing statement token");let ae=[];for(;!i("endcall");)ae.push(o());s(D.OpenStatement,"Expected '{%'"),n("endcall"),s(D.CloseStatement,"Expected closing statement token");let Fe=new qk(J,Ie);N=new DP(Fe,$,ae);break}case"break":++r,s(D.CloseStatement,"Expected closing statement token"),N=new yP;break;case"continue":++r,s(D.CloseStatement,"Expected closing statement token"),N=new bP;break;case"filter":{++r;let $=le();$ instanceof nn&&a(D.OpenParen)&&($=H($)),s(D.CloseStatement,"Expected closing statement token");let J=[];for(;!i("endfilter");)J.push(o());s(D.OpenStatement,"Expected '{%'"),n("endfilter"),s(D.CloseStatement,"Expected '%}'"),N=new CP($,J);break}default:throw new SyntaxError(`Unknown statement type: ${P}`)}return N}function f(){s(D.OpenExpression,"Expected opening expression token");let P=E();return s(D.CloseExpression,"Expected closing expression token"),P}function m(){let P=x(),N=null,$=[];if(a(D.Equals))++r,N=x();else{for(s(D.CloseStatement,"Expected %} token");!i("endset");)$.push(o());s(D.OpenStatement,"Expected {% token"),n("endset")}return s(D.CloseStatement,"Expected closing statement token"),new vP(P,N,$)}function h(){let P=E();s(D.CloseStatement,"Expected closing statement token");let N=[],$=[];for(;!i("elif","else","endif");)N.push(o());if(i("elif")){++r,++r;let J=h();$.push(J)}else if(i("else"))for(++r,++r,s(D.CloseStatement,"Expected closing statement token");!i("endif");)$.push(o());return new wP(P,N,$)}function w(){let P=le();if(P.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let N=U();s(D.CloseStatement,"Expected closing statement token");let $=[];for(;!i("endmacro");)$.push(o());return new kP(P,N,$)}function x(P=!1){let N=P?le:E,$=[N()],J=a(D.Comma);for(;J&&(++r,$.push(N()),!!a(D.Comma)););return J?new Vk($):$[0]}function v(){let P=x(!0);if(!(P instanceof nn||P instanceof Vk))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${P.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;let N=E();s(D.CloseStatement,"Expected closing statement token");let $=[];for(;!i("endfor","else");)$.push(o());let J=[];if(i("else"))for(++r,++r,s(D.CloseStatement,"Expected closing statement token");!i("endfor");)J.push(o());return new xP(P,N,$,J)}function E(){return A()}function A(){let P=S();if(l("if")){++r;let N=S();if(l("else")){++r;let $=A();return new BP(N,P,$)}else return new PP(P,N)}return P}function S(){let P=M();for(;l("or");){let N=t[r];++r;let $=M();P=new lo(N,P,$)}return P}function M(){let P=L();for(;l("and");){let N=t[r];++r;let $=L();P=new lo(N,P,$)}return P}function L(){let P;for(;l("not");){let N=t[r];++r;let $=L();P=new NP(N,$)}return P??O()}function O(){let P=k();for(;;){let N;if(l("not","in"))N=new Gt("not in",D.Identifier),r+=2;else if(l("in"))N=t[r++];else if(a(D.ComparisonBinaryOperator))N=t[r++];else break;let $=k();P=new lo(N,P,$)}return P}function k(){let P=B();for(;a(D.AdditiveBinaryOperator);){let N=t[r];++r;let $=B();P=new lo(N,P,$)}return P}function G(){let P=Y(le());return a(D.OpenParen)?H(P):P}function H(P){let N=new qk(P,U());return N=Y(N),a(D.OpenParen)&&(N=H(N)),N}function U(){s(D.OpenParen,"Expected opening parenthesis for arguments list");let P=V();return s(D.CloseParen,"Expected closing parenthesis for arguments list"),P}function V(){let P=[];for(;!a(D.CloseParen);){let N;if(t[r].type===D.MultiplicativeBinaryOperator&&t[r].value==="*"){++r;let $=E();N=new $P($)}else if(N=E(),a(D.Equals)){if(++r,!(N instanceof nn))throw new SyntaxError("Expected identifier for keyword argument");let $=E();N=new RP(N,$)}P.push(N),a(D.Comma)&&++r}return P}function q(){let P=[],N=!1;for(;!a(D.CloseSquareBracket);)a(D.Colon)?(P.push(void 0),++r,N=!0):(P.push(E()),a(D.Colon)&&(++r,N=!0));if(P.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(N){if(P.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new zP(...P)}return P[0]}function Y(P){for(;a(D.Dot)||a(D.OpenSquareBracket);){let N=t[r];++r;let $,J=N.type===D.OpenSquareBracket;if(J)$=q(),s(D.CloseSquareBracket,"Expected closing square bracket");else if($=le(),$.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");P=new AP(P,$,J)}return P}function B(){let P=C();for(;a(D.MultiplicativeBinaryOperator);){let N=t[r++],$=C();P=new lo(N,P,$)}return P}function C(){let P=te();for(;l("is");){++r;let N=l("not");N&&++r;let $=le();if(!($ instanceof nn))throw new SyntaxError("Expected identifier for the test");P=new LP(P,N,$)}return P}function te(){let P=G();for(;a(D.Pipe);){++r;let N=le();if(!(N instanceof nn))throw new SyntaxError("Expected identifier for the filter");a(D.OpenParen)&&(N=H(N)),P=new IP(P,N)}return P}function le(){let P=t[r++];switch(P.type){case D.NumericLiteral:{let N=P.value;return N.includes(".")?new MP(Number(N)):new TP(Number(N))}case D.StringLiteral:{let N=P.value;for(;a(D.StringLiteral);)N+=t[r++].value;return new Wk(N)}case D.Identifier:return new nn(P.value);case D.OpenParen:{let N=x();return s(D.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),N}case D.OpenSquareBracket:{let N=[];for(;!a(D.CloseSquareBracket);)N.push(E()),a(D.Comma)&&++r;return++r,new SP(N)}case D.OpenCurlyBracket:{let N=new Map;for(;!a(D.CloseCurlyBracket);){let $=E();s(D.Colon,"Expected colon between key and value in object literal");let J=E();N.set($,J),a(D.Comma)&&++r}return++r,new OP(N)}default:throw new SyntaxError(`Unexpected token: ${P.type}`)}}for(;r<t.length;)e.body.push(o());return e}function FP(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 Hk(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 GP(t){return t.replace(/\b\w/g,e=>e.toUpperCase())}function jP(t){return qP(new Date,t)}function qP(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 WP(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function VP(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(WP(e),"gu");return t.replaceAll(o,a=>n>0?(--n,r):a)}var Xk=class extends Error{},Kk=class extends Error{},cr=class{type="RuntimeValue";value;builtins=new Map;constructor(t=void 0){this.value=t}__bool__(){return new pe(!!this.value)}toString(){return String(this.value)}},he=class extends cr{type="IntegerValue"},Ze=class extends cr{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},ee=class extends cr{type="StringValue";builtins=new Map([["upper",new qe(()=>new ee(this.value.toUpperCase()))],["lower",new qe(()=>new ee(this.value.toLowerCase()))],["strip",new qe(()=>new ee(this.value.trim()))],["title",new qe(()=>new ee(GP(this.value)))],["capitalize",new qe(()=>new ee(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new he(this.value.length)],["rstrip",new qe(()=>new ee(this.value.trimEnd()))],["lstrip",new qe(()=>new ee(this.value.trimStart()))],["startswith",new qe(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");let e=t[0];if(e instanceof ee)return new pe(this.value.startsWith(e.value));if(e instanceof ye){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 pe(!0)}return new pe(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new qe(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");let e=t[0];if(e instanceof ee)return new pe(this.value.endsWith(e.value));if(e instanceof ye){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 pe(!0)}return new pe(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new qe(t=>{let e=t[0]??new Ve;if(!(e instanceof ee||e instanceof Ve))throw new Error("sep argument must be a string or null");let r=t[1]??new he(-1);if(!(r instanceof he))throw new Error("maxsplit argument must be a number");let s=[];if(e instanceof Ve){let n=this.value.trimStart();for(let{0:o,index:a}of n.matchAll(/\S+/g)){if(r.value!==-1&&s.length>=r.value&&a!==void 0){s.push(o+n.slice(a+o.length));break}s.push(o)}}else{if(e.value==="")throw new Error("empty separator");s=this.value.split(e.value),r.value!==-1&&s.length>r.value&&s.push(s.splice(r.value).join(e.value))}return new ye(s.map(n=>new ee(n)))})],["replace",new qe(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 Ve:s=t[2]:s=new Ve,!(s instanceof he||s instanceof Ve))throw new Error("replace() count argument must be a number or null");return new ee(VP(this.value,e.value,r.value,s.value))})]])},pe=class extends cr{type="BooleanValue"},HP=/[\x7f-\uffff]/g;function Yk(t){return t.replace(HP,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function gs(t,e={},r=0,s=!0){let{indent:n=null,ensureAscii:o=!1,separators:a=null,sortKeys:i=!1}=e,l,c;switch(a?[l,c]=a:n?(l=",",c=": "):(l=", ",c=": "),t.type){case"NullValue":return"null";case"UndefinedValue":return s?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(t.value);case"StringValue":{let p=JSON.stringify(t.value);return o&&(p=Yk(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=>gs(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],[v])=>x.localeCompare(v)));let w=h.map(([x,v])=>{let E=JSON.stringify(x);o&&(E=Yk(E));let A=`${E}${c}${gs(v,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 ft=class extends cr{type="ObjectValue";__bool__(){return new pe(this.value.size>0)}builtins=new Map([["get",new qe(([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 Ve})],["items",new qe(()=>this.items())],["keys",new qe(()=>this.keys())],["values",new qe(()=>this.values())],["dictsort",new qe(t=>{let e=new Map,r=t.filter(i=>i instanceof co?(e=i.value,!1):!0),s=r.at(0)??e.get("case_sensitive")??new pe(!1);if(!(s instanceof pe))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 pe(!1);if(!(o instanceof pe))throw new Error("reverse must be a boolean");let a=Array.from(this.value.entries()).map(([i,l])=>new ye([new ee(i),l])).sort((i,l)=>{let c=n.value==="key"?0:1,p=i.value[c],f=l.value[c],m=ff(p,f,s.value);return o.value?-m:m});return new ye(a)})]]);items(){return new ye(Array.from(this.value.entries()).map(([t,e])=>new ye([new ee(t),e])))}keys(){return new ye(Array.from(this.value.keys()).map(t=>new ee(t)))}values(){return new ye(Array.from(this.value.values()))}toString(){return gs(this,{},0,!1)}},co=class extends ft{type="KeywordArgumentsValue"},ye=class extends cr{type="ArrayValue";builtins=new Map([["length",new he(this.value.length)]]);__bool__(){return new pe(this.value.length>0)}toString(){return gs(this,{},0,!1)}},Qk=class extends ye{type="TupleValue"},qe=class extends cr{type="FunctionValue"},Ve=class extends cr{type="NullValue"},je=class extends cr{type="UndefinedValue"},_s=class{constructor(t){this.parent=t}variables=new Map([["namespace",new qe(t=>{if(t.length===0)return new ft(new Map);if(t.length!==1||!(t[0]instanceof ft))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 qe],["odd",t=>{if(!(t instanceof he))throw new Error(`cannot odd on ${t.type}`);return t.value%2!==0}],["even",t=>{if(!(t instanceof he))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 he||t instanceof Ze],["integer",t=>t instanceof he],["iterable",t=>t.type==="ArrayValue"||t.type==="StringValue"],["mapping",t=>t instanceof ft],["sequence",t=>t instanceof ye||t instanceof ft||t instanceof ee],["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,Hl(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 XP(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",FP),t.set("strftime_now",jP),t.set("True",!0),t.set("False",!1),t.set("None",null)}function Jk(t,e){let r=e.split("."),s=t;for(let n of r)if(s instanceof ft)s=s.value.get(n)??new je;else if(s instanceof ye){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 ff(t,e,r=!1){if(t instanceof Ve&&e instanceof Ve)return 0;if(t instanceof Ve||e instanceof Ve)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 he||o instanceof Ze||o instanceof pe,n=o=>o instanceof pe?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 KP=class{global;constructor(t){this.global=t??new _s}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 pe(r.value==s.value);case"!=":return new pe(r.value!=s.value)}if(r instanceof je||s instanceof je){if(s instanceof je&&["in","not in"].includes(t.operator.value))return new pe(t.operator.value==="not in");throw new Error(`Cannot perform operation ${t.operator.value} on undefined values`)}else{if(r instanceof Ve||s instanceof Ve)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 he||r instanceof Ze)&&(s instanceof he||s instanceof Ze)){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 Ze||s instanceof Ze?new Ze(a):new he(a)}case"/":return new Ze(n/o);case"%":{let a=n%o;return r instanceof Ze||s instanceof Ze?new Ze(a):new he(a)}case"<":return new pe(n<o);case">":return new pe(n>o);case">=":return new pe(n>=o);case"<=":return new pe(n<=o)}}else if(r instanceof ye&&s instanceof ye){if(t.operator.value==="+")return new ye(r.value.concat(s.value))}else if(s instanceof ye){let n=s.value.find(o=>o.value===r.value)!==void 0;switch(t.operator.value){case"in":return new pe(n);case"not in":return new pe(!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 pe(s.value.includes(r.value));case"not in":return new pe(!s.value.includes(r.value))}if(r instanceof ee&&s instanceof ft)switch(t.operator.value){case"in":return new pe(s.value.has(r.value));case"not in":return new pe(!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 ye))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==="safe")return t;if(s.value==="tojson")return new ee(gs(t,{}));if(t instanceof ye)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 he(t.value.length);case"reverse":return new ye(t.value.slice().reverse());case"sort":return new ye(t.value.slice().sort((n,o)=>ff(n,o,!1)));case"join":return new ee(t.value.map(n=>n.value).join(""));case"string":return new ee(gs(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 ye(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 qe)return n.value([],r);if(n instanceof he)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 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 wt)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 c=o.get("separators")??new We,p=null;if(c instanceof ve||c instanceof mk){if(c.value.length!==2)throw new Error("separators must be a tuple of two strings");let[f,m]=c.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(!(c instanceof We))throw new Error("If set, separators must be a tuple of two strings");return new ee(_s(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(c=>c.value);else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`);let[a,i]=this.evaluateArguments(s.args,r),l=a.at(0)??i.get("separator")??new 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 c=o.at(2)??a.get("attribute")??new We;if(!(c instanceof ee||c instanceof me||c instanceof We))throw new Error("attribute must be a string, integer, or null");let p=f=>{if(c instanceof We)return f;let m=c instanceof me?String(c.value):c.value;return hk(f,m)};return new ve(t.value.slice().sort((f,m)=>{let h=p(f),w=p(m),x=Vp(h,w,l.value);return i.value?-x:x}))}case"selectattr":case"rejectattr":{let o=n==="selectattr";if(t.value.some(f=>!(f instanceof wt)))throw new Error(`\`${n}\` can only be applied to array of objects`);if(s.args.some(f=>f.type!=="StringLiteral"))throw new Error(`arguments of \`${n}\` must be strings`);let[a,i,l]=s.args.map(f=>this.evaluate(f,r)),c;if(i){let f=r.tests.get(i.value);if(!f)throw new Error(`Unknown test: ${i.value}`);c=f}else c=(...f)=>f[0].__bool__().value;let p=t.value.filter(f=>{let m=f.value.get(a.value),h=m?c(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(c=>{if(!(c instanceof wt))throw new Error("items in map must be an object");let p=hk(c,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),c=o.at(2)??a.get("blank")??new ce(!1),p=t.value.split(`
7
+ `));case"join":case"string":return t;case"int":{let n=parseInt(t.value,10);return new he(isNaN(n)?0:n)}case"float":{let n=parseFloat(t.value);return new Ze(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${s.value}`)}else if(t instanceof he||t instanceof Ze)switch(s.value){case"abs":return t instanceof he?new he(Math.abs(t.value)):new Ze(Math.abs(t.value));case"int":return new he(Math.floor(t.value));case"float":return new Ze(t.value);case"string":return new ee(t.toString());default:throw new Error(`Unknown NumericValue filter: ${s.value}`)}else if(t instanceof ft)switch(s.value){case"items":return new ye(Array.from(t.value.entries()).map(([n,o])=>new ye([new ee(n),o])));case"length":return new he(t.value.size);default:{let n=t.builtins.get(s.value);if(n)return n instanceof qe?n.value([],r):n;throw new Error(`Unknown ObjectValue filter: ${s.value}`)}}else if(t instanceof pe)switch(s.value){case"bool":return new pe(t.value);case"int":return new he(t.value?1:0);case"float":return new Ze(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 Ve;if(!(a instanceof he||a instanceof Ve))throw new Error("If set, indent must be a number");let i=o.get("ensure_ascii")??new pe(!1);if(!(i instanceof pe))throw new Error("If set, ensure_ascii must be a boolean");let l=o.get("sort_keys")??new pe(!1);if(!(l instanceof pe))throw new Error("If set, sort_keys must be a boolean");let c=o.get("separators")??new Ve,p=null;if(c instanceof ye||c instanceof Qk){if(c.value.length!==2)throw new Error("separators must be a tuple of two strings");let[f,m]=c.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(!(c instanceof Ve))throw new Error("If set, separators must be a tuple of two strings");return new ee(gs(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 ye)o=t.value.map(c=>c.value);else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`);let[a,i]=this.evaluateArguments(s.args,r),l=a.at(0)??i.get("separator")??new 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 he(0):new Ze(0));if(t instanceof ee){let l=n==="int"?parseInt(t.value,10):parseFloat(t.value);return isNaN(l)?i:n==="int"?new he(l):new Ze(l)}else{if(t instanceof he||t instanceof Ze)return t;if(t instanceof pe)return n==="int"?new he(t.value?1:0):new Ze(t.value?1:0);throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}}else if(n==="default"){let[o,a]=this.evaluateArguments(s.args,r),i=o[0]??new ee(""),l=o[1]??a.get("boolean")??new pe(!1);if(!(l instanceof pe))throw new Error("`default` filter flag must be a boolean");return t instanceof je||l.value&&!t.__bool__().value?i:t}if(t instanceof ye){switch(n){case"sort":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("reverse")??new pe(!1);if(!(i instanceof pe))throw new Error("reverse must be a boolean");let l=o.at(1)??a.get("case_sensitive")??new pe(!1);if(!(l instanceof pe))throw new Error("case_sensitive must be a boolean");let c=o.at(2)??a.get("attribute")??new Ve;if(!(c instanceof ee||c instanceof he||c instanceof Ve))throw new Error("attribute must be a string, integer, or null");let p=f=>{if(c instanceof Ve)return f;let m=c instanceof he?String(c.value):c.value;return Jk(f,m)};return new ye(t.value.slice().sort((f,m)=>{let h=p(f),w=p(m),x=ff(h,w,l.value);return i.value?-x:x}))}case"selectattr":case"rejectattr":{let o=n==="selectattr";if(t.value.some(f=>!(f instanceof ft)))throw new Error(`\`${n}\` can only be applied to array of objects`);if(s.args.some(f=>f.type!=="StringLiteral"))throw new Error(`arguments of \`${n}\` must be strings`);let[a,i,l]=s.args.map(f=>this.evaluate(f,r)),c;if(i){let f=r.tests.get(i.value);if(!f)throw new Error(`Unknown test: ${i.value}`);c=f}else c=(...f)=>f[0].__bool__().value;let p=t.value.filter(f=>{let m=f.value.get(a.value),h=m?c(m,l):!1;return o?h:!h});return new ye(p)}case"map":{let[,o]=this.evaluateArguments(s.args,r);if(o.has("attribute")){let a=o.get("attribute");if(!(a instanceof ee))throw new Error("attribute must be a string");let i=o.get("default"),l=t.value.map(c=>{if(!(c instanceof ft))throw new Error("items in map must be an object");let p=Jk(c,a.value);return p instanceof je?i??new je:p});return new ye(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}else if(t instanceof ee){switch(n){case"indent":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("width")??new he(4);if(!(i instanceof he))throw new Error("width must be a number");let l=o.at(1)??a.get("first")??new pe(!1),c=o.at(2)??a.get("blank")??new pe(!1),p=t.value.split(`
8
8
  `),f=" ".repeat(i.value),m=p.map((h,w)=>!l.value&&w===0||!c.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 Qn(i)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(t instanceof wt){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 Qn(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 Qn(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(uk(t.value,s.value,n.value,o.value)):new ee(uk(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 wt){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 lr?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 wt))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 hs(e),s,n;if(t.iterable.type==="SelectExpression"){let c=t.iterable;n=this.evaluate(c.lhs,r),s=c.test}else n=this.evaluate(t.iterable,r);if(!(n instanceof ve||n instanceof wt))throw new Error(`Expected iterable or object type in for loop: got ${n.type}`);n instanceof wt&&(n=n.keys());let o=[],a=[];for(let c=0;c<n.value.length;++c){let p=new hs(r),f=n.value[c],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 b=0;b<h.value.length;++b){if(h.value[b].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${h.value[b].type}`);x.setVariable(h.value[b].value,w.value[b])}}}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 c=0;c<o.length;++c){let p=new Map([["index",new me(c+1)],["index0",new me(c)],["revindex",new me(o.length-c)],["revindex0",new me(o.length-c-1)],["first",new ce(c===0)],["last",new ce(c===o.length-1)],["length",new me(o.length)],["previtem",c>0?o[c-1]:new je],["nextitem",c<o.length-1?o[c+1]:new je]]);r.setVariable("loop",new wt(p)),a[c](r);try{let f=this.evaluateBlock(t.body,r);i+=f.value}catch(f){if(f instanceof fk)continue;if(f instanceof pk)break;throw f}l=!1}if(l){let c=this.evaluateBlock(t.defaultBlock,r);i+=c.value}return new ee(i)}evaluateMacro(t,e){return e.setVariable(t.name.value,new Ge((r,s)=>{let n=new hs(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 c=i;if(!l)throw new Error(`Missing positional argument: ${c.value}`);n.setVariable(c.value,l)}else if(i.type==="KeywordArgumentExpression"){let c=i,p=l??o?.value.get(c.key.value)??this.evaluate(c.value,n);n.setVariable(c.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 c=new hs(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}`);c.setVariable(f.value,i[p]??new je)}return this.evaluateBlock(t.body,c)}),[s,n]=this.evaluateArguments(t.call.args,e);s.push(new Qn(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 hs(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 pk;case"Continue":throw new fk;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 mk(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 wt(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 Ol(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(Ol)):new wt(new Map(Object.entries(t).map(([e,r])=>[e,Ol(r)])));case"function":return new Ge((e,r)=>{let s=t(...e.map(n=>n.value))??null;return Ol(s)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}var ot=`
10
- `,tP="{%- ",rP=" -%}";function sP(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 nP(t,e=" "){let r=typeof e=="number"?" ".repeat(e):e;return Zt(t.body,0,r).replace(/\n$/,"")}function mt(...t){return tP+t.join(" ")+rP}function Zt(t,e,r){return t.map(s=>oP(s,e,r)).join(ot)}function oP(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return Zt(t.body,e,r);case"If":return aP(t,e,r);case"For":return iP(t,e,r);case"Set":return lP(t,e,r);case"Macro":return cP(t,e,r);case"Break":return s+mt("break");case"Continue":return s+mt("continue");case"CallStatement":return uP(t,e,r);case"FilterStatement":return pP(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+ke(t)+" -}}"}}function aP(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+Zt(n[0].body,e+1,r);for(let i=1;i<n.length;++i)a+=ot+s+mt("elif",ke(n[i].test))+ot+Zt(n[i].body,e+1,r);return o&&o.alternate.length>0&&(a+=ot+s+mt("else")+ot+Zt(o.alternate,e+1,r)),a+=ot+s+mt("endif"),a}function iP(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+Zt(t.body,e+1,r);return t.defaultBlock.length>0&&(o+=ot+s+mt("else")+ot+Zt(t.defaultBlock,e+1,r)),o+=ot+s+mt("endfor"),o}function lP(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+Zt(t.body,e+1,r)+ot+s+mt("endset")}function cP(t,e,r){let s=r.repeat(e),n=t.args.map(ke).join(", ");return s+mt("macro",`${t.name.value}(${n})`)+ot+Zt(t.body,e+1,r)+ot+s+mt("endmacro")}function uP(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+=Zt(t.body,e+1,r)+ot,a+=s+mt("endcall"),a}function pP(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+=Zt(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=sP(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 _k=class{parsed;constructor(t){let e=bC(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=WC(e)}render(t){let e=new hs;if(ZC(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new eP(e).run(this.parsed).value}format(t){return nP(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")}};var fP={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"},gs=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=Et.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=Et.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let s=Et.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",fP[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 Et.promises.readFile(this.filePath)).buffer}async blob(){let e=await Et.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await Et.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},en=class{constructor(e){this.path=e}async match(e){let r=Bt.join(this.path,e),s=new gs(r);if(s.exists)return s}async put(e,r,s=void 0){let n=Bt.join(this.path,e);try{let o=r.headers.get("Content-Length"),a=parseInt(o??"0"),i=0;await Et.promises.mkdir(Bt.dirname(n),{recursive:!0});let l=Et.createWriteStream(n),c=r.body.getReader();for(;;){let{done:p,value:f}=await c.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 Et.promises.unlink(n)}catch{}throw o}}async delete(e){let r=Bt.join(this.path,e);try{return await Et.promises.unlink(r),!0}catch{return!1}}};var gk={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"},Il=100,wk=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Jn(...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 Tr(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 xk(t){return!(!wk.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function yk(t,e,r){if(!r)return null;let s=gk[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${s}: "${e}".`)}async function bk(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:c,value:p}=await i.read();if(c)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 cr(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){Q.warn("An error occurred while opening the browser cache:",r)}}if(!e&&de.useFSCache){if(!ge.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");e=new en(t??de.cacheDir)}return e}async function vk(t,...e){for(let r of e)try{let s=await t.match(r);if(s)return s}catch{continue}}async function dP(t){if(!Tr(t,["http:","https:"]))return null;let e=Hp(t);return e.set("Range","bytes=0-0"),de.fetch(t,{method:"GET",headers:e})}async function ur(t,e,r={}){let s=await cr(r?.cache_dir),{localPath:n,remoteURL:o,proposedCacheKey:a,validModelId:i}=ws(t,e,r,s),l=await xs(s,n,a);if(l!==void 0&&typeof l!="string"){let c=l.headers.get("content-length"),p=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:p||void 0,fromCache:!0}}if(de.allowLocalModels&&!Tr(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(de.allowRemoteModels&&!r.local_files_only&&i)try{let c=await dP(o);if(c&&c.status>=200&&c.status<300){let p,f=c.headers.get("content-type");if(c.status===206){let m=c.headers.get("content-range");if(m){let h=m.match(/bytes \d+-\d+\/(\d+)/);h&&(p=parseInt(h[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(p===void 0){let m=c.headers.get("content-length");p=m?parseInt(m,10):void 0}return{exists:!0,size:p,contentType:f||void 0,fromCache:!1}}}catch(c){Q.warn(`Unable to fetch file metadata for "${o}": ${c}`)}return{exists:!1,fromCache:!1}}async function zr(t){return de.useFS&&!Tr(t,["http:","https:","blob:"])?new gs(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t):de.fetch(t,{headers:Hp(t)})}function Hp(t){let e=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(e){let s=!!process.env?.TESTING_REMOTELY,n=de.version;if(r.set("User-Agent",`transformers.js/${n}; is_ci/${s};`),Tr(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 ws(t,e,r={},s=null){let n=r.revision??"main",o=Jn(t,e),a=xk(t),i=a?Jn(de.localModelPath,o):o,l=Jn(de.remoteHost,de.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),c=s instanceof en?n==="main"?o:Jn(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:a}}async function xs(t,e,r){if(t)return await vk(t,e,r)}async function mP(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=>Er(a.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await r.put(s,n,i)}}async function hP(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:p}=ws(t,e,s,o),f,m=!1,h;h=await xs(o,i,c);let w=h!==void 0;if(!w){if(de.allowLocalModels)if(Tr(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{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||!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(!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 yk(h.status,l,r);f=c}m=o&&typeof Response<"u"&&h instanceof Response&&h.status===200}Er(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()),Er(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 M=await ur(t,e,s);M.size&&(A=M.size)}catch{}E=await bk(h,M=>{Er(s.progress_callback,{status:"progress",name:t,file:e,...M})},A)}x=E}if(m&&f&&typeof h!="string"&&await mP(t,e,o,f,h,x,s),Er(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 gs)return h.filePath;let b=await o?.match(f);if(b instanceof gs)return b.filePath;if(b instanceof Response)return new Uint8Array(await b.arrayBuffer());if(typeof b=="string")return b;throw new Error("Unable to get model file path or buffer.")}async function Zn(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`.")}Er(s.progress_callback,{status:"initiate",name:t,file:e});let o=await cr(s?.cache_dir);return await hP(t,e,r,s,n,o)}async function Xp(t,e,r=!0,s={}){let n=await Zn(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 Xp(t,e,r,s);return n===null?{}:JSON.parse(n)}function Ek(t,[e,r,s],[n,o],a="bilinear",i=!1){let l=o/s,c=n/r,p=new t.constructor(n*o*e),f=r*s,m=n*o;for(let h=0;h<n;++h)for(let w=0;w<o;++w){let x=h*o+w,b=(w+.5)/l-.5,E=(h+.5)/c-.5,A=Math.floor(b),S=Math.floor(E),M=Math.min(A+1,s-1),C=Math.min(S+1,r-1);A=Math.max(A,0),S=Math.max(S,0);let P=b-A,k=E-S,F=(1-P)*(1-k),H=P*(1-k),V=(1-P)*k,J=P*k,X=S*s,Y=C*s,U=X+A,L=X+M,ne=Y+A,ae=Y+M;for(let I=0;I<e;++I){let N=I*f;p[I*m+x]=F*t[N+U]+H*t[N+L]+V*t[N+ne]+J*t[N+ae]}}return p}function Ak(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 c=e.length-1,p=i;c>=0;--c)l+=p%e[c]*o[c],p=Math.floor(p/e[c]);a[l]=t[i]}return[a,s]}function Ne(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 Yp(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 Tk(t,e){let r=0;for(let s=0;s<t.length;++s)r+=t[s]*e[s];return r}function _P(t,e){let r=Tk(t,e),s=kk(t),n=kk(e);return r/(s*n)}function kk(t){return Math.sqrt(t.reduce((e,r)=>e+r*r,0))}function eo(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 Mk(t){return t>0&&(t&t-1)===0}var Cl=class{constructor(e){if(this.size=e|0,this.size<=1||!Mk(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,c,p=this._bitrev;if(i===4)for(l=0,c=0;l<n;l+=i,++c){let m=p[c];this._singleTransform2(r,e,l,m,a)}else for(l=0,c=0;l<n;l+=i,++c){let m=p[c];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 b=w,E=b+m,A=E+m,S=A+m,M=e[b],C=e[b+1],P=e[E],k=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=P*X-k*Y,L=P*Y+k*X,ne=f[2*x],ae=s*f[2*x+1],I=F*ne-H*ae,N=F*ae+H*ne,$=f[3*x],te=s*f[3*x+1],pe=V*$-J*te,Fe=V*te+J*$,Pe=M+I,Mt=C+N,Je=M-I,et=C-N,st=U+pe,Te=L+Fe,xe=s*(U-pe),qe=s*(L-Fe);e[b]=Pe+st,e[b+1]=Mt+Te,e[E]=Je+qe,e[E+1]=et-xe,e[A]=Pe-st,e[A+1]=Mt-Te,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],c=e[n+o+1];r[s]=a+l,r[s+1]=i+c,r[s+2]=a-l,r[s+3]=i-c}_singleTransform4(e,r,s,n,o,a){let i=o*2,l=o*3,c=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],b=e[n+l+1],E=c+h,A=p+w,S=c-h,M=p-w,C=f+x,P=m+b,k=a*(f-x),F=a*(m-b);r[s]=E+C,r[s+1]=A+P,r[s+2]=S+F,r[s+3]=M-k,r[s+4]=E-C,r[s+5]=A-P,r[s+6]=S-F,r[s+7]=M+k}_realTransform4(e,r,s){let n=this._csize,a=1<<this._width,i=n/a<<1,l,c,p=this._bitrev;if(i===4)for(l=0,c=0;l<n;l+=i,++c){let h=p[c];this._singleRealTransform2(r,e,l,h>>>1,a>>>1)}else for(l=0,c=0;l<n;l+=i,++c){let h=p[c];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 b=0,E=0;b<=x;b+=2,E+=a){let A=l+b,S=A+w,M=S+w,C=M+w,P=e[A],k=e[A+1],F=e[S],H=e[S+1],V=e[M],J=e[M+1],X=e[C],Y=e[C+1],U=P,L=k,ne=f[E],ae=s*f[E+1],I=F*ne-H*ae,N=F*ae+H*ne,$=f[2*E],te=s*f[2*E+1],pe=V*$-J*te,Fe=V*te+J*$,Pe=f[3*E],Mt=s*f[3*E+1],Je=X*Pe-Y*Mt,et=X*Mt+Y*Pe,st=U+pe,Te=L+Fe,xe=U-pe,qe=L-Fe,St=I+Je,be=N+et,Re=s*(I-Je),Pr=s*(N-et);if(e[A]=st+St,e[A+1]=Te+be,e[S]=xe+Pr,e[S+1]=qe-Re,b===0){e[M]=st-St,e[M+1]=Te-be;continue}if(b===x)continue;let cs=l+w-b,Ot=l+h-b;e[cs]=xe-s*Pr,e[cs+1]=-qe-s*Re,e[Ot]=st-s*St,e[Ot+1]=-Te+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,c=e[n],p=e[n+o],f=e[n+i],m=e[n+l],h=c+f,w=c-f,x=p+m,b=a*(p-m);r[s]=h+x,r[s+1]=0,r[s+2]=w,r[s+3]=-b,r[s+4]=h-x,r[s+5]=0,r[s+6]=w,r[s+7]=b}},Kp=class{constructor(e){let r=2*(e-1),s=2*(2*e-1),n=2**Math.ceil(Math.log2(s));this.bufferSize=n,this._a=r;let o=new Float64Array(s),a=new Float64Array(n);this._chirpBuffer=new Float64Array(n),this._buffer1=new Float64Array(n),this._buffer2=new Float64Array(n),this._outBuffer1=new Float64Array(n),this._outBuffer2=new Float64Array(n);let i=-2*Math.PI/e,l=Math.cos(i),c=Math.sin(i);for(let p=0;p<s>>1;++p){let f=(p+1-e)**2/2,m=Math.sqrt(l**2+c**2)**f,h=f*Math.atan2(c,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 Cl(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,r,s){let n=this._buffer1,o=this._buffer2,a=this._outBuffer1,i=this._outBuffer2,l=this._chirpBuffer,c=this._slicedChirpBuffer,p=this._a;if(s)for(let f=0;f<c.length;f+=2){let m=f+1,h=f>>1,w=r[h];n[f]=w*c[f],n[m]=w*c[m]}else for(let f=0;f<c.length;f+=2){let m=f+1;n[f]=r[f]*c[f]-r[m]*c[m],n[m]=r[f]*c[m]+r[m]*c[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=c[f],x=c[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)}},Pl=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=Mk(e),this.isPowerOfTwo?(this.fft=new Cl(e),this.outputBufferSize=2*e):(this.fft=new Kp(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,r){this.fft.realTransform(e,r)}transform(e,r){this.fft.transform(e,r)}};function Sk(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 ys(t,e){let r=Math.pow(10,e);return Math.round(t*r)/r}function Ok(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function Ik(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,b;m<h&&m<w?(x=m,b=0):h<m&&h<w?(x=h,b=1):(x=w,b=2),n[f][p]=t[f-1][p-1]+x,o[f][p]=b}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=[],c=[];for(;a>0||i>0;)switch(l.push(a-1),c.push(i-1),o[a][i]){case 0:--a,--i;break;case 1:--a;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${a}, ${i}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}var Ck=(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 c=0,p=(l&32768)<<16,f=(l&31744)>>10,m=l&1023;if(f===31)c=p|2139095040|m<<13;else if(f===0)if(m===0)c=p;else{let h=113;for(;(m&1024)===0;)m<<=1,--h;m&=-1025,c=p|h<<23|m<<13}else c=p|f+112<<23|m<<13;a[0]=c,t[l]=i[0]}}let r=e.length,s=t,n=new Float32Array(r);for(let o=0;o<r;++o)n[o]=s[e[o]];return n}})();var Qp={};ms(Qp,{default:()=>gP});var gP={};var jf={};ms(jf,{InferenceSession:()=>Mf,TRACE:()=>Fl,TRACE_EVENT_BEGIN:()=>Br,TRACE_EVENT_END:()=>Fr,TRACE_FUNC_BEGIN:()=>Ts,TRACE_FUNC_END:()=>Ms,Tensor:()=>tr,default:()=>VP,env:()=>Ve,registerBackend:()=>As});var Af=Object.defineProperty,wP=Object.getOwnPropertyDescriptor,xP=Object.getOwnPropertyNames,yP=Object.prototype.hasOwnProperty,bP=(t=>typeof ds<"u"?ds:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof ds<"u"?ds:e)[r]}):t)(function(t){if(typeof ds<"u")return ds.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),ye=(t,e)=>()=>(t&&(e=t(t=0)),e),lo=(t,e)=>{for(var r in e)Af(t,r,{get:e[r],enumerable:!0})},vP=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of xP(e))!yP.call(t,n)&&n!==r&&Af(t,n,{get:()=>e[n],enumerable:!(s=wP(e,n))||s.enumerable});return t},Bl=t=>vP(Af({},"__esModule",{value:!0}),t),to,Rr,As,Pk,oE,aE=ye(()=>{"use strict";to=new Map,Rr=[],As=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let s=to.get(t);if(s===void 0)to.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=Rr.indexOf(t);n!==-1&&Rr.splice(n,1);for(let o=0;o<Rr.length;o++)if(to.get(Rr[o]).priority<=r){Rr.splice(o,0,t);return}Rr.push(t)}return}throw new TypeError("not a valid backend")},Pk=async t=>{let e=to.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}}},oE=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),s=r.length===0?Rr:r,n,o=[],a=new Set;for(let l of s){let c=await Pk(l);typeof c=="string"?o.push({name:l,err:c}):(n||(n=c),n===c&&a.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of o)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=e.filter(l=>a.has(typeof l=="string"?l:l.name));return[n,new Proxy(t,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),kP=ye(()=>{"use strict";aE()}),iE,EP=ye(()=>{"use strict";iE="1.24.0-dev.20251116-b39e144322"}),Jp,ut,lE=ye(()=>{"use strict";EP(),Jp="warning",ut={wasm:{},webgl:{},webgpu:{},versions:{common:iE},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}`);Jp=t}},get logLevel(){return Jp}},Object.defineProperty(ut,"logLevel",{enumerable:!0})}),Ve,AP=ye(()=>{"use strict";lE(),Ve=ut}),cE,uE,TP=ye(()=>{"use strict";cE=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let p=o*n,f=0,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 b=0;b<n;b++){let E=(t.data[f++]-c[0])*l[0],A=(t.data[m++]-c[1])*l[1],S=(t.data[h++]-c[2])*l[2],M=w===-1?255:(t.data[w++]-c[3])*l[3];s.fillStyle="rgba("+E+","+A+","+S+","+M+")",s.fillRect(b,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")},uE=(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,c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,h=0,w=1,x=2,b=3,E=0,A=f,S=f*2,M=-1;i==="RGBA"?(E=0,A=f,S=f*2,M=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 C=0;C<o*n;h+=m,w+=m,x+=m,b+=m,C++)s.data[h]=(t.data[E++]-p[0])*c[0],s.data[w]=(t.data[A++]-p[1])*c[1],s.data[x]=(t.data[S++]-p[2])*c[2],s.data[b]=M===-1?255:(t.data[M++]-p[3])*c[3]}else throw new Error("Can not access image data");return s}}),Ll,pE,fE,dE,mE,hE,MP=ye(()=>{"use strict";Tf(),Ll=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,m=0,h=1,w=2,x=3,b=0,E=c,A=c*2,S=-1;i==="RGB"&&(f=3,m=0,h=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(b=0,A=c,E=c*2):l==="BGR"&&(A=0,E=c,b=c*2);for(let M=0;M<c;M++,m+=f,w+=f,h+=f,x+=f)p[b++]=(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 $t("float32",p,[1,4,r,s]):new $t("float32",p,[1,3,r,s])},pE=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")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){let p=l();p.width=t.width,p.height=t.height;let f=c(p);if(f!=null){let 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=c(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=c(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,Ll(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,f)=>{let m=l(),h=c(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(Ll(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return Ll(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},fE=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new $t({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},dE=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new $t({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},mE=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new $t({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},hE=(t,e,r)=>new $t({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),ks,ao,Zp,_E,SP=ye(()=>{"use strict";ks=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ao=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Zp=!1,_E=()=>{if(!Zp){Zp=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(ks.set("int64",BigInt64Array),ao.set(BigInt64Array,"int64")),e&&(ks.set("uint64",BigUint64Array),ao.set(BigUint64Array,"uint64")),s?(ks.set("float16",r),ao.set(r,"float16")):ks.set("float16",Uint16Array)}}}),gE,wE,OP=ye(()=>{"use strict";Tf(),gE=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},wE=(t,e)=>{switch(t.location){case"cpu":return new $t(t.type,t.data,e);case"cpu-pinned":return new $t({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new $t({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new $t({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new $t({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),$t,Tf=ye(()=>{"use strict";TP(),MP(),SP(),OP(),$t=class{constructor(t,e,r){_E();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=ks.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=ks.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=ao.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=gE(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 pE(t,e)}static fromTexture(t,e){return fE(t,e)}static fromGpuBuffer(t,e){return dE(t,e)}static fromMLTensor(t,e){return mE(t,e)}static fromPinnedBuffer(t,e,r){return hE(t,e,r)}toDataURL(t){return cE(this,t)}toImageData(t){return uE(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 wE(this,t)}}}),tr,xE=ye(()=>{"use strict";Tf(),tr=$t}),Fl,ef,Ts,Ms,Br,Fr,yE=ye(()=>{"use strict";lE(),Fl=(t,e)=>{(typeof ut.trace>"u"?!ut.wasm.trace:!ut.trace)||console.timeStamp(`${t}::ORT::${e}`)},ef=(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}`),Fl("CPU",o);return}r[n].includes("TRACE_FUNC")&&(s=!0)}},Ts=t=>{(typeof ut.trace>"u"?!ut.wasm.trace:!ut.trace)||ef("BEGIN",t)},Ms=t=>{(typeof ut.trace>"u"?!ut.wasm.trace:!ut.trace)||ef("END",t)},Br=t=>{(typeof ut.trace>"u"?!ut.wasm.trace:!ut.trace)||console.time(`ORT::${t}`)},Fr=t=>{(typeof ut.trace>"u"?!ut.wasm.trace:!ut.trace)||console.timeEnd(`ORT::${t}`)}}),bE,IP=ye(()=>{"use strict";aE(),xE(),yE(),bE=class vE{constructor(e){this.handler=e}async run(e,r,s){Ts(),Br("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof tr||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 tr)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,p=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(p.indexOf(f)!==-1){let m=r[f];(m===null||m instanceof tr)&&(c=!0,a=!1,n[f]=m)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof e[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(let c of this.outputNames)n[c]=null;let i=await this.handler.run(e,n,o),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let p=i[c];p instanceof tr?l[c]=p:l[c]=new tr(p.type,p.data,p.dims)}return Fr("InferenceSession.run"),Ms(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){Ts(),Br("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 oE(a),c=await i.createInferenceSessionHandler(o,l);return Fr("InferenceSession.create"),Ms(),new vE(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Mf,CP=ye(()=>{"use strict";IP(),Mf=bE}),PP=ye(()=>{"use strict"}),LP=ye(()=>{"use strict"}),NP=ye(()=>{"use strict"}),zP=ye(()=>{"use strict"}),kE={};lo(kE,{InferenceSession:()=>Mf,TRACE:()=>Fl,TRACE_EVENT_BEGIN:()=>Br,TRACE_EVENT_END:()=>Fr,TRACE_FUNC_BEGIN:()=>Ts,TRACE_FUNC_END:()=>Ms,Tensor:()=>tr,env:()=>Ve,registerBackend:()=>As});var Ss=ye(()=>{"use strict";kP(),AP(),CP(),xE(),PP(),LP(),yE(),NP(),zP()}),Sf=ye(()=>{"use strict"}),EE={};lo(EE,{default:()=>AE});var tf,rf,AE,RP=ye(()=>{"use strict";BE(),Os(),Of(),tf="ort-wasm-proxy-worker",rf=globalThis.self?.name===tf,rf&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":If(r.wasm).then(()=>{zf(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;Rf(n,s).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})});break}case"copy-from":{let{buffer:s}=r,n=ql(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;$f(s,n).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":Df(r),postMessage({type:e});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:a,options:i}=r;Uf(s,n,o,a,new Array(a.length).fill(null),i).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:e,out:l},Ff([...o,...l]))},l=>{postMessage({type:e,err:l})});break}case"end-profiling":Bf(r),postMessage({type:e});break;default:}}catch(s){postMessage({type:e,err:s})}}),AE=rf?null:t=>new Worker(t??zt,{type:"module",name:tf})}),TE={};lo(TE,{default:()=>ME});async function Lk(t={}){var e=t,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");e.mountExternalData=(u,d)=>{u.startsWith("./")&&(u=u.substring(2)),(e.Uc||(e.Uc=new Map)).set(u,d)},e.unmountExternalData=()=>{delete e.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,Be:!0}).buffer.constructor;let o=()=>{let u=d=>(..._)=>{let g=ar;return _=d(..._),ar!=g?new Promise((v,T)=>{vp={resolve:v,reject:T}}):_};(()=>{for(let d of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])e[d]=u(e[d])})(),typeof jsepRunAsync<"u"&&(e._OrtRun=jsepRunAsync(e._OrtRun),e._OrtRunWithBinding=jsepRunAsync(e._OrtRunWithBinding)),o=void 0};e.asyncInit=()=>{o?.()};var a,i,l=(u,d)=>{throw d},c=import.meta.url,p="";if(r||s){try{p=new URL(".",c).href}catch{}s&&(i=u=>{var d=new XMLHttpRequest;return d.open("GET",u,!1),d.responseType="arraybuffer",d.send(null),new Uint8Array(d.response)}),a=async u=>{if(P(u))return new Promise((_,g)=>{var v=new XMLHttpRequest;v.open("GET",u,!0),v.responseType="arraybuffer",v.onload=()=>{v.status==200||v.status==0&&v.response?_(v.response):g(v.status)},v.onerror=g,v.send(null)});var d=await fetch(u,{credentials:"same-origin"});if(d.ok)return d.arrayBuffer();throw Error(d.status+" : "+d.url)}}var f,m,h,w,x,b,E=console.log.bind(console),A=console.error.bind(console),S=E,M=A,C=!1,P=u=>u.startsWith("file://");function k(){Lr.buffer!=V.buffer&&pe()}if(n){let u=function(d){try{var _=d.data,g=_.Oc;if(g==="load"){let v=[];self.onmessage=T=>v.push(T),b=()=>{postMessage({Oc:"loaded"});for(let T of v)u(T);self.onmessage=u};for(let T of _.de)e[T]&&!e[T].proxy||(e[T]=(...O)=>{postMessage({Oc:"callHandler",ce:T,args:O})},T=="print"&&(S=e[T]),T=="printErr"&&(M=e[T]));Lr=_.je,pe(),m=_.ke,Je(),vl()}else if(g==="run"){(function(v){var T=(k(),L)[v+52>>>2>>>0];v=(k(),L)[v+56>>>2>>>0],B1(T,T-v),ie(T)})(_.Nc),Np(_.Nc,0,0,1,0,0),Mb(),xp(_.Nc),H||(v1(),H=!0);try{Q2(_.he,_.Wc)}catch(v){if(v!="unwind")throw v}}else _.target!=="setimmediate"&&(g==="checkMailbox"?H&&ml():g&&(M(`worker: received unknown command ${g}`),M(_)))}catch(v){throw z1(),v}};var F=u,H=!1;self.onunhandledrejection=d=>{throw d.reason||d},self.onmessage=u}var V,J,X,Y,U,L,ne,ae,I,N,$,te=!1;function pe(){var u=Lr.buffer;e.HEAP8=V=new Int8Array(u),X=new Int16Array(u),e.HEAPU8=J=new Uint8Array(u),Y=new Uint16Array(u),e.HEAP32=U=new Int32Array(u),e.HEAPU32=L=new Uint32Array(u),ne=new Float32Array(u),ae=new Float64Array(u),I=new BigInt64Array(u),N=new BigUint64Array(u)}function Fe(){te=!0,n?b():kr._b()}function Pe(u){throw M(u="Aborted("+u+")"),C=!0,u=new WebAssembly.RuntimeError(u+". Build with -sASSERTIONS for more info."),x?.(u),u}function Mt(){return{a:{f:J2,J:Z2,k:eT,p:tT,l:rT,ta:sT,b:nT,ca:oT,Ka:Lb,s:aT,da:$b,_a:Db,Ga:Ub,Ia:Bb,$a:Fb,Ya:jb,Ra:Gb,Xa:qb,pa:Wb,Ha:Vb,Yb:Hb,Za:Xb,Fa:Kb,eb:iT,Da:cT,Tb:uT,Rb:fT,Ca:mT,M:hT,H:_T,Sb:gT,ka:ET,Ub:AT,Ua:TT,Wb:ST,La:OT,Pb:IT,la:CT,Ta:xp,bb:PT,U:RT,n:FT,c:gp,sb:jT,w:GT,L:qT,z:WT,j:VT,o:s1,tb:HT,G:XT,T:KT,g:YT,u:QT,m:JT,i:ZT,Oa:eM,Pa:tM,Qa:rM,Ma:i1,Na:l1,Qb:c1,fb:nM,db:iM,Y:lM,rb:cM,ma:uM,cb:oM,gb:pM,ab:fM,Xb:dM,N:sM,hb:mM,X:hM,Vb:_M,ob:AM,C:TM,sa:MM,ra:SM,qb:OM,W:IM,v:CM,nb:PM,mb:LM,lb:NM,pb:zM,kb:RM,jb:$M,ib:DM,Va:h1,Wa:_1,Ja:Ot,ea:g1,oa:w1,Sa:x1,na:y1,Db:XS,xa:BS,Eb:HS,ya:US,F:OS,e:_S,r:mS,x:dS,D:TS,Ib:RS,ba:NS,B:wS,za:$S,$:FS,ha:zS,Fb:WS,Gb:qS,Ba:IS,Aa:LS,Jb:CS,wa:VS,aa:DS,d:gS,A:xS,q:hS,Cb:KS,t:bS,y:MS,I:yS,E:vS,K:SS,S:jS,ja:AS,_:GS,Kb:ES,Lb:kS,P:PS,h:BM,a:Lr,Ob:Pr,Hb:FM,ia:jM,O:GM,qa:qM,Mb:WM,Q:VM,zb:HM,Ab:XM,ua:KM,fa:YM,R:QM,Ea:JM,va:ZM,Z:eS,xb:tS,Zb:rS,V:sS,Bb:nS,ub:oS,vb:iS,wb:lS,ga:cS,yb:uS,Nb:pS}}}async function Je(){function u(g,v){var T=kr=g.exports;g={};for(let[O,z]of Object.entries(T))typeof z=="function"?(T=LT(z),g[O]=T):g[O]=z;return kr=g,kr=(function(){var O=kr,z=K=>Me=>K(Me)>>>0,B=K=>()=>K()>>>0;return(O=Object.assign({},O)).$b=z(O.$b),O.Cc=B(O.Cc),O.Ec=z(O.Ec),O.rd=(K=>(Me,Le)=>K(Me,Le)>>>0)(O.rd),O.wd=z(O.wd),O.xd=B(O.xd),O.Bd=z(O.Bd),O})(),Ab.push(kr.id),b1=(g=kr).$b,v1=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,Sp=e._OrtGetWebGpuDevice=g.Bc,yl=g.Cc,Yt=e._free=g.Dc,Ks=e._malloc=g.Ec,k1=e._wgpuBufferRelease=g.Fc,E1=e._wgpuCreateInstance=g.Gc,A1=g.Hc,T1=g.Ic,M1=g.Jc,S1=g.Kc,O1=g.Lc,I1=g.Pc,C1=g.Zc,P1=g._c,L1=g.$c,Op=g.bd,Ip=g.cd,Cp=g.dd,Pp=g.ed,Wn=g.fd,Lp=g.gd,N1=g.hd,Np=g.kd,z1=g.ld,R1=g.md,$1=g.nd,zp=g.od,D1=g.pd,U1=g.qd,Rp=g.rd,_e=g.sd,Vn=g.td,B1=g.ud,ie=g.vd,bl=g.wd,le=g.xd,F1=g.yd,$p=g.zd,j1=g.Ad,G1=g.Bd,q1=g.Cd,Dp=g.Dd,W1=g.Ed,V1=g.Fd,H1=g.Gd,X1=g.Hd,K1=g.Id,Y1=g.Jd,Q1=g.Kd,J1=g.Ld,Z1=g.Md,ev=g.Nd,tv=g.Od,rv=g.Pd,sv=g.Qd,nv=g.Rd,ov=g.Td,av=g.Ud,iv=g.Vd,lv=g.Wd,cv=g.Yd,uv=g.Zd,pv=g._d,fv=g.$d,dv=g.ae,mv=g.be,hv=g.pe,_v=g.qe,gv=g.re,wv=g.se,xv=g.te,yv=g.ue,bv=g.ve,vv=g.we,kv=g.xe,Ev=g.ye,Av=g.ze,Tv=g.Xe,Mv=g.Ye,Sv=g.Ze,Ov=g._e,m=v,kr}var d,_=Mt();return e.instantiateWasm?new Promise(g=>{e.instantiateWasm(_,(v,T)=>{g(u(v,T))})}):n?u(new WebAssembly.Instance(m,Mt()),m):($??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.asyncify.wasm",p):p+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href,d=await(async function(g){var v=$;if(!f&&!P(v))try{var T=fetch(v,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(T,g)}catch(O){M(`wasm streaming compile failed: ${O}`),M("falling back to ArrayBuffer instantiation")}return(async function(O,z){try{var B=await(async function(K){if(!f)try{var Me=await a(K);return new Uint8Array(Me)}catch{}if(K==$&&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,z)}catch(K){M(`failed to asynchronously prepare wasm: ${K}`),Pe(K)}})(v,g)})(_),u(d.instance,d.module))}class et{name="ExitStatus";constructor(d){this.message=`Program terminated with exit(${d})`,this.status=d}}var st=u=>{u.terminate(),u.onmessage=()=>{}},Te=[],xe=0,qe=null,St=u=>{tt.length==0&&(Ob(),Sb(tt[0]));var d=tt.pop();if(!d)return 6;jn.push(d),us[u.Nc]=d,d.Nc=u.Nc;var _={Oc:"run",he:u.ge,Wc:u.Wc,Nc:u.Nc};return d.postMessage(_,u.Yc),0},be=0,Re=(u,d,..._)=>{var g,v=16*_.length,T=le(),O=bl(v),z=O>>>3;for(g of _)typeof g=="bigint"?((k(),I)[z++>>>0]=1n,(k(),I)[z++>>>0]=g):((k(),I)[z++>>>0]=0n,(k(),ae)[z++>>>0]=g);return u=R1(u,0,v,O,d),ie(T),u};function Pr(u){if(n)return Re(0,1,u);if(h=u,!(0<be)){for(var d of jn)st(d);for(d of tt)st(d);tt=[],jn=[],us={},C=!0}l(0,new et(u))}function cs(u){if(n)return Re(1,0,u);Ot(u)}var Ot=u=>{if(h=u,n)throw cs(u),"unwind";Pr(u)},tt=[],jn=[],Ab=[],us={},Tb=u=>{var d=u.Nc;delete us[d],tt.push(u),jn.splice(jn.indexOf(u),1),u.Nc=0,$1(d)};function Mb(){Ab.forEach(u=>u())}var Sb=u=>new Promise(d=>{u.onmessage=v=>{var T=v.data;if(v=T.Oc,T.Vc&&T.Vc!=yl()){var O=us[T.Vc];O?O.postMessage(T,T.Yc):M(`Internal error! Worker sent a message "${v}" to target pthread ${T.Vc}, but that thread no longer exists!`)}else v==="checkMailbox"?ml():v==="spawnThread"?St(T):v==="cleanupThread"?vt(()=>{Tb(us[T.ie])}):v==="loaded"?(u.loaded=!0,d(u)):T.target==="setimmediate"?u.postMessage(T):v==="uncaughtException"?u.onerror(T.error):v==="callHandler"?e[T.ce](...T.args):v&&M(`worker sent an unknown command ${v}`)},u.onerror=v=>{throw M(`worker sent an error! ${v.filename}:${v.lineno}: ${v.message}`),v};var _,g=[];for(_ of[])e.propertyIsEnumerable(_)&&g.push(_);u.postMessage({Oc:"load",de:g,je:Lr,ke:m})});function Ob(){var u=new Worker((()=>{let d=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new d("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});tt.push(u)}var Lr,Q2=(u,d)=>{be=0,u=Dp(u,d),0<be?h=u:zp(u)},fl=[],dl=0,bt=u=>-9007199254740992>u||9007199254740992<u?NaN:Number(u);function J2(u){var d=new dp(u>>>=0);return(k(),V)[d.Qc+12>>>0]==0&&(Ib(d,!0),dl--),Cb(d,!1),fl.push(d),G1(u)}var Ws=0,Z2=()=>{_e(0,0);var u=fl.pop();F1(u.Xc),Ws=0};function Ib(u,d){d=d?1:0,(k(),V)[u.Qc+12>>>0]=d}function Cb(u,d){d=d?1:0,(k(),V)[u.Qc+13>>>0]=d}class dp{constructor(d){this.Xc=d,this.Qc=d-24}}var mp=u=>{var d=Ws;if(!d)return Vn(0),0;var _=new dp(d);(k(),L)[_.Qc+16>>>2>>>0]=d;var g=(k(),L)[_.Qc+4>>>2>>>0];if(!g)return Vn(0),d;for(var v of u){if(v===0||v===g)break;if(j1(v,g,_.Qc+16))return Vn(v),d}return Vn(g),d};function eT(){return mp([])}function tT(u){return mp([u>>>0])}function rT(u,d,_,g){return mp([u>>>0,d>>>0,_>>>0,g>>>0])}var sT=()=>{var u=fl.pop();u||Pe("no exception to throw");var d=u.Xc;throw(k(),V)[u.Qc+13>>>0]==0&&(fl.push(u),Cb(u,!0),Ib(u,!1),dl++),$p(d),Ws=d};function nT(u,d,_){var g=new dp(u>>>=0);throw d>>>=0,_>>>=0,(k(),L)[g.Qc+16>>>2>>>0]=0,(k(),L)[g.Qc+4>>>2>>>0]=d,(k(),L)[g.Qc+8>>>2>>>0]=_,$p(u),dl++,Ws=u}var oT=()=>dl;function Pb(u,d,_,g){return n?Re(2,1,u,d,_,g):Lb(u,d,_,g)}function Lb(u,d,_,g){if(u>>>=0,d>>>=0,_>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var v=[];return n&&v.length===0?Pb(u,d,_,g):(u={ge:_,Nc:u,Wc:g,Yc:v},n?(u.Oc="spawnThread",postMessage(u,v),0):St(u))}function aT(u){throw Ws||=u>>>0,Ws}var Nb=globalThis.TextDecoder&&new TextDecoder,zb=(u,d,_,g)=>{if(_=d+_,g)return _;for(;u[d]&&!(d>=_);)++d;return d},Rb=(u,d=0,_,g)=>{if(16<(_=zb(u,d>>>=0,_,g))-d&&u.buffer&&Nb)return Nb.decode(u.buffer instanceof ArrayBuffer?u.subarray(d,_):u.slice(d,_));for(g="";d<_;){var v=u[d++];if(128&v){var T=63&u[d++];if((224&v)==192)g+=String.fromCharCode((31&v)<<6|T);else{var O=63&u[d++];65536>(v=(240&v)==224?(15&v)<<12|T<<6|O:(7&v)<<18|T<<12|O<<6|63&u[d++])?g+=String.fromCharCode(v):(v-=65536,g+=String.fromCharCode(55296|v>>10,56320|1023&v))}}else g+=String.fromCharCode(v)}return g},Vs=(u,d,_)=>(u>>>=0)?Rb((k(),J),u,d,_):"";function $b(u,d,_){return n?Re(3,1,u,d,_):0}function Db(u,d){if(n)return Re(4,1,u,d)}function Ub(u,d){if(n)return Re(5,1,u,d)}function Bb(u,d,_){if(n)return Re(6,1,u,d,_)}function Fb(u,d,_){return n?Re(7,1,u,d,_):0}function jb(u,d){if(n)return Re(8,1,u,d)}function Gb(u,d,_){if(n)return Re(9,1,u,d,_)}function qb(u,d,_,g){if(n)return Re(10,1,u,d,_,g)}function Wb(u,d,_,g){if(n)return Re(11,1,u,d,_,g)}function Vb(u,d,_,g){if(n)return Re(12,1,u,d,_,g)}function Hb(u){if(n)return Re(13,1,u)}function Xb(u,d){if(n)return Re(14,1,u,d)}function Kb(u,d,_){if(n)return Re(15,1,u,d,_)}var iT=()=>Pe(""),or=u=>{u>>>=0;for(var d="";;){var _=(k(),J)[u++>>>0];if(!_)return d;d+=String.fromCharCode(_)}},hp={},_p={},lT={},Hs=class extends Error{constructor(u){super(u),this.name="BindingError"}};function wr(u,d,_={}){return(function(g,v,T={}){var O=v.name;if(!g)throw new Hs(`type "${O}" must have a positive integer typeid pointer`);if(_p.hasOwnProperty(g)){if(T.ee)return;throw new Hs(`Cannot register type '${O}' twice`)}_p[g]=v,delete lT[g],hp.hasOwnProperty(g)&&(v=hp[g],delete hp[g],v.forEach(z=>z()))})(u,d,_)}var Yb=(u,d,_)=>{switch(d){case 1:return _?g=>(k(),V)[g>>>0]:g=>(k(),J)[g>>>0];case 2:return _?g=>(k(),X)[g>>>1>>>0]:g=>(k(),Y)[g>>>1>>>0];case 4:return _?g=>(k(),U)[g>>>2>>>0]:g=>(k(),L)[g>>>2>>>0];case 8:return _?g=>(k(),I)[g>>>3>>>0]:g=>(k(),N)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${d}): ${u}`)}};function cT(u,d,_,g,v){u>>>=0,_>>>=0,d=or(d>>>0);let T=O=>O;if(g=g===0n){let O=8*_;T=z=>BigInt.asUintN(O,z),v=T(v)}wr(u,{name:d,Mc:T,Sc:(O,z)=>(typeof z=="number"&&(z=BigInt(z)),z),Rc:Yb(d,_,!g),Tc:null})}function uT(u,d,_,g){wr(u>>>=0,{name:d=or(d>>>0),Mc:function(v){return!!v},Sc:function(v,T){return T?_:g},Rc:function(v){return this.Mc((k(),J)[v>>>0])},Tc:null})}var Qb=[],ps=[0,1,,1,null,1,!0,1,!1,1];function gp(u){9<(u>>>=0)&&--ps[u+1]==0&&(ps[u]=void 0,Qb.push(u))}var Ut=u=>{if(!u)throw new Hs(`Cannot use deleted val. handle = ${u}`);return ps[u]},Kt=u=>{switch(u){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let d=Qb.pop()||ps.length;return ps[d]=u,ps[d+1]=1,d}};function wp(u){return this.Mc((k(),L)[u>>>2>>>0])}var pT={name:"emscripten::val",Mc:u=>{var d=Ut(u);return gp(u),d},Sc:(u,d)=>Kt(d),Rc:wp,Tc:null};function fT(u){return wr(u>>>0,pT)}var dT=(u,d)=>{switch(d){case 4:return function(_){return this.Mc((k(),ne)[_>>>2>>>0])};case 8:return function(_){return this.Mc((k(),ae)[_>>>3>>>0])};default:throw new TypeError(`invalid float width (${d}): ${u}`)}};function mT(u,d,_){_>>>=0,wr(u>>>=0,{name:d=or(d>>>0),Mc:g=>g,Sc:(g,v)=>v,Rc:dT(d,_),Tc:null})}function hT(u,d,_,g,v){u>>>=0,_>>>=0,d=or(d>>>0);let T=z=>z;if(g===0){var O=32-8*_;T=z=>z<<O>>>O,v=T(v)}wr(u,{name:d,Mc:T,Sc:(z,B)=>B,Rc:Yb(d,_,g!==0),Tc:null})}function _T(u,d,_){function g(T){var O=(k(),L)[T>>>2>>>0];return T=(k(),L)[T+4>>>2>>>0],new v((k(),V).buffer,T,O)}var v=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][d];wr(u>>>=0,{name:_=or(_>>>0),Mc:g,Rc:g},{ee:!0})}var xr=(u,d,_)=>{var g=(k(),J);if(d>>>=0,0<_){var v=d;_=d+_-1;for(var T=0;T<u.length;++T){var O=u.codePointAt(T);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,T++}}g[d>>>0]=0,u=d-v}else u=0;return u},yr=u=>{for(var d=0,_=0;_<u.length;++_){var g=u.charCodeAt(_);127>=g?d++:2047>=g?d+=2:55296<=g&&57343>=g?(d+=4,++_):d+=3}return d};function gT(u,d){wr(u>>>=0,{name:d=or(d>>>0),Mc(_){var g=(k(),L)[_>>>2>>>0];return g=Vs(_+4,g,!0),Yt(_),g},Sc(_,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var v=typeof g=="string";if(!(v||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new Hs("Cannot pass non-string to std::string");var T=v?yr(g):g.length,O=Ks(4+T+1),z=O+4;return(k(),L)[O>>>2>>>0]=T,v?xr(g,z,T+1):(k(),J).set(g,z>>>0),_!==null&&_.push(Yt,O),O},Rc:wp,Tc(_){Yt(_)}})}var Jb=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,wT=(u,d,_)=>{if(u>>>=1,16<(d=zb((k(),Y),u,d/2,_))-u&&Jb)return Jb.decode((k(),Y).slice(u,d));for(_="";u<d;++u){var g=(k(),Y)[u>>>0];_+=String.fromCharCode(g)}return _},xT=(u,d,_)=>{if(_??=2147483647,2>_)return 0;var g=d;_=(_-=2)<2*u.length?_/2:u.length;for(var v=0;v<_;++v){var T=u.charCodeAt(v);(k(),X)[d>>>1>>>0]=T,d+=2}return(k(),X)[d>>>1>>>0]=0,d-g},yT=u=>2*u.length,bT=(u,d,_)=>{var g="";u>>>=2;for(var v=0;!(v>=d/4);v++){var T=(k(),L)[u+v>>>0];if(!T&&!_)break;g+=String.fromCodePoint(T)}return g},vT=(u,d,_)=>{if(d>>>=0,_??=2147483647,4>_)return 0;var g=d;_=g+_-4;for(var v=0;v<u.length;++v){var T=u.codePointAt(v);if(65535<T&&v++,(k(),U)[d>>>2>>>0]=T,(d+=4)+4>_)break}return(k(),U)[d>>>2>>>0]=0,d-g},kT=u=>{for(var d=0,_=0;_<u.length;++_)65535<u.codePointAt(_)&&_++,d+=4;return d};function ET(u,d,_){if(u>>>=0,d>>>=0,_=or(_>>>=0),d===2)var g=wT,v=xT,T=yT;else g=bT,v=vT,T=kT;wr(u,{name:_,Mc:O=>{var z=(k(),L)[O>>>2>>>0];return z=g(O+4,z*d,!0),Yt(O),z},Sc:(O,z)=>{if(typeof z!="string")throw new Hs(`Cannot pass non-string to C++ string type ${_}`);var B=T(z),K=Ks(4+B+d);return(k(),L)[K>>>2>>>0]=B/d,v(z,K+4,B+d),O!==null&&O.push(Yt,K),K},Rc:wp,Tc(O){Yt(O)}})}function AT(u,d){wr(u>>>=0,{fe:!0,name:d=or(d>>>0),Mc:()=>{},Sc:()=>{}})}function TT(u){Np(u>>>0,!s,1,!r,131072,!1),Mb()}var vt=u=>{if(!C)try{if(u(),!(0<be))try{n?yl()&&zp(h):Ot(h)}catch(d){d instanceof et||d=="unwind"||l(0,d)}}catch(d){d instanceof et||d=="unwind"||l(0,d)}},MT=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function xp(u){u>>>=0,MT||(Atomics.waitAsync((k(),U),u>>>2,u).value.then(ml),u+=128,Atomics.store((k(),U),u>>>2,1))}var ml=()=>vt(()=>{var u=yl();u&&(xp(u),U1())});function ST(u,d){(u>>>=0)==d>>>0?setTimeout(ml):n?postMessage({Vc:u,Oc:"checkMailbox"}):(u=us[u])&&u.postMessage({Oc:"checkMailbox"})}var yp=[];function OT(u,d,_,g,v){for(d>>>=0,v>>>=0,yp.length=0,_=v>>>3,g=v+g>>>3;_<g;){var T;T=(k(),I)[_++>>>0]?(k(),I)[_++>>>0]:(k(),ae)[_++>>>0],yp.push(T)}return(d?Up[d]:fS[u])(...yp)}var IT=()=>{be=0};function CT(u){u>>>=0,n?postMessage({Oc:"cleanupThread",ie:u}):Tb(us[u])}function PT(u){}var hl=u=>{try{u()}catch(d){Pe(d)}};function LT(u){var d=(..._)=>{_l.push(u);try{return u(..._)}finally{C||(_l.pop(),ar&&Nr===1&&_l.length===0&&(Nr=0,be+=1,hl(Mv),typeof Fibers<"u"&&Fibers.De()))}};return t1.set(u,d),d}var Nr=0,ar=null,Zb=0,_l=[],bp=new Map,e1=new Map,t1=new Map,NT=0,vp=null,zT=[],r1=u=>(function(d){if(!C){if(Nr===0){var _=!1,g=!1;d((v=0)=>{if(!C&&(Zb=v,_=!0,g)){Nr=2,hl(()=>Sv(ar)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),v=!1;try{var T=(function(){var B=(k(),U)[ar+8>>>2>>>0];return B=e1.get(B),B=t1.get(B),--be,B()})()}catch(B){T=B,v=!0}var O=!1;if(!ar){var z=vp;z&&(vp=null,(v?z.reject:z.resolve)(T),O=!0)}if(v&&!O)throw T}}),g=!0,_||(Nr=1,ar=(function(){var v=Ks(65548),T=v+12;if((k(),L)[v>>>2>>>0]=T,(k(),L)[v+4>>>2>>>0]=T+65536,T=_l[0],!bp.has(T)){var O=NT++;bp.set(T,O),e1.set(O,T)}return T=bp.get(T),(k(),U)[v+8>>>2>>>0]=T,v})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),hl(()=>Tv(ar)))}else Nr===2?(Nr=0,hl(Ov),Yt(ar),ar=null,zT.forEach(vt)):Pe(`invalid state: ${Nr}`);return Zb}})(d=>{u().then(d)});function RT(u){return u>>>=0,r1(async()=>{var d=await Ut(u);return Kt(d)})}var kp=[],$T=u=>{var d=kp.length;return kp.push(u),d},DT=(u,d)=>{for(var _=Array(u),g=0;g<u;++g){var v=g,T=(k(),L)[d+4*g>>>2>>>0],O=_p[T];if(O===void 0)throw u=`parameter ${g}`,T=b1(T),d=or(T),Yt(T),new Hs(`${u} has unknown type ${d}`);_[v]=O}return _},UT=(u,d,_)=>{var g=[];return u=u(g,_),g.length&&((k(),L)[d>>>2>>>0]=Kt(g)),u},BT={},gl=u=>{var d=BT[u];return d===void 0?or(u):d};function FT(u,d,_){var[g,...v]=DT(u,d>>>0);d=g.Sc.bind(g);var T=v.map(B=>B.Rc.bind(B));u--;var O={toValue:Ut};switch(u=T.map((B,K)=>{var Me=`argFromPtr${K}`;return O[Me]=B,`${Me}(args${K?"+"+8*K:""})`}),_){case 0:var z="toValue(handle)";break;case 2:z="new (toValue(handle))";break;case 3:z="";break;case 1:O.getStringOrSymbol=gl,z="toValue(handle)[getStringOrSymbol(methodName)]"}return z+=`(${u})`,g.fe||(O.toReturnWire=d,O.emval_returnValue=UT,z=`return emval_returnValue(toReturnWire, destructorsRef, ${z})`),z=`return function (handle, methodName, destructorsRef, args) {
9
+ `))}case"replace":{let o=t.builtins.get("replace");if(!(o instanceof qe))throw new Error("replace filter not available");let[a,i]=this.evaluateArguments(s.args,r);return o.value([...a,new co(i)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(t instanceof ft){let o=t.builtins.get(n);if(o&&o instanceof qe){let[a,i]=this.evaluateArguments(s.args,r);return i.size>0&&a.push(new co(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 pe(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 pe(!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 co(s));let n=this.evaluate(t.callee,e);if(n.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${n.type}`);return n.value(r,e)}evaluateSliceExpression(t,e,r){if(!(t instanceof ye||t instanceof 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 he||s instanceof je))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof he||n instanceof je))throw new Error("Slice stop must be numeric or undefined");if(!(o instanceof he||o instanceof je))throw new Error("Slice step must be numeric or undefined");return t instanceof ye?new ye(Hk(t.value,s.value,n.value,o.value)):new ee(Hk(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 ft){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 ye||r instanceof ee)if(s instanceof he)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 cr?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 ye))throw new Error(`Cannot unpack non-iterable type in set: ${r.type}`);let n=r.value;if(n.length!==s.value.length)throw new Error(`Too ${s.value.length>n.length?"few":"many"} items to unpack in set`);for(let o=0;o<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 ft))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 Ve}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 _s(e),s,n;if(t.iterable.type==="SelectExpression"){let c=t.iterable;n=this.evaluate(c.lhs,r),s=c.test}else n=this.evaluate(t.iterable,r);if(!(n instanceof ye||n instanceof ft))throw new Error(`Expected iterable or object type in for loop: got ${n.type}`);n instanceof ft&&(n=n.keys());let o=[],a=[];for(let c=0;c<n.value.length;++c){let p=new _s(r),f=n.value[c],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 v=0;v<h.value.length;++v){if(h.value[v].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${h.value[v].type}`);x.setVariable(h.value[v].value,w.value[v])}}}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 c=0;c<o.length;++c){let p=new Map([["index",new he(c+1)],["index0",new he(c)],["revindex",new he(o.length-c)],["revindex0",new he(o.length-c-1)],["first",new pe(c===0)],["last",new pe(c===o.length-1)],["length",new he(o.length)],["previtem",c>0?o[c-1]:new je],["nextitem",c<o.length-1?o[c+1]:new je]]);r.setVariable("loop",new ft(p)),a[c](r);try{let f=this.evaluateBlock(t.body,r);i+=f.value}catch(f){if(f instanceof Kk)continue;if(f instanceof Xk)break;throw f}l=!1}if(l){let c=this.evaluateBlock(t.defaultBlock,r);i+=c.value}return new ee(i)}evaluateMacro(t,e){return e.setVariable(t.name.value,new qe((r,s)=>{let n=new _s(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 c=i;if(!l)throw new Error(`Missing positional argument: ${c.value}`);n.setVariable(c.value,l)}else if(i.type==="KeywordArgumentExpression"){let c=i,p=l??o?.value.get(c.key.value)??this.evaluate(c.value,n);n.setVariable(c.key.value,p)}else throw new Error(`Unknown argument type: ${i.type}`)}return this.evaluateBlock(t.body,n)})),new Ve}evaluateCallStatement(t,e){let r=new qe((i,l)=>{let c=new _s(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}`);c.setVariable(f.value,i[p]??new je)}return this.evaluateBlock(t.body,c)}),[s,n]=this.evaluateArguments(t.call.args,e);s.push(new co(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 _s(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 Xk;case"Continue":throw new Kk;case"IntegerLiteral":return new he(t.value);case"FloatLiteral":return new Ze(t.value);case"StringLiteral":return new ee(t.value);case"ArrayLiteral":return new ye(t.value.map(r=>this.evaluate(r,e)));case"TupleLiteral":return new Qk(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 ft(r)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"FilterStatement":return this.evaluateFilterStatement(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);case"SelectExpression":return this.evaluateSelectExpression(t,e);case"Ternary":return this.evaluateTernaryExpression(t,e);case"Comment":return new Ve;default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function Hl(t){switch(typeof t){case"number":return Number.isInteger(t)?new he(t):new Ze(t);case"string":return new ee(t);case"boolean":return new pe(t);case"undefined":return new je;case"object":return t===null?new Ve:Array.isArray(t)?new ye(t.map(Hl)):new ft(new Map(Object.entries(t).map(([e,r])=>[e,Hl(r)])));case"function":return new qe((e,r)=>{let s=t(...e.map(n=>n.value))??null;return Hl(s)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}var it=`
10
+ `,YP="{%- ",QP=" -%}";function JP(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 ZP(t,e=" "){let r=typeof e=="number"?" ".repeat(e):e;return Zt(t.body,0,r).replace(/\n$/,"")}function yt(...t){return YP+t.join(" ")+QP}function Zt(t,e,r){return t.map(s=>eL(s,e,r)).join(it)}function eL(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return Zt(t.body,e,r);case"If":return tL(t,e,r);case"For":return rL(t,e,r);case"Set":return sL(t,e,r);case"Macro":return nL(t,e,r);case"Break":return s+yt("break");case"Continue":return s+yt("continue");case"CallStatement":return oL(t,e,r);case"FilterStatement":return aL(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+ke(t)+" -}}"}}function tL(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+yt("if",ke(n[0].test))+it+Zt(n[0].body,e+1,r);for(let i=1;i<n.length;++i)a+=it+s+yt("elif",ke(n[i].test))+it+Zt(n[i].body,e+1,r);return o&&o.alternate.length>0&&(a+=it+s+yt("else")+it+Zt(o.alternate,e+1,r)),a+=it+s+yt("endif"),a}function rL(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+yt("for",ke(t.loopvar),"in",n)+it+Zt(t.body,e+1,r);return t.defaultBlock.length>0&&(o+=it+s+yt("else")+it+Zt(t.defaultBlock,e+1,r)),o+=it+s+yt("endfor"),o}function sL(t,e,r){let s=r.repeat(e),n=ke(t.assignee),o=t.value?ke(t.value):"",a=s+yt("set",`${n}${t.value?" = "+o:""}`);return t.body.length===0?a:a+it+Zt(t.body,e+1,r)+it+s+yt("endset")}function nL(t,e,r){let s=r.repeat(e),n=t.args.map(ke).join(", ");return s+yt("macro",`${t.name.value}(${n})`)+it+Zt(t.body,e+1,r)+it+s+yt("endmacro")}function oL(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+yt(`call${n}`,o)+it;return a+=Zt(t.body,e+1,r)+it,a+=s+yt("endcall"),a}function aL(t,e,r){let s=r.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:ke(t.filter),o=s+yt("filter",n)+it;return o+=Zt(t.body,e+1,r)+it,o+=s+yt("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=JP(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 Zk=class{parsed;constructor(t){let e=_P(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=UP(e)}render(t){let e=new _s;if(XP(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new KP(e).run(this.parsed).value}format(t){return ZP(this.parsed,t?.indent||" ")}};var rt=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")}};var iL={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"},Lr=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=wt.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=wt.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let s=wt.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",iL[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 wt.promises.readFile(this.filePath)).buffer}async blob(){let e=await wt.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await wt.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}};var an=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(ie.IS_CRYPTO_AVAILABLE){let i=new Uint32Array(1);crypto.getRandomValues(i),e=i[0]}else e=Date.now()>>>0;let r=this._mt,s=(i,l)=>Math.imul(i,l)>>>0,n=[];for(let i=e||0;i>0;i=Math.floor(i/4294967296))n.push(i&4294967295);n.length||n.push(0),r[0]=19650218;for(let i=1;i<624;++i)r[i]=s(1812433253,r[i-1]^r[i-1]>>>30)+i>>>0;let o=1,a=0;for(let i=Math.max(624,n.length);i>0;--i,++o,++a)o>=624&&(r[0]=r[623],o=1),a>=n.length&&(a=0),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1664525))+n[a]+a>>>0;for(let i=623;i>0;--i,++o)o>=624&&(r[0]=r[623],o=1),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1566083941))-o>>>0;r[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let s=0;s<624;++s){let n=e[s]&2147483648|e[(s+1)%624]&2147483647;e[s]=(e[(s+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let r=e[this._idx++];return r^=r>>>11,r^=r<<7&2636928640,r^=r<<15&4022730752,r^=r>>>18,r>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,r=1){let s=this._gauss_next;if(this._gauss_next=null,s===null){let n=this.random()*2*Math.PI,o=Math.sqrt(-2*Math.log(1-this.random()));s=Math.cos(n)*o,this._gauss_next=Math.sin(n)*o}return e+s*r}shuffle(e){for(let r=e.length-1;r>0;--r){let s=32-Math.clz32(r+1),n=this._int32()>>>32-s;for(;n>r;)n=this._int32()>>>32-s;let o=e[r];e[r]=e[n],e[n]=o}}choices(e,r){return e[eE(this._random_fn,r)]}};function eE(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 an,ws=Object.freeze({Random:an,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)}),tE=t=>eE(ws.random,t);var lL=new an,ln=class{constructor(e){this.path=e}async match(e){let r=Ut.join(this.path,e),s=new Lr(r);if(s.exists)return s}async put(e,r,s=void 0){let n=Ut.join(this.path,e),o=ie.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=lL._int32().toString(36),i=n+`.tmp.${o}.${a}`;try{let l=r.headers.get("Content-Length"),c=parseInt(l??"0"),p=0;await wt.promises.mkdir(Ut.dirname(n),{recursive:!0});let f=wt.createWriteStream(i),m=r.body.getReader();for(;;){let{done:h,value:w}=await m.read();if(h)break;await new Promise((v,E)=>{f.write(w,A=>{if(A){E(A);return}v()})}),p+=w.length;let x=c?p/c*100:0;s?.({progress:x,loaded:p,total:c})}await new Promise((h,w)=>{f.close(x=>x?w(x):h())}),await wt.promises.rename(i,n)}catch(l){try{await wt.promises.unlink(i)}catch{}throw l}}async delete(e){let r=Ut.join(this.path,e);try{return await wt.promises.unlink(r),!0}catch{return!1}}};var rE={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"},Xl=100,sE=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function uo(...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 Nr(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 nE(t){return!(!sE.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function oE(t,e,r){if(!r)return null;let s=rE[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${s}: "${e}".`)}async function aE(t,e,r){let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):r??0;s===null&&!r&&Z.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let o=new Uint8Array(n),a=0,i=t.body.getReader();async function l(){let{done:c,value:p}=await i.read();if(c)return;let f=a+p.length;if(f>n){n=f;let 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}function df(t){return Nr(t,["blob:"])}function mf(t){let e;if(typeof location<"u"&&location.href)e=location.href;else if(typeof import.meta<"u"&&import.meta.url)e=import.meta.url;else return t;return new URL(t,e).href}var lE="SHA-256",cL="experimental_transformers-hash-cache",iE=t=>({algorithm:lE,value:t}),po=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(cL),this.#t);static isAvailable=()=>typeof navigator<"u"&&"crossOriginStorage"in navigator;match=async e=>{let r=await this._getFileHash(e);if(r)try{let[s]=await navigator.crossOriginStorage.requestFileHandles([iE(r)]),n=await s.getFile();return new Response(n,{headers:{"Content-Length":String(n.size)}})}catch{return}};put=async(e,r)=>{let s=await this._getFileHash(e);if(s){let n=await r.blob();await this._storeBlobInCOS(n,s)}else this._processAndStore(e,r.body)};_storeBlobInCOS=async(e,r)=>{let[s]=await navigator.crossOriginStorage.requestFileHandles([iE(r)],{create:!0}),n=await s.createWritable();await n.write(e),await n.close()};_processAndStore=async(e,r)=>{try{let s=[];for await(let a of r)s.push(a);let n=new Blob(s),o=await this._getBlobHash(n);await this._storeBlobInCOS(n,o);try{await(await this._getHashCache()).put(e,new Response(o))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let r=await this._getHashCache(),s=await r.match(e);if(s)return s.text();let n=await this._getLfsFileHash(e);return n?(await r.put(e,new Response(n)),n):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes("/resolve/"))return null;let r=e.replace("/resolve/","/raw/");try{let n=(await fetch(r).then(o=>o.text())).match(/^oid sha256:([0-9a-f]+)$/m);return n?n[1]:null}catch{return null}};_getBlobHash=async e=>{let r=await e.arrayBuffer(),s=await crypto.subtle.digest(lE,r);return Array.from(new Uint8Array(s)).map(o=>o.toString(16).padStart(2,"0")).join("")}};async function tr(t=null){let e=null;if(me.useCustomCache){if(!me.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!me.customCache.match||!me.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");e=me.customCache}if(!e&&me.experimental_useCrossOriginStorage&&po.isAvailable()&&(e=new po),!e&&me.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{e=await caches.open(me.cacheKey)}catch(r){Z.warn("An error occurred while opening the browser cache:",r)}}if(!e&&me.useFSCache){if(!ie.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");e=new ln(t??me.cacheDir)}return e}async function cE(t,...e){for(let r of e)try{let s=await t.match(r);if(s)return s}catch{continue}}var Kl=class{#t;#e;constructor(e){this.#t=e,this.#e=new Map}get(e){if(!this.#e.has(e))return;let r=this.#e.get(e);return this.#e.delete(e),this.#e.set(e,r),r}put(e,r){this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,r),this.#e.size>this.#t&&this.#e.delete(this.#e.keys().next().value)}delete(e){return this.#e.delete(e)}clear(){this.#e.clear()}};var uL=100,hf=new Kl(uL);function Yl(t,e){let r=hf.get(t);if(r!==void 0)return r;let s=e().then(n=>n,n=>(hf.delete(t),Promise.reject(n)));return hf.put(t,s),s}async function pL(t){if(!Nr(t,["http:","https:"]))return null;let e=_f(t);return e.set("Range","bytes=0-0"),me.fetch(t,{method:"GET",headers:e,cache:"no-store"})}function pr(t,e,r={}){let s=JSON.stringify([t,e,r?.revision,r?.cache_dir,r?.local_files_only]);return Yl(s,()=>fL(t,e,r))}async function fL(t,e,r){let s=await tr(r?.cache_dir),{localPath:n,remoteURL:o,proposedCacheKey:a,validModelId:i}=Rr(t,e,r,s),l=await $r(s,n,a);if(l!==void 0&&typeof l!="string"){let c=l.headers.get("content-length"),p=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:p||void 0,fromCache:!0}}if(me.allowLocalModels&&!Nr(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(me.allowRemoteModels&&!r.local_files_only&&i)try{let c=await pL(o);if(c&&c.status>=200&&c.status<300){let p,f=c.headers.get("content-type");if(c.status===206){let m=c.headers.get("content-range");if(m){let h=m.match(/bytes \d+-\d+\/(\d+)/);h&&(p=parseInt(h[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(p===void 0){let m=c.headers.get("content-length");p=m?parseInt(m,10):void 0}return{exists:!0,size:p,contentType:f||void 0,fromCache:!1}}}catch(c){Z.warn(`Unable to fetch file metadata for "${o}": ${c}`)}return{exists:!1,fromCache:!1}}async function zr(t){return me.useFS&&!Nr(t,["http:","https:","blob:"])?new Lr(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t):me.fetch(t,{headers:_f(t)})}function _f(t){let e=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(e){let s=!!process.env?.TESTING_REMOTELY,n=me.version;if(r.set("User-Agent",`transformers.js/${n}; is_ci/${s};`),Nr(t,["http:","https:"],["huggingface.co","hf.co"])){let a=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;a&&r.set("Authorization",`Bearer ${a}`)}}return r}function Rr(t,e,r={},s=null){let n=r.revision??"main",o=uo(t,e),a=nE(t),i=a?uo(me.localModelPath,o):o,l=uo(me.remoteHost,me.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),c=s instanceof ln?n==="main"?o:uo(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:a}}async function $r(t,e,r){if(t)return await cE(t,e,r)}async function dL(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=>{Z.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 mL(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:p}=Rr(t,e,s,o),f,m=!1,h;h=await $r(o,i,c);let w=h!==void 0;if(!w){if(me.allowLocalModels)if(Nr(a,["http:","https:"])){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${a}.`);if(!me.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${a}.`)}else try{h=await zr(i),f=i}catch(A){Z.warn(`Unable to load from local path "${i}": "${A}"`)}if(h===void 0||typeof h!="string"&&h.status===404){if(s.local_files_only||!me.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!p)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${t}".`);if(h=await zr(l),h.status!==200)return oE(h.status,l,r);f=c}m=o&&typeof Response<"u"&&h instanceof Response&&h.status===200}vr(s.progress_callback,{status:"download",name:t,file:e});let x;if(!(ie.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 M=await pr(t,e,s);M.size&&(A=M.size)}catch{}E=await aE(h,M=>{vr(s.progress_callback,{status:"progress",name:t,file:e,...M})},A)}x=E}if(m&&f&&typeof h!="string"&&await dL(t,e,o,f,h,x,s),vr(s.progress_callback,{status:"done",name:t,file:e}),x){if(!ie.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return x}if(h instanceof Lr)return h.filePath;let v=await o?.match(f);if(v instanceof Lr)return v.filePath;if(v instanceof Response)return new Uint8Array(await v.arrayBuffer());if(typeof v=="string")return v;throw new Error("Unable to get model file path or buffer.")}async function fo(t,e,r=!0,s={},n=!1){if(!me.allowLocalModels){if(s.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!me.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}vr(s.progress_callback,{status:"initiate",name:t,file:e});let o=await tr(s?.cache_dir);return await mL(t,e,r,s,n,o)}async function gf(t,e,r=!0,s={}){let n=await fo(t,e,r,s,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function dt(t,e,r=!0,s={}){let n=await gf(t,e,r,s);return n===null?{}:JSON.parse(n)}function pE(t,[e,r,s],[n,o],a="bilinear",i=!1){let l=o/s,c=n/r,p=new t.constructor(n*o*e),f=r*s,m=n*o;for(let h=0;h<n;++h)for(let w=0;w<o;++w){let x=h*o+w,v=(w+.5)/l-.5,E=(h+.5)/c-.5,A=Math.floor(v),S=Math.floor(E),M=Math.min(A+1,s-1),L=Math.min(S+1,r-1);A=Math.max(A,0),S=Math.max(S,0);let O=v-A,k=E-S,G=(1-O)*(1-k),H=O*(1-k),U=(1-O)*k,V=O*k,q=S*s,Y=L*s,B=q+A,C=q+M,te=Y+A,le=Y+M;for(let P=0;P<e;++P){let N=P*f;p[P*m+x]=G*t[N+B]+H*t[N+C]+U*t[N+te]+V*t[N+le]}}return p}function fE(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 c=e.length-1,p=i;c>=0;--c)l+=p%e[c]*o[c],p=Math.floor(p/e[c]);a[l]=t[i]}return[a,s]}function Re(t){let e=Ce(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 xf(t){let e=Ce(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 dE(t,e){let r=0;for(let s=0;s<t.length;++s)r+=t[s]*e[s];return r}function hL(t,e){let r=dE(t,e),s=uE(t),n=uE(e);return r/(s*n)}function uE(t){return Math.sqrt(t.reduce((e,r)=>e+r*r,0))}function mo(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 Ce(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 mE(t){return t>0&&(t&t-1)===0}var Ql=class{constructor(e){if(this.size=e|0,this.size<=1||!mE(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,c,p=this._bitrev;if(i===4)for(l=0,c=0;l<n;l+=i,++c){let m=p[c];this._singleTransform2(r,e,l,m,a)}else for(l=0,c=0;l<n;l+=i,++c){let m=p[c];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 v=w,E=v+m,A=E+m,S=A+m,M=e[v],L=e[v+1],O=e[E],k=e[E+1],G=e[A],H=e[A+1],U=e[S],V=e[S+1],q=f[x],Y=s*f[x+1],B=O*q-k*Y,C=O*Y+k*q,te=f[2*x],le=s*f[2*x+1],P=G*te-H*le,N=G*le+H*te,$=f[3*x],J=s*f[3*x+1],Ie=U*$-V*J,ae=U*J+V*$,Fe=M+P,Je=L+N,tt=M-P,nt=L-N,at=B+Ie,Me=C+ae,xe=s*(B-Ie),We=s*(C-ae);e[v]=Fe+at,e[v+1]=Je+Me,e[E]=tt+We,e[E+1]=nt-xe,e[A]=Fe-at,e[A+1]=Je-Me,e[S]=tt-We,e[S+1]=nt+xe}}}}_singleTransform2(e,r,s,n,o){let a=e[n],i=e[n+1],l=e[n+o],c=e[n+o+1];r[s]=a+l,r[s+1]=i+c,r[s+2]=a-l,r[s+3]=i-c}_singleTransform4(e,r,s,n,o,a){let i=o*2,l=o*3,c=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],v=e[n+l+1],E=c+h,A=p+w,S=c-h,M=p-w,L=f+x,O=m+v,k=a*(f-x),G=a*(m-v);r[s]=E+L,r[s+1]=A+O,r[s+2]=S+G,r[s+3]=M-k,r[s+4]=E-L,r[s+5]=A-O,r[s+6]=S-G,r[s+7]=M+k}_realTransform4(e,r,s){let n=this._csize,a=1<<this._width,i=n/a<<1,l,c,p=this._bitrev;if(i===4)for(l=0,c=0;l<n;l+=i,++c){let h=p[c];this._singleRealTransform2(r,e,l,h>>>1,a>>>1)}else for(l=0,c=0;l<n;l+=i,++c){let h=p[c];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 v=0,E=0;v<=x;v+=2,E+=a){let A=l+v,S=A+w,M=S+w,L=M+w,O=e[A],k=e[A+1],G=e[S],H=e[S+1],U=e[M],V=e[M+1],q=e[L],Y=e[L+1],B=O,C=k,te=f[E],le=s*f[E+1],P=G*te-H*le,N=G*le+H*te,$=f[2*E],J=s*f[2*E+1],Ie=U*$-V*J,ae=U*J+V*$,Fe=f[3*E],Je=s*f[3*E+1],tt=q*Fe-Y*Je,nt=q*Je+Y*Fe,at=B+Ie,Me=C+ae,xe=B-Ie,We=C-ae,Ot=P+tt,ve=N+nt,De=s*(P-tt),Ir=s*(N-nt);if(e[A]=at+Ot,e[A+1]=Me+ve,e[S]=xe+Ir,e[S+1]=We-De,v===0){e[M]=at-Ot,e[M+1]=Me-ve;continue}if(v===x)continue;let us=l+w-v,It=l+h-v;e[us]=xe-s*Ir,e[us+1]=-We-s*De,e[It]=at-s*Ot,e[It+1]=-Me+s*ve}}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,c=e[n],p=e[n+o],f=e[n+i],m=e[n+l],h=c+f,w=c-f,x=p+m,v=a*(p-m);r[s]=h+x,r[s+1]=0,r[s+2]=w,r[s+3]=-v,r[s+4]=h-x,r[s+5]=0,r[s+6]=w,r[s+7]=v}},wf=class{constructor(e){let r=2*(e-1),s=2*(2*e-1),n=2**Math.ceil(Math.log2(s));this.bufferSize=n,this._a=r;let o=new Float64Array(s),a=new Float64Array(n);this._chirpBuffer=new Float64Array(n),this._buffer1=new Float64Array(n),this._buffer2=new Float64Array(n),this._outBuffer1=new Float64Array(n),this._outBuffer2=new Float64Array(n);let i=-2*Math.PI/e,l=Math.cos(i),c=Math.sin(i);for(let p=0;p<s>>1;++p){let f=(p+1-e)**2/2,m=Math.sqrt(l**2+c**2)**f,h=f*Math.atan2(c,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 Ql(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,r,s){let n=this._buffer1,o=this._buffer2,a=this._outBuffer1,i=this._outBuffer2,l=this._chirpBuffer,c=this._slicedChirpBuffer,p=this._a;if(s)for(let f=0;f<c.length;f+=2){let m=f+1,h=f>>1,w=r[h];n[f]=w*c[f],n[m]=w*c[m]}else for(let f=0;f<c.length;f+=2){let m=f+1;n[f]=r[f]*c[f]-r[m]*c[m],n[m]=r[f]*c[m]+r[m]*c[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=c[f],x=c[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)}},Jl=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=mE(e),this.isPowerOfTwo?(this.fft=new Ql(e),this.outputBufferSize=2*e):(this.fft=new wf(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,r){this.fft.realTransform(e,r)}transform(e,r){this.fft.transform(e,r)}};function hE(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 xs(t,e){let r=Math.pow(10,e);return Math.round(t*r)/r}function _E(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function gE(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,v;m<h&&m<w?(x=m,v=0):h<m&&h<w?(x=h,v=1):(x=w,v=2),n[f][p]=t[f-1][p-1]+x,o[f][p]=v}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=[],c=[];for(;a>0||i>0;)switch(l.push(a-1),c.push(i-1),o[a][i]){case 0:--a,--i;break;case 1:--a;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${a}, ${i}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}var wE=(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 c=0,p=(l&32768)<<16,f=(l&31744)>>10,m=l&1023;if(f===31)c=p|2139095040|m<<13;else if(f===0)if(m===0)c=p;else{let h=113;for(;(m&1024)===0;)m<<=1,--h;m&=-1025,c=p|h<<23|m<<13}else c=p|f+112<<23|m<<13;a[0]=c,t[l]=i[0]}}let r=e.length,s=t,n=new Float32Array(r);for(let o=0;o<r;++o)n[o]=s[e[o]];return n}})();var yf={};hs(yf,{default:()=>_L});var _L={};var ud={};hs(ud,{InferenceSession:()=>Kf,TRACE:()=>ic,TRACE_EVENT_BEGIN:()=>Gr,TRACE_EVENT_END:()=>jr,TRACE_FUNC_BEGIN:()=>As,TRACE_FUNC_END:()=>Ts,Tensor:()=>rr,default:()=>WL,env:()=>He,registerBackend:()=>Es});var Hf=Object.defineProperty,gL=Object.getOwnPropertyDescriptor,wL=Object.getOwnPropertyNames,xL=Object.prototype.hasOwnProperty,yL=(t=>typeof ms<"u"?ms:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof ms<"u"?ms:e)[r]}):t)(function(t){if(typeof ms<"u")return ms.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),be=(t,e)=>()=>(t&&(e=t(t=0)),e),vo=(t,e)=>{for(var r in e)Hf(t,r,{get:e[r],enumerable:!0})},bL=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of wL(e))!xL.call(t,n)&&n!==r&&Hf(t,n,{get:()=>e[n],enumerable:!(s=gL(e,n))||s.enumerable});return t},ac=t=>bL(Hf({},"__esModule",{value:!0}),t),ho,Dr,Es,xE,VE,HE=be(()=>{"use strict";ho=new Map,Dr=[],Es=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let s=ho.get(t);if(s===void 0)ho.set(t,{backend:e,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${r}`)}if(r>=0){let n=Dr.indexOf(t);n!==-1&&Dr.splice(n,1);for(let o=0;o<Dr.length;o++)if(ho.get(Dr[o]).priority<=r){Dr.splice(o,0,t);return}Dr.push(t)}return}throw new TypeError("not a valid backend")},xE=async t=>{let e=ho.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}}},VE=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),s=r.length===0?Dr:r,n,o=[],a=new Set;for(let l of s){let c=await xE(l);typeof c=="string"?o.push({name:l,err:c}):(n||(n=c),n===c&&a.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of o)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=e.filter(l=>a.has(typeof l=="string"?l:l.name));return[n,new Proxy(t,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),vL=be(()=>{"use strict";HE()}),XE,kL=be(()=>{"use strict";XE="1.24.0-dev.20251116-b39e144322"}),bf,mt,KE=be(()=>{"use strict";kL(),bf="warning",mt={wasm:{},webgl:{},webgpu:{},versions:{common:XE},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}`);bf=t}},get logLevel(){return bf}},Object.defineProperty(mt,"logLevel",{enumerable:!0})}),He,EL=be(()=>{"use strict";KE(),He=mt}),YE,QE,AL=be(()=>{"use strict";YE=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let p=o*n,f=0,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 v=0;v<n;v++){let E=(t.data[f++]-c[0])*l[0],A=(t.data[m++]-c[1])*l[1],S=(t.data[h++]-c[2])*l[2],M=w===-1?255:(t.data[w++]-c[3])*l[3];s.fillStyle="rgba("+E+","+A+","+S+","+M+")",s.fillRect(v,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")},QE=(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,c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,h=0,w=1,x=2,v=3,E=0,A=f,S=f*2,M=-1;i==="RGBA"?(E=0,A=f,S=f*2,M=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 L=0;L<o*n;h+=m,w+=m,x+=m,v+=m,L++)s.data[h]=(t.data[E++]-p[0])*c[0],s.data[w]=(t.data[A++]-p[1])*c[1],s.data[x]=(t.data[S++]-p[2])*c[2],s.data[v]=M===-1?255:(t.data[M++]-p[3])*c[3]}else throw new Error("Can not access image data");return s}}),Zl,JE,ZE,eA,tA,rA,TL=be(()=>{"use strict";Xf(),Zl=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,m=0,h=1,w=2,x=3,v=0,E=c,A=c*2,S=-1;i==="RGB"&&(f=3,m=0,h=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(v=0,A=c,E=c*2):l==="BGR"&&(A=0,E=c,v=c*2);for(let M=0;M<c;M++,m+=f,w+=f,h+=f,x+=f)p[v++]=(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 $t("float32",p,[1,4,r,s]):new $t("float32",p,[1,3,r,s])},JE=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")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){let p=l();p.width=t.width,p.height=t.height;let f=c(p);if(f!=null){let 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=c(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=c(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,Zl(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,f)=>{let m=l(),h=c(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(Zl(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return Zl(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},ZE=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new $t({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},eA=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new $t({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},tA=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new $t({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},rA=(t,e,r)=>new $t({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),vs,yo,vf,sA,ML=be(()=>{"use strict";vs=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),yo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),vf=!1,sA=()=>{if(!vf){vf=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(vs.set("int64",BigInt64Array),yo.set(BigInt64Array,"int64")),e&&(vs.set("uint64",BigUint64Array),yo.set(BigUint64Array,"uint64")),s?(vs.set("float16",r),yo.set(r,"float16")):vs.set("float16",Uint16Array)}}}),nA,oA,SL=be(()=>{"use strict";Xf(),nA=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},oA=(t,e)=>{switch(t.location){case"cpu":return new $t(t.type,t.data,e);case"cpu-pinned":return new $t({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new $t({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new $t({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new $t({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),$t,Xf=be(()=>{"use strict";AL(),TL(),ML(),SL(),$t=class{constructor(t,e,r){sA();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=vs.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=vs.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=yo.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=nA(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 JE(t,e)}static fromTexture(t,e){return ZE(t,e)}static fromGpuBuffer(t,e){return eA(t,e)}static fromMLTensor(t,e){return tA(t,e)}static fromPinnedBuffer(t,e,r){return rA(t,e,r)}toDataURL(t){return YE(this,t)}toImageData(t){return QE(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 oA(this,t)}}}),rr,aA=be(()=>{"use strict";Xf(),rr=$t}),ic,kf,As,Ts,Gr,jr,iA=be(()=>{"use strict";KE(),ic=(t,e)=>{(typeof mt.trace>"u"?!mt.wasm.trace:!mt.trace)||console.timeStamp(`${t}::ORT::${e}`)},kf=(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}`),ic("CPU",o);return}r[n].includes("TRACE_FUNC")&&(s=!0)}},As=t=>{(typeof mt.trace>"u"?!mt.wasm.trace:!mt.trace)||kf("BEGIN",t)},Ts=t=>{(typeof mt.trace>"u"?!mt.wasm.trace:!mt.trace)||kf("END",t)},Gr=t=>{(typeof mt.trace>"u"?!mt.wasm.trace:!mt.trace)||console.time(`ORT::${t}`)},jr=t=>{(typeof mt.trace>"u"?!mt.wasm.trace:!mt.trace)||console.timeEnd(`ORT::${t}`)}}),lA,OL=be(()=>{"use strict";HE(),aA(),iA(),lA=class cA{constructor(e){this.handler=e}async run(e,r,s){As(),Gr("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof rr||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 rr)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,p=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(p.indexOf(f)!==-1){let m=r[f];(m===null||m instanceof rr)&&(c=!0,a=!1,n[f]=m)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof e[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(let c of this.outputNames)n[c]=null;let i=await this.handler.run(e,n,o),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let p=i[c];p instanceof rr?l[c]=p:l[c]=new rr(p.type,p.data,p.dims)}return jr("InferenceSession.run"),Ts(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){As(),Gr("InferenceSession.create");let o,a={};if(typeof e=="string"){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let 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 VE(a),c=await i.createInferenceSessionHandler(o,l);return jr("InferenceSession.create"),Ts(),new cA(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Kf,IL=be(()=>{"use strict";OL(),Kf=lA}),CL=be(()=>{"use strict"}),PL=be(()=>{"use strict"}),LL=be(()=>{"use strict"}),NL=be(()=>{"use strict"}),uA={};vo(uA,{InferenceSession:()=>Kf,TRACE:()=>ic,TRACE_EVENT_BEGIN:()=>Gr,TRACE_EVENT_END:()=>jr,TRACE_FUNC_BEGIN:()=>As,TRACE_FUNC_END:()=>Ts,Tensor:()=>rr,env:()=>He,registerBackend:()=>Es});var Ms=be(()=>{"use strict";vL(),EL(),IL(),aA(),CL(),PL(),iA(),LL(),NL()}),Yf=be(()=>{"use strict"}),pA={};vo(pA,{default:()=>fA});var Ef,Af,fA,zL=be(()=>{"use strict";MA(),Ss(),Qf(),Ef="ort-wasm-proxy-worker",Af=globalThis.self?.name===Ef,Af&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":Jf(r.wasm).then(()=>{sd(r).then(()=>{postMessage({type:e})},s=>{postMessage({type:e,err:s})})},s=>{postMessage({type:e,err:s})});break;case"init-ep":{let{epName:s,env:n}=r;nd(n,s).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})});break}case"copy-from":{let{buffer:s}=r,n=uc(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;od(s,n).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":ad(r),postMessage({type:e});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:a,options:i}=r;id(s,n,o,a,new Array(a.length).fill(null),i).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:e,out:l},cd([...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})}}),fA=Af?null:t=>new Worker(t??zt,{type:"module",name:Ef})}),dA={};vo(dA,{default:()=>mA});async function yE(t={}){var e=t,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");e.mountExternalData=(u,d)=>{u.startsWith("./")&&(u=u.substring(2)),(e.Uc||(e.Uc=new Map)).set(u,d)},e.unmountExternalData=()=>{delete e.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,Be:!0}).buffer.constructor;let o=()=>{let u=d=>(..._)=>{let g=ir;return _=d(..._),ir!=g?new Promise((b,T)=>{Dp={resolve:b,reject:T}}):_};(()=>{for(let d of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])e[d]=u(e[d])})(),typeof jsepRunAsync<"u"&&(e._OrtRun=jsepRunAsync(e._OrtRun),e._OrtRunWithBinding=jsepRunAsync(e._OrtRunWithBinding)),o=void 0};e.asyncInit=()=>{o?.()};var a,i,l=(u,d)=>{throw d},c=import.meta.url,p="";if(r||s){try{p=new URL(".",c).href}catch{}s&&(i=u=>{var d=new XMLHttpRequest;return d.open("GET",u,!1),d.responseType="arraybuffer",d.send(null),new Uint8Array(d.response)}),a=async u=>{if(O(u))return new Promise((_,g)=>{var b=new XMLHttpRequest;b.open("GET",u,!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(u,{credentials:"same-origin"});if(d.ok)return d.arrayBuffer();throw Error(d.status+" : "+d.url)}}var f,m,h,w,x,v,E=console.log.bind(console),A=console.error.bind(console),S=E,M=A,L=!1,O=u=>u.startsWith("file://");function k(){Cr.buffer!=U.buffer&&Ie()}if(n){let u=function(d){try{var _=d.data,g=_.Oc;if(g==="load"){let b=[];self.onmessage=T=>b.push(T),v=()=>{postMessage({Oc:"loaded"});for(let T of b)u(T);self.onmessage=u};for(let T of _.de)e[T]&&!e[T].proxy||(e[T]=(...I)=>{postMessage({Oc:"callHandler",ce:T,args:I})},T=="print"&&(S=e[T]),T=="printErr"&&(M=e[T]));Cr=_.je,Ie(),m=_.ke,tt(),Bl()}else if(g==="run"){(function(b){var T=(k(),C)[b+52>>>2>>>0];b=(k(),C)[b+56>>>2>>>0],Tv(T,T-b),ce(T)})(_.Nc),Yp(_.Nc,0,0,1,0,0),d1(),zp(_.Nc),H||(lv(),H=!0);try{jT(_.he,_.Wc)}catch(b){if(b!="unwind")throw b}}else _.target!=="setimmediate"&&(g==="checkMailbox"?H&&Cl():g&&(M(`worker: received unknown command ${g}`),M(_)))}catch(b){throw bv(),b}};var G=u,H=!1;self.onunhandledrejection=d=>{throw d.reason||d},self.onmessage=u}var U,V,q,Y,B,C,te,le,P,N,$,J=!1;function Ie(){var u=Cr.buffer;e.HEAP8=U=new Int8Array(u),q=new Int16Array(u),e.HEAPU8=V=new Uint8Array(u),Y=new Uint16Array(u),e.HEAP32=B=new Int32Array(u),e.HEAPU32=C=new Uint32Array(u),te=new Float32Array(u),le=new Float64Array(u),P=new BigInt64Array(u),N=new BigUint64Array(u)}function ae(){J=!0,n?v():br._b()}function Fe(u){throw M(u="Aborted("+u+")"),L=!0,u=new WebAssembly.RuntimeError(u+". Build with -sASSERTIONS for more info."),x?.(u),u}function Je(){return{a:{f:qT,J:WT,k:VT,p:HT,l:XT,ta:KT,b:YT,ca:QT,Ka:x1,s:JT,da:k1,_a:E1,Ga:A1,Ia:T1,$a:M1,Ya:S1,Ra:O1,Xa:I1,pa:C1,Ha:P1,Yb:L1,Za:N1,Fa:z1,eb:ZT,Da:tM,Tb:rM,Rb:nM,Ca:aM,M:iM,I:lM,Sb:cM,ka:_M,Ub:gM,Ua:wM,Wb:yM,La:bM,Pb:vM,la:kM,Ta:zp,bb:EM,U:SM,n:LM,c:Lp,sb:NM,w:zM,L:RM,z:$M,j:DM,o:j1,tb:BM,G:UM,T:FM,h:GM,u:jM,m:qM,i:WM,Oa:VM,Pa:HM,Qa:XM,Ma:H1,Na:X1,Qb:K1,fb:YM,db:ZM,Y:eS,rb:tS,ma:rS,cb:QM,gb:sS,ab:nS,Xb:oS,N:KM,hb:aS,X:iS,Vb:lS,ob:gS,C:wS,sa:xS,ra:yS,qb:bS,W:vS,v:kS,nb:ES,mb:AS,lb:TS,pb:MS,kb:SS,jb:OS,ib:IS,Va:tv,Wa:rv,Ja:It,ea:sv,oa:nv,Sa:ov,na:av,Db:UO,xa:PO,Eb:BO,ya:CO,F:bO,e:lO,r:aO,x:oO,D:wO,Ib:SO,ba:TO,B:uO,za:OO,$:LO,ha:MO,Fb:$O,Gb:RO,Ba:vO,Aa:AO,Jb:kO,wa:DO,aa:IO,d:cO,A:pO,q:iO,Cb:FO,t:dO,y:xO,H:fO,E:mO,K:yO,S:NO,ja:gO,_:zO,Kb:_O,Lb:hO,P:EO,g:PS,a:Cr,Ob:Ir,Hb:LS,ia:NS,O:zS,qa:RS,Mb:$S,Q:DS,zb:BS,Ab:US,ua:FS,fa:GS,R:jS,Ea:qS,va:WS,Z:VS,xb:HS,Zb:XS,V:KS,Bb:YS,ub:QS,vb:ZS,wb:eO,ga:tO,yb:rO,Nb:sO}}}async function tt(){function u(g,b){var T=br=g.exports;g={};for(let[I,z]of Object.entries(T))typeof z=="function"?(T=AM(z),g[I]=T):g[I]=z;return br=g,br=(function(){var I=br,z=Q=>Se=>Q(Se)>>>0,F=Q=>()=>Q()>>>0;return(I=Object.assign({},I)).$b=z(I.$b),I.Cc=F(I.Cc),I.Ec=z(I.Ec),I.rd=(Q=>(Se,ze)=>Q(Se,ze)>>>0)(I.rd),I.wd=z(I.wd),I.xd=F(I.xd),I.Bd=z(I.Bd),I})(),p1.push(br.id),iv=(g=br).$b,lv=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,qp=e._OrtGetWebGpuDevice=g.Bc,$l=g.Cc,Yt=e._free=g.Dc,tn=e._malloc=g.Ec,cv=e._wgpuBufferRelease=g.Fc,uv=e._wgpuCreateInstance=g.Gc,pv=g.Hc,fv=g.Ic,dv=g.Jc,mv=g.Kc,hv=g.Lc,_v=g.Pc,gv=g.Zc,wv=g._c,xv=g.$c,Wp=g.bd,Vp=g.cd,Hp=g.dd,Xp=g.ed,so=g.fd,Kp=g.gd,yv=g.hd,Yp=g.kd,bv=g.ld,vv=g.md,kv=g.nd,Qp=g.od,Ev=g.pd,Av=g.qd,Jp=g.rd,ge=g.sd,no=g.td,Tv=g.ud,ce=g.vd,Dl=g.wd,ue=g.xd,Mv=g.yd,Zp=g.zd,Sv=g.Ad,Ov=g.Bd,Iv=g.Cd,ef=g.Dd,Cv=g.Ed,Pv=g.Fd,Lv=g.Gd,Nv=g.Hd,zv=g.Id,Rv=g.Jd,$v=g.Kd,Dv=g.Ld,Bv=g.Md,Uv=g.Nd,Fv=g.Od,Gv=g.Pd,jv=g.Qd,qv=g.Rd,Wv=g.Td,Vv=g.Ud,Hv=g.Vd,Xv=g.Wd,Kv=g.Yd,Yv=g.Zd,Qv=g._d,Jv=g.$d,Zv=g.ae,ek=g.be,tk=g.pe,rk=g.qe,sk=g.re,nk=g.se,ok=g.te,ak=g.ue,ik=g.ve,lk=g.we,ck=g.xe,uk=g.ye,pk=g.ze,fk=g.Xe,dk=g.Ye,mk=g.Ze,hk=g._e,m=b,br}var d,_=Je();return e.instantiateWasm?new Promise(g=>{e.instantiateWasm(_,(b,T)=>{g(u(b,T))})}):n?u(new WebAssembly.Instance(m,Je()),m):($??=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=$;if(!f&&!O(b))try{var T=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(T,g)}catch(I){M(`wasm streaming compile failed: ${I}`),M("falling back to ArrayBuffer instantiation")}return(async function(I,z){try{var F=await(async function(Q){if(!f)try{var Se=await a(Q);return new Uint8Array(Se)}catch{}if(Q==$&&f)Q=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";Q=i(Q)}return Q})(I);return await WebAssembly.instantiate(F,z)}catch(Q){M(`failed to asynchronously prepare wasm: ${Q}`),Fe(Q)}})(b,g)})(_),u(d.instance,d.module))}class nt{name="ExitStatus";constructor(d){this.message=`Program terminated with exit(${d})`,this.status=d}}var at=u=>{u.terminate(),u.onmessage=()=>{}},Me=[],xe=0,We=null,Ot=u=>{ot.length==0&&(h1(),m1(ot[0]));var d=ot.pop();if(!d)return 6;eo.push(d),ps[u.Nc]=d,d.Nc=u.Nc;var _={Oc:"run",he:u.ge,Wc:u.Wc,Nc:u.Nc};return d.postMessage(_,u.Yc),0},ve=0,De=(u,d,..._)=>{var g,b=16*_.length,T=ue(),I=Dl(b),z=I>>>3;for(g of _)typeof g=="bigint"?((k(),P)[z++>>>0]=1n,(k(),P)[z++>>>0]=g):((k(),P)[z++>>>0]=0n,(k(),le)[z++>>>0]=g);return u=vv(u,0,b,I,d),ce(T),u};function Ir(u){if(n)return De(0,1,u);if(h=u,!(0<ve)){for(var d of eo)at(d);for(d of ot)at(d);ot=[],eo=[],ps={},L=!0}l(0,new nt(u))}function us(u){if(n)return De(1,0,u);It(u)}var It=u=>{if(h=u,n)throw us(u),"unwind";Ir(u)},ot=[],eo=[],p1=[],ps={},f1=u=>{var d=u.Nc;delete ps[d],ot.push(u),eo.splice(eo.indexOf(u),1),u.Nc=0,kv(d)};function d1(){p1.forEach(u=>u())}var m1=u=>new Promise(d=>{u.onmessage=b=>{var T=b.data;if(b=T.Oc,T.Vc&&T.Vc!=$l()){var I=ps[T.Vc];I?I.postMessage(T,T.Yc):M(`Internal error! Worker sent a message "${b}" to target pthread ${T.Vc}, but that thread no longer exists!`)}else b==="checkMailbox"?Cl():b==="spawnThread"?Ot(T):b==="cleanupThread"?Mt(()=>{f1(ps[T.ie])}):b==="loaded"?(u.loaded=!0,d(u)):T.target==="setimmediate"?u.postMessage(T):b==="uncaughtException"?u.onerror(T.error):b==="callHandler"?e[T.ce](...T.args):b&&M(`worker sent an unknown command ${b}`)},u.onerror=b=>{throw M(`worker sent an error! ${b.filename}:${b.lineno}: ${b.message}`),b};var _,g=[];for(_ of[])e.propertyIsEnumerable(_)&&g.push(_);u.postMessage({Oc:"load",de:g,je:Cr,ke:m})});function h1(){var u=new Worker((()=>{let d=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new d("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});ot.push(u)}var Cr,jT=(u,d)=>{ve=0,u=ef(u,d),0<ve?h=u:Qp(u)},Ol=[],Il=0,Tt=u=>-9007199254740992>u||9007199254740992<u?NaN:Number(u);function qT(u){var d=new Op(u>>>=0);return(k(),U)[d.Qc+12>>>0]==0&&(_1(d,!0),Il--),g1(d,!1),Ol.push(d),Ov(u)}var Qs=0,WT=()=>{ge(0,0);var u=Ol.pop();Mv(u.Xc),Qs=0};function _1(u,d){d=d?1:0,(k(),U)[u.Qc+12>>>0]=d}function g1(u,d){d=d?1:0,(k(),U)[u.Qc+13>>>0]=d}class Op{constructor(d){this.Xc=d,this.Qc=d-24}}var Ip=u=>{var d=Qs;if(!d)return no(0),0;var _=new Op(d);(k(),C)[_.Qc+16>>>2>>>0]=d;var g=(k(),C)[_.Qc+4>>>2>>>0];if(!g)return no(0),d;for(var b of u){if(b===0||b===g)break;if(Sv(b,g,_.Qc+16))return no(b),d}return no(g),d};function VT(){return Ip([])}function HT(u){return Ip([u>>>0])}function XT(u,d,_,g){return Ip([u>>>0,d>>>0,_>>>0,g>>>0])}var KT=()=>{var u=Ol.pop();u||Fe("no exception to throw");var d=u.Xc;throw(k(),U)[u.Qc+13>>>0]==0&&(Ol.push(u),g1(u,!0),_1(u,!1),Il++),Zp(d),Qs=d};function YT(u,d,_){var g=new Op(u>>>=0);throw d>>>=0,_>>>=0,(k(),C)[g.Qc+16>>>2>>>0]=0,(k(),C)[g.Qc+4>>>2>>>0]=d,(k(),C)[g.Qc+8>>>2>>>0]=_,Zp(u),Il++,Qs=u}var QT=()=>Il;function w1(u,d,_,g){return n?De(2,1,u,d,_,g):x1(u,d,_,g)}function x1(u,d,_,g){if(u>>>=0,d>>>=0,_>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var b=[];return n&&b.length===0?w1(u,d,_,g):(u={ge:_,Nc:u,Wc:g,Yc:b},n?(u.Oc="spawnThread",postMessage(u,b),0):Ot(u))}function JT(u){throw Qs||=u>>>0,Qs}var y1=globalThis.TextDecoder&&new TextDecoder,b1=(u,d,_,g)=>{if(_=d+_,g)return _;for(;u[d]&&!(d>=_);)++d;return d},v1=(u,d=0,_,g)=>{if(16<(_=b1(u,d>>>=0,_,g))-d&&u.buffer&&y1)return y1.decode(u.buffer instanceof ArrayBuffer?u.subarray(d,_):u.slice(d,_));for(g="";d<_;){var b=u[d++];if(128&b){var T=63&u[d++];if((224&b)==192)g+=String.fromCharCode((31&b)<<6|T);else{var I=63&u[d++];65536>(b=(240&b)==224?(15&b)<<12|T<<6|I:(7&b)<<18|T<<12|I<<6|63&u[d++])?g+=String.fromCharCode(b):(b-=65536,g+=String.fromCharCode(55296|b>>10,56320|1023&b))}}else g+=String.fromCharCode(b)}return g},Js=(u,d,_)=>(u>>>=0)?v1((k(),V),u,d,_):"";function k1(u,d,_){return n?De(3,1,u,d,_):0}function E1(u,d){if(n)return De(4,1,u,d)}function A1(u,d){if(n)return De(5,1,u,d)}function T1(u,d,_){if(n)return De(6,1,u,d,_)}function M1(u,d,_){return n?De(7,1,u,d,_):0}function S1(u,d){if(n)return De(8,1,u,d)}function O1(u,d,_){if(n)return De(9,1,u,d,_)}function I1(u,d,_,g){if(n)return De(10,1,u,d,_,g)}function C1(u,d,_,g){if(n)return De(11,1,u,d,_,g)}function P1(u,d,_,g){if(n)return De(12,1,u,d,_,g)}function L1(u){if(n)return De(13,1,u)}function N1(u,d){if(n)return De(14,1,u,d)}function z1(u,d,_){if(n)return De(15,1,u,d,_)}var ZT=()=>Fe(""),ar=u=>{u>>>=0;for(var d="";;){var _=(k(),V)[u++>>>0];if(!_)return d;d+=String.fromCharCode(_)}},Cp={},Pp={},eM={},Zs=class extends Error{constructor(u){super(u),this.name="BindingError"}};function _r(u,d,_={}){return(function(g,b,T={}){var I=b.name;if(!g)throw new Zs(`type "${I}" must have a positive integer typeid pointer`);if(Pp.hasOwnProperty(g)){if(T.ee)return;throw new Zs(`Cannot register type '${I}' twice`)}Pp[g]=b,delete eM[g],Cp.hasOwnProperty(g)&&(b=Cp[g],delete Cp[g],b.forEach(z=>z()))})(u,d,_)}var R1=(u,d,_)=>{switch(d){case 1:return _?g=>(k(),U)[g>>>0]:g=>(k(),V)[g>>>0];case 2:return _?g=>(k(),q)[g>>>1>>>0]:g=>(k(),Y)[g>>>1>>>0];case 4:return _?g=>(k(),B)[g>>>2>>>0]:g=>(k(),C)[g>>>2>>>0];case 8:return _?g=>(k(),P)[g>>>3>>>0]:g=>(k(),N)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${d}): ${u}`)}};function tM(u,d,_,g,b){u>>>=0,_>>>=0,d=ar(d>>>0);let T=I=>I;if(g=g===0n){let I=8*_;T=z=>BigInt.asUintN(I,z),b=T(b)}_r(u,{name:d,Mc:T,Sc:(I,z)=>(typeof z=="number"&&(z=BigInt(z)),z),Rc:R1(d,_,!g),Tc:null})}function rM(u,d,_,g){_r(u>>>=0,{name:d=ar(d>>>0),Mc:function(b){return!!b},Sc:function(b,T){return T?_:g},Rc:function(b){return this.Mc((k(),V)[b>>>0])},Tc:null})}var $1=[],fs=[0,1,,1,null,1,!0,1,!1,1];function Lp(u){9<(u>>>=0)&&--fs[u+1]==0&&(fs[u]=void 0,$1.push(u))}var Bt=u=>{if(!u)throw new Zs(`Cannot use deleted val. handle = ${u}`);return fs[u]},Kt=u=>{switch(u){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let d=$1.pop()||fs.length;return fs[d]=u,fs[d+1]=1,d}};function Np(u){return this.Mc((k(),C)[u>>>2>>>0])}var sM={name:"emscripten::val",Mc:u=>{var d=Bt(u);return Lp(u),d},Sc:(u,d)=>Kt(d),Rc:Np,Tc:null};function nM(u){return _r(u>>>0,sM)}var oM=(u,d)=>{switch(d){case 4:return function(_){return this.Mc((k(),te)[_>>>2>>>0])};case 8:return function(_){return this.Mc((k(),le)[_>>>3>>>0])};default:throw new TypeError(`invalid float width (${d}): ${u}`)}};function aM(u,d,_){_>>>=0,_r(u>>>=0,{name:d=ar(d>>>0),Mc:g=>g,Sc:(g,b)=>b,Rc:oM(d,_),Tc:null})}function iM(u,d,_,g,b){u>>>=0,_>>>=0,d=ar(d>>>0);let T=z=>z;if(g===0){var I=32-8*_;T=z=>z<<I>>>I,b=T(b)}_r(u,{name:d,Mc:T,Sc:(z,F)=>F,Rc:R1(d,_,g!==0),Tc:null})}function lM(u,d,_){function g(T){var I=(k(),C)[T>>>2>>>0];return T=(k(),C)[T+4>>>2>>>0],new b((k(),U).buffer,T,I)}var b=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][d];_r(u>>>=0,{name:_=ar(_>>>0),Mc:g,Rc:g},{ee:!0})}var gr=(u,d,_)=>{var g=(k(),V);if(d>>>=0,0<_){var b=d;_=d+_-1;for(var T=0;T<u.length;++T){var I=u.codePointAt(T);if(127>=I){if(d>=_)break;g[d++>>>0]=I}else if(2047>=I){if(d+1>=_)break;g[d++>>>0]=192|I>>6,g[d++>>>0]=128|63&I}else if(65535>=I){if(d+2>=_)break;g[d++>>>0]=224|I>>12,g[d++>>>0]=128|I>>6&63,g[d++>>>0]=128|63&I}else{if(d+3>=_)break;g[d++>>>0]=240|I>>18,g[d++>>>0]=128|I>>12&63,g[d++>>>0]=128|I>>6&63,g[d++>>>0]=128|63&I,T++}}g[d>>>0]=0,u=d-b}else u=0;return u},wr=u=>{for(var d=0,_=0;_<u.length;++_){var g=u.charCodeAt(_);127>=g?d++:2047>=g?d+=2:55296<=g&&57343>=g?(d+=4,++_):d+=3}return d};function cM(u,d){_r(u>>>=0,{name:d=ar(d>>>0),Mc(_){var g=(k(),C)[_>>>2>>>0];return g=Js(_+4,g,!0),Yt(_),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 Zs("Cannot pass non-string to std::string");var T=b?wr(g):g.length,I=tn(4+T+1),z=I+4;return(k(),C)[I>>>2>>>0]=T,b?gr(g,z,T+1):(k(),V).set(g,z>>>0),_!==null&&_.push(Yt,I),I},Rc:Np,Tc(_){Yt(_)}})}var D1=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,uM=(u,d,_)=>{if(u>>>=1,16<(d=b1((k(),Y),u,d/2,_))-u&&D1)return D1.decode((k(),Y).slice(u,d));for(_="";u<d;++u){var g=(k(),Y)[u>>>0];_+=String.fromCharCode(g)}return _},pM=(u,d,_)=>{if(_??=2147483647,2>_)return 0;var g=d;_=(_-=2)<2*u.length?_/2:u.length;for(var b=0;b<_;++b){var T=u.charCodeAt(b);(k(),q)[d>>>1>>>0]=T,d+=2}return(k(),q)[d>>>1>>>0]=0,d-g},fM=u=>2*u.length,dM=(u,d,_)=>{var g="";u>>>=2;for(var b=0;!(b>=d/4);b++){var T=(k(),C)[u+b>>>0];if(!T&&!_)break;g+=String.fromCodePoint(T)}return g},mM=(u,d,_)=>{if(d>>>=0,_??=2147483647,4>_)return 0;var g=d;_=g+_-4;for(var b=0;b<u.length;++b){var T=u.codePointAt(b);if(65535<T&&b++,(k(),B)[d>>>2>>>0]=T,(d+=4)+4>_)break}return(k(),B)[d>>>2>>>0]=0,d-g},hM=u=>{for(var d=0,_=0;_<u.length;++_)65535<u.codePointAt(_)&&_++,d+=4;return d};function _M(u,d,_){if(u>>>=0,d>>>=0,_=ar(_>>>=0),d===2)var g=uM,b=pM,T=fM;else g=dM,b=mM,T=hM;_r(u,{name:_,Mc:I=>{var z=(k(),C)[I>>>2>>>0];return z=g(I+4,z*d,!0),Yt(I),z},Sc:(I,z)=>{if(typeof z!="string")throw new Zs(`Cannot pass non-string to C++ string type ${_}`);var F=T(z),Q=tn(4+F+d);return(k(),C)[Q>>>2>>>0]=F/d,b(z,Q+4,F+d),I!==null&&I.push(Yt,Q),Q},Rc:Np,Tc(I){Yt(I)}})}function gM(u,d){_r(u>>>=0,{fe:!0,name:d=ar(d>>>0),Mc:()=>{},Sc:()=>{}})}function wM(u){Yp(u>>>0,!s,1,!r,131072,!1),d1()}var Mt=u=>{if(!L)try{if(u(),!(0<ve))try{n?$l()&&Qp(h):It(h)}catch(d){d instanceof nt||d=="unwind"||l(0,d)}}catch(d){d instanceof nt||d=="unwind"||l(0,d)}},xM=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function zp(u){u>>>=0,xM||(Atomics.waitAsync((k(),B),u>>>2,u).value.then(Cl),u+=128,Atomics.store((k(),B),u>>>2,1))}var Cl=()=>Mt(()=>{var u=$l();u&&(zp(u),Av())});function yM(u,d){(u>>>=0)==d>>>0?setTimeout(Cl):n?postMessage({Vc:u,Oc:"checkMailbox"}):(u=ps[u])&&u.postMessage({Oc:"checkMailbox"})}var Rp=[];function bM(u,d,_,g,b){for(d>>>=0,b>>>=0,Rp.length=0,_=b>>>3,g=b+g>>>3;_<g;){var T;T=(k(),P)[_++>>>0]?(k(),P)[_++>>>0]:(k(),le)[_++>>>0],Rp.push(T)}return(d?tf[d]:nO[u])(...Rp)}var vM=()=>{ve=0};function kM(u){u>>>=0,n?postMessage({Oc:"cleanupThread",ie:u}):f1(ps[u])}function EM(u){}var Pl=u=>{try{u()}catch(d){Fe(d)}};function AM(u){var d=(..._)=>{Ll.push(u);try{return u(..._)}finally{L||(Ll.pop(),ir&&Pr===1&&Ll.length===0&&(Pr=0,ve+=1,Pl(dk),typeof Fibers<"u"&&Fibers.De()))}};return F1.set(u,d),d}var Pr=0,ir=null,B1=0,Ll=[],$p=new Map,U1=new Map,F1=new Map,TM=0,Dp=null,MM=[],G1=u=>(function(d){if(!L){if(Pr===0){var _=!1,g=!1;d((b=0)=>{if(!L&&(B1=b,_=!0,g)){Pr=2,Pl(()=>mk(ir)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),b=!1;try{var T=(function(){var F=(k(),B)[ir+8>>>2>>>0];return F=U1.get(F),F=F1.get(F),--ve,F()})()}catch(F){T=F,b=!0}var I=!1;if(!ir){var z=Dp;z&&(Dp=null,(b?z.reject:z.resolve)(T),I=!0)}if(b&&!I)throw T}}),g=!0,_||(Pr=1,ir=(function(){var b=tn(65548),T=b+12;if((k(),C)[b>>>2>>>0]=T,(k(),C)[b+4>>>2>>>0]=T+65536,T=Ll[0],!$p.has(T)){var I=TM++;$p.set(T,I),U1.set(I,T)}return T=$p.get(T),(k(),B)[b+8>>>2>>>0]=T,b})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),Pl(()=>fk(ir)))}else Pr===2?(Pr=0,Pl(hk),Yt(ir),ir=null,MM.forEach(Mt)):Fe(`invalid state: ${Pr}`);return B1}})(d=>{u().then(d)});function SM(u){return u>>>=0,G1(async()=>{var d=await Bt(u);return Kt(d)})}var Bp=[],OM=u=>{var d=Bp.length;return Bp.push(u),d},IM=(u,d)=>{for(var _=Array(u),g=0;g<u;++g){var b=g,T=(k(),C)[d+4*g>>>2>>>0],I=Pp[T];if(I===void 0)throw u=`parameter ${g}`,T=iv(T),d=ar(T),Yt(T),new Zs(`${u} has unknown type ${d}`);_[b]=I}return _},CM=(u,d,_)=>{var g=[];return u=u(g,_),g.length&&((k(),C)[d>>>2>>>0]=Kt(g)),u},PM={},Nl=u=>{var d=PM[u];return d===void 0?ar(u):d};function LM(u,d,_){var[g,...b]=IM(u,d>>>0);d=g.Sc.bind(g);var T=b.map(F=>F.Rc.bind(F));u--;var I={toValue:Bt};switch(u=T.map((F,Q)=>{var Se=`argFromPtr${Q}`;return I[Se]=F,`${Se}(args${Q?"+"+8*Q:""})`}),_){case 0:var z="toValue(handle)";break;case 2:z="new (toValue(handle))";break;case 3:z="";break;case 1:I.getStringOrSymbol=Nl,z="toValue(handle)[getStringOrSymbol(methodName)]"}return z+=`(${u})`,g.fe||(I.toReturnWire=d,I.emval_returnValue=CM,z=`return emval_returnValue(toReturnWire, destructorsRef, ${z})`),z=`return function (handle, methodName, destructorsRef, args) {
11
11
  ${z}
12
- }`,_=new Function(Object.keys(O),z)(...Object.values(O)),z=`methodCaller<(${v.map(B=>B.name)}) => ${g.name}>`,$T(Object.defineProperty(_,"name",{value:z}))}function jT(u,d){return d>>>=0,(u=Ut(u>>>0))==Ut(d)}function GT(u){return(u>>>=0)?(u=gl(u),Kt(globalThis[u])):Kt(globalThis)}function qT(u){return u=gl(u>>>0),Kt(e[u])}function WT(u,d){return d>>>=0,u=Ut(u>>>0),d=Ut(d),Kt(u[d])}function VT(u){9<(u>>>=0)&&(ps[u+1]+=1)}function s1(u,d,_,g,v){return kp[u>>>0](d>>>0,_>>>0,g>>>0,v>>>0)}function HT(u,d,_,g,v){return s1(u>>>0,d>>>0,_>>>0,g>>>0,v>>>0)}function XT(){return Kt([])}function KT(u){u=Ut(u>>>0);for(var d=Array(u.length),_=0;_<u.length;_++)d[_]=u[_];return Kt(d)}function YT(u){return Kt(gl(u>>>0))}function QT(){return Kt({})}function JT(u){for(var d=Ut(u>>>=0);d.length;){var _=d.pop();d.pop()(_)}gp(u)}function ZT(u,d,_){d>>>=0,_>>>=0,u=Ut(u>>>0),d=Ut(d),_=Ut(_),u[d]=_}function eM(u,d){u=bt(u),d>>>=0,u=new Date(1e3*u),(k(),U)[d>>>2>>>0]=u.getUTCSeconds(),(k(),U)[d+4>>>2>>>0]=u.getUTCMinutes(),(k(),U)[d+8>>>2>>>0]=u.getUTCHours(),(k(),U)[d+12>>>2>>>0]=u.getUTCDate(),(k(),U)[d+16>>>2>>>0]=u.getUTCMonth(),(k(),U)[d+20>>>2>>>0]=u.getUTCFullYear()-1900,(k(),U)[d+24>>>2>>>0]=u.getUTCDay(),u=(u.getTime()-Date.UTC(u.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(k(),U)[d+28>>>2>>>0]=u}var n1=u=>u%4==0&&(u%100!=0||u%400==0),o1=[0,31,60,91,121,152,182,213,244,274,305,335],a1=[0,31,59,90,120,151,181,212,243,273,304,334];function tM(u,d){u=bt(u),d>>>=0,u=new Date(1e3*u),(k(),U)[d>>>2>>>0]=u.getSeconds(),(k(),U)[d+4>>>2>>>0]=u.getMinutes(),(k(),U)[d+8>>>2>>>0]=u.getHours(),(k(),U)[d+12>>>2>>>0]=u.getDate(),(k(),U)[d+16>>>2>>>0]=u.getMonth(),(k(),U)[d+20>>>2>>>0]=u.getFullYear()-1900,(k(),U)[d+24>>>2>>>0]=u.getDay();var _=(n1(u.getFullYear())?o1:a1)[u.getMonth()]+u.getDate()-1|0;(k(),U)[d+28>>>2>>>0]=_,(k(),U)[d+36>>>2>>>0]=-60*u.getTimezoneOffset(),_=new Date(u.getFullYear(),6,1).getTimezoneOffset();var g=new Date(u.getFullYear(),0,1).getTimezoneOffset();u=0|(_!=g&&u.getTimezoneOffset()==Math.min(g,_)),(k(),U)[d+32>>>2>>>0]=u}function rM(u){u>>>=0;var d=new Date((k(),U)[u+20>>>2>>>0]+1900,(k(),U)[u+16>>>2>>>0],(k(),U)[u+12>>>2>>>0],(k(),U)[u+8>>>2>>>0],(k(),U)[u+4>>>2>>>0],(k(),U)[u>>>2>>>0],0),_=(k(),U)[u+32>>>2>>>0],g=d.getTimezoneOffset(),v=new Date(d.getFullYear(),6,1).getTimezoneOffset(),T=new Date(d.getFullYear(),0,1).getTimezoneOffset(),O=Math.min(T,v);return 0>_?(k(),U)[u+32>>>2>>>0]=+(v!=T&&O==g):0<_!=(O==g)&&(v=Math.max(T,v),d.setTime(d.getTime()+6e4*((0<_?O:v)-g))),(k(),U)[u+24>>>2>>>0]=d.getDay(),_=(n1(d.getFullYear())?o1:a1)[d.getMonth()]+d.getDate()-1|0,(k(),U)[u+28>>>2>>>0]=_,(k(),U)[u>>>2>>>0]=d.getSeconds(),(k(),U)[u+4>>>2>>>0]=d.getMinutes(),(k(),U)[u+8>>>2>>>0]=d.getHours(),(k(),U)[u+12>>>2>>>0]=d.getDate(),(k(),U)[u+16>>>2>>>0]=d.getMonth(),(k(),U)[u+20>>>2>>>0]=d.getYear(),u=d.getTime(),BigInt(isNaN(u)?-1:u/1e3)}function i1(u,d,_,g,v,T,O){return n?Re(16,1,u,d,_,g,v,T,O):-52}function l1(u,d,_,g,v,T){if(n)return Re(17,1,u,d,_,g,v,T)}var Gn={},sM=()=>performance.timeOrigin+performance.now();function c1(u,d){if(n)return Re(18,1,u,d);if(Gn[u]&&(clearTimeout(Gn[u].id),delete Gn[u]),!d)return 0;var _=setTimeout(()=>{delete Gn[u],vt(()=>D1(u,performance.timeOrigin+performance.now()))},d);return Gn[u]={id:_,Ce:d},0}function nM(u,d,_,g){u>>>=0,d>>>=0,_>>>=0,g>>>=0;var v=new Date().getFullYear(),T=new Date(v,0,1).getTimezoneOffset();v=new Date(v,6,1).getTimezoneOffset();var O=Math.max(T,v);(k(),L)[u>>>2>>>0]=60*O,(k(),U)[d>>>2>>>0]=+(T!=v),u=(d=z=>{var B=Math.abs(z);return`UTC${0<=z?"-":"+"}${String(Math.floor(B/60)).padStart(2,"0")}${String(B%60).padStart(2,"0")}`})(T),d=d(v),v<T?(xr(u,_,17),xr(d,g,17)):(xr(u,g,17),xr(d,_,17))}var oM=()=>Date.now(),aM=1;function iM(u,d,_){if(_>>>=0,!(0<=u&&3>=u))return 28;if(u===0)u=Date.now();else{if(!aM)return 52;u=performance.timeOrigin+performance.now()}return u=Math.round(1e6*u),(k(),I)[_>>>3>>>0]=BigInt(u),0}var Ep=[],u1=(u,d)=>{Ep.length=0;for(var _;_=(k(),J)[u++>>>0];){var g=_!=105;d+=(g&=_!=112)&&d%8?4:0,Ep.push(_==112?(k(),L)[d>>>2>>>0]:_==106?(k(),I)[d>>>3>>>0]:_==105?(k(),U)[d>>>2>>>0]:(k(),ae)[d>>>3>>>0]),d+=g?8:4}return Ep};function lM(u,d,_){return u>>>=0,d=u1(d>>>0,_>>>0),Up[u](...d)}function cM(u,d,_){return u>>>=0,d=u1(d>>>0,_>>>0),Up[u](...d)}var uM=()=>{};function pM(u,d){return M(Vs(u>>>0,d>>>0))}var fM=()=>{throw be+=1,"unwind"};function dM(){return 4294901760}var mM=()=>1,hM=()=>navigator.hardwareConcurrency;function _M(u){u>>>=0;var d=(k(),J).length;if(u<=d||4294901760<u)return!1;for(var _=1;4>=_;_*=2){var g=d*(1+.2/_);g=Math.min(g,u+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(u,g)/65536))-Lr.buffer.byteLength+65535)/65536|0;try{Lr.grow(g),pe();var v=1;break e}catch{}v=void 0}if(v)return!0}return!1}var ir=u=>{var d=yr(u)+1,_=bl(d);return xr(u,_,d),_},Ap=(u,d)=>{(k(),L)[u>>>2>>>0]=d;var _=(k(),L)[u>>>2>>>0];(k(),L)[u+4>>>2>>>0]=(d-_)/4294967296},qn=u=>(k(),L)[u>>>2>>>0]+4294967296*(k(),U)[u+4>>>2>>>0],ft=[],gM=(u,d)=>{ft[u>>>0]=d},br=[],wl=[],Xs=(u,d)=>{wl[u]=new Promise(_=>d.finally(()=>_(u)))},re=u=>{if(u)return ft[u>>>0]},wM=(u,d)=>{for(u=(k(),L)[u>>>2>>>0];u;u=(k(),L)[u>>>2>>>0])d[(k(),U)[u+4>>>2>>>0]](u)},xl=(u,d,_)=>{(k(),L)[u>>>2>>>0]=d,(k(),L)[u+4>>>2>>>0]=_},p1=u=>{var d=(k(),L)[u>>>2>>>0];return u=(k(),L)[u+4>>>2>>>0],Vs(d,u)},vr=u=>{var d=(k(),L)[u>>>2>>>0];return u=(k(),L)[u+4>>>2>>>0],d?Vs(d,u):u===0?"":void 0},xM=u=>{var d=vr(u+4),_=(_=(k(),L)[u+12>>>2>>>0])?re(_):"auto";if(u+=16){var g=re((k(),L)[u+4>>>2>>>0]),v=(k(),L)[u+16>>>2>>>0],T=(k(),L)[u+20>>>2>>>0];if(v){for(var O={},z=0;z<v;++z){var B=T+24*z;O[p1(B+4)]=(k(),ae)[B+16>>>3>>>0]}v=O}else v=void 0;u={module:g,constants:v,entryPoint:vr(u+8)}}else u=void 0;return{label:d,layout:_,compute:u}},f1=(u,d)=>{function _(g,v){g=u[g],(k(),L)[d+v>>>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),Ap(d+64,u.maxUniformBufferBindingSize),Ap(d+72,u.maxStorageBufferBindingSize),_("maxVertexBuffers",88),Ap(d+96,u.maxBufferSize),_("maxVertexAttributes",104),_("maxVertexBufferArrayStride",108),_("maxInterStageShaderVariables",112),_("maxColorAttachments",116),_("maxColorAttachmentBytesPerSample",120),_("maxComputeWorkgroupStorageSize",124),_("maxComputeInvocationsPerWorkgroup",128),_("maxComputeWorkgroupSizeX",132),_("maxComputeWorkgroupSizeY",136),_("maxComputeWorkgroupSizeZ",140),_("maxComputeWorkgroupsPerDimension",144),u.Ae!==void 0&&_("maxImmediateSize",148)},yM=[,"validation","out-of-memory","internal"],bM=[,"compatibility","core"],d1={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"},vM=[,"low-power","high-performance"],kM=[,"occlusion","timestamp"],EM={undefined:1,unknown:1,destroyed:2};function AM(u,d,_,g,v,T){d=bt(d),_=bt(_),g>>>=0,v>>>=0,T>>>=0;var O=re(u>>>0);if(u={},T){var z=(k(),L)[T+12>>>2>>>0];if(z){var B=(k(),L)[T+16>>>2>>>0];u.requiredFeatures=Array.from((k(),L).subarray(B>>>2>>>0,B+4*z>>>2>>>0),se=>d1[se])}var K=(k(),L)[T+20>>>2>>>0];if(K){let se=function(kt,lt,fs=!1){lt=K+lt,(lt=(k(),L)[lt>>>2>>>0])==4294967295||fs&&lt==0||(Be[kt]=lt)},it=function(kt,lt){lt=K+lt;var fs=(k(),L)[lt>>>2>>>0],YS=(k(),L)[lt+4>>>2>>>0];fs==4294967295&&YS==4294967295||(Be[kt]=qn(lt))};var Me=se,Le=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),u.requiredLimits=Be}(z=(k(),L)[T+24>>>2>>>0])&&(z={label:vr(z+4)},u.defaultQueue=z),u.label=vr(T+4)}be+=1,Xs(d,O.requestDevice(u).then(se=>{--be,vt(()=>{ft[v>>>0]=se.queue,ft[g>>>0]=se,Xs(_,se.lost.then(it=>{vt(()=>{se.onuncapturederror=()=>{};var kt=le(),lt=ir(it.message);Ip(_,EM[it.reason],lt),ie(kt)})})),se.onuncapturederror=it=>{var kt=5;it.error instanceof GPUValidationError?kt=2:it.error instanceof GPUOutOfMemoryError?kt=3:it.error instanceof GPUInternalError&&(kt=4);var lt=le();it=ir(it.error.message),N1(g,kt,it),ie(lt)},"adapterInfo"in se||(se.adapterInfo=O.info),Lp(d,1,g,0)})},se=>{--be,vt(()=>{var it=le(),kt=ir(se.message);Lp(d,3,g,kt),_&&Ip(_,4,kt),ie(it)})}))}function TM(u){var d=re(u>>>=0),_=br[u];if(_){for(var g=0;g<_.length;++g)_[g]();delete br[u]}d.destroy()}function MM(u,d,_){_>>>=0;var g=re(u>>>=0);_==4294967295&&(_=void 0);try{var v=g.getMappedRange(d>>>0,_)}catch{return 0}var T=Rp(16,v.byteLength);return(k(),J).set(new Uint8Array(v),T>>>0),br[u].push(()=>Yt(T)),T}function SM(u,d,_){_>>>=0;var g=re(u>>>=0);_==4294967295&&(_=void 0);try{var v=g.getMappedRange(d>>>0,_)}catch{return 0}var T=Rp(16,v.byteLength);return(k(),J).fill(0,T,v.byteLength),br[u].push(()=>{new Uint8Array(v).set((k(),J).subarray(T>>>0,T+v.byteLength>>>0)),Yt(T)}),T}function OM(u,d,_,g,v){u>>>=0,d=bt(d),_=bt(_),v>>>=0;var T=re(u);br[u]=[],v==4294967295&&(v=void 0),be+=1,Xs(d,T.mapAsync(_,g>>>0,v).then(()=>{--be,vt(()=>{Cp(d,1,0)})},O=>{--be,vt(()=>{le();var z=ir(O.message);Cp(d,O.name==="AbortError"?4:O.name==="OperationError"?3:0,z),delete br[u]})}))}function IM(u){var d=re(u>>>=0),_=br[u];if(_){for(var g=0;g<_.length;++g)_[g]();delete br[u],d.unmap()}}function CM(u){delete ft[u>>>0]}function PM(u,d,_){u>>>=0,d>>>=0,_>>>=0;var g=!!(k(),L)[d+32>>>2>>>0];d={label:vr(d+4),usage:(k(),L)[d+16>>>2>>>0],size:qn(d+24),mappedAtCreation:g},u=re(u);try{var v=u.createBuffer(d)}catch{return!1}return ft[_>>>0]=v,g&&(br[_]=[]),!0}function LM(u,d,_,g){u>>>=0,d=bt(d),g>>>=0,_=xM(_>>>0),u=re(u),be+=1,Xs(d,u.createComputePipelineAsync(_).then(v=>{--be,vt(()=>{ft[g>>>0]=v,Op(d,1,g,0)})},v=>{--be,vt(()=>{var T=le(),O=ir(v.message);Op(d,v.reason==="validation"?3:v.reason==="internal"?4:0,g,O),ie(T)})}))}function NM(u,d,_){u>>>=0,d>>>=0,_>>>=0;var g=(k(),L)[d>>>2>>>0],v=(k(),U)[g+4>>>2>>>0];d={label:vr(d+4),code:""},v===2&&(d.code=p1(g+8)),u=re(u).createShaderModule(d),ft[_>>>0]=u}var zM=u=>{(u=re(u)).onuncapturederror=null,u.destroy()};function RM(u,d){d=bt(d),u=re(u>>>0),be+=1,Xs(d,u.popErrorScope().then(_=>{--be,vt(()=>{var g=5;_?_ instanceof GPUValidationError?g=2:_ instanceof GPUOutOfMemoryError?g=3:_ instanceof GPUInternalError&&(g=4):g=1;var v=le(),T=_?ir(_.message):0;Pp(d,1,g,T),ie(v)})},_=>{--be,vt(()=>{var g=le(),v=ir(_.message);Pp(d,1,5,v),ie(g)})}))}function $M(u,d,_,g){if(d=bt(d),g>>>=0,_>>>=0){var v={featureLevel:bM[(k(),U)[_+4>>>2>>>0]],powerPreference:vM[(k(),U)[_+8>>>2>>>0]],forceFallbackAdapter:!!(k(),L)[_+12>>>2>>>0]};(u=(k(),L)[_>>>2>>>0])!==0&&(k(),v.Fe=!!(k(),L)[u+8>>>2>>>0])}"gpu"in navigator?(be+=1,Xs(d,navigator.gpu.requestAdapter(v).then(T=>{--be,vt(()=>{if(T)ft[g>>>0]=T,Wn(d,1,g,0);else{var O=le(),z=ir("WebGPU not available on this browser (requestAdapter returned null)");Wn(d,3,g,z),ie(O)}})},T=>{--be,vt(()=>{var O=le(),z=ir(T.message);Wn(d,4,g,z),ie(O)})}))):(v=le(),u=ir("WebGPU not available on this browser (navigator.gpu is not available)"),Wn(d,3,g,u),ie(v))}function DM(u,d,_){return u>>>=0,d>>>=0,_>>>=0,r1(async()=>{var g=[];if(_){var v=(k(),U)[_>>>2>>>0];g.length=d+1,g[d]=new Promise(z=>setTimeout(z,v,0))}else g.length=d;for(var T=0;T<d;++T){var O=qn(u+8*T);if(!(O in wl))return O;g[T]=wl[O]}return g=await Promise.race(g),delete wl[g],g})}var Tp,Mp={},m1=()=>{if(!Tp){var u,d={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(u in Mp)Mp[u]===void 0?delete d[u]:d[u]=Mp[u];var _=[];for(u in d)_.push(`${u}=${d[u]}`);Tp=_}return Tp};function h1(u,d){if(n)return Re(19,1,u,d);u>>>=0,d>>>=0;var _,g=0,v=0;for(_ of m1()){var T=d+g;(k(),L)[u+v>>>2>>>0]=T,g+=xr(_,T,1/0)+1,v+=4}return 0}function _1(u,d){if(n)return Re(20,1,u,d);u>>>=0,d>>>=0;var _=m1();for(var g of((k(),L)[u>>>2>>>0]=_.length,u=0,_))u+=yr(g)+1;return(k(),L)[d>>>2>>>0]=u,0}function g1(u){return n?Re(21,1,u):52}function w1(u,d,_,g){return n?Re(22,1,u,d,_,g):52}function x1(u,d,_,g){return n?Re(23,1,u,d,_,g):70}var UM=[null,[],[]];function y1(u,d,_,g){if(n)return Re(24,1,u,d,_,g);d>>>=0,_>>>=0,g>>>=0;for(var v=0,T=0;T<_;T++){var O=(k(),L)[d>>>2>>>0],z=(k(),L)[d+4>>>2>>>0];d+=8;for(var B=0;B<z;B++){var K=u,Me=(k(),J)[O+B>>>0],Le=UM[K];Me===0||Me===10?((K===1?S:M)(Rb(Le)),Le.length=0):Le.push(Me)}v+=z}return(k(),L)[g>>>2>>>0]=v,0}function BM(u){return u>>>0}function FM(u,d){return f1(re(u>>>0).limits,d>>>0),1}function jM(u,d){return re(u>>>0).features.has(d1[d])}function GM(u){return BigInt(re(u>>>0).size)}function qM(u){return BigInt(re(u>>>0).usage)}function WM(u,d){if(u>>>=0,d>>>=0){var _=vr(d+4);_={label:_,timestampWrites:d=(d=(k(),L)[d+12>>>2>>>0])!==0?{querySet:re((k(),L)[d+4>>>2>>>0]),beginningOfPassWriteIndex:(k(),L)[d+8>>>2>>>0],endOfPassWriteIndex:(k(),L)[d+12>>>2>>>0]}:void 0}}return d=re(u),u=O1(0),_=d.beginComputePass(_),ft[u>>>0]=_,u}function VM(u,d,_,g,v,T){_=bt(_),v=bt(v),T=bt(T),re(u>>>0).copyBufferToBuffer(re(d>>>0),_,re(g>>>0),v,T)}function HM(u){var d=re(u>>>0);return u=M1(0),d=d.finish(),ft[u>>>0]=d,u}function XM(u,d,_,g,v,T){T=bt(T),re(u>>>0).resolveQuerySet(re(d>>>0),_,g,re(v>>>0),T)}function KM(u,d,_,g){re(u>>>0).dispatchWorkgroups(d,_,g)}function YM(u,d,_){_=bt(_),re(u>>>0).dispatchWorkgroupsIndirect(re(d>>>0),_)}function QM(u){re(u>>>0).end()}function JM(u,d,_,g,v){g>>>=0,v>>>=0,u=re(u>>>0),_=re(_>>>0),g==0?u.setBindGroup(d,_):u.setBindGroup(d,_,(k(),L),v>>>2,g)}function ZM(u,d){re(u>>>0).setPipeline(re(d>>>0))}function eS(u,d,_){re(u>>>0).Ee(re(d>>>0),_)}function tS(u,d){var _=re(u>>>0);return u=T1(0),d=_.getBindGroupLayout(d),ft[u>>>0]=d,u}function rS(u,d){function _(v){var T=(k(),L)[v+8>>>2>>>0],O=(k(),L)[v+32>>>2>>>0],z=(k(),L)[v+36>>>2>>>0],B=0;return wM(v,{327681:K=>{B=(k(),L)[K+8>>>2>>>0]}}),T?((O=qn(v+24))==-1&&(O=void 0),T={buffer:re(T),offset:qn(v+16),size:O}):T=re(O||z||B),{binding:(k(),L)[v+4>>>2>>>0],resource:T}}u>>>=0,d={label:vr(4+(d>>>=0)),layout:re((k(),L)[d+12>>>2>>>0]),entries:(function(v,T){for(var O=[],z=0;z<v;++z)O.push(_(T+40*z));return O})((k(),L)[d+16>>>2>>>0],(k(),L)[d+20>>>2>>>0])},u=re(u);var g=A1(0);return gM(g,u.createBindGroup(d)),g}function sS(u,d){var _;return u>>>=0,(d>>>=0)&&(_={label:vr(d+4)}),d=re(u),u=S1(0),_=d.createCommandEncoder(_),ft[u>>>0]=_,u}function nS(u,d){u>>>=0,d>>>=0,d={type:kM[(k(),U)[d+12>>>2>>>0]],count:(k(),L)[d+16>>>2>>>0]};var _=re(u);return u=I1(0),d=_.createQuerySet(d),ft[u>>>0]=d,u}function oS(u,d){u=re(u>>>0).adapterInfo,d>>>=0,(k(),L)[d+52>>>2>>>0]=u.subgroupMinSize,(k(),L)[d+56>>>2>>>0]=u.subgroupMaxSize;var _=u.vendor+u.architecture+u.device+u.description,g=yr(_)+1,v=Ks(g);return v&&xr(_,v,g),_=v,g=yr(u.vendor),xl(d+4,_,g),_+=g,g=yr(u.architecture),xl(d+12,_,g),_+=g,g=yr(u.device),xl(d+20,_,g),xl(d+28,_+g,yr(u.description)),(k(),U)[d+36>>>2>>>0]=2,u=u.isFallbackAdapter?3:4,(k(),U)[d+40>>>2>>>0]=u,(k(),L)[d+44>>>2>>>0]=0,(k(),L)[d+48>>>2>>>0]=0,1}var aS={"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 iS(u,d){d>>>=0;var _=re(u>>>0);u=Ks(4*_.features.size);var g=0,v=0;for(let T of _.features)0<=(_=aS[T])&&((k(),U)[u+g>>>2>>>0]=_,g+=4,v++);(k(),L)[d+4>>>2>>>0]=u,(k(),L)[d>>>2>>>0]=v}function lS(u,d){return f1(re(u>>>0).limits,d>>>0),1}function cS(u,d){re(u>>>0).pushErrorScope(yM[d])}function uS(u,d,_){d>>>=0,_>>>=0,u=re(u>>>0),d=Array.from((k(),U).subarray(_>>>2>>>0,_+4*d>>>2>>>0),g=>re(g)),u.submit(d)}function pS(u,d,_,g,v){_=bt(_),g>>>=0,v>>>=0,u=re(u>>>0),d=re(d>>>0),g=(k(),J).subarray(g>>>0,g+v>>>0),u.writeBuffer(d,_,g,0,v)}n||(function(){for(var u=e.numThreads-1;u--;)Ob();Te.push(async()=>{var d=(async function(){if(!n)return Promise.all(tt.map(Sb))})();xe++,await d,--xe==0&&qe&&(d=qe,qe=null,d())})})(),n||(Lr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),pe()),e.wasmBinary&&(f=e.wasmBinary),e.stackSave=()=>le(),e.stackRestore=u=>ie(u),e.stackAlloc=u=>bl(u),e.setValue=function(u,d,_="i8"){switch(_.endsWith("*")&&(_="*"),_){case"i1":case"i8":(k(),V)[u>>>0]=d;break;case"i16":(k(),X)[u>>>1>>>0]=d;break;case"i32":(k(),U)[u>>>2>>>0]=d;break;case"i64":(k(),I)[u>>>3>>>0]=BigInt(d);break;case"float":(k(),ne)[u>>>2>>>0]=d;break;case"double":(k(),ae)[u>>>3>>>0]=d;break;case"*":(k(),L)[u>>>2>>>0]=d;break;default:Pe(`invalid type for setValue: ${_}`)}},e.getValue=function(u,d="i8"){switch(d.endsWith("*")&&(d="*"),d){case"i1":case"i8":return(k(),V)[u>>>0];case"i16":return(k(),X)[u>>>1>>>0];case"i32":return(k(),U)[u>>>2>>>0];case"i64":return(k(),I)[u>>>3>>>0];case"float":return(k(),ne)[u>>>2>>>0];case"double":return(k(),ae)[u>>>3>>>0];case"*":return(k(),L)[u>>>2>>>0];default:Pe(`invalid type for getValue: ${d}`)}},e.UTF8ToString=Vs,e.stringToUTF8=xr,e.lengthBytesUTF8=yr;var b1,v1,Sp,yl,Yt,Ks,k1,E1,A1,T1,M1,S1,O1,I1,C1,P1,L1,Op,Ip,Cp,Pp,Wn,Lp,N1,Np,z1,R1,$1,zp,D1,U1,Rp,_e,Vn,B1,ie,bl,le,F1,$p,j1,G1,q1,Dp,W1,V1,H1,X1,K1,Y1,Q1,J1,Z1,ev,tv,rv,sv,nv,ov,av,iv,lv,cv,uv,pv,fv,dv,mv,hv,_v,gv,wv,xv,yv,bv,vv,kv,Ev,Av,Tv,Mv,Sv,Ov,kr,fS=[Pr,cs,Pb,$b,Db,Ub,Bb,Fb,jb,Gb,qb,Wb,Vb,Hb,Xb,Kb,i1,l1,c1,h1,_1,g1,w1,x1,y1],Up={922732:(u,d,_,g,v)=>{if(e===void 0||!e.Uc)return 1;if((u=Vs(Number(u>>>0))).startsWith("./")&&(u=u.substring(2)),!(u=e.Uc.get(u)))return 2;if(d=Number(d>>>0),_=Number(_>>>0),g=Number(g>>>0),d+_>u.byteLength)return 3;try{let T=u.subarray(d,d+_);switch(v){case 0:(k(),J).set(T,g>>>0);break;case 1:e.ad?e.ad(g,T):e.oe(g,T);break;default:return 4}return 0}catch{return 4}},923556:(u,d,_)=>{e.Sd(u,(k(),J).subarray(d>>>0,d+_>>>0))},923620:()=>e.me(),923662:u=>{e.jd(u)},923699:()=>typeof wasmOffsetConverter<"u"};function dS(u,d,_,g){var v=le();try{return J1(u,d,_,g)}catch(T){if(ie(v),T!==T+0)throw T;_e(1,0)}}function mS(u,d,_){var g=le();try{return K1(u,d,_)}catch(v){if(ie(g),v!==v+0)throw v;_e(1,0)}}function hS(u,d,_){var g=le();try{q1(u,d,_)}catch(v){if(ie(g),v!==v+0)throw v;_e(1,0)}}function _S(u,d){var _=le();try{return Dp(u,d)}catch(g){if(ie(_),g!==g+0)throw g;_e(1,0)}}function gS(u){var d=le();try{W1(u)}catch(_){if(ie(d),_!==_+0)throw _;_e(1,0)}}function wS(u,d,_,g,v,T,O){var z=le();try{return X1(u,d,_,g,v,T,O)}catch(B){if(ie(z),B!==B+0)throw B;_e(1,0)}}function xS(u,d){var _=le();try{Z1(u,d)}catch(g){if(ie(_),g!==g+0)throw g;_e(1,0)}}function yS(u,d,_,g,v,T){var O=le();try{V1(u,d,_,g,v,T)}catch(z){if(ie(O),z!==z+0)throw z;_e(1,0)}}function bS(u,d,_,g){var v=le();try{Q1(u,d,_,g)}catch(T){if(ie(v),T!==T+0)throw T;_e(1,0)}}function vS(u,d,_,g,v,T,O){var z=le();try{tv(u,d,_,g,v,T,O)}catch(B){if(ie(z),B!==B+0)throw B;_e(1,0)}}function kS(u,d,_,g,v,T,O){var z=le();try{rv(u,d,_,g,v,T,O)}catch(B){if(ie(z),B!==B+0)throw B;_e(1,0)}}function ES(u,d,_,g,v,T,O,z){var B=le();try{pv(u,d,_,g,v,T,O,z)}catch(K){if(ie(B),K!==K+0)throw K;_e(1,0)}}function AS(u,d,_,g,v,T,O,z,B,K,Me,Le){var Be=le();try{sv(u,d,_,g,v,T,O,z,B,K,Me,Le)}catch(se){if(ie(Be),se!==se+0)throw se;_e(1,0)}}function TS(u,d,_,g,v){var T=le();try{return ev(u,d,_,g,v)}catch(O){if(ie(T),O!==O+0)throw O;_e(1,0)}}function MS(u,d,_,g,v){var T=le();try{H1(u,d,_,g,v)}catch(O){if(ie(T),O!==O+0)throw O;_e(1,0)}}function SS(u,d,_,g,v,T,O,z){var B=le();try{Y1(u,d,_,g,v,T,O,z)}catch(K){if(ie(B),K!==K+0)throw K;_e(1,0)}}function OS(u){var d=le();try{return fv(u)}catch(_){if(ie(d),_!==_+0)throw _;_e(1,0)}}function IS(u,d,_){var g=le();try{return dv(u,d,_)}catch(v){if(ie(g),v!==v+0)throw v;_e(1,0)}}function CS(u,d){var _=le();try{return Av(u,d)}catch(g){if(ie(_),g!==g+0)throw g;return _e(1,0),0n}}function PS(u,d,_,g,v){var T=le();try{mv(u,d,_,g,v)}catch(O){if(ie(T),O!==O+0)throw O;_e(1,0)}}function LS(u){var d=le();try{return nv(u)}catch(_){if(ie(d),_!==_+0)throw _;return _e(1,0),0n}}function NS(u,d,_,g,v,T){var O=le();try{return cv(u,d,_,g,v,T)}catch(z){if(ie(O),z!==z+0)throw z;_e(1,0)}}function zS(u,d,_,g,v,T){var O=le();try{return hv(u,d,_,g,v,T)}catch(z){if(ie(O),z!==z+0)throw z;_e(1,0)}}function RS(u,d,_,g,v,T){var O=le();try{return _v(u,d,_,g,v,T)}catch(z){if(ie(O),z!==z+0)throw z;_e(1,0)}}function $S(u,d,_,g,v,T,O,z){var B=le();try{return uv(u,d,_,g,v,T,O,z)}catch(K){if(ie(B),K!==K+0)throw K;_e(1,0)}}function DS(u,d,_,g,v){var T=le();try{return gv(u,d,_,g,v)}catch(O){if(ie(T),O!==O+0)throw O;return _e(1,0),0n}}function US(u,d,_,g){var v=le();try{return wv(u,d,_,g)}catch(T){if(ie(v),T!==T+0)throw T;_e(1,0)}}function BS(u,d,_,g){var v=le();try{return xv(u,d,_,g)}catch(T){if(ie(v),T!==T+0)throw T;_e(1,0)}}function FS(u,d,_,g,v,T,O,z,B,K,Me,Le){var Be=le();try{return yv(u,d,_,g,v,T,O,z,B,K,Me,Le)}catch(se){if(ie(Be),se!==se+0)throw se;_e(1,0)}}function jS(u,d,_,g,v,T,O,z,B,K,Me){var Le=le();try{bv(u,d,_,g,v,T,O,z,B,K,Me)}catch(Be){if(ie(Le),Be!==Be+0)throw Be;_e(1,0)}}function GS(u,d,_,g,v,T,O,z,B,K,Me,Le,Be,se,it,kt){var lt=le();try{vv(u,d,_,g,v,T,O,z,B,K,Me,Le,Be,se,it,kt)}catch(fs){if(ie(lt),fs!==fs+0)throw fs;_e(1,0)}}function qS(u,d,_,g){var v=le();try{return kv(u,d,_,g)}catch(T){if(ie(v),T!==T+0)throw T;_e(1,0)}}function WS(u,d,_,g,v){var T=le();try{return Ev(u,d,_,g,v)}catch(O){if(ie(T),O!==O+0)throw O;_e(1,0)}}function VS(u,d,_){var g=le();try{return av(u,d,_)}catch(v){if(ie(g),v!==v+0)throw v;return _e(1,0),0n}}function HS(u,d,_){var g=le();try{return ov(u,d,_)}catch(v){if(ie(g),v!==v+0)throw v;_e(1,0)}}function XS(u,d,_){var g=le();try{return iv(u,d,_)}catch(v){if(ie(g),v!==v+0)throw v;_e(1,0)}}function KS(u,d,_,g){var v=le();try{lv(u,d,_,g)}catch(T){if(ie(v),T!==T+0)throw T;_e(1,0)}}function vl(){if(0<xe)qe=vl;else if(n)w?.(e),Fe();else{for(var u=Te;0<u.length;)u.shift()(e);0<xe?qe=vl:(e.calledRun=!0,C||(Fe(),w?.(e)))}}return n||(kr=await Je(),vl()),e.PTR_SIZE=4,e.webgpuInit=u=>{let d=new WeakMap,_,g,v=1;e.webgpuRegisterDevice=z=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(z){var B=d.get(z);if(!B){let K=((Me,Le=0)=>{var Be=L1(Le);return Le=P1(Le,Be),ft[Be>>>0]=Me.queue,ft[Le>>>0]=Me,Le})(z,B=E1(0));B=[v++,B,K],d.set(z,B)}return _=z,g=B[0],B}_=void 0,g=0};let T=new Map;e.webgpuOnCreateSession=z=>{if(g!==void 0){var B=g;if(g=void 0,z){let K=Sp(B);T.set(z,K),B===0&&u(_??re(K))}_=void 0}},e.webgpuOnReleaseSession=z=>{T.delete(z)};let O=Symbol("gpuBufferMetadata");e.webgpuRegisterBuffer=(z,B,K)=>{if(K)return z[O]=[K,NaN],K;if(K=z[O])return K[1]++,K[0];if((B=T.get(B))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return B=((Me,Le=0)=>(Me.mapState==="unmapped"||Pe(),Le=C1(Le),ft[Le>>>0]=Me,Le))(z,B),z[O]=[B,1],B},e.webgpuUnregisterBuffer=z=>{let B=z[O];if(!B)throw Error("Buffer is not registered");B[1]--,B[1]===0&&(k1(B[0]),delete z[O])},e.webgpuGetBuffer=z=>re(z),e.webgpuCreateDownloader=(z,B,K)=>{if((K=T.get(K))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let Me=re(K),Le=16*Math.ceil(Number(B)/16);return async()=>{let Be=Me.createBuffer({size:Le,usage:9});try{let se=Me.createCommandEncoder();return se.copyBufferToBuffer(z,0,Be,0,Le),Me.queue.submit([se.finish()]),await Be.mapAsync(GPUMapMode.READ),Be.getMappedRange().slice(0,B)}finally{Be.destroy()}}},e.ad=(z,B)=>{var K=B.buffer;let Me=B.byteOffset,Le=B.byteLength;if(B=16*Math.ceil(Number(Le)/16),z=re(z),!_){var Be=Sp(g);_=re(Be)}let se=(Be=_.createBuffer({mappedAtCreation:!0,size:B,usage:6})).getMappedRange();new Uint8Array(se).set(new Uint8Array(K,Me,Le)),Be.unmap(),(K=_.createCommandEncoder()).copyBufferToBuffer(Be,0,z,0,B),_.queue.submit([K.finish()]),Be.destroy()}},e.webnnInit=u=>{let d=u[0];[e.me,e.jd,e.webnnEnsureTensor,e.Sd,e.webnnDownloadTensor,e.le,e.webnnEnableTraceEvent]=u.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,v,T)=>d.registerMLTensor(_,g,v,T),e.webnnCreateMLContext=_=>d.createMLContext(_),e.webnnRegisterMLConstant=(_,g,v,T,O,z)=>d.registerMLConstant(_,g,v,T,O,e.Uc,z),e.webnnRegisterGraphInput=d.registerGraphInput.bind(d),e.webnnIsGraphInput=d.isGraphInput.bind(d),e.webnnRegisterGraphOutput=d.registerGraphOutput.bind(d),e.webnnIsGraphOutput=d.isGraphOutput.bind(d),e.webnnCreateTemporaryTensor=d.createTemporaryTensor.bind(d),e.webnnIsGraphInputOutputTypeSupported=d.isGraphInputOutputTypeSupported.bind(d)},te?e:new Promise((u,d)=>{w=u,x=d})}var ME,Nk,$P=ye(()=>{"use strict";ME=Lk,Nk=globalThis.self?.name?.startsWith("em-pthread"),Nk&&Lk()}),sf,yf,zk,zt,SE,Nl,Rk,$k,nf,Dk,of,OE,af,IE,Of=ye(()=>{"use strict";Sf(),sf=typeof location>"u"?void 0:location.origin,yf=import.meta.url>"file:"&&import.meta.url<"file;",zk=()=>{if(yf){let t=URL;return new URL(new t("ort.webgpu.bundle.min.mjs",import.meta.url).href,sf).href}return import.meta.url},zt=zk(),SE=()=>{if(zt&&!zt.startsWith("blob:"))return zt.substring(0,zt.lastIndexOf("/")+1)},Nl=(t,e)=>{try{let r=e??zt;return(r?new URL(t,r):new URL(t)).origin===sf}catch{return!1}},Rk=(t,e)=>{let r=e??zt;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},$k=(t,e)=>`${e??"./"}${t}`,nf=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},Dk=async t=>(await import(t)).default,of=(RP(),Bl(EE)).default,OE=async()=>{if(!zt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Nl(zt))return[void 0,of()];let t=await nf(zt);return[t,of(t)]},af=($P(),Bl(TE)).default,IE=async(t,e,r,s)=>{let n=af&&!(t||e);if(n)if(zt)n=Nl(zt)||s&&!r;else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,af];{let o="ort-wasm-simd-threaded.asyncify.mjs",a=t??Rk(o,e),i=r&&a&&!Nl(a,e),l=i?await nf(a):a??$k(o,e);return[i?l:void 0,await Dk(l)]}}}),lf,zl,ro,cf,Uk,Bk,Fk,If,Ue,Os=ye(()=>{"use strict";Of(),zl=!1,ro=!1,cf=!1,Uk=()=>{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}},Bk=()=>{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}},Fk=()=>{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}},If=async t=>{if(zl)return Promise.resolve();if(ro)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(cf)throw new Error("previous call to 'initializeWebAssembly()' failed.");ro=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!Fk())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Bk())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=Uk();r>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),t.numThreads=r=1);let n=t.wasmPaths,o=typeof n=="string"?n:void 0,a=n?.mjs,i=a?.href??a,l=n?.wasm,c=l?.href??l,p=t.wasmBinary,[f,m]=await IE(i,o,r>1,!!p||!!c),h=!1,w=[];if(e>0&&w.push(new Promise(x=>{setTimeout(()=>{h=!0,x()},e)})),w.push(new Promise((x,b)=>{let E={numThreads:r};if(p)E.wasmBinary=p,E.locateFile=A=>A;else if(c||o)E.locateFile=A=>c??o+A;else if(i&&i.indexOf("blob:")!==0)E.locateFile=A=>new URL(A,i).href;else if(f){let A=SE();A&&(E.locateFile=S=>A+S)}m(E).then(A=>{ro=!1,zl=!0,lf=A,x(),f&&URL.revokeObjectURL(f)},A=>{ro=!1,cf=!0,b(A)})})),await Promise.race(w),h)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},Ue=()=>{if(zl&&lf)return lf;throw new Error("WebAssembly is not initialized yet.")}}),Rt,jl,Ie,Cf=ye(()=>{"use strict";Os(),Rt=(t,e)=>{let r=Ue(),s=r.lengthBytesUTF8(t)+1,n=r._malloc(s);return r.stringToUTF8(t,n,s),e.push(n),n},jl=(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")jl(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)}}}),CE,DP=ye(()=>{"use strict";Os(),Cf(),CE=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=Rt(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&&jl(t.extra,"",new WeakSet,(a,i)=>{let l=Rt(a,s),c=Rt(i,s);e._OrtAddRunConfigEntry(r,l,c)!==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}}}),jk,Gk,qk,Rl,$r,Wk,PE,UP=ye(()=>{"use strict";Os(),Cf(),jk=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}`)}},Gk=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},qk=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)},Rl=(t,e,r,s)=>{let n=Rt(e,s),o=Rt(r,s);Ue()._OrtAddSessionConfigEntry(t,n,o)!==0&&Ie(`Can't set a session config entry: ${e} - ${r}.`)},$r=(t,e,r,s)=>{let n=Rt(e,s),o=Rt(r,s);t.push([n,o])},Wk=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&&Rl(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&&$r(a,"enableGraphCapture","1",r),typeof h.preferredLayout=="string"&&$r(a,"preferredLayout",h.preferredLayout,r),h.forceCpuNodeNames){let x=Array.isArray(h.forceCpuNodeNames)?h.forceCpuNodeNames:[h.forceCpuNodeNames];$r(a,"forceCpuNodeNames",x.join(`
13
- `),r)}h.validationMode&&$r(a,"validationMode",h.validationMode,r)}let m=Ue().webgpuRegisterDevice(f);if(m){let[h,w,x]=m;$r(a,"deviceId",h.toString(),r),$r(a,"webgpuInstance",w.toString(),r),$r(a,"webgpuDevice",x.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=Rt(o,r),l=a.length,c=0,p=0;if(l>0){c=Ue()._malloc(l*Ue().PTR_SIZE),r.push(c),p=Ue()._malloc(l*Ue().PTR_SIZE),r.push(p);for(let f=0;f<l;f++)Ue().setValue(c+f*Ue().PTR_SIZE,a[f][0],"*"),Ue().setValue(p+f*Ue().PTR_SIZE,a[f][1],"*")}await Ue()._OrtAppendExecutionProvider(t,i,c,p,l)!==0&&Ie(`Can't append execution provider: ${o}.`)}},PE=async t=>{let e=Ue(),r=0,s=[],n=t||{};qk(n);try{let o=jk(n.graphOptimizationLevel??"all"),a=Gk(n.executionMode??"sequential"),i=typeof n.logId=="string"?Rt(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let p=typeof n.optimizedModelFilePath=="string"?Rt(n.optimizedModelFilePath,s):0;if(r=e._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,l,c,p),r===0&&Ie("Can't create session options."),n.executionProviders&&await Wk(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);Rl(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=Rt(f,s);e._OrtAddFreeDimensionOverride(r,h,m)!==0&&Ie(`Can't set a free dimension override: ${f} - ${m}.`)}return n.extra!==void 0&&jl(n.extra,"",new WeakSet,(f,m)=>{Rl(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}}}),Es,Ul,rn,io,Gl,Pf,Lf,bf,sn=ye(()=>{"use strict";Es=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}`)}},Ul=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}`)}},rn=(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},io=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}`)}},Gl=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}`)}},Pf=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",Lf=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",bf=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}`)}}}),Nf,LE=ye(()=>{"use strict";Sf(),Nf=async t=>{if(typeof t=="string"){let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let r=e.headers.get("Content-Length"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${t}, no response body.`);let n=e.body.getReader(),o;try{o=new ArrayBuffer(s)}catch(i){if(i instanceof RangeError){let l=Math.ceil(s/65536);o=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let a=0;for(;;){let{done:i,value:l}=await n.read();if(i)break;let c=l.byteLength;new Uint8Array(o,a,c).set(l),a+=c}return new Uint8Array(o,0,s)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),NE,BP=ye(()=>{"use strict";sn(),NE=(t,e)=>new(io(e))(t)}),Vk,Hk,Xk,Kk,zE,Yk,xt,RE=ye(()=>{"use strict";sn(),Vk=["V","I","W","E","F"],Hk=(t,e)=>{console.log(`[${Vk[t]},${new Date().toISOString()}]${e}`)},zE=(t,e)=>{Xk=t,Kk=e},Yk=(t,e)=>{let r=Gl(t),s=Gl(Xk);r>=s&&Hk(r,typeof e=="function"?e():e)},xt=(...t)=>{Kk&&Yk(...t)}}),uf,vf,pf,Qk,ff,Jk,df,mf,hf,Zk,$E,FP=ye(()=>{"use strict";sn(),RE(),uf=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),vf=(t,e)=>{if(e==="int32")return t;let r=uf.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(io(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'`)}},pf=(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,ff=()=>Qk++,Jk=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),df=(t,e)=>{let r=uf.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},mf=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 df(this.dataType,this.tensorShape)}destroy(){xt("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=pf(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}},hf=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=Jk.get(e),!a||o?.input.dataTypes.includes(a))throw new Error(`WebNN backend does not support data type: ${e}`);xt("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!==df(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=vf(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 xt("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?pf(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()}},Zk=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=ff();return this.tensorTrackersById.set(t,new hf(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){xt("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){xt("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=ff(),a=new mf({sessionId:t,context:n,tensor:e,dataType:r,shape:s});return this.tensorTrackersById.set(o,new hf(this,a)),this.externalTensors.add(a),o}async getCachedTensor(t,e,r,s,n,o,a){let i=this.getMLContext(t);for(let[c,p]of this.freeTensors.entries())if(p.canReuseTensor(i,e,r)){xt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}`);let f=this.freeTensors.splice(c,1)[0];return f.sessionId=t,f}xt("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 mf({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)}},$E=(...t)=>new Zk(...t)}),DE={};lo(DE,{WebNNBackend:()=>UE});var so,eE,UE,jP=ye(()=>{"use strict";sn(),Os(),BP(),FP(),RE(),so=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),eE=(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])},UE=class{constructor(t){this.tensorManager=$E(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,zE(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(t){xt("verbose",()=>`[WebNN] onRunStart {sessionId: ${t}}`),this.activeSessionId=t}onRunEnd(t){xt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${t}}`);let e=this.temporarySessionTensorIds.get(t);if(e){for(let r of e)xt("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=>eE(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){xt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,e,r,s,n){let o=so.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){xt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${e}, shape: ${r}}`);let s=so.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");xt("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 NE(r,e)}}registerMLTensor(t,e,r,s){let n=so.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.registerTensor(t,e,n,s);return xt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(t,e,r,s,n,o,a=!1){if(!o)throw new Error("External mounted files are not available.");let i=t;t.startsWith("./")&&(i=t.substring(2));let l=o.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(e+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(e,e+r).buffer,p;switch(n.dataType){case"float32":p=new Float32Array(c);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":p=new Int32Array(c);break;case"uint32":p=new Uint32Array(c);break;case"int64":if(a){let f=vf(new Uint8Array(c),"int64");p=new Int32Array(f.buffer),n.dataType="int32"}else p=new BigInt64Array(c);break;case"uint64":p=new BigUint64Array(c);break;case"int8":p=new Int8Array(c);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return xt("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=so.get(Es(e)),n=this.mlOpSupportLimitsBySessionId.get(t);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),tE,zf,Rf,Dr,rE,_f,ql,$f,Df,gf,Uf,Bf,Ff,BE=ye(()=>{"use strict";Ss(),DP(),UP(),sn(),Os(),Cf(),LE(),tE=(t,e)=>{Ue()._OrtInit(t,e)!==0&&Ie("Can't initialize onnxruntime.")},zf=async t=>{tE(t.wasm.numThreads,Gl(t.logLevel))},Rf=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(jP(),Bl(DE)).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])}},Dr=new Map,rE=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)}},_f=(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 c=r.HEAPU32[n/4+1],p=[];for(let f=0;f<c;f++){let m=Number(r.getValue(n+8+f*o,"*"));p.push(m!==0?r.UTF8ToString(m):Number(r.getValue(n+8+(f+c)*o,"*")))}return[i,l,p]}finally{r.stackRestore(s),n!==0&&r._OrtFree(n)}},ql=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]},$f=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]=ql(t);let o=0,a=0,i=0,l=[],c=[],p=[];try{if([a,l]=await PE(e),e?.externalData&&n.mountExternalData){let M=[];for(let C of e.externalData){let P=typeof C=="string"?C:C.path;M.push(Nf(typeof C=="string"?C:C.data).then(k=>{n.mountExternalData(P,k)}))}await Promise.all(M)}for(let M of e?.executionProviders??[])if((typeof M=="string"?M:M.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof M!="string"){let C=M,P=C?.context,k=C?.gpuDevice,F=C?.deviceType,H=C?.powerPreference;P?n.currentContext=P:k?n.currentContext=await n.webnnCreateMLContext(k):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]=rE(o),h=!!e?.enableGraphCapture,w=[],x=[],b=[],E=[],A=[];for(let M=0;M<f;M++){let[C,P,k]=_f(o,M);C===0&&Ie("Can't get an input name."),c.push(C);let F=n.UTF8ToString(C);w.push(F),b.push(P===0?{name:F,isTensor:!1}:{name:F,isTensor:!0,type:Ul(P),shape:k})}for(let M=0;M<m;M++){let[C,P,k]=_f(o,M+f);C===0&&Ie("Can't get an output name."),p.push(C);let F=n.UTF8ToString(C);x.push(F),E.push(P===0?{name:F,isTensor:!1}:{name:F,isTensor:!0,type:Ul(P),shape:k});{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(M=>M==="gpu-buffer"||M==="ml-tensor"||M==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(o),i===0&&Ie("Can't create IO binding."),S={handle:i,outputPreferredLocations:A,outputPreferredLocationsEncoded:A.map(M=>M==="ml-tensor-cpu-output"?"ml-tensor":M).map(M=>bf(M))}),Dr.set(o,[o,c,p,S,h,!1]),[o,w,x,b,E]}catch(f){throw c.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?.()}},Df=t=>{let e=Ue(),r=Dr.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."),Dr.delete(t)},gf=async(t,e,r,s,n,o,a=!1)=>{if(!t){e.push(0);return}let i=Ue(),l=i.PTR_SIZE,c=t[0],p=t[1],f=t[3],m=f,h,w;if(c==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&f!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let E=t[2].gpuBuffer;w=rn(Es(c),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=rn(Es(c),p);let A=i.webnnRegisterMLTensor;if(!A)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');h=A(s,E,Es(c),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,Rt(E[A],r),"*")}}else{let A=i.webnnIsGraphInput,S=i.webnnIsGraphOutput;if(c!=="string"&&A&&S){let M=i.UTF8ToString(n);if(A(s,M)||S(s,M)){let C=Es(c);w=rn(C,p),m="ml-tensor";let P=i.webnnCreateTemporaryTensor,k=i.webnnUploadTensor;if(!P||!k)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let F=await P(s,C,p);k(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(),b=i.stackAlloc(4*p.length);try{p.forEach((A,S)=>i.setValue(b+S*l,A,l===4?"i32":"i64"));let E=i._OrtCreateTensor(Es(c),h,w,b,p.length,bf(m));E===0&&Ie(`Can't create tensor for input/output. session=${s}, index=${o}.`),e.push(E)}finally{i.stackRestore(x)}},Uf=async(t,e,r,s,n,o)=>{let a=Ue(),i=a.PTR_SIZE,l=Dr.get(t);if(!l)throw new Error(`cannot run inference. invalid session id: ${t}`);let c=l[0],p=l[1],f=l[2],m=l[3],h=l[4],w=l[5],x=e.length,b=s.length,E=0,A=[],S=[],M=[],C=[],P=[],k=a.stackSave(),F=a.stackAlloc(x*i),H=a.stackAlloc(x*i),V=a.stackAlloc(b*i),J=a.stackAlloc(b*i);try{[E,A]=CE(o),Br("wasm prepareInputOutputTensor");for(let L=0;L<x;L++)await gf(r[L],S,C,t,p[e[L]],e[L],h);for(let L=0;L<b;L++)await gf(n[L],M,C,t,f[s[L]],x+s[L],h);Fr("wasm prepareInputOutputTensor");for(let L=0;L<x;L++)a.setValue(F+L*i,S[L],"*"),a.setValue(H+L*i,p[e[L]],"*");for(let L=0;L<b;L++)a.setValue(V+L*i,M[L],"*"),a.setValue(J+L*i,f[s[L]],"*");if(m&&!w){let{handle:L,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}).`);Br("wasm bindInputsOutputs");for(let I=0;I<x;I++){let N=e[I];await a._OrtBindInput(L,p[N],S[I])!==0&&Ie(`Can't bind input[${I}] for session=${t}.`)}for(let I=0;I<b;I++){let N=s[I];n[I]?.[3]?(P.push(M[I]),a._OrtBindOutput(L,f[N],M[I],0)!==0&&Ie(`Can't bind pre-allocated output[${I}] for session=${t}.`)):a._OrtBindOutput(L,f[N],0,ae[N])!==0&&Ie(`Can't bind output[${I}] to ${ne[I]} for session=${t}.`)}Fr("wasm bindInputsOutputs"),Dr.set(t,[c,p,f,m,h,!0])}a.jsepOnRunStart?.(c),a.webnnOnRunStart?.(c);let X;m?X=await a._OrtRunWithBinding(c,m.handle,b,V,E):X=await a._OrtRun(c,H,F,x,J,b,V,E),X!==0&&Ie("failed to call OrtRun().");let Y=[],U=[];Br("wasm ProcessOutputTensor");for(let L=0;L<b;L++){let ne=Number(a.getValue(V+L*i,"*"));if(ne===M[L]||P.includes(M[L])){Y.push(n[L]),ne!==M[L]&&a._OrtReleaseTensor(ne)!==0&&Ie("Can't release tensor.");continue}let ae=a.stackSave(),I=a.stackAlloc(4*i),N=!1,$,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 ${L}.`);let pe=i===4?"i32":"i64",Fe=Number(a.getValue(I,pe));te=a.getValue(I+i,"*");let Pe=a.getValue(I+i*2,"*"),Mt=Number(a.getValue(I+i*3,pe)),Je=[];for(let Te=0;Te<Mt;Te++)Je.push(Number(a.getValue(Pe+Te*i,pe)));a._OrtFree(Pe)!==0&&Ie("Can't free memory for tensor dims.");let et=Je.reduce((Te,xe)=>Te*xe,1);$=Ul(Fe);let st=m?.outputPreferredLocations[s[L]];if($==="string"){if(st==="gpu-buffer"||st==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Te=[];for(let xe=0;xe<et;xe++){let qe=a.getValue(te+xe*i,"*"),St=a.getValue(te+(xe+1)*i,"*"),be=xe===et-1?void 0:St-qe;Te.push(a.UTF8ToString(qe,be))}Y.push([$,Je,Te,"cpu"])}else if(st==="gpu-buffer"&&et>0){let Te=a.webgpuGetBuffer;if(!Te)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let xe=Te(te),qe=rn(Fe,et);if(qe===void 0||!Pf($))throw new Error(`Unsupported data type: ${$}`);N=!0;{a.webgpuRegisterBuffer(xe,t,te);let St=a.webgpuCreateDownloader(xe,qe,t);Y.push([$,Je,{gpuBuffer:xe,download:async()=>{let be=await St();return new(io($))(be)},dispose:()=>{a._OrtReleaseTensor(ne)!==0&&Ie("Can't release tensor.")}},"gpu-buffer"])}}else if(st==="ml-tensor"&&et>0){let Te=a.webnnEnsureTensor,xe=a.webnnIsGraphInputOutputTypeSupported;if(!Te||!xe)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(rn(Fe,et)===void 0||!Lf($))throw new Error(`Unsupported data type: ${$}`);if(!xe(t,$,!1))throw new Error(`preferredLocation "ml-tensor" for ${$} output is not supported by current WebNN Context.`);let qe=await Te(t,te,Fe,Je,!1);N=!0,Y.push([$,Je,{mlTensor:qe,download:a.webnnCreateMLTensorDownloader(te,$),dispose:()=>{a.webnnReleaseTensorId(te),a._OrtReleaseTensor(ne)}},"ml-tensor"])}else if(st==="ml-tensor-cpu-output"&&et>0){let Te=a.webnnCreateMLTensorDownloader(te,$)(),xe=Y.length;N=!0,U.push((async()=>{let qe=[xe,await Te];return a.webnnReleaseTensorId(te),a._OrtReleaseTensor(ne),qe})()),Y.push([$,Je,[],"cpu"])}else{let Te=io($),xe=new Te(et);new Uint8Array(xe.buffer,xe.byteOffset,xe.byteLength).set(a.HEAPU8.subarray(te,te+xe.byteLength)),Y.push([$,Je,xe,"cpu"])}}finally{a.stackRestore(ae),$==="string"&&te&&a._free(te),N||a._OrtReleaseTensor(ne)}}m&&!h&&(a._OrtClearBoundOutputs(m.handle)!==0&&Ie("Can't clear bound outputs."),Dr.set(t,[c,p,f,m,h,!1]));for(let[L,ne]of await Promise.all(U))Y[L][2]=ne;return Fr("wasm ProcessOutputTensor"),Y}finally{a.webnnOnRunEnd?.(c),a.stackRestore(k),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)),M.forEach(X=>a._OrtReleaseTensor(X)),C.forEach(X=>a._free(X)),E!==0&&a._OrtReleaseRunOptions(E),A.forEach(X=>a._free(X))}},Bf=t=>{let e=Ue(),r=Dr.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)},Ff=t=>{let e=[];for(let r of t){let s=r[2];!Array.isArray(s)&&"buffer"in s&&e.push(s.buffer)}return e}}),Ur,Gt,tn,no,oo,$l,wf,Dl,bs,vs,sE,FE,jE,GE,qE,WE,VE,HE,XE=ye(()=>{"use strict";Ss(),BE(),Os(),Of(),Ur=()=>!!Ve.wasm.proxy&&typeof document<"u",tn=!1,no=!1,oo=!1,Dl=new Map,bs=(t,e)=>{let r=Dl.get(t);r?r.push(e):Dl.set(t,[e])},vs=()=>{if(tn||!no||oo||!Gt)throw new Error("worker not ready")},sE=t=>{switch(t.data.type){case"init-wasm":tn=!1,t.data.err?(oo=!0,wf[1](t.data.err)):(no=!0,wf[0]()),$l&&(URL.revokeObjectURL($l),$l=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=Dl.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}default:}},FE=async()=>{if(!no){if(tn)throw new Error("multiple calls to 'initWasm()' detected.");if(oo)throw new Error("previous call to 'initWasm()' failed.");if(tn=!0,Ur())return new Promise((t,e)=>{Gt?.terminate(),OE().then(([r,s])=>{try{Gt=s,Gt.onerror=o=>e(o),Gt.onmessage=sE,wf=[t,e];let n={type:"init-wasm",in:Ve};!n.in.wasm.wasmPaths&&(r||yf)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href}),Gt.postMessage(n),$l=r}catch(n){e(n)}},e)});try{await If(Ve.wasm),await zf(Ve),no=!0}catch(t){throw oo=!0,t}finally{tn=!1}}},jE=async t=>{if(Ur())return vs(),new Promise((e,r)=>{bs("init-ep",[e,r]);let s={type:"init-ep",in:{epName:t,env:Ve}};Gt.postMessage(s)});await Rf(Ve,t)},GE=async t=>Ur()?(vs(),new Promise((e,r)=>{bs("copy-from",[e,r]);let s={type:"copy-from",in:{buffer:t}};Gt.postMessage(s,[t.buffer])})):ql(t),qE=async(t,e)=>{if(Ur()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return vs(),new Promise((r,s)=>{bs("create",[r,s]);let n={type:"create",in:{model:t,options:{...e}}},o=[];t instanceof Uint8Array&&o.push(t.buffer),Gt.postMessage(n,o)})}else return $f(t,e)},WE=async t=>{if(Ur())return vs(),new Promise((e,r)=>{bs("release",[e,r]);let s={type:"release",in:t};Gt.postMessage(s)});Df(t)},VE=async(t,e,r,s,n,o)=>{if(Ur()){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 vs(),new Promise((a,i)=>{bs("run",[a,i]);let l=r,c={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:s,options:o}};Gt.postMessage(c,Ff(l))})}else return Uf(t,e,r,s,n,o)},HE=async t=>{if(Ur())return vs(),new Promise((e,r)=>{bs("end-profiling",[e,r]);let s={type:"end-profiling",in:t};Gt.postMessage(s)});Bf(t)}}),xf,nE,KE,GP=ye(()=>{"use strict";Ss(),XE(),sn(),Sf(),LE(),xf=(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()}`)}},nE=t=>{switch(t[3]){case"cpu":return new tr(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!Pf(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=t[2];return tr.fromGpuBuffer(r,{dataType:e,dims:t[1],download:s,dispose:n})}case"ml-tensor":{let e=t[0];if(!Lf(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=t[2];return tr.fromMLTensor(r,{dataType:e,dims:t[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},KE=class{async fetchModelAndCopyToWasmMemory(t){return GE(await Nf(t))}async loadModel(t,e){Ts();let r;typeof t=="string"?r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await qE(r,e),Ms()}async dispose(){return WE(this.sessionId)}async run(t,e,r){Ts();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)=>xf(f,()=>`input "${this.inputNames[n[m]]}"`)),l=o.map((f,m)=>f?xf(f,()=>`output "${this.outputNames[a[m]]}"`):null),c=await VE(this.sessionId,n,i,a,l,r),p={};for(let f=0;f<c.length;f++)p[this.outputNames[a[f]]]=o[f]??nE(c[f]);return Ms(),p}startProfiling(){}endProfiling(){HE(this.sessionId)}}}),YE={};lo(YE,{OnnxruntimeWebAssemblyBackend:()=>Ef,initializeFlags:()=>kf,wasmBackend:()=>QE});var kf,Ef,QE,qP=ye(()=>{"use strict";Ss(),XE(),GP(),kf=()=>{(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"?bP("node:os").cpus().length:navigator.hardwareConcurrency;Ve.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Ef=class{async init(t){kf(),await FE(),await jE(t)}async createInferenceSessionHandler(t,e){let r=new KE;return await r.loadModel(t,e),r}},QE=new Ef});Ss();Ss();Ss();var WP="1.25.0-dev.20260228-6e72d31970",VP=kE;{let t=(qP(),Bl(YE)).wasmBackend;As("webgpu",t,5),As("webnn",t,5),As("cpu",t,10),As("wasm",t,10)}Object.defineProperty(Ve.versions,"web",{value:WP,enumerable:!0});async function JE(t){let e=t.split("/").pop(),r;try{if(r=await cr(),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 de.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 ZE(t){let e=await JE(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 eA(t){let e=await JE(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 Gf(t){return Tr(t,["blob:"])}function qf(t){let e;if(typeof location<"u"&&location.href)e=location.href;else if(typeof import.meta<"u"&&import.meta.url)e=import.meta.url;else return t;return new URL(t,e).href}var tA="1.24.2";var rA="warning",Wf={wasm:{},webgl:{},webgpu:{},versions:{common:tA},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}`);rA=t}},get logLevel(){return rA}};Object.defineProperty(Wf,"logLevel",{enumerable:!0});var sA=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let p=o*n,f=0,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 b=0;b<n;b++){let E=(t.data[f++]-c[0])*l[0],A=(t.data[m++]-c[1])*l[1],S=(t.data[h++]-c[2])*l[2],M=w===-1?255:(t.data[w++]-c[3])*l[3];s.fillStyle="rgba("+E+","+A+","+S+","+M+")",s.fillRect(b,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")},nA=(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,c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,h=0,w=1,x=2,b=3,E=0,A=f,S=f*2,M=-1;i==="RGBA"?(E=0,A=f,S=f*2,M=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 C=0;C<o*n;h+=m,w+=m,x+=m,b+=m,C++)s.data[h]=(t.data[E++]-p[0])*c[0],s.data[w]=(t.data[A++]-p[1])*c[1],s.data[x]=(t.data[S++]-p[2])*c[2],s.data[b]=M===-1?255:(t.data[M++]-p[3])*c[3]}else throw new Error("Can not access image data");return s};var Vf=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,m=0,h=1,w=2,x=3,b=0,E=c,A=c*2,S=-1;i==="RGB"&&(f=3,m=0,h=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(b=0,A=c,E=c*2):l==="BGR"&&(A=0,E=c,b=c*2);for(let C=0;C<c;C++,m+=f,w+=f,h+=f,x+=f)p[b++]=(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 ht("float32",p,[1,4,r,s]):new ht("float32",p,[1,3,r,s])},oA=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")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){let p=l();p.width=t.width,p.height=t.height;let f=c(p);if(f!=null){let 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=c(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=c(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,Vf(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,f)=>{let m=l(),h=c(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(Vf(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return Vf(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},aA=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new ht({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},iA=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new ht({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},lA=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new ht({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},cA=(t,e,r)=>new ht({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]});var Is=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),co=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),uA=!1,pA=()=>{if(!uA){uA=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(Is.set("int64",BigInt64Array),co.set(BigInt64Array,"int64")),e&&(Is.set("uint64",BigUint64Array),co.set(BigUint64Array,"uint64")),s?(Is.set("float16",r),co.set(r,"float16")):Is.set("float16",Uint16Array)}};var fA=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},dA=(t,e)=>{switch(t.location){case"cpu":return new ht(t.type,t.data,e);case"cpu-pinned":return new ht({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new ht({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new ht({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new ht({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}};var ht=class{constructor(e,r,s){pA();let n,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,o=e.dims,e.location){case"cpu-pinned":{let i=Is.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,l;if(typeof e=="string")if(n=e,l=s,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{let c=Is.get(e);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&c===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${c.name} as data.`);e==="uint64"||e==="int64"?i=c.from(r,BigInt):i=c.from(r)}else if(r instanceof c)i=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&r instanceof Uint16Array&&c!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${n} tensor's data must be type of ${c}`)}else if(l=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let c=typeof e[0];if(c==="string")n="string",i=e;else if(c==="boolean")n="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(e);else{let c=co.get(e.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=c,i=e}if(l===void 0)l=[i.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");o=l,this.cpuData=i,this.dataLocation="cpu"}let a=fA(o);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=o,this.size=a}static async fromImage(e,r){return oA(e,r)}static fromTexture(e,r){return aA(e,r)}static fromGpuBuffer(e,r){return iA(e,r)}static fromMLTensor(e,r){return lA(e,r)}static fromPinnedBuffer(e,r,s){return cA(e,r,s)}toDataURL(e){return sA(this,e)}toImageData(e){return nA(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return dA(this,e)}};var Wl=ht;var HP=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 gA(t){return t<=It.DEBUG?0:t<=It.INFO?2:t<=It.WARNING||t<=It.ERROR?3:4}var XP={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},qt=[],Hf,on,mA=Symbol.for("onnxruntime");if(mA in globalThis)on=globalThis[mA];else if(ge.IS_NODE_ENV){switch(on=Qp,process.platform){case"win32":qt.push("dml");break;case"linux":process.arch==="x64"&&qt.push("cuda");break;case"darwin":qt.push("coreml");break}qt.push("webgpu"),qt.push("cpu"),Hf=["cpu"]}else on=jf,ge.IS_WEBNN_AVAILABLE&&qt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),ge.IS_WEBGPU_AVAILABLE&&qt.push("webgpu"),qt.push("wasm"),Hf=["wasm"];var KP=on.InferenceSession;function wA(t=null){if(!t)return Hf;switch(t){case"auto":return qt;case"gpu":return qt.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(qt.includes(t))return[HP[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${qt.join(", ")}.`)}var xA=ge.IS_BROWSER_ENV||ge.IS_WEBWORKER_ENV,hA=Promise.resolve(),nn=null;async function YP(){return nn||(de.useWasmCache&&typeof _t?.wasm?.wasmPaths=="object"&&_t?.wasm?.wasmPaths?.wasm&&_t?.wasm?.wasmPaths?.mjs?(nn=(async()=>{let e=_t.wasm.wasmPaths;await Promise.all([e.wasm&&!Gf(e.wasm)?(async()=>{try{let r=await ZE(qf(e.wasm));r&&(_t.wasm.wasmBinary=r)}catch(r){Q.warn("Failed to pre-load WASM binary:",r)}})():Promise.resolve(),e.mjs&&!Gf(e.mjs)?(async()=>{try{let r=await eA(qf(e.mjs));r&&(_t.wasm.wasmPaths.mjs=r)}catch(r){Q.warn("Failed to pre-load WASM factory:",r)}})():Promise.resolve()])})(),nn):(nn=Promise.resolve(),nn))}async function Vl(t,e,r){await YP();let s=gA(de.logLevel??It.WARNING),n=()=>KP.create(t,{logSeverityLevel:s,...e}),o=await(xA?hA=hA.then(n):n());return o.config=r,o}var _A=Promise.resolve();async function Hl(t,e){let r=()=>t.run(e);return await(xA?_A=_A.then(r):r())}function Xl(t){return t instanceof on.Tensor}var _t=on?.env;if(_t?.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&_t.versions?.web&&!_t.wasm.wasmPaths){let t=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${_t.versions.web}/dist/`;_t.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`}}_t.wasm.proxy=!1}_t?.webgpu&&(_t.webgpu.powerPreference="high-performance");function uo(){return _t?.wasm?.proxy}function yA(t){let e=gA(t);_t.logLevel=XP[e]}yA(de.logLevel??It.WARNING);de.backends.onnx={..._t,setLogLevel:yA};var jr=async(t,e,r)=>{let s=await Vl(new Uint8Array(t),e);return(async n=>{let o=uo(),a=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(o?c.clone():c).ort_tensor])),i=await Hl(s,a);return Array.isArray(r)?r.map(l=>new D(i[l])):new D(i[r])})},pr=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=jr([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=jr([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=jr([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=jr([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=jr([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=jr([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=jr([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=jr([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 bA=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"}),Xf=ge.IS_NODE_ENV?"cpu":"wasm";function Kl(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 (${Xf}).`),Xf):Xf}var EA=(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}})(),gt=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),vA=gt.fp32,kA=Object.freeze({[bA.wasm]:gt.q8}),po=Object.freeze({[gt.fp32]:"",[gt.fp16]:"_fp16",[gt.int8]:"_int8",[gt.uint8]:"_uint8",[gt.q8]:"_quantized",[gt.q4]:"_q4",[gt.q4f16]:"_q4f16",[gt.bnb4]:"_bnb4"});function Yl(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===gt.auto){if(s){let l=typeof s=="string"?s:s?.[e];if(l&&l!==gt.auto&&gt.hasOwnProperty(l))return l}i=kA[r]??vA}else o&&gt.hasOwnProperty(o)?i=o:i=kA[r]??vA;return a&&n&&n(`dtype not specified for "${e}". Using the default dtype (${i}) for this device (${r}).`),i}var an=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 Ql=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 fr=new Ql,Cs=Object.freeze({Random:Ql,seed:fr.seed.bind(fr),random:fr.random.bind(fr),gauss:fr.gauss.bind(fr),shuffle:fr.shuffle.bind(fr),choices:fr.choices.bind(fr)}),TA=t=>AA(Cs.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 Xl(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new Wl(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=dr(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 QP(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=dr(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:dr(m,this.dims[p],p,!1),h=h===null?this.dims[p]:dr(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(),c=!0;for(let p=1;p<n.length;++p)if(s[p][0]!==0||s[p][1]!==this.dims[p]){c=!1;break}if(c){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 JP(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=(c,p)=>c+p**e;if(r===null){let c=n.reduce(o,0)**(1/e);return new t(this.type,[c],[])}let[a,i,l]=fo(o,this,r,s);if(e!==1)for(let c=0;c<i.length;++c)i[c]=i[c]**(1/e);return new t(a,i,l)}normalize_(e=2,r=1){r=dr(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,c=a,p=1;l>=0;--l){let f=this.dims[l];if(l!==r){let m=c%f;i+=m*p,p*=this.dims[l]}c=Math.floor(c/f)}n[a]/=o[i]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return Kf(this.dims)}squeeze(e=null){return new t(this.type,this.data,MA(this.dims,e))}squeeze_(e=null){return this.dims=MA(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,SA(this.dims,e))}unsqueeze_(e){return this.dims=SA(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 ec(this,e,r)}min(e=null,r=!1){if(e===null){let a=eo(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=fo((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]=fo((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=eo(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=Kf(s),c=Kf(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/c[h]);f=f%c[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(!an.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,Ck(this.data),this.dims);return new t(e,an[e].from(this.data,r),this.dims)}};function QP(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 JP(t,e){let[r,s]=Ak(t.data,t.dims,e);return new D(t.type,r,s)}function Yf(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=Ek(t.data,[o,a,i],[e,r],s,n);return new D(t.type,l,[o,e,r])}async function Wt(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 pr.nearest_interpolate_4d;else if(r==="bilinear")n=await pr.bilinear_interpolate_4d;else if(r==="bicubic")n=await pr.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 OA(t,e){return await(await pr.matmul)({a:t,b:e})}async function d$(t,e){return await(await pr.rfft)({x:t,a:e})}async function rr(t,e){let r=await pr.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 Jl=t=>new D("int64",t,[t.length]);async function Zl(t,e,r,s,n){return await(await pr.slice)({x:t,s:Jl(e),e:Jl(r),a:Jl(s),t:Jl(n??new Array(s.length).fill(1))})}function IA(t,e){let r=t.data,s=e.data,n=[t.dims[0],t.dims[2]],o=new r.constructor(n[0]*n[1]),[a,i,l]=t.dims,c=0;for(let p=0;p<a;++p){let f=p*l*i;for(let m=0;m<l;++m){let h=0,w=0,x=p*i,b=f+m;for(let A=0;A<i;++A){let S=Number(s[x+A]);w+=S,h+=r[b+A*l]*S}let E=h/w;o[c++]=E}}return new D(t.type,o,n)}function m$(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]=Qf(t,1,0,!0),i=o.data,l=a.data,c=t.data,p=new c.constructor(c.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]=(c[w]-l[f])/(i[f]+r)}}return new D(t.type,p,t.dims)}function MA(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 SA(t,e){return e=dr(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function dr(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=dr(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:c}=t[i];for(let p=0;p<l.length;++p){let f=0;for(let m=c.length-1,h=p,w=1;m>=0;--m){let x=c[m],b=h%x;m===e&&(b+=a),f+=b*w,w*=r[m],h=Math.floor(h/x)}n[f]=l[p]}a+=c[e]}}return new D(o,n,r)}function Vt(t,e=0){return Ee(t.map(r=>r.unsqueeze(e)),e)}function fo(t,e,r,s=!1,n=null){let o=e.data,a=e.dims;r=dr(r,a.length);let i=a.slice();i[r]=1;let l=new o.constructor(o.length/a[r]);n!==null&&l.fill(n);for(let c=0;c<o.length;++c){let p=0;for(let f=a.length-1,m=c,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[c],c,p)}return s||i.splice(r,1),[e.type,l,i]}function Qf(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=dr(e,o.length);let a=ec(t,e,s),i=a.data,[l,c,p]=fo((m,h,w,x)=>m+(h-i[x])**2,t,e,s);for(let m=0;m<c.length;++m)c[m]=Math.sqrt(c[m]/(o[e]-r));return[new D(l,c,p),a]}function ec(t,e=null,r=!1){let s=t.dims,n=t.data;if(e===null){let l=n.reduce((c,p)=>c+p,0);return new D(t.type,[l/n.length],[])}e=dr(e,s.length);let[o,a,i]=fo((l,c)=>l+c,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 Kf(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 Jf(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 Jf(t,e,r,s)}function mo(t,e){return He(t.dims,e)}function at(t){return Jf(t,1n,"int64",BigInt64Array)}function tc(t){return at(t.dims)}function Zf(t){return Jf(t,0n,"int64",BigInt64Array)}function ed(t){return Zf(t.dims)}function h$(t){let e=t.reduce((r,s)=>r*s,1);return new D("float32",Float32Array.from({length:e},()=>Cs.random()),t)}function CA(t){let e=t.reduce((r,s)=>r*s,1);return new D("float32",Float32Array.from({length:e},()=>Cs.gauss()),t)}function PA(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,c=Math.floor(i/8),p=i%8;a[c]|=l<<7-p,r&&p===0&&(a[c]-=128)}return new D(s,a,[t.dims[0],t.dims[1]/8])}async function ln(t){if(!t)throw new Error("modelId is required for get_tokenizer_files");return(await ur(t,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function td(t,e){let r=await ln(t);return await Promise.all(r.map(s=>ct(t,s,!0,e)))}function rd(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 ZP=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function eL(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 tL(t,e){for(let r of Object.keys(t))t[r].length=e}function Ps(t,...e){for(let r of e){if(!Object.hasOwn(t,r))continue;let s=t[r];if(s)if(typeof s=="object"){if(s.__type==="AddedToken")return s.content;throw Error(`Unknown token: ${s}`)}else return s}return null}function rL(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 nk(e,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=Ps(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Ps(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Ps(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Ps(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Ps(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Ps(r,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=r.chat_template??null,Array.isArray(this.chat_template)){let n=Object.create(null);for(let{name:o,template:a}of this.chat_template){if(typeof o!="string"||typeof a!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');n[o]=a}this.chat_template=n}this._compiled_template_cache=new Map;let s=rL(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 td(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 c=Array.isArray(e),p;if(c){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&&tL(p[m],a):n&&eL(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(!c)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=rd(e)),!Array.isArray(e)||e.length===0||!Bv(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:c=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 _k(n),this._compiled_template_cache.set(n,w));let x=Object.create(null);for(let E of ZP){let A=Ps(this.config,E);A&&(x[E]=A)}let b=w.render({messages:e,add_generation_prompt:o,tools:r,documents:s,...x,...h});if(a){let E=this._call(b,{add_special_tokens:!1,padding:i,truncation:l,max_length:c,return_tensor:p,...m});return f?E:E.input_ids}return b}};function cn(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 Hd={};ms(Hd,{AlbertTokenizer:()=>sd,AutoTokenizer:()=>Z,BartTokenizer:()=>nd,BertTokenizer:()=>od,BlenderbotSmallTokenizer:()=>ad,BlenderbotTokenizer:()=>id,BloomTokenizer:()=>ld,CLIPTokenizer:()=>ud,CamembertTokenizer:()=>cd,CodeGenTokenizer:()=>fd,CodeLlamaTokenizer:()=>pd,CohereTokenizer:()=>dd,ConvBertTokenizer:()=>md,DebertaTokenizer:()=>_d,DebertaV2Tokenizer:()=>hd,DistilBertTokenizer:()=>gd,ElectraTokenizer:()=>wd,EsmTokenizer:()=>xd,FalconTokenizer:()=>yd,GPT2Tokenizer:()=>kd,GPTNeoXTokenizer:()=>vd,GemmaTokenizer:()=>bd,HerbertTokenizer:()=>Ed,LlamaTokenizer:()=>Ad,M2M100Tokenizer:()=>Td,MBart50Tokenizer:()=>Sd,MBartTokenizer:()=>ho,MPNetTokenizer:()=>Cd,MarianTokenizer:()=>Md,MgpstrTokenizer:()=>Od,MobileBertTokenizer:()=>Id,NllbTokenizer:()=>Pd,NougatTokenizer:()=>Ld,PreTrainedTokenizer:()=>q,Qwen2Tokenizer:()=>Nd,RoFormerTokenizer:()=>Rd,RobertaTokenizer:()=>zd,SiglipTokenizer:()=>$d,SpeechT5Tokenizer:()=>Dd,SqueezeBertTokenizer:()=>Ud,T5Tokenizer:()=>Bd,TokenizersBackend:()=>q,VitsTokenizer:()=>jd,Wav2Vec2CTCTokenizer:()=>Gd,WhisperTokenizer:()=>qd,XLMRobertaTokenizer:()=>Wd,XLMTokenizer:()=>Vd});var sd=class extends q{return_token_type_ids=!0};var nd=class extends q{};var od=class extends q{return_token_type_ids=!0};var ad=class extends q{};var id=class extends q{};var ld=class extends q{};var cd=class extends q{};var ud=class extends q{};var pd=class extends q{};var fd=class extends q{};var dd=class extends q{};var md=class extends q{return_token_type_ids=!0};var hd=class extends q{return_token_type_ids=!0};var _d=class extends q{return_token_type_ids=!0};var gd=class extends q{};var wd=class extends q{return_token_type_ids=!0};var xd=class extends q{};var yd=class extends q{};var bd=class extends q{};var vd=class extends q{};var kd=class extends q{};var Ed=class extends q{return_token_type_ids=!0};var Ad=class extends q{padding_side="left"};var Td=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 cn(this,e,r,s)}};var Md=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)}`),dt([n],super._encode_text(o))}}};var ho=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 cn(this,e,r,s)}};var Sd=class extends ho{};var Od=class extends q{};var Id=class extends q{return_token_type_ids=!0};var Cd=class extends q{};var Pd=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 cn(this,e,r,s)}};var Ld=class extends q{};var Nd=class extends q{};var zd=class extends q{};var Rd=class extends q{return_token_type_ids=!0};var $d=class extends q{};var Dd=class extends q{};var Ud=class extends q{return_token_type_ids=!0};var Bd=class extends q{};var Fd=class extends Ft{decode_chain(e){let r="";for(let s=1;s<e.length;s+=2)r+=e[s];return[r]}},jd=class extends q{constructor(e,r){super(e,r),this._tokenizer.decoder=new Fd({type:"VitsDecoder"})}};var Gd=class extends q{};var LA=[["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"]],_o=new Map(LA),sL=new Map([...LA.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 NA(t){t=t.toLowerCase();let e=sL.get(t);if(e===void 0){let r=t.match(/^<\|([a-z]{2})\|>$/);if(r&&(t=r[1]),_o.has(t))e=t;else{let n=t.length===2?_o.keys():_o.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var nL="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",zA=new RegExp(`^[${nL}]+$`,"gu"),qd=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 c=[],p=l(),f=0,m=this.timestamp_begin,w=m+1500,x=[],b=[],E=!1,A=null,S=new Set(this.all_special_ids);for(let P of e){let k=P.tokens,F=i?P.token_timestamps:null,H=null,V=m;if("stride"in P){let[Y,U,L]=P.stride;if(f-=U,A=Y-L,U&&(V=U/n+m),L)for(let ne=k.length-1;ne>=0;--ne){let ae=Number(k[ne]);if(ae>=m){if(H!==null&&(ae-m)*n<A)break;H=ae}}}let J=[],X=[];for(let Y=0;Y<k.length;++Y){let U=Number(k[Y]);if(S.has(U)){let L=this.decode([U]),ne=_o.get(L.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,c.push(p),x=[],J=[],p=l()}a=p.language=ne}}else if(U>=m&&U<=w){let L=(U-m)*n+f,ne=ys(L,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&&b.push(X);let[ae,I]=this.findLongestCommonSequence(x,b),N=this.decode(ae);p.text=N,i&&(p.words=this.collateWordTimestamps(ae,I,a)),c.push(p),x=[],J=[],b=[],X=[],p=l()}}else if(J.push(U),i){let L=ys(F[Y]+f,2),ne;if(Y+1<F.length){ne=ys(F[Y+1]+f,2);let ae=this.decode([U]);zA.test(ae)&&(ne=ys(Math.min(L+n,ne),2))}else ne=null;X.push([L,ne])}}if("stride"in P){let[Y,U,L]=P.stride;f+=Y-L}J.length>0?(x.push(J),i&&b.push(X)):x.every(Y=>Y.length===0)&&(p=l(),x=[],J=[],b=[],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[P,k]=this.findLongestCommonSequence(x,b),F=this.decode(P);p.text=F,i&&(p.words=this.collateWordTimestamps(P,k,a)),c.push(p)}let M=Object.create(null),C=c.map(P=>P.text).join("");if(r||s){for(let P=0;P<c.length;++P){let k=c[P];r||delete k.timestamp,s||delete k.language}if(i){let P=[];for(let k of c)for(let F of k.words)P.push(F);M={chunks:P}}else M={chunks:c}}return[C,M]}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 c=1;c<e.length;++c){let p=e[c],f=0,m=[n,n,0,0],h=p.length;for(let M=1;M<n+h;++M){let C=Math.max(0,n-M),P=Math.min(n,n+h-M),k=s.slice(C,P),F=Math.max(0,M-n),H=Math.min(h,M),V=p.slice(F,H);if(k.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=k.filter((U,L)=>U===V[L]&&l[C+L]<=r[c][F+L]).length:J=k.filter((U,L)=>U===V[L]).length;let X=M/1e4,Y=J/M+X;J>1&&Y>f&&(f=Y,m=[C,P,F,H])}let[w,x,b,E]=m,A=Math.floor((x+w)/2),S=Math.floor((E+b)/2);o.push(...s.slice(0,A)),s=p.slice(S),n=s.length,a&&(i.push(...l.slice(0,A)),l=r[c].slice(S))}return o.push(...s),a?(i.push(...l),[o,i]):[o,[]]}collateWordTimestamps(e,r,s){let[n,o,a]=this.combineTokensIntoWords(e,s),i=[];for(let l=0;l<n.length;++l){let c=a[l];i.push({text:n[l],timestamp:[r[c.at(0)][0],r[c.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=rd(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=[],c=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[c+m.indexOf(s)]===s)&&(n.push(m),o.push(i),a.push(l),i=[],l=[],c+=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 c=r[l],p=s[l],f=n[l],m=p[0]>=this._tokenizer.token_to_id("<|endoftext|>"),h=c.startsWith(" "),w=c.trim(),x=zA.test(w);if(m||h||x||o.length===0)o.push(c),a.push(p),i.push(f);else{let b=o.length-1;o[b]+=c,a[b].push(...p),i[b].push(...f)}}return[o,a,i]}mergePunctuations(e,r,s,n,o){let a=structuredClone(e),i=structuredClone(r),l=structuredClone(s),c=a.length-2,p=a.length-1;for(;c>=0;)a[c].startsWith(" ")&&n.includes(a[c].trim())?(a[p]=a[c]+a[p],i[p]=dt(i[c],i[p]),l[p]=dt(l[c],l[p]),a[c]="",i[c]=[],l[c]=[]):p=c,--c;for(c=0,p=1;p<a.length;)!a[c].endsWith(" ")&&o.includes(a[p])?(a[c]+=a[p],i[c]=dt(i[c],i[p]),l[c]=dt(l[c],l[p]),a[p]="",i[p]=[],l[p]=[]):c=p,++p;return[a.filter(f=>f),i.filter(f=>f.length>0),l.filter(f=>f.length>0)]}};var Wd=class extends q{};var Vd=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 td(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",p=Hd[c];return p||(Q.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),p=q),new p(i,l)}};var Gr="https://github.com/huggingface/transformers.js/issues/new/choose";var go="preprocessor_config.json",Mr=go,RA="processor_config.json",$A="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,RA,!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?Xp(e,$A,!0,r):null]);return new this(s,n,o)}};var Tc={};ms(Tc,{ChatterboxProcessor:()=>lm,Florence2Processor:()=>Jm,Gemma3nProcessor:()=>Zm,GroundingDinoProcessor:()=>eh,Idefics3Processor:()=>kc,JinaCLIPProcessor:()=>rh,LlavaProcessor:()=>sh,MgpstrProcessor:()=>nh,MoonshineProcessor:()=>oh,OwlViTProcessor:()=>ah,PaliGemmaProcessor:()=>ih,Phi3VProcessor:()=>lh,PixtralProcessor:()=>ch,Processor:()=>oe,PyAnnoteProcessor:()=>uh,Qwen2VLProcessor:()=>Eo,Qwen2_5_VLProcessor:()=>Ao,Qwen3VLProcessor:()=>ph,Sam2Processor:()=>Ec,Sam2VideoProcessor:()=>fh,SamProcessor:()=>To,SmolVLMProcessor:()=>kc,SpeechT5Processor:()=>dh,UltravoxProcessor:()=>mh,VLChatProcessor:()=>th,VoxtralProcessor:()=>hh,Wav2Vec2Processor:()=>_h,Wav2Vec2ProcessorWithLM:()=>gh,WhisperProcessor:()=>wh});var $e=class extends Ze{constructor(e){super(),this.config=e}static async from_pretrained(e,r={}){let s=await ct(e,go,!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 vo={};ms(vo,{ASTFeatureExtractor:()=>Yd,ChatterboxFeatureExtractor:()=>Qd,ClapFeatureExtractor:()=>Jd,DacFeatureExtractor:()=>yo,EncodecFeatureExtractor:()=>xo,FeatureExtractor:()=>$e,Gemma3nAudioFeatureExtractor:()=>Zd,MoonshineFeatureExtractor:()=>em,ParakeetFeatureExtractor:()=>tm,PyAnnoteFeatureExtractor:()=>bo,SeamlessM4TFeatureExtractor:()=>rm,SnacFeatureExtractor:()=>sm,SpeechT5FeatureExtractor:()=>nm,Wav2Vec2FeatureExtractor:()=>om,WeSpeakerFeatureExtractor:()=>am,WhisperFeatureExtractor:()=>im});var oL=()=>{};var DA={fromWeb:oL};var aL=()=>{};var UA=aL;async function rc(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=DA.fromWeb(r),n=Et.createWriteStream(t);await UA(s,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function Kd(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 c=0;c<n.length;++c)o[c]=a*(i[c]+l[c])/2}else o=n.getChannelData(0);return o}function jA(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 BA(t){return jA(t,.5)}function iL(t){return jA(t,.54)}var lL={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 Xd(t,e="htk"){let r=lL[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 cL={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 uL(t,e="htk"){let r=cL[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 pL(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 c=-i[l]/r[l],p=i[l+2]/r[l+1];o[l][a]=Math.max(0,Math.min(c,p))}}return o}function FA(t,e,r){let s=(e-t)/(r-1);return Float64Array.from({length:r},(n,o)=>t+s*o)}function At(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=Xd(r,a),c=Xd(s,a),p=FA(l,c,e+2),f=uL(p,a),m;if(i){let w=n/((t-1)*2);m=Xd(Float64Array.from({length:t},(x,b)=>b*w),a),f=p}else m=FA(0,Math.floor(n/2),t);let h=pL(m,f);if(o!==null&&o==="slaney")for(let w=0;w<e;++w){let x=h[w],b=2/(f[w+2]-f[w]);for(let E=0;E<t;++E)x[E]*=b}return h}function fL(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[Qs(o,n)];for(let o=1;o<=r;++o)s[n+e+o]=t[Qs(n-o,n)];return s}function GA(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 dL(t,e=1,r=1e-5,s=null){return GA(t,20,e,r,s)}function mL(t,e=1,r=1e-10,s=null){return GA(t,10,e,r,s)}async function Ct(t,e,r,s,{fft_length:n=null,power:o=1,center:a=!0,pad_mode:i="reflect",onesided:l=!0,preemphasis:c=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:b=null,remove_dc_offset:E=null,min_num_frames:A=null,max_num_frames:S=null,do_pad:M=!0,transpose:C=!1,mel_offset:P=0}={}){let k=e.length;if(n===null&&(n=r),r>n)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(k!==r)throw new Error(`Length of the window (${k}) 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 N=Math.floor((n-1)/2)+1;t=fL(t,N,N);break}case"constant":{let N=Math.floor(n/2),$=new t.constructor(t.length+2*N);$.set(t,N),t=$;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?M&&(J=S):J=V=S);let X=new Pl(n),Y=new Float64Array(n),U=new Float64Array(X.outputBufferSize),L=new Float32Array(H*J);for(let N=0;N<V;++N){let $=N*s,te=Math.min(t.length-$,r);te!==r&&Y.fill(0,0,r);for(let pe=0;pe<te;++pe)Y[pe]=t[$+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(c!==null){for(let pe=te-1;pe>=1;--pe)Y[pe]-=c*Y[pe-1];Y[0]*=1-c}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;L[pe*J+N]=U[Fe]**2+U[Fe+1]**2}}if(o!==null&&o!==2){let N=o/2;for(let $=0;$<L.length;++$)L[$]**=N}let ne=f.length,ae=await OA(new D("float32",f.flat(),[ne,H]),new D("float32",L,[H,J]));C&&(ae=ae.transpose(1,0));let I=ae.data;for(let N=0;N<I.length;++N)I[N]=P+Math.max(m,I[N]);if(o!==null&&h!==null){let N=Math.min(I.length,V*ne);switch(h){case"log":for(let $=0;$<N;++$)I[$]=Math.log(I[$]);break;case"log10":for(let $=0;$<N;++$)I[$]=Math.log10(I[$]);break;case"dB":if(o===1)dL(I,w,x,b);else if(o===2)mL(I,w,x,b);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 Pt(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=BA(o);break;case"hamming":a=iL(o);break;case"povey":a=BA(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 hL(t,e){let r=t.reduce((o,a)=>o+a.length,0),s=new ArrayBuffer(44),n=new DataView(s);return sc(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),sc(n,8,"WAVE"),sc(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),sc(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...t.map(o=>o.buffer)],{type:"audio/wav"})}function sc(t,e,r){for(let s=0;s<r.length;++s)t.setUint8(e+s,r.charCodeAt(s))}var wo=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]),hL(e,this.sampling_rate)}async save(e){return rc(e,this.toBlob())}};var Yd=class extends $e{constructor(e){super(e);let r=this.config.sampling_rate,s=At(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=Pt(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,r){return Ct(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 xo=class extends $e{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 Qd=class extends $e{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 Jd=class extends $e{constructor(e){super(e),this.mel_filters=At(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=At(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=Pt(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(Cs.random()*(i+1));e=e.subarray(l,l+r),o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${s}" not implemented`);else{if(i<0){let l=new Float64Array(r);if(l.set(e),n==="repeat")for(let c=e.length;c<r;c+=e.length)l.set(e.subarray(0,Math.min(e.length,r-c)),c);else if(n==="repeatpad")for(let c=e.length;c<-i;c+=e.length)l.set(e,c);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 Ct(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 yo=class extends xo{};var Zd=class extends $e{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=At(Math.floor(1+r/2),s,n,o,a,null,"htk",!1);this.mel_filters=l,this.window=Pt(i,"hann")}async _extract_fbank_features(e,r){return Ct(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,c=new Float64Array(e.length+l);c.set(e),this.config.padding_value!==0&&c.fill(this.config.padding_value,e.length),e=c}let a=await this._extract_fbank_features(e,this.config.max_length),i=He([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}};var em=class extends $e{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 _L=1e-5,tm=class extends $e{constructor(e){super(e),this.config.mel_filters??=At(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=Pt(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 Ct(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 c=s>1?s-1:1;for(let f=0;f<a;++f){let m=i[f]/s,h=(l[f]-s*m*m)/c,x=1/(Math.sqrt(h)+_L);for(let b=0;b<s;++b){let E=b*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 bo=class extends $e{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 c=Ne(o[l]),[p,f]=Se(c),[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:c,end:p,score:f})=>({id:l,start:c*s,end:p*s,confidence:f/(p-c)})))}return n}};var rm=class extends $e{constructor(e){super(e);let r=this.config.sampling_rate,s=At(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=Pt(400,"povey",{periodic:!1})}async _extract_fbank_features(e,r){return e=e.map(s=>s*32768),Ct(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,b=a.data;for(let E=0;E<x;++E){let A=0;for(let P=0;P<w;++P)A+=b[P*x+E];let S=A/w,M=0;for(let P=0;P<w;++P)M+=(b[P*x+E]-S)**2;M/=w-1;let C=Math.sqrt(M+1e-7);for(let P=0;P<w;++P){let k=P*x+E;b[k]=(b[k]-S)/C}}}let i;if(r){let[w,x]=a.dims,b=a.data,E=w%s;if(E>0){let A=new Float32Array(x*(w+E));A.set(b),A.fill(this.config.padding_value,b.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,c]=a.dims,p=this.config.stride;if(l%p!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${p}).`);let m=a.view(1,Math.floor(l/p),c*p),h={input_features:m};if(o){let w=m.dims[1],x=new BigInt64Array(w);if(i){let b=i.data;for(let E=1,A=0;E<l;E+=p,++A)x[A]=b[E]}else x.fill(1n);h.attention_mask=new D("int64",x,[1,w])}return h}};var sm=class extends yo{};var nm=class extends $e{};var om=class extends $e{_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 am=class extends $e{constructor(e){super(e);let r=this.config.sampling_rate,s=At(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=Pt(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),Ct(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 c=l*a*i,p=l*i;for(let f=0;f<a;++f){let m=c+f*i;for(let h=0;h<i;++h)n[m+h]-=s[p+h]}}}return{input_features:r}}};var im=class extends $e{constructor(e){super(e),this.config.mel_filters??=At(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=Pt(this.config.n_fft,"hann")}async _extract_fbank_features(e){let r=await Ct(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,go,!0,r),n=s.feature_extractor_type,o=vo[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${Gr}.`);return new o(s)}};var lm=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}}};var nc={};var Ls,qA,qr,sr=ge.IS_BROWSER_ENV||ge.IS_WEBWORKER_ENV;if(sr)Ls=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(t,e)},qr=self.createImageBitmap,qA=self.ImageData;else if(nc)qr=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 gL={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},wL=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(!sr)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(sr){let r=await qr(e),s=Ls(r.width,r.height).getContext("2d");return s.drawImage(r,0,0),new this(s.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{let r=nc(await e.arrayBuffer());return await qr(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=gL[s]??s,o=Fp(e),a=Fp(r);if(o&&a)return this;if(o?e=r/this.height*this.width:a&&(r=e/this.width*this.height),sr){let i=this.channels,l=this.toCanvas(),c=Ls(e,r).getContext("2d");return c.drawImage(l,0,0,e,r),new t(c.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 qr(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(sr){let o=this.channels,a=this.toCanvas(),i=this.width+e+r,l=this.height+s+n,c=Ls(i,l).getContext("2d");return c.drawImage(a,0,0,this.width,this.height,e,s,this.width,this.height),new t(c.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 qr(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(sr){let i=this.channels,l=this.toCanvas(),c=Ls(o,a).getContext("2d");return c.drawImage(l,e,r,o,a,0,0,o,a),new t(c.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 qr(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(sr){let o=this.channels,a=this.toCanvas(),i=Ls(e,r).getContext("2d"),l=0,c=0,p=0,f=0;return s>=0?l=s:p=-s,n>=0?c=n:f=-n,i.drawImage(a,l,c,e,r,p,f,e,r),new t(i.getImageData(0,0,e,r).data,e,r,4).convert(o)}else{let o=this.toSharp();if(s>=0&&n>=0)o=o.extract({left:Math.floor(s),top:Math.floor(n),width:e,height:r});else if(s<=0&&n<=0){let a=Math.floor(-n),i=Math.floor(-s);o=o.extend({top:a,left:i,right:e-this.width-i,bottom:r-this.height-a})}else{let a=[0,0],i=0;n<0?(a[0]=Math.floor(-n),a[1]=r-this.height-a[0]):i=Math.floor(n);let l=[0,0],c=0;s<0?(l[0]=Math.floor(-s),l[1]=e-this.width-l[0]):c=Math.floor(s),o=o.extend({top:a[0],bottom:a[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:e,height:r})}return await qr(o)}}async toBlob(e="image/png",r=1){if(!sr)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(!sr)throw new Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),r=Ls(e.width,e.height),s=new qA(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 c=n*l;for(let p=0;p<n;++p)i[p][l]=e[c+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(sr){if(ge.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let r=e.split(".").pop().toLowerCase(),s=wL.get(r)??"image/png",n=await this.toBlob(s);return rc(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(sr)throw new Error("toSharp() is only supported in server-side environments.");return nc(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},xL=Ke.read.bind(Ke);function WA(t,e,r=0,s=null){let n=t/e,o=Ok(n)*e;return s!==null&&o>s&&(o=Math.floor(n)*e),o<r&&(o=Math.ceil(n)*e),o}function cm([t,e],r){return[Math.max(Math.floor(t/r),1)*r,Math.max(Math.floor(e/r),1)*r]}function um([t,e,r,s]){return[t-r/2,e-s/2,t+r/2,e+s/2]}function Wr(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 c=[];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 b=h[x],E=[],A;if(s){A=b.sigmoid().data;for(let S=0;S<A.length;++S)A[S]>e&&E.push(S)}else{let S=Se(b.data)[1];if(S===l-1||(A=Ne(b.data),A[S]<e))continue;E.push(S)}for(let S of E){let M=w[x].data;M=um(M),f!==null&&(M=M.map((C,P)=>C*f[(P+1)%2])),m.boxes.push(M),m.classes.push(S),m.scores.push(A[S])}}c.push(m)}return c}function oc(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=Yf(i,a,"bilinear",!1));let[l,c]=a??i.dims.slice(-2),p=new D("int32",new Int32Array(l*c),[l,c]),f=i[0].data,m=p.data;for(let x=1;x<i.dims[0];++x){let b=i[x].data;for(let E=0;E<b.length;++E)b[E]>f[E]&&(f[E]=b[E],m[E]=x)}let h=new Array(i.dims[0]);for(let x=0;x<m.length;++x){let b=m[x];h[b]=b}let w=h.filter(x=>x!==void 0);n.push({segmentation:p,labels:w})}return n}function yL(t,e,r,s){let n=[],o=[],a=[];for(let i=0;i<t.dims[0];++i){let l=t[i],c=e[i],p=Se(l.data)[1];if(p===s)continue;let m=Ne(l.data)[p];m>r&&(n.push(c),o.push(m),a.push(p))}return[n,o,a]}function bL(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 c=a>0&&i>0;return c&&(c=a/i>n),[c,o]}function vL(t,e,r,s,n,o=null,a=null){let[i,l]=a??t[0].dims,c=new D("int32",new Int32Array(i*l),[i,l]),p=[];if(a!==null)for(let x=0;x<t.length;++x)t[x]=Yf(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 b=e[x],E=t[x].data;for(let A=0;A<E.length;++A)E[A]*=b,E[A]>m[A]&&(f[A]=x,m[A]=E[A])}let h=0,w=c.data;for(let x=0;x<r.length;++x){let b=r[x],[E,A]=bL(f,t,x,s,n);if(E){++h;for(let S of A)w[S]=h;p.push({id:h,label_id:b,score:e[x]})}}return[c,p]}function ac(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(),[c,p,f]=a.dims;if(f-=1,o!==null&&o.length!==c)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<c;++h){let w=o!==null?o[h]:null,x=a[h],b=l[h],[E,A,S]=yL(x,b,e,f);if(S.length===0){let[P,k]=w??b.dims.slice(-2),F=new D("int32",new Int32Array(P*k).fill(-1),[P,k]);m.push({segmentation:F,segments_info:[]});continue}let[M,C]=vL(E,A,S,r,s,n,w);m.push({segmentation:M,segments_info:C})}return m}function ic(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),c=Math.min(o,i);return l===n&&c===o?e:(n>o?c=Math.floor(o*l/n):o>n&&(l=Math.floor(n*c/o)),await e.resize(c,l,{resample:s}))}async crop_margin(e,r=200){let s=e.clone().grayscale(),n=eo(s.data)[0],a=Se(s.data)[0]-n;if(a===0)return e;let i=r/255,l=s.width,c=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),c=Math.min(c,h),p=Math.max(p,x),f=Math.max(f,h))}return e=await e.crop([l,c,p,f]),e}pad_image(e,r,s,{mode:n="constant",center:o=!1,constant_values:a=0}={}){let[i,l,c]=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*c);if(Array.isArray(a))for(let x=0;x<m.length;++x)m[x]=a[x%c];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 b=(x+w)*p,E=x*l;for(let A=0;A<l;++A){let S=(b+A+h)*c,M=(E+A)*c;for(let C=0;C<c;++C)m[S+C]=e[M+C]}}if(n==="symmetric"){if(o)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");let x=i-1,b=l-1;for(let E=0;E<f;++E){let A=E*p,S=Qs(E,x)*l;for(let M=0;M<p;++M){if(E<i&&M<l)continue;let C=(A+M)*c,P=(S+Qs(M,b))*c;for(let k=0;k<c;++k)m[C+k]=e[P+k]}}}e=m,r=[f,p,c]}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,c=n*i,p=a===void 0?1:Math.min(a/l,a/c),f=Math.floor(Number((l*p).toFixed(2))),m=Math.floor(Number((c*p).toFixed(2)));return this.size_divisibility!==void 0&&([f,m]=cm([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 c=l/n,p=i/s;Math.abs(1-p)<Math.abs(1-c)?c=p:p=c,l=WA(c*n,this.config.ensure_multiple_of),i=WA(p*s,this.config.ensure_multiple_of)}return[i,l]}else{if(this.size_divisibility!==void 0)return cm([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 c=[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 b=0;b<e.channels;++b)p[x+b]=(p[x+b]-h[b])/w[b]}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]=cm([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:c,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:Vt(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,Mr,!0,r);return new this(s)}};var mn={};ms(mn,{BeitFeatureExtractor:()=>pm,BitImageProcessor:()=>fm,CLIPFeatureExtractor:()=>mm,CLIPImageProcessor:()=>lc,ChineseCLIPFeatureExtractor:()=>dm,ConvNextFeatureExtractor:()=>hm,ConvNextImageProcessor:()=>cc,DINOv3ViTImageProcessor:()=>wm,DPTFeatureExtractor:()=>ym,DPTImageProcessor:()=>fc,DeiTFeatureExtractor:()=>_m,DeiTImageProcessor:()=>uc,DetrFeatureExtractor:()=>gm,DetrImageProcessor:()=>pc,DonutFeatureExtractor:()=>xm,DonutImageProcessor:()=>un,EfficientNetImageProcessor:()=>bm,GLPNFeatureExtractor:()=>vm,GroundingDinoImageProcessor:()=>km,Idefics3ImageProcessor:()=>dc,ImageFeatureExtractor:()=>W,ImageProcessor:()=>W,JinaCLIPImageProcessor:()=>Am,LlavaOnevisionImageProcessor:()=>Tm,Mask2FormerImageProcessor:()=>Sm,MaskFormerFeatureExtractor:()=>Mm,MaskFormerImageProcessor:()=>pn,MobileNetV1FeatureExtractor:()=>Om,MobileNetV1ImageProcessor:()=>mc,MobileNetV2FeatureExtractor:()=>Im,MobileNetV2ImageProcessor:()=>hc,MobileNetV3FeatureExtractor:()=>Cm,MobileNetV3ImageProcessor:()=>_c,MobileNetV4FeatureExtractor:()=>Pm,MobileNetV4ImageProcessor:()=>gc,MobileViTFeatureExtractor:()=>Lm,MobileViTImageProcessor:()=>wc,NougatImageProcessor:()=>Nm,OwlViTFeatureExtractor:()=>zm,OwlViTImageProcessor:()=>fn,Owlv2ImageProcessor:()=>Rm,Phi3VImageProcessor:()=>Um,PixtralImageProcessor:()=>Bm,PvtImageProcessor:()=>Fm,Qwen2VLImageProcessor:()=>jm,RTDetrImageProcessor:()=>Gm,Sam2ImageProcessor:()=>ko,Sam3ImageProcessor:()=>ko,SamImageProcessor:()=>ko,SapiensFeatureExtractor:()=>qm,SapiensImageProcessor:()=>xc,SegformerFeatureExtractor:()=>Wm,SegformerImageProcessor:()=>yc,SiglipImageProcessor:()=>Vm,SmolVLMImageProcessor:()=>dc,Swin2SRImageProcessor:()=>Hm,VLMImageProcessor:()=>Em,ViTFeatureExtractor:()=>Xm,ViTImageProcessor:()=>bc,VitMatteImageProcessor:()=>Km,VitPoseImageProcessor:()=>Ym,YolosFeatureExtractor:()=>Qm,YolosImageProcessor:()=>vc});var pm=class extends W{};var fm=class extends W{};var dm=class extends W{};var lc=class extends W{},mm=class extends lc{};var cc=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}},hm=class extends cc{};var uc=class extends W{},_m=class extends uc{};var pc=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 Wr(...e)}post_process_panoptic_segmentation(...e){return ac(...e)}post_process_instance_segmentation(...e){return ic(...e)}},gm=class extends pc{};var wm=class extends W{};var un=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 c=this.image_std;Array.isArray(c)||(c=new Array(i).fill(l));let p=l.map((f,m)=>-f/c[m]);return super.pad_image(e,r,s,{center:!0,constant_values:p,...n})}},xm=class extends un{};var fc=class extends W{},ym=class extends fc{};var bm=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 vm=class extends W{};var km=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 dc=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=[],c=[];for(let E of n){let A=await Promise.all(E.map(C=>this.preprocess(C)));l.push(...A.map(C=>C.original_size)),c.push(...A.map(C=>C.reshaped_input_size)),A.forEach(C=>C.pixel_values.unsqueeze_(0));let{longest_edge:S}=this.max_image_size,M;if(r??this.do_image_splitting){let C=new Array(A.length),P=new Array(A.length);M=await Promise.all(A.map(async(k,F)=>{let H=this.get_resize_for_vision_encoder(k.pixel_values,S),V=await Wt(k.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 C[F]=X,P[F]=Y,Ee(J,0)})),a.push(C),i.push(P)}else{let C=[S,S];M=await Promise.all(A.map(P=>Wt(P.pixel_values,{size:C}))),a.push(new Array(A.length).fill(0)),i.push(new Array(A.length).fill(0))}o.push(Ee(M,0))}let p=o.length,[f,m,h,w]=o[0].dims,x,b;if(p===1)x=o[0].unsqueeze_(0),b=He([p,f,h,w],!0);else{let E=Math.max(...o.map(M=>M.dims.at(0)));b=He([p,E,h,w],!0);let A=b.data,S=E*h*w;for(let M=0;M<p;++M){let C=o[M].dims[0];if(C<E){o[M]=Ee([o[M],He([E-C,m,h,w],0)],0);let P=M*S+C*h*w,k=(M+1)*S;A.fill(!1,P,k)}}x=Vt(o,0)}return{pixel_values:x,pixel_attention_mask:b,original_sizes:l,reshaped_input_sizes:c,...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,c=0;if(a>s||i>n){l=Math.ceil(a/s),c=Math.ceil(i/n);let p=Math.ceil(a/l),f=Math.ceil(i/c);for(let w=0;w<l;++w)for(let x=0;x<c;++x){let b,E,A,S;w===l-1?(E=a-p,S=a):(E=w*p,S=(w+1)*p),x===c-1?(b=i-f,A=i):(b=x*f,A=(x+1)*f);let P=await Zl(e,[E,b],[S,A],[2,3]);o.push(P)}let m=s,h=n;(a!==m||i!==h)&&(e=await Wt(e,{size:[m,h]}))}return o.push(e),{frames:o,num_splits_h:l,num_splits_w:c}}};var Em=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 Am=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 Tm=class extends W{};var pn=class extends W{post_process_panoptic_segmentation(...e){return ac(...e)}post_process_instance_segmentation(...e){return ic(...e)}},Mm=class extends pn{};var Sm=class extends pn{};var mc=class extends W{},Om=class extends mc{};var hc=class extends W{},Im=class extends hc{};var _c=class extends W{},Cm=class extends _c{};var gc=class extends W{},Pm=class extends gc{};var wc=class extends W{},Lm=class extends wc{};var Nm=class extends un{};var fn=class extends W{post_process_object_detection(...e){return Wr(...e)}},zm=class extends fn{};var Rm=class extends fn{};var Dt=336,kL=[2,3],{ceil:$m,floor:dn,sqrt:Dm}=Math,Um=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 dn((dn(r/Dt)*dn(e/Dt)+1)*s+1+(dn(r/Dt)+1)*Dm(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),c=Math.floor(l/a);return[l,c]}pad_image(e,r,s,n={}){let[o,a]=r,i=Dt*$m(o/Dt),l=Dt*$m(a/Dt),c=[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:c,...n})}async _call(e,{num_crops:r=null}={}){if(this._num_crops=r??=this.config.num_crops,r<4||Dm(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 Wt(m,{size:[Dt,Dt],mode:"bicubic"});if(r>0){let b=[],E=Dm(r),A=dn(w/E),S=dn(h/E);for(let C=0;C<E;++C)for(let P=0;P<E;++P){let k,F,H,V;C===E-1?(F=h-S,V=h):(F=C*S,V=(C+1)*S),P===E-1?(k=w-A,H=w):(k=P*A,H=(P+1)*A);let Y=await Zl(m,[F,k],[V,H],kL);b.push(Y)}let M=await Wt(Ee(b,0),{size:[Dt,Dt],mode:"bicubic"});i.push(Ee([x,M],0))}else i.push(x)}let l=Vt(i,0),c=a.map(m=>m.map(h=>Dt*$m(h/Dt))),p=new D("int64",c.flat(),[s,2]),f=c.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 Bm=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:c,spatial_merge_size:p}=this.config;if(!p)throw new Error("config must contain 'spatial_merge_size'");let f=c*p,m=Math.floor((i-1)/f)+1,h=Math.floor((l-1)/f)+1;return[m*f,h*f]}};var Fm=class extends W{};function EL(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 jm=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 EL(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:c}=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]/c),h=Math.floor(a.dims[3]/c),w=a.view(p,i,f,Math.floor(m/l),l,c,Math.floor(h/l),l,c).permute(0,3,6,4,7,2,1,5,8).view(p*m*h,f*i*c*c),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 Gm=class extends W{post_process_object_detection(...e){return Wr(...e)}};var ko=class extends W{reshape_input_points(e,r,s,n=!1){e=structuredClone(e);let o=jp(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],[c,p]=s[a],f=[p/l,c/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=jp(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 c=0;c<r.length;++c){let p=r[c],f=s[c],m=await Wt(e[c],{mode:"bilinear",size:l});if(m=m.slice(null,null,[0,f[0]],[0,f[1]]),m=await Wt(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 xc=class extends W{post_process_semantic_segmentation(...e){return oc(...e)}},qm=class extends xc{};var yc=class extends W{post_process_semantic_segmentation(...e){return oc(...e)}},Wm=class extends yc{};var Vm=class extends W{};var Hm=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 bc=class extends W{},Xm=class extends bc{};var Km=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:Vt(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 Ym=class extends W{post_process_pose_estimation(e,r,{threshold:s=null}={}){let n=e.tolist(),[o,a,i,l]=e.dims,c=[];for(let p=0;p<o;++p){let f=n[p],m=r[p],h=[];for(let w=0;w<m.length;++w){let x=m[w],b=[],E=[],A=[],S=x.at(-2)/l,M=x.at(-1)/i;for(let C=0;C<f.length;++C){let[P,k]=[0,0],F=0,H=-1/0,V=f[C];for(let X=0;X<V.length;++X){let Y=V[X];for(let U=0;U<Y.length;++U){let L=Y[U];F+=L,H=Math.max(H,L),P+=(U+.5)*L,k+=X*L}}if(s!=null&&H<s)continue;let J=[S*P/F,M*k/F];b.push(J),A.push(C),E.push(H)}h.push({bbox:x,scores:E,labels:A,keypoints:b})}c.push(h)}return c}};var vc=class extends W{post_process_object_detection(...e){return Wr(...e)}},Qm=class extends vc{};var De=class{static async from_pretrained(e,r={}){let s=await ct(e,Mr,!0,r),n=s.image_processor_type??s.feature_extractor_type,o=mn[n?.replace(/Fast$/,"")];return o||(n!==void 0&&Q.warn(`Image processor type '${n}' not found, assuming base ImageProcessor. Please report this at ${Gr}.`),o=W),new o(s)}};var Jm=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=[],c=[];for(let[p,f,...m]of i)l.push(f?f.trim():l.at(-1)??""),c.push(m.map((h,w)=>(Number(h)+.5)/this.size_per_bin*s[w%2]));o={labels:l,[a]:c};break;default:throw new Error(`Task "${r}" (of type "${n}") not yet implemented.`)}return{[r]:o}}async _call(e,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=await this.image_processor(e,s),o=r?this.tokenizer(this.construct_prompts(r),s):{};return{...n,...o}}};var Zm=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:c,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=`
12
+ }`,_=new Function(Object.keys(I),z)(...Object.values(I)),z=`methodCaller<(${b.map(F=>F.name)}) => ${g.name}>`,OM(Object.defineProperty(_,"name",{value:z}))}function NM(u,d){return d>>>=0,(u=Bt(u>>>0))==Bt(d)}function zM(u){return(u>>>=0)?(u=Nl(u),Kt(globalThis[u])):Kt(globalThis)}function RM(u){return u=Nl(u>>>0),Kt(e[u])}function $M(u,d){return d>>>=0,u=Bt(u>>>0),d=Bt(d),Kt(u[d])}function DM(u){9<(u>>>=0)&&(fs[u+1]+=1)}function j1(u,d,_,g,b){return Bp[u>>>0](d>>>0,_>>>0,g>>>0,b>>>0)}function BM(u,d,_,g,b){return j1(u>>>0,d>>>0,_>>>0,g>>>0,b>>>0)}function UM(){return Kt([])}function FM(u){u=Bt(u>>>0);for(var d=Array(u.length),_=0;_<u.length;_++)d[_]=u[_];return Kt(d)}function GM(u){return Kt(Nl(u>>>0))}function jM(){return Kt({})}function qM(u){for(var d=Bt(u>>>=0);d.length;){var _=d.pop();d.pop()(_)}Lp(u)}function WM(u,d,_){d>>>=0,_>>>=0,u=Bt(u>>>0),d=Bt(d),_=Bt(_),u[d]=_}function VM(u,d){u=Tt(u),d>>>=0,u=new Date(1e3*u),(k(),B)[d>>>2>>>0]=u.getUTCSeconds(),(k(),B)[d+4>>>2>>>0]=u.getUTCMinutes(),(k(),B)[d+8>>>2>>>0]=u.getUTCHours(),(k(),B)[d+12>>>2>>>0]=u.getUTCDate(),(k(),B)[d+16>>>2>>>0]=u.getUTCMonth(),(k(),B)[d+20>>>2>>>0]=u.getUTCFullYear()-1900,(k(),B)[d+24>>>2>>>0]=u.getUTCDay(),u=(u.getTime()-Date.UTC(u.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(k(),B)[d+28>>>2>>>0]=u}var q1=u=>u%4==0&&(u%100!=0||u%400==0),W1=[0,31,60,91,121,152,182,213,244,274,305,335],V1=[0,31,59,90,120,151,181,212,243,273,304,334];function HM(u,d){u=Tt(u),d>>>=0,u=new Date(1e3*u),(k(),B)[d>>>2>>>0]=u.getSeconds(),(k(),B)[d+4>>>2>>>0]=u.getMinutes(),(k(),B)[d+8>>>2>>>0]=u.getHours(),(k(),B)[d+12>>>2>>>0]=u.getDate(),(k(),B)[d+16>>>2>>>0]=u.getMonth(),(k(),B)[d+20>>>2>>>0]=u.getFullYear()-1900,(k(),B)[d+24>>>2>>>0]=u.getDay();var _=(q1(u.getFullYear())?W1:V1)[u.getMonth()]+u.getDate()-1|0;(k(),B)[d+28>>>2>>>0]=_,(k(),B)[d+36>>>2>>>0]=-60*u.getTimezoneOffset(),_=new Date(u.getFullYear(),6,1).getTimezoneOffset();var g=new Date(u.getFullYear(),0,1).getTimezoneOffset();u=0|(_!=g&&u.getTimezoneOffset()==Math.min(g,_)),(k(),B)[d+32>>>2>>>0]=u}function XM(u){u>>>=0;var d=new Date((k(),B)[u+20>>>2>>>0]+1900,(k(),B)[u+16>>>2>>>0],(k(),B)[u+12>>>2>>>0],(k(),B)[u+8>>>2>>>0],(k(),B)[u+4>>>2>>>0],(k(),B)[u>>>2>>>0],0),_=(k(),B)[u+32>>>2>>>0],g=d.getTimezoneOffset(),b=new Date(d.getFullYear(),6,1).getTimezoneOffset(),T=new Date(d.getFullYear(),0,1).getTimezoneOffset(),I=Math.min(T,b);return 0>_?(k(),B)[u+32>>>2>>>0]=+(b!=T&&I==g):0<_!=(I==g)&&(b=Math.max(T,b),d.setTime(d.getTime()+6e4*((0<_?I:b)-g))),(k(),B)[u+24>>>2>>>0]=d.getDay(),_=(q1(d.getFullYear())?W1:V1)[d.getMonth()]+d.getDate()-1|0,(k(),B)[u+28>>>2>>>0]=_,(k(),B)[u>>>2>>>0]=d.getSeconds(),(k(),B)[u+4>>>2>>>0]=d.getMinutes(),(k(),B)[u+8>>>2>>>0]=d.getHours(),(k(),B)[u+12>>>2>>>0]=d.getDate(),(k(),B)[u+16>>>2>>>0]=d.getMonth(),(k(),B)[u+20>>>2>>>0]=d.getYear(),u=d.getTime(),BigInt(isNaN(u)?-1:u/1e3)}function H1(u,d,_,g,b,T,I){return n?De(16,1,u,d,_,g,b,T,I):-52}function X1(u,d,_,g,b,T){if(n)return De(17,1,u,d,_,g,b,T)}var to={},KM=()=>performance.timeOrigin+performance.now();function K1(u,d){if(n)return De(18,1,u,d);if(to[u]&&(clearTimeout(to[u].id),delete to[u]),!d)return 0;var _=setTimeout(()=>{delete to[u],Mt(()=>Ev(u,performance.timeOrigin+performance.now()))},d);return to[u]={id:_,Ce:d},0}function YM(u,d,_,g){u>>>=0,d>>>=0,_>>>=0,g>>>=0;var b=new Date().getFullYear(),T=new Date(b,0,1).getTimezoneOffset();b=new Date(b,6,1).getTimezoneOffset();var I=Math.max(T,b);(k(),C)[u>>>2>>>0]=60*I,(k(),B)[d>>>2>>>0]=+(T!=b),u=(d=z=>{var F=Math.abs(z);return`UTC${0<=z?"-":"+"}${String(Math.floor(F/60)).padStart(2,"0")}${String(F%60).padStart(2,"0")}`})(T),d=d(b),b<T?(gr(u,_,17),gr(d,g,17)):(gr(u,g,17),gr(d,_,17))}var QM=()=>Date.now(),JM=1;function ZM(u,d,_){if(_>>>=0,!(0<=u&&3>=u))return 28;if(u===0)u=Date.now();else{if(!JM)return 52;u=performance.timeOrigin+performance.now()}return u=Math.round(1e6*u),(k(),P)[_>>>3>>>0]=BigInt(u),0}var Up=[],Y1=(u,d)=>{Up.length=0;for(var _;_=(k(),V)[u++>>>0];){var g=_!=105;d+=(g&=_!=112)&&d%8?4:0,Up.push(_==112?(k(),C)[d>>>2>>>0]:_==106?(k(),P)[d>>>3>>>0]:_==105?(k(),B)[d>>>2>>>0]:(k(),le)[d>>>3>>>0]),d+=g?8:4}return Up};function eS(u,d,_){return u>>>=0,d=Y1(d>>>0,_>>>0),tf[u](...d)}function tS(u,d,_){return u>>>=0,d=Y1(d>>>0,_>>>0),tf[u](...d)}var rS=()=>{};function sS(u,d){return M(Js(u>>>0,d>>>0))}var nS=()=>{throw ve+=1,"unwind"};function oS(){return 4294901760}var aS=()=>1,iS=()=>navigator.hardwareConcurrency;function lS(u){u>>>=0;var d=(k(),V).length;if(u<=d||4294901760<u)return!1;for(var _=1;4>=_;_*=2){var g=d*(1+.2/_);g=Math.min(g,u+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(u,g)/65536))-Cr.buffer.byteLength+65535)/65536|0;try{Cr.grow(g),Ie();var b=1;break e}catch{}b=void 0}if(b)return!0}return!1}var lr=u=>{var d=wr(u)+1,_=Dl(d);return gr(u,_,d),_},Fp=(u,d)=>{(k(),C)[u>>>2>>>0]=d;var _=(k(),C)[u>>>2>>>0];(k(),C)[u+4>>>2>>>0]=(d-_)/4294967296},ro=u=>(k(),C)[u>>>2>>>0]+4294967296*(k(),B)[u+4>>>2>>>0],gt=[],cS=(u,d)=>{gt[u>>>0]=d},xr=[],zl=[],en=(u,d)=>{zl[u]=new Promise(_=>d.finally(()=>_(u)))},se=u=>{if(u)return gt[u>>>0]},uS=(u,d)=>{for(u=(k(),C)[u>>>2>>>0];u;u=(k(),C)[u>>>2>>>0])d[(k(),B)[u+4>>>2>>>0]](u)},Rl=(u,d,_)=>{(k(),C)[u>>>2>>>0]=d,(k(),C)[u+4>>>2>>>0]=_},Q1=u=>{var d=(k(),C)[u>>>2>>>0];return u=(k(),C)[u+4>>>2>>>0],Js(d,u)},yr=u=>{var d=(k(),C)[u>>>2>>>0];return u=(k(),C)[u+4>>>2>>>0],d?Js(d,u):u===0?"":void 0},pS=u=>{var d=yr(u+4),_=(_=(k(),C)[u+12>>>2>>>0])?se(_):"auto";if(u+=16){var g=se((k(),C)[u+4>>>2>>>0]),b=(k(),C)[u+16>>>2>>>0],T=(k(),C)[u+20>>>2>>>0];if(b){for(var I={},z=0;z<b;++z){var F=T+24*z;I[Q1(F+4)]=(k(),le)[F+16>>>3>>>0]}b=I}else b=void 0;u={module:g,constants:b,entryPoint:yr(u+8)}}else u=void 0;return{label:d,layout:_,compute:u}},J1=(u,d)=>{function _(g,b){g=u[g],(k(),C)[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),Fp(d+64,u.maxUniformBufferBindingSize),Fp(d+72,u.maxStorageBufferBindingSize),_("maxVertexBuffers",88),Fp(d+96,u.maxBufferSize),_("maxVertexAttributes",104),_("maxVertexBufferArrayStride",108),_("maxInterStageShaderVariables",112),_("maxColorAttachments",116),_("maxColorAttachmentBytesPerSample",120),_("maxComputeWorkgroupStorageSize",124),_("maxComputeInvocationsPerWorkgroup",128),_("maxComputeWorkgroupSizeX",132),_("maxComputeWorkgroupSizeY",136),_("maxComputeWorkgroupSizeZ",140),_("maxComputeWorkgroupsPerDimension",144),u.Ae!==void 0&&_("maxImmediateSize",148)},fS=[,"validation","out-of-memory","internal"],dS=[,"compatibility","core"],Z1={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"},mS=[,"low-power","high-performance"],hS=[,"occlusion","timestamp"],_S={undefined:1,unknown:1,destroyed:2};function gS(u,d,_,g,b,T){d=Tt(d),_=Tt(_),g>>>=0,b>>>=0,T>>>=0;var I=se(u>>>0);if(u={},T){var z=(k(),C)[T+12>>>2>>>0];if(z){var F=(k(),C)[T+16>>>2>>>0];u.requiredFeatures=Array.from((k(),C).subarray(F>>>2>>>0,F+4*z>>>2>>>0),ne=>Z1[ne])}var Q=(k(),C)[T+20>>>2>>>0];if(Q){let ne=function(St,pt,ds=!1){pt=Q+pt,(pt=(k(),C)[pt>>>2>>>0])==4294967295||ds&&pt==0||(Ge[St]=pt)},ut=function(St,pt){pt=Q+pt;var ds=(k(),C)[pt>>>2>>>0],GO=(k(),C)[pt+4>>>2>>>0];ds==4294967295&&GO==4294967295||(Ge[St]=ro(pt))};var Se=ne,ze=ut,Ge={};ne("maxTextureDimension1D",4),ne("maxTextureDimension2D",8),ne("maxTextureDimension3D",12),ne("maxTextureArrayLayers",16),ne("maxBindGroups",20),ne("maxBindGroupsPlusVertexBuffers",24),ne("maxDynamicUniformBuffersPerPipelineLayout",32),ne("maxDynamicStorageBuffersPerPipelineLayout",36),ne("maxSampledTexturesPerShaderStage",40),ne("maxSamplersPerShaderStage",44),ne("maxStorageBuffersPerShaderStage",48),ne("maxStorageTexturesPerShaderStage",52),ne("maxUniformBuffersPerShaderStage",56),ne("minUniformBufferOffsetAlignment",80),ne("minStorageBufferOffsetAlignment",84),ut("maxUniformBufferBindingSize",64),ut("maxStorageBufferBindingSize",72),ne("maxVertexBuffers",88),ut("maxBufferSize",96),ne("maxVertexAttributes",104),ne("maxVertexBufferArrayStride",108),ne("maxInterStageShaderVariables",112),ne("maxColorAttachments",116),ne("maxColorAttachmentBytesPerSample",120),ne("maxComputeWorkgroupStorageSize",124),ne("maxComputeInvocationsPerWorkgroup",128),ne("maxComputeWorkgroupSizeX",132),ne("maxComputeWorkgroupSizeY",136),ne("maxComputeWorkgroupSizeZ",140),ne("maxComputeWorkgroupsPerDimension",144),ne("maxImmediateSize",148,!0),u.requiredLimits=Ge}(z=(k(),C)[T+24>>>2>>>0])&&(z={label:yr(z+4)},u.defaultQueue=z),u.label=yr(T+4)}ve+=1,en(d,I.requestDevice(u).then(ne=>{--ve,Mt(()=>{gt[b>>>0]=ne.queue,gt[g>>>0]=ne,en(_,ne.lost.then(ut=>{Mt(()=>{ne.onuncapturederror=()=>{};var St=ue(),pt=lr(ut.message);Vp(_,_S[ut.reason],pt),ce(St)})})),ne.onuncapturederror=ut=>{var St=5;ut.error instanceof GPUValidationError?St=2:ut.error instanceof GPUOutOfMemoryError?St=3:ut.error instanceof GPUInternalError&&(St=4);var pt=ue();ut=lr(ut.error.message),yv(g,St,ut),ce(pt)},"adapterInfo"in ne||(ne.adapterInfo=I.info),Kp(d,1,g,0)})},ne=>{--ve,Mt(()=>{var ut=ue(),St=lr(ne.message);Kp(d,3,g,St),_&&Vp(_,4,St),ce(ut)})}))}function wS(u){var d=se(u>>>=0),_=xr[u];if(_){for(var g=0;g<_.length;++g)_[g]();delete xr[u]}d.destroy()}function xS(u,d,_){_>>>=0;var g=se(u>>>=0);_==4294967295&&(_=void 0);try{var b=g.getMappedRange(d>>>0,_)}catch{return 0}var T=Jp(16,b.byteLength);return(k(),V).set(new Uint8Array(b),T>>>0),xr[u].push(()=>Yt(T)),T}function yS(u,d,_){_>>>=0;var g=se(u>>>=0);_==4294967295&&(_=void 0);try{var b=g.getMappedRange(d>>>0,_)}catch{return 0}var T=Jp(16,b.byteLength);return(k(),V).fill(0,T,b.byteLength),xr[u].push(()=>{new Uint8Array(b).set((k(),V).subarray(T>>>0,T+b.byteLength>>>0)),Yt(T)}),T}function bS(u,d,_,g,b){u>>>=0,d=Tt(d),_=Tt(_),b>>>=0;var T=se(u);xr[u]=[],b==4294967295&&(b=void 0),ve+=1,en(d,T.mapAsync(_,g>>>0,b).then(()=>{--ve,Mt(()=>{Hp(d,1,0)})},I=>{--ve,Mt(()=>{ue();var z=lr(I.message);Hp(d,I.name==="AbortError"?4:I.name==="OperationError"?3:0,z),delete xr[u]})}))}function vS(u){var d=se(u>>>=0),_=xr[u];if(_){for(var g=0;g<_.length;++g)_[g]();delete xr[u],d.unmap()}}function kS(u){delete gt[u>>>0]}function ES(u,d,_){u>>>=0,d>>>=0,_>>>=0;var g=!!(k(),C)[d+32>>>2>>>0];d={label:yr(d+4),usage:(k(),C)[d+16>>>2>>>0],size:ro(d+24),mappedAtCreation:g},u=se(u);try{var b=u.createBuffer(d)}catch{return!1}return gt[_>>>0]=b,g&&(xr[_]=[]),!0}function AS(u,d,_,g){u>>>=0,d=Tt(d),g>>>=0,_=pS(_>>>0),u=se(u),ve+=1,en(d,u.createComputePipelineAsync(_).then(b=>{--ve,Mt(()=>{gt[g>>>0]=b,Wp(d,1,g,0)})},b=>{--ve,Mt(()=>{var T=ue(),I=lr(b.message);Wp(d,b.reason==="validation"?3:b.reason==="internal"?4:0,g,I),ce(T)})}))}function TS(u,d,_){u>>>=0,d>>>=0,_>>>=0;var g=(k(),C)[d>>>2>>>0],b=(k(),B)[g+4>>>2>>>0];d={label:yr(d+4),code:""},b===2&&(d.code=Q1(g+8)),u=se(u).createShaderModule(d),gt[_>>>0]=u}var MS=u=>{(u=se(u)).onuncapturederror=null,u.destroy()};function SS(u,d){d=Tt(d),u=se(u>>>0),ve+=1,en(d,u.popErrorScope().then(_=>{--ve,Mt(()=>{var g=5;_?_ instanceof GPUValidationError?g=2:_ instanceof GPUOutOfMemoryError?g=3:_ instanceof GPUInternalError&&(g=4):g=1;var b=ue(),T=_?lr(_.message):0;Xp(d,1,g,T),ce(b)})},_=>{--ve,Mt(()=>{var g=ue(),b=lr(_.message);Xp(d,1,5,b),ce(g)})}))}function OS(u,d,_,g){if(d=Tt(d),g>>>=0,_>>>=0){var b={featureLevel:dS[(k(),B)[_+4>>>2>>>0]],powerPreference:mS[(k(),B)[_+8>>>2>>>0]],forceFallbackAdapter:!!(k(),C)[_+12>>>2>>>0]};(u=(k(),C)[_>>>2>>>0])!==0&&(k(),b.Fe=!!(k(),C)[u+8>>>2>>>0])}"gpu"in navigator?(ve+=1,en(d,navigator.gpu.requestAdapter(b).then(T=>{--ve,Mt(()=>{if(T)gt[g>>>0]=T,so(d,1,g,0);else{var I=ue(),z=lr("WebGPU not available on this browser (requestAdapter returned null)");so(d,3,g,z),ce(I)}})},T=>{--ve,Mt(()=>{var I=ue(),z=lr(T.message);so(d,4,g,z),ce(I)})}))):(b=ue(),u=lr("WebGPU not available on this browser (navigator.gpu is not available)"),so(d,3,g,u),ce(b))}function IS(u,d,_){return u>>>=0,d>>>=0,_>>>=0,G1(async()=>{var g=[];if(_){var b=(k(),B)[_>>>2>>>0];g.length=d+1,g[d]=new Promise(z=>setTimeout(z,b,0))}else g.length=d;for(var T=0;T<d;++T){var I=ro(u+8*T);if(!(I in zl))return I;g[T]=zl[I]}return g=await Promise.race(g),delete zl[g],g})}var Gp,jp={},ev=()=>{if(!Gp){var u,d={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(u in jp)jp[u]===void 0?delete d[u]:d[u]=jp[u];var _=[];for(u in d)_.push(`${u}=${d[u]}`);Gp=_}return Gp};function tv(u,d){if(n)return De(19,1,u,d);u>>>=0,d>>>=0;var _,g=0,b=0;for(_ of ev()){var T=d+g;(k(),C)[u+b>>>2>>>0]=T,g+=gr(_,T,1/0)+1,b+=4}return 0}function rv(u,d){if(n)return De(20,1,u,d);u>>>=0,d>>>=0;var _=ev();for(var g of((k(),C)[u>>>2>>>0]=_.length,u=0,_))u+=wr(g)+1;return(k(),C)[d>>>2>>>0]=u,0}function sv(u){return n?De(21,1,u):52}function nv(u,d,_,g){return n?De(22,1,u,d,_,g):52}function ov(u,d,_,g){return n?De(23,1,u,d,_,g):70}var CS=[null,[],[]];function av(u,d,_,g){if(n)return De(24,1,u,d,_,g);d>>>=0,_>>>=0,g>>>=0;for(var b=0,T=0;T<_;T++){var I=(k(),C)[d>>>2>>>0],z=(k(),C)[d+4>>>2>>>0];d+=8;for(var F=0;F<z;F++){var Q=u,Se=(k(),V)[I+F>>>0],ze=CS[Q];Se===0||Se===10?((Q===1?S:M)(v1(ze)),ze.length=0):ze.push(Se)}b+=z}return(k(),C)[g>>>2>>>0]=b,0}function PS(u){return u>>>0}function LS(u,d){return J1(se(u>>>0).limits,d>>>0),1}function NS(u,d){return se(u>>>0).features.has(Z1[d])}function zS(u){return BigInt(se(u>>>0).size)}function RS(u){return BigInt(se(u>>>0).usage)}function $S(u,d){if(u>>>=0,d>>>=0){var _=yr(d+4);_={label:_,timestampWrites:d=(d=(k(),C)[d+12>>>2>>>0])!==0?{querySet:se((k(),C)[d+4>>>2>>>0]),beginningOfPassWriteIndex:(k(),C)[d+8>>>2>>>0],endOfPassWriteIndex:(k(),C)[d+12>>>2>>>0]}:void 0}}return d=se(u),u=hv(0),_=d.beginComputePass(_),gt[u>>>0]=_,u}function DS(u,d,_,g,b,T){_=Tt(_),b=Tt(b),T=Tt(T),se(u>>>0).copyBufferToBuffer(se(d>>>0),_,se(g>>>0),b,T)}function BS(u){var d=se(u>>>0);return u=dv(0),d=d.finish(),gt[u>>>0]=d,u}function US(u,d,_,g,b,T){T=Tt(T),se(u>>>0).resolveQuerySet(se(d>>>0),_,g,se(b>>>0),T)}function FS(u,d,_,g){se(u>>>0).dispatchWorkgroups(d,_,g)}function GS(u,d,_){_=Tt(_),se(u>>>0).dispatchWorkgroupsIndirect(se(d>>>0),_)}function jS(u){se(u>>>0).end()}function qS(u,d,_,g,b){g>>>=0,b>>>=0,u=se(u>>>0),_=se(_>>>0),g==0?u.setBindGroup(d,_):u.setBindGroup(d,_,(k(),C),b>>>2,g)}function WS(u,d){se(u>>>0).setPipeline(se(d>>>0))}function VS(u,d,_){se(u>>>0).Ee(se(d>>>0),_)}function HS(u,d){var _=se(u>>>0);return u=fv(0),d=_.getBindGroupLayout(d),gt[u>>>0]=d,u}function XS(u,d){function _(b){var T=(k(),C)[b+8>>>2>>>0],I=(k(),C)[b+32>>>2>>>0],z=(k(),C)[b+36>>>2>>>0],F=0;return uS(b,{327681:Q=>{F=(k(),C)[Q+8>>>2>>>0]}}),T?((I=ro(b+24))==-1&&(I=void 0),T={buffer:se(T),offset:ro(b+16),size:I}):T=se(I||z||F),{binding:(k(),C)[b+4>>>2>>>0],resource:T}}u>>>=0,d={label:yr(4+(d>>>=0)),layout:se((k(),C)[d+12>>>2>>>0]),entries:(function(b,T){for(var I=[],z=0;z<b;++z)I.push(_(T+40*z));return I})((k(),C)[d+16>>>2>>>0],(k(),C)[d+20>>>2>>>0])},u=se(u);var g=pv(0);return cS(g,u.createBindGroup(d)),g}function KS(u,d){var _;return u>>>=0,(d>>>=0)&&(_={label:yr(d+4)}),d=se(u),u=mv(0),_=d.createCommandEncoder(_),gt[u>>>0]=_,u}function YS(u,d){u>>>=0,d>>>=0,d={type:hS[(k(),B)[d+12>>>2>>>0]],count:(k(),C)[d+16>>>2>>>0]};var _=se(u);return u=_v(0),d=_.createQuerySet(d),gt[u>>>0]=d,u}function QS(u,d){u=se(u>>>0).adapterInfo,d>>>=0,(k(),C)[d+52>>>2>>>0]=u.subgroupMinSize,(k(),C)[d+56>>>2>>>0]=u.subgroupMaxSize;var _=u.vendor+u.architecture+u.device+u.description,g=wr(_)+1,b=tn(g);return b&&gr(_,b,g),_=b,g=wr(u.vendor),Rl(d+4,_,g),_+=g,g=wr(u.architecture),Rl(d+12,_,g),_+=g,g=wr(u.device),Rl(d+20,_,g),Rl(d+28,_+g,wr(u.description)),(k(),B)[d+36>>>2>>>0]=2,u=u.isFallbackAdapter?3:4,(k(),B)[d+40>>>2>>>0]=u,(k(),C)[d+44>>>2>>>0]=0,(k(),C)[d+48>>>2>>>0]=0,1}var JS={"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 ZS(u,d){d>>>=0;var _=se(u>>>0);u=tn(4*_.features.size);var g=0,b=0;for(let T of _.features)0<=(_=JS[T])&&((k(),B)[u+g>>>2>>>0]=_,g+=4,b++);(k(),C)[d+4>>>2>>>0]=u,(k(),C)[d>>>2>>>0]=b}function eO(u,d){return J1(se(u>>>0).limits,d>>>0),1}function tO(u,d){se(u>>>0).pushErrorScope(fS[d])}function rO(u,d,_){d>>>=0,_>>>=0,u=se(u>>>0),d=Array.from((k(),B).subarray(_>>>2>>>0,_+4*d>>>2>>>0),g=>se(g)),u.submit(d)}function sO(u,d,_,g,b){_=Tt(_),g>>>=0,b>>>=0,u=se(u>>>0),d=se(d>>>0),g=(k(),V).subarray(g>>>0,g+b>>>0),u.writeBuffer(d,_,g,0,b)}n||(function(){for(var u=e.numThreads-1;u--;)h1();Me.push(async()=>{var d=(async function(){if(!n)return Promise.all(ot.map(m1))})();xe++,await d,--xe==0&&We&&(d=We,We=null,d())})})(),n||(Cr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),Ie()),e.wasmBinary&&(f=e.wasmBinary),e.stackSave=()=>ue(),e.stackRestore=u=>ce(u),e.stackAlloc=u=>Dl(u),e.setValue=function(u,d,_="i8"){switch(_.endsWith("*")&&(_="*"),_){case"i1":case"i8":(k(),U)[u>>>0]=d;break;case"i16":(k(),q)[u>>>1>>>0]=d;break;case"i32":(k(),B)[u>>>2>>>0]=d;break;case"i64":(k(),P)[u>>>3>>>0]=BigInt(d);break;case"float":(k(),te)[u>>>2>>>0]=d;break;case"double":(k(),le)[u>>>3>>>0]=d;break;case"*":(k(),C)[u>>>2>>>0]=d;break;default:Fe(`invalid type for setValue: ${_}`)}},e.getValue=function(u,d="i8"){switch(d.endsWith("*")&&(d="*"),d){case"i1":case"i8":return(k(),U)[u>>>0];case"i16":return(k(),q)[u>>>1>>>0];case"i32":return(k(),B)[u>>>2>>>0];case"i64":return(k(),P)[u>>>3>>>0];case"float":return(k(),te)[u>>>2>>>0];case"double":return(k(),le)[u>>>3>>>0];case"*":return(k(),C)[u>>>2>>>0];default:Fe(`invalid type for getValue: ${d}`)}},e.UTF8ToString=Js,e.stringToUTF8=gr,e.lengthBytesUTF8=wr;var iv,lv,qp,$l,Yt,tn,cv,uv,pv,fv,dv,mv,hv,_v,gv,wv,xv,Wp,Vp,Hp,Xp,so,Kp,yv,Yp,bv,vv,kv,Qp,Ev,Av,Jp,ge,no,Tv,ce,Dl,ue,Mv,Zp,Sv,Ov,Iv,ef,Cv,Pv,Lv,Nv,zv,Rv,$v,Dv,Bv,Uv,Fv,Gv,jv,qv,Wv,Vv,Hv,Xv,Kv,Yv,Qv,Jv,Zv,ek,tk,rk,sk,nk,ok,ak,ik,lk,ck,uk,pk,fk,dk,mk,hk,br,nO=[Ir,us,w1,k1,E1,A1,T1,M1,S1,O1,I1,C1,P1,L1,N1,z1,H1,X1,K1,tv,rv,sv,nv,ov,av],tf={925676:(u,d,_,g,b)=>{if(e===void 0||!e.Uc)return 1;if((u=Js(Number(u>>>0))).startsWith("./")&&(u=u.substring(2)),!(u=e.Uc.get(u)))return 2;if(d=Number(d>>>0),_=Number(_>>>0),g=Number(g>>>0),d+_>u.byteLength)return 3;try{let T=u.subarray(d,d+_);switch(b){case 0:(k(),V).set(T,g>>>0);break;case 1:e.ad?e.ad(g,T):e.oe(g,T);break;default:return 4}return 0}catch{return 4}},926500:(u,d,_)=>{e.Sd(u,(k(),V).subarray(d>>>0,d+_>>>0))},926564:()=>e.me(),926606:u=>{e.jd(u)},926643:()=>typeof wasmOffsetConverter<"u"};function oO(u,d,_,g){var b=ue();try{return Dv(u,d,_,g)}catch(T){if(ce(b),T!==T+0)throw T;ge(1,0)}}function aO(u,d,_){var g=ue();try{return zv(u,d,_)}catch(b){if(ce(g),b!==b+0)throw b;ge(1,0)}}function iO(u,d,_){var g=ue();try{Iv(u,d,_)}catch(b){if(ce(g),b!==b+0)throw b;ge(1,0)}}function lO(u,d){var _=ue();try{return ef(u,d)}catch(g){if(ce(_),g!==g+0)throw g;ge(1,0)}}function cO(u){var d=ue();try{Cv(u)}catch(_){if(ce(d),_!==_+0)throw _;ge(1,0)}}function uO(u,d,_,g,b,T,I){var z=ue();try{return Nv(u,d,_,g,b,T,I)}catch(F){if(ce(z),F!==F+0)throw F;ge(1,0)}}function pO(u,d){var _=ue();try{Bv(u,d)}catch(g){if(ce(_),g!==g+0)throw g;ge(1,0)}}function fO(u,d,_,g,b,T){var I=ue();try{Pv(u,d,_,g,b,T)}catch(z){if(ce(I),z!==z+0)throw z;ge(1,0)}}function dO(u,d,_,g){var b=ue();try{$v(u,d,_,g)}catch(T){if(ce(b),T!==T+0)throw T;ge(1,0)}}function mO(u,d,_,g,b,T,I){var z=ue();try{Fv(u,d,_,g,b,T,I)}catch(F){if(ce(z),F!==F+0)throw F;ge(1,0)}}function hO(u,d,_,g,b,T,I){var z=ue();try{Gv(u,d,_,g,b,T,I)}catch(F){if(ce(z),F!==F+0)throw F;ge(1,0)}}function _O(u,d,_,g,b,T,I,z){var F=ue();try{Qv(u,d,_,g,b,T,I,z)}catch(Q){if(ce(F),Q!==Q+0)throw Q;ge(1,0)}}function gO(u,d,_,g,b,T,I,z,F,Q,Se,ze){var Ge=ue();try{jv(u,d,_,g,b,T,I,z,F,Q,Se,ze)}catch(ne){if(ce(Ge),ne!==ne+0)throw ne;ge(1,0)}}function wO(u,d,_,g,b){var T=ue();try{return Uv(u,d,_,g,b)}catch(I){if(ce(T),I!==I+0)throw I;ge(1,0)}}function xO(u,d,_,g,b){var T=ue();try{Lv(u,d,_,g,b)}catch(I){if(ce(T),I!==I+0)throw I;ge(1,0)}}function yO(u,d,_,g,b,T,I,z){var F=ue();try{Rv(u,d,_,g,b,T,I,z)}catch(Q){if(ce(F),Q!==Q+0)throw Q;ge(1,0)}}function bO(u){var d=ue();try{return Jv(u)}catch(_){if(ce(d),_!==_+0)throw _;ge(1,0)}}function vO(u,d,_){var g=ue();try{return Zv(u,d,_)}catch(b){if(ce(g),b!==b+0)throw b;ge(1,0)}}function kO(u,d){var _=ue();try{return pk(u,d)}catch(g){if(ce(_),g!==g+0)throw g;return ge(1,0),0n}}function EO(u,d,_,g,b){var T=ue();try{ek(u,d,_,g,b)}catch(I){if(ce(T),I!==I+0)throw I;ge(1,0)}}function AO(u){var d=ue();try{return qv(u)}catch(_){if(ce(d),_!==_+0)throw _;return ge(1,0),0n}}function TO(u,d,_,g,b,T){var I=ue();try{return Kv(u,d,_,g,b,T)}catch(z){if(ce(I),z!==z+0)throw z;ge(1,0)}}function MO(u,d,_,g,b,T){var I=ue();try{return tk(u,d,_,g,b,T)}catch(z){if(ce(I),z!==z+0)throw z;ge(1,0)}}function SO(u,d,_,g,b,T){var I=ue();try{return rk(u,d,_,g,b,T)}catch(z){if(ce(I),z!==z+0)throw z;ge(1,0)}}function OO(u,d,_,g,b,T,I,z){var F=ue();try{return Yv(u,d,_,g,b,T,I,z)}catch(Q){if(ce(F),Q!==Q+0)throw Q;ge(1,0)}}function IO(u,d,_,g,b){var T=ue();try{return sk(u,d,_,g,b)}catch(I){if(ce(T),I!==I+0)throw I;return ge(1,0),0n}}function CO(u,d,_,g){var b=ue();try{return nk(u,d,_,g)}catch(T){if(ce(b),T!==T+0)throw T;ge(1,0)}}function PO(u,d,_,g){var b=ue();try{return ok(u,d,_,g)}catch(T){if(ce(b),T!==T+0)throw T;ge(1,0)}}function LO(u,d,_,g,b,T,I,z,F,Q,Se,ze){var Ge=ue();try{return ak(u,d,_,g,b,T,I,z,F,Q,Se,ze)}catch(ne){if(ce(Ge),ne!==ne+0)throw ne;ge(1,0)}}function NO(u,d,_,g,b,T,I,z,F,Q,Se){var ze=ue();try{ik(u,d,_,g,b,T,I,z,F,Q,Se)}catch(Ge){if(ce(ze),Ge!==Ge+0)throw Ge;ge(1,0)}}function zO(u,d,_,g,b,T,I,z,F,Q,Se,ze,Ge,ne,ut,St){var pt=ue();try{lk(u,d,_,g,b,T,I,z,F,Q,Se,ze,Ge,ne,ut,St)}catch(ds){if(ce(pt),ds!==ds+0)throw ds;ge(1,0)}}function RO(u,d,_,g){var b=ue();try{return ck(u,d,_,g)}catch(T){if(ce(b),T!==T+0)throw T;ge(1,0)}}function $O(u,d,_,g,b){var T=ue();try{return uk(u,d,_,g,b)}catch(I){if(ce(T),I!==I+0)throw I;ge(1,0)}}function DO(u,d,_){var g=ue();try{return Vv(u,d,_)}catch(b){if(ce(g),b!==b+0)throw b;return ge(1,0),0n}}function BO(u,d,_){var g=ue();try{return Wv(u,d,_)}catch(b){if(ce(g),b!==b+0)throw b;ge(1,0)}}function UO(u,d,_){var g=ue();try{return Hv(u,d,_)}catch(b){if(ce(g),b!==b+0)throw b;ge(1,0)}}function FO(u,d,_,g){var b=ue();try{Xv(u,d,_,g)}catch(T){if(ce(b),T!==T+0)throw T;ge(1,0)}}function Bl(){if(0<xe)We=Bl;else if(n)w?.(e),ae();else{for(var u=Me;0<u.length;)u.shift()(e);0<xe?We=Bl:(e.calledRun=!0,L||(ae(),w?.(e)))}}return n||(br=await tt(),Bl()),e.PTR_SIZE=4,e.webgpuInit=u=>{let d=new WeakMap,_,g,b=1;e.webgpuRegisterDevice=z=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(z){var F=d.get(z);if(!F){let Q=((Se,ze=0)=>{var Ge=xv(ze);return ze=wv(ze,Ge),gt[Ge>>>0]=Se.queue,gt[ze>>>0]=Se,ze})(z,F=uv(0));F=[b++,F,Q],d.set(z,F)}return _=z,g=F[0],F}_=void 0,g=0};let T=new Map;e.webgpuOnCreateSession=z=>{if(g!==void 0){var F=g;if(g=void 0,z){let Q=qp(F);T.set(z,Q),F===0&&u(_??se(Q))}_=void 0}},e.webgpuOnReleaseSession=z=>{T.delete(z)};let I=Symbol("gpuBufferMetadata");e.webgpuRegisterBuffer=(z,F,Q)=>{if(Q)return z[I]=[Q,NaN],Q;if(Q=z[I])return Q[1]++,Q[0];if((F=T.get(F))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return F=((Se,ze=0)=>(Se.mapState==="unmapped"||Fe(),ze=gv(ze),gt[ze>>>0]=Se,ze))(z,F),z[I]=[F,1],F},e.webgpuUnregisterBuffer=z=>{let F=z[I];if(!F)throw Error("Buffer is not registered");F[1]--,F[1]===0&&(cv(F[0]),delete z[I])},e.webgpuGetBuffer=z=>se(z),e.webgpuCreateDownloader=(z,F,Q)=>{if((Q=T.get(Q))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let Se=se(Q),ze=16*Math.ceil(Number(F)/16);return async()=>{let Ge=Se.createBuffer({size:ze,usage:9});try{let ne=Se.createCommandEncoder();return ne.copyBufferToBuffer(z,0,Ge,0,ze),Se.queue.submit([ne.finish()]),await Ge.mapAsync(GPUMapMode.READ),Ge.getMappedRange().slice(0,F)}finally{Ge.destroy()}}},e.ad=(z,F)=>{var Q=F.buffer;let Se=F.byteOffset,ze=F.byteLength;if(F=16*Math.ceil(Number(ze)/16),z=se(z),!_){var Ge=qp(g);_=se(Ge)}let ne=(Ge=_.createBuffer({mappedAtCreation:!0,size:F,usage:6})).getMappedRange();new Uint8Array(ne).set(new Uint8Array(Q,Se,ze)),Ge.unmap(),(Q=_.createCommandEncoder()).copyBufferToBuffer(Ge,0,z,0,F),_.queue.submit([Q.finish()]),Ge.destroy()}},e.webnnInit=u=>{let d=u[0];[e.me,e.jd,e.webnnEnsureTensor,e.Sd,e.webnnDownloadTensor,e.le,e.webnnEnableTraceEvent]=u.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,T)=>d.registerMLTensor(_,g,b,T),e.webnnCreateMLContext=_=>d.createMLContext(_),e.webnnRegisterMLConstant=(_,g,b,T,I,z)=>d.registerMLConstant(_,g,b,T,I,e.Uc,z),e.webnnRegisterGraphInput=d.registerGraphInput.bind(d),e.webnnIsGraphInput=d.isGraphInput.bind(d),e.webnnRegisterGraphOutput=d.registerGraphOutput.bind(d),e.webnnIsGraphOutput=d.isGraphOutput.bind(d),e.webnnCreateTemporaryTensor=d.createTemporaryTensor.bind(d),e.webnnIsGraphInputOutputTypeSupported=d.isGraphInputOutputTypeSupported.bind(d)},J?e:new Promise((u,d)=>{w=u,x=d})}var mA,bE,RL=be(()=>{"use strict";mA=yE,bE=globalThis.self?.name?.startsWith("em-pthread"),bE&&yE()}),Tf,Gf,vE,zt,hA,ec,kE,EE,Mf,AE,Sf,_A,Of,gA,Qf=be(()=>{"use strict";Yf(),Tf=typeof location>"u"?void 0:location.origin,Gf=import.meta.url>"file:"&&import.meta.url<"file;",vE=()=>{if(Gf){let t=URL;return new URL(new t("ort.webgpu.bundle.min.mjs",import.meta.url).href,Tf).href}return import.meta.url},zt=vE(),hA=()=>{if(zt&&!zt.startsWith("blob:"))return zt.substring(0,zt.lastIndexOf("/")+1)},ec=(t,e)=>{try{let r=e??zt;return(r?new URL(t,r):new URL(t)).origin===Tf}catch{return!1}},kE=(t,e)=>{let r=e??zt;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},EE=(t,e)=>`${e??"./"}${t}`,Mf=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},AE=async t=>(await import(t)).default,Sf=(zL(),ac(pA)).default,_A=async()=>{if(!zt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(ec(zt))return[void 0,Sf()];let t=await Mf(zt);return[t,Sf(t)]},Of=(RL(),ac(dA)).default,gA=async(t,e,r,s)=>{let n=Of&&!(t||e);if(n)if(zt)n=ec(zt)||s&&!r;else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,Of];{let o="ort-wasm-simd-threaded.asyncify.mjs",a=t??kE(o,e),i=r&&a&&!ec(a,e),l=i?await Mf(a):a??EE(o,e);return[i?l:void 0,await AE(l)]}}}),If,tc,_o,Cf,TE,ME,SE,Jf,Ue,Ss=be(()=>{"use strict";Qf(),tc=!1,_o=!1,Cf=!1,TE=()=>{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}},ME=()=>{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}},SE=()=>{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}},Jf=async t=>{if(tc)return Promise.resolve();if(_o)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Cf)throw new Error("previous call to 'initializeWebAssembly()' failed.");_o=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!SE())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!ME())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=TE();r>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),t.numThreads=r=1);let n=t.wasmPaths,o=typeof n=="string"?n:void 0,a=n?.mjs,i=a?.href??a,l=n?.wasm,c=l?.href??l,p=t.wasmBinary,[f,m]=await gA(i,o,r>1,!!p||!!c),h=!1,w=[];if(e>0&&w.push(new Promise(x=>{setTimeout(()=>{h=!0,x()},e)})),w.push(new Promise((x,v)=>{let E={numThreads:r};if(p)E.wasmBinary=p,E.locateFile=A=>A;else if(c||o)E.locateFile=A=>c??o+A;else if(i&&i.indexOf("blob:")!==0)E.locateFile=A=>new URL(A,i).href;else if(f){let A=hA();A&&(E.locateFile=S=>A+S)}m(E).then(A=>{_o=!1,tc=!0,If=A,x(),f&&URL.revokeObjectURL(f)},A=>{_o=!1,Cf=!0,v(A)})})),await Promise.race(w),h)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},Ue=()=>{if(tc&&If)return If;throw new Error("WebAssembly is not initialized yet.")}}),Rt,lc,Pe,Zf=be(()=>{"use strict";Ss(),Rt=(t,e)=>{let r=Ue(),s=r.lengthBytesUTF8(t)+1,n=r._malloc(s);return r.stringToUTF8(t,n,s),e.push(n),n},lc=(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")lc(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}`)})},Pe=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)}}}),wA,$L=be(()=>{"use strict";Ss(),Zf(),wA=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=Rt(t.tag,s)),r=e._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),r===0&&Pe("Can't create run options."),t?.extra!==void 0&&lc(t.extra,"",new WeakSet,(a,i)=>{let l=Rt(a,s),c=Rt(i,s);e._OrtAddRunConfigEntry(r,l,c)!==0&&Pe(`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}}}),OE,IE,CE,rc,Br,PE,xA,DL=be(()=>{"use strict";Ss(),Zf(),OE=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}`)}},IE=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},CE=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)},rc=(t,e,r,s)=>{let n=Rt(e,s),o=Rt(r,s);Ue()._OrtAddSessionConfigEntry(t,n,o)!==0&&Pe(`Can't set a session config entry: ${e} - ${r}.`)},Br=(t,e,r,s)=>{let n=Rt(e,s),o=Rt(r,s);t.push([n,o])},PE=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&&rc(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&&Br(a,"enableGraphCapture","1",r),typeof h.preferredLayout=="string"&&Br(a,"preferredLayout",h.preferredLayout,r),h.forceCpuNodeNames){let x=Array.isArray(h.forceCpuNodeNames)?h.forceCpuNodeNames:[h.forceCpuNodeNames];Br(a,"forceCpuNodeNames",x.join(`
13
+ `),r)}h.validationMode&&Br(a,"validationMode",h.validationMode,r)}let m=Ue().webgpuRegisterDevice(f);if(m){let[h,w,x]=m;Br(a,"deviceId",h.toString(),r),Br(a,"webgpuInstance",w.toString(),r),Br(a,"webgpuDevice",x.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=Rt(o,r),l=a.length,c=0,p=0;if(l>0){c=Ue()._malloc(l*Ue().PTR_SIZE),r.push(c),p=Ue()._malloc(l*Ue().PTR_SIZE),r.push(p);for(let f=0;f<l;f++)Ue().setValue(c+f*Ue().PTR_SIZE,a[f][0],"*"),Ue().setValue(p+f*Ue().PTR_SIZE,a[f][1],"*")}await Ue()._OrtAppendExecutionProvider(t,i,c,p,l)!==0&&Pe(`Can't append execution provider: ${o}.`)}},xA=async t=>{let e=Ue(),r=0,s=[],n=t||{};CE(n);try{let o=OE(n.graphOptimizationLevel??"all"),a=IE(n.executionMode??"sequential"),i=typeof n.logId=="string"?Rt(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let p=typeof n.optimizedModelFilePath=="string"?Rt(n.optimizedModelFilePath,s):0;if(r=e._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,l,c,p),r===0&&Pe("Can't create session options."),n.executionProviders&&await PE(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);rc(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=Rt(f,s);e._OrtAddFreeDimensionOverride(r,h,m)!==0&&Pe(`Can't set a free dimension override: ${f} - ${m}.`)}return n.extra!==void 0&&lc(n.extra,"",new WeakSet,(f,m)=>{rc(r,f,m,s)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&Pe("Can't release session options."),s.forEach(a=>e._free(a)),o}}}),ks,oc,un,bo,cc,ed,td,jf,pn=be(()=>{"use strict";ks=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}`)}},oc=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${t}`)}},un=(t,e)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][t],s=typeof e=="number"?e:e.reduce((n,o)=>n*o,1);return r>0?Math.ceil(s*r):void 0},bo=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}`)}},cc=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}`)}},ed=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",jf=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}`)}}}),rd,yA=be(()=>{"use strict";Yf(),rd=async t=>{if(typeof t=="string"){let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let r=e.headers.get("Content-Length"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${t}, no response body.`);let n=e.body.getReader(),o;try{o=new ArrayBuffer(s)}catch(i){if(i instanceof RangeError){let l=Math.ceil(s/65536);o=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let a=0;for(;;){let{done:i,value:l}=await n.read();if(i)break;let c=l.byteLength;new Uint8Array(o,a,c).set(l),a+=c}return new Uint8Array(o,0,s)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),bA,BL=be(()=>{"use strict";pn(),bA=(t,e)=>new(bo(e))(t)}),LE,NE,zE,RE,vA,$E,kt,kA=be(()=>{"use strict";pn(),LE=["V","I","W","E","F"],NE=(t,e)=>{console.log(`[${LE[t]},${new Date().toISOString()}]${e}`)},vA=(t,e)=>{zE=t,RE=e},$E=(t,e)=>{let r=cc(t),s=cc(zE);r>=s&&NE(r,typeof e=="function"?e():e)},kt=(...t)=>{RE&&$E(...t)}}),Pf,qf,Lf,DE,Nf,BE,zf,Rf,$f,UE,EA,UL=be(()=>{"use strict";pn(),kA(),Pf=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),qf=(t,e)=>{if(e==="int32")return t;let r=Pf.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(bo(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'`)}},Lf=(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}`)}},DE=1,Nf=()=>DE++,BE=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),zf=(t,e)=>{let r=Pf.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},Rf=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 zf(this.dataType,this.tensorShape)}destroy(){kt("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=Lf(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}},$f=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=BE.get(e),!a||o?.input.dataTypes.includes(a))throw new Error(`WebNN backend does not support data type: ${e}`);kt("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!==zf(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=qf(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 kt("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?Lf(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()}},UE=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=Nf();return this.tensorTrackersById.set(t,new $f(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){kt("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){kt("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=Nf(),a=new Rf({sessionId:t,context:n,tensor:e,dataType:r,shape:s});return this.tensorTrackersById.set(o,new $f(this,a)),this.externalTensors.add(a),o}async getCachedTensor(t,e,r,s,n,o,a){let i=this.getMLContext(t);for(let[c,p]of this.freeTensors.entries())if(p.canReuseTensor(i,e,r)){kt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}`);let f=this.freeTensors.splice(c,1)[0];return f.sessionId=t,f}kt("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 Rf({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)}},EA=(...t)=>new UE(...t)}),AA={};vo(AA,{WebNNBackend:()=>TA});var go,FE,TA,FL=be(()=>{"use strict";pn(),Ss(),BL(),UL(),kA(),go=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),FE=(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])},TA=class{constructor(t){this.tensorManager=EA(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,vA(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(t){kt("verbose",()=>`[WebNN] onRunStart {sessionId: ${t}}`),this.activeSessionId=t}onRunEnd(t){kt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${t}}`);let e=this.temporarySessionTensorIds.get(t);if(e){for(let r of e)kt("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=>FE(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){kt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,e,r,s,n){let o=go.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){kt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${e}, shape: ${r}}`);let s=go.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");kt("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 bA(r,e)}}registerMLTensor(t,e,r,s){let n=go.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.registerTensor(t,e,n,s);return kt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(t,e,r,s,n,o,a=!1){if(!o)throw new Error("External mounted files are not available.");let i=t;t.startsWith("./")&&(i=t.substring(2));let l=o.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(e+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(e,e+r).buffer,p;switch(n.dataType){case"float32":p=new Float32Array(c);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":p=new Int32Array(c);break;case"uint32":p=new Uint32Array(c);break;case"int64":if(a){let f=qf(new Uint8Array(c),"int64");p=new Int32Array(f.buffer),n.dataType="int32"}else p=new BigInt64Array(c);break;case"uint64":p=new BigUint64Array(c);break;case"int8":p=new Int8Array(c);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return kt("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=go.get(ks(e)),n=this.mlOpSupportLimitsBySessionId.get(t);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),GE,sd,nd,Ur,jE,Df,uc,od,ad,Bf,id,ld,cd,MA=be(()=>{"use strict";Ms(),$L(),DL(),pn(),Ss(),Zf(),yA(),GE=(t,e)=>{Ue()._OrtInit(t,e)!==0&&Pe("Can't initialize onnxruntime.")},sd=async t=>{GE(t.wasm.numThreads,cc(t.logLevel))},nd=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(FL(),ac(AA)).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])}},Ur=new Map,jE=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&&Pe("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)}},Df=(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&&Pe("Can't get session input/output metadata.");let i=Number(r.getValue(a,"*"));n=Number(r.getValue(a+o,"*"));let l=r.HEAP32[n/4];if(l===0)return[i,0];let c=r.HEAPU32[n/4+1],p=[];for(let f=0;f<c;f++){let m=Number(r.getValue(n+8+f*o,"*"));p.push(m!==0?r.UTF8ToString(m):Number(r.getValue(n+8+(f+c)*o,"*")))}return[i,l,p]}finally{r.stackRestore(s),n!==0&&r._OrtFree(n)}},uc=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]},od=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]=uc(t);let o=0,a=0,i=0,l=[],c=[],p=[];try{if([a,l]=await xA(e),e?.externalData&&n.mountExternalData){let M=[];for(let L of e.externalData){let O=typeof L=="string"?L:L.path;M.push(rd(typeof L=="string"?L:L.data).then(k=>{n.mountExternalData(O,k)}))}await Promise.all(M)}for(let M of e?.executionProviders??[])if((typeof M=="string"?M:M.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof M!="string"){let L=M,O=L?.context,k=L?.gpuDevice,G=L?.deviceType,H=L?.powerPreference;O?n.currentContext=O:k?n.currentContext=await n.webnnCreateMLContext(k):n.currentContext=await n.webnnCreateMLContext({deviceType:G,powerPreference:H})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(r,s,a),n.webgpuOnCreateSession?.(o),o===0&&Pe("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[f,m]=jE(o),h=!!e?.enableGraphCapture,w=[],x=[],v=[],E=[],A=[];for(let M=0;M<f;M++){let[L,O,k]=Df(o,M);L===0&&Pe("Can't get an input name."),c.push(L);let G=n.UTF8ToString(L);w.push(G),v.push(O===0?{name:G,isTensor:!1}:{name:G,isTensor:!0,type:oc(O),shape:k})}for(let M=0;M<m;M++){let[L,O,k]=Df(o,M+f);L===0&&Pe("Can't get an output name."),p.push(L);let G=n.UTF8ToString(L);x.push(G),E.push(O===0?{name:G,isTensor:!1}:{name:G,isTensor:!0,type:oc(O),shape:k});{if(h&&e?.preferredOutputLocation===void 0){A.push("gpu-buffer");continue}let H=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[G]??"cpu",U=n.webnnIsGraphOutput;if(H==="cpu"&&U&&U(o,G)){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(M=>M==="gpu-buffer"||M==="ml-tensor"||M==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(o),i===0&&Pe("Can't create IO binding."),S={handle:i,outputPreferredLocations:A,outputPreferredLocationsEncoded:A.map(M=>M==="ml-tensor-cpu-output"?"ml-tensor":M).map(M=>jf(M))}),Ur.set(o,[o,c,p,S,h,!1]),[o,w,x,v,E]}catch(f){throw c.forEach(m=>n._OrtFree(m)),p.forEach(m=>n._OrtFree(m)),i!==0&&n._OrtReleaseBinding(i)!==0&&Pe("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&Pe("Can't release session."),f}finally{n._free(r),a!==0&&n._OrtReleaseSessionOptions(a)!==0&&Pe("Can't release session options."),l.forEach(f=>n._free(f)),n.unmountExternalData?.()}},ad=t=>{let e=Ue(),r=Ur.get(t);if(!r)throw new Error(`cannot release session. invalid session id: ${t}`);let[s,n,o,a,i]=r;a&&(i&&e._OrtClearBoundOutputs(a.handle)!==0&&Pe("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&Pe("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&&Pe("Can't release session."),Ur.delete(t)},Bf=async(t,e,r,s,n,o,a=!1)=>{if(!t){e.push(0);return}let i=Ue(),l=i.PTR_SIZE,c=t[0],p=t[1],f=t[3],m=f,h,w;if(c==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&f!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let E=t[2].gpuBuffer;w=un(ks(c),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=un(ks(c),p);let A=i.webnnRegisterMLTensor;if(!A)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');h=A(s,E,ks(c),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,Rt(E[A],r),"*")}}else{let A=i.webnnIsGraphInput,S=i.webnnIsGraphOutput;if(c!=="string"&&A&&S){let M=i.UTF8ToString(n);if(A(s,M)||S(s,M)){let L=ks(c);w=un(L,p),m="ml-tensor";let O=i.webnnCreateTemporaryTensor,k=i.webnnUploadTensor;if(!O||!k)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let G=await O(s,L,p);k(G,new Uint8Array(E.buffer,E.byteOffset,E.byteLength)),h=G}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(),v=i.stackAlloc(4*p.length);try{p.forEach((A,S)=>i.setValue(v+S*l,A,l===4?"i32":"i64"));let E=i._OrtCreateTensor(ks(c),h,w,v,p.length,jf(m));E===0&&Pe(`Can't create tensor for input/output. session=${s}, index=${o}.`),e.push(E)}finally{i.stackRestore(x)}},id=async(t,e,r,s,n,o)=>{let a=Ue(),i=a.PTR_SIZE,l=Ur.get(t);if(!l)throw new Error(`cannot run inference. invalid session id: ${t}`);let c=l[0],p=l[1],f=l[2],m=l[3],h=l[4],w=l[5],x=e.length,v=s.length,E=0,A=[],S=[],M=[],L=[],O=[],k=a.stackSave(),G=a.stackAlloc(x*i),H=a.stackAlloc(x*i),U=a.stackAlloc(v*i),V=a.stackAlloc(v*i);try{[E,A]=wA(o),Gr("wasm prepareInputOutputTensor");for(let C=0;C<x;C++)await Bf(r[C],S,L,t,p[e[C]],e[C],h);for(let C=0;C<v;C++)await Bf(n[C],M,L,t,f[s[C]],x+s[C],h);jr("wasm prepareInputOutputTensor");for(let C=0;C<x;C++)a.setValue(G+C*i,S[C],"*"),a.setValue(H+C*i,p[e[C]],"*");for(let C=0;C<v;C++)a.setValue(U+C*i,M[C],"*"),a.setValue(V+C*i,f[s[C]],"*");if(m&&!w){let{handle:C,outputPreferredLocations:te,outputPreferredLocationsEncoded:le}=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}).`);Gr("wasm bindInputsOutputs");for(let P=0;P<x;P++){let N=e[P];await a._OrtBindInput(C,p[N],S[P])!==0&&Pe(`Can't bind input[${P}] for session=${t}.`)}for(let P=0;P<v;P++){let N=s[P];n[P]?.[3]?(O.push(M[P]),a._OrtBindOutput(C,f[N],M[P],0)!==0&&Pe(`Can't bind pre-allocated output[${P}] for session=${t}.`)):a._OrtBindOutput(C,f[N],0,le[N])!==0&&Pe(`Can't bind output[${P}] to ${te[P]} for session=${t}.`)}jr("wasm bindInputsOutputs"),Ur.set(t,[c,p,f,m,h,!0])}a.jsepOnRunStart?.(c),a.webnnOnRunStart?.(c);let q;m?q=await a._OrtRunWithBinding(c,m.handle,v,U,E):q=await a._OrtRun(c,H,G,x,V,v,U,E),q!==0&&Pe("failed to call OrtRun().");let Y=[],B=[];Gr("wasm ProcessOutputTensor");for(let C=0;C<v;C++){let te=Number(a.getValue(U+C*i,"*"));if(te===M[C]||O.includes(M[C])){Y.push(n[C]),te!==M[C]&&a._OrtReleaseTensor(te)!==0&&Pe("Can't release tensor.");continue}let le=a.stackSave(),P=a.stackAlloc(4*i),N=!1,$,J=0;try{a._OrtGetTensorData(te,P,P+i,P+2*i,P+3*i)!==0&&Pe(`Can't access output tensor data on index ${C}.`);let Ie=i===4?"i32":"i64",ae=Number(a.getValue(P,Ie));J=a.getValue(P+i,"*");let Fe=a.getValue(P+i*2,"*"),Je=Number(a.getValue(P+i*3,Ie)),tt=[];for(let Me=0;Me<Je;Me++)tt.push(Number(a.getValue(Fe+Me*i,Ie)));a._OrtFree(Fe)!==0&&Pe("Can't free memory for tensor dims.");let nt=tt.reduce((Me,xe)=>Me*xe,1);$=oc(ae);let at=m?.outputPreferredLocations[s[C]];if($==="string"){if(at==="gpu-buffer"||at==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Me=[];for(let xe=0;xe<nt;xe++){let We=a.getValue(J+xe*i,"*"),Ot=a.getValue(J+(xe+1)*i,"*"),ve=xe===nt-1?void 0:Ot-We;Me.push(a.UTF8ToString(We,ve))}Y.push([$,tt,Me,"cpu"])}else if(at==="gpu-buffer"&&nt>0){let Me=a.webgpuGetBuffer;if(!Me)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let xe=Me(J),We=un(ae,nt);if(We===void 0||!ed($))throw new Error(`Unsupported data type: ${$}`);N=!0;{a.webgpuRegisterBuffer(xe,t,J);let Ot=a.webgpuCreateDownloader(xe,We,t);Y.push([$,tt,{gpuBuffer:xe,download:async()=>{let ve=await Ot();return new(bo($))(ve)},dispose:()=>{a._OrtReleaseTensor(te)!==0&&Pe("Can't release tensor.")}},"gpu-buffer"])}}else if(at==="ml-tensor"&&nt>0){let Me=a.webnnEnsureTensor,xe=a.webnnIsGraphInputOutputTypeSupported;if(!Me||!xe)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(un(ae,nt)===void 0||!td($))throw new Error(`Unsupported data type: ${$}`);if(!xe(t,$,!1))throw new Error(`preferredLocation "ml-tensor" for ${$} output is not supported by current WebNN Context.`);let We=await Me(t,J,ae,tt,!1);N=!0,Y.push([$,tt,{mlTensor:We,download:a.webnnCreateMLTensorDownloader(J,$),dispose:()=>{a.webnnReleaseTensorId(J),a._OrtReleaseTensor(te)}},"ml-tensor"])}else if(at==="ml-tensor-cpu-output"&&nt>0){let Me=a.webnnCreateMLTensorDownloader(J,$)(),xe=Y.length;N=!0,B.push((async()=>{let We=[xe,await Me];return a.webnnReleaseTensorId(J),a._OrtReleaseTensor(te),We})()),Y.push([$,tt,[],"cpu"])}else{let Me=bo($),xe=new Me(nt);new Uint8Array(xe.buffer,xe.byteOffset,xe.byteLength).set(a.HEAPU8.subarray(J,J+xe.byteLength)),Y.push([$,tt,xe,"cpu"])}}finally{a.stackRestore(le),$==="string"&&J&&a._free(J),N||a._OrtReleaseTensor(te)}}m&&!h&&(a._OrtClearBoundOutputs(m.handle)!==0&&Pe("Can't clear bound outputs."),Ur.set(t,[c,p,f,m,h,!1]));for(let[C,te]of await Promise.all(B))Y[C][2]=te;return jr("wasm ProcessOutputTensor"),Y}finally{a.webnnOnRunEnd?.(c),a.stackRestore(k),r.forEach(q=>{q&&q[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(q[2].gpuBuffer)}),n.forEach(q=>{q&&q[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(q[2].gpuBuffer)}),S.forEach(q=>a._OrtReleaseTensor(q)),M.forEach(q=>a._OrtReleaseTensor(q)),L.forEach(q=>a._free(q)),E!==0&&a._OrtReleaseRunOptions(E),A.forEach(q=>a._free(q))}},ld=t=>{let e=Ue(),r=Ur.get(t);if(!r)throw new Error("invalid session id");let s=r[0],n=e._OrtEndProfiling(s);n===0&&Pe("Can't get an profile file name."),e._OrtFree(n)},cd=t=>{let e=[];for(let r of t){let s=r[2];!Array.isArray(s)&&"buffer"in s&&e.push(s.buffer)}return e}}),Fr,jt,cn,wo,xo,sc,Uf,nc,ys,bs,qE,SA,OA,IA,CA,PA,LA,NA,zA=be(()=>{"use strict";Ms(),MA(),Ss(),Qf(),Fr=()=>!!He.wasm.proxy&&typeof document<"u",cn=!1,wo=!1,xo=!1,nc=new Map,ys=(t,e)=>{let r=nc.get(t);r?r.push(e):nc.set(t,[e])},bs=()=>{if(cn||!wo||xo||!jt)throw new Error("worker not ready")},qE=t=>{switch(t.data.type){case"init-wasm":cn=!1,t.data.err?(xo=!0,Uf[1](t.data.err)):(wo=!0,Uf[0]()),sc&&(URL.revokeObjectURL(sc),sc=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=nc.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}default:}},SA=async()=>{if(!wo){if(cn)throw new Error("multiple calls to 'initWasm()' detected.");if(xo)throw new Error("previous call to 'initWasm()' failed.");if(cn=!0,Fr())return new Promise((t,e)=>{jt?.terminate(),_A().then(([r,s])=>{try{jt=s,jt.onerror=o=>e(o),jt.onmessage=qE,Uf=[t,e];let n={type:"init-wasm",in:He};!n.in.wasm.wasmPaths&&(r||Gf)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href}),jt.postMessage(n),sc=r}catch(n){e(n)}},e)});try{await Jf(He.wasm),await sd(He),wo=!0}catch(t){throw xo=!0,t}finally{cn=!1}}},OA=async t=>{if(Fr())return bs(),new Promise((e,r)=>{ys("init-ep",[e,r]);let s={type:"init-ep",in:{epName:t,env:He}};jt.postMessage(s)});await nd(He,t)},IA=async t=>Fr()?(bs(),new Promise((e,r)=>{ys("copy-from",[e,r]);let s={type:"copy-from",in:{buffer:t}};jt.postMessage(s,[t.buffer])})):uc(t),CA=async(t,e)=>{if(Fr()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return bs(),new Promise((r,s)=>{ys("create",[r,s]);let n={type:"create",in:{model:t,options:{...e}}},o=[];t instanceof Uint8Array&&o.push(t.buffer),jt.postMessage(n,o)})}else return od(t,e)},PA=async t=>{if(Fr())return bs(),new Promise((e,r)=>{ys("release",[e,r]);let s={type:"release",in:t};jt.postMessage(s)});ad(t)},LA=async(t,e,r,s,n,o)=>{if(Fr()){if(r.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return bs(),new Promise((a,i)=>{ys("run",[a,i]);let l=r,c={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:s,options:o}};jt.postMessage(c,cd(l))})}else return id(t,e,r,s,n,o)},NA=async t=>{if(Fr())return bs(),new Promise((e,r)=>{ys("end-profiling",[e,r]);let s={type:"end-profiling",in:t};jt.postMessage(s)});ld(t)}}),Ff,WE,RA,GL=be(()=>{"use strict";Ms(),zA(),pn(),Yf(),yA(),Ff=(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()}`)}},WE=t=>{switch(t[3]){case"cpu":return new rr(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!ed(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=t[2];return rr.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 rr.fromMLTensor(r,{dataType:e,dims:t[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},RA=class{async fetchModelAndCopyToWasmMemory(t){return IA(await rd(t))}async loadModel(t,e){As();let r;typeof t=="string"?r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await CA(r,e),Ts()}async dispose(){return PA(this.sessionId)}async run(t,e,r){As();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)=>Ff(f,()=>`input "${this.inputNames[n[m]]}"`)),l=o.map((f,m)=>f?Ff(f,()=>`output "${this.outputNames[a[m]]}"`):null),c=await LA(this.sessionId,n,i,a,l,r),p={};for(let f=0;f<c.length;f++)p[this.outputNames[a[f]]]=o[f]??WE(c[f]);return Ts(),p}startProfiling(){}endProfiling(){NA(this.sessionId)}}}),$A={};vo($A,{OnnxruntimeWebAssemblyBackend:()=>Vf,initializeFlags:()=>Wf,wasmBackend:()=>DA});var Wf,Vf,DA,jL=be(()=>{"use strict";Ms(),zA(),GL(),Wf=()=>{(typeof He.wasm.initTimeout!="number"||He.wasm.initTimeout<0)&&(He.wasm.initTimeout=0);let t=He.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.`),He.wasm.simd=!1),typeof He.wasm.proxy!="boolean"&&(He.wasm.proxy=!1),typeof He.wasm.trace!="boolean"&&(He.wasm.trace=!1),typeof He.wasm.numThreads!="number"||!Number.isInteger(He.wasm.numThreads)||He.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)He.wasm.numThreads=1;else{let e=typeof navigator>"u"?yL("node:os").cpus().length:navigator.hardwareConcurrency;He.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Vf=class{async init(t){Wf(),await SA(),await OA(t)}async createInferenceSessionHandler(t,e){let r=new RA;return await r.loadModel(t,e),r}},DA=new Vf});Ms();Ms();Ms();var qL="1.25.0-dev.20260307-d626b568e0",WL=uA;{let t=(jL(),ac($A)).wasmBackend;Es("webgpu",t,5),Es("webnn",t,5),Es("cpu",t,10),Es("wasm",t,10)}Object.defineProperty(He.versions,"web",{value:qL,enumerable:!0});async function BA(t){let e=t.split("/").pop(),r;try{if(r=await tr(),r){let n=await r.match(t);if(n)return n}}catch(n){Z.warn(`Failed to load ${e} from cache:`,n)}let s=await me.fetch(t);if(!s.ok)throw new Error(`Failed to fetch ${e}: ${s.status} ${s.statusText}`);if(r)try{await r.put(t,s.clone())}catch(n){Z.warn(`Failed to cache ${e}:`,n)}return s}async function UA(t){let e=await BA(t);if(!e||typeof e=="string")return null;try{return await e.arrayBuffer()}catch(r){return Z.warn("Failed to read WASM binary:",r),null}}async function FA(t){if(ie.IS_SERVICE_WORKER_ENV||ie.IS_CHROME_AVAILABLE)return t;let e=await BA(t);if(!e||typeof e=="string")return null;try{let r=await e.text();r=r.replaceAll("globalThis.process?.versions?.node","false");let s=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(s)}catch(r){return Z.warn("Failed to read WASM factory:",r),null}}var GA="1.24.3";var jA="warning",pd={wasm:{},webgl:{},webgpu:{},versions:{common:GA},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);jA=t}},get logLevel(){return jA}};Object.defineProperty(pd,"logLevel",{enumerable:!0});var qA=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let 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 v=0;v<n;v++){let E=(t.data[f++]-c[0])*l[0],A=(t.data[m++]-c[1])*l[1],S=(t.data[h++]-c[2])*l[2],M=w===-1?255:(t.data[w++]-c[3])*l[3];s.fillStyle="rgba("+E+","+A+","+S+","+M+")",s.fillRect(v,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")},WA=(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,c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,h=0,w=1,x=2,v=3,E=0,A=f,S=f*2,M=-1;i==="RGBA"?(E=0,A=f,S=f*2,M=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 L=0;L<o*n;h+=m,w+=m,x+=m,v+=m,L++)s.data[h]=(t.data[E++]-p[0])*c[0],s.data[w]=(t.data[A++]-p[1])*c[1],s.data[x]=(t.data[S++]-p[2])*c[2],s.data[v]=M===-1?255:(t.data[M++]-p[3])*c[3]}else throw new Error("Can not access image data");return s};var fd=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,m=0,h=1,w=2,x=3,v=0,E=c,A=c*2,S=-1;i==="RGB"&&(f=3,m=0,h=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(v=0,A=c,E=c*2):l==="BGR"&&(A=0,E=c,v=c*2);for(let L=0;L<c;L++,m+=f,w+=f,h+=f,x+=f)p[v++]=(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 bt("float32",p,[1,4,r,s]):new bt("float32",p,[1,3,r,s])},VA=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")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){let p=l();p.width=t.width,p.height=t.height;let f=c(p);if(f!=null){let 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=c(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=c(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,fd(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,f)=>{let m=l(),h=c(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(fd(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return fd(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},HA=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new bt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},XA=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new bt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},KA=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new bt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},YA=(t,e,r)=>new bt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]});var 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]]),ko=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),QA=!1,JA=()=>{if(!QA){QA=!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),ko.set(BigInt64Array,"int64")),e&&(Os.set("uint64",BigUint64Array),ko.set(BigUint64Array,"uint64")),s?(Os.set("float16",r),ko.set(r,"float16")):Os.set("float16",Uint16Array)}};var ZA=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},e2=(t,e)=>{switch(t.location){case"cpu":return new bt(t.type,t.data,e);case"cpu-pinned":return new bt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new bt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new bt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new bt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}};var bt=class{constructor(e,r,s){JA();let n,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,o=e.dims,e.location){case"cpu-pinned":{let i=Os.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,l;if(typeof e=="string")if(n=e,l=s,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{let c=Os.get(e);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&c===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${c.name} as data.`);e==="uint64"||e==="int64"?i=c.from(r,BigInt):i=c.from(r)}else if(r instanceof c)i=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&r instanceof Uint16Array&&c!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${n} tensor's data must be type of ${c}`)}else if(l=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let c=typeof e[0];if(c==="string")n="string",i=e;else if(c==="boolean")n="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(e);else{let c=ko.get(e.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=c,i=e}if(l===void 0)l=[i.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");o=l,this.cpuData=i,this.dataLocation="cpu"}let a=ZA(o);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=o,this.size=a}static async fromImage(e,r){return VA(e,r)}static fromTexture(e,r){return HA(e,r)}static fromGpuBuffer(e,r){return XA(e,r)}static fromMLTensor(e,r){return KA(e,r)}static fromPinnedBuffer(e,r,s){return YA(e,r,s)}toDataURL(e){return qA(this,e)}toImageData(e){return WA(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return e2(this,e)}};var pc=bt;var VL=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}});function n2(t){return t<=Ct.DEBUG?0:t<=Ct.INFO?2:t<=Ct.WARNING||t<=Ct.ERROR?3:4}var HL={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},qt=[],dd,dn,t2=Symbol.for("onnxruntime");if(t2 in globalThis)dn=globalThis[t2];else if(ie.IS_NODE_ENV){switch(dn=yf,process.platform){case"win32":qt.push("dml");break;case"linux":process.arch==="x64"&&qt.push("cuda");break;case"darwin":qt.push("coreml");break}qt.push("webgpu"),qt.push("cpu"),dd=["cpu"]}else dn=ud,ie.IS_WEBNN_AVAILABLE&&qt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),ie.IS_WEBGPU_AVAILABLE&&qt.push("webgpu"),qt.push("wasm"),dd=["wasm"];var XL=dn.InferenceSession;function o2(t=null){if(!t)return dd;switch(t){case"auto":return qt;case"gpu":return qt.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(qt.includes(t))return[VL[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${qt.join(", ")}.`)}var r2=Promise.resolve(),fn=null;async function KL(){if(fn)return fn;if(!(me.useWasmCache&&typeof lt?.wasm?.wasmPaths=="object"&&lt?.wasm?.wasmPaths?.wasm&&lt?.wasm?.wasmPaths?.mjs)){if(ie.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return fn=Promise.resolve(),fn}return fn=(async()=>{let e=lt.wasm.wasmPaths,r=!1;await Promise.all([e.wasm&&!df(e.wasm)?(async()=>{try{let s=await UA(mf(e.wasm));s&&(lt.wasm.wasmBinary=s,r=!0)}catch(s){Z.warn("Failed to pre-load WASM binary:",s)}})():Promise.resolve(),e.mjs&&!df(e.mjs)?(async()=>{try{let s=await FA(mf(e.mjs));s&&(lt.wasm.wasmPaths.mjs=s)}catch(s){Z.warn("Failed to pre-load WASM factory:",s)}})():Promise.resolve()]),r||(lt.wasm.wasmPaths.mjs=e.mjs)})(),fn}async function fc(t,e,r){await KL();let s=n2(me.logLevel??Ct.WARNING),n=()=>XL.create(t,{logSeverityLevel:s,...e}),o=await(ie.IS_WEB_ENV?r2=r2.then(n):n());return o.config=r,o}var s2=Promise.resolve();async function dc(t,e){let r=()=>t.run(e);return ie.IS_WEB_ENV?s2=s2.then(r):r()}function mc(t){return t instanceof dn.Tensor}var lt=dn?.env;function Eo(){return lt?.wasm?.proxy}if(lt){let t=function(e){let r=n2(e);lt.logLevel=HL[r]};if(lt.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&lt.versions?.web&&!lt.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${lt.versions.web}/dist/`;lt.wasm.wasmPaths=ie.IS_SAFARI?{mjs:`${e}ort-wasm-simd-threaded.mjs`,wasm:`${e}ort-wasm-simd-threaded.wasm`}:{mjs:`${e}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${e}ort-wasm-simd-threaded.asyncify.wasm`}}lt.wasm.proxy=!1}lt.webgpu&&(lt.webgpu.powerPreference="high-performance"),t(me.logLevel??Ct.WARNING),me.backends.onnx={...lt,setLogLevel:t}}var qr=async(t,e,r)=>{let s=await fc(new Uint8Array(t),e);return(async n=>{let o=Eo(),a=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(o?c.clone():c).ort_tensor])),i=await dc(s,a);return Array.isArray(r)?r.map(l=>new R(i[l])):new R(i[r])})},fr=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=qr([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=qr([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=qr([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=qr([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=qr([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=qr([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=qr([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=qr([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}};var a2=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"}),md=ie.IS_NODE_ENV?"cpu":"wasm";function hc(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 (${md}).`),md):md}var c2=(function(){let t;return async function(){if(t===void 0)if(!ie.IS_WEBGPU_AVAILABLE)t=!1;else try{t=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{t=!1}return t}})(),vt=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),i2=vt.fp32,l2=Object.freeze({[a2.wasm]:vt.q8}),Ao=Object.freeze({[vt.fp32]:"",[vt.fp16]:"_fp16",[vt.int8]:"_int8",[vt.uint8]:"_uint8",[vt.q8]:"_quantized",[vt.q4]:"_q4",[vt.q4f16]:"_q4f16",[vt.bnb4]:"_bnb4"});function _c(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===vt.auto){if(s){let l=typeof s=="string"?s:s?.[e];if(l&&l!==vt.auto&&vt.hasOwnProperty(l))return l}i=l2[r]??i2}else o&&vt.hasOwnProperty(o)?i=o:i=l2[r]??i2;return a&&n&&n(`dtype not specified for "${e}". Using the default dtype (${i}) for this device (${r}).`),i}var Er=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 R=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 mc(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new pc(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=dr(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 YL(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=dr(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:dr(m,this.dims[p],p,!1),h=h===null?this.dims[p]:dr(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(),c=!0;for(let p=1;p<n.length;++p)if(s[p][0]!==0||s[p][1]!==this.dims[p]){c=!1;break}if(c){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 QL(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,r=!1){return this.norm(1,e,r)}norm(e="fro",r=null,s=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);let n=this.data,o=n instanceof BigInt64Array||n instanceof BigUint64Array;if(o&&e!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let a,i;if(o?(a=(f,m)=>f+m,i=0n):(a=(f,m)=>f+m**e,i=0),r===null){let f=n.reduce(a,i);return e!==1&&(f=f**(1/e)),new t(this.type,[f],[])}let[l,c,p]=To(a,this,r,s);if(e!==1)for(let f=0;f<c.length;++f)c[f]=c[f]**(1/e);return new t(l,c,p)}normalize_(e=2,r=1){r=dr(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,c=a,p=1;l>=0;--l){let f=this.dims[l];if(l!==r){let m=c%f;i+=m*p,p*=this.dims[l]}c=Math.floor(c/f)}n[a]/=o[i]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return hd(this.dims)}squeeze(e=null){return new t(this.type,this.data,u2(this.dims,e))}squeeze_(e=null){return this.dims=u2(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,p2(this.dims,e))}unsqueeze_(e){return this.dims=p2(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 xc(this,e,r)}min(e=null,r=!1){if(e===null){let a=mo(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=To((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=Ce(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=To((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=mo(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=Ce(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=hd(s),c=hd(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/c[h]);f=f%c[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(!Er.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,wE(this.data),this.dims);return new t(e,Er[e].from(this.data,r),this.dims)}};function YL(t,e){let r=t.length,s=e.reduce((o,a)=>o*a);if(r!==s)throw Error(`cannot reshape array of size ${r} into shape (${e})`);let n=t;for(let o=e.length-1;o>=0;o--)n=n.reduce((a,i)=>{let l=a[a.length-1];return l.length<e[o]?l.push(i):a.push([i]),a},[[]]);return n[0]}function QL(t,e){let[r,s]=fE(t.data,t.dims,e);return new R(t.type,r,s)}function _d(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=pE(t.data,[o,a,i],[e,r],s,n);return new R(t.type,l,[o,e,r])}async function Et(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 fr.nearest_interpolate_4d;else if(r==="bilinear")n=await fr.bilinear_interpolate_4d;else if(r==="bicubic")n=await fr.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${r}`);let o=new R("int64",new BigInt64Array(s.map(BigInt)),[s.length]);return await n({x:t,s:o})}async function f2(t,e){return await(await fr.matmul)({a:t,b:e})}async function L4(t,e){return await(await fr.rfft)({x:t,a:e})}async function sr(t,e){let r=await fr.top_k;return e==null?e=t.dims.at(-1):e=Math.min(e,t.dims.at(-1)),await r({x:t,k:new R("int64",[BigInt(e)],[1])})}var gc=t=>new R("int64",t,[t.length]);async function wc(t,e,r,s,n){return await(await fr.slice)({x:t,s:gc(e),e:gc(r),a:gc(s),t:gc(n??new Array(s.length).fill(1))})}function d2(t,e){let r=t.data,s=e.data,n=[t.dims[0],t.dims[2]],o=new r.constructor(n[0]*n[1]),[a,i,l]=t.dims,c=0;for(let p=0;p<a;++p){let f=p*l*i;for(let m=0;m<l;++m){let h=0,w=0,x=p*i,v=f+m;for(let A=0;A<i;++A){let S=Number(s[x+A]);w+=S,h+=r[v+A*l]*S}let E=h/w;o[c++]=E}}return new R(t.type,o,n)}function N4(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,c=t.data,p=new c.constructor(c.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]=(c[w]-l[f])/(i[f]+r)}}return new R(t.type,p,t.dims)}function u2(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 p2(t,e){return e=dr(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function dr(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=dr(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:c}=t[i];for(let p=0;p<l.length;++p){let f=0;for(let m=c.length-1,h=p,w=1;m>=0;--m){let x=c[m],v=h%x;m===e&&(v+=a),f+=v*w,w*=r[m],h=Math.floor(h/x)}n[f]=l[p]}a+=c[e]}}return new R(o,n,r)}function Pt(t,e=0){return Ee(t.map(r=>r.unsqueeze(e)),e)}function To(t,e,r,s=!1,n=null){let o=e.data,a=e.dims;r=dr(r,a.length);let i=a.slice();i[r]=1;let l=new o.constructor(o.length/a[r]);n!==null&&l.fill(n);for(let c=0;c<o.length;++c){let p=0;for(let f=a.length-1,m=c,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[c],c,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 R(t.type,[h],[]);return[new R(t.type,[w],[]),x]}e=dr(e,o.length);let a=xc(t,e,s),i=a.data,[l,c,p]=To((m,h,w,x)=>m+(h-i[x])**2,t,e,s);for(let m=0;m<c.length;++m)c[m]=Math.sqrt(c[m]/(o[e]-r));return[new R(l,c,p),a]}function xc(t,e=null,r=!1){let s=t.dims,n=t.data;if(e===null){let l=n.reduce((c,p)=>c+p,0);return new R(t.type,[l/n.length],[])}e=dr(e,s.length);let[o,a,i]=To((l,c)=>l+c,t,e,r);if(s[e]!==1)for(let l=0;l<a.length;++l)a[l]/=s[e];return new R(o,a,i)}function hd(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 wd(t,e,r,s){let n=t.reduce((o,a)=>o*a,1);return new R(r,new s(n).fill(e),t)}function Xe(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 wd(t,e,r,s)}function Mo(t,e){return Xe(t.dims,e)}function st(t){return wd(t,1n,"int64",BigInt64Array)}function yc(t){return st(t.dims)}function xd(t){return wd(t,0n,"int64",BigInt64Array)}function yd(t){return xd(t.dims)}function z4(t){let e=t.reduce((r,s)=>r*s,1);return new R("float32",Float32Array.from({length:e},()=>ws.random()),t)}function m2(t){let e=t.reduce((r,s)=>r*s,1);return new R("float32",Float32Array.from({length:e},()=>ws.gauss()),t)}function h2(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,c=Math.floor(i/8),p=i%8;a[c]|=l<<7-p,r&&p===0&&(a[c]-=128)}return new R(s,a,[t.dims[0],t.dims[1]/8])}async function mn(t){if(!t)throw new Error("modelId is required for get_tokenizer_files");return(await pr(t,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function bd(t,e){let r=await mn(t);return await Promise.all(r.map(s=>dt(t,s,!0,e)))}function vd(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 JL=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function ZL(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"?xt(t[n],i):xt(i,t[n])}}function eN(t,e){for(let r of Object.keys(t))t[r].length=e}function Is(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 tN(t){let e=[];for(let r of t.get_added_tokens_decoder().values())r.special&&e.push(r);return e}var W=class extends rt{return_token_type_ids=!1;padding_side="right";constructor(e,r){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=r,this._tokenizer=new Fk(e,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=Is(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Is(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Is(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Is(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Is(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Is(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=tN(this._tokenizer);this.all_special_ids=s.map(n=>n.id),this.all_special_tokens=s.map(n=>n.content)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let i=await bd(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(r=>this._tokenizer.token_to_id(r))}_call(e,{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 c=Array.isArray(e),p;if(c){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?(Z.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&&(Z.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(Ce(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&&eN(p[m],a):n&&ZL(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 R("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(!c)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 R&&(e=e.tolist()),e.map(s=>this.decode(s,r))}decode(e,r={}){if(e instanceof R&&(e=vd(e)),!Array.isArray(e)||e.length===0||!kk(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:c=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 Zk(n),this._compiled_template_cache.set(n,w));let x=Object.create(null);for(let E of JL){let A=Is(this.config,E);A&&(x[E]=A)}let v=w.render({messages:e,add_generation_prompt:o,tools:r,documents:s,...x,...h});if(a){let E=this._call(v,{add_special_tokens:!1,padding:i,truncation:l,max_length:c,return_tensor:p,...m});return f?E:E.input_ids}return v}};function hn(t,e,r,s){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=s.src_lang,o=s.tgt_lang;if(!t.language_codes.includes(o))throw new Error(`Target language code "${o}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(n!==void 0){if(!t.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);for(let a of t._tokenizer.post_processor.config.single)if("SpecialToken"in a&&t.languageRegex.test(a.SpecialToken.id)){a.SpecialToken.id=t.lang_to_token(n);break}}return s.forced_bos_token_id=t._tokenizer.token_to_id(t.lang_to_token(o)),t._call(e,r)}var dm={};hs(dm,{AlbertTokenizer:()=>kd,AutoTokenizer:()=>oe,BartTokenizer:()=>Ed,BertTokenizer:()=>Ad,BlenderbotSmallTokenizer:()=>Td,BlenderbotTokenizer:()=>Md,BloomTokenizer:()=>Sd,CLIPTokenizer:()=>Id,CamembertTokenizer:()=>Od,CodeGenTokenizer:()=>Pd,CodeLlamaTokenizer:()=>Cd,CohereTokenizer:()=>Ld,ConvBertTokenizer:()=>Nd,DebertaTokenizer:()=>Rd,DebertaV2Tokenizer:()=>zd,DistilBertTokenizer:()=>$d,ElectraTokenizer:()=>Dd,EsmTokenizer:()=>Bd,FalconTokenizer:()=>Ud,GPT2Tokenizer:()=>jd,GPTNeoXTokenizer:()=>Gd,GemmaTokenizer:()=>Fd,HerbertTokenizer:()=>qd,LlamaTokenizer:()=>Wd,M2M100Tokenizer:()=>Vd,MBart50Tokenizer:()=>Xd,MBartTokenizer:()=>So,MPNetTokenizer:()=>Qd,MarianTokenizer:()=>Hd,MgpstrTokenizer:()=>Kd,MobileBertTokenizer:()=>Yd,NllbTokenizer:()=>Jd,NougatTokenizer:()=>Zd,PreTrainedTokenizer:()=>W,Qwen2Tokenizer:()=>em,RoFormerTokenizer:()=>rm,RobertaTokenizer:()=>tm,SiglipTokenizer:()=>sm,SpeechT5Tokenizer:()=>nm,SqueezeBertTokenizer:()=>om,T5Tokenizer:()=>am,TokenizersBackend:()=>W,VitsTokenizer:()=>lm,Wav2Vec2CTCTokenizer:()=>cm,WhisperTokenizer:()=>um,XLMRobertaTokenizer:()=>pm,XLMTokenizer:()=>fm});var kd=class extends W{return_token_type_ids=!0};var Ed=class extends W{};var Ad=class extends W{return_token_type_ids=!0};var Td=class extends W{};var Md=class extends W{};var Sd=class extends W{};var Od=class extends W{};var Id=class extends W{};var Cd=class extends W{};var Pd=class extends W{};var Ld=class extends W{};var Nd=class extends W{return_token_type_ids=!0};var zd=class extends W{return_token_type_ids=!0};var Rd=class extends W{return_token_type_ids=!0};var $d=class extends W{};var Dd=class extends W{return_token_type_ids=!0};var Bd=class extends W{};var Ud=class extends W{};var Fd=class extends W{};var Gd=class extends W{};var jd=class extends W{};var qd=class extends W{return_token_type_ids=!0};var Wd=class extends W{padding_side="left"};var Vd=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s.slice(2,-2)),this.lang_to_token=s=>`__${s}__`}_build_translation_inputs(e,r,s){return hn(this,e,r,s)}};var Hd=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(s=>this.languageRegex.test(s)),Z.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)||Z.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),xt([n],super._encode_text(o))}}};var So=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return hn(this,e,r,s)}};var Xd=class extends So{};var Kd=class extends W{};var Yd=class extends W{return_token_type_ids=!0};var Qd=class extends W{};var Jd=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return hn(this,e,r,s)}};var Zd=class extends W{};var em=class extends W{};var tm=class extends W{};var rm=class extends W{return_token_type_ids=!0};var sm=class extends W{};var nm=class extends W{};var om=class extends W{return_token_type_ids=!0};var am=class extends W{};var im=class extends Ft{decode_chain(e){let r="";for(let s=1;s<e.length;s+=2)r+=e[s];return[r]}},lm=class extends W{constructor(e,r){super(e,r),this._tokenizer.decoder=new im({type:"VitsDecoder"})}};var cm=class extends W{};var _2=[["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"]],Oo=new Map(_2),rN=new Map([..._2.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 g2(t){t=t.toLowerCase();let e=rN.get(t);if(e===void 0){let r=t.match(/^<\|([a-z]{2})\|>$/);if(r&&(t=r[1]),Oo.has(t))e=t;else{let n=t.length===2?Oo.keys():Oo.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var sN="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",w2=new RegExp(`^[${sN}]+$`,"gu"),um=class extends W{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:r=!1,return_language:s=!1,time_precision:n=null,force_full_sequences:o=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null,i=r==="word";function l(){return{language:a,timestamp:[null,null],text:""}}let c=[],p=l(),f=0,m=this.timestamp_begin,w=m+1500,x=[],v=[],E=!1,A=null,S=new Set(this.all_special_ids);for(let O of e){let k=O.tokens,G=i?O.token_timestamps:null,H=null,U=m;if("stride"in O){let[Y,B,C]=O.stride;if(f-=B,A=Y-C,B&&(U=B/n+m),C)for(let te=k.length-1;te>=0;--te){let le=Number(k[te]);if(le>=m){if(H!==null&&(le-m)*n<A)break;H=le}}}let V=[],q=[];for(let Y=0;Y<k.length;++Y){let B=Number(k[Y]);if(S.has(B)){let C=this.decode([B]),te=Oo.get(C.slice(2,-2));if(te!==void 0){if(a!==null&&te!==a&&!r){x.push(V);let le=this.findLongestCommonSequence(x)[0],P=this.decode(le);p.text=P,c.push(p),x=[],V=[],p=l()}a=p.language=te}}else if(B>=m&&B<=w){let C=(B-m)*n+f,te=xs(C,2);if(H!==null&&B>=H)E=!0;else if(E||x.length>0&&B<U)E=!1;else if(p.timestamp[0]===null)p.timestamp[0]=te;else if(te!==p.timestamp[0]){p.timestamp[1]=te,x.push(V),i&&v.push(q);let[le,P]=this.findLongestCommonSequence(x,v),N=this.decode(le);p.text=N,i&&(p.words=this.collateWordTimestamps(le,P,a)),c.push(p),x=[],V=[],v=[],q=[],p=l()}}else if(V.push(B),i){let C=xs(G[Y]+f,2),te;if(Y+1<G.length){te=xs(G[Y+1]+f,2);let le=this.decode([B]);w2.test(le)&&(te=xs(Math.min(C+n,te),2))}else te=null;q.push([C,te])}}if("stride"in O){let[Y,B,C]=O.stride;f+=Y-C}V.length>0?(x.push(V),i&&v.push(q)):x.every(Y=>Y.length===0)&&(p=l(),x=[],V=[],v=[],q=[])}if(x.length>0){if(o&&r)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[O,k]=this.findLongestCommonSequence(x,v),G=this.decode(O);p.text=G,i&&(p.words=this.collateWordTimestamps(O,k,a)),c.push(p)}let M=Object.create(null),L=c.map(O=>O.text).join("");if(r||s){for(let O=0;O<c.length;++O){let k=c[O];r||delete k.timestamp,s||delete k.language}if(i){let O=[];for(let k of c)for(let G of k.words)O.push(G);M={chunks:O}}else M={chunks:c}}return[L,M]}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 c=1;c<e.length;++c){let p=e[c],f=0,m=[n,n,0,0],h=p.length;for(let M=1;M<n+h;++M){let L=Math.max(0,n-M),O=Math.min(n,n+h-M),k=s.slice(L,O),G=Math.max(0,M-n),H=Math.min(h,M),U=p.slice(G,H);if(k.length!==U.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let V;a?V=k.filter((B,C)=>B===U[C]&&l[L+C]<=r[c][G+C]).length:V=k.filter((B,C)=>B===U[C]).length;let q=M/1e4,Y=V/M+q;V>1&&Y>f&&(f=Y,m=[L,O,G,H])}let[w,x,v,E]=m,A=Math.floor((x+w)/2),S=Math.floor((E+v)/2);o.push(...s.slice(0,A)),s=p.slice(S),n=s.length,a&&(i.push(...l.slice(0,A)),l=r[c].slice(S))}return o.push(...s),a?(i.push(...l),[o,i]):[o,[]]}collateWordTimestamps(e,r,s){let[n,o,a]=this.combineTokensIntoWords(e,s),i=[];for(let l=0;l<n.length;++l){let c=a[l];i.push({text:n[l],timestamp:[r[c.at(0)][0],r[c.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 R&&(e=vd(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=[],c=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[c+m.indexOf(s)]===s)&&(n.push(m),o.push(i),a.push(l),i=[],l=[],c+=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 c=r[l],p=s[l],f=n[l],m=p[0]>=this._tokenizer.token_to_id("<|endoftext|>"),h=c.startsWith(" "),w=c.trim(),x=w2.test(w);if(m||h||x||o.length===0)o.push(c),a.push(p),i.push(f);else{let v=o.length-1;o[v]+=c,a[v].push(...p),i[v].push(...f)}}return[o,a,i]}mergePunctuations(e,r,s,n,o){let a=structuredClone(e),i=structuredClone(r),l=structuredClone(s),c=a.length-2,p=a.length-1;for(;c>=0;)a[c].startsWith(" ")&&n.includes(a[c].trim())?(a[p]=a[c]+a[p],i[p]=xt(i[c],i[p]),l[p]=xt(l[c],l[p]),a[c]="",i[c]=[],l[c]=[]):p=c,--c;for(c=0,p=1;p<a.length;)!a[c].endsWith(" ")&&o.includes(a[p])?(a[c]+=a[p],i[c]=xt(i[c],i[p]),l[c]=xt(l[c],l[p]),a[p]="",i[p]=[],l[p]=[]):c=p,++p;return[a.filter(f=>f),i.filter(f=>f.length>0),l.filter(f=>f.length>0)]}};var pm=class extends W{};var fm=class extends W{return_token_type_ids=!0;constructor(e,r){super(e,r),Z.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}};var oe=class{static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let[i,l]=await bd(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",p=dm[c];return p||(Z.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),p=W),new p(i,l)}};var Wr="https://github.com/huggingface/transformers.js/issues/new/choose";var Io="preprocessor_config.json",Ar=Io,x2="processor_config.json",y2="chat_template.jinja";var re=class extends rt{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?dt(e,x2,!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?gf(e,y2,!0,r):null]);return new this(s,n,o)}};var Hc={};hs(Hc,{ChatterboxProcessor:()=>Im,Florence2Processor:()=>bh,Gemma3nProcessor:()=>vh,GraniteSpeechProcessor:()=>kh,GroundingDinoProcessor:()=>Eh,Idefics3Processor:()=>jc,JinaCLIPProcessor:()=>Th,Lfm2VlProcessor:()=>Mh,LlavaProcessor:()=>Sh,MgpstrProcessor:()=>Oh,MoonshineProcessor:()=>Ih,OwlViTProcessor:()=>Ch,PaliGemmaProcessor:()=>Ph,Phi3VProcessor:()=>Lh,PixtralProcessor:()=>Nh,Processor:()=>re,PyAnnoteProcessor:()=>zh,Qwen2VLProcessor:()=>$o,Qwen2_5_VLProcessor:()=>Do,Qwen3VLProcessor:()=>Rh,Sam2Processor:()=>qc,Sam2VideoProcessor:()=>$h,SamProcessor:()=>Bo,SmolVLMProcessor:()=>jc,SpeechT5Processor:()=>Dh,UltravoxProcessor:()=>Bh,VLChatProcessor:()=>Ah,VoxtralProcessor:()=>Uh,VoxtralRealtimeProcessor:()=>Gh,Wav2Vec2Processor:()=>jh,Wav2Vec2ProcessorWithLM:()=>qh,WhisperProcessor:()=>Wh});var Ae=class extends rt{constructor(e){super(),this.config=e}static async from_pretrained(e,r={}){let s=await dt(e,Io,!0,r);return new this(s)}};function Be(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 zo={};hs(zo,{ASTFeatureExtractor:()=>_m,ChatterboxFeatureExtractor:()=>gm,ClapFeatureExtractor:()=>wm,DacFeatureExtractor:()=>Lo,EncodecFeatureExtractor:()=>Po,FeatureExtractor:()=>Ae,Gemma3nAudioFeatureExtractor:()=>xm,GraniteSpeechFeatureExtractor:()=>ym,MoonshineFeatureExtractor:()=>bm,ParakeetFeatureExtractor:()=>vm,PyAnnoteFeatureExtractor:()=>No,SeamlessM4TFeatureExtractor:()=>km,SnacFeatureExtractor:()=>Em,SpeechT5FeatureExtractor:()=>Am,VoxtralRealtimeFeatureExtractor:()=>Sm,Wav2Vec2FeatureExtractor:()=>Tm,WeSpeakerFeatureExtractor:()=>Mm,WhisperFeatureExtractor:()=>Om});var nN=()=>{};var b2={fromWeb:nN};var oN=()=>{};var v2=oN;async function bc(t,e){if(ie.IS_BROWSER_ENV){if(ie.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");let r=URL.createObjectURL(e),s=document.createElement("a");s.href=r,s.download=t,s.click(),s.remove(),URL.revokeObjectURL(r)}else if(ie.IS_FS_AVAILABLE){let r=e.stream(),s=b2.fromWeb(r),n=wt.createWriteStream(t);await v2(s,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function hm(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"&&Z.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);let n=await s.decodeAudioData(r),o;if(n.numberOfChannels===2){let a=Math.sqrt(2),i=n.getChannelData(0),l=n.getChannelData(1);o=new Float32Array(i.length);for(let c=0;c<n.length;++c)o[c]=a*(i[c]+l[c])/2}else o=n.getChannelData(0);return o}function A2(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 k2(t){return A2(t,.5)}function aN(t){return A2(t,.54)}var iN={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 mm(t,e="htk"){let r=iN[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 lN={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 cN(t,e="htk"){let r=lN[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}function uN(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 c=-i[l]/r[l],p=i[l+2]/r[l+1];o[l][a]=Math.max(0,Math.min(c,p))}}return o}function E2(t,e,r){let s=(e-t)/(r-1);return Float64Array.from({length:r},(n,o)=>t+s*o)}function ct(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=mm(r,a),c=mm(s,a),p=E2(l,c,e+2),f=cN(p,a),m;if(i){let w=n/((t-1)*2);m=mm(Float64Array.from({length:t},(x,v)=>v*w),a),f=p}else m=E2(0,Math.floor(n/2),t);let h=uN(m,f);if(o!==null&&o==="slaney")for(let w=0;w<e;++w){let x=h[w],v=2/(f[w+2]-f[w]);for(let E=0;E<t;++E)x[E]*=v}return h}function pN(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[sn(o,n)];for(let o=1;o<=r;++o)s[n+e+o]=t[sn(n-o,n)];return s}function T2(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=Ce(t)[0]-n;for(let i=0;i<t.length;++i)t[i]=Math.max(t[i],a)}return t}function fN(t,e=1,r=1e-5,s=null){return T2(t,20,e,r,s)}function dN(t,e=1,r=1e-10,s=null){return T2(t,10,e,r,s)}async function ht(t,e,r,s,{fft_length:n=null,power:o=1,center:a=!0,pad_mode:i="reflect",onesided:l=!0,preemphasis:c=null,preemphasis_htk_flavor:p=!0,mel_filters:f=null,mel_floor:m=1e-10,log_mel:h=null,max_log_mel:w=null,reference:x=1,min_value:v=1e-10,db_range:E=null,remove_dc_offset:A=null,min_num_frames:S=null,max_num_frames:M=null,do_pad:L=!0,transpose:O=!1,mel_offset:k=0}={}){let G=e.length;if(n===null&&(n=r),r>n)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(G!==r)throw new Error(`Length of the window (${G}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(o===null&&f!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!p)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(a)switch(i){case"reflect":{let $=Math.floor((n-1)/2)+1;t=pN(t,$,$);break}case"constant":{let $=Math.floor(n/2),J=new t.constructor(t.length+2*$);J.set(t,$),t=J;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}let H=Math.floor(1+Math.floor((t.length-r)/s));S!==null&&H<S&&(H=S);let U=l?Math.floor(n/2)+1:n,V=H,q=H;M!==null&&(M>H?L&&(q=M):q=V=M);let Y=new Jl(n),B=new Float64Array(n),C=new Float64Array(Y.outputBufferSize),te=new Float32Array(U*q);for(let $=0;$<V;++$){let J=$*s,Ie=Math.min(t.length-J,r);Ie!==r&&B.fill(0,0,r);for(let ae=0;ae<Ie;++ae)B[ae]=t[J+ae];if(A){let ae=0;for(let Je=0;Je<Ie;++Je)ae+=B[Je];let Fe=ae/Ie;for(let Je=0;Je<Ie;++Je)B[Je]-=Fe}if(c!==null){for(let ae=Ie-1;ae>=1;--ae)B[ae]-=c*B[ae-1];B[0]*=1-c}for(let ae=0;ae<e.length;++ae)B[ae]*=e[ae];Y.realTransform(C,B);for(let ae=0;ae<U;++ae){let Fe=ae<<1;te[ae*q+$]=C[Fe]**2+C[Fe+1]**2}}if(o!==null&&o!==2){let $=o/2;for(let J=0;J<te.length;++J)te[J]**=$}let le=f.length,P=await f2(new R("float32",f.flat(),[le,U]),new R("float32",te,[U,q]));O&&(P=P.transpose(1,0));let N=P.data;for(let $=0;$<N.length;++$)N[$]=k+Math.max(m,N[$]);if(o!==null&&h!==null){let $=Math.min(N.length,V*le);switch(h){case"log":for(let J=0;J<$;++J)N[J]=Math.log(N[J]);break;case"log10":for(let J=0;J<$;++J)N[J]=Math.log10(N[J]);break;case"log10_max_norm":{for(let ae=0;ae<$;++ae)N[ae]=Math.log10(N[ae]);let Ie=(w??Ce(N)[0])-8;for(let ae=0;ae<$;++ae)N[ae]=(Math.max(N[ae],Ie)+4)/4;break}case"dB":if(o===1)fN(N,x,v,E);else if(o===2)dN(N,x,v,E);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', 'log10_max_norm', or 'dB'. Got '${h}'`)}}return P}function _t(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=k2(o);break;case"hamming":a=aN(o);break;case"povey":a=k2(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 mN(t,e){let r=t.reduce((o,a)=>o+a.length,0),s=new ArrayBuffer(44),n=new DataView(s);return vc(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),vc(n,8,"WAVE"),vc(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),vc(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...t.map(o=>o.buffer)],{type:"audio/wav"})}function vc(t,e,r){for(let s=0;s<r.length;++s)t.setUint8(e+s,r.charCodeAt(s))}var Co=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]),mN(e,this.sampling_rate)}async save(e){return bc(e,this.toBlob())}};var _m=class extends Ae{constructor(e){super(e);let r=this.config.sampling_rate,s=ct(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=_t(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,r){return ht(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){Be(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 Po=class extends Ae{async _call(e){Be(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 R("float32",e,s)}}};var gm=class extends Ae{async _call(e){Be(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,e.length];return{input_values:new R("float32",e,r)}}};var wm=class extends Ae{constructor(e){super(e),this.mel_filters=ct(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=ct(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=_t(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(ws.random()*(i+1));e=e.subarray(l,l+r),o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${s}" not implemented`);else{if(i<0){let l=new Float64Array(r);if(l.set(e),n==="repeat")for(let c=e.length;c<r;c+=e.length)l.set(e.subarray(0,Math.min(e.length,r-c)),c);else if(n==="repeatpad")for(let c=e.length;c<-i;c+=e.length)l.set(e,c);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 ht(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 Be(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 Lo=class extends Po{};var xm=class extends Ae{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=ct(Math.floor(1+r/2),s,n,o,a,null,"htk",!1);this.mel_filters=l,this.window=_t(i,"hann")}async _extract_fbank_features(e,r){return ht(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(Be(e,"Gemma3nAudioFeatureExtractor"),s&&e.length>r&&(e=e.slice(0,r)),n&&e.length%o!==0){let l=o-e.length%o,c=new Float64Array(e.length+l);c.set(e),this.config.padding_value!==0&&c.fill(this.config.padding_value,e.length),e=c}let a=await this._extract_fbank_features(e,this.config.max_length),i=Xe([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}};var ym=class extends Ae{constructor(e){super(e);let{n_fft:r,win_length:s,n_mels:n,sample_rate:o}=e.melspec_kwargs;this.mel_filters=ct(Math.floor(1+r/2),n,0,o/2,o,null,"htk");let a=_t(s,"hann");this.window=new Float64Array(r);let i=Math.floor((r-s)/2);this.window.set(a,i)}async _call(e){Be(e,"GraniteSpeechFeatureExtractor");let{n_fft:r,hop_length:s,n_mels:n}=this.config.melspec_kwargs,o=1+Math.floor((e.length-1)/s),a=o-o%2;return{input_features:(await ht(e,this.window,r,s,{power:2,mel_filters:this.mel_filters,log_mel:"log10_max_norm",transpose:!0,max_num_frames:a,do_pad:!1})).view(-1,2*n).unsqueeze_(0)}}};var bm=class extends Ae{async _call(e){Be(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,e.length];return{input_values:new R("float32",e,r)}}};var hN=1e-5,vm=class extends Ae{constructor(e){super(e),this.config.mel_filters??=ct(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=_t(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 ht(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){Be(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 c=s>1?s-1:1;for(let f=0;f<a;++f){let m=i[f]/s,h=(l[f]-s*m*m)/c,x=1/(Math.sqrt(h)+hN);for(let v=0;v<s;++v){let E=v*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 R("int64",p,[1,o])}}};var No=class extends Ae{async _call(e){Be(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,1,e.length];return{input_values:new R("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 c=Re(o[l]),[p,f]=Ce(c),[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:c,end:p,score:f})=>({id:l,start:c*s,end:p*s,confidence:f/(p-c)})))}return n}};var km=class extends Ae{constructor(e){super(e);let r=this.config.sampling_rate,s=ct(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=_t(400,"povey",{periodic:!1})}async _extract_fbank_features(e,r){return e=e.map(s=>s*32768),ht(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}={}){Be(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[w,x]=a.dims,v=a.data;for(let E=0;E<x;++E){let A=0;for(let O=0;O<w;++O)A+=v[O*x+E];let S=A/w,M=0;for(let O=0;O<w;++O)M+=(v[O*x+E]-S)**2;M/=w-1;let L=Math.sqrt(M+1e-7);for(let O=0;O<w;++O){let k=O*x+E;v[k]=(v[k]-S)/L}}}let i;if(r){let[w,x]=a.dims,v=a.data,E=w%s;if(E>0){let A=new Float32Array(x*(w+E));A.set(v),A.fill(this.config.padding_value,v.length);let S=w+E;a=new R(a.type,A,[S,x]),o&&(i=new R("int64",new BigInt64Array(S),[1,S]),i.data.fill(1n,0,w))}}let[l,c]=a.dims,p=this.config.stride;if(l%p!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${p}).`);let m=a.view(1,Math.floor(l/p),c*p),h={input_features:m};if(o){let w=m.dims[1],x=new BigInt64Array(w);if(i){let v=i.data;for(let E=1,A=0;E<l;E+=p,++A)x[A]=v[E]}else x.fill(1n);h.attention_mask=new R("int64",x,[1,w])}return h}};var Em=class extends Lo{};var Am=class extends Ae{};var Tm=class extends Ae{_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){Be(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 R("float32",r,s),attention_mask:new R("int64",new BigInt64Array(r.length).fill(1n),s)}}};var Mm=class extends Ae{constructor(e){super(e);let r=this.config.sampling_rate,s=ct(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=_t(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(r=>r*32768),ht(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){Be(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 c=l*a*i,p=l*i;for(let f=0;f<a;++f){let m=c+f*i;for(let h=0;h<i;++h)n[m+h]-=s[p+h]}}}return{input_features:r}}};var Sm=class extends Ae{constructor(e){super(e),this.config.mel_filters??=ct(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=_t(this.config.n_fft,"hann")}async _extract_fbank_features(e,{center:r=!0}={}){let{n_fft:s,hop_length:n,mel_filters:o,global_log_mel_max:a}=this.config,i=Math.floor(r?e.length/n:(e.length-s)/n);return await ht(e,this.window,s,n,{power:2,mel_filters:o,log_mel:"log10_max_norm",max_log_mel:a,center:r,max_num_frames:i,do_pad:!1})}async _call(e,{center:r=!0}={}){return Be(e,"VoxtralRealtimeFeatureExtractor"),{input_features:(await this._extract_fbank_features(e,{center:r})).unsqueeze_(0)}}};var Om=class extends Ae{constructor(e){super(e),this.config.mel_filters??=ct(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=_t(this.config.n_fft,"hann")}async _extract_fbank_features(e){return await ht(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10_max_norm",max_num_frames:Math.min(Math.floor(e.length/this.config.hop_length),this.config.nb_max_frames)})}async _call(e,{max_length:r=null}={}){Be(e,"WhisperFeatureExtractor");let s,n=r??this.config.n_samples;return e.length>n?(e.length>this.config.n_samples&&Z.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 Ke=class{static async from_pretrained(e,r={}){let s=await dt(e,Io,!0,r),n=s.feature_extractor_type,o=zo[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${Wr}.`);return new o(s)}};var Im=class extends re{static tokenizer_class=oe;static feature_extractor_class=Ke;async _call(e,r=null){let s=this.tokenizer(e),n=r?await this.feature_extractor(r):{};return{...s,...n}}};var kc={};var Cs,M2,Vr;if(ie.IS_WEB_ENV)Cs=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(t,e)},Vr=self.createImageBitmap,M2=self.ImageData;else if(kc)Vr=async t=>{let r=(await t.metadata()).channels,{data:s,info:n}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),o=new Qe(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 _N={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},gN=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Qe=class t{constructor(e,r,s,n){this.data=e,this.width=r,this.height=s,this.channels=n}get size(){return[this.width,this.height]}static async read(e){if(e instanceof t)return e;if(typeof e=="string"||e instanceof URL)return await this.fromURL(e);if(e instanceof Blob)return await this.fromBlob(e);if(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)return this.fromCanvas(e);throw new Error(`Unsupported input type: ${typeof e}`)}static fromCanvas(e){if(!ie.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");let s=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new t(s,e.width,e.height,4)}static async fromURL(e){let r=await 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(ie.IS_WEB_ENV){let r=await Vr(e),s=Cs(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=kc(await e.arrayBuffer());return await Vr(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=_N[s]??s,o=af(e),a=af(r);if(o&&a)return this;if(o?e=r/this.height*this.width:a&&(r=e/this.width*this.height),ie.IS_WEB_ENV){let i=this.channels,l=this.toCanvas(),c=Cs(e,r).getContext("2d");return c.drawImage(l,0,0,e,r),new t(c.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")&&(Z.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 Vr(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(ie.IS_WEB_ENV){let o=this.channels,a=this.toCanvas(),i=this.width+e+r,l=this.height+s+n,c=Cs(i,l).getContext("2d");return c.drawImage(a,0,0,this.width,this.height,e,s,this.width,this.height),new t(c.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 Vr(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(ie.IS_WEB_ENV){let i=this.channels,l=this.toCanvas(),c=Cs(o,a).getContext("2d");return c.drawImage(l,e,r,o,a,0,0,o,a),new t(c.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 Vr(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(ie.IS_WEB_ENV){let o=this.channels,a=this.toCanvas(),i=Cs(e,r).getContext("2d"),l=0,c=0,p=0,f=0;return s>=0?l=s:p=-s,n>=0?c=n:f=-n,i.drawImage(a,l,c,e,r,p,f,e,r),new t(i.getImageData(0,0,e,r).data,e,r,4).convert(o)}else{let o=this.toSharp();if(s>=0&&n>=0)o=o.extract({left:Math.floor(s),top:Math.floor(n),width:e,height:r});else if(s<=0&&n<=0){let a=Math.floor(-n),i=Math.floor(-s);o=o.extend({top:a,left:i,right:e-this.width-i,bottom:r-this.height-a})}else{let a=[0,0],i=0;n<0?(a[0]=Math.floor(-n),a[1]=r-this.height-a[0]):i=Math.floor(n);let l=[0,0],c=0;s<0?(l[0]=Math.floor(-s),l[1]=e-this.width-l[0]):c=Math.floor(s),o=o.extend({top:a[0],bottom:a[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:e,height:r})}return await Vr(o)}}async toBlob(e="image/png",r=1){if(!ie.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:r})}toTensor(e="CHW"){let r=new R("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!=="HWC")if(e==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${e}`);return r}toCanvas(){if(!ie.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),r=Cs(e.width,e.height),s=new M2(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 c=n*l;for(let p=0;p<n;++p)i[p][l]=e[c+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(ie.IS_WEB_ENV){if(ie.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let r=e.split(".").pop().toLowerCase(),s=gN.get(r)??"image/png",n=await this.toBlob(s);return bc(e,n)}else if(ie.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(ie.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return kc(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},wN=Qe.read.bind(Qe);function S2(t,e,r=0,s=null){let n=t/e,o=_E(n)*e;return s!==null&&o>s&&(o=Math.floor(n)*e),o<r&&(o=Math.ceil(n)*e),o}function Cm([t,e],r){return[Math.max(Math.floor(t/r),1)*r,Math.max(Math.floor(e/r),1)*r]}function Pm([t,e,r,s]){return[t-r/2,e-s/2,t+r/2,e+s/2]}function Hr(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 c=[];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 v=h[x],E=[],A;if(s){A=v.sigmoid().data;for(let S=0;S<A.length;++S)A[S]>e&&E.push(S)}else{let S=Ce(v.data)[1];if(S===l-1||(A=Re(v.data),A[S]<e))continue;E.push(S)}for(let S of E){let M=w[x].data;M=Pm(M),f!==null&&(M=M.map((L,O)=>L*f[(O+1)%2])),m.boxes.push(M),m.classes.push(S),m.scores.push(A[S])}}c.push(m)}return c}function Ec(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=_d(i,a,"bilinear",!1));let[l,c]=a??i.dims.slice(-2),p=new R("int32",new Int32Array(l*c),[l,c]),f=i[0].data,m=p.data;for(let x=1;x<i.dims[0];++x){let v=i[x].data;for(let E=0;E<v.length;++E)v[E]>f[E]&&(f[E]=v[E],m[E]=x)}let h=new Array(i.dims[0]);for(let x=0;x<m.length;++x){let v=m[x];h[v]=v}let w=h.filter(x=>x!==void 0);n.push({segmentation:p,labels:w})}return n}function xN(t,e,r,s){let n=[],o=[],a=[];for(let i=0;i<t.dims[0];++i){let l=t[i],c=e[i],p=Ce(l.data)[1];if(p===s)continue;let m=Re(l.data)[p];m>r&&(n.push(c),o.push(m),a.push(p))}return[n,o,a]}function yN(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 c=a>0&&i>0;return c&&(c=a/i>n),[c,o]}function bN(t,e,r,s,n,o=null,a=null){let[i,l]=a??t[0].dims,c=new R("int32",new Int32Array(i*l),[i,l]),p=[];if(a!==null)for(let x=0;x<t.length;++x)t[x]=_d(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 v=e[x],E=t[x].data;for(let A=0;A<E.length;++A)E[A]*=v,E[A]>m[A]&&(f[A]=x,m[A]=E[A])}let h=0,w=c.data;for(let x=0;x<r.length;++x){let v=r[x],[E,A]=yN(f,t,x,s,n);if(E){++h;for(let S of A)w[S]=h;p.push({id:h,label_id:v,score:e[x]})}}return[c,p]}function Ac(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 Tc(t,e=.5,r=.5,s=.8,n=null,o=null){n===null&&(Z.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(),[c,p,f]=a.dims;if(f-=1,o!==null&&o.length!==c)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<c;++h){let w=o!==null?o[h]:null,x=a[h],v=l[h],[E,A,S]=xN(x,v,e,f);if(S.length===0){let[O,k]=w??v.dims.slice(-2),G=new R("int32",new Int32Array(O*k).fill(-1),[O,k]);m.push({segmentation:G,segments_info:[]});continue}let[M,L]=bN(E,A,S,r,s,n,w);m.push({segmentation:M,segments_info:L})}return m}function Mc(t,e=.5,r=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}var X=class extends rt{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),c=Math.min(o,i);return l===n&&c===o?e:(n>o?c=Math.floor(o*l/n):o>n&&(l=Math.floor(n*c/o)),await e.resize(c,l,{resample:s}))}async crop_margin(e,r=200){let s=e.clone().grayscale(),n=mo(s.data)[0],a=Ce(s.data)[0]-n;if(a===0)return e;let i=r/255,l=s.width,c=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),c=Math.min(c,h),p=Math.max(p,x),f=Math.max(f,h))}return e=await e.crop([l,c,p,f]),e}pad_image(e,r,s,{mode:n="constant",center:o=!1,constant_values:a=0}={}){let[i,l,c]=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*c);if(Array.isArray(a))for(let x=0;x<m.length;++x)m[x]=a[x%c];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 v=(x+w)*p,E=x*l;for(let A=0;A<l;++A){let S=(v+A+h)*c,M=(E+A)*c;for(let L=0;L<c;++L)m[S+L]=e[M+L]}}if(n==="symmetric"){if(o)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");let x=i-1,v=l-1;for(let E=0;E<f;++E){let A=E*p,S=sn(E,x)*l;for(let M=0;M<p;++M){if(E<i&&M<l)continue;let L=(A+M)*c,O=(S+sn(M,v))*c;for(let k=0;k<c;++k)m[L+k]=e[O+k]}}}e=m,r=[f,p,c]}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,c=n*i,p=a===void 0?1:Math.min(a/l,a/c),f=Math.floor(Number((l*p).toFixed(2))),m=Math.floor(Number((c*p).toFixed(2)));return this.size_divisibility!==void 0&&([f,m]=Cm([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 c=l/n,p=i/s;Math.abs(1-p)<Math.abs(1-c)?c=p:p=c,l=S2(c*n,this.config.ensure_multiple_of),i=S2(p*s,this.config.ensure_multiple_of)}return[i,l]}else{if(this.size_divisibility!==void 0)return Cm([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 c=[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 v=0;v<e.channels;++v)p[x+v]=(p[x+v]-h[v])/w[v]}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]=Cm([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 R("float32",p,f).permute(2,0,1);return{original_size:[l,i],reshaped_input_size:c,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:Pt(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 dt(e,Ar,!0,r);return new this(s)}};var yn={};hs(yn,{BeitFeatureExtractor:()=>Lm,BitImageProcessor:()=>Nm,CLIPFeatureExtractor:()=>Rm,CLIPImageProcessor:()=>Sc,ChineseCLIPFeatureExtractor:()=>zm,ConvNextFeatureExtractor:()=>$m,ConvNextImageProcessor:()=>Oc,DINOv3ViTImageProcessor:()=>Um,DPTFeatureExtractor:()=>Gm,DPTImageProcessor:()=>Pc,DeiTFeatureExtractor:()=>Dm,DeiTImageProcessor:()=>Ic,DetrFeatureExtractor:()=>Bm,DetrImageProcessor:()=>Cc,DonutFeatureExtractor:()=>Fm,DonutImageProcessor:()=>_n,EfficientNetImageProcessor:()=>jm,GLPNFeatureExtractor:()=>qm,GroundingDinoImageProcessor:()=>Wm,Idefics3ImageProcessor:()=>Lc,ImageFeatureExtractor:()=>X,ImageProcessor:()=>X,JinaCLIPImageProcessor:()=>Hm,Lfm2VlImageProcessor:()=>Xm,LlavaOnevisionImageProcessor:()=>Km,Mask2FormerImageProcessor:()=>Qm,MaskFormerFeatureExtractor:()=>Ym,MaskFormerImageProcessor:()=>gn,MobileNetV1FeatureExtractor:()=>Jm,MobileNetV1ImageProcessor:()=>Nc,MobileNetV2FeatureExtractor:()=>Zm,MobileNetV2ImageProcessor:()=>zc,MobileNetV3FeatureExtractor:()=>eh,MobileNetV3ImageProcessor:()=>Rc,MobileNetV4FeatureExtractor:()=>th,MobileNetV4ImageProcessor:()=>$c,MobileViTFeatureExtractor:()=>rh,MobileViTImageProcessor:()=>Dc,NougatImageProcessor:()=>sh,OwlViTFeatureExtractor:()=>nh,OwlViTImageProcessor:()=>wn,Owlv2ImageProcessor:()=>oh,Phi3VImageProcessor:()=>lh,PixtralImageProcessor:()=>ch,PvtImageProcessor:()=>uh,Qwen2VLImageProcessor:()=>ph,RTDetrImageProcessor:()=>fh,Sam2ImageProcessor:()=>Ro,Sam3ImageProcessor:()=>Ro,SamImageProcessor:()=>Ro,SapiensFeatureExtractor:()=>dh,SapiensImageProcessor:()=>Bc,SegformerFeatureExtractor:()=>mh,SegformerImageProcessor:()=>Uc,SiglipImageProcessor:()=>hh,SmolVLMImageProcessor:()=>Lc,Swin2SRImageProcessor:()=>_h,VLMImageProcessor:()=>Vm,ViTFeatureExtractor:()=>gh,ViTImageProcessor:()=>Fc,VitMatteImageProcessor:()=>wh,VitPoseImageProcessor:()=>xh,YolosFeatureExtractor:()=>yh,YolosImageProcessor:()=>Gc});var Lm=class extends X{};var Nm=class extends X{};var zm=class extends X{};var Sc=class extends X{},Rm=class extends Sc{};var Oc=class extends X{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}},$m=class extends Oc{};var Ic=class extends X{},Dm=class extends Ic{};var Cc=class extends X{async _call(e){let r=await super._call(e),s=[r.pixel_values.dims[0],64,64],n=Xe(s,1n);return{...r,pixel_mask:n}}post_process_object_detection(...e){return Hr(...e)}post_process_panoptic_segmentation(...e){return Tc(...e)}post_process_instance_segmentation(...e){return Mc(...e)}},Bm=class extends Cc{};var Um=class extends X{};var _n=class extends X{pad_image(e,r,s,n={}){let[o,a,i]=r,l=this.image_mean;Array.isArray(this.image_mean)||(l=new Array(i).fill(l));let c=this.image_std;Array.isArray(c)||(c=new Array(i).fill(l));let p=l.map((f,m)=>-f/c[m]);return super.pad_image(e,r,s,{center:!0,constant_values:p,...n})}},Fm=class extends _n{};var Pc=class extends X{},Gm=class extends Pc{};var jm=class extends X{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 qm=class extends X{};var Wm=class extends X{async _call(e){let r=await super._call(e),s=r.pixel_values.dims,n=st([s[0],s[2],s[3]]);return{...r,pixel_mask:n}}};var Lc=class extends X{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,r){let[s,n]=e.dims.slice(-2),o=n/s;return n>=s?(n=Math.ceil(n/r)*r,s=Math.floor(n/o),s=Math.ceil(s/r)*r):(s=Math.ceil(s/r)*r,n=Math.floor(s*o),n=Math.ceil(n/r)*r),{height:s,width:n}}async _call(e,{do_image_splitting:r=null,return_row_col_info:s=!1}={}){let n;if(!Array.isArray(e))n=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?n=e:n=[e]}let o=[],a=[],i=[],l=[],c=[];for(let E of n){let A=await Promise.all(E.map(L=>this.preprocess(L)));l.push(...A.map(L=>L.original_size)),c.push(...A.map(L=>L.reshaped_input_size)),A.forEach(L=>L.pixel_values.unsqueeze_(0));let{longest_edge:S}=this.max_image_size,M;if(r??this.do_image_splitting){let L=new Array(A.length),O=new Array(A.length);M=await Promise.all(A.map(async(k,G)=>{let H=this.get_resize_for_vision_encoder(k.pixel_values,S),U=await Et(k.pixel_values,{size:[H.height,H.width]}),{frames:V,num_splits_h:q,num_splits_w:Y}=await this.split_image(U,this.max_image_size);return L[G]=q,O[G]=Y,Ee(V,0)})),a.push(L),i.push(O)}else{let L=[S,S];M=await Promise.all(A.map(O=>Et(O.pixel_values,{size:L}))),a.push(new Array(A.length).fill(0)),i.push(new Array(A.length).fill(0))}o.push(Ee(M,0))}let p=o.length,[f,m,h,w]=o[0].dims,x,v;if(p===1)x=o[0].unsqueeze_(0),v=Xe([p,f,h,w],!0);else{let E=Math.max(...o.map(M=>M.dims.at(0)));v=Xe([p,E,h,w],!0);let A=v.data,S=E*h*w;for(let M=0;M<p;++M){let L=o[M].dims[0];if(L<E){o[M]=Ee([o[M],Xe([E-L,m,h,w],0)],0);let O=M*S+L*h*w,k=(M+1)*S;A.fill(!1,O,k)}}x=Pt(o,0)}return{pixel_values:x,pixel_attention_mask:v,original_sizes:l,reshaped_input_sizes:c,...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,c=0;if(a>s||i>n){l=Math.ceil(a/s),c=Math.ceil(i/n);let p=Math.ceil(a/l),f=Math.ceil(i/c);for(let w=0;w<l;++w)for(let x=0;x<c;++x){let v,E,A,S;w===l-1?(E=a-p,S=a):(E=w*p,S=(w+1)*p),x===c-1?(v=i-f,A=i):(v=x*f,A=(x+1)*f);let O=await wc(e,[E,v],[S,A],[2,3]);o.push(O)}let m=s,h=n;(a!==m||i!==h)&&(e=await Et(e,{size:[m,h]}))}return o.push(e),{frames:o,num_splits_h:l,num_splits_w:c}}};var Vm=class extends X{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 Hm=class extends X{constructor(e){let{resize_mode:r,fill_color:s,interpolation:n,size:o,...a}=e,i=r==="squash"?{width:o,height:o}:r==="shortest"?{shortest_edge:o}:{longest_edge:o},l=n==="bicubic"?3:2;super({...a,size:i,resample:l,do_center_crop:!0,crop_size:o,do_normalize:!0})}};function O2(t,e){return Math.round(t/e)*e}function vN(t,e,r,s,n){let o=1/0,a=[1,1],i=r*s;for(let l of e){let c=Math.abs(t-l[0]/l[1]);c<o?(o=c,a=l):c===o&&i>.5*n*n*l[0]*l[1]&&(a=l)}return a}function kN(t,e){let r=[],s=new Set;for(let n=t;n<=e;++n)for(let o=1;o<=n;++o)for(let a=1;a<=n;++a){let i=o*a;if(i>=t&&i<=e){let l=o<<16|a;s.has(l)||(s.add(l),r.push([o,a]))}}return r.sort((n,o)=>n[0]*n[1]-o[0]*o[1])}function EN(t,e){let[r,s,n,o]=t.dims,a=Math.floor(n/e),i=Math.floor(o/e),l=e*e*s,c=t.data,p=new Float32Array(r*a*i*l),f=n*o;for(let m=0;m<r;++m){let h=m*s*f,w=m*a*i*l;for(let x=0;x<a;++x)for(let v=0;v<i;++v){let E=w+(x*i+v)*l;for(let A=0;A<e;++A){let S=(x*e+A)*o+v*e;for(let M=0;M<e;++M){let L=S+M;for(let O=0;O<s;++O)p[E++]=c[h+O*f+L]}}}}return new R("float32",p,[r,a*i,l])}function AN(t,e){let[,r,s]=t.dims,n=new BigInt64Array(e);n.fill(1n,0,r);let o=t;if(r<e){let a=new Float32Array(e*s);a.set(t.data),o=new R("float32",a,[1,e,s])}return{padded:o,mask:new R("int64",n,[e])}}var Xm=class extends X{constructor(e){super(e),this.downsample_factor=e.downsample_factor??2,this.do_image_splitting=e.do_image_splitting??!0,this.min_tiles=e.min_tiles??2,this.max_tiles=e.max_tiles??10,this.use_thumbnail=e.use_thumbnail??!0,this.min_image_tokens=e.min_image_tokens??64,this.max_image_tokens=e.max_image_tokens??256,this.encoder_patch_size=e.encoder_patch_size??e.patch_size??16,this.tile_size=e.tile_size??512,this.max_pixels_tolerance=e.max_pixels_tolerance??2,this.return_row_col_info=e.return_row_col_info??!1;let r=this.max_image_tokens*this.downsample_factor**2,s=this.do_image_splitting?(this.tile_size/this.encoder_patch_size)**2:0;this.max_num_patches=Math.max(r,s)}_is_image_too_large(e,r){let s=this.encoder_patch_size*this.downsample_factor,n=Math.max(this.encoder_patch_size,O2(e,s)),o=Math.max(this.encoder_patch_size,O2(r,s));return n*o>this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,r){let s=kN(this.min_tiles,this.max_tiles),[n,o]=vN(r/e,s,r,e,this.tile_size);return{grid_width:n,grid_height:o,target_width:this.tile_size*n,target_height:this.tile_size*o}}async _call(e,{return_row_col_info:r=null}={}){let s;Array.isArray(e)?Array.isArray(e[0])?s=e:s=[e]:s=[[e]];let n=[],o=[],a=[],i=[],l=[],c=[];for(let f of s){let m=await Promise.all(f.map(h=>this.preprocess(h,{do_pad:!1})));for(let{pixel_values:h}of m){let[,w,x]=h.dims,v=h.unsqueeze_(0),E=this.encoder_patch_size*this.downsample_factor,A=E**2,[S,M]=Ac(Math.max(E,w),Math.max(E,x),E,this.min_image_tokens*A,this.max_image_tokens*A).map(U=>Math.max(E,U)),L,O=1,k=1,G=this._is_image_too_large(w,x),H=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(G&&H){let{grid_width:U,grid_height:V,target_width:q,target_height:Y}=this._get_grid_layout(w,x);O=V,k=U;let B=await Et(v,{size:[Y,q]});L=[];for(let C=0;C<V;++C)for(let te=0;te<U;++te){let le=C*this.tile_size,P=te*this.tile_size;L.push(B.slice(null,null,[le,le+this.tile_size],[P,P+this.tile_size]))}this.use_thumbnail&&U*V!==1&&L.push(await Et(v,{size:[S,M]}))}else L=[await Et(v,{size:[S,M]})];for(let U of L){let[,,V,q]=U.dims,Y=EN(U,this.encoder_patch_size),{padded:B,mask:C}=AN(Y,this.max_num_patches);n.push(B),o.push(C),a.push([Math.floor(V/this.encoder_patch_size),Math.floor(q/this.encoder_patch_size)])}i.push(O),l.push(k),c.push([S,M])}}let p={pixel_values:Ee(n,0),pixel_attention_mask:Pt(o,0),spatial_shapes:new R("int64",BigInt64Array.from(a.flat(),BigInt),[a.length,2])};return(r??this.return_row_col_info)&&(p.image_rows=i,p.image_cols=l,p.image_sizes=c),p}};var Km=class extends X{};var gn=class extends X{post_process_panoptic_segmentation(...e){return Tc(...e)}post_process_instance_segmentation(...e){return Mc(...e)}},Ym=class extends gn{};var Qm=class extends gn{};var Nc=class extends X{},Jm=class extends Nc{};var zc=class extends X{},Zm=class extends zc{};var Rc=class extends X{},eh=class extends Rc{};var $c=class extends X{},th=class extends $c{};var Dc=class extends X{},rh=class extends Dc{};var sh=class extends _n{};var wn=class extends X{post_process_object_detection(...e){return Hr(...e)}},nh=class extends wn{};var oh=class extends wn{};var Dt=336,TN=[2,3],{ceil:ah,floor:xn,sqrt:ih}=Math,lh=class extends X{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 xn((xn(r/Dt)*xn(e/Dt)+1)*s+1+(xn(r/Dt)+1)*ih(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),c=Math.floor(l/a);return[l,c]}pad_image(e,r,s,n={}){let[o,a]=r,i=Dt*ah(o/Dt),l=Dt*ah(a/Dt),c=[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:c,...n})}async _call(e,{num_crops:r=null}={}){if(this._num_crops=r??=this.config.num_crops,r<4||ih(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 Et(m,{size:[Dt,Dt],mode:"bicubic"});if(r>0){let v=[],E=ih(r),A=xn(w/E),S=xn(h/E);for(let L=0;L<E;++L)for(let O=0;O<E;++O){let k,G,H,U;L===E-1?(G=h-S,U=h):(G=L*S,U=(L+1)*S),O===E-1?(k=w-A,H=w):(k=O*A,H=(O+1)*A);let Y=await wc(m,[G,k],[U,H],TN);v.push(Y)}let M=await Et(Ee(v,0),{size:[Dt,Dt],mode:"bicubic"});i.push(Ee([x,M],0))}else i.push(x)}let l=Pt(i,0),c=a.map(m=>m.map(h=>Dt*ah(h/Dt))),p=new R("int64",c.flat(),[s,2]),f=c.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 ch=class extends X{get_resize_output_image_size(e,r){let{longest_edge:s}=r;if(s===void 0)throw new Error("size must contain 'longest_edge'");let[n,o]=e.size,a=Math.max(n,o)/s,i=n,l=o;a>1&&(i=Math.floor(n/a),l=Math.floor(o/a));let{patch_size:c,spatial_merge_size:p}=this.config;if(!p)throw new Error("config must contain 'spatial_merge_size'");let f=c*p,m=Math.floor((i-1)/f)+1,h=Math.floor((l-1)/f)+1;return[m*f,h*f]}};var uh=class extends X{};var ph=class extends X{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 Ac(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:c}=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]/c),h=Math.floor(a.dims[3]/c),w=a.view(p,i,f,Math.floor(m/l),l,c,Math.floor(h/l),l,c).permute(0,3,6,4,7,2,1,5,8).view(p*m*h,f*i*c*c),x=new R("int64",[p,m,h],[1,3]);return{pixel_values:w,image_grid_thw:x,original_sizes:n,reshaped_input_sizes:o}}};var fh=class extends X{post_process_object_detection(...e){return Hr(...e)}};var Ro=class extends X{reshape_input_points(e,r,s,n=!1){e=structuredClone(e);let o=lf(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],[c,p]=s[a],f=[p/l,c/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 R("float32",Float32Array.from(e.flat(1/0)),o)}add_input_labels(e,r){let s=lf(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 R("int64",e.flat(1/0).map(BigInt),s)}async _call(e,{input_points:r=null,input_labels:s=null,input_boxes:n=null}={}){let o=await super._call(e);if(r&&(o.input_points=this.reshape_input_points(r,o.original_sizes,o.reshaped_input_sizes)),s){if(!o.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");o.input_labels=this.add_input_labels(s,o.input_points)}return n&&(o.input_boxes=this.reshape_input_points(n,o.original_sizes,o.reshaped_input_sizes,!0)),o}async post_process_masks(e,r,s,{mask_threshold:n=0,binarize:o=!0,pad_size:a=null}={}){let i=[];a=a??this.pad_size??this.size;let l=[a.height,a.width];for(let c=0;c<r.length;++c){let p=r[c],f=s[c],m=await Et(e[c],{mode:"bilinear",size:l});if(m=m.slice(null,null,[0,f[0]],[0,f[1]]),m=await Et(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 R("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 Bc=class extends X{post_process_semantic_segmentation(...e){return Ec(...e)}},dh=class extends Bc{};var Uc=class extends X{post_process_semantic_segmentation(...e){return Ec(...e)}},mh=class extends Uc{};var hh=class extends X{};var _h=class extends X{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 Fc=class extends X{},gh=class extends Fc{};var wh=class extends X{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:Pt(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 xh=class extends X{post_process_pose_estimation(e,r,{threshold:s=null}={}){let n=e.tolist(),[o,a,i,l]=e.dims,c=[];for(let p=0;p<o;++p){let f=n[p],m=r[p],h=[];for(let w=0;w<m.length;++w){let x=m[w],v=[],E=[],A=[],S=x.at(-2)/l,M=x.at(-1)/i;for(let L=0;L<f.length;++L){let[O,k]=[0,0],G=0,H=-1/0,U=f[L];for(let q=0;q<U.length;++q){let Y=U[q];for(let B=0;B<Y.length;++B){let C=Y[B];G+=C,H=Math.max(H,C),O+=(B+.5)*C,k+=q*C}}if(s!=null&&H<s)continue;let V=[S*O/G,M*k/G];v.push(V),A.push(L),E.push(H)}h.push({bbox:x,scores:E,labels:A,keypoints:v})}c.push(h)}return c}};var Gc=class extends X{post_process_object_detection(...e){return Hr(...e)}},yh=class extends Gc{};var Le=class{static async from_pretrained(e,r={}){let s=await dt(e,Ar,!0,r),n=s.image_processor_type??s.feature_extractor_type,o=yn[n?.replace(/Fast$/,"")];return o||(n!==void 0&&Z.warn(`Image processor type '${n}' not found, assuming base ImageProcessor. Please report this at ${Wr}.`),o=X),new o(s)}};var bh=class extends re{static tokenizer_class=oe;static image_processor_class=Le;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=[],c=[];for(let[p,f,...m]of i)l.push(f?f.trim():l.at(-1)??""),c.push(m.map((h,w)=>(Number(h)+.5)/this.size_per_bin*s[w%2]));o={labels:l,[a]:c};break;default:throw new Error(`Task "${r}" (of type "${n}") not yet implemented.`)}return{[r]:o}}async _call(e,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=await this.image_processor(e,s),o=r?this.tokenizer(this.construct_prompts(r),s):{};return{...n,...o}}};var vh=class extends re{static image_processor_class=Le;static feature_extractor_class=Ke;static tokenizer_class=oe;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:c,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=`
14
14
 
15
15
  ${o}${m}${i}
16
16
 
@@ -18,10 +18,10 @@ ${o}${m}${i}
18
18
 
19
19
  ${c}${h}${f}
20
20
 
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 AL(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 eh=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 c=a.dims.at(1),p=a.sigmoid(),f=p.max(-1).tolist(),m=i.tolist().map(w=>w.map(x=>um(x))),h=[];for(let w=0;w<l;++w){let x=o!==null?o[w]:null;x!==null&&(m[w]=m[w].map(M=>M.map((C,P)=>C*x[(P+1)%2])));let b=f[w],E=[],A=[],S=[];for(let M=0;M<c;++M){let C=b[M];if(C<=s)continue;let P=m[w][M],k=p[w][M];E.push(C),S.push(P);let F=AL(k.gt(n),r[w]);A.push(F)}h.push({scores:E,boxes:S,labels:this.batch_decode(A)})}return h}};function TL(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}}};var kh=class extends re{static tokenizer_class=oe;static feature_extractor_class=Ke;static uses_processor_config=!0;_get_num_audio_features(e){let{hop_length:r}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:s,projector_downsample_rate:n}=this.feature_extractor.config,o=Math.floor(s/n),a=Math.floor(e/r)+1,i=Math.floor(a/2);return Math.ceil(i/s)*o}async _call(e,r=null,s={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(r){let{input_features:a}=await this.feature_extractor(r);n.input_features=a;let i=this._get_num_audio_features(r.length),l=new Uint8Array(i).fill(1);n.input_features_mask=new R("bool",l,[1,i]);let c=this.config.audio_token??"<|audio|>";if(!e.includes(c))throw new Error(`The input text does not contain the audio token ${c}.`);e=e.replaceAll(c,c.repeat(i))}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}};function MN(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 Eh=class extends re{static tokenizer_class=oe;static image_processor_class=Le;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 c=a.dims.at(1),p=a.sigmoid(),f=p.max(-1).tolist(),m=i.tolist().map(w=>w.map(x=>Pm(x))),h=[];for(let w=0;w<l;++w){let x=o!==null?o[w]:null;x!==null&&(m[w]=m[w].map(M=>M.map((L,O)=>L*x[(O+1)%2])));let v=f[w],E=[],A=[],S=[];for(let M=0;M<c;++M){let L=v[M];if(L<=s)continue;let O=m[w][M],k=p[w][M];E.push(L),S.push(O);let G=MN(k.gt(n),r[w]);A.push(G)}h.push({scores:E,boxes:S,labels:this.batch_decode(A)})}return h}};function SN(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+=`
22
22
  `}return a+=`
23
- ${s}${o}`+n.repeat(t)+`${s}`,a}function ML(t,e,r,s){return`${e}${s}`+r.repeat(t)+`${e}`}function SL(t,e,r,s,n,o){return t===0&&e===0?ML(r,s,n,o):TL(r,t,e,s,n,o)}var kc=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=[],c=[];for(let f=0;f<e.length;++f){let m=e[f],h=o[f],w=a[f];l.push(jv(m,this.image_token));let x=h.map((A,S)=>SL(A,w[S],i,this.fake_image_token,this.image_token,this.global_img_token)),b=m.split(this.image_token);if(b.length===0)throw new Error("The image token should be present in the text.");let E=b[0];for(let A=0;A<x.length;++A)E+=x[A]+b[A+1];c.push(E)}return{...this.tokenizer(c),...n}}};var th=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(b=>b.images).flatMap(b=>b.images).map(b=>Ke.read(b)));let n=this.tokenizer,o=n.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:s}),a=b=>n.encode(b,{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[c,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 b=1;b<i.length;++b){let E=new Array(this.num_image_tokens).fill(c),A=a(i[b]);m=dt(m,[p],E,[f],A);let S=new Array(this.num_image_tokens).fill(!0);h=dt(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 b=await this.image_processor(r);return b.pixel_values.unsqueeze_(0),{...x,...b}}return x}};var rh=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 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,patch_size:c,num_additional_image_tokens:p}=this.config,f=Math.floor(a/c)*Math.floor(i/c)+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 VA={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]},nh=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(!VA.hasOwnProperty(r))throw new Error(`Format ${r} is not supported.`);let[s,n]=VA[r],o=this[s].bind(this),[a,i]=e.dims,l=[],c=[],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(Ne(h[E]));if(x.push(A),S==n)break;w.push(S)}let b=x.length>0?x.reduce((E,A)=>E*A,1):0;c.push(w),l.push(b)}return[o(c),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,c]=this._decode_helper(s,"wp"),p=[],f=[];for(let m=0;m<n.length;++m){let[h,w]=Se([o[m],i[m],c[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 oh=class extends oe{static tokenizer_class=Z;static feature_extractor_class=rt;async _call(e){return await this.feature_extractor(e)}};var ah=class extends oe{static tokenizer_class=Z;static image_processor_class=De};var hn="<image>";function OL(t,e,r,s,n){return`${s.repeat(r*n)}${e}${t}
24
- `}var ih=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(c=>c.includes(hn))?a=r.map(c=>{let p=c.replaceAll(hn,hn.repeat(o)),f=p.lastIndexOf(hn),m=f===-1?0:f+hn.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(c=>OL(c,n,o,hn,e.length)));let i=this.tokenizer(a,s);return{...await this.image_processor(e,s),...i}}};var HA="<|image|>",IL=/<\|image_\d+\|>/g,lh=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,c=e.map((f,m)=>f.split(IL).join(HA.repeat(l[m])));a=this.tokenizer(c,{padding:s,truncation:n});let p=this.tokenizer._tokenizer.token_to_id(HA);a.input_ids.map_(f=>f==p?-f:f)}else a=this.tokenizer(e);return{...a,...i}}};var ch=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:c,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 b=0;b<r.length;++b){let E=l.repeat(x),A=E+c,S=E+p,M=A.repeat(w-1)+S;r[b]=r[b].replace(l,M)}}let o=r?this.tokenizer(r,s):{};return{...n,...o}}};var uh=class extends oe{static feature_extractor_class=bo;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 Eo=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,c=o.tolist();e=e.map(p=>{for(;p.includes("<|image_pad|>");){let f=Number(c[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 Ao=class extends Eo{};var ph=class extends Ao{};var To=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 Ec=class extends To{},fh=class extends Ec{};var dh=class extends oe{static tokenizer_class=Z;static feature_extractor_class=rt;async _call(e){return await this.feature_extractor(e)}};var mh=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),c=1+Math.ceil(l/this.config.stack_factor);n.audio_token_len=[c],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(c))}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}};var Ac="[AUDIO]",CL="[BEGIN_AUDIO]",PL=375;function LL(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 hh=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(Ac))throw new Error(`The input text does not contain the audio token ${Ac}.`);Array.isArray(r)||(r=[r]);let a=e.split(Ac),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,c=r.map(w=>LL(w,l)),p=c.map(w=>w.length),f=c.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+=CL;for(let x=0;x<p[w];++x)h+=Ac.repeat(PL);h+=a[w+1]}e=h}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}};var _h=class extends oe{static tokenizer_class=Z;static feature_extractor_class=rt;async _call(e){return await this.feature_extractor(e)}};var gh=class extends oe{static tokenizer_class=Z;static feature_extractor_class=rt;async _call(e){return await this.feature_extractor(e)}};var wh=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,Mr,!0,r),{image_processor_type:n,feature_extractor_type:o,processor_class:a}=s;if(a&&Tc[a])return Tc[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 c=mn[n.replace(/Fast$/,"")];if(!c)throw new Error(`Unknown image_processor_type: '${n}'.`);i.image_processor=new c(s)}if(o){let c=mn[o];if(c)i.image_processor=new c(s);else{let p=vo[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 NL(t,e){return await ct(t,"config.json",!0,e)}function _n(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=_n(t.text_config);break;case"moondream1":r=_n(t.phi_config);break;case"musicgen":r=_n(t.decoder);break;case"multi_modality":r=_n(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=_n(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 Sc(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:c}=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,c];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:c,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:b}=t,E=c/i,A=e?.batch_size??1,S=(b??x*c)+2*w*h;for(let M=0;M<a;++M)if((!o||o[M]==="mamba")&&(n[`${s}_conv.${M}`]=[A,S,p],n[`${s}_ssm.${M}`]=[A,f,m,h]),!o||o[M]==="attention")for(let C of["key","value"])n[`${r}.${M}.${C}`]=[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:c,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,b=h*p,E=x*2+b,A=o??c/i,S=e?.batch_size??1;for(let M=0;M<a.length;++M)if(a[M]==="full_attention")for(let C of["key","value"])n[`${r}.${M}.${C}`]=[S,l,0,A];else if(a[M]==="linear_attention")n[`${s}_conv.${M}`]=[S,E,w],n[`${s}_recurrent.${M}`]=[S,p,m,h];else throw new Error(`Unsupported layer type: ${a[M]}`);return n}return zL(t,e)}function zL(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 c=0;c<n.num_decoder_layers;++c)s[`${e}.${c}.encoder.key`]=i,s[`${e}.${c}.encoder.value`]=i,s[`${e}.${c}.decoder.key`]=l,s[`${e}.${c}.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 c=0;c<a;++c)s[`${e}.${c}.key`]=l,s[`${e}.${c}.value`]=l}else if(n.multi_query){let l=[r*o,0,2*i];for(let c=0;c<a;++c)s[`${e}.${c}.key_value`]=l}else if(n.model_type==="bloom"){let l=[r*o,i,0],c=[r*o,0,i];for(let p=0;p<a;++p)s[`${e}.${p}.key`]=l,s[`${e}.${p}.value`]=c}else if(n.model_type==="openelm")for(let l=0;l<a;++l){let c=[r,o[l],0,i];s[`${e}.${l}.key`]=c,s[`${e}.${l}.value`]=c}else{let l=[r,o,0,i];for(let c=0;c<a;++c)s[`${e}.${c}.key`]=l,s[`${e}.${c}.value`]=l}}return s}var Mc=class t{model_type=null;is_encoder_decoder=!1;max_position_embeddings;"transformers.js_config";constructor(e){Object.assign(this,e),this.normalized_config=_n(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 NL(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(i)}},Sr=class{static async from_pretrained(...e){return Mc.from_pretrained(...e)}};function xh(t,e,r){return t?typeof t=="object"&&t!==null?t.hasOwnProperty(e)?+t[e]:t.hasOwnProperty(r)?+t[r]:0:+t:0}function yh(t,e){let r=[];for(let s=0;s<e;++s)r.push(`${t}_data${s===0?"":"_"+s}`);return r}async function XA(t,e,r,s){let n=`${e}${s}.onnx`,o=`${r.subfolder??""}/${n}`;return await Zn(t,o,!0,r,ge.IS_NODE_ENV)}async function KA(t,e,r,s,n,o={}){let a=`${e}${r}.onnx`,i=ge.IS_NODE_ENV,l=[],c=xh(n,a,e);if(c>0){if(c>Il)throw new Error(`The number of external data chunks (${c}) exceeds the maximum allowed value (${Il}).`);let p=yh(a,c);for(let f of p){let m=`${s.subfolder??""}/${f}`;l.push(new Promise(async(h,w)=>{let x=await Zn(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 Zn(t,p.data,!0,s);return{...p,data:f}}return p}));return Promise.all(l)}async function RL(t,e,r,s=!1){let n=r.config?.["transformers.js_config"]??{},o=Kl(r.device??n.device,e,{warn:S=>Q.info(S)}),a=wA(o),i=n.device_config??{};i.hasOwnProperty(o)&&(n={...n,...i[o]});let l=Yl(r.dtype??n.dtype,e,o,{configDtype:n.dtype,warn:S=>Q.info(S)});if(po.hasOwnProperty(l)){if(o==="webgpu"&&!ge.IS_NODE_ENV&&l===gt.fp16&&!await EA())throw new Error(`The device (${o}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${l}. Should be one of: ${Object.keys(gt).join(", ")}`);let c=n.kv_cache_dtype,p=c?typeof c=="string"?c:c[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=po[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=XA(t,e,r,f),x=r.use_external_data_format??n.use_external_data_format,b=await KA(t,e,f,r,x,m);if(b.length>0&&!ge.IS_NODE_ENV&&(m.externalData=b),s&&o==="webgpu"&&c!==!1){let S=Sc(r.config,{prefix:"present"});if(Object.keys(S).length>0&&!uo()){let M={};for(let C in S)M[C]="gpu-buffer";m.preferredOutputLocation=M}}return{buffer_or_path:await w,session_options:m,session_config:{dtype:l,kv_cache_dtype:p,device:o}}}async function Tt(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 RL(t,e[n],r,n===s),l=await Vl(o,a,i);return[n,l]})))}function YA(t){for(let e in t)Xl(t[e])?t[e]=new D(t[e]):typeof t[e]=="object"&&YA(t[e]);return t}async function ue(t,e){let r=$L(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 Hl(t,s);return YA(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 $L(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]=uo()?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 ze=class{};var G=class extends ze{constructor({logits:e,...r}){super(),this.logits=e;let s=Object.values(r);s.length>0&&(this.attentions=s)}},he=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}},yt=class extends ze{constructor({logits:e}){super(),this.logits=e}};var Oc=class extends ze{constructor({alphas:e}){super(),this.alphas=e}};var Ht=class extends Ze{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},Mo=class extends Ze{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},Ns=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()}},Ic=class extends Ht{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}},Cc=class extends Ht{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}},gn=class extends Ht{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}},Pc=class extends Ht{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=Yp(n),c=Math.log(l.subarray(this.timestamp_begin).map(Math.exp).reduce((f,m)=>f+m)),p=Se(l.subarray(0,this.timestamp_begin))[0];c>p&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return r}},Lc=class extends Ht{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}},Nc=class extends Ht{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}},zc=class extends Ht{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}},Rc=class extends Ht{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}},$c=class extends Ht{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}},Dc=class extends Ht{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}},Uc=class extends Mo{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}},QA=class extends Mo{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}},JA=class extends Mo{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 wn=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 xn=class extends Ze{_call(e,r){throw Error("StoppingCriteria needs to be subclassed")}},Bc=class t extends Ze{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof t?e=e.criteria:e instanceof xn&&(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()}},Fc=class extends xn{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)}},jc=class extends xn{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)})}},ZA=class extends xn{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 zs=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 TA(e)}static getSampler(e){if(e.do_sample)return new vh(e);if(e.num_beams>1)return new kh(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 bh(e)}},bh=class extends zs{async sample(e){let r=Se(e.data)[1];return[[BigInt(r),0]]}},vh=class extends zs{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 rr(e,r),o=Ne(s.data);return Array.from({length:this.generation_config.num_beams},()=>{let a=this.randomSelect(o);return[n.data[a],Math.log(o[a])]})}},kh=class extends zs{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 rr(e,r),o=Ne(s.data);return Array.from({length:this.generation_config.num_beams},(a,i)=>[n.data[i],Math.log(o[i])])}};var So=null;function t2(t){So=t}function Eh(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 Ah(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},e2={[j.DecoderOnly]:{can_generate:!0,forward:Lt,prepare_inputs:Oo},[j.DecoderOnlyWithoutHead]:{can_generate:!1,forward:Lt,prepare_inputs:Oo},[j.Seq2Seq]:{can_generate:!0,forward:Gc,prepare_inputs:Io},[j.Vision2Seq]:{can_generate:!0,forward:Gc,prepare_inputs:Io},[j.Musicgen]:{can_generate:!0,forward:Gc},[j.EncoderDecoder]:{can_generate:!1,forward:Gc},[j.ImageTextToText]:{can_generate:!0,forward:BL,prepare_inputs:qc},[j.AudioTextToText]:{can_generate:!0,forward:UL,prepare_inputs:qc},[j.Phi3V]:{can_generate:!0,prepare_inputs:qc},[j.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:qc},[j.MultiModality]:{can_generate:!0},[j.AutoEncoder]:{can_generate:!1,forward:DL},[j.Chatterbox]:{can_generate:!0,forward:Xt},default:{can_generate:!1,forward:Xt}},mr=new Map,Wc=new Map,Rs=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=Rs.get(this.constructor),o=mr.get(n),a=e2[o]??e2.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:c=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:c,dtype:p,use_external_data_format:f,session_options:m},w=Rs.get(this),x=mr.get(w);s=h.config=await Sr.from_pretrained(e,h);let b;if(x===j.DecoderOnly)b=await Promise.all([Tt(e,{model:h.model_file_name??"model"},h,"model"),Or(e,{generation_config:"generation_config.json"},h)]);else if(x===j.Seq2Seq||x===j.Vision2Seq)b=await Promise.all([Tt(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},h,"decoder_model_merged"),Or(e,{generation_config:"generation_config.json"},h)]);else if(x===j.MaskGeneration)b=await Promise.all([Tt(e,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},h)]);else if(x===j.EncoderDecoder)b=await Promise.all([Tt(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"),b=await Promise.all([Tt(e,E,h,"decoder_model_merged"),Or(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"};b=await Promise.all([Tt(e,E,h,"decoder_model_merged"),Or(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"};b=await Promise.all([Tt(e,E,h),Or(e,{generation_config:"generation_config.json"},h)])}else if(x===j.Musicgen)b=await Promise.all([Tt(e,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},h,"decoder_model_merged"),Or(e,{generation_config:"generation_config.json"},h)]);else if(x===j.MultiModality)b=await Promise.all([Tt(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"),Or(e,{generation_config:"generation_config.json"},h)]);else if(x===j.Phi3V)b=await Promise.all([Tt(e,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},h,"model"),Or(e,{generation_config:"generation_config.json"},h)]);else if(x===j.Chatterbox)b=await Promise.all([Tt(e,{embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"},h,"model"),Or(e,{generation_config:"generation_config.json"},h)]);else if(x===j.AutoEncoder)b=await Promise.all([Tt(e,{encoder_model:"encoder_model",decoder_model:"decoder_model"},h)]);else if(x===j.Supertonic)b=await Promise.all([Tt(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 ${Gr}.`)}b=await Promise.all([Tt(e,{model:h.model_file_name??"model"},h)])}return new this(s,...b)}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 Ns;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&n.push(new Nc(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&n.push(new Lc(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&n.push(new $c(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&n.push(new zc(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 Rc(r,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&n.push(new Ic(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&n.push(new Cc(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 gn(e.begin_suppress_tokens,o))}return e.guidance_scale!==null&&e.guidance_scale>1&&n.push(new Dc(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 Uc(e.temperature)),s!==null&&n.extend(s),n}_prepare_generation_config(e,r,s=wn){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 Bc;return e.max_length!==null&&s.push(new Fc(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&s.push(new jc(e.eos_token_id)),r&&s.extend(r),s}_validate_model_class(){if(!this.can_generate){let e=[So.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,So.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,So.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,So.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),r=Rs.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,...c}=r,p=await this._prepare_inputs_embeds(r);r={...c,...nt(p,["inputs_embeds","attention_mask"])}}let{last_hidden_state:o}=await Xt(this,r);if(n.guidance_scale!==null&&n.guidance_scale>1)o=Ee([o,mo(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=Eh(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=Eh(i)}return s.decoder_attention_mask=tc(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:c}=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:c,generation_config:r})));let f;p?{input_ids:f,model_inputs:l}=this._prepare_decoder_input_ids_for_generation({batch_size:l[c].dims.at(0),model_input_name:c,model_kwargs:l,decoder_start_token_id:r.decoder_start_token_id,bos_token_id:r.bos_token_id,generation_config:r}):f=l[c];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[c].dims.at(0),b=zs.getSampler(r),E=new Array(x).fill(0),A=f.tolist();o&&o.put(A);let S,M={},C={};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 M||(M[Y]=[]),M[Y].push(X[Y])}else this._return_dict_in_generate_keys&&Object.assign(C,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 b(Y);for(let[L,ne]of U){let ae=BigInt(L);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 P=this.getPastKeyValues(S,l.past_key_values,!0),k=new D("int64",A.flat(),[A.length,A[0].length]);if(r.return_dict_in_generate)return{sequences:k,past_key_values:P,...M,...C};for(let F of Object.values(S))F.location==="gpu-buffer"&&F.dispose();return k}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"?an.float16:an.float32,i=Sc(this.config,{batch_size:n});for(let l in i){let c=i[l].reduce((p,f)=>p*f,1);e[l]=new D(o,new a(c),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 Gc(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 Xt(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 Lt(t,o,!0)}async function Xt(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=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=at([n[0],n[2],n[3]])}return await ue(r,s)}async function DL(t,e){let r=await t.encode(e);return await t.decode(r)}async function Lt(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=Ah(!!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=FL(o,n,i)}t.addPastKeyValues(o,n);let a=nt(o,s.inputNames);return await ue(s,a)}async function r2(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:c=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(c&&h&&o.dims[1]===1){let x=o.dims[1],b=Object.values(c)[0].dims.at(-2);a=Ee([at([o.dims[0],b]),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:b}=m;[i]=t.get_rope_index(o,x,b,a)}return await Lt(t,{inputs_embeds:l,past_key_values:c,attention_mask:a,position_ids:i,generation_config:p,logits_processor:f},!0)}async function UL(t,e){return await r2(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 BL(t,e){return await r2(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 Th(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 c=0;c<s;++c){let p=i+c;n[p]===0n?o[p]=BigInt(1):(o[p]=l,l+=n[p])}}return{data:o,dims:t.dims}}function FL(t,e=null,r=0){let{input_ids:s,inputs_embeds:n,attention_mask:o}=t,{data:a,dims:i}=Th(o,r),l=new D("int64",a,i);if(e){let c=-(s??n).dims.at(1);l=l.slice(null,[c,null])}return l}function Oo(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 Io(t,e,r,s){return r.past_key_values&&(e=e.map(n=>[n.at(-1)])),{...r,decoder_input_ids:Eh(e)}}function qc(t,...e){return t.config.is_encoder_decoder?Io(t,...e):Oo(t,...e)}function s2({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n}){let o=s.tolist().map(c=>c.reduce((p,f,m)=>(f==t&&p.push(m),p),[])),a=o.reduce((c,p)=>c+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 c=0;c<o.length;++c){let p=o[c],f=e[c];for(let m=0;m<p.length;++m)f[p[m]].data.set(r[l++].data)}return{inputs_embeds:e,attention_mask:n}}function hr({image_token_id:t,inputs_embeds:e,image_features:r,input_ids:s,attention_mask:n}){return s2({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n})}function Vc({audio_token_id:t,inputs_embeds:e,audio_features:r,input_ids:s,attention_mask:n}){return s2({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n})}async function Or(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 Ri={};ms(Ri,{ASTForAudioClassification:()=>Dh,ASTModel:()=>$h,ASTPreTrainedModel:()=>No,AfmoeForCausalLM:()=>Nh,AfmoeModel:()=>Lh,AfmoePreTrainedModel:()=>Po,AlbertForMaskedLM:()=>Ih,AlbertForQuestionAnswering:()=>Oh,AlbertForSequenceClassification:()=>Sh,AlbertModel:()=>Mh,AlbertPreTrainedModel:()=>$s,ApertusForCausalLM:()=>Ph,ApertusModel:()=>Ch,ApertusPreTrainedModel:()=>Co,ArceeForCausalLM:()=>Rh,ArceeModel:()=>zh,ArceePreTrainedModel:()=>Lo,BartForConditionalGeneration:()=>Bh,BartForSequenceClassification:()=>Fh,BartModel:()=>Uh,BartPretrainedModel:()=>yn,BeitForImageClassification:()=>Gh,BeitModel:()=>jh,BeitPreTrainedModel:()=>zo,BertForMaskedLM:()=>Wh,BertForQuestionAnswering:()=>Xh,BertForSequenceClassification:()=>Vh,BertForTokenClassification:()=>Hh,BertModel:()=>qh,BertPreTrainedModel:()=>Vr,BlenderbotForConditionalGeneration:()=>Yh,BlenderbotModel:()=>Kh,BlenderbotPreTrainedModel:()=>Ro,BlenderbotSmallForConditionalGeneration:()=>Jh,BlenderbotSmallModel:()=>Qh,BlenderbotSmallPreTrainedModel:()=>$o,BloomForCausalLM:()=>e_,BloomModel:()=>Zh,BloomPreTrainedModel:()=>Do,CLIPModel:()=>l_,CLIPPreTrainedModel:()=>_r,CLIPSegForImageSegmentation:()=>d_,CLIPSegModel:()=>f_,CLIPSegPreTrainedModel:()=>Go,CLIPTextModel:()=>c_,CLIPTextModelWithProjection:()=>jo,CLIPVisionModel:()=>u_,CLIPVisionModelWithProjection:()=>p_,CamembertForMaskedLM:()=>r_,CamembertForQuestionAnswering:()=>o_,CamembertForSequenceClassification:()=>s_,CamembertForTokenClassification:()=>n_,CamembertModel:()=>t_,CamembertPreTrainedModel:()=>Hr,ChatterboxModel:()=>Uo,ChatterboxPreTrainedModel:()=>Hc,ChineseCLIPModel:()=>a_,ChineseCLIPPreTrainedModel:()=>Xc,ClapAudioModelWithProjection:()=>Fo,ClapModel:()=>i_,ClapPreTrainedModel:()=>bn,ClapTextModelWithProjection:()=>Bo,CodeGenForCausalLM:()=>h_,CodeGenModel:()=>m_,CodeGenPreTrainedModel:()=>qo,Cohere2ForCausalLM:()=>x_,Cohere2Model:()=>w_,Cohere2PreTrainedModel:()=>Vo,CohereForCausalLM:()=>g_,CohereModel:()=>__,CoherePreTrainedModel:()=>Wo,ConvBertForMaskedLM:()=>b_,ConvBertForQuestionAnswering:()=>E_,ConvBertForSequenceClassification:()=>v_,ConvBertForTokenClassification:()=>k_,ConvBertModel:()=>y_,ConvBertPreTrainedModel:()=>Xr,ConvNextForImageClassification:()=>T_,ConvNextModel:()=>A_,ConvNextPreTrainedModel:()=>Ho,ConvNextV2ForImageClassification:()=>S_,ConvNextV2Model:()=>M_,ConvNextV2PreTrainedModel:()=>Xo,DFineForObjectDetection:()=>P_,DFineModel:()=>C_,DFinePreTrainedModel:()=>Yo,DINOv3ConvNextModel:()=>rg,DINOv3ConvNextPreTrainedModel:()=>tu,DINOv3ViTModel:()=>sg,DINOv3ViTPreTrainedModel:()=>ru,DPTForDepthEstimation:()=>pg,DPTModel:()=>ug,DPTPreTrainedModel:()=>ra,DacDecoderModel:()=>Jo,DacDecoderOutput:()=>Yc,DacEncoderModel:()=>Qo,DacEncoderOutput:()=>Kc,DacModel:()=>L_,DacPreTrainedModel:()=>vn,DebertaForMaskedLM:()=>z_,DebertaForQuestionAnswering:()=>D_,DebertaForSequenceClassification:()=>R_,DebertaForTokenClassification:()=>$_,DebertaModel:()=>N_,DebertaPreTrainedModel:()=>Kr,DebertaV2ForMaskedLM:()=>B_,DebertaV2ForQuestionAnswering:()=>G_,DebertaV2ForSequenceClassification:()=>F_,DebertaV2ForTokenClassification:()=>j_,DebertaV2Model:()=>U_,DebertaV2PreTrainedModel:()=>Yr,DecisionTransformerModel:()=>q_,DecisionTransformerPreTrainedModel:()=>Qc,DeiTForImageClassification:()=>V_,DeiTModel:()=>W_,DeiTPreTrainedModel:()=>Zo,DepthAnythingForDepthEstimation:()=>H_,DepthAnythingPreTrainedModel:()=>Jc,DepthProForDepthEstimation:()=>X_,DepthProPreTrainedModel:()=>Zc,DetrForObjectDetection:()=>Y_,DetrForSegmentation:()=>Q_,DetrModel:()=>K_,DetrObjectDetectionOutput:()=>En,DetrPreTrainedModel:()=>kn,DetrSegmentationOutput:()=>eu,Dinov2ForImageClassification:()=>Z_,Dinov2Model:()=>J_,Dinov2PreTrainedModel:()=>ea,Dinov2WithRegistersForImageClassification:()=>tg,Dinov2WithRegistersModel:()=>eg,Dinov2WithRegistersPreTrainedModel:()=>ta,DistilBertForMaskedLM:()=>lg,DistilBertForQuestionAnswering:()=>ig,DistilBertForSequenceClassification:()=>og,DistilBertForTokenClassification:()=>ag,DistilBertModel:()=>ng,DistilBertPreTrainedModel:()=>Qr,DonutSwinModel:()=>cg,DonutSwinPreTrainedModel:()=>su,EdgeTamModel:()=>Xy,EfficientNetForImageClassification:()=>dg,EfficientNetModel:()=>fg,EfficientNetPreTrainedModel:()=>sa,ElectraForMaskedLM:()=>hg,ElectraForQuestionAnswering:()=>wg,ElectraForSequenceClassification:()=>_g,ElectraForTokenClassification:()=>gg,ElectraModel:()=>mg,ElectraPreTrainedModel:()=>Jr,Ernie4_5ForCausalLM:()=>yg,Ernie4_5Model:()=>xg,Ernie4_5PretrainedModel:()=>na,EsmForMaskedLM:()=>vg,EsmForSequenceClassification:()=>kg,EsmForTokenClassification:()=>Eg,EsmModel:()=>bg,EsmPreTrainedModel:()=>Ds,ExaoneForCausalLM:()=>Tg,ExaoneModel:()=>Ag,ExaonePreTrainedModel:()=>oa,FalconForCausalLM:()=>Sg,FalconH1ForCausalLM:()=>Ig,FalconH1Model:()=>Og,FalconH1PreTrainedModel:()=>ia,FalconModel:()=>Mg,FalconPreTrainedModel:()=>aa,FastViTForImageClassification:()=>Pg,FastViTModel:()=>Cg,FastViTPreTrainedModel:()=>la,Florence2ForConditionalGeneration:()=>Lg,Florence2PreTrainedModel:()=>nu,GLPNForDepthEstimation:()=>Gg,GLPNModel:()=>jg,GLPNPreTrainedModel:()=>ma,GPT2LMHeadModel:()=>Zg,GPT2Model:()=>Jg,GPT2PreTrainedModel:()=>xa,GPTBigCodeForCausalLM:()=>Wg,GPTBigCodeModel:()=>qg,GPTBigCodePreTrainedModel:()=>ha,GPTJForCausalLM:()=>tw,GPTJModel:()=>ew,GPTJPreTrainedModel:()=>ya,GPTNeoForCausalLM:()=>Hg,GPTNeoModel:()=>Vg,GPTNeoPreTrainedModel:()=>_a,GPTNeoXForCausalLM:()=>Kg,GPTNeoXModel:()=>Xg,GPTNeoXPreTrainedModel:()=>ga,Gemma2ForCausalLM:()=>$g,Gemma2Model:()=>Rg,Gemma2PreTrainedModel:()=>ua,Gemma3ForCausalLM:()=>Ug,Gemma3Model:()=>Dg,Gemma3PreTrainedModel:()=>pa,Gemma3nForConditionalGeneration:()=>fa,Gemma3nPreTrainedModel:()=>ou,GemmaForCausalLM:()=>zg,GemmaModel:()=>Ng,GemmaPreTrainedModel:()=>ca,GlmForCausalLM:()=>Fg,GlmModel:()=>Bg,GlmPreTrainedModel:()=>da,GptOssForCausalLM:()=>Qg,GptOssModel:()=>Yg,GptOssPreTrainedModel:()=>wa,GraniteForCausalLM:()=>sw,GraniteModel:()=>rw,GraniteMoeHybridForCausalLM:()=>ow,GraniteMoeHybridModel:()=>nw,GraniteMoeHybridPreTrainedModel:()=>va,GranitePreTrainedModel:()=>ba,GroundingDinoForObjectDetection:()=>aw,GroundingDinoPreTrainedModel:()=>au,GroupViTModel:()=>iw,GroupViTPreTrainedModel:()=>iu,HeliumForCausalLM:()=>cw,HeliumModel:()=>lw,HeliumPreTrainedModel:()=>ka,HieraForImageClassification:()=>pw,HieraModel:()=>uw,HieraPreTrainedModel:()=>Ea,HubertForCTC:()=>ww,HubertForSequenceClassification:()=>xw,HubertModel:()=>gw,HubertPreTrainedModel:()=>_w,HunYuanDenseV1ForCausalLM:()=>bw,HunYuanDenseV1Model:()=>yw,HunYuanDenseV1PreTrainedModel:()=>Aa,IJepaForImageClassification:()=>Ew,IJepaModel:()=>kw,IJepaPreTrainedModel:()=>Ta,Idefics3ForConditionalGeneration:()=>cu,Idefics3PreTrainedModel:()=>lu,JAISLMHeadModel:()=>Tw,JAISModel:()=>Aw,JAISPreTrainedModel:()=>Ma,JinaCLIPModel:()=>Mw,JinaCLIPPreTrainedModel:()=>An,JinaCLIPTextModel:()=>Sa,JinaCLIPVisionModel:()=>Sw,Lfm2ForCausalLM:()=>Iw,Lfm2Model:()=>Ow,Lfm2MoeForCausalLM:()=>Pw,Lfm2MoeModel:()=>Cw,Lfm2MoePreTrainedModel:()=>Ia,Lfm2PreTrainedModel:()=>Oa,LiteWhisperForConditionalGeneration:()=>ob,Llama4ForCausalLM:()=>zw,Llama4PreTrainedModel:()=>uu,LlamaForCausalLM:()=>Nw,LlamaModel:()=>Lw,LlamaPreTrainedModel:()=>Ca,LlavaForConditionalGeneration:()=>Tn,LlavaOnevisionForConditionalGeneration:()=>Tn,LlavaPreTrainedModel:()=>pu,LlavaQwen2ForCausalLM:()=>$w,LongT5ForConditionalGeneration:()=>Uw,LongT5Model:()=>Dw,LongT5PreTrainedModel:()=>Pa,M2M100ForConditionalGeneration:()=>Fw,M2M100Model:()=>Bw,M2M100PreTrainedModel:()=>La,MBartForCausalLM:()=>Kw,MBartForConditionalGeneration:()=>Hw,MBartForSequenceClassification:()=>Xw,MBartModel:()=>Vw,MBartPreTrainedModel:()=>Us,MPNetForMaskedLM:()=>Lx,MPNetForQuestionAnswering:()=>Rx,MPNetForSequenceClassification:()=>Nx,MPNetForTokenClassification:()=>zx,MPNetModel:()=>Px,MPNetPreTrainedModel:()=>Zr,MT5ForConditionalGeneration:()=>Bx,MT5Model:()=>Ux,MT5PreTrainedModel:()=>Wa,MarianMTModel:()=>Gw,MarianModel:()=>jw,MarianPreTrainedModel:()=>Na,MaskFormerForInstanceSegmentation:()=>Ww,MaskFormerModel:()=>qw,MaskFormerPreTrainedModel:()=>za,Metric3DForDepthEstimation:()=>Yw,Metric3DPreTrainedModel:()=>fu,Metric3Dv2ForDepthEstimation:()=>Qw,Metric3Dv2PreTrainedModel:()=>du,MgpstrForSceneTextRecognition:()=>Jw,MgpstrModelOutput:()=>mu,MgpstrPreTrainedModel:()=>hu,MimiDecoderModel:()=>$a,MimiDecoderOutput:()=>gu,MimiEncoderModel:()=>Ra,MimiEncoderOutput:()=>_u,MimiModel:()=>Zw,MimiPreTrainedModel:()=>Mn,MistralForCausalLM:()=>tx,MistralModel:()=>ex,MistralPreTrainedModel:()=>Da,MobileBertForMaskedLM:()=>sx,MobileBertForQuestionAnswering:()=>ox,MobileBertForSequenceClassification:()=>nx,MobileBertModel:()=>rx,MobileBertPreTrainedModel:()=>Bs,MobileLLMForCausalLM:()=>ix,MobileLLMModel:()=>ax,MobileLLMPreTrainedModel:()=>Ua,MobileNetV1ForImageClassification:()=>cx,MobileNetV1ForSemanticSegmentation:()=>ux,MobileNetV1Model:()=>lx,MobileNetV1PreTrainedModel:()=>Sn,MobileNetV2ForImageClassification:()=>fx,MobileNetV2ForSemanticSegmentation:()=>dx,MobileNetV2Model:()=>px,MobileNetV2PreTrainedModel:()=>On,MobileNetV3ForImageClassification:()=>hx,MobileNetV3ForSemanticSegmentation:()=>_x,MobileNetV3Model:()=>mx,MobileNetV3PreTrainedModel:()=>In,MobileNetV4ForImageClassification:()=>wx,MobileNetV4ForSemanticSegmentation:()=>xx,MobileNetV4Model:()=>gx,MobileNetV4PreTrainedModel:()=>Cn,MobileViTForImageClassification:()=>bx,MobileViTModel:()=>yx,MobileViTPreTrainedModel:()=>Ba,MobileViTV2ForImageClassification:()=>kx,MobileViTV2Model:()=>vx,MobileViTV2PreTrainedModel:()=>Fa,ModernBertDecoderForCausalLM:()=>Ox,ModernBertDecoderModel:()=>Sx,ModernBertDecoderPreTrainedModel:()=>ja,ModernBertForMaskedLM:()=>Ax,ModernBertForSequenceClassification:()=>Tx,ModernBertForTokenClassification:()=>Mx,ModernBertModel:()=>Ex,ModernBertPreTrainedModel:()=>Fs,Moondream1ForConditionalGeneration:()=>Rw,MoonshineForConditionalGeneration:()=>Cx,MoonshineModel:()=>Ix,MoonshinePreTrainedModel:()=>Ga,MptForCausalLM:()=>Dx,MptModel:()=>$x,MptPreTrainedModel:()=>qa,MultiModalityCausalLM:()=>Fx,MultiModalityPreTrainedModel:()=>wu,MusicgenForCausalLM:()=>Gx,MusicgenForConditionalGeneration:()=>Ha,MusicgenModel:()=>jx,MusicgenPreTrainedModel:()=>Va,NanoChatForCausalLM:()=>Wx,NanoChatModel:()=>qx,NanoChatPreTrainedModel:()=>Xa,NeoBertForMaskedLM:()=>Hx,NeoBertForQuestionAnswering:()=>Yx,NeoBertForSequenceClassification:()=>Xx,NeoBertForTokenClassification:()=>Kx,NeoBertModel:()=>Vx,NeoBertPreTrainedModel:()=>es,NomicBertModel:()=>Qx,NomicBertPreTrainedModel:()=>xu,OPTForCausalLM:()=>iy,OPTModel:()=>ay,OPTPreTrainedModel:()=>Za,Olmo2ForCausalLM:()=>ty,Olmo2Model:()=>ey,Olmo2PreTrainedModel:()=>Ya,Olmo3ForCausalLM:()=>sy,Olmo3Model:()=>ry,Olmo3PreTrainedModel:()=>Qa,OlmoForCausalLM:()=>Zx,OlmoModel:()=>Jx,OlmoPreTrainedModel:()=>Ka,OpenELMForCausalLM:()=>oy,OpenELMModel:()=>ny,OpenELMPreTrainedModel:()=>Ja,OwlViTForObjectDetection:()=>py,OwlViTModel:()=>uy,OwlViTPreTrainedModel:()=>ti,Owlv2ForObjectDetection:()=>cy,Owlv2Model:()=>ly,Owlv2PreTrainedModel:()=>ei,PaliGemmaForConditionalGeneration:()=>fy,PaliGemmaPreTrainedModel:()=>yu,ParakeetForCTC:()=>dy,ParakeetPreTrainedModel:()=>bu,PatchTSMixerForPrediction:()=>hy,PatchTSMixerModel:()=>my,PatchTSMixerPreTrainedModel:()=>ri,PatchTSTForPrediction:()=>gy,PatchTSTModel:()=>_y,PatchTSTPreTrainedModel:()=>si,Phi3ForCausalLM:()=>by,Phi3Model:()=>yy,Phi3PreTrainedModel:()=>oi,Phi3VForCausalLM:()=>ai,Phi3VPreTrainedModel:()=>vu,PhiForCausalLM:()=>xy,PhiModel:()=>wy,PhiPreTrainedModel:()=>ni,PreTrainedModel:()=>y,PvtForImageClassification:()=>ky,PvtModel:()=>vy,PvtPreTrainedModel:()=>ii,PyAnnoteForAudioFrameClassification:()=>Ay,PyAnnoteModel:()=>Ey,PyAnnotePreTrainedModel:()=>li,Qwen2ForCausalLM:()=>My,Qwen2Model:()=>Ty,Qwen2PreTrainedModel:()=>ci,Qwen2VLForConditionalGeneration:()=>ui,Qwen2VLPreTrainedModel:()=>ku,Qwen2_5_VLForConditionalGeneration:()=>pi,Qwen3ForCausalLM:()=>Oy,Qwen3Model:()=>Sy,Qwen3PreTrainedModel:()=>fi,Qwen3VLForConditionalGeneration:()=>di,Qwen3_5ForConditionalGeneration:()=>mi,Qwen3_5MoeForConditionalGeneration:()=>Iy,RFDetrForObjectDetection:()=>Ny,RFDetrModel:()=>Ly,RFDetrObjectDetectionOutput:()=>Eu,RFDetrPreTrainedModel:()=>_i,RTDetrForObjectDetection:()=>I_,RTDetrModel:()=>O_,RTDetrObjectDetectionOutput:()=>gr,RTDetrPreTrainedModel:()=>Ko,RTDetrV2ForObjectDetection:()=>Vy,RTDetrV2Model:()=>Wy,RTDetrV2ObjectDetectionOutput:()=>Au,RTDetrV2PreTrainedModel:()=>gi,ResNetForImageClassification:()=>Py,ResNetModel:()=>Cy,ResNetPreTrainedModel:()=>hi,RoFormerForMaskedLM:()=>Fy,RoFormerForQuestionAnswering:()=>qy,RoFormerForSequenceClassification:()=>jy,RoFormerForTokenClassification:()=>Gy,RoFormerModel:()=>By,RoFormerPreTrainedModel:()=>rs,RobertaForMaskedLM:()=>Ry,RobertaForQuestionAnswering:()=>Uy,RobertaForSequenceClassification:()=>$y,RobertaForTokenClassification:()=>Dy,RobertaModel:()=>zy,RobertaPreTrainedModel:()=>ts,Sam2ImageSegmentationOutput:()=>Su,Sam2Model:()=>wi,Sam2PreTrainedModel:()=>Ou,Sam3TrackerModel:()=>Ky,SamImageSegmentationOutput:()=>Tu,SamModel:()=>Hy,SamPreTrainedModel:()=>Mu,SapiensForDepthEstimation:()=>Qy,SapiensForNormalEstimation:()=>Jy,SapiensForSemanticSegmentation:()=>Yy,SapiensPreTrainedModel:()=>Pn,SegformerForImageClassification:()=>e0,SegformerForSemanticSegmentation:()=>t0,SegformerModel:()=>Zy,SegformerPreTrainedModel:()=>Ln,SiglipModel:()=>r0,SiglipPreTrainedModel:()=>xi,SiglipTextModel:()=>yi,SiglipVisionModel:()=>s0,SmolLM3ForCausalLM:()=>o0,SmolLM3Model:()=>n0,SmolLM3PreTrainedModel:()=>bi,SmolVLMForConditionalGeneration:()=>vw,SnacDecoderModel:()=>ki,SnacEncoderModel:()=>vi,SnacModel:()=>a0,SnacPreTrainedModel:()=>Nn,SpeechT5ForSpeechToText:()=>l0,SpeechT5ForTextToSpeech:()=>c0,SpeechT5HifiGan:()=>u0,SpeechT5Model:()=>i0,SpeechT5PreTrainedModel:()=>zn,SqueezeBertForMaskedLM:()=>f0,SqueezeBertForQuestionAnswering:()=>m0,SqueezeBertForSequenceClassification:()=>d0,SqueezeBertModel:()=>p0,SqueezeBertPreTrainedModel:()=>js,StableLmForCausalLM:()=>_0,StableLmModel:()=>h0,StableLmPreTrainedModel:()=>Ei,Starcoder2ForCausalLM:()=>w0,Starcoder2Model:()=>g0,Starcoder2PreTrainedModel:()=>Ai,StyleTextToSpeech2Model:()=>x0,StyleTextToSpeech2PreTrainedModel:()=>Iu,SupertonicForConditionalGeneration:()=>Ti,SupertonicPreTrainedModel:()=>Cu,Swin2SRForImageSuperResolution:()=>E0,Swin2SRModel:()=>k0,Swin2SRPreTrainedModel:()=>Mi,SwinForImageClassification:()=>b0,SwinForSemanticSegmentation:()=>v0,SwinModel:()=>y0,SwinPreTrainedModel:()=>Rn,T5ForConditionalGeneration:()=>T0,T5Model:()=>A0,T5PreTrainedModel:()=>Si,TableTransformerForObjectDetection:()=>S0,TableTransformerModel:()=>M0,TableTransformerObjectDetectionOutput:()=>Pu,TableTransformerPreTrainedModel:()=>Oi,TrOCRForCausalLM:()=>O0,TrOCRPreTrainedModel:()=>Lu,UltravoxModel:()=>zu,UltravoxPreTrainedModel:()=>Nu,UniSpeechForCTC:()=>P0,UniSpeechForSequenceClassification:()=>L0,UniSpeechModel:()=>C0,UniSpeechPreTrainedModel:()=>$n,UniSpeechSatForAudioFrameClassification:()=>$0,UniSpeechSatForCTC:()=>z0,UniSpeechSatForSequenceClassification:()=>R0,UniSpeechSatModel:()=>N0,UniSpeechSatPreTrainedModel:()=>Gs,VaultGemmaForCausalLM:()=>U0,VaultGemmaModel:()=>D0,VaultGemmaPreTrainedModel:()=>Ii,ViTForImageClassification:()=>j0,ViTMAEModel:()=>G0,ViTMAEPreTrainedModel:()=>Ru,ViTMSNForImageClassification:()=>W0,ViTMSNModel:()=>q0,ViTMSNPreTrainedModel:()=>Pi,ViTModel:()=>F0,ViTPreTrainedModel:()=>Ci,VisionEncoderDecoderModel:()=>B0,VitMatteForImageMatting:()=>V0,VitMattePreTrainedModel:()=>$u,VitPoseForPoseEstimation:()=>H0,VitPosePreTrainedModel:()=>Du,VitsModel:()=>X0,VitsModelOutput:()=>Uu,VitsPreTrainedModel:()=>Bu,VoxtralForConditionalGeneration:()=>I0,Wav2Vec2BertForCTC:()=>Y0,Wav2Vec2BertForSequenceClassification:()=>Q0,Wav2Vec2BertModel:()=>K0,Wav2Vec2BertPreTrainedModel:()=>Dn,Wav2Vec2ForAudioFrameClassification:()=>hw,Wav2Vec2ForCTC:()=>dw,Wav2Vec2ForSequenceClassification:()=>mw,Wav2Vec2Model:()=>fw,Wav2Vec2PreTrainedModel:()=>nr,WavLMForAudioFrameClassification:()=>rb,WavLMForCTC:()=>Z0,WavLMForSequenceClassification:()=>eb,WavLMForXVector:()=>tb,WavLMModel:()=>J0,WavLMPreTrainedModel:()=>ss,WeSpeakerResNetModel:()=>sb,WeSpeakerResNetPreTrainedModel:()=>ju,WhisperForConditionalGeneration:()=>qu,WhisperModel:()=>nb,WhisperPreTrainedModel:()=>Li,XLMForQuestionAnswering:()=>ub,XLMForSequenceClassification:()=>lb,XLMForTokenClassification:()=>cb,XLMModel:()=>ab,XLMPreTrainedModel:()=>ns,XLMRobertaForMaskedLM:()=>fb,XLMRobertaForQuestionAnswering:()=>hb,XLMRobertaForSequenceClassification:()=>db,XLMRobertaForTokenClassification:()=>mb,XLMRobertaModel:()=>pb,XLMRobertaPreTrainedModel:()=>os,XLMWithLMHeadModel:()=>ib,XVectorOutput:()=>Fu,YolosForObjectDetection:()=>gb,YolosModel:()=>_b,YolosObjectDetectionOutput:()=>Wu,YolosPreTrainedModel:()=>Ni,YoutuForCausalLM:()=>xb,YoutuModel:()=>wb,YoutuPreTrainedModel:()=>zi});var $s=class extends y{},Mh=class extends $s{},Sh=class extends $s{async _call(e){return new G(await super._call(e))}},Oh=class extends $s{async _call(e){return new Ae(await super._call(e))}},Ih=class extends $s{async _call(e){return new we(await super._call(e))}};var Co=class extends y{},Ch=class extends Co{},Ph=class extends Co{};var Po=class extends y{},Lh=class extends Po{},Nh=class extends Po{};var Lo=class extends y{},zh=class extends Lo{},Rh=class extends Lo{};var No=class extends y{},$h=class extends No{},Dh=class extends No{};var yn=class extends y{},Uh=class extends yn{},Bh=class extends yn{},Fh=class extends yn{async _call(e){return new G(await super._call(e))}};var zo=class extends y{},jh=class extends zo{},Gh=class extends zo{async _call(e){return new G(await super._call(e))}};var Vr=class extends y{},qh=class extends Vr{},Wh=class extends Vr{async _call(e){return new we(await super._call(e))}},Vh=class extends Vr{async _call(e){return new G(await super._call(e))}},Hh=class extends Vr{async _call(e){return new he(await super._call(e))}},Xh=class extends Vr{async _call(e){return new Ae(await super._call(e))}};var Ro=class extends y{},Kh=class extends Ro{},Yh=class extends Ro{};var $o=class extends y{},Qh=class extends $o{},Jh=class extends $o{};var Do=class extends y{},Zh=class extends Do{},e_=class extends Do{};var Hr=class extends y{},t_=class extends Hr{},r_=class extends Hr{async _call(e){return new we(await super._call(e))}},s_=class extends Hr{async _call(e){return new G(await super._call(e))}},n_=class extends Hr{async _call(e){return new he(await super._call(e))}},o_=class extends Hr{async _call(e){return new Ae(await super._call(e))}};var jL=4299n,n2=6561n,Hc=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"]},Uo=class extends Hc{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:c=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 M=Object.values(i)[0].dims.at(-2);r=at([a.dims[0],M+S])}}return{...await Lt(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,generation_config:l,logits_processor:c},!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==n2)-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>=n2?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),Oo(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],jL),l=Ee([s,a,i],1),{waveform:c}=await ue(this.sessions.conditional_decoder,{speech_tokens:l,speaker_features:o,speaker_embeddings:n});return c}};var Xc=class extends y{},a_=class extends Xc{};var bn=class extends y{},i_=class extends bn{},Bo=class extends bn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Fo=class extends bn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"audio_model"})}};var _r=class extends y{},l_=class extends _r{},c_=class extends _r{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},jo=class extends _r{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},u_=class extends _r{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}},p_=class extends _r{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var Go=class extends y{},f_=class extends Go{},d_=class extends Go{};var qo=class extends y{},m_=class extends qo{},h_=class extends qo{};var Wo=class extends y{},__=class extends Wo{},g_=class extends Wo{};var Vo=class extends y{},w_=class extends Vo{},x_=class extends Vo{};var Xr=class extends y{},y_=class extends Xr{},b_=class extends Xr{async _call(e){return new we(await super._call(e))}},v_=class extends Xr{async _call(e){return new G(await super._call(e))}},k_=class extends Xr{async _call(e){return new he(await super._call(e))}},E_=class extends Xr{async _call(e){return new Ae(await super._call(e))}};var Ho=class extends y{},A_=class extends Ho{},T_=class extends Ho{async _call(e){return new G(await super._call(e))}};var Xo=class extends y{},M_=class extends Xo{},S_=class extends Xo{async _call(e){return new G(await super._call(e))}};var Ko=class extends y{},O_=class extends Ko{},I_=class extends Ko{async _call(e){return new gr(await super._call(e))}},gr=class extends ze{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var Yo=class extends y{},C_=class extends Yo{},P_=class extends Yo{async _call(e){return new gr(await super._call(e))}};var Kc=class extends ze{constructor({audio_codes:e}){super(),this.audio_codes=e}},Yc=class extends ze{constructor({audio_values:e}){super(),this.audio_values=e}},vn=class extends y{main_input_name="input_values";forward_params=["input_values"]},L_=class extends vn{async encode(e){return new Kc(await ue(this.sessions.encoder_model,e))}async decode(e){return new Yc(await ue(this.sessions.decoder_model,e))}},Qo=class extends vn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},Jo=class extends vn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var Kr=class extends y{},N_=class extends Kr{},z_=class extends Kr{async _call(e){return new we(await super._call(e))}},R_=class extends Kr{async _call(e){return new G(await super._call(e))}},$_=class extends Kr{async _call(e){return new he(await super._call(e))}},D_=class extends Kr{async _call(e){return new Ae(await super._call(e))}};var Yr=class extends y{},U_=class extends Yr{},B_=class extends Yr{async _call(e){return new we(await super._call(e))}},F_=class extends Yr{async _call(e){return new G(await super._call(e))}},j_=class extends Yr{async _call(e){return new he(await super._call(e))}},G_=class extends Yr{async _call(e){return new Ae(await super._call(e))}};var Qc=class extends y{},q_=class extends Qc{};var Zo=class extends y{},W_=class extends Zo{},V_=class extends Zo{async _call(e){return new G(await super._call(e))}};var Jc=class extends y{},H_=class extends Jc{};var Zc=class extends y{},X_=class extends Zc{};var kn=class extends y{},K_=class extends kn{},Y_=class extends kn{async _call(e){return new En(await super._call(e))}},Q_=class extends kn{async _call(e){return new eu(await super._call(e))}},En=class extends ze{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}},eu=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 ea=class extends y{},J_=class extends ea{},Z_=class extends ea{async _call(e){return new G(await super._call(e))}};var ta=class extends y{},eg=class extends ta{},tg=class extends ta{async _call(e){return new G(await super._call(e))}};var tu=class extends y{},rg=class extends tu{};var ru=class extends y{},sg=class extends ru{};var Qr=class extends y{},ng=class extends Qr{},og=class extends Qr{async _call(e){return new G(await super._call(e))}},ag=class extends Qr{async _call(e){return new he(await super._call(e))}},ig=class extends Qr{async _call(e){return new Ae(await super._call(e))}},lg=class extends Qr{async _call(e){return new we(await super._call(e))}};var su=class extends y{},cg=class extends su{};var ra=class extends y{},ug=class extends ra{},pg=class extends ra{};var sa=class extends y{},fg=class extends sa{},dg=class extends sa{async _call(e){return new G(await super._call(e))}};var Jr=class extends y{},mg=class extends Jr{},hg=class extends Jr{async _call(e){return new we(await super._call(e))}},_g=class extends Jr{async _call(e){return new G(await super._call(e))}},gg=class extends Jr{async _call(e){return new he(await super._call(e))}},wg=class extends Jr{async _call(e){return new Ae(await super._call(e))}};var na=class extends y{},xg=class extends na{},yg=class extends na{};var Ds=class extends y{},bg=class extends Ds{},vg=class extends Ds{async _call(e){return new we(await super._call(e))}},kg=class extends Ds{async _call(e){return new G(await super._call(e))}},Eg=class extends Ds{async _call(e){return new he(await super._call(e))}};var oa=class extends y{},Ag=class extends oa{},Tg=class extends oa{};var aa=class extends y{},Mg=class extends aa{},Sg=class extends aa{};var ia=class extends y{},Og=class extends ia{},Ig=class extends ia{};var la=class extends y{},Cg=class extends la{},Pg=class extends la{async _call(e){return new G(await super._call(e))}};var nu=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"},Lg=class extends nu{_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:c}){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 Xt(this,{inputs_embeds:l,attention_mask:s});a=f}if(!c){if(!n)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");c=await this.encode_text({input_ids:n})}return await Lt(this,{inputs_embeds:c,attention_mask:o,encoder_attention_mask:s,encoder_hidden_states:a,past_key_values:i},!0)}};var ca=class extends y{},Ng=class extends ca{},zg=class extends ca{};var ua=class extends y{},Rg=class extends ua{},$g=class extends ua{};var pa=class extends y{},Dg=class extends pa{},Ug=class extends pa{};var ou=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"]},fa=class extends ou{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:c=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 Lt(this,{inputs_embeds:i,per_layer_inputs:l,past_key_values:c,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 hr({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 Vc({audio_token_id:this.config.audio_token_id,...e,audio_features:s})}};var da=class extends y{},Bg=class extends da{},Fg=class extends da{};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 ya=class extends y{},ew=class extends ya{},tw=class extends ya{};var ba=class extends y{},rw=class extends ba{},sw=class extends ba{};var va=class extends y{},nw=class extends va{},ow=class extends va{};var au=class extends y{},aw=class extends au{};var iu=class extends y{},iw=class extends iu{};var ka=class extends y{},lw=class extends ka{},cw=class extends ka{};var Ea=class extends y{},uw=class extends Ea{},pw=class extends Ea{async _call(e){return new G(await super._call(e))}};var nr=class extends y{},fw=class extends nr{},dw=class extends nr{async _call(e){return new yt(await super._call(e))}},mw=class extends nr{async _call(e){return new G(await super._call(e))}},hw=class extends nr{async _call(e){return new he(await super._call(e))}};var _w=class extends y{},gw=class extends nr{},ww=class extends nr{async _call(e){return new yt(await super._call(e))}},xw=class extends nr{async _call(e){return new G(await super._call(e))}};var Aa=class extends y{},yw=class extends Aa{},bw=class extends Aa{};var lu=class extends y{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]},cu=class extends lu{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 hr({image_token_id:this.config.image_token_id,...e,image_features:s})}},vw=class extends cu{};var Ta=class extends y{},kw=class extends Ta{},Ew=class extends Ta{async _call(e){return new G(await super._call(e))}};var Ma=class extends y{},Aw=class extends Ma{},Tw=class extends Ma{};var An=class extends y{},Mw=class extends An{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:c}=this.config.vision_config;e.pixel_values=He([0,3,c,c],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}},Sa=class extends An{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Sw=class extends An{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var Oa=class extends y{},Ow=class extends Oa{},Iw=class extends Oa{};var Ia=class extends y{},Cw=class extends Ia{},Pw=class extends Ia{};var Ca=class extends y{},Lw=class extends Ca{},Nw=class extends Ca{};var uu=class extends y{},zw=class extends uu{};var pu=class extends y{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},Tn=class extends pu{_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return hr({image_token_id:this.config.image_token_index,...e,image_features:s})}},Rw=class extends Tn{},$w=class extends Tn{};var Pa=class extends y{},Dw=class extends Pa{},Uw=class extends Pa{};var La=class extends y{},Bw=class extends La{},Fw=class extends La{};var Na=class extends y{},jw=class extends Na{},Gw=class extends Na{};var za=class extends y{},qw=class extends za{},Ww=class extends za{};var Us=class extends y{},Vw=class extends Us{},Hw=class extends Us{},Xw=class extends Us{async _call(e){return new G(await super._call(e))}},Kw=class extends Us{};var fu=class extends y{},Yw=class extends fu{};var du=class extends y{},Qw=class extends du{};var mu=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]}},hu=class extends y{},Jw=class extends hu{async _call(e){return new mu(await super._call(e))}};var _u=class extends ze{constructor({audio_codes:e}){super(),this.audio_codes=e}},gu=class extends ze{constructor({audio_values:e}){super(),this.audio_values=e}},Mn=class extends y{main_input_name="input_values";forward_params=["input_values"]},Zw=class extends Mn{async encode(e){return new _u(await ue(this.sessions.encoder_model,e))}async decode(e){return new gu(await ue(this.sessions.decoder_model,e))}},Ra=class extends Mn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},$a=class extends Mn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var Da=class extends y{},ex=class extends Da{},tx=class extends Da{};var Bs=class extends y{},rx=class extends Bs{},sx=class extends Bs{async _call(e){return new we(await super._call(e))}},nx=class extends Bs{async _call(e){return new G(await super._call(e))}},ox=class extends Bs{async _call(e){return new Ae(await super._call(e))}};var Ua=class extends y{},ax=class extends Ua{},ix=class extends Ua{};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{},fx=class extends On{async _call(e){return new G(await super._call(e))}},dx=class extends On{};var In=class extends y{},mx=class extends In{},hx=class extends In{async _call(e){return new G(await super._call(e))}},_x=class extends In{};var Cn=class extends y{},gx=class extends Cn{},wx=class extends Cn{async _call(e){return new G(await super._call(e))}},xx=class extends Cn{};var Ba=class extends y{},yx=class extends Ba{},bx=class extends Ba{async _call(e){return new G(await super._call(e))}};var Fa=class extends y{},vx=class extends Fa{},kx=class extends Fa{async _call(e){return new G(await super._call(e))}};var Fs=class extends y{},Ex=class extends Fs{},Ax=class extends Fs{async _call(e){return new we(await super._call(e))}},Tx=class extends Fs{async _call(e){return new G(await super._call(e))}},Mx=class extends Fs{async _call(e){return new he(await super._call(e))}};var ja=class extends y{},Sx=class extends ja{},Ox=class extends ja{};var Ga=class extends y{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},Ix=class extends Ga{},Cx=class extends Ga{};var Zr=class extends y{},Px=class extends Zr{},Lx=class extends Zr{async _call(e){return new we(await super._call(e))}},Nx=class extends Zr{async _call(e){return new G(await super._call(e))}},zx=class extends Zr{async _call(e){return new he(await super._call(e))}},Rx=class extends Zr{async _call(e){return new Ae(await super._call(e))}};var qa=class extends y{},$x=class extends qa{},Dx=class extends qa{};var Wa=class extends y{},Ux=class extends Wa{},Bx=class extends Wa{};var wu=class extends y{},Fx=class extends wu{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,c=nt(e,l.inputNames);s=await ue(l,c)}else{let l=this.sessions.gen_img_embeds,c=nt({image_ids:e.input_ids},l.inputNames);s=await ue(l,c)}let n={...e,...s},o=await Lt(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,mo(r.input_ids,BigInt(s.pad_token_id))],0),r.attention_mask=Ee([r.attention_mask,mo(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 c of i){let p=Ke.fromTensor(c);l.push(p)}return l}};var Va=class extends y{},jx=class extends Va{},Gx=class extends Va{},Ha=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 c=0;c<e.size;++c){if(e.data[c]==this.config.decoder.pad_token_id)continue;let p=c%s,f=Math.floor(c/s)%n,m=p-f;m>0&&m<=o&&(e.data[a++]=e.data[c])}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)),Io(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 Xa=class extends y{},qx=class extends Xa{},Wx=class extends Xa{};var es=class extends y{},Vx=class extends es{},Hx=class extends es{async _call(e){return new we(await super._call(e))}},Xx=class extends es{async _call(e){return new G(await super._call(e))}},Kx=class extends es{async _call(e){return new he(await super._call(e))}},Yx=class extends es{async _call(e){return new Ae(await super._call(e))}};var xu=class extends y{},Qx=class extends xu{};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 Za=class extends y{},ay=class extends Za{},iy=class extends Za{};var ei=class extends y{},ly=class extends ei{},cy=class extends ei{};var ti=class extends y{},uy=class extends ti{},py=class extends ti{};var yu=class extends y{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},fy=class extends yu{_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return hr({image_token_id:this.config.image_token_index,...e,image_features:s})}};var bu=class extends y{},dy=class extends bu{async _call(e){return new yt(await super._call(e))}};var ri=class extends y{},my=class extends ri{},hy=class extends ri{};var si=class extends y{},_y=class extends si{},gy=class extends si{};var ni=class extends y{},wy=class extends ni{},xy=class extends ni{};var oi=class extends y{},yy=class extends oi{},by=class extends oi{};var vu=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},ai=class extends vu{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:c=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 Lt(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,position_ids:o,generation_config:l,logits_processor:c},!1)}};var ii=class extends y{},vy=class extends ii{},ky=class extends ii{async _call(e){return new G(await super._call(e))}};var li=class extends y{},Ey=class extends li{},Ay=class extends li{async _call(e){return new he(await super._call(e))}};var ci=class extends y{},Ty=class extends ci{},My=class extends ci{};var ku=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},ui=class extends ku{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,c=o.spatial_merge_size??2,p=[];if(r||s){let f=e.tolist();n||(n=tc(e));let m=n.tolist(),h=Array.from({length:3},A=>Array.from({length:e.dims[0]},S=>Array.from({length:e.dims[1]},M=>1))),w=r?r.tolist():[],x=s?s.tolist():[],b=0,E=0;for(let A=0;A<f.length;++A){let S=f[A].filter((I,N)=>m[A][N]==1),C=S.reduce((I,N,$)=>(N==l&&I.push($),I),[]).map(I=>S[I+1]),P=C.filter(I=>I==a).length,k=C.filter(I=>I==i).length,F=[],H=0,V=P,J=k;for(let I=0;I<C.length;++I){let N=S.findIndex((Ot,tt)=>tt>H&&Ot==a),$=S.findIndex((Ot,tt)=>tt>H&&Ot==i),te=V>0&&N!==-1?N:S.length+1,pe=J>0&&$!==-1?$:S.length+1,Fe,Pe,Mt,Je;te<pe?([Pe,Mt,Je]=w[b],++b,--V,Fe=te):([Pe,Mt,Je]=x[E],++E,--J,Fe=pe);let[et,st,Te]=[Number(Pe),Math.floor(Number(Mt)/c),Math.floor(Number(Je)/c)],xe=Fe-H,qe=F.length>0?Se(F.at(-1))[0]+1:0;F.push(Array.from({length:3*xe},(Ot,tt)=>qe+tt%xe));let St=xe+qe,be=et*st*Te,Re=Array.from({length:be},(Ot,tt)=>St+Math.floor(tt/(st*Te))),Pr=Array.from({length:be},(Ot,tt)=>St+Math.floor(tt/Te)%st),cs=Array.from({length:be},(Ot,tt)=>St+tt%Te);F.push([Re,Pr,cs].flat()),H=Fe+be}if(H<S.length){let I=F.length>0?Se(F.at(-1))[0]+1:0,N=S.length-H;F.push(Array.from({length:3*N},($,te)=>I+te%N))}let X=F.reduce((I,N)=>I+N.length,0),Y=new Array(X),U=0;for(let I=0;I<3;++I)for(let N=0;N<F.length;++N){let $=F[N],te=$.length/3;for(let pe=I*te;pe<(I+1)*te;++pe)Y[U++]=$[pe]}let L=0,ne=m[A];for(let I=0;I<ne.length;++I)if(ne[I]==1){for(let N=0;N<3;++N)h[N][A][I]=Y[N*X/3+L];++L}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}=Th(n),h=BigInt64Array.from({length:3*f.length},(x,b)=>f[b%f.length]),w=Array.from({length:m[0]},(x,b)=>Se(f.subarray(m[1]*b,m[1]*(b+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]),Zf([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 hr({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=Vt([o,o,o],0)}return r}};var pi=class extends ui{image_grid_thw_name="image_grid_thw"};var fi=class extends y{},Sy=class extends fi{},Oy=class extends fi{};var di=class extends pi{};var mi=class extends di{};var Iy=class extends mi{};var hi=class extends y{},Cy=class extends hi{},Py=class extends hi{async _call(e){return new G(await super._call(e))}};var _i=class extends y{},Ly=class extends _i{},Ny=class extends _i{async _call(e){return new Eu(await super._call(e))}},Eu=class extends gr{};var ts=class extends y{},zy=class extends ts{},Ry=class extends ts{async _call(e){return new we(await super._call(e))}},$y=class extends ts{async _call(e){return new G(await super._call(e))}},Dy=class extends ts{async _call(e){return new he(await super._call(e))}},Uy=class extends ts{async _call(e){return new Ae(await super._call(e))}};var rs=class extends y{},By=class extends rs{},Fy=class extends rs{async _call(e){return new we(await super._call(e))}},jy=class extends rs{async _call(e){return new G(await super._call(e))}},Gy=class extends rs{async _call(e){return new he(await super._call(e))}},qy=class extends rs{async _call(e){return new Ae(await super._call(e))}};var gi=class extends y{},Wy=class extends gi{},Vy=class extends gi{async _call(e){return new Au(await super._call(e))}},Au=class extends gr{};var Tu=class extends ze{constructor({iou_scores:e,pred_masks:r}){super(),this.iou_scores=e,this.pred_masks=r}},Mu=class extends y{},Hy=class extends Mu{async get_image_embeddings({pixel_values:e}){return await Xt(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 Tu(await super._call(e))}};var Su=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}},Ou=class extends y{},wi=class extends Ou{async get_image_embeddings({pixel_values:e}){return await Xt(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 Su(await super._call(e))}},Xy=class extends wi{},Ky=class extends wi{};var Pn=class extends y{},Yy=class extends Pn{},Qy=class extends Pn{},Jy=class extends Pn{};var Ln=class extends y{},Zy=class extends Ln{},e0=class extends Ln{},t0=class extends Ln{};var xi=class extends y{},r0=class extends xi{},yi=class extends xi{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},s0=class extends _r{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var bi=class extends y{},n0=class extends bi{},o0=class extends bi{};var Nn=class extends y{main_input_name="input_values";forward_params=["input_values"]},a0=class extends Nn{async encode(e){return await ue(this.sessions.encoder_model,e)}async decode(e){return await ue(this.sessions.decoder_model,e)}},vi=class extends Nn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},ki=class extends Nn{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{},i0=class extends zn{},l0=class extends zn{},c0=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:c}=await Xt(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,b=null,E=0;for(;;){++E;let M=Ah(!!b),C;b?C=b.output_sequence_out:C=new D("float32",new Float32Array(h),[1,1,h]);let P={use_cache_branch:M,output_sequence:C,encoder_attention_mask:c,speaker_embeddings:r,encoder_hidden_states:l};this.addPastKeyValues(P,x),b=await ue(this.sessions.decoder_model_merged,P),x=this.getPastKeyValues(b,x);let{prob:k,spectrum:F}=b;if(w.push(F),E>=m&&(Array.from(k.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}}},u0=class extends y{main_input_name="spectrogram"};var js=class extends y{},p0=class extends js{},f0=class extends js{async _call(e){return new we(await super._call(e))}},d0=class extends js{async _call(e){return new G(await super._call(e))}},m0=class extends js{async _call(e){return new Ae(await super._call(e))}};var Ei=class extends y{},h0=class extends Ei{},_0=class extends Ei{};var Ai=class extends y{},g0=class extends Ai{},w0=class extends Ai{};var Iu=class extends y{},x0=class extends Iu{};var Cu=class extends y{},Ti=class extends Cu{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:c}=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)),b=Math.max(...x),E=e.dims[0],A=new BigInt64Array(E*b);for(let V=0;V<E;++V)A.fill(1n,V*b,V*b+x[V]);let S=new D("int64",A,[E,b]),M=c*i,C=M*b,P=CA([E,M,b]),k=P.data;for(let V=0;V<E;++V)if(x[V]!==b)for(let J=0;J<M;++J)k.fill(0,V*C+J*b+x[V],V*C+(J+1)*b);let F=He([E],n);for(let V=0;V<n;++V){let J=He([E],V);({denoised_latents:P}=await ue(this.sessions.latent_denoiser,{style:s,noisy_latents:P,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:P});return{waveform:H,durations:m}}};var Rn=class extends y{},y0=class extends Rn{},b0=class extends Rn{async _call(e){return new G(await super._call(e))}},v0=class extends Rn{};var Mi=class extends y{},k0=class extends Mi{},E0=class extends Mi{};var Si=class extends y{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]},A0=class extends Si{},T0=class extends Si{};var Oi=class extends y{},M0=class extends Oi{},S0=class extends Oi{async _call(e){return new Pu(await super._call(e))}},Pu=class extends En{};var Lu=class extends y{},O0=class extends Lu{};var Nu=class extends y{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},zu=class extends Nu{_merge_input_ids_with_audio_features(e){let r=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,r);return Vc({audio_token_id:this.config.ignore_index??this.config.audio_token_id,...e,audio_features:s})}},I0=class extends zu{};var $n=class extends y{},C0=class extends $n{},P0=class extends $n{async _call(e){return new yt(await super._call(e))}},L0=class extends $n{async _call(e){return new G(await super._call(e))}};var Gs=class extends y{},N0=class extends Gs{},z0=class extends Gs{async _call(e){return new yt(await super._call(e))}},R0=class extends Gs{async _call(e){return new G(await super._call(e))}},$0=class extends Gs{async _call(e){return new he(await super._call(e))}};var Ii=class extends y{},D0=class extends Ii{},U0=class extends Ii{};var B0=class extends y{main_input_name="pixel_values";forward_params=["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"]};var Ci=class extends y{},F0=class extends Ci{},j0=class extends Ci{async _call(e){return new G(await super._call(e))}};var Ru=class extends y{},G0=class extends Ru{};var Pi=class extends y{},q0=class extends Pi{},W0=class extends Pi{async _call(e){return new G(await super._call(e))}};var $u=class extends y{},V0=class extends $u{async _call(e){return new Oc(await super._call(e))}};var Du=class extends y{},H0=class extends Du{};var Uu=class extends ze{constructor({waveform:e,spectrogram:r}){super(),this.waveform=e,this.spectrogram=r}},Bu=class extends y{},X0=class extends Bu{async _call(e){return new Uu(await super._call(e))}};var Dn=class extends y{},K0=class extends Dn{},Y0=class extends Dn{async _call(e){return new yt(await super._call(e))}},Q0=class extends Dn{async _call(e){return new G(await super._call(e))}};var Fu=class extends ze{constructor({logits:e,embeddings:r}){super(),this.logits=e,this.embeddings=r}},ss=class extends y{},J0=class extends ss{},Z0=class extends ss{async _call(e){return new yt(await super._call(e))}},eb=class extends ss{async _call(e){return new G(await super._call(e))}},tb=class extends ss{async _call(e){return new Fu(await super._call(e))}},rb=class extends ss{async _call(e){return new he(await super._call(e))}};var ju=class extends y{},sb=class extends ju{};var Gu=class extends wn{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 Li=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"]},nb=class extends Li{},qu=class extends Li{_prepare_generation_config(e,r){return super._prepare_generation_config(e,r,Gu)}_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=`<|${NA(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 Ns,s.push(new Pc(r,a))),r.begin_suppress_tokens&&(s??=new Ns,s.push(new gn(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,b)=>Ee(a.map(E=>E[b]),2)),l=Vt(r.map(([x,b])=>{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,b,null,[0,s]):i[x].slice(null,b)})).transpose(1,0,2,3),[c,p]=Qf(l,-2,0,!0),f=l.clone();for(let x=0;x<f.dims[0];++x){let b=f[x];for(let E=0;E<b.dims[0];++E){let A=b[E],S=c[x][E][0].data,M=p[x][E][0].data;for(let C=0;C<A.dims[0];++C){let P=A[C].data;for(let k=0;k<P.length;++k)P[k]=(P[k]-M[k])/S[k];P.set(Sk(P,o))}}}let m=[ec(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 b=m[x].neg().squeeze_(0),[E,A]=Ik(b.tolist()),S=Array.from({length:E.length-1},(P,k)=>E[k+1]-E[k]),M=dt([1],S).map(P=>!!P),C=[];for(let P=0;P<M.length;++P)M[P]&&C.push(A[P]*n);w[x].data.set(C,1)}return w}},ob=class extends qu{};var ns=class extends y{},ab=class extends ns{},ib=class extends ns{async _call(e){return new we(await super._call(e))}},lb=class extends ns{async _call(e){return new G(await super._call(e))}},cb=class extends ns{async _call(e){return new he(await super._call(e))}},ub=class extends ns{async _call(e){return new Ae(await super._call(e))}};var os=class extends y{},pb=class extends os{},fb=class extends os{async _call(e){return new we(await super._call(e))}},db=class extends os{async _call(e){return new G(await super._call(e))}},mb=class extends os{async _call(e){return new he(await super._call(e))}},hb=class extends os{async _call(e){return new Ae(await super._call(e))}};var Ni=class extends y{},_b=class extends Ni{},gb=class extends Ni{async _call(e){return new Wu(await super._call(e))}},Wu=class extends ze{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var zi=class extends y{},wb=class extends zi{},xb=class extends zi{};var GL=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"]]),qL=new Map([["t5","T5Model"],["longt5","LongT5Model"],["mt5","MT5Model"],["bart","BartModel"],["mbart","MBartModel"],["marian","MarianModel"],["whisper","WhisperModel"],["m2m_100","M2M100Model"],["blenderbot","BlenderbotModel"],["blenderbot-small","BlenderbotSmallModel"]]),WL=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),VL=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"]]),o2=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"]]),a2=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),i2=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),l2=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"]]),c2=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"]]),u2=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),p2=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"]]),HL=new Map([["multi_modality","MultiModalityCausalLM"]]),f2=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"]]),d2=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"]]),m2=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),h2=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"]]),_2=new Map([["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"]]),XL=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),g2=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"]]),w2=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),x2=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),Un=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),y2=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),b2=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),v2=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),k2=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),E2=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),A2=new Map([["wavlm","WavLMForXVector"]]),T2=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),M2=new Map([["vitmatte","VitMatteForImageMatting"]]),KL=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),S2=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),O2=new Map([["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),I2=new Map([["sapiens","SapiensForNormalEstimation"]]),C2=new Map([["vitpose","VitPoseForPoseEstimation"]]),P2=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),yb=[[GL,j.EncoderOnly],[qL,j.EncoderDecoder],[VL,j.DecoderOnlyWithoutHead],[WL,j.AutoEncoder],[l2,j.EncoderOnly],[c2,j.EncoderOnly],[u2,j.Seq2Seq],[o2,j.Seq2Seq],[p2,j.DecoderOnly],[HL,j.MultiModality],[f2,j.EncoderOnly],[d2,j.EncoderOnly],[m2,j.Vision2Seq],[h2,j.ImageTextToText],[_2,j.AudioTextToText],[g2,j.EncoderOnly],[Un,j.EncoderOnly],[b2,j.EncoderOnly],[y2,j.EncoderOnly],[M2,j.EncoderOnly],[KL,j.EncoderOnly],[S2,j.EncoderOnly],[O2,j.EncoderOnly],[I2,j.EncoderOnly],[C2,j.EncoderOnly],[w2,j.EncoderOnly],[x2,j.EncoderOnly],[v2,j.MaskGeneration],[k2,j.EncoderOnly],[E2,j.EncoderOnly],[a2,j.Seq2Seq],[i2,j.EncoderOnly],[A2,j.EncoderOnly],[T2,j.EncoderOnly],[P2,j.EncoderOnly]];for(let[t,e]of yb)for(let r of t.values()){mr.set(r,e);let s=Ri[r];Rs.set(s,r),Wc.set(r,s)}var YL=[["MusicgenForConditionalGeneration",Ha,j.Musicgen],["Phi3VForCausalLM",ai,j.Phi3V],["CLIPTextModelWithProjection",jo,j.EncoderOnly],["SiglipTextModel",yi,j.EncoderOnly],["JinaCLIPTextModel",Sa,j.EncoderOnly],["ClapTextModelWithProjection",Bo,j.EncoderOnly],["ClapAudioModelWithProjection",Fo,j.EncoderOnly],["DacEncoderModel",Qo,j.EncoderOnly],["DacDecoderModel",Jo,j.EncoderOnly],["MimiEncoderModel",Ra,j.EncoderOnly],["MimiDecoderModel",$a,j.EncoderOnly],["SnacEncoderModel",vi,j.EncoderOnly],["SnacDecoderModel",ki,j.EncoderOnly],["Gemma3nForConditionalGeneration",fa,j.ImageAudioTextToText],["SupertonicForConditionalGeneration",Ti,j.Supertonic],["ChatterboxModel",Uo,j.Chatterbox]];for(let[t,e,r]of YL)mr.set(t,r),Rs.set(e,t),Wc.set(t,e);var bb=new Map([["modnet",Un],["birefnet",Un],["isnet",Un],["ben",Un]]);for(let[t,e]of bb.entries())e.set(t,"PreTrainedModel"),mr.set(t,j.EncoderOnly),Wc.set(t,y);mr.set("PreTrainedModel",j.EncoderOnly);Rs.set(y,"PreTrainedModel");var Ce={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:l2,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:c2,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:a2,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:i2,MODEL_FOR_MASKED_LM_MAPPING_NAMES:f2,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:d2,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:g2,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:Un,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:y2,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:b2,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:w2,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:x2,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:v2,MODEL_FOR_CTC_MAPPING_NAMES:k2,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:E2,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:A2,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:T2,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:XL,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:M2,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:S2,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:O2,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:I2,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:C2,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:P2,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:h2,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:_2,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:u2,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:o2,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:p2,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:m2};t2(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:c=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:c,dtype:p,use_external_data_format:f,session_options:m};if(h.config=await Sr.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 b=x.get(w);if(!b){for(let E of x.values())if(E[0]===w){b=E;break}if(!b)continue}return await Ri[b].from_pretrained(e,h)}if(this.BASE_IF_FAIL)return bb.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}`)}},Ir=class extends Oe{static MODEL_CLASS_MAPPINGS=yb.map(e=>e[0]);static BASE_IF_FAIL=!0},$i=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},Vu=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},Bn=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},Hu=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},Xu=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},Ku=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},Yu=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},Qu=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},Ju=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},Zu=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},ep=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},Di=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},Ui=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},Bi=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},tp=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},rp=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]},L2=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]},sp=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_CTC_MAPPING_NAMES]},np=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]},N2=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]},z2=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]},op=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]},R2=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]},ap=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},ip=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]},D2=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]},lp=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]},U2=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ce.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]},B2=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 as(t,e){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(r=>typeof r=="string"||r instanceof URL?Kd(r,e):r instanceof Float64Array?new Float32Array(r):r))}function Fi(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 fe=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 ji=class extends fe{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"?c=>c.sigmoid():c=>new D("float32",Ne(c.data),c.dims),l=[];for(let c of n.logits){let p=i(c),f=await rr(p,r),m=f[0].tolist(),w=f[1].tolist().map((x,b)=>({label:a?a[x]:`LABEL_${x}`,score:m[b]}));r===1?l.push(...w):l.push(w)}return Array.isArray(e)||r===1?l:l[0]}};var Gi=class extends fe{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 c=0;c<a.dims[0];++c){let p=n.input_ids[c],f=a[c],m=[];for(let h=0;h<f.dims[0];++h){let w=f[h],x=Se(w.data)[1],b=i?i[x]:`LABEL_${x}`;if(r.includes(b))continue;let E=this.tokenizer.decode([p[h].item()],{skip_special_tokens:!0});if(E==="")continue;let A=Ne(w.data);m.push({entity:b,score:A[x],index:h,word:E})}l.push(m)}return s?l:l[0]}};var qi=class extends fe{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(),c=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(P=>P==f),b=a[h].tolist(),E=i[h].tolist();for(let P=1;P<b.length;++P)(c[h]==0||P<=x||p.findIndex(k=>k==w[P])!==-1)&&(b[P]=-1/0,E[P]=-1/0);let A=Ne(b).map((P,k)=>[P,k]),S=Ne(E).map((P,k)=>[P,k]);A[0][0]=0,S[0][0]=0;let M=Fv(A,S).filter(P=>P[0][1]<=P[1][1]).map(P=>[P[0][1],P[1][1],P[0][0]*P[1][0]]).sort((P,k)=>k[2]-P[2]),C=[];for(let P=0;P<Math.min(M.length,s);++P){let[k,F,H]=M[P],V=w.slice(k,F+1),J=this.tokenizer.decode(V,{skip_special_tokens:!0});C.push({answer:J,score:H})}s===1?m.push(...C):m.push(C)}return o?m:m[0]}};var Wi=class extends fe{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 c=0;c<l.length;++c){let p=l[c],f=p.findIndex(b=>b==s);if(f===-1)throw Error(`Mask token (${n}) not found in text.`);let m=a[c][f],h=await rr(new D("float32",Ne(m.data),m.dims),r),w=h[0].tolist(),x=h[1].tolist();i.push(x.map((b,E)=>{let A=p.slice();return A[f]=b,{score:w[E],token:Number(b),token_str:this.tokenizer.decode([b]),sequence:this.tokenizer.decode(A,{skip_special_tokens:!0})}}))}return Array.isArray(e)?i:i[0]}};var Cr=class extends fe{_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 Vi=class extends Cr{_key="summary_text"};var Hi=class extends Cr{_key="translation_text"};function F2(t){return Array.isArray(t)&&t.every(e=>"role"in e&&"content"in e)}var Xi=class extends fe{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(F2(e))e=[e];else if(Array.isArray(e)&&e.every(F2))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 c=this.tokenizer(i,{add_special_tokens:o,padding:!0,truncation:!0,...a}),p=await this.model.generate({...c,...r}),f=this.tokenizer.batch_decode(p,{skip_special_tokens:!0}),m;!l&&c.input_ids.dims.at(-1)>0&&(m=this.tokenizer.batch_decode(c.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 Ki=class extends fe{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(c=>s.replace("{}",c)),i=n||r.length===1,l=[];for(let c of e){let p=[];for(let h of a){let w=this.tokenizer(c,{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=>Ne(h)[1]):Ne(p)).map((h,w)=>[h,w]).sort((h,w)=>w[0]-h[0]);l.push({sequence:c,labels:m.map(h=>r[h[1]]),scores:m.map(h=>h[0])})}return o?l:l[0]}};var Yi=class extends fe{async _call(e,{top_k:r=5}={}){let s=this.processor.feature_extractor.config.sampling_rate,n=await as(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 rr(new D("float32",Ne(p.data),p.dims),r),m=f[0].tolist(),w=f[1].tolist().map((x,b)=>({label:o?o[x]:`LABEL_${x}`,score:m[b]}));a.push(w)}return Array.isArray(e)?a:a[0]}};var Qi=class extends fe{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 as(e,i),c=[];for(let p of l){let f=await this.processor(p),m=await this.model({...a,...f}),h=Ne(m.logits_per_audio.data);c.push([...h].map((w,x)=>({score:w,label:r[x]})))}return n?c[0]:c}};var Ji=class extends fe{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 as(n,o),i=[];for(let l of a){let c=await this.processor(l),f=(await this.model(c)).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),c=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 as(c,h),x=[];for(let b 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 M=h*n,C=h*a,P=M-2*C,k=0;for(;;){let F=k+M,H=b.subarray(k,F),V=await this.processor(H),J=k===0,X=F>=b.length;if(E.push({stride:[H.length,J?0:C,X?0:C],input_features:V.input_features,is_last:X}),X)break;k+=P}}else E=[{stride:[b.length,0,0],input_features:(await this.processor(b)).input_features,is_last:!0}];for(let M of E){i.num_frames=Math.floor(M.stride[0]/m);let C=await this.model.generate({inputs:M.input_features,...i});s==="word"?(M.tokens=C.sequences.tolist()[0],M.token_timestamps=C.token_timestamps.tolist()[0].map(P=>ys(P,2))):M.tokens=C[0].tolist(),M.stride=M.stride.map(P=>P/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 as(n,o),i=[];for(let l of a){let c=await this.processor(l),p=Math.floor(l.length/o)*6,f=await this.model.generate({max_new_tokens:p,...r,...c}),m=this.processor.batch_decode(f,{skip_special_tokens:!0})[0];i.push({text:m})}return s?i[0]:i}};var Zi=class extends fe{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 de.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,c=[];for(let p=0;p<a;++p){let f=l?Math.min(Math.ceil(l[p]),i):i,m=p*i;c.push(new wo(o.slice(m,m+f),s))}return Array.isArray(e)?c:c[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:c,durations:p}=await this.model.generate_speech({...i,style:r,num_inference_steps:s,speed:n});return this._postprocess_waveform(e,c,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 Ir.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 el=class extends fe{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}),c=this.tokenizer.batch_decode(l,{skip_special_tokens:!0}).map(p=>({generated_text:p.trim()}));a.push(c)}return s?a:a[0]}};var tl=class extends fe{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 c=await rr(new D("float32",Ne(l.data),l.dims),r),p=c[0].tolist(),m=c[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 j2={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},qs=class extends fe{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 c=await Qe(e),p=c.map(A=>[A.height,A.width]),f=await this.processor(c),{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=j2[i];else if(this.processor.image_processor){for(let[A,S]of Object.entries(j2))if(S in this.processor.image_processor){x=this.processor.image_processor[S].bind(this.processor.image_processor),i=A;break}}let b=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 M of A.segments_info){let C=new Uint8ClampedArray(S.data.length);for(let k=0;k<S.data.length;++k)S.data[k]===M.id&&(C[k]=255);let P=new Ke(C,S.dims[1],S.dims[0],1);E.push({score:M.score,label:b[M.label_id],mask:P})}}else if(i==="semantic"){let{segmentation:A,labels:S}=x(w,a??p)[0];for(let M of S){let C=new Uint8ClampedArray(A.data.length);for(let k=0;k<A.data.length;++k)A.data[k]===M&&(C[k]=255);let P=new Ke(C,A.dims[1],A.dims[0],1);E.push({score:null,label:b[M],mask:P})}}else throw Error(`Subtask ${i} not supported.`);else{let S=w[h[0]];for(let M=0;M<p.length;++M){let C=p[M],P=S[M];P.data.some(F=>F<-1e-5||F>1+1e-5)&&P.sigmoid_();let k=await Ke.fromTensor(P.mul_(255).to("uint8")).resize(C[1],C[0]);E.push({label:null,score:null,mask:k})}}return E}};var rl=class extends qs{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 sl=class extends fe{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),c=await this.model({...i,pixel_values:l}),p=this.model.config.model_type==="siglip"?m=>m.sigmoid().data:m=>Ne(m.data),f=[];for(let m of c.logits_per_image){let w=[...p(m)].map((x,b)=>({score:x,label:r[b]}));w.sort((x,b)=>b.score-x.score),f.push(w)}return n?f:f[0]}};var nl=class extends fe{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),c=await this.model({pixel_values:i,pixel_mask:l}),p=this.processor.image_processor.post_process_object_detection(c,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:Fi(w,!s)})));return n?m:m[0]}};var ol=class extends fe{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}),c=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=c.pixel_values[f].unsqueeze_(0),x=await this.model({...l,pixel_values:w}),b;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];b=E.boxes.map((A,S)=>({score:E.scores[S],label:E.labels[S],box:Fi(A,!o)}))}else{let E=this.processor.image_processor.post_process_object_detection(x,s,h,!0)[0];b=E.boxes.map((A,S)=>({score:E.scores[S],label:r[E.classes[S]],box:Fi(A,!o)}))}b.sort((E,A)=>A.score-E.score),n!==null&&(b=b.slice(0,n)),p.push(b)}return a?p:p[0]}};var al=class extends fe{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 il=class extends fe{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 ll=class extends fe{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,c]=i.dims.slice(-2),[p,f]=r[a].size,m=(await Wt(i.view(1,1,l,c),{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),b=Ke.fromTensor(x);o.push({predicted_depth:m,depth:b})}return Array.isArray(e)?o:o[0]}};var cl=class extends fe{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=IA(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=PA(l,o)),l}};var ul=class extends fe{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 Fn=Object.freeze({"text-classification":{tokenizer:Z,pipeline:ji,model:$i,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:Z,pipeline:Gi,model:Vu,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:Z,pipeline:qi,model:Ju,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:Z,pipeline:Wi,model:Qu,default:{model:"onnx-community/ettin-encoder-32m-ONNX",dtype:"fp32"},type:"text"},summarization:{tokenizer:Z,pipeline:Vi,model:Bn,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:Z,pipeline:Hi,model:Bn,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:Z,pipeline:Cr,model:Bn,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:Z,pipeline:Xi,model:Yu,default:{model:"onnx-community/Qwen3-0.6B-ONNX",dtype:"q4"},type:"text"},"zero-shot-classification":{tokenizer:Z,pipeline:Ki,model:$i,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:Yi,model:np,processor:pt,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:Z,pipeline:Qi,model:Ir,processor:pt,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:Z,pipeline:Ji,model:[Hu,sp],processor:pt,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:Z,pipeline:Zi,model:[Ku,Xu],processor:[pt,null],default:{model:"onnx-community/Supertonic-TTS-ONNX",dtype:"fp32"},type:"text"},"image-to-text":{tokenizer:Z,pipeline:el,model:Zu,processor:pt,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:tl,model:ep,processor:pt,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:qs,model:[Di,Ui,Bi],processor:pt,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:rl,model:[Di,Ui,Bi],processor:pt,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:Z,pipeline:sl,model:Ir,processor:pt,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:nl,model:tp,processor:pt,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:Z,pipeline:ol,model:rp,processor:pt,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:Z,pipeline:al,model:op,processor:pt,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:il,model:ap,processor:pt,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:ll,model:ip,processor:pt,default:{model:"onnx-community/depth-anything-v2-small"},type:"image"},"feature-extraction":{tokenizer:Z,pipeline:cl,model:Ir,default:{model:"onnx-community/all-MiniLM-L6-v2-ONNX",dtype:"fp32"},type:"text"},"image-feature-extraction":{processor:pt,pipeline:ul,model:[lp,Ir],default:{model:"onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX",dtype:"fp32"},type:"image"}}),cp=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function up(t,{config:e=null,dtype:r=null,device:s=null,model_file_name:n=null}={}){e=await Sr.from_pretrained(t,{config:e});let o=["config.json"],a=e["transformers.js_config"]??{},i=a.use_external_data_format,l="onnx",c=s??a.device,p=r??a.dtype,f,m=e.architectures||[],h=!1;for(let b of m){let E=mr.get(b);if(E!==void 0){f=E,h=!0;break}}if(!h&&e.model_type){let b=mr.get(e.model_type);b!==void 0&&(f=b,h=!0)}if(!h){let b=m.length>0?m.join(", "):"(none)";Q.warn(`[get_model_files] Architecture(s) not found in MODEL_TYPE_MAPPING: [${b}] for model type '${e.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${Gr}`),f=j.EncoderOnly}let w=(b,E=null)=>{E=E??b;let A=Kl(c,b),S=Yl(p,b,A),M=po[S]??"",C=`${E}${M}.onnx`,P=l?`${l}/${C}`:C;o.push(P);let k=xh(i,C,b);for(let F of yh(C,k)){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 pp(t){if(!t)throw new Error("modelId is required");return(await ur(t,Mr,{})).exists?[Mr]:[]}async function is(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 up(t,{config:e,dtype:r,device:s,model_file_name:n});if(o){let l=await ln(t);i.push(...l)}if(a){let l=await pp(t);i.push(...l)}return i}function QL(t){let e=Fn[t];return e?{tokenizer:!!e.tokenizer,processor:!!e.processor}:null}async function ls(t,e,r={}){t=cp[t]??t;let s=QL(t);if(!s)throw new Error(`Unsupported pipeline task: ${t}. Must be one of [${Object.keys(Fn).join(", ")}]`);return is(e,{...r,include_tokenizer:s.tokenizer,include_processor:s.processor})}async function ane(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:c="onnx",use_external_data_format:p=null,model_file_name:f=null,session_options:m={}}={}){t=cp[t]??t;let h=Fn[t.split("_",1)[0]];if(!h)throw Error(`Unsupported pipeline: ${t}. Must be one of [${Object.keys(Fn)}]`);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 ls(t,e,{device:i,dtype:l});(await Promise.all(S.map(async C=>ur(e,C)))).forEach((C,P)=>{C.exists&&(w[S[P]]={loaded:0,total:C.size??0})})}let x={progress_callback:r?S=>{if(S.status==="progress"){w[S.file]={loaded:S.loaded,total:S.total};let M=Object.values(w).reduce((k,F)=>k+F.loaded,0),C=Object.values(w).reduce((k,F)=>k+F.total,0),P=C>0?M/C*100:0;r({status:"progress_total",name:S.name,progress:P,loaded:M,total:C,files:structuredClone(w)})}r(S)}:void 0,config:s,cache_dir:n,local_files_only:o,revision:a,device:i,dtype:l,subfolder:c,use_external_data_format:p,model_file_name:f,session_options:m},b=new Map([["tokenizer",h.tokenizer],["model",h.model],["processor",h.processor]]),E=await JL(b,e,x);E.task=t,Er(r,{status:"ready",task:t,model:e});let A=h.pipeline;return new A(E)}async function JL(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,c)=>{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{c(m);return}}}c(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 ZL=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,vb=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},G2=ge.IS_PROCESS_AVAILABLE?t=>process.stdout.write(t):t=>console.log(t),kb=class extends vb{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??G2,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(`
26
- `)?(o=n.slice(this.print_len),this.token_cache=[],this.print_len=0):n.length>0&&ZL(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===G2&&ge.IS_PROCESS_AVAILABLE&&this.callback_function?.(`
27
- `)}},q2=class extends kb{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:c=!0,decode_kwargs:p={}}={}){super(e,{skip_prompt:r,skip_special_tokens:c,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 pl=class{constructor(e,r){this.image=e,this.timestamp=r}},fp=class{constructor(e,r){e.length>0&&e[0]instanceof Ke&&(e=e.map((s,n)=>new pl(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 eN(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 de.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 c=document.createElement("canvas");c.width=n.videoWidth,c.height=n.videoHeight;let p=c.getContext("2d",{willReadFrequently:!0});for(let f of l){n.currentTime=f,await new Promise(x=>{n.onseeked=x}),p.drawImage(n,0,0,c.width,c.height);let m=p.getImageData(0,0,c.width,c.height),h=new Ke(m.data,c.width,c.height,4),w=new pl(h,f);s.push(w)}return n.remove(),new fp(s,o)}async function W2(t,e,r={}){let s=await cr(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}=ws(t,o,r,s),l=await xs(s,a,i);return{file:o,cached:!!l}}));return{allCached:n.every(o=>o.cached),files:n}}async function V2(t,e={}){if(!t)throw new Error("modelId is required");let r=await is(t,e);return await W2(t,r,e)}async function H2(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await ls(t,e,r);return await W2(e,s,r)}async function X2(t,e,r={}){let s=await cr(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}=ws(t,o,r,s),c=!!await xs(s,a,i),p=!1;if(c){let f=await s.delete(i),m=!f&&i!==a?await s.delete(a):!1;p=f||m}return{file:o,deleted:p,wasCached:c}}));return{filesDeleted:n.filter(o=>o.deleted).length,filesCached:n.filter(o=>o.wasCached).length,files:n}}async function K2(t,e={}){if(!t)throw new Error("modelId is required");let r=await is(t,e);return await X2(t,r,e)}async function Y2(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await ls(t,e,r);return await X2(e,s,r)}var Eb=class{static async get_files(e,r={}){return is(e,r)}static async get_pipeline_files(e,r,s={}){return ls(e,r,s)}static async get_model_files(e,r={}){return up(e,r)}static async get_tokenizer_files(e){return ln(e)}static async get_processor_files(e){return pp(e)}static async is_cached(e,r={}){return V2(e,r)}static async is_pipeline_cached(e,r,s={}){return H2(e,r,s)}static async get_file_metadata(e,r,s={}){return ur(e,r,s)}static async clear_cache(e,r={}){return K2(e,r)}static async clear_pipeline_cache(e,r,s={}){return Y2(e,r,s)}};export{Yd as ASTFeatureExtractor,Dh as ASTForAudioClassification,$h as ASTModel,No as ASTPreTrainedModel,Nh as AfmoeForCausalLM,Lh as AfmoeModel,Po as AfmoePreTrainedModel,Ih as AlbertForMaskedLM,Oh as AlbertForQuestionAnswering,Sh as AlbertForSequenceClassification,Mh as AlbertModel,$s as AlbertPreTrainedModel,sd as AlbertTokenizer,Ph as ApertusForCausalLM,Ch as ApertusModel,Co as ApertusPreTrainedModel,Rh as ArceeForCausalLM,zh as ArceeModel,Lo as ArceePreTrainedModel,Yi as AudioClassificationPipeline,Sr as AutoConfig,rt as AutoFeatureExtractor,De as AutoImageProcessor,Ir as AutoModel,np as AutoModelForAudioClassification,z2 as AutoModelForAudioFrameClassification,B2 as AutoModelForAudioTextToText,sp as AutoModelForCTC,Yu as AutoModelForCausalLM,ip as AutoModelForDepthEstimation,op as AutoModelForDocumentQuestionAnswering,ep as AutoModelForImageClassification,lp as AutoModelForImageFeatureExtraction,R2 as AutoModelForImageMatting,Di as AutoModelForImageSegmentation,U2 as AutoModelForImageTextToText,ap as AutoModelForImageToImage,L2 as AutoModelForMaskGeneration,Qu as AutoModelForMaskedLM,$2 as AutoModelForNormalEstimation,tp as AutoModelForObjectDetection,D2 as AutoModelForPoseEstimation,Ju as AutoModelForQuestionAnswering,Ui as AutoModelForSemanticSegmentation,Bn as AutoModelForSeq2SeqLM,$i as AutoModelForSequenceClassification,Hu as AutoModelForSpeechSeq2Seq,Xu as AutoModelForTextToSpectrogram,Ku as AutoModelForTextToWaveform,Vu as AutoModelForTokenClassification,Bi as AutoModelForUniversalSegmentation,Zu as AutoModelForVision2Seq,N2 as AutoModelForXVector,rp as AutoModelForZeroShotObjectDetection,pt as AutoProcessor,Z as AutoTokenizer,Ji as AutomaticSpeechRecognitionPipeline,rl as BackgroundRemovalPipeline,Bh as BartForConditionalGeneration,Fh as BartForSequenceClassification,Uh as BartModel,yn as BartPretrainedModel,nd as BartTokenizer,vb as BaseStreamer,pm as BeitFeatureExtractor,Gh as BeitForImageClassification,jh as BeitModel,zo as BeitPreTrainedModel,Wh as BertForMaskedLM,Xh as BertForQuestionAnswering,Vh as BertForSequenceClassification,Hh as BertForTokenClassification,qh as BertModel,Vr as BertPreTrainedModel,od as BertTokenizer,fm as BitImageProcessor,Yh as BlenderbotForConditionalGeneration,Kh as BlenderbotModel,Ro as BlenderbotPreTrainedModel,Jh as BlenderbotSmallForConditionalGeneration,Qh as BlenderbotSmallModel,$o as BlenderbotSmallPreTrainedModel,ad as BlenderbotSmallTokenizer,id as BlenderbotTokenizer,e_ as BloomForCausalLM,Zh as BloomModel,Do as BloomPreTrainedModel,ld as BloomTokenizer,mm as CLIPFeatureExtractor,lc as CLIPImageProcessor,l_ as CLIPModel,_r as CLIPPreTrainedModel,d_ as CLIPSegForImageSegmentation,f_ as CLIPSegModel,Go as CLIPSegPreTrainedModel,c_ as CLIPTextModel,jo as CLIPTextModelWithProjection,ud as CLIPTokenizer,u_ as CLIPVisionModel,p_ as CLIPVisionModelWithProjection,r_ as CamembertForMaskedLM,o_ as CamembertForQuestionAnswering,s_ as CamembertForSequenceClassification,n_ as CamembertForTokenClassification,t_ as CamembertModel,Hr as CamembertPreTrainedModel,cd as CamembertTokenizer,Qd as ChatterboxFeatureExtractor,Uo as ChatterboxModel,Hc as ChatterboxPreTrainedModel,lm as ChatterboxProcessor,dm as ChineseCLIPFeatureExtractor,a_ as ChineseCLIPModel,Xc as ChineseCLIPPreTrainedModel,Fo as ClapAudioModelWithProjection,Jd as ClapFeatureExtractor,i_ as ClapModel,bn as ClapPreTrainedModel,Bo as ClapTextModelWithProjection,Dc as ClassifierFreeGuidanceLogitsProcessor,h_ as CodeGenForCausalLM,m_ as CodeGenModel,qo as CodeGenPreTrainedModel,fd as CodeGenTokenizer,pd as CodeLlamaTokenizer,x_ as Cohere2ForCausalLM,w_ as Cohere2Model,Vo as Cohere2PreTrainedModel,g_ as CohereForCausalLM,__ as CohereModel,Wo as CoherePreTrainedModel,dd as CohereTokenizer,b_ as ConvBertForMaskedLM,E_ as ConvBertForQuestionAnswering,v_ as ConvBertForSequenceClassification,k_ as ConvBertForTokenClassification,y_ as ConvBertModel,Xr as ConvBertPreTrainedModel,md as ConvBertTokenizer,hm as ConvNextFeatureExtractor,T_ as ConvNextForImageClassification,cc as ConvNextImageProcessor,A_ as ConvNextModel,Ho as ConvNextPreTrainedModel,S_ as ConvNextV2ForImageClassification,M_ as ConvNextV2Model,Xo as ConvNextV2PreTrainedModel,P_ as DFineForObjectDetection,C_ as DFineModel,Yo as DFinePreTrainedModel,rg as DINOv3ConvNextModel,tu as DINOv3ConvNextPreTrainedModel,wm as DINOv3ViTImageProcessor,sg as DINOv3ViTModel,ru as DINOv3ViTPreTrainedModel,ym as DPTFeatureExtractor,pg as DPTForDepthEstimation,fc as DPTImageProcessor,ug as DPTModel,ra as DPTPreTrainedModel,Jo as DacDecoderModel,Yc as DacDecoderOutput,Qo as DacEncoderModel,Kc as DacEncoderOutput,yo as DacFeatureExtractor,L_ as DacModel,vn as DacPreTrainedModel,z_ as DebertaForMaskedLM,D_ as DebertaForQuestionAnswering,R_ as DebertaForSequenceClassification,$_ as DebertaForTokenClassification,N_ as DebertaModel,Kr as DebertaPreTrainedModel,_d as DebertaTokenizer,B_ as DebertaV2ForMaskedLM,G_ as DebertaV2ForQuestionAnswering,F_ as DebertaV2ForSequenceClassification,j_ as DebertaV2ForTokenClassification,U_ as DebertaV2Model,Yr as DebertaV2PreTrainedModel,hd as DebertaV2Tokenizer,q_ as DecisionTransformerModel,Qc as DecisionTransformerPreTrainedModel,_m as DeiTFeatureExtractor,V_ as DeiTForImageClassification,uc as DeiTImageProcessor,W_ as DeiTModel,Zo as DeiTPreTrainedModel,H_ as DepthAnythingForDepthEstimation,Jc as DepthAnythingPreTrainedModel,ll as DepthEstimationPipeline,X_ as DepthProForDepthEstimation,Zc as DepthProPreTrainedModel,gm as DetrFeatureExtractor,Y_ as DetrForObjectDetection,Q_ as DetrForSegmentation,pc as DetrImageProcessor,K_ as DetrModel,En as DetrObjectDetectionOutput,kn as DetrPreTrainedModel,eu as DetrSegmentationOutput,Z_ as Dinov2ForImageClassification,J_ as Dinov2Model,ea as Dinov2PreTrainedModel,tg as Dinov2WithRegistersForImageClassification,eg as Dinov2WithRegistersModel,ta as Dinov2WithRegistersPreTrainedModel,lg as DistilBertForMaskedLM,ig as DistilBertForQuestionAnswering,og as DistilBertForSequenceClassification,ag as DistilBertForTokenClassification,ng as DistilBertModel,Qr as DistilBertPreTrainedModel,gd as DistilBertTokenizer,al as DocumentQuestionAnsweringPipeline,xm as DonutFeatureExtractor,un as DonutImageProcessor,cg as DonutSwinModel,su as DonutSwinPreTrainedModel,Xy as EdgeTamModel,dg as EfficientNetForImageClassification,bm as EfficientNetImageProcessor,fg as EfficientNetModel,sa as EfficientNetPreTrainedModel,hg as ElectraForMaskedLM,wg as ElectraForQuestionAnswering,_g as ElectraForSequenceClassification,gg as ElectraForTokenClassification,mg as ElectraModel,Jr as ElectraPreTrainedModel,wd as ElectraTokenizer,xo as EncodecFeatureExtractor,jc as EosTokenCriteria,yg as Ernie4_5ForCausalLM,xg as Ernie4_5Model,na as Ernie4_5PretrainedModel,vg as EsmForMaskedLM,kg as EsmForSequenceClassification,Eg as EsmForTokenClassification,bg as EsmModel,Ds as EsmPreTrainedModel,xd as EsmTokenizer,Tg as ExaoneForCausalLM,Ag as ExaoneModel,oa as ExaonePreTrainedModel,Sg as FalconForCausalLM,Ig as FalconH1ForCausalLM,Og as FalconH1Model,ia as FalconH1PreTrainedModel,Mg as FalconModel,aa as FalconPreTrainedModel,yd as FalconTokenizer,Pg as FastViTForImageClassification,Cg as FastViTModel,la as FastViTPreTrainedModel,cl as FeatureExtractionPipeline,$e as FeatureExtractor,Wi as FillMaskPipeline,Lg as Florence2ForConditionalGeneration,nu as Florence2PreTrainedModel,Jm as Florence2Processor,Ic as ForcedBOSTokenLogitsProcessor,Cc as ForcedEOSTokenLogitsProcessor,vm as GLPNFeatureExtractor,Gg as GLPNForDepthEstimation,jg as GLPNModel,ma as GLPNPreTrainedModel,Zg as GPT2LMHeadModel,Jg as GPT2Model,xa as GPT2PreTrainedModel,kd as GPT2Tokenizer,Wg as GPTBigCodeForCausalLM,qg as GPTBigCodeModel,ha as GPTBigCodePreTrainedModel,tw as GPTJForCausalLM,ew as GPTJModel,ya as GPTJPreTrainedModel,Hg as GPTNeoForCausalLM,Vg as GPTNeoModel,_a as GPTNeoPreTrainedModel,Kg as GPTNeoXForCausalLM,Xg as GPTNeoXModel,ga as GPTNeoXPreTrainedModel,vd as GPTNeoXTokenizer,$g as Gemma2ForCausalLM,Rg as Gemma2Model,ua as Gemma2PreTrainedModel,Ug as Gemma3ForCausalLM,Dg as Gemma3Model,pa as Gemma3PreTrainedModel,Zd as Gemma3nAudioFeatureExtractor,fa as Gemma3nForConditionalGeneration,ou as Gemma3nPreTrainedModel,Zm as Gemma3nProcessor,zg as GemmaForCausalLM,Ng as GemmaModel,ca as GemmaPreTrainedModel,bd as GemmaTokenizer,Fg as GlmForCausalLM,Bg as GlmModel,da as GlmPreTrainedModel,Qg as GptOssForCausalLM,Yg as GptOssModel,wa as GptOssPreTrainedModel,sw as GraniteForCausalLM,rw as GraniteModel,ow as GraniteMoeHybridForCausalLM,nw as GraniteMoeHybridModel,va as GraniteMoeHybridPreTrainedModel,ba as GranitePreTrainedModel,aw as GroundingDinoForObjectDetection,km as GroundingDinoImageProcessor,au as GroundingDinoPreTrainedModel,eh as GroundingDinoProcessor,iw as GroupViTModel,iu as GroupViTPreTrainedModel,cw as HeliumForCausalLM,lw as HeliumModel,ka as HeliumPreTrainedModel,Ed as HerbertTokenizer,pw as HieraForImageClassification,uw as HieraModel,Ea as HieraPreTrainedModel,ww as HubertForCTC,xw as HubertForSequenceClassification,gw as HubertModel,_w as HubertPreTrainedModel,bw as HunYuanDenseV1ForCausalLM,yw as HunYuanDenseV1Model,Aa as HunYuanDenseV1PreTrainedModel,Ew as IJepaForImageClassification,kw as IJepaModel,Ta as IJepaPreTrainedModel,cu as Idefics3ForConditionalGeneration,dc as Idefics3ImageProcessor,lu as Idefics3PreTrainedModel,kc as Idefics3Processor,tl as ImageClassificationPipeline,ul as ImageFeatureExtractionPipeline,W as ImageFeatureExtractor,W as ImageProcessor,qs as ImageSegmentationPipeline,il as ImageToImagePipeline,el as ImageToTextPipeline,ZA as InterruptableStoppingCriteria,Tw as JAISLMHeadModel,Aw as JAISModel,Ma as JAISPreTrainedModel,Am as JinaCLIPImageProcessor,Mw as JinaCLIPModel,An as JinaCLIPPreTrainedModel,rh as JinaCLIPProcessor,Sa as JinaCLIPTextModel,Sw as JinaCLIPVisionModel,Iw as Lfm2ForCausalLM,Ow as Lfm2Model,Pw as Lfm2MoeForCausalLM,Cw as Lfm2MoeModel,Ia as Lfm2MoePreTrainedModel,Oa as Lfm2PreTrainedModel,ob as LiteWhisperForConditionalGeneration,zw as Llama4ForCausalLM,uu as Llama4PreTrainedModel,Nw as LlamaForCausalLM,Lw as LlamaModel,Ca as LlamaPreTrainedModel,Ad as LlamaTokenizer,Tn as LlavaForConditionalGeneration,Tn as LlavaOnevisionForConditionalGeneration,Tm as LlavaOnevisionImageProcessor,pu as LlavaPreTrainedModel,sh as LlavaProcessor,$w as LlavaQwen2ForCausalLM,It as LogLevel,Ht as LogitsProcessor,Ns as LogitsProcessorList,Mo as LogitsWarper,Uw as LongT5ForConditionalGeneration,Dw as LongT5Model,Pa as LongT5PreTrainedModel,Fw as M2M100ForConditionalGeneration,Bw as M2M100Model,La as M2M100PreTrainedModel,Td as M2M100Tokenizer,Sd as MBart50Tokenizer,Kw as MBartForCausalLM,Hw as MBartForConditionalGeneration,Xw as MBartForSequenceClassification,Vw as MBartModel,Us as MBartPreTrainedModel,ho as MBartTokenizer,Lx as MPNetForMaskedLM,Rx as MPNetForQuestionAnswering,Nx as MPNetForSequenceClassification,zx as MPNetForTokenClassification,Px as MPNetModel,Zr as MPNetPreTrainedModel,Cd as MPNetTokenizer,Bx as MT5ForConditionalGeneration,Ux as MT5Model,Wa as MT5PreTrainedModel,Gw as MarianMTModel,jw as MarianModel,Na as MarianPreTrainedModel,Md as MarianTokenizer,Sm as Mask2FormerImageProcessor,Mm as MaskFormerFeatureExtractor,Ww as MaskFormerForInstanceSegmentation,pn as MaskFormerImageProcessor,qw as MaskFormerModel,za as MaskFormerPreTrainedModel,Fc as MaxLengthCriteria,Yw as Metric3DForDepthEstimation,fu as Metric3DPreTrainedModel,Qw as Metric3Dv2ForDepthEstimation,du as Metric3Dv2PreTrainedModel,Jw as MgpstrForSceneTextRecognition,mu as MgpstrModelOutput,hu as MgpstrPreTrainedModel,nh as MgpstrProcessor,Od as MgpstrTokenizer,$a as MimiDecoderModel,gu as MimiDecoderOutput,Ra as MimiEncoderModel,_u as MimiEncoderOutput,Zw as MimiModel,Mn as MimiPreTrainedModel,zc as MinLengthLogitsProcessor,Rc as MinNewTokensLengthLogitsProcessor,tx as MistralForCausalLM,ex as MistralModel,Da as MistralPreTrainedModel,sx as MobileBertForMaskedLM,ox as MobileBertForQuestionAnswering,nx as MobileBertForSequenceClassification,rx as MobileBertModel,Bs as MobileBertPreTrainedModel,Id as MobileBertTokenizer,ix as MobileLLMForCausalLM,ax as MobileLLMModel,Ua as MobileLLMPreTrainedModel,Om as MobileNetV1FeatureExtractor,cx as MobileNetV1ForImageClassification,ux as MobileNetV1ForSemanticSegmentation,mc as MobileNetV1ImageProcessor,lx as MobileNetV1Model,Sn as MobileNetV1PreTrainedModel,Im as MobileNetV2FeatureExtractor,fx as MobileNetV2ForImageClassification,dx as MobileNetV2ForSemanticSegmentation,hc as MobileNetV2ImageProcessor,px as MobileNetV2Model,On as MobileNetV2PreTrainedModel,Cm as MobileNetV3FeatureExtractor,hx as MobileNetV3ForImageClassification,_x as MobileNetV3ForSemanticSegmentation,_c as MobileNetV3ImageProcessor,mx as MobileNetV3Model,In as MobileNetV3PreTrainedModel,Pm as MobileNetV4FeatureExtractor,wx as MobileNetV4ForImageClassification,xx as MobileNetV4ForSemanticSegmentation,gc as MobileNetV4ImageProcessor,gx as MobileNetV4Model,Cn as MobileNetV4PreTrainedModel,Lm as MobileViTFeatureExtractor,bx as MobileViTForImageClassification,wc as MobileViTImageProcessor,yx as MobileViTModel,Ba as MobileViTPreTrainedModel,kx as MobileViTV2ForImageClassification,vx as MobileViTV2Model,Fa as MobileViTV2PreTrainedModel,Eb as ModelRegistry,Ox as ModernBertDecoderForCausalLM,Sx as ModernBertDecoderModel,ja as ModernBertDecoderPreTrainedModel,Ax as ModernBertForMaskedLM,Tx as ModernBertForSequenceClassification,Mx as ModernBertForTokenClassification,Ex as ModernBertModel,Fs as ModernBertPreTrainedModel,Rw as Moondream1ForConditionalGeneration,em as MoonshineFeatureExtractor,Cx as MoonshineForConditionalGeneration,Ix as MoonshineModel,Ga as MoonshinePreTrainedModel,oh as MoonshineProcessor,Dx as MptForCausalLM,$x as MptModel,qa as MptPreTrainedModel,Fx as MultiModalityCausalLM,wu as MultiModalityPreTrainedModel,Gx as MusicgenForCausalLM,Ha as MusicgenForConditionalGeneration,jx as MusicgenModel,Va as MusicgenPreTrainedModel,Wx as NanoChatForCausalLM,qx as NanoChatModel,Xa as NanoChatPreTrainedModel,Hx as NeoBertForMaskedLM,Yx as NeoBertForQuestionAnswering,Xx as NeoBertForSequenceClassification,Kx as NeoBertForTokenClassification,Vx as NeoBertModel,es as NeoBertPreTrainedModel,Pd as NllbTokenizer,$c as NoBadWordsLogitsProcessor,Lc as NoRepeatNGramLogitsProcessor,Qx as NomicBertModel,xu as NomicBertPreTrainedModel,Nm as NougatImageProcessor,Ld as NougatTokenizer,iy as OPTForCausalLM,ay as OPTModel,Za as OPTPreTrainedModel,nl as ObjectDetectionPipeline,ty as Olmo2ForCausalLM,ey as Olmo2Model,Ya as Olmo2PreTrainedModel,sy as Olmo3ForCausalLM,ry as Olmo3Model,Qa as Olmo3PreTrainedModel,Zx as OlmoForCausalLM,Jx as OlmoModel,Ka as OlmoPreTrainedModel,oy as OpenELMForCausalLM,ny as OpenELMModel,Ja as OpenELMPreTrainedModel,zm as OwlViTFeatureExtractor,py as OwlViTForObjectDetection,fn as OwlViTImageProcessor,uy as OwlViTModel,ti as OwlViTPreTrainedModel,ah as OwlViTProcessor,cy as Owlv2ForObjectDetection,Rm as Owlv2ImageProcessor,ly as Owlv2Model,ei as Owlv2PreTrainedModel,fy as PaliGemmaForConditionalGeneration,yu as PaliGemmaPreTrainedModel,ih as PaliGemmaProcessor,tm as ParakeetFeatureExtractor,dy as ParakeetForCTC,bu as ParakeetPreTrainedModel,hy as PatchTSMixerForPrediction,my as PatchTSMixerModel,ri as PatchTSMixerPreTrainedModel,gy as PatchTSTForPrediction,_y as PatchTSTModel,si as PatchTSTPreTrainedModel,by as Phi3ForCausalLM,yy as Phi3Model,oi as Phi3PreTrainedModel,ai as Phi3VForCausalLM,Um as Phi3VImageProcessor,vu as Phi3VPreTrainedModel,lh as Phi3VProcessor,xy as PhiForCausalLM,wy as PhiModel,ni as PhiPreTrainedModel,Bm as PixtralImageProcessor,ch as PixtralProcessor,y as PreTrainedModel,q as PreTrainedTokenizer,Mc as PretrainedConfig,oe as Processor,ky as PvtForImageClassification,Fm as PvtImageProcessor,vy as PvtModel,ii as PvtPreTrainedModel,bo as PyAnnoteFeatureExtractor,Ay as PyAnnoteForAudioFrameClassification,Ey as PyAnnoteModel,li as PyAnnotePreTrainedModel,uh as PyAnnoteProcessor,qi as QuestionAnsweringPipeline,My as Qwen2ForCausalLM,Ty as Qwen2Model,ci as Qwen2PreTrainedModel,Nd as Qwen2Tokenizer,ui as Qwen2VLForConditionalGeneration,jm as Qwen2VLImageProcessor,ku as Qwen2VLPreTrainedModel,Eo as Qwen2VLProcessor,pi as Qwen2_5_VLForConditionalGeneration,Ao as Qwen2_5_VLProcessor,Oy as Qwen3ForCausalLM,Sy as Qwen3Model,fi as Qwen3PreTrainedModel,di as Qwen3VLForConditionalGeneration,ph as Qwen3VLProcessor,mi as Qwen3_5ForConditionalGeneration,Iy as Qwen3_5MoeForConditionalGeneration,Ny as RFDetrForObjectDetection,Ly as RFDetrModel,Eu as RFDetrObjectDetectionOutput,_i as RFDetrPreTrainedModel,I_ as RTDetrForObjectDetection,Gm as RTDetrImageProcessor,O_ as RTDetrModel,gr as RTDetrObjectDetectionOutput,Ko as RTDetrPreTrainedModel,Vy as RTDetrV2ForObjectDetection,Wy as RTDetrV2Model,Au as RTDetrV2ObjectDetectionOutput,gi as RTDetrV2PreTrainedModel,wo as RawAudio,Ke as RawImage,fp as RawVideo,pl as RawVideoFrame,Nc as RepetitionPenaltyLogitsProcessor,Py as ResNetForImageClassification,Cy as ResNetModel,hi as ResNetPreTrainedModel,Fy as RoFormerForMaskedLM,qy as RoFormerForQuestionAnswering,jy as RoFormerForSequenceClassification,Gy as RoFormerForTokenClassification,By as RoFormerModel,rs as RoFormerPreTrainedModel,Rd as RoFormerTokenizer,Ry as RobertaForMaskedLM,Uy as RobertaForQuestionAnswering,$y as RobertaForSequenceClassification,Dy as RobertaForTokenClassification,zy as RobertaModel,ts as RobertaPreTrainedModel,zd as RobertaTokenizer,ko as Sam2ImageProcessor,Su as Sam2ImageSegmentationOutput,wi as Sam2Model,Ou as Sam2PreTrainedModel,Ec as Sam2Processor,fh as Sam2VideoProcessor,ko as Sam3ImageProcessor,Ky as Sam3TrackerModel,ko as SamImageProcessor,Tu as SamImageSegmentationOutput,Hy as SamModel,Mu as SamPreTrainedModel,To as SamProcessor,qm as SapiensFeatureExtractor,Qy as SapiensForDepthEstimation,Jy as SapiensForNormalEstimation,Yy as SapiensForSemanticSegmentation,xc as SapiensImageProcessor,Pn as SapiensPreTrainedModel,rm as SeamlessM4TFeatureExtractor,Wm as SegformerFeatureExtractor,e0 as SegformerForImageClassification,t0 as SegformerForSemanticSegmentation,yc as SegformerImageProcessor,Zy as SegformerModel,Ln as SegformerPreTrainedModel,Vm as SiglipImageProcessor,r0 as SiglipModel,xi as SiglipPreTrainedModel,yi as SiglipTextModel,$d as SiglipTokenizer,s0 as SiglipVisionModel,o0 as SmolLM3ForCausalLM,n0 as SmolLM3Model,bi as SmolLM3PreTrainedModel,vw as SmolVLMForConditionalGeneration,dc as SmolVLMImageProcessor,kc as SmolVLMProcessor,ki as SnacDecoderModel,vi as SnacEncoderModel,sm as SnacFeatureExtractor,a0 as SnacModel,Nn as SnacPreTrainedModel,nm as SpeechT5FeatureExtractor,l0 as SpeechT5ForSpeechToText,c0 as SpeechT5ForTextToSpeech,u0 as SpeechT5HifiGan,i0 as SpeechT5Model,zn as SpeechT5PreTrainedModel,dh as SpeechT5Processor,Dd as SpeechT5Tokenizer,f0 as SqueezeBertForMaskedLM,m0 as SqueezeBertForQuestionAnswering,d0 as SqueezeBertForSequenceClassification,p0 as SqueezeBertModel,js as SqueezeBertPreTrainedModel,Ud as SqueezeBertTokenizer,_0 as StableLmForCausalLM,h0 as StableLmModel,Ei as StableLmPreTrainedModel,w0 as Starcoder2ForCausalLM,g0 as Starcoder2Model,Ai as Starcoder2PreTrainedModel,xn as StoppingCriteria,Bc as StoppingCriteriaList,x0 as StyleTextToSpeech2Model,Iu as StyleTextToSpeech2PreTrainedModel,Vi as SummarizationPipeline,Ti as SupertonicForConditionalGeneration,Cu as SupertonicPreTrainedModel,gn as SuppressTokensAtBeginLogitsProcessor,E0 as Swin2SRForImageSuperResolution,Hm as Swin2SRImageProcessor,k0 as Swin2SRModel,Mi as Swin2SRPreTrainedModel,b0 as SwinForImageClassification,v0 as SwinForSemanticSegmentation,y0 as SwinModel,Rn as SwinPreTrainedModel,T0 as T5ForConditionalGeneration,A0 as T5Model,Si as T5PreTrainedModel,Bd as T5Tokenizer,S0 as TableTransformerForObjectDetection,M0 as TableTransformerModel,Pu as TableTransformerObjectDetectionOutput,Oi as TableTransformerPreTrainedModel,Uc as TemperatureLogitsWarper,D as Tensor,Cr as Text2TextGenerationPipeline,ji as TextClassificationPipeline,Xi as TextGenerationPipeline,kb as TextStreamer,Zi as TextToAudioPipeline,Gi as TokenClassificationPipeline,q as TokenizersBackend,JA as TopKLogitsWarper,QA as TopPLogitsWarper,O0 as TrOCRForCausalLM,Lu as TrOCRPreTrainedModel,Hi as TranslationPipeline,zu as UltravoxModel,Nu as UltravoxPreTrainedModel,mh as UltravoxProcessor,P0 as UniSpeechForCTC,L0 as UniSpeechForSequenceClassification,C0 as UniSpeechModel,$n as UniSpeechPreTrainedModel,$0 as UniSpeechSatForAudioFrameClassification,z0 as UniSpeechSatForCTC,R0 as UniSpeechSatForSequenceClassification,N0 as UniSpeechSatModel,Gs as UniSpeechSatPreTrainedModel,th as VLChatProcessor,Em as VLMImageProcessor,U0 as VaultGemmaForCausalLM,D0 as VaultGemmaModel,Ii as VaultGemmaPreTrainedModel,Xm as ViTFeatureExtractor,j0 as ViTForImageClassification,bc as ViTImageProcessor,G0 as ViTMAEModel,Ru as ViTMAEPreTrainedModel,W0 as ViTMSNForImageClassification,q0 as ViTMSNModel,Pi as ViTMSNPreTrainedModel,F0 as ViTModel,Ci as ViTPreTrainedModel,B0 as VisionEncoderDecoderModel,V0 as VitMatteForImageMatting,Km as VitMatteImageProcessor,$u as VitMattePreTrainedModel,H0 as VitPoseForPoseEstimation,Ym as VitPoseImageProcessor,Du as VitPosePreTrainedModel,X0 as VitsModel,Uu as VitsModelOutput,Bu as VitsPreTrainedModel,jd as VitsTokenizer,I0 as VoxtralForConditionalGeneration,hh as VoxtralProcessor,Y0 as Wav2Vec2BertForCTC,Q0 as Wav2Vec2BertForSequenceClassification,K0 as Wav2Vec2BertModel,Dn as Wav2Vec2BertPreTrainedModel,Gd as Wav2Vec2CTCTokenizer,om as Wav2Vec2FeatureExtractor,hw as Wav2Vec2ForAudioFrameClassification,dw as Wav2Vec2ForCTC,mw as Wav2Vec2ForSequenceClassification,fw as Wav2Vec2Model,nr as Wav2Vec2PreTrainedModel,_h as Wav2Vec2Processor,gh as Wav2Vec2ProcessorWithLM,rb as WavLMForAudioFrameClassification,Z0 as WavLMForCTC,eb as WavLMForSequenceClassification,tb as WavLMForXVector,J0 as WavLMModel,ss as WavLMPreTrainedModel,am as WeSpeakerFeatureExtractor,sb as WeSpeakerResNetModel,ju as WeSpeakerResNetPreTrainedModel,im as WhisperFeatureExtractor,qu as WhisperForConditionalGeneration,nb as WhisperModel,Li as WhisperPreTrainedModel,wh as WhisperProcessor,q2 as WhisperTextStreamer,Pc as WhisperTimeStampLogitsProcessor,qd as WhisperTokenizer,ub as XLMForQuestionAnswering,lb as XLMForSequenceClassification,cb as XLMForTokenClassification,ab as XLMModel,ns as XLMPreTrainedModel,fb as XLMRobertaForMaskedLM,hb as XLMRobertaForQuestionAnswering,db as XLMRobertaForSequenceClassification,mb as XLMRobertaForTokenClassification,pb as XLMRobertaModel,os as XLMRobertaPreTrainedModel,Wd as XLMRobertaTokenizer,Vd as XLMTokenizer,ib as XLMWithLMHeadModel,Fu as XVectorOutput,Qm as YolosFeatureExtractor,gb as YolosForObjectDetection,vc as YolosImageProcessor,_b as YolosModel,Wu as YolosObjectDetectionOutput,Ni as YolosPreTrainedModel,xb as YoutuForCausalLM,wb as YoutuModel,zi as YoutuPreTrainedModel,Qi as ZeroShotAudioClassificationPipeline,Ki as ZeroShotClassificationPipeline,sl as ZeroShotImageClassificationPipeline,ol as ZeroShotObjectDetectionPipeline,Ee as cat,_P as cos_sim,Tk as dot,de as env,He as full,mo as full_like,Yf as interpolate,Wt as interpolate_4d,m$ as layer_norm,xL as load_image,eN as load_video,Yp as log_softmax,OA as matmul,ec as mean,IA as mean_pooling,at as ones,tc as ones_like,JP as permute,ane as pipeline,PA as quantize_embeddings,h$ as rand,CA as randn,Cs as random,Kd as read_audio,d$ as rfft,Zl as slice,Ne as softmax,Vt as stack,Qf as std_mean,rr as topk,Zf as zeros,ed as zeros_like};
23
+ ${s}${o}`+n.repeat(t)+`${s}`,a}function ON(t,e,r,s){return`${e}${s}`+r.repeat(t)+`${e}`}function IN(t,e,r,s,n,o){return t===0&&e===0?ON(r,s,n,o):SN(r,t,e,s,n,o)}var jc=class extends re{static image_processor_class=Le;static tokenizer_class=oe;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=[],c=[];for(let f=0;f<e.length;++f){let m=e[f],h=o[f],w=a[f];l.push(Ak(m,this.image_token));let x=h.map((A,S)=>IN(A,w[S],i,this.fake_image_token,this.image_token,this.global_img_token)),v=m.split(this.image_token);if(v.length===0)throw new Error("The image token should be present in the text.");let E=v[0];for(let A=0;A<x.length;++A)E+=x[A]+v[A+1];c.push(E)}return{...this.tokenizer(c),...n}}};var Ah=class extends re{static image_processor_class=Le;static tokenizer_class=oe;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(v=>v.images).flatMap(v=>v.images).map(v=>Qe.read(v)));let n=this.tokenizer,o=n.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:s}),a=v=>n.encode(v,{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[c,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 v=1;v<i.length;++v){let E=new Array(this.num_image_tokens).fill(c),A=a(i[v]);m=xt(m,[p],E,[f],A);let S=new Array(this.num_image_tokens).fill(!0);h=xt(h,[!1],S,[!1],new Array(A.length).fill(!1))}let w=[1,m.length],x={input_ids:new R("int64",m,w),attention_mask:new R("int64",new Array(m.length).fill(1),w),images_seq_mask:new R("bool",h,w),images_emb_mask:new R("bool",new Array(l*this.num_image_tokens).fill(!0),[1,l,this.num_image_tokens])};if(r&&r.length>0){let v=await this.image_processor(r);return v.pixel_values.unsqueeze_(0),{...x,...v}}return x}};var Th=class extends re{static tokenizer_class=oe;static image_processor_class=Le;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 Mh=class extends re{static tokenizer_class=oe;static image_processor_class=Le;async _call(e,r=null,s={}){let{image_rows:n,image_cols:o,image_sizes:a,...i}=await this.image_processor(e,{...s,return_row_col_info:!0});if(r){let l=this.config.image_token??"<image>",{tile_size:c=512,downsample_factor:p=2,encoder_patch_size:f=16,use_thumbnail:m=!0}=this.image_processor.config,h=S=>Math.ceil(Math.floor(S/f)/p),w=h(c)**2,x=this.config.image_start_token??"<|image_start|>",v=this.config.image_end_token??"<|image_end|>",E=this.config.image_thumbnail??"<|img_thumbnail|>";Array.isArray(r)||(r=[r]);let A=0;r=r.map(S=>{let M=S.split(l);return M[0]+M.slice(1).map(L=>{let O=A++,[k,G]=a[O],H=n[O],U=o[O],V=h(k)*h(G),q=x;if(H>1||U>1){let Y=l.repeat(w);for(let B=0;B<H;++B)for(let C=0;C<U;++C)q+=`<|img_row_${B+1}_col_${C+1}|>`+Y;m&&(q+=E+l.repeat(V))}else q+=l.repeat(V);return q+v+L}).join("")})}return{...i,...r?this.tokenizer(r,s):{}}}};var Sh=class extends re{static tokenizer_class=oe;static image_processor_class=Le;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:c,num_additional_image_tokens:p}=this.config,f=Math.floor(a/c)*Math.floor(i/c)+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 I2={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]},Oh=class extends re{static tokenizer_class=oe;static image_processor_class=Le;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(!I2.hasOwnProperty(r))throw new Error(`Format ${r} is not supported.`);let[s,n]=I2[r],o=this[s].bind(this),[a,i]=e.dims,l=[],c=[],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]=Ce(Re(h[E]));if(x.push(A),S==n)break;w.push(S)}let v=x.length>0?x.reduce((E,A)=>E*A,1):0;c.push(w),l.push(v)}return[o(c),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,c]=this._decode_helper(s,"wp"),p=[],f=[];for(let m=0;m<n.length;++m){let[h,w]=Ce([o[m],i[m],c[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 oe.from_pretrained("Xenova/gpt2"),n=await oe.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 Ih=class extends re{static tokenizer_class=oe;static feature_extractor_class=Ke;async _call(e){return await this.feature_extractor(e)}};var Ch=class extends re{static tokenizer_class=oe;static image_processor_class=Le};var bn="<image>";function CN(t,e,r,s,n){return`${s.repeat(r*n)}${e}${t}
24
+ `}var Ph=class extends re{static tokenizer_class=oe;static image_processor_class=Le;static uses_processor_config=!1;async _call(e,r=null,s={}){r||(Z.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(c=>c.includes(bn))?a=r.map(c=>{let p=c.replaceAll(bn,bn.repeat(o)),f=p.lastIndexOf(bn),m=f===-1?0:f+bn.length;return p.slice(0,m)+n+p.slice(m)+`
25
+ `}):(Z.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(c=>CN(c,n,o,bn,e.length)));let i=this.tokenizer(a,s);return{...await this.image_processor(e,s),...i}}};var C2="<|image|>",PN=/<\|image_\d+\|>/g,Lh=class extends re{static image_processor_class=Le;static tokenizer_class=oe;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,c=e.map((f,m)=>f.split(PN).join(C2.repeat(l[m])));a=this.tokenizer(c,{padding:s,truncation:n});let p=this.tokenizer._tokenizer.token_to_id(C2);a.input_ids.map_(f=>f==p?-f:f)}else a=this.tokenizer(e);return{...a,...i}}};var Nh=class extends re{static tokenizer_class=oe;static image_processor_class=Le;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:c,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 v=0;v<r.length;++v){let E=l.repeat(x),A=E+c,S=E+p,M=A.repeat(w-1)+S;r[v]=r[v].replace(l,M)}}let o=r?this.tokenizer(r,s):{};return{...n,...o}}};var zh=class extends re{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 $o=class extends re{static image_processor_class=Le;static tokenizer_class=oe;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,c=o.tolist();e=e.map(p=>{for(;p.includes("<|image_pad|>");){let f=Number(c[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 Do=class extends $o{};var Rh=class extends Do{};var Bo=class extends re{static image_processor_class=Le;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 qc=class extends Bo{},$h=class extends qc{};var Dh=class extends re{static tokenizer_class=oe;static feature_extractor_class=Ke;async _call(e){return await this.feature_extractor(e)}};var Bh=class extends re{static tokenizer_class=oe;static feature_extractor_class=Ke;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),c=1+Math.ceil(l/this.config.stack_factor);n.audio_token_len=[c],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(c))}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}};var Wc="[AUDIO]",LN="[BEGIN_AUDIO]",NN=375;function zN(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 Uh=class extends re{static tokenizer_class=oe;static feature_extractor_class=Ke;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(Wc))throw new Error(`The input text does not contain the audio token ${Wc}.`);Array.isArray(r)||(r=[r]);let a=e.split(Wc),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,c=r.map(w=>zN(w,l)),p=c.map(w=>w.length),f=c.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+=LN;for(let x=0;x<p[w];++x)h+=Wc.repeat(NN);h+=a[w+1]}e=h}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}};var P2=32,Fh=6,Vc=8,RN=10,$N=32,Gh=class extends re{static tokenizer_class=oe;static feature_extractor_class=Ke;static uses_processor_config=!1;get num_mel_frames_first_audio_chunk(){return(Fh+1)*Vc}get num_samples_first_audio_chunk(){let{hop_length:e,n_fft:r}=this.feature_extractor.config;return(this.num_mel_frames_first_audio_chunk-1)*e+Math.floor(r/2)}get num_samples_per_audio_chunk(){let{hop_length:e,n_fft:r}=this.feature_extractor.config;return Vc*e+r}get num_right_pad_tokens(){return Fh+1+RN}get audio_length_per_tok(){return Vc}get raw_audio_length_per_tok(){return Vc*this.feature_extractor.config.hop_length}async _call(e,{is_streaming:r=!1,is_first_audio_chunk:s=!0}={}){if(Be(e,"VoxtralRealtimeProcessor"),!r&&!s)throw new Error("In non-streaming mode (`is_streaming=false`), `is_first_audio_chunk` must be `true`.");if(s)if(r){let n=P2*this.raw_audio_length_per_tok,o=new Float32Array(n+e.length);o.set(e,n);let a=await this.feature_extractor(o,{center:!0}),l=1+(P2+Fh),c=new BigInt64Array(l).fill(BigInt($N));return c[0]=1n,{input_ids:new R("int64",c,[1,l]),...a}}else{let n=this.num_right_pad_tokens*this.raw_audio_length_per_tok,o=new Float32Array(e.length+n);return o.set(e),await this.feature_extractor(o,{center:!0})}else return await this.feature_extractor(e,{center:!1})}};var jh=class extends re{static tokenizer_class=oe;static feature_extractor_class=Ke;async _call(e){return await this.feature_extractor(e)}};var qh=class extends re{static tokenizer_class=oe;static feature_extractor_class=Ke;async _call(e){return await this.feature_extractor(e)}};var Wh=class extends re{static tokenizer_class=oe;static feature_extractor_class=Ke;async _call(e){return await this.feature_extractor(e)}};var Xc=class{static async from_pretrained(e,r={}){let s=await dt(e,Ar,!0,r),{image_processor_type:n,feature_extractor_type:o,processor_class:a}=s;if(a&&Hc[a])return Hc[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 c=yn[n.replace(/Fast$/,"")];if(!c)throw new Error(`Unknown image_processor_type: '${n}'.`);i.image_processor=new c(s)}if(o){let c=yn[o];if(c)i.image_processor=new c(s);else{let p=zo[o];if(!p)throw new Error(`Unknown feature_extractor_type: '${o}'.`);i.feature_extractor=new p(s)}}let l={};return new re(l,i,null)}};async function DN(t,e){return await dt(t,"config.json",!0,e)}function vn(t){let e={},r={};switch(t.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"granite_speech":case"ultravox":case"voxtral":case"voxtral_realtime":case"smolvlm":case"gemma3n":case"lfm2_vl":case"chatterbox":case"mistral3":case"qwen2_5_vl":case"qwen3_vl":case"qwen3_vl_moe":r=vn(t.text_config);break;case"moondream1":r=vn(t.phi_config);break;case"musicgen":r=vn(t.decoder);break;case"multi_modality":r=vn(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"voxtral_realtime_text":case"voxtral_realtime_encoder":case"starcoder2":case"qwen2":case"qwen2_moe":case"qwen2_vl":case"qwen2_vl_text":case"qwen2_5_vl_text":case"qwen3_moe":case"qwen3_vl_text":case"qwen3_vl_moe_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=vn(t.decoder),o="num_decoder_layers"in n,a=Ye(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,...Ye(t,["model_type","multi_query","is_encoder_decoder"])};for(let n in e)s[n]=t[e[n]];return s}function Ps(t,e){if(t instanceof kn||(t=new kn(t)),["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:c}=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,c];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:c,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:v}=t,E=c/i,A=e?.batch_size??1,S=(v??x*c)+2*w*h;for(let M=0;M<a;++M)if((!o||o[M]==="mamba")&&(n[`${s}_conv.${M}`]=[A,S,p],n[`${s}_ssm.${M}`]=[A,f,m,h]),!o||o[M]==="attention")for(let L of["key","value"])n[`${r}.${M}.${L}`]=[A,l,0,E];return n}else if(["qwen3_next","qwen3_5_text","qwen3_5_moe_text","olmo_hybrid"].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:c,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,x=m*f,v=h*p,E=o??c/i,A=e?.batch_size??1;for(let S=0;S<a.length;++S)if(a[S]==="full_attention")for(let M of["key","value"])n[`${r}.${S}.${M}`]=[A,l,0,E];else if(a[S]==="linear_attention"){if(t.model_type==="olmo_hybrid")n[`${s}_conv.${S}.key`]=[A,x,w],n[`${s}_conv.${S}.value`]=[A,v,w],n[`${s}_conv.${S}.query`]=[A,x,w];else{let M=x*2+v;n[`${s}_conv.${S}`]=[A,M,w]}n[`${s}_recurrent.${S}`]=[A,p,m,h]}else throw new Error(`Unsupported layer type: ${a[S]}`);return n}else if(["lfm2_vl","qwen3_5","qwen3_5_moe","voxtral_realtime"].includes(t.model_type)){let r;return t.model_type==="voxtral_realtime"&&e?.session_name==="audio_encoder"?r=t.audio_config:r=t.text_config,Ps(r,e)}return BN(t,e)}function BN(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 c=0;c<n.num_decoder_layers;++c)s[`${e}.${c}.encoder.key`]=i,s[`${e}.${c}.encoder.value`]=i,s[`${e}.${c}.decoder.key`]=l,s[`${e}.${c}.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 c=0;c<a;++c)s[`${e}.${c}.key`]=l,s[`${e}.${c}.value`]=l}else if(n.multi_query){let l=[r*o,0,2*i];for(let c=0;c<a;++c)s[`${e}.${c}.key_value`]=l}else if(n.model_type==="bloom"){let l=[r*o,i,0],c=[r*o,0,i];for(let p=0;p<a;++p)s[`${e}.${p}.key`]=l,s[`${e}.${p}.value`]=c}else if(n.model_type==="openelm")for(let l=0;l<a;++l){let c=[r,o[l],0,i];s[`${e}.${l}.key`]=c,s[`${e}.${l}.value`]=c}else{let l=[r,o,0,i];for(let c=0;c<a;++c)s[`${e}.${c}.key`]=l,s[`${e}.${c}.value`]=l}}return s}var kn=class t{model_type=null;is_encoder_decoder=!1;max_position_embeddings;"transformers.js_config";constructor(e){Object.assign(this,e),this.normalized_config=vn(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 DN(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(i)}},Wt=class{static async from_pretrained(...e){return kn.from_pretrained(...e)}};function Vh(t,e,r){return t?typeof t=="object"&&t!==null?t.hasOwnProperty(e)?+t[e]:t.hasOwnProperty(r)?+t[r]:0:+t:0}function Hh(t,e){let r=[];for(let s=0;s<e;++s)r.push(`${t}_data${s===0?"":"_"+s}`);return r}async function L2(t,e,r,s){let n=`${e}${s}.onnx`,o=`${r.subfolder??""}/${n}`;return await fo(t,o,!0,r,ie.IS_NODE_ENV)}async function N2(t,e,r,s,n,o={}){let a=`${e}${r}.onnx`,i=ie.IS_NODE_ENV,l=[],c=Vh(n,a,e);if(c>0){if(c>Xl)throw new Error(`The number of external data chunks (${c}) exceeds the maximum allowed value (${Xl}).`);let p=Hh(a,c);for(let f of p){let m=`${s.subfolder??""}/${f}`;l.push(new Promise(async(h,w)=>{let x=await fo(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 fo(t,p.data,!0,s);return{...p,data:f}}return p}));return Promise.all(l)}async function UN(t,e,r,s=!1,n=void 0){let o=r.config?.["transformers.js_config"]??{},a=hc(r.device??o.device,e,{warn:M=>Z.info(M)}),i=o2(a),l=o.device_config??{};l.hasOwnProperty(a)&&(o={...o,...l[a]});let c=_c(r.dtype??o.dtype,e,a,{configDtype:o.dtype,warn:M=>Z.info(M)});if(Ao.hasOwnProperty(c)){if(a==="webgpu"&&!ie.IS_NODE_ENV&&c===vt.fp16&&!await c2())throw new Error(`The device (${a}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${c}. Should be one of: ${Object.keys(vt).join(", ")}`);let p=o.kv_cache_dtype,f=p?typeof p=="string"?p:p[c]??"float32":void 0;if(f&&!["float32","float16"].includes(f))throw new Error(`Invalid kv_cache_dtype: ${f}. Should be one of: float32, float16`);let m=Ao[c],h={...r.session_options};h.executionProviders??=i;let w=o.free_dimension_overrides;w?h.freeDimensionOverrides??=w:a.startsWith("webnn")&&!h.freeDimensionOverrides&&Z.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 x=L2(t,e,r,m),v=r.use_external_data_format??o.use_external_data_format,E=await N2(t,e,m,r,v,h);if(E.length>0&&!ie.IS_NODE_ENV&&(h.externalData=E),s&&a==="webgpu"&&p!==!1){let M=Ps(r.config,{prefix:"present",session_name:n});if(Object.keys(M).length>0&&!Eo()){let L={};for(let O in M)L[O]="gpu-buffer";h.preferredOutputLocation=L}}return{buffer_or_path:await x,session_options:h,session_config:{dtype:c,kv_cache_dtype:f,device:a}}}async function z2(t,e,r,s=void 0){return Object.fromEntries(await Promise.all(Object.keys(e).map(async n=>{let o=s?.[n]??!1,{buffer_or_path:a,session_options:i,session_config:l}=await UN(t,e[n],r,o,n),c=await fc(a,i,l);return[n,c]})))}function R2(t){for(let e in t)mc(t[e])?t[e]=new R(t[e]):typeof t[e]=="object"&&R2(t[e]);return t}async function fe(t,e){let r=FN(t,e);try{let s=Object.fromEntries(Object.entries(r).map(([o,a])=>{let i=a.ort_tensor;return ie.IS_NODE_ENV&&typeof Float16Array<"u"&&i.cpuData instanceof Float16Array&&(i.cpuData=new Uint16Array(i.cpuData.buffer)),[o,i]})),n=await dc(t,s);return R2(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 Z.error(`An error occurred during model execution: "${s}".`),Z.error("Inputs given to model:",n),s}}function FN(t,e){let r=Object.create(null),s=[];for(let a of t.inputNames){let i=e[a];if(!(i instanceof R)){s.push(a);continue}r[a]=Eo()?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));Z.warn(`WARNING: Too many inputs were provided (${n} > ${o}). The following inputs will be ignored: "${a.join(", ")}".`)}return r}var $e=class{};var j=class extends $e{constructor({logits:e,...r}){super(),this.logits=e;let s=Object.values(r);s.length>0&&(this.attentions=s)}},_e=class extends $e{constructor({logits:e}){super(),this.logits=e}},we=class extends $e{constructor({logits:e}){super(),this.logits=e}},Te=class extends $e{constructor({start_logits:e,end_logits:r}){super(),this.start_logits=e,this.end_logits=r}},At=class extends $e{constructor({logits:e}){super(),this.logits=e}};var Kc=class extends $e{constructor({alphas:e}){super(),this.alphas=e}};var Vt=class extends rt{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},Uo=class extends rt{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},Ls=class extends rt{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()}},Yc=class extends Vt{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}},Qc=class extends Vt{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}},En=class extends Vt{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}},Jc=class extends Vt{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=xf(n),c=Math.log(l.subarray(this.timestamp_begin).map(Math.exp).reduce((f,m)=>f+m)),p=Ce(l.subarray(0,this.timestamp_begin))[0];c>p&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return r}},Zc=class extends Vt{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}},eu=class extends Vt{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}},tu=class extends Vt{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}},ru=class extends Vt{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}},su=class extends Vt{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}},nu=class extends Vt{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}},ou=class extends Uo{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}},$2=class extends Uo{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}},D2=class extends Uo{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 An=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,Ye(e,Object.getOwnPropertyNames(this)))}};var Xr=class extends rt{_call(e,r){throw Error("StoppingCriteria needs to be subclassed")}},Tn=class t extends rt{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof t?e=e.criteria:e instanceof Xr&&(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()}},au=class extends Xr{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)}},iu=class extends Xr{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)})}},B2=class extends Xr{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 Ns=class extends rt{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 tE(e)}static getSampler(e){if(e.do_sample)return new Kh(e);if(e.num_beams>1)return new Yh(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 Xh(e)}},Xh=class extends Ns{async sample(e){let r=Ce(e.data)[1];return[[BigInt(r),0]]}},Kh=class extends Ns{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 sr(e,r),o=Re(s.data);return Array.from({length:this.generation_config.num_beams},()=>{let a=this.randomSelect(o);return[n.data[a],Math.log(o[a])]})}},Yh=class extends Ns{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 sr(e,r),o=Re(s.data);return Array.from({length:this.generation_config.num_beams},(a,i)=>[n.data[i],Math.log(o[i])])}};var Qh=class{constructor(e){if(e)for(let r in e){if(r in this)throw new TypeError(`Key "${r}" conflicts with an existing property on DynamicCache`);let s=e[r];if(!(s instanceof R))throw new TypeError(`Expected a Tensor for key "${r}", got ${typeof s}`);this[r]=s}}get_seq_length(){let e=this;for(let r in e)if(r.startsWith("past_key_values."))return e[r].dims.at(-2);throw new Error("Unable to determine sequence length from the cache.")}async dispose(){let e=[];for(let r of Object.values(this))r.location==="gpu-buffer"&&e.push(r.dispose());await Promise.all(e)}},Fo=Qh;var zs=null;function F2(t){zs=t}function Jh(t){if(t instanceof R)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 R("int64",BigInt64Array.from(t.flat().map(e=>BigInt(e))),[t.length,t[0].length])}else return new R("int64",BigInt64Array.from(t.map(e=>BigInt(e))),[1,t.length])}function Zh(t){return new R("bool",[t],[1])}var K={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,MultimodalLanguageModelOnly:16,VoxtralRealtime:17},Mn={[K.DecoderOnly]:{can_generate:!0,forward:Lt,prepare_inputs:Sn,sessions:(t,e)=>({model:e.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[K.DecoderOnlyWithoutHead]:{can_generate:!1,forward:Lt,prepare_inputs:Sn,sessions:(t,e)=>({model:e.model_file_name??"model"})},[K.Seq2Seq]:{can_generate:!0,forward:lu,prepare_inputs:jo,sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[K.Vision2Seq]:{can_generate:!0,forward:lu,prepare_inputs:jo,sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[K.Musicgen]:{can_generate:!0,forward:lu,sessions:()=>({model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[K.EncoderDecoder]:{can_generate:!1,forward:lu,sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[K.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[K.ImageTextToText]:{can_generate:!0,forward:U2,prepare_inputs:Go,sessions:t=>{let e={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};return t.is_encoder_decoder&&(e.model="encoder_model"),e},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[K.AudioTextToText]:{can_generate:!0,forward:jN,prepare_inputs:Go,sessions:()=>({embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[K.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:Go,sessions:()=>({embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"}),optional_configs:{generation_config:"generation_config.json"}},[K.Phi3V]:{can_generate:!0,prepare_inputs:Go,sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[K.MultiModality]:{can_generate:!0,sessions:()=>({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"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[K.AutoEncoder]:{can_generate:!1,forward:GN,sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[K.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[K.Chatterbox]:{can_generate:!0,forward:Ht,sessions:()=>({embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[K.MultimodalLanguageModelOnly]:{can_generate:!0,forward:U2,prepare_inputs:Go,sessions:()=>({embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[K.VoxtralRealtime]:{can_generate:!0,prepare_inputs:Sn,sessions:()=>({embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:"generation_config.json"}},default:{can_generate:!1,forward:Ht,sessions:(t,e)=>({model:e.model_file_name??"model"})}};function G2(t,e,r={}){let s=Mn[t]??Mn.default;return{sessions:s.sessions(e,r),cache_sessions:s.cache_sessions,optional_configs:s.optional_configs}}var nr=new Map,cu=new Map,Rs=new Map,y=class extends rt{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=Rs.get(this.constructor),o=nr.get(n),a=Mn[o]??Mn.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:c=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:c,dtype:p,use_external_data_format:f,session_options:m},w=Rs.get(this),x=nr.get(w);s=h.config=await Wt.from_pretrained(e,h);let v=Mn[x]??Mn.default;if(x===void 0){let M=w??s?.model_type;M!=="custom"&&Z.warn(`Model type for '${M}' not found, assuming encoder-only architecture. Please report this at ${Wr}.`)}let E=v.sessions(s,h),A=[z2(e,E,h,v.cache_sessions)];v.optional_configs&&A.push(WN(e,v.optional_configs,h));let S=await Promise.all(A);return new this(s,...S)}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 Ls;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&n.push(new eu(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&n.push(new Zc(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&n.push(new su(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&n.push(new tu(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 ru(r,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&n.push(new Yc(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&n.push(new Qc(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 En(e.begin_suppress_tokens,o))}return e.guidance_scale!==null&&e.guidance_scale>1&&n.push(new nu(e.guidance_scale)),e.temperature===0&&e.do_sample&&(Z.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 ou(e.temperature)),s!==null&&n.extend(s),n}_prepare_generation_config(e,r,s=An){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,Ye(r,Object.getOwnPropertyNames(o))),o}_get_stopping_criteria(e,r=null){let s=new Tn;return e.max_length!==null&&s.push(new au(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&s.push(new iu(e.eos_token_id)),r&&s.extend(r),s}_validate_model_class(){if(!this.can_generate){let e=[zs.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,zs.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,zs.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,zs.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),r=Rs.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 R("int64",e.flat(),[e.length,1]),n?"decoder_attention_mask"in s:s.attention_mask=Ee([s.attention_mask,st([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=Ye(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,...c}=r,p=await this._prepare_inputs_embeds(r);r={...c,...Ye(p,["inputs_embeds","attention_mask"])}}let{last_hidden_state:o}=await Ht(this,r);if(n.guidance_scale!==null&&n.guidance_scale>1)o=Ee([o,Mo(o,0)],0),"attention_mask"in r&&(r.attention_mask=Ee([r.attention_mask,yd(r.attention_mask)],0));else if(r.decoder_input_ids){let a=Jh(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 R)){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=Jh(i)}return s.decoder_attention_mask=yc(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:c}=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:c,generation_config:r})));let f;p?{input_ids:f,model_inputs:l}=this._prepare_decoder_input_ids_for_generation({batch_size:l[c].dims.at(0),model_input_name:c,model_kwargs:l,decoder_start_token_id:r.decoder_start_token_id,bos_token_id:r.bos_token_id,generation_config:r}):f=l[c];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[c].dims.at(0),v=Ns.getSampler(r),E=new Array(x).fill(0),A=f.tolist();o&&o.put(A);let S,M={},L={};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 q=this.getAttentions(S);for(let Y in q)Y in M||(M[Y]=[]),M[Y].push(q[Y])}else this._return_dict_in_generate_keys&&Object.assign(L,Ye(S,this._return_dict_in_generate_keys));let G=S.logits.slice(null,-1,null).to("float32"),H=h(A,G),U=[];for(let q=0;q<H.dims.at(0);++q){let Y=H[q],B=await v(Y);for(let[C,te]of B){let le=BigInt(C);E[q]+=te,A[q].push(le),U.push([le]);break}}if(o&&o.put(U),w(A).every(q=>q))break;l=this._update_model_kwargs_for_generation({generated_input_ids:U,outputs:S,model_inputs:l,is_encoder_decoder:p})}o&&o.end();let O=this.getPastKeyValues(S,l.past_key_values,!0),k=new R("int64",A.flat(),[A.length,A[0].length]);if(r.return_dict_in_generate)return{sequences:k,past_key_values:O,...M,...L};for(let G of Object.values(S))G.location==="gpu-buffer"&&G.dispose();return k}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 new Fo(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"?Er.float16:Er.float32,i=Ps(this.config,{batch_size:n});for(let l in i){let c=i[l].reduce((p,f)=>p*f,1);e[l]=new R(o,new a(c),i[l])}}}async _encode_input(e,r,s){if(!Object.hasOwn(this.sessions,e))throw new Error(`Model does not have a ${e} session.`);let n=this.sessions[e];return(await fe(n,Ye(r,n.inputNames)))[s]}async encode_image(e){return this._encode_input("vision_encoder",e,"image_features")}async encode_text(e){return this._encode_input("embed_tokens",e,"inputs_embeds")}async encode_audio(e){return this._encode_input("audio_encoder",e,"audio_features")}};async function lu(t,e){let{encoder_outputs:r,input_ids:s,decoder_input_ids:n,...o}=e;if(!r){let a=Ye(e,t.sessions.model.inputNames);r=(await Ht(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 Lt(t,o,!0)}async function Ht(t,e){let r=t.sessions.model,s=Ye(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=yd(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=st([n[0],n[2],n[3]])}return await fe(r,s)}async function GN(t,e){let r=await t.encode(e);return await t.decode(r)}async function Lt(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=Zh(!!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=qN(o,n,i)}s.inputNames.includes("num_logits_to_keep")&&!o.num_logits_to_keep&&(o.num_logits_to_keep=new R("int64",[0n],[])),t.addPastKeyValues(o,n);let a=Ye(o,s.inputNames);return await fe(s,a)}async function j2(t,{encode_function:e,merge_function:r,modality_input_names:s,modality_output_name:n,input_ids:o=null,attention_mask:a=null,position_ids:i=null,inputs_embeds:l=null,past_key_values:c=null,generation_config:p=null,logits_processor:f=null,...m}){if(!l){l=await t.encode_text({input_ids:o,...m});let w=Ye(m,s);if(Object.keys(w).length>0){if(o.dims[1]!==1){let x=await e({...w,...m});({inputs_embeds:l,attention_mask:a}=r({[n]:x,inputs_embeds:l,input_ids:o,attention_mask:a}))}else if(c&&o.dims[1]===1){let x=o.dims[1],v=c.get_seq_length();a=Ee([st([o.dims[0],v]),a.slice(null,[a.dims[1]-x,a.dims[1]])],1)}}}if(!i&&["qwen2_vl","qwen2_vl_text","qwen2_5_vl","qwen2_5_vl_text","qwen3_vl","qwen3_vl_text","qwen3_vl_moe","qwen3_vl_moe_text","qwen3_5","qwen3_5_text","qwen3_5_moe","qwen3_5_moe_text"].includes(t.config.model_type)){let{image_grid_thw:w,video_grid_thw:x}=m;[i]=t.get_rope_index(o,w,x,a)}return await Lt(t,{inputs_embeds:l,past_key_values:c,attention_mask:a,position_ids:i,generation_config:p,logits_processor:f},!0)}async function jN(t,e){return await j2(t,{...e,modality_input_names:["audio_values","input_features"],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 U2(t,e){return await j2(t,{...e,modality_input_names:["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 e_(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 c=0;c<s;++c){let p=i+c;n[p]===0n?o[p]=BigInt(1):(o[p]=l,l+=n[p])}}return{data:o,dims:t.dims}}function qN(t,e=null,r=0){let{input_ids:s,inputs_embeds:n,attention_mask:o}=t,{data:a,dims:i}=e_(o,r),l=new R("int64",a,i);if(e){let c=-(s??n).dims.at(1);l=l.slice(null,[c,null])}return l}function Sn(t,e,r,s){let n=r.past_key_values?r.past_key_values.get_seq_length():0;if((t.sessions.decoder_model_merged??t.sessions.model)?.inputNames.includes("num_logits_to_keep")&&!r.num_logits_to_keep&&(r.num_logits_to_keep=new R("int64",[1n],[])),!r.attention_mask){let a;for(let i of["input_ids","inputs_embeds","position_ids"])if(r[i]){a=r[i].dims;break}if(!a)throw new Error("attention_mask is not provided, and unable to infer its shape from model inputs.");r.attention_mask=st([a[0],n+a[1]])}if(r.past_key_values){let{input_ids:a,attention_mask:i}=r;i&&i.dims[1]>a.dims[1]||n<a.dims[1]&&(r.input_ids=a.slice(null,[n,null]))}return r}function jo(t,e,r,s){return r.past_key_values&&(e=e.map(n=>[n.at(-1)])),{...r,decoder_input_ids:Jh(e)}}function Go(t,...e){return t.config.is_encoder_decoder?jo(t,...e):Sn(t,...e)}function q2({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n}){let o=s.tolist().map(c=>c.reduce((p,f,m)=>(f==t&&p.push(m),p),[])),a=o.reduce((c,p)=>c+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 c=0;c<o.length;++c){let p=o[c],f=e[c];for(let m=0;m<p.length;++m)f[p[m]].data.set(r[l++].data)}return{inputs_embeds:e,attention_mask:n}}function On({image_token_id:t,inputs_embeds:e,image_features:r,input_ids:s,attention_mask:n}){return q2({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n})}function uu({audio_token_id:t,inputs_embeds:e,audio_features:r,input_ids:s,attention_mask:n}){return q2({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n})}async function WN(t,e,r){return Object.fromEntries(await Promise.all(Object.keys(e).map(async s=>{let n=await dt(t,e[s],!1,r);return[s,n]})))}var Zi={};hs(Zi,{ASTForAudioClassification:()=>f_,ASTModel:()=>p_,ASTPreTrainedModel:()=>Ho,AfmoeForCausalLM:()=>l_,AfmoeModel:()=>i_,AfmoePreTrainedModel:()=>Wo,AlbertForMaskedLM:()=>n_,AlbertForQuestionAnswering:()=>s_,AlbertForSequenceClassification:()=>r_,AlbertModel:()=>t_,AlbertPreTrainedModel:()=>$s,ApertusForCausalLM:()=>a_,ApertusModel:()=>o_,ApertusPreTrainedModel:()=>qo,ArceeForCausalLM:()=>u_,ArceeModel:()=>c_,ArceePreTrainedModel:()=>Vo,BartForConditionalGeneration:()=>m_,BartForSequenceClassification:()=>h_,BartModel:()=>d_,BartPretrainedModel:()=>In,BeitForImageClassification:()=>g_,BeitModel:()=>__,BeitPreTrainedModel:()=>Xo,BertForMaskedLM:()=>x_,BertForQuestionAnswering:()=>v_,BertForSequenceClassification:()=>y_,BertForTokenClassification:()=>b_,BertModel:()=>w_,BertPreTrainedModel:()=>Kr,BlenderbotForConditionalGeneration:()=>E_,BlenderbotModel:()=>k_,BlenderbotPreTrainedModel:()=>Ko,BlenderbotSmallForConditionalGeneration:()=>T_,BlenderbotSmallModel:()=>A_,BlenderbotSmallPreTrainedModel:()=>Yo,BloomForCausalLM:()=>S_,BloomModel:()=>M_,BloomPreTrainedModel:()=>Qo,CLIPModel:()=>R_,CLIPPreTrainedModel:()=>mr,CLIPSegForImageSegmentation:()=>F_,CLIPSegModel:()=>U_,CLIPSegPreTrainedModel:()=>ra,CLIPTextModel:()=>$_,CLIPTextModelWithProjection:()=>ta,CLIPVisionModel:()=>D_,CLIPVisionModelWithProjection:()=>B_,CamembertForMaskedLM:()=>I_,CamembertForQuestionAnswering:()=>L_,CamembertForSequenceClassification:()=>C_,CamembertForTokenClassification:()=>P_,CamembertModel:()=>O_,CamembertPreTrainedModel:()=>Yr,ChatterboxModel:()=>Jo,ChatterboxPreTrainedModel:()=>pu,ChineseCLIPModel:()=>N_,ChineseCLIPPreTrainedModel:()=>fu,ClapAudioModelWithProjection:()=>ea,ClapModel:()=>z_,ClapPreTrainedModel:()=>Cn,ClapTextModelWithProjection:()=>Zo,CodeGenForCausalLM:()=>j_,CodeGenModel:()=>G_,CodeGenPreTrainedModel:()=>sa,Cohere2ForCausalLM:()=>H_,Cohere2Model:()=>V_,Cohere2PreTrainedModel:()=>oa,CohereForCausalLM:()=>W_,CohereModel:()=>q_,CoherePreTrainedModel:()=>na,ConvBertForMaskedLM:()=>K_,ConvBertForQuestionAnswering:()=>J_,ConvBertForSequenceClassification:()=>Y_,ConvBertForTokenClassification:()=>Q_,ConvBertModel:()=>X_,ConvBertPreTrainedModel:()=>Qr,ConvNextForImageClassification:()=>eg,ConvNextModel:()=>Z_,ConvNextPreTrainedModel:()=>aa,ConvNextV2ForImageClassification:()=>rg,ConvNextV2Model:()=>tg,ConvNextV2PreTrainedModel:()=>ia,DFineForObjectDetection:()=>ag,DFineModel:()=>og,DFinePreTrainedModel:()=>ca,DINOv3ConvNextModel:()=>Ig,DINOv3ConvNextPreTrainedModel:()=>xu,DINOv3ViTModel:()=>Cg,DINOv3ViTPreTrainedModel:()=>yu,DPTForDepthEstimation:()=>Bg,DPTModel:()=>Dg,DPTPreTrainedModel:()=>ha,DacDecoderModel:()=>pa,DacDecoderOutput:()=>mu,DacEncoderModel:()=>ua,DacEncoderOutput:()=>du,DacModel:()=>ig,DacPreTrainedModel:()=>Pn,DebertaForMaskedLM:()=>cg,DebertaForQuestionAnswering:()=>fg,DebertaForSequenceClassification:()=>ug,DebertaForTokenClassification:()=>pg,DebertaModel:()=>lg,DebertaPreTrainedModel:()=>Jr,DebertaV2ForMaskedLM:()=>mg,DebertaV2ForQuestionAnswering:()=>gg,DebertaV2ForSequenceClassification:()=>hg,DebertaV2ForTokenClassification:()=>_g,DebertaV2Model:()=>dg,DebertaV2PreTrainedModel:()=>Zr,DecisionTransformerModel:()=>wg,DecisionTransformerPreTrainedModel:()=>hu,DeiTForImageClassification:()=>yg,DeiTModel:()=>xg,DeiTPreTrainedModel:()=>fa,DepthAnythingForDepthEstimation:()=>bg,DepthAnythingPreTrainedModel:()=>_u,DepthProForDepthEstimation:()=>vg,DepthProPreTrainedModel:()=>gu,DetrForObjectDetection:()=>Eg,DetrForSegmentation:()=>Ag,DetrModel:()=>kg,DetrObjectDetectionOutput:()=>Nn,DetrPreTrainedModel:()=>Ln,DetrSegmentationOutput:()=>wu,Dinov2ForImageClassification:()=>Mg,Dinov2Model:()=>Tg,Dinov2PreTrainedModel:()=>da,Dinov2WithRegistersForImageClassification:()=>Og,Dinov2WithRegistersModel:()=>Sg,Dinov2WithRegistersPreTrainedModel:()=>ma,DistilBertForMaskedLM:()=>Rg,DistilBertForQuestionAnswering:()=>zg,DistilBertForSequenceClassification:()=>Lg,DistilBertForTokenClassification:()=>Ng,DistilBertModel:()=>Pg,DistilBertPreTrainedModel:()=>es,DonutSwinModel:()=>$g,DonutSwinPreTrainedModel:()=>bu,EdgeTamModel:()=>L0,EfficientNetForImageClassification:()=>Fg,EfficientNetModel:()=>Ug,EfficientNetPreTrainedModel:()=>_a,ElectraForMaskedLM:()=>jg,ElectraForQuestionAnswering:()=>Vg,ElectraForSequenceClassification:()=>qg,ElectraForTokenClassification:()=>Wg,ElectraModel:()=>Gg,ElectraPreTrainedModel:()=>ts,Ernie4_5ForCausalLM:()=>Xg,Ernie4_5Model:()=>Hg,Ernie4_5PretrainedModel:()=>ga,EsmForMaskedLM:()=>Yg,EsmForSequenceClassification:()=>Qg,EsmForTokenClassification:()=>Jg,EsmModel:()=>Kg,EsmPreTrainedModel:()=>Ds,ExaoneForCausalLM:()=>ew,ExaoneModel:()=>Zg,ExaonePreTrainedModel:()=>wa,FalconForCausalLM:()=>rw,FalconH1ForCausalLM:()=>nw,FalconH1Model:()=>sw,FalconH1PreTrainedModel:()=>ya,FalconModel:()=>tw,FalconPreTrainedModel:()=>xa,FastViTForImageClassification:()=>aw,FastViTModel:()=>ow,FastViTPreTrainedModel:()=>ba,Florence2ForConditionalGeneration:()=>iw,Florence2PreTrainedModel:()=>vu,GLPNForDepthEstimation:()=>gw,GLPNModel:()=>_w,GLPNPreTrainedModel:()=>Ma,GPT2LMHeadModel:()=>Mw,GPT2Model:()=>Tw,GPT2PreTrainedModel:()=>Pa,GPTBigCodeForCausalLM:()=>xw,GPTBigCodeModel:()=>ww,GPTBigCodePreTrainedModel:()=>Sa,GPTJForCausalLM:()=>Ow,GPTJModel:()=>Sw,GPTJPreTrainedModel:()=>La,GPTNeoForCausalLM:()=>bw,GPTNeoModel:()=>yw,GPTNeoPreTrainedModel:()=>Oa,GPTNeoXForCausalLM:()=>kw,GPTNeoXModel:()=>vw,GPTNeoXPreTrainedModel:()=>Ia,Gemma2ForCausalLM:()=>pw,Gemma2Model:()=>uw,Gemma2PreTrainedModel:()=>ka,Gemma3ForCausalLM:()=>dw,Gemma3Model:()=>fw,Gemma3PreTrainedModel:()=>Ea,Gemma3nForCausalLM:()=>Aa,Gemma3nForConditionalGeneration:()=>zn,Gemma3nPreTrainedModel:()=>ku,GemmaForCausalLM:()=>cw,GemmaModel:()=>lw,GemmaPreTrainedModel:()=>va,GlmForCausalLM:()=>hw,GlmModel:()=>mw,GlmPreTrainedModel:()=>Ta,GptOssForCausalLM:()=>Aw,GptOssModel:()=>Ew,GptOssPreTrainedModel:()=>Ca,GraniteForCausalLM:()=>Cw,GraniteModel:()=>Iw,GraniteMoeHybridForCausalLM:()=>Lw,GraniteMoeHybridModel:()=>Pw,GraniteMoeHybridPreTrainedModel:()=>za,GranitePreTrainedModel:()=>Na,GraniteSpeechForConditionalGeneration:()=>Nw,GroundingDinoForObjectDetection:()=>zw,GroundingDinoPreTrainedModel:()=>Au,GroupViTModel:()=>Rw,GroupViTPreTrainedModel:()=>Tu,HeliumForCausalLM:()=>Dw,HeliumModel:()=>$w,HeliumPreTrainedModel:()=>Ra,HieraForImageClassification:()=>Uw,HieraModel:()=>Bw,HieraPreTrainedModel:()=>$a,HubertForCTC:()=>Hw,HubertForSequenceClassification:()=>Xw,HubertModel:()=>Vw,HubertPreTrainedModel:()=>Ww,HunYuanDenseV1ForCausalLM:()=>Yw,HunYuanDenseV1Model:()=>Kw,HunYuanDenseV1PreTrainedModel:()=>Da,IJepaForImageClassification:()=>tx,IJepaModel:()=>ex,IJepaPreTrainedModel:()=>Ba,Idefics3ForConditionalGeneration:()=>Zw,JAISLMHeadModel:()=>sx,JAISModel:()=>rx,JAISPreTrainedModel:()=>Ua,JinaCLIPModel:()=>nx,JinaCLIPPreTrainedModel:()=>Rn,JinaCLIPTextModel:()=>Fa,JinaCLIPVisionModel:()=>ox,Lfm2ForCausalLM:()=>ix,Lfm2Model:()=>ax,Lfm2MoeForCausalLM:()=>cx,Lfm2MoeModel:()=>lx,Lfm2MoePreTrainedModel:()=>ja,Lfm2PreTrainedModel:()=>Ga,Lfm2VlForConditionalGeneration:()=>ux,LiteWhisperForConditionalGeneration:()=>Vb,Llama4ForCausalLM:()=>dx,Llama4PreTrainedModel:()=>Su,LlamaForCausalLM:()=>fx,LlamaModel:()=>px,LlamaPreTrainedModel:()=>qa,LlavaForConditionalGeneration:()=>Xt,LlavaOnevisionForConditionalGeneration:()=>Xt,LlavaPreTrainedModel:()=>Mu,LlavaQwen2ForCausalLM:()=>Jw,LongT5ForConditionalGeneration:()=>hx,LongT5Model:()=>mx,LongT5PreTrainedModel:()=>Wa,M2M100ForConditionalGeneration:()=>gx,M2M100Model:()=>_x,M2M100PreTrainedModel:()=>Va,MBartForCausalLM:()=>Ax,MBartForConditionalGeneration:()=>kx,MBartForSequenceClassification:()=>Ex,MBartModel:()=>vx,MBartPreTrainedModel:()=>Us,MPNetForMaskedLM:()=>cy,MPNetForQuestionAnswering:()=>fy,MPNetForSequenceClassification:()=>uy,MPNetForTokenClassification:()=>py,MPNetModel:()=>ly,MPNetPreTrainedModel:()=>rs,MT5ForConditionalGeneration:()=>_y,MT5Model:()=>hy,MT5PreTrainedModel:()=>ni,MarianMTModel:()=>xx,MarianModel:()=>wx,MarianPreTrainedModel:()=>Ha,MaskFormerForInstanceSegmentation:()=>bx,MaskFormerModel:()=>yx,MaskFormerPreTrainedModel:()=>Xa,Metric3DForDepthEstimation:()=>Tx,Metric3DPreTrainedModel:()=>Ou,Metric3Dv2ForDepthEstimation:()=>Mx,Metric3Dv2PreTrainedModel:()=>Iu,MgpstrForSceneTextRecognition:()=>Sx,MgpstrModelOutput:()=>Cu,MgpstrPreTrainedModel:()=>Pu,MimiDecoderModel:()=>Ya,MimiDecoderOutput:()=>Nu,MimiEncoderModel:()=>Ka,MimiEncoderOutput:()=>Lu,MimiModel:()=>Ox,MimiPreTrainedModel:()=>$n,MistralForCausalLM:()=>Cx,MistralModel:()=>Ix,MistralPreTrainedModel:()=>Qa,MobileBertForMaskedLM:()=>Lx,MobileBertForQuestionAnswering:()=>zx,MobileBertForSequenceClassification:()=>Nx,MobileBertModel:()=>Px,MobileBertPreTrainedModel:()=>Fs,MobileLLMForCausalLM:()=>$x,MobileLLMModel:()=>Rx,MobileLLMPreTrainedModel:()=>Ja,MobileNetV1ForImageClassification:()=>Bx,MobileNetV1ForSemanticSegmentation:()=>Ux,MobileNetV1Model:()=>Dx,MobileNetV1PreTrainedModel:()=>Dn,MobileNetV2ForImageClassification:()=>Gx,MobileNetV2ForSemanticSegmentation:()=>jx,MobileNetV2Model:()=>Fx,MobileNetV2PreTrainedModel:()=>Bn,MobileNetV3ForImageClassification:()=>Wx,MobileNetV3ForSemanticSegmentation:()=>Vx,MobileNetV3Model:()=>qx,MobileNetV3PreTrainedModel:()=>Un,MobileNetV4ForImageClassification:()=>Xx,MobileNetV4ForSemanticSegmentation:()=>Kx,MobileNetV4Model:()=>Hx,MobileNetV4PreTrainedModel:()=>Fn,MobileViTForImageClassification:()=>Qx,MobileViTModel:()=>Yx,MobileViTPreTrainedModel:()=>Za,MobileViTV2ForImageClassification:()=>Zx,MobileViTV2Model:()=>Jx,MobileViTV2PreTrainedModel:()=>ei,ModernBertDecoderForCausalLM:()=>oy,ModernBertDecoderModel:()=>ny,ModernBertDecoderPreTrainedModel:()=>ti,ModernBertForMaskedLM:()=>ty,ModernBertForSequenceClassification:()=>ry,ModernBertForTokenClassification:()=>sy,ModernBertModel:()=>ey,ModernBertPreTrainedModel:()=>Gs,Moondream1ForConditionalGeneration:()=>Qw,MoonshineForConditionalGeneration:()=>iy,MoonshineModel:()=>ay,MoonshinePreTrainedModel:()=>ri,MptForCausalLM:()=>my,MptModel:()=>dy,MptPreTrainedModel:()=>si,MultiModalityCausalLM:()=>gy,MultiModalityPreTrainedModel:()=>zu,MusicgenForCausalLM:()=>xy,MusicgenForConditionalGeneration:()=>ai,MusicgenModel:()=>wy,MusicgenPreTrainedModel:()=>oi,NanoChatForCausalLM:()=>by,NanoChatModel:()=>yy,NanoChatPreTrainedModel:()=>ii,NeoBertForMaskedLM:()=>ky,NeoBertForQuestionAnswering:()=>Ty,NeoBertForSequenceClassification:()=>Ey,NeoBertForTokenClassification:()=>Ay,NeoBertModel:()=>vy,NeoBertPreTrainedModel:()=>ss,NomicBertModel:()=>My,NomicBertPreTrainedModel:()=>Ru,OPTForCausalLM:()=>By,OPTModel:()=>Dy,OPTPreTrainedModel:()=>di,Olmo2ForCausalLM:()=>Cy,Olmo2Model:()=>Iy,Olmo2PreTrainedModel:()=>ci,Olmo3ForCausalLM:()=>Ly,Olmo3Model:()=>Py,Olmo3PreTrainedModel:()=>ui,OlmoForCausalLM:()=>Oy,OlmoHybridForCausalLM:()=>zy,OlmoHybridModel:()=>Ny,OlmoHybridPreTrainedModel:()=>pi,OlmoModel:()=>Sy,OlmoPreTrainedModel:()=>li,OpenELMForCausalLM:()=>$y,OpenELMModel:()=>Ry,OpenELMPreTrainedModel:()=>fi,OwlViTForObjectDetection:()=>jy,OwlViTModel:()=>Gy,OwlViTPreTrainedModel:()=>hi,Owlv2ForObjectDetection:()=>Fy,Owlv2Model:()=>Uy,Owlv2PreTrainedModel:()=>mi,PaliGemmaForConditionalGeneration:()=>qy,ParakeetForCTC:()=>Wy,ParakeetPreTrainedModel:()=>$u,PatchTSMixerForPrediction:()=>Hy,PatchTSMixerModel:()=>Vy,PatchTSMixerPreTrainedModel:()=>_i,PatchTSTForPrediction:()=>Ky,PatchTSTModel:()=>Xy,PatchTSTPreTrainedModel:()=>gi,Phi3ForCausalLM:()=>Zy,Phi3Model:()=>Jy,Phi3PreTrainedModel:()=>xi,Phi3VForCausalLM:()=>yi,Phi3VPreTrainedModel:()=>Du,PhiForCausalLM:()=>Qy,PhiModel:()=>Yy,PhiPreTrainedModel:()=>wi,PreTrainedModel:()=>y,PvtForImageClassification:()=>t0,PvtModel:()=>e0,PvtPreTrainedModel:()=>bi,PyAnnoteForAudioFrameClassification:()=>s0,PyAnnoteModel:()=>r0,PyAnnotePreTrainedModel:()=>vi,Qwen2ForCausalLM:()=>o0,Qwen2Model:()=>n0,Qwen2MoeForCausalLM:()=>i0,Qwen2MoeModel:()=>a0,Qwen2MoePreTrainedModel:()=>Ei,Qwen2PreTrainedModel:()=>ki,Qwen2VLForCausalLM:()=>js,Qwen2VLForConditionalGeneration:()=>Gn,Qwen2VLPreTrainedModel:()=>Bu,Qwen2_5_VLForCausalLM:()=>qs,Qwen2_5_VLForConditionalGeneration:()=>Ai,Qwen3ForCausalLM:()=>c0,Qwen3Model:()=>l0,Qwen3MoeForCausalLM:()=>p0,Qwen3MoeModel:()=>u0,Qwen3MoePreTrainedModel:()=>Mi,Qwen3NextForCausalLM:()=>d0,Qwen3NextModel:()=>f0,Qwen3NextPreTrainedModel:()=>Si,Qwen3PreTrainedModel:()=>Ti,Qwen3VLForCausalLM:()=>Vs,Qwen3VLForConditionalGeneration:()=>Ws,Qwen3VLMoeForCausalLM:()=>Oi,Qwen3VLMoeForConditionalGeneration:()=>m0,Qwen3_5ForCausalLM:()=>Hs,Qwen3_5ForConditionalGeneration:()=>jn,Qwen3_5MoeForCausalLM:()=>Ii,Qwen3_5MoeForConditionalGeneration:()=>h0,RFDetrForObjectDetection:()=>x0,RFDetrModel:()=>w0,RFDetrObjectDetectionOutput:()=>Uu,RFDetrPreTrainedModel:()=>Pi,RTDetrForObjectDetection:()=>ng,RTDetrModel:()=>sg,RTDetrObjectDetectionOutput:()=>hr,RTDetrPreTrainedModel:()=>la,RTDetrV2ForObjectDetection:()=>C0,RTDetrV2Model:()=>I0,RTDetrV2ObjectDetectionOutput:()=>Fu,RTDetrV2PreTrainedModel:()=>Li,ResNetForImageClassification:()=>g0,ResNetModel:()=>_0,ResNetPreTrainedModel:()=>Ci,RoFormerForMaskedLM:()=>T0,RoFormerForQuestionAnswering:()=>O0,RoFormerForSequenceClassification:()=>M0,RoFormerForTokenClassification:()=>S0,RoFormerModel:()=>A0,RoFormerPreTrainedModel:()=>os,RobertaForMaskedLM:()=>b0,RobertaForQuestionAnswering:()=>E0,RobertaForSequenceClassification:()=>v0,RobertaForTokenClassification:()=>k0,RobertaModel:()=>y0,RobertaPreTrainedModel:()=>ns,Sam2ImageSegmentationOutput:()=>qu,Sam2Model:()=>Ni,Sam2PreTrainedModel:()=>Wu,Sam3TrackerModel:()=>N0,SamImageSegmentationOutput:()=>Gu,SamModel:()=>P0,SamPreTrainedModel:()=>ju,SapiensForDepthEstimation:()=>R0,SapiensForNormalEstimation:()=>$0,SapiensForSemanticSegmentation:()=>z0,SapiensPreTrainedModel:()=>qn,SegformerForImageClassification:()=>B0,SegformerForSemanticSegmentation:()=>U0,SegformerModel:()=>D0,SegformerPreTrainedModel:()=>Wn,SiglipModel:()=>F0,SiglipPreTrainedModel:()=>zi,SiglipTextModel:()=>Ri,SiglipVisionModel:()=>G0,SmolLM3ForCausalLM:()=>q0,SmolLM3Model:()=>j0,SmolLM3PreTrainedModel:()=>$i,SnacDecoderModel:()=>Bi,SnacEncoderModel:()=>Di,SnacModel:()=>W0,SnacPreTrainedModel:()=>Vn,SpeechT5ForSpeechToText:()=>H0,SpeechT5ForTextToSpeech:()=>X0,SpeechT5HifiGan:()=>K0,SpeechT5Model:()=>V0,SpeechT5PreTrainedModel:()=>Hn,SqueezeBertForMaskedLM:()=>Q0,SqueezeBertForQuestionAnswering:()=>Z0,SqueezeBertForSequenceClassification:()=>J0,SqueezeBertModel:()=>Y0,SqueezeBertPreTrainedModel:()=>Xs,StableLmForCausalLM:()=>tb,StableLmModel:()=>eb,StableLmPreTrainedModel:()=>Ui,Starcoder2ForCausalLM:()=>sb,Starcoder2Model:()=>rb,Starcoder2PreTrainedModel:()=>Fi,StyleTextToSpeech2Model:()=>nb,StyleTextToSpeech2PreTrainedModel:()=>Vu,SupertonicForConditionalGeneration:()=>Gi,SupertonicPreTrainedModel:()=>Hu,Swin2SRForImageSuperResolution:()=>cb,Swin2SRModel:()=>lb,Swin2SRPreTrainedModel:()=>ji,SwinForImageClassification:()=>ab,SwinForSemanticSegmentation:()=>ib,SwinModel:()=>ob,SwinPreTrainedModel:()=>Xn,T5ForConditionalGeneration:()=>pb,T5Model:()=>ub,T5PreTrainedModel:()=>qi,TableTransformerForObjectDetection:()=>db,TableTransformerModel:()=>fb,TableTransformerObjectDetectionOutput:()=>Xu,TableTransformerPreTrainedModel:()=>Wi,TrOCRForCausalLM:()=>mb,TrOCRPreTrainedModel:()=>Ku,UltravoxModel:()=>Bs,UltravoxPreTrainedModel:()=>Eu,UniSpeechForCTC:()=>_b,UniSpeechForSequenceClassification:()=>gb,UniSpeechModel:()=>hb,UniSpeechPreTrainedModel:()=>Kn,UniSpeechSatForAudioFrameClassification:()=>bb,UniSpeechSatForCTC:()=>xb,UniSpeechSatForSequenceClassification:()=>yb,UniSpeechSatModel:()=>wb,UniSpeechSatPreTrainedModel:()=>Ks,VaultGemmaForCausalLM:()=>kb,VaultGemmaModel:()=>vb,VaultGemmaPreTrainedModel:()=>Vi,ViTForImageClassification:()=>Tb,ViTMAEModel:()=>Mb,ViTMAEPreTrainedModel:()=>Yu,ViTMSNForImageClassification:()=>Ob,ViTMSNModel:()=>Sb,ViTMSNPreTrainedModel:()=>Xi,ViTModel:()=>Ab,ViTPreTrainedModel:()=>Hi,VisionEncoderDecoderModel:()=>Eb,VitMatteForImageMatting:()=>Ib,VitMattePreTrainedModel:()=>Qu,VitPoseForPoseEstimation:()=>Cb,VitPosePreTrainedModel:()=>Ju,VitsModel:()=>Pb,VitsModelOutput:()=>Zu,VitsPreTrainedModel:()=>ep,VoxtralForConditionalGeneration:()=>Lb,VoxtralRealtimeForConditionalGeneration:()=>Ki,VoxtralRealtimePreTrainedModel:()=>tp,Wav2Vec2BertForCTC:()=>$b,Wav2Vec2BertForSequenceClassification:()=>Db,Wav2Vec2BertModel:()=>Rb,Wav2Vec2BertPreTrainedModel:()=>Yn,Wav2Vec2ForAudioFrameClassification:()=>qw,Wav2Vec2ForCTC:()=>Gw,Wav2Vec2ForSequenceClassification:()=>jw,Wav2Vec2Model:()=>Fw,Wav2Vec2PreTrainedModel:()=>or,WavLMForAudioFrameClassification:()=>jb,WavLMForCTC:()=>Ub,WavLMForSequenceClassification:()=>Fb,WavLMForXVector:()=>Gb,WavLMModel:()=>Bb,WavLMPreTrainedModel:()=>as,WeSpeakerResNetModel:()=>qb,WeSpeakerResNetPreTrainedModel:()=>sp,WhisperForConditionalGeneration:()=>op,WhisperModel:()=>Wb,WhisperPreTrainedModel:()=>Yi,XLMForQuestionAnswering:()=>Qb,XLMForSequenceClassification:()=>Kb,XLMForTokenClassification:()=>Yb,XLMModel:()=>Hb,XLMPreTrainedModel:()=>is,XLMRobertaForMaskedLM:()=>Zb,XLMRobertaForQuestionAnswering:()=>r1,XLMRobertaForSequenceClassification:()=>e1,XLMRobertaForTokenClassification:()=>t1,XLMRobertaModel:()=>Jb,XLMRobertaPreTrainedModel:()=>ls,XLMWithLMHeadModel:()=>Xb,XVectorOutput:()=>rp,YolosForObjectDetection:()=>n1,YolosModel:()=>s1,YolosObjectDetectionOutput:()=>ap,YolosPreTrainedModel:()=>Qi,YoutuForCausalLM:()=>a1,YoutuModel:()=>o1,YoutuPreTrainedModel:()=>Ji});var $s=class extends y{},t_=class extends $s{},r_=class extends $s{async _call(e){return new j(await super._call(e))}},s_=class extends $s{async _call(e){return new Te(await super._call(e))}},n_=class extends $s{async _call(e){return new we(await super._call(e))}};var qo=class extends y{},o_=class extends qo{},a_=class extends qo{};var Wo=class extends y{},i_=class extends Wo{},l_=class extends Wo{};var Vo=class extends y{},c_=class extends Vo{},u_=class extends Vo{};var Ho=class extends y{},p_=class extends Ho{},f_=class extends Ho{};var In=class extends y{},d_=class extends In{},m_=class extends In{},h_=class extends In{async _call(e){return new j(await super._call(e))}};var Xo=class extends y{},__=class extends Xo{},g_=class extends Xo{async _call(e){return new j(await super._call(e))}};var Kr=class extends y{},w_=class extends Kr{},x_=class extends Kr{async _call(e){return new we(await super._call(e))}},y_=class extends Kr{async _call(e){return new j(await super._call(e))}},b_=class extends Kr{async _call(e){return new _e(await super._call(e))}},v_=class extends Kr{async _call(e){return new Te(await super._call(e))}};var Ko=class extends y{},k_=class extends Ko{},E_=class extends Ko{};var Yo=class extends y{},A_=class extends Yo{},T_=class extends Yo{};var Qo=class extends y{},M_=class extends Qo{},S_=class extends Qo{};var Yr=class extends y{},O_=class extends Yr{},I_=class extends Yr{async _call(e){return new we(await super._call(e))}},C_=class extends Yr{async _call(e){return new j(await super._call(e))}},P_=class extends Yr{async _call(e){return new _e(await super._call(e))}},L_=class extends Yr{async _call(e){return new Te(await super._call(e))}};var VN=4299n,W2=6561n,pu=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"]},Jo=class extends pu{async encode_speech(e){return fe(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:c=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 R)){let S=e.dims[0];if(n==null)n=Xe([S],.5);else if(typeof n=="number")n=Xe([S],n);else if(Array.isArray(n))n=new R("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 fe(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=st([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 M=i.get_seq_length();r=st([a.dims[0],M+S])}}return{...await Lt(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,generation_config:l,logits_processor:c},!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==W2)-1);r.position_ids=new R("int64",n,[e.length,1])}else{let o=r.input_ids.tolist().map(a=>{let i=0;return a.map(l=>l>=W2?0:i++)});r.position_ids=new R("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),Sn(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=Xe([a.dims[0],3],VN),l=Ee([s,a,i],1),{waveform:c}=await fe(this.sessions.conditional_decoder,{speech_tokens:l,speaker_features:o,speaker_embeddings:n});return c}};var fu=class extends y{},N_=class extends fu{};var Cn=class extends y{},z_=class extends Cn{},Zo=class extends Cn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},ea=class extends Cn{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{},$_=class extends mr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},ta=class extends mr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},D_=class extends mr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}},B_=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 ra=class extends y{},U_=class extends ra{},F_=class extends ra{};var sa=class extends y{},G_=class extends sa{},j_=class extends sa{};var na=class extends y{},q_=class extends na{},W_=class extends na{};var oa=class extends y{},V_=class extends oa{},H_=class extends oa{};var Qr=class extends y{},X_=class extends Qr{},K_=class extends Qr{async _call(e){return new we(await super._call(e))}},Y_=class extends Qr{async _call(e){return new j(await super._call(e))}},Q_=class extends Qr{async _call(e){return new _e(await super._call(e))}},J_=class extends Qr{async _call(e){return new Te(await super._call(e))}};var aa=class extends y{},Z_=class extends aa{},eg=class extends aa{async _call(e){return new j(await super._call(e))}};var ia=class extends y{},tg=class extends ia{},rg=class extends ia{async _call(e){return new j(await super._call(e))}};var la=class extends y{},sg=class extends la{},ng=class extends la{async _call(e){return new hr(await super._call(e))}},hr=class extends $e{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var ca=class extends y{},og=class extends ca{},ag=class extends ca{async _call(e){return new hr(await super._call(e))}};var du=class extends $e{constructor({audio_codes:e}){super(),this.audio_codes=e}},mu=class extends $e{constructor({audio_values:e}){super(),this.audio_values=e}},Pn=class extends y{main_input_name="input_values";forward_params=["input_values"]},ig=class extends Pn{async encode(e){return new du(await fe(this.sessions.encoder_model,e))}async decode(e){return new mu(await fe(this.sessions.decoder_model,e))}},ua=class extends Pn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},pa=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 Jr=class extends y{},lg=class extends Jr{},cg=class extends Jr{async _call(e){return new we(await super._call(e))}},ug=class extends Jr{async _call(e){return new j(await super._call(e))}},pg=class extends Jr{async _call(e){return new _e(await super._call(e))}},fg=class extends Jr{async _call(e){return new Te(await super._call(e))}};var Zr=class extends y{},dg=class extends Zr{},mg=class extends Zr{async _call(e){return new we(await super._call(e))}},hg=class extends Zr{async _call(e){return new j(await super._call(e))}},_g=class extends Zr{async _call(e){return new _e(await super._call(e))}},gg=class extends Zr{async _call(e){return new Te(await super._call(e))}};var hu=class extends y{},wg=class extends hu{};var fa=class extends y{},xg=class extends fa{},yg=class extends fa{async _call(e){return new j(await super._call(e))}};var _u=class extends y{},bg=class extends _u{};var gu=class extends y{},vg=class extends gu{};var Ln=class extends y{},kg=class extends Ln{},Eg=class extends Ln{async _call(e){return new Nn(await super._call(e))}},Ag=class extends Ln{async _call(e){return new wu(await super._call(e))}},Nn=class extends $e{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}},wu=class extends $e{constructor({logits:e,pred_boxes:r,pred_masks:s}){super(),this.logits=e,this.pred_boxes=r,this.pred_masks=s}};var da=class extends y{},Tg=class extends da{},Mg=class extends da{async _call(e){return new j(await super._call(e))}};var ma=class extends y{},Sg=class extends ma{},Og=class extends ma{async _call(e){return new j(await super._call(e))}};var xu=class extends y{},Ig=class extends xu{};var yu=class extends y{},Cg=class extends yu{};var es=class extends y{},Pg=class extends es{},Lg=class extends es{async _call(e){return new j(await super._call(e))}},Ng=class extends es{async _call(e){return new _e(await super._call(e))}},zg=class extends es{async _call(e){return new Te(await super._call(e))}},Rg=class extends es{async _call(e){return new we(await super._call(e))}};var bu=class extends y{},$g=class extends bu{};var ha=class extends y{},Dg=class extends ha{},Bg=class extends ha{};var _a=class extends y{},Ug=class extends _a{},Fg=class extends _a{async _call(e){return new j(await super._call(e))}};var ts=class extends y{},Gg=class extends ts{},jg=class extends ts{async _call(e){return new we(await super._call(e))}},qg=class extends ts{async _call(e){return new j(await super._call(e))}},Wg=class extends ts{async _call(e){return new _e(await super._call(e))}},Vg=class extends ts{async _call(e){return new Te(await super._call(e))}};var ga=class extends y{},Hg=class extends ga{},Xg=class extends ga{};var Ds=class extends y{},Kg=class extends Ds{},Yg=class extends Ds{async _call(e){return new we(await super._call(e))}},Qg=class extends Ds{async _call(e){return new j(await super._call(e))}},Jg=class extends Ds{async _call(e){return new _e(await super._call(e))}};var wa=class extends y{},Zg=class extends wa{},ew=class extends wa{};var xa=class extends y{},tw=class extends xa{},rw=class extends xa{};var ya=class extends y{},sw=class extends ya{},nw=class extends ya{};var ba=class extends y{},ow=class extends ba{},aw=class extends ba{async _call(e){return new j(await super._call(e))}};var vu=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"},iw=class extends vu{_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([st(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:c}){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 Ht(this,{inputs_embeds:l,attention_mask:s});a=f}if(!c){if(!n)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");c=await this.encode_text({input_ids:n})}return await Lt(this,{inputs_embeds:c,attention_mask:o,encoder_attention_mask:s,encoder_hidden_states:a,past_key_values:i},!0)}};var va=class extends y{},lw=class extends va{},cw=class extends va{};var ka=class extends y{},uw=class extends ka{},pw=class extends ka{};var Ea=class extends y{},fw=class extends Ea{},dw=class extends Ea{};var ku=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"]},zn=class extends ku{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:c=null,generation_config:p=null,logits_processor:f=null,...m}){if((!i||!l)&&({inputs_embeds:i,per_layer_inputs:l}=await fe(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(s){let{image_features:w}=await fe(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 fe(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 Lt(this,{inputs_embeds:i,per_layer_inputs:l,past_key_values:c,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 On({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 uu({audio_token_id:this.config.audio_token_id,...e,audio_features:s})}},Aa=class extends zn{};var Ta=class extends y{},mw=class extends Ta{},hw=class extends Ta{};var Ma=class extends y{},_w=class extends Ma{},gw=class extends Ma{};var Sa=class extends y{},ww=class extends Sa{},xw=class extends Sa{};var Oa=class extends y{},yw=class extends Oa{},bw=class extends Oa{};var Ia=class extends y{},vw=class extends Ia{},kw=class extends Ia{};var Ca=class extends y{},Ew=class extends Ca{},Aw=class extends Ca{};var Pa=class extends y{},Tw=class extends Pa{},Mw=class extends Pa{};var La=class extends y{},Sw=class extends La{},Ow=class extends La{};var Na=class extends y{},Iw=class extends Na{},Cw=class extends Na{};var za=class extends y{},Pw=class extends za{},Lw=class extends za{};var Eu=class extends y{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},Bs=class extends Eu{_merge_input_ids_with_audio_features(e){let r=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,r);return uu({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:s})}};var Nw=class extends Bs{forward_params=["input_ids","attention_mask","input_features","past_key_values"]};var Au=class extends y{},zw=class extends Au{};var Tu=class extends y{},Rw=class extends Tu{};var Ra=class extends y{},$w=class extends Ra{},Dw=class extends Ra{};var $a=class extends y{},Bw=class extends $a{},Uw=class extends $a{async _call(e){return new j(await super._call(e))}};var or=class extends y{},Fw=class extends or{},Gw=class extends or{async _call(e){return new At(await super._call(e))}},jw=class extends or{async _call(e){return new j(await super._call(e))}},qw=class extends or{async _call(e){return new _e(await super._call(e))}};var Ww=class extends y{},Vw=class extends or{},Hw=class extends or{async _call(e){return new At(await super._call(e))}},Xw=class extends or{async _call(e){return new j(await super._call(e))}};var Da=class extends y{},Kw=class extends Da{},Yw=class extends Da{};var Mu=class extends y{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},Xt=class extends Mu{_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return On({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:s})}},Qw=class extends Xt{},Jw=class extends Xt{};var Zw=class extends Xt{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]};var Ba=class extends y{},ex=class extends Ba{},tx=class extends Ba{async _call(e){return new j(await super._call(e))}};var Ua=class extends y{},rx=class extends Ua{},sx=class extends Ua{};var Rn=class extends y{},nx=class extends Rn{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=st([e.pixel_values.dims[0],1])),s){let{image_size:c}=this.config.vision_config;e.pixel_values=Xe([0,3,c,c],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}},Fa=class extends Rn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},ox=class extends Rn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var Ga=class extends y{},ax=class extends Ga{},ix=class extends Ga{};var ja=class extends y{},lx=class extends ja{},cx=class extends ja{};var ux=class extends Xt{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"]};var qa=class extends y{},px=class extends qa{},fx=class extends qa{};var Su=class extends y{},dx=class extends Su{};var Wa=class extends y{},mx=class extends Wa{},hx=class extends Wa{};var Va=class extends y{},_x=class extends Va{},gx=class extends Va{};var Ha=class extends y{},wx=class extends Ha{},xx=class extends Ha{};var Xa=class extends y{},yx=class extends Xa{},bx=class extends Xa{};var Us=class extends y{},vx=class extends Us{},kx=class extends Us{},Ex=class extends Us{async _call(e){return new j(await super._call(e))}},Ax=class extends Us{};var Ou=class extends y{},Tx=class extends Ou{};var Iu=class extends y{},Mx=class extends Iu{};var Cu=class extends $e{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{},Sx=class extends Pu{async _call(e){return new Cu(await super._call(e))}};var Lu=class extends $e{constructor({audio_codes:e}){super(),this.audio_codes=e}},Nu=class extends $e{constructor({audio_values:e}){super(),this.audio_values=e}},$n=class extends y{main_input_name="input_values";forward_params=["input_values"]},Ox=class extends $n{async encode(e){return new Lu(await fe(this.sessions.encoder_model,e))}async decode(e){return new Nu(await fe(this.sessions.decoder_model,e))}},Ka=class extends $n{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},Ya=class extends $n{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var Qa=class extends y{},Ix=class extends Qa{},Cx=class extends Qa{};var Fs=class extends y{},Px=class extends Fs{},Lx=class extends Fs{async _call(e){return new we(await super._call(e))}},Nx=class extends Fs{async _call(e){return new j(await super._call(e))}},zx=class extends Fs{async _call(e){return new Te(await super._call(e))}};var Ja=class extends y{},Rx=class extends Ja{},$x=class extends Ja{};var Dn=class extends y{},Dx=class extends Dn{},Bx=class extends Dn{async _call(e){return new j(await super._call(e))}},Ux=class extends Dn{};var Bn=class extends y{},Fx=class extends Bn{},Gx=class extends Bn{async _call(e){return new j(await super._call(e))}},jx=class extends Bn{};var Un=class extends y{},qx=class extends Un{},Wx=class extends Un{async _call(e){return new j(await super._call(e))}},Vx=class extends Un{};var Fn=class extends y{},Hx=class extends Fn{},Xx=class extends Fn{async _call(e){return new j(await super._call(e))}},Kx=class extends Fn{};var Za=class extends y{},Yx=class extends Za{},Qx=class extends Za{async _call(e){return new j(await super._call(e))}};var ei=class extends y{},Jx=class extends ei{},Zx=class extends ei{async _call(e){return new j(await super._call(e))}};var Gs=class extends y{},ey=class extends Gs{},ty=class extends Gs{async _call(e){return new we(await super._call(e))}},ry=class extends Gs{async _call(e){return new j(await super._call(e))}},sy=class extends Gs{async _call(e){return new _e(await super._call(e))}};var ti=class extends y{},ny=class extends ti{},oy=class extends ti{};var ri=class extends y{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},ay=class extends ri{},iy=class extends ri{};var rs=class extends y{},ly=class extends rs{},cy=class extends rs{async _call(e){return new we(await super._call(e))}},uy=class extends rs{async _call(e){return new j(await super._call(e))}},py=class extends rs{async _call(e){return new _e(await super._call(e))}},fy=class extends rs{async _call(e){return new Te(await super._call(e))}};var si=class extends y{},dy=class extends si{},my=class extends si{};var ni=class extends y{},hy=class extends ni{},_y=class extends ni{};var zu=class extends y{},gy=class extends zu{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,c=Ye(e,l.inputNames);s=await fe(l,c)}else{let l=this.sessions.gen_img_embeds,c=Ye({image_ids:e.input_ids},l.inputNames);s=await fe(l,c)}let n={...e,...s},o=await Lt(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 fe(a,Ye(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,Mo(r.input_ids,BigInt(s.pad_token_id))],0),r.attention_mask=Ee([r.attention_mask,Mo(r.attention_mask,0n)],0))),(n||!r.pixel_values)&&(r.pixel_values=Xe([0,0,3,384,384],1)),n&&(r.images_seq_mask=new R("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),r.images_emb_mask=new R("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 fe(o,{generated_tokens:n}),i=a.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),l=[];for(let c of i){let p=Qe.fromTensor(c);l.push(p)}return l}};var oi=class extends y{},wy=class extends oi{},xy=class extends oi{},ai=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 c=0;c<e.size;++c){if(e.data[c]==this.config.decoder.pad_token_id)continue;let p=c%s,f=Math.floor(c/s)%n,m=p-f;m>0&&m<=o&&(e.data[a++]=e.data[c])}let i=Math.floor(r/n),l=a/(i*n);return new R(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)),jo(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 fe(this.sessions.encodec_decode,{audio_codes:s});return n}};var ii=class extends y{},yy=class extends ii{},by=class extends ii{};var ss=class extends y{},vy=class extends ss{},ky=class extends ss{async _call(e){return new we(await super._call(e))}},Ey=class extends ss{async _call(e){return new j(await super._call(e))}},Ay=class extends ss{async _call(e){return new _e(await super._call(e))}},Ty=class extends ss{async _call(e){return new Te(await super._call(e))}};var Ru=class extends y{},My=class extends Ru{};var li=class extends y{},Sy=class extends li{},Oy=class extends li{};var ci=class extends y{},Iy=class extends ci{},Cy=class extends ci{};var ui=class extends y{},Py=class extends ui{},Ly=class extends ui{};var pi=class extends y{},Ny=class extends pi{},zy=class extends pi{};var fi=class extends y{},Ry=class extends fi{},$y=class extends fi{};var di=class extends y{},Dy=class extends di{},By=class extends di{};var mi=class extends y{},Uy=class extends mi{},Fy=class extends mi{};var hi=class extends y{},Gy=class extends hi{},jy=class extends hi{};var qy=class extends Xt{};var $u=class extends y{},Wy=class extends $u{async _call(e){return new At(await super._call(e))}};var _i=class extends y{},Vy=class extends _i{},Hy=class extends _i{};var gi=class extends y{},Xy=class extends gi{},Ky=class extends gi{};var wi=class extends y{},Yy=class extends wi{},Qy=class extends wi{};var xi=class extends y{},Jy=class extends xi{},Zy=class extends xi{};var Du=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},yi=class extends Du{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:c=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 fe(this.sessions.vision_encoder,{pixel_values:s,image_sizes:n}))}else{let h=this.config.normalized_config.hidden_size;m=new R("float32",[],[0,h])}({inputs_embeds:a}=await fe(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:m}))}return await Lt(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,position_ids:o,generation_config:l,logits_processor:c},!1)}};var bi=class extends y{},e0=class extends bi{},t0=class extends bi{async _call(e){return new j(await super._call(e))}};var vi=class extends y{},r0=class extends vi{},s0=class extends vi{async _call(e){return new _e(await super._call(e))}};var ki=class extends y{},n0=class extends ki{},o0=class extends ki{};var Ei=class extends y{},a0=class extends Ei{},i0=class extends Ei{};var Bu=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},Gn=class extends Bu{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,c=o.spatial_merge_size??2,p=[];if(r||s){let f=e.tolist();n||(n=yc(e));let m=n.tolist(),h=Array.from({length:3},A=>Array.from({length:e.dims[0]},S=>Array.from({length:e.dims[1]},M=>1))),w=r?r.tolist():[],x=s?s.tolist():[],v=0,E=0;for(let A=0;A<f.length;++A){let S=f[A].filter((P,N)=>m[A][N]==1),L=S.reduce((P,N,$)=>(N==l&&P.push($),P),[]).map(P=>S[P+1]),O=L.filter(P=>P==a).length,k=L.filter(P=>P==i).length,G=[],H=0,U=O,V=k;for(let P=0;P<L.length;++P){let N=S.findIndex((It,ot)=>ot>H&&It==a),$=S.findIndex((It,ot)=>ot>H&&It==i),J=U>0&&N!==-1?N:S.length+1,Ie=V>0&&$!==-1?$:S.length+1,ae,Fe,Je,tt;J<Ie?([Fe,Je,tt]=w[v],++v,--U,ae=J):([Fe,Je,tt]=x[E],++E,--V,ae=Ie);let[nt,at,Me]=[Number(Fe),Math.floor(Number(Je)/c),Math.floor(Number(tt)/c)],xe=ae-H,We=G.length>0?Ce(G.at(-1))[0]+1:0;G.push(Array.from({length:3*xe},(It,ot)=>We+ot%xe));let Ot=xe+We,ve=nt*at*Me,De=Array.from({length:ve},(It,ot)=>Ot+Math.floor(ot/(at*Me))),Ir=Array.from({length:ve},(It,ot)=>Ot+Math.floor(ot/Me)%at),us=Array.from({length:ve},(It,ot)=>Ot+ot%Me);G.push([De,Ir,us].flat()),H=ae+ve}if(H<S.length){let P=G.length>0?Ce(G.at(-1))[0]+1:0,N=S.length-H;G.push(Array.from({length:3*N},($,J)=>P+J%N))}let q=G.reduce((P,N)=>P+N.length,0),Y=new Array(q),B=0;for(let P=0;P<3;++P)for(let N=0;N<G.length;++N){let $=G[N],J=$.length/3;for(let Ie=P*J;Ie<(P+1)*J;++Ie)Y[B++]=$[Ie]}let C=0,te=m[A];for(let P=0;P<te.length;++P)if(te[P]==1){for(let N=0;N<3;++N)h[N][A][P]=Y[N*q/3+C];++C}let le=Ce(Y)[0];p.push(le+1-f[A].length)}return[new R("int64",h.flat(1/0),[3,e.dims[0],e.dims[1]]),new R("int64",p,[p.length,1])]}else if(n){let{data:f,dims:m}=e_(n),h=BigInt64Array.from({length:3*f.length},(x,v)=>f[v%f.length]),w=Array.from({length:m[0]},(x,v)=>Ce(f.subarray(m[1]*v,m[1]*(v+1)))[0]+1n+BigInt(m[1]));return[new R("int64",h,[3,...m]),new R("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 R("int64",h,[3,...e.dims]),xd([f,1])]}}async encode_image({pixel_values:e,image_grid_thw:r}){return(await fe(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:r})).image_features}_merge_input_ids_with_image_features(e){return On({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=r.past_key_values.get_seq_length();if(n<r.input_ids.dims[1]){let[o,a]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask);r.rope_deltas=a,r.position_ids=o.slice(null,null,[n,null]),r.input_ids=r.input_ids.slice(null,[n,null])}else{r.rope_deltas||([,r.rope_deltas]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask));let o=BigInt(n),a=r.rope_deltas.map(i=>o+i);r.position_ids=Pt([a,a,a],0)}}return r}},js=class extends Gn{};var Ai=class extends Gn{image_grid_thw_name="image_grid_thw"},qs=class extends js{image_grid_thw_name="image_grid_thw"};var Ti=class extends y{},l0=class extends Ti{},c0=class extends Ti{};var Mi=class extends y{},u0=class extends Mi{},p0=class extends Mi{};var Si=class extends y{},f0=class extends Si{},d0=class extends Si{};var Ws=class extends Ai{},Vs=class extends qs{};var m0=class extends Ws{},Oi=class extends Vs{};var jn=class extends Ws{},Hs=class extends jn{};var h0=class extends jn{},Ii=class extends Hs{};var Ci=class extends y{},_0=class extends Ci{},g0=class extends Ci{async _call(e){return new j(await super._call(e))}};var Pi=class extends y{},w0=class extends Pi{},x0=class extends Pi{async _call(e){return new Uu(await super._call(e))}},Uu=class extends hr{};var ns=class extends y{},y0=class extends ns{},b0=class extends ns{async _call(e){return new we(await super._call(e))}},v0=class extends ns{async _call(e){return new j(await super._call(e))}},k0=class extends ns{async _call(e){return new _e(await super._call(e))}},E0=class extends ns{async _call(e){return new Te(await super._call(e))}};var os=class extends y{},A0=class extends os{},T0=class extends os{async _call(e){return new we(await super._call(e))}},M0=class extends os{async _call(e){return new j(await super._call(e))}},S0=class extends os{async _call(e){return new _e(await super._call(e))}},O0=class extends os{async _call(e){return new Te(await super._call(e))}};var Li=class extends y{},I0=class extends Li{},C0=class extends Li{async _call(e){return new Fu(await super._call(e))}},Fu=class extends hr{};var Gu=class extends $e{constructor({iou_scores:e,pred_masks:r}){super(),this.iou_scores=e,this.pred_masks=r}},ju=class extends y{},P0=class extends ju{async get_image_embeddings({pixel_values:e}){return await Ht(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??=st(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 fe(this.sessions.prompt_encoder_mask_decoder,r)}async _call(e){return new Gu(await super._call(e))}};var qu=class extends $e{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}},Wu=class extends y{},Ni=class extends Wu{async get_image_embeddings({pixel_values:e}){return await Ht(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??=st(a.slice(0,-1)),e.input_boxes??=Xe([a[0],0,4],0)}else if(e.input_boxes){let a=e.input_boxes.dims;e.input_labels=Xe([a[0],a[1],0],-1n),e.input_points=Xe([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=Ye(e,n.inputNames);return await fe(n,o)}async _call(e){return new qu(await super._call(e))}},L0=class extends Ni{},N0=class extends Ni{};var qn=class extends y{},z0=class extends qn{},R0=class extends qn{},$0=class extends qn{};var Wn=class extends y{},D0=class extends Wn{},B0=class extends Wn{},U0=class extends Wn{};var zi=class extends y{},F0=class extends zi{},Ri=class extends zi{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},G0=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 $i=class extends y{},j0=class extends $i{},q0=class extends $i{};var Vn=class extends y{main_input_name="input_values";forward_params=["input_values"]},W0=class extends Vn{async encode(e){return await fe(this.sessions.encoder_model,e)}async decode(e){return await fe(this.sessions.decoder_model,e)}},Di=class extends Vn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},Bi=class extends Vn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var Hn=class extends y{},V0=class extends Hn{},H0=class extends Hn{},X0=class extends Hn{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:c}=await Ht(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,v=null,E=0;for(;;){++E;let M=Zh(!!v),L;v?L=v.output_sequence_out:L=new R("float32",new Float32Array(h),[1,1,h]);let O={use_cache_branch:M,output_sequence:L,encoder_attention_mask:c,speaker_embeddings:r,encoder_hidden_states:l};this.addPastKeyValues(O,x),v=await fe(this.sessions.decoder_model_merged,O),x=this.getPastKeyValues(v,x);let{prob:k,spectrum:G}=v;if(w.push(G),E>=m&&(Array.from(k.data).filter(H=>H>=s).length>0||E>=f))break}let A=Ee(w),{waveform:S}=await fe(a.sessions.model,{spectrogram:A});return{spectrogram:A,waveform:S}}},K0=class extends y{main_input_name="spectrogram"};var Xs=class extends y{},Y0=class extends Xs{},Q0=class extends Xs{async _call(e){return new we(await super._call(e))}},J0=class extends Xs{async _call(e){return new j(await super._call(e))}},Z0=class extends Xs{async _call(e){return new Te(await super._call(e))}};var Ui=class extends y{},eb=class extends Ui{},tb=class extends Ui{};var Fi=class extends y{},rb=class extends Fi{},sb=class extends Fi{};var Vu=class extends y{},nb=class extends Vu{};var Hu=class extends y{},Gi=class extends Hu{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:c}=this.config,{last_hidden_state:p,durations:f}=await fe(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,U=>Math.ceil(U/h)),v=Math.max(...x),E=e.dims[0],A=new BigInt64Array(E*v);for(let U=0;U<E;++U)A.fill(1n,U*v,U*v+x[U]);let S=new R("int64",A,[E,v]),M=c*i,L=M*v,O=m2([E,M,v]),k=O.data;for(let U=0;U<E;++U)if(x[U]!==v)for(let V=0;V<M;++V)k.fill(0,U*L+V*v+x[U],U*L+(V+1)*v);let G=Xe([E],n);for(let U=0;U<n;++U){let V=Xe([E],U);({denoised_latents:O}=await fe(this.sessions.latent_denoiser,{style:s,noisy_latents:O,latent_mask:S,encoder_outputs:p,attention_mask:r,timestep:V,num_inference_steps:G}))}let{waveform:H}=await fe(this.sessions.voice_decoder,{latents:O});return{waveform:H,durations:m}}};var Xn=class extends y{},ob=class extends Xn{},ab=class extends Xn{async _call(e){return new j(await super._call(e))}},ib=class extends Xn{};var ji=class extends y{},lb=class extends ji{},cb=class extends ji{};var qi=class extends y{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]},ub=class extends qi{},pb=class extends qi{};var Wi=class extends y{},fb=class extends Wi{},db=class extends Wi{async _call(e){return new Xu(await super._call(e))}},Xu=class extends Nn{};var Ku=class extends y{},mb=class extends Ku{};var Kn=class extends y{},hb=class extends Kn{},_b=class extends Kn{async _call(e){return new At(await super._call(e))}},gb=class extends Kn{async _call(e){return new j(await super._call(e))}};var Ks=class extends y{},wb=class extends Ks{},xb=class extends Ks{async _call(e){return new At(await super._call(e))}},yb=class extends Ks{async _call(e){return new j(await super._call(e))}},bb=class extends Ks{async _call(e){return new _e(await super._call(e))}};var Vi=class extends y{},vb=class extends Vi{},kb=class extends Vi{};var Eb=class extends y{main_input_name="pixel_values";forward_params=["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"]};var Hi=class extends y{},Ab=class extends Hi{},Tb=class extends Hi{async _call(e){return new j(await super._call(e))}};var Yu=class extends y{},Mb=class extends Yu{};var Xi=class extends y{},Sb=class extends Xi{},Ob=class extends Xi{async _call(e){return new j(await super._call(e))}};var Qu=class extends y{},Ib=class extends Qu{async _call(e){return new Kc(await super._call(e))}};var Ju=class extends y{},Cb=class extends Ju{};var Zu=class extends $e{constructor({waveform:e,spectrogram:r}){super(),this.waveform=e,this.spectrogram=r}},ep=class extends y{},Pb=class extends ep{async _call(e){return new Zu(await super._call(e))}};var Lb=class extends Bs{};var V2=2,HN=1,Nb=new WeakMap;function XN(t,e){let{text_config:r,audio_config:s}=t.config,n=t.sessions.audio_encoder,{num_mel_bins:o,hidden_size:a}=s,i=o+a,l=new Fo,c=n?.config?.kv_cache_dtype??"float32",p=c==="float16"?Er.float16:Er.float32,f=Ps(s,{batch_size:1});for(let w in f){let x=f[w].reduce((v,E)=>v*E,1);l[w]=new R(c,new p(x),f[w])}let m=new R(c,new p(i*V2),[1,i,V2]),h=e[Symbol.asyncIterator]?.()??e[Symbol.iterator]?.();if(!h)throw new Error("input_features must be iterable or async iterable");return{encoder_session:n,enc_kv_cache:l,enc_padding_cache:m,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:h,text_hidden_size:r.hidden_size}}async function KN(t,e){let r=e.dims[2],s=Math.floor((HN+r-3)/2)+1,n=new R("int64",BigInt64Array.from({length:s},(p,f)=>BigInt(t.enc_past_seq_len+f)),[1,s]),o=t.enc_past_seq_len+s,a=st([1,o]),{audio_embeds:i,present_padding_cache:l,...c}=await fe(t.encoder_session,{input_features:e,attention_mask:a,position_ids:n,past_padding_cache:t.enc_padding_cache,...t.enc_kv_cache});t.enc_padding_cache.location==="gpu-buffer"&&t.enc_padding_cache.dispose(),t.enc_padding_cache=l;for(let p in c)if(p.startsWith("present.")){let f=p.replace("present","past_key_values"),m=t.enc_kv_cache[f];m?.location==="gpu-buffer"&&m.dispose(),t.enc_kv_cache[f]=c[p]}return t.enc_past_seq_len=o,i}async function YN(t,e){for(;t.audio_embed_total_tokens<e&&!t.stream_exhausted;){let r=await t.chunks_iter.next();if(r.done){t.stream_exhausted=!0;break}let s=await KN(t,r.value);t.audio_embed_queue.push({data:s.data,tokens:s.dims[1]}),t.audio_embed_total_tokens+=s.dims[1]}}function QN(t,e,r){if(t.audio_embed_queue.length===0)return;let s=e.data,n=0,o=r;for(;o>0&&t.audio_embed_queue.length>0;){let a=t.audio_embed_queue[0],i=a.tokens-t.audio_queue_offset,l=Math.min(o,i),c=t.audio_queue_offset*t.text_hidden_size;for(let p=0;p<l*t.text_hidden_size;++p)s[n*t.text_hidden_size+p]+=a.data[c+p];n+=l,o-=l,t.audio_queue_offset+=l,t.audio_queue_offset>=a.tokens&&(t.audio_embed_queue.shift(),t.audio_queue_offset=0)}t.audio_consumed+=r-o}var zb=class extends Xr{constructor(e){super(),this._s=e}_call(e){let r=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return e.map(()=>r)}},tp=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values"]},Ki=class extends tp{async forward({input_ids:e,past_key_values:r,...s}){let n=e.dims[1],o=Nb.get(this);o&&await YN(o,o.audio_consumed+n);let{inputs_embeds:a}=await fe(this.sessions.embed_tokens,{input_ids:e});o&&QN(o,a,n);let i={inputs_embeds:a,...s};this.addPastKeyValues(i,r);let l=this.sessions.decoder_model_merged,c=Ye(i,l.inputNames);return await fe(l,c)}async generate({input_features:e,stopping_criteria:r,...s}){if(!e)throw new Error("input_features (generator/iterable) must be provided");let n=XN(this,e);Nb.set(this,n);let o=new Tn;o.push(new zb(n)),r&&o.extend(r);try{return await super.generate({...s,stopping_criteria:o})}finally{n.enc_kv_cache.dispose(),Nb.delete(this)}}};var Yn=class extends y{},Rb=class extends Yn{},$b=class extends Yn{async _call(e){return new At(await super._call(e))}},Db=class extends Yn{async _call(e){return new j(await super._call(e))}};var rp=class extends $e{constructor({logits:e,embeddings:r}){super(),this.logits=e,this.embeddings=r}},as=class extends y{},Bb=class extends as{},Ub=class extends as{async _call(e){return new At(await super._call(e))}},Fb=class extends as{async _call(e){return new j(await super._call(e))}},Gb=class extends as{async _call(e){return new rp(await super._call(e))}},jb=class extends as{async _call(e){return new _e(await super._call(e))}};var sp=class extends y{},qb=class extends sp{};var np=class extends An{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 Yi=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"]},Wb=class extends Yi{},op=class extends Yi{_prepare_generation_config(e,r){return super._prepare_generation_config(e,r,np)}_retrieve_init_tokens(e){let r=[e.decoder_start_token_id],s=e.language,n=e.task;if(e.is_multilingual){s||(Z.warn("No language specified - defaulting to English (en)."),s="en");let a=`<|${g2(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&&(Z.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 Ls,s.push(new Jc(r,a))),r.begin_suppress_tokens&&(s??=new Ls,s.push(new En(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"&&Z.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&&Z.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&&(Z.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,v)=>Ee(a.map(E=>E[v]),2)),l=Pt(r.map(([x,v])=>{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,v,null,[0,s]):i[x].slice(null,v)})).transpose(1,0,2,3),[c,p]=gd(l,-2,0,!0),f=l.clone();for(let x=0;x<f.dims[0];++x){let v=f[x];for(let E=0;E<v.dims[0];++E){let A=v[E],S=c[x][E][0].data,M=p[x][E][0].data;for(let L=0;L<A.dims[0];++L){let O=A[L].data;for(let k=0;k<O.length;++k)O[k]=(O[k]-M[k])/S[k];O.set(hE(O,o))}}}let m=[xc(f,1)],h=e.sequences.dims,w=new R("float32",new Float32Array(h[0]*h[1]),h);for(let x=0;x<h[0];++x){let v=m[x].neg().squeeze_(0),[E,A]=gE(v.tolist()),S=Array.from({length:E.length-1},(O,k)=>E[k+1]-E[k]),M=xt([1],S).map(O=>!!O),L=[];for(let O=0;O<M.length;++O)M[O]&&L.push(A[O]*n);w[x].data.set(L,1)}return w}},Vb=class extends op{};var is=class extends y{},Hb=class extends is{},Xb=class extends is{async _call(e){return new we(await super._call(e))}},Kb=class extends is{async _call(e){return new j(await super._call(e))}},Yb=class extends is{async _call(e){return new _e(await super._call(e))}},Qb=class extends is{async _call(e){return new Te(await super._call(e))}};var ls=class extends y{},Jb=class extends ls{},Zb=class extends ls{async _call(e){return new we(await super._call(e))}},e1=class extends ls{async _call(e){return new j(await super._call(e))}},t1=class extends ls{async _call(e){return new _e(await super._call(e))}},r1=class extends ls{async _call(e){return new Te(await super._call(e))}};var Qi=class extends y{},s1=class extends Qi{},n1=class extends Qi{async _call(e){return new ap(await super._call(e))}},ap=class extends $e{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var Ji=class extends y{},o1=class extends Ji{},a1=class extends Ji{};var JN=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"]]),ZN=new Map([["t5","T5Model"],["longt5","LongT5Model"],["mt5","MT5Model"],["bart","BartModel"],["mbart","MBartModel"],["marian","MarianModel"],["whisper","WhisperModel"],["m2m_100","M2M100Model"],["blenderbot","BlenderbotModel"],["blenderbot-small","BlenderbotSmallModel"]]),ez=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),tz=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"],["olmo_hybrid","OlmoHybridModel"],["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"],["qwen2_moe","Qwen2MoeModel"],["qwen3","Qwen3Model"],["qwen3_moe","Qwen3MoeModel"],["qwen3_next","Qwen3NextModel"],["phi","PhiModel"],["phi3","Phi3Model"],["mpt","MptModel"],["opt","OPTModel"],["mistral","MistralModel"],["ministral","MinistralModel"],["ministral3","Ministral3Model"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2Model"],["falcon","FalconModel"],["falcon_h1","FalconH1Model"],["stablelm","StableLmModel"],["modernbert-decoder","ModernBertDecoderModel"],["hunyuan_v1_dense","HunYuanDenseV1Model"],["youtu","YoutuModel"]]),H2=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"]]),X2=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),K2=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),Y2=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"]]),Q2=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"]]),J2=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),Z2=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"],["olmo_hybrid","OlmoHybridForCausalLM"],["mobilellm","MobileLLMForCausalLM"],["granite","GraniteForCausalLM"],["granitemoehybrid","GraniteMoeHybridForCausalLM"],["cohere","CohereForCausalLM"],["cohere2","Cohere2ForCausalLM"],["gemma","GemmaForCausalLM"],["gemma2","Gemma2ForCausalLM"],["vaultgemma","VaultGemmaForCausalLM"],["gemma3_text","Gemma3ForCausalLM"],["gemma3","Gemma3ForCausalLM"],["helium","HeliumForCausalLM"],["glm","GlmForCausalLM"],["openelm","OpenELMForCausalLM"],["qwen2","Qwen2ForCausalLM"],["qwen2_moe","Qwen2MoeForCausalLM"],["qwen3","Qwen3ForCausalLM"],["qwen3_moe","Qwen3MoeForCausalLM"],["qwen3_next","Qwen3NextForCausalLM"],["qwen2_vl","Qwen2VLForCausalLM"],["qwen2_5_vl","Qwen2_5_VLForCausalLM"],["qwen3_vl","Qwen3VLForCausalLM"],["qwen3_vl_moe","Qwen3VLMoeForCausalLM"],["qwen3_5","Qwen3_5ForCausalLM"],["qwen3_5_moe","Qwen3_5MoeForCausalLM"],["gemma3n","Gemma3nForCausalLM"],["phi","PhiForCausalLM"],["phi3","Phi3ForCausalLM"],["mpt","MptForCausalLM"],["opt","OPTForCausalLM"],["mbart","MBartForCausalLM"],["mistral","MistralForCausalLM"],["ministral","MinistralForCausalLM"],["ministral3","Ministral3ForCausalLM"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2ForCausalLM"],["falcon","FalconForCausalLM"],["falcon_h1","FalconH1ForCausalLM"],["trocr","TrOCRForCausalLM"],["stablelm","StableLmForCausalLM"],["modernbert-decoder","ModernBertDecoderForCausalLM"],["hunyuan_v1_dense","HunYuanDenseV1ForCausalLM"],["youtu","YoutuForCausalLM"],["phi3_v","Phi3VForCausalLM"]]),rz=new Map([["multi_modality","MultiModalityCausalLM"]]),eT=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"]]),tT=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"]]),rT=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),sT=new Map([["llava","LlavaForConditionalGeneration"],["llava_onevision","LlavaOnevisionForConditionalGeneration"],["moondream1","Moondream1ForConditionalGeneration"],["florence2","Florence2ForConditionalGeneration"],["qwen2_vl","Qwen2VLForConditionalGeneration"],["qwen2_5_vl","Qwen2_5_VLForConditionalGeneration"],["qwen3_vl","Qwen3VLForConditionalGeneration"],["qwen3_vl_moe","Qwen3VLMoeForConditionalGeneration"],["qwen3_5","Qwen3_5ForConditionalGeneration"],["qwen3_5_moe","Qwen3_5MoeForConditionalGeneration"],["lfm2_vl","Lfm2VlForConditionalGeneration"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"],["paligemma","PaliGemmaForConditionalGeneration"],["llava_qwen2","LlavaQwen2ForCausalLM"],["gemma3n","Gemma3nForConditionalGeneration"],["mistral3","Mistral3ForConditionalGeneration"]]),nT=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),sz=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),oT=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"]]),aT=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),iT=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),Qn=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),lT=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),cT=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),uT=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),pT=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),fT=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),dT=new Map([["wavlm","WavLMForXVector"]]),mT=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),hT=new Map([["vitmatte","VitMatteForImageMatting"]]),nz=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),_T=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),gT=new Map([["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),wT=new Map([["sapiens","SapiensForNormalEstimation"]]),xT=new Map([["vitpose","VitPoseForPoseEstimation"]]),yT=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),i1=[[JN,K.EncoderOnly],[ZN,K.EncoderDecoder],[tz,K.DecoderOnlyWithoutHead],[ez,K.AutoEncoder],[Y2,K.EncoderOnly],[Q2,K.EncoderOnly],[J2,K.Seq2Seq],[H2,K.Seq2Seq],[Z2,K.DecoderOnly],[rz,K.MultiModality],[eT,K.EncoderOnly],[tT,K.EncoderOnly],[rT,K.Vision2Seq],[sT,K.ImageTextToText],[nT,K.AudioTextToText],[oT,K.EncoderOnly],[Qn,K.EncoderOnly],[cT,K.EncoderOnly],[lT,K.EncoderOnly],[hT,K.EncoderOnly],[nz,K.EncoderOnly],[_T,K.EncoderOnly],[gT,K.EncoderOnly],[wT,K.EncoderOnly],[xT,K.EncoderOnly],[aT,K.EncoderOnly],[iT,K.EncoderOnly],[uT,K.MaskGeneration],[pT,K.EncoderOnly],[fT,K.EncoderOnly],[X2,K.Seq2Seq],[K2,K.EncoderOnly],[dT,K.EncoderOnly],[mT,K.EncoderOnly],[yT,K.EncoderOnly]];for(let[t,e]of i1)for(let r of t.values()){nr.set(r,e);let s=Zi[r];Rs.set(s,r),cu.set(r,s)}var oz=[["MusicgenForConditionalGeneration",ai,K.Musicgen],["Phi3VForCausalLM",yi,K.Phi3V],["CLIPTextModelWithProjection",ta,K.EncoderOnly],["SiglipTextModel",Ri,K.EncoderOnly],["JinaCLIPTextModel",Fa,K.EncoderOnly],["ClapTextModelWithProjection",Zo,K.EncoderOnly],["ClapAudioModelWithProjection",ea,K.EncoderOnly],["DacEncoderModel",ua,K.EncoderOnly],["DacDecoderModel",pa,K.EncoderOnly],["MimiEncoderModel",Ka,K.EncoderOnly],["MimiDecoderModel",Ya,K.EncoderOnly],["SnacEncoderModel",Di,K.EncoderOnly],["SnacDecoderModel",Bi,K.EncoderOnly],["Gemma3nForConditionalGeneration",zn,K.ImageAudioTextToText],["SupertonicForConditionalGeneration",Gi,K.Supertonic],["ChatterboxModel",Jo,K.Chatterbox],["Qwen2VLForCausalLM",js,K.MultimodalLanguageModelOnly],["Qwen2_5_VLForCausalLM",qs,K.MultimodalLanguageModelOnly],["Qwen3VLForCausalLM",Vs,K.MultimodalLanguageModelOnly],["Qwen3VLMoeForCausalLM",Oi,K.MultimodalLanguageModelOnly],["Qwen3_5ForCausalLM",Hs,K.MultimodalLanguageModelOnly],["Qwen3_5MoeForCausalLM",Ii,K.MultimodalLanguageModelOnly],["Gemma3nForCausalLM",Aa,K.MultimodalLanguageModelOnly],["VoxtralRealtimeForConditionalGeneration",Ki,K.VoxtralRealtime]];for(let[t,e,r]of oz)nr.set(t,r),Rs.set(e,t),cu.set(t,e);var bT=new Map([["modnet",Qn],["birefnet",Qn],["isnet",Qn],["ben",Qn]]);for(let[t,e]of bT.entries())e.set(t,"PreTrainedModel"),nr.set(t,K.EncoderOnly),cu.set(t,y);var vT=new Set(bT.keys());nr.set("PreTrainedModel",K.EncoderOnly);Rs.set(y,"PreTrainedModel");var Ne={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:Y2,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:Q2,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:X2,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:K2,MODEL_FOR_MASKED_LM_MAPPING_NAMES:eT,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:tT,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:oT,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:Qn,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:lT,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:cT,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:aT,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:iT,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:uT,MODEL_FOR_CTC_MAPPING_NAMES:pT,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:fT,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:dT,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:mT,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:sz,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:hT,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:_T,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:gT,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:wT,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:xT,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:yT,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:sT,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:nT,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:J2,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:H2,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:Z2,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:rT};F2(Ne);var Oe=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(let r of this.MODEL_CLASS_MAPPINGS)if(r.has(e))return!0;return this.BASE_IF_FAIL}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:c=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:c,dtype:p,use_external_data_format:f,session_options:m};if(h.config=await Wt.from_pretrained(e,h),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let{model_type:w}=h.config;for(let x of this.MODEL_CLASS_MAPPINGS){let v=x.get(w);if(!v){for(let E of x.values())if(E[0]===w){v=E;break}if(!v)continue}return await Zi[v].from_pretrained(e,h)}if(this.BASE_IF_FAIL)return vT.has(w)||Z.warn(`Unknown model class "${w}", attempting to construct from base class.`),await y.from_pretrained(e,h);throw Error(`Unsupported model type: ${w}`)}},Tr=class extends Oe{static MODEL_CLASS_MAPPINGS=i1.map(e=>e[0]);static BASE_IF_FAIL=!0},el=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},ip=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},Jn=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},lp=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},cp=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},up=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},pp=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},fp=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},dp=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},mp=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},hp=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},tl=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},rl=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},sl=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},_p=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},gp=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]},kT=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]},wp=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_CTC_MAPPING_NAMES]},xp=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]},ET=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]},AT=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]},yp=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]},TT=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]},bp=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},vp=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]},MT=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]},ST=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]},kp=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]},OT=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]},IT=class extends Oe{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function et(t){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(e=>Qe.read(e)))}async function cs(t,e){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(r=>typeof r=="string"||r instanceof URL?hm(r,e):r instanceof Float64Array?new Float32Array(r):r))}function nl(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 rt{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 ol=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"?c=>c.sigmoid():c=>new R("float32",Re(c.data),c.dims),l=[];for(let c of n.logits){let p=i(c),f=await sr(p,r),m=f[0].tolist(),w=f[1].tolist().map((x,v)=>({label:a?a[x]:`LABEL_${x}`,score:m[v]}));r===1?l.push(...w):l.push(w)}return Array.isArray(e)||r===1?l:l[0]}};var al=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 c=0;c<a.dims[0];++c){let p=n.input_ids[c],f=a[c],m=[];for(let h=0;h<f.dims[0];++h){let w=f[h],x=Ce(w.data)[1],v=i?i[x]:`LABEL_${x}`;if(r.includes(v))continue;let E=this.tokenizer.decode([p[h].item()],{skip_special_tokens:!0});if(E==="")continue;let A=Re(w.data);m.push({entity:v,score:A[x],index:h,word:E})}l.push(m)}return s?l:l[0]}};var il=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(),c=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(O=>O==f),v=a[h].tolist(),E=i[h].tolist();for(let O=1;O<v.length;++O)(c[h]==0||O<=x||p.findIndex(k=>k==w[O])!==-1)&&(v[O]=-1/0,E[O]=-1/0);let A=Re(v).map((O,k)=>[O,k]),S=Re(E).map((O,k)=>[O,k]);A[0][0]=0,S[0][0]=0;let M=Ek(A,S).filter(O=>O[0][1]<=O[1][1]).map(O=>[O[0][1],O[1][1],O[0][0]*O[1][0]]).sort((O,k)=>k[2]-O[2]),L=[];for(let O=0;O<Math.min(M.length,s);++O){let[k,G,H]=M[O],U=w.slice(k,G+1),V=this.tokenizer.decode(U,{skip_special_tokens:!0});L.push({answer:V,score:H})}s===1?m.push(...L):m.push(L)}return o?m:m[0]}};var ll=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 c=0;c<l.length;++c){let p=l[c],f=p.findIndex(v=>v==s);if(f===-1)throw Error(`Mask token (${n}) not found in text.`);let m=a[c][f],h=await sr(new R("float32",Re(m.data),m.dims),r),w=h[0].tolist(),x=h[1].tolist();i.push(x.map((v,E)=>{let A=p.slice();return A[f]=v,{score:w[E],token:Number(v),token_str:this.tokenizer.decode([v]),sequence:this.tokenizer.decode(A,{skip_special_tokens:!0})}}))}return Array.isArray(e)?i:i[0]}};var Mr=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 cl=class extends Mr{_key="summary_text"};var ul=class extends Mr{_key="translation_text"};function CT(t){return Array.isArray(t)&&t.every(e=>"role"in e&&"content"in e)}var pl=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(CT(e))e=[e];else if(Array.isArray(e)&&e.every(CT))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 c=this.tokenizer(i,{add_special_tokens:o,padding:!0,truncation:!0,...a}),p=await this.model.generate({...c,...r}),f=this.tokenizer.batch_decode(p,{skip_special_tokens:!0}),m;!l&&c.input_ids.dims.at(-1)>0&&(m=this.tokenizer.batch_decode(c.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 fl=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&&(Z.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&&(Z.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(c=>s.replace("{}",c)),i=n||r.length===1,l=[];for(let c of e){let p=[];for(let h of a){let w=this.tokenizer(c,{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=>Re(h)[1]):Re(p)).map((h,w)=>[h,w]).sort((h,w)=>w[0]-h[0]);l.push({sequence:c,labels:m.map(h=>r[h[1]]),scores:m.map(h=>h[0])})}return o?l:l[0]}};var dl=class extends de{async _call(e,{top_k:r=5}={}){let s=this.processor.feature_extractor.config.sampling_rate,n=await cs(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 sr(new R("float32",Re(p.data),p.dims),r),m=f[0].tolist(),w=f[1].tolist().map((x,v)=>({label:o?o[x]:`LABEL_${x}`,score:m[v]}));a.push(w)}return Array.isArray(e)?a:a[0]}};var ml=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 cs(e,i),c=[];for(let p of l){let f=await this.processor(p),m=await this.model({...a,...f}),h=Re(m.logits_per_audio.data);c.push([...h].map((w,x)=>({score:w,label:r[x]})))}return n?c[0]:c}};var hl=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&&Z.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),r.task&&Z.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 cs(n,o),i=[];for(let l of a){let c=await this.processor(l),f=(await this.model(c)).logits[0],m=[];for(let w of f)m.push(Ce(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),c=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 cs(c,h),x=[];for(let v 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 M=h*n,L=h*a,O=M-2*L,k=0;for(;;){let G=k+M,H=v.subarray(k,G),U=await this.processor(H),V=k===0,q=G>=v.length;if(E.push({stride:[H.length,V?0:L,q?0:L],input_features:U.input_features,is_last:q}),q)break;k+=O}}else E=[{stride:[v.length,0,0],input_features:(await this.processor(v)).input_features,is_last:!0}];for(let M of E){i.num_frames=Math.floor(M.stride[0]/m);let L=await this.model.generate({inputs:M.input_features,...i});s==="word"?(M.tokens=L.sequences.tolist()[0],M.token_timestamps=L.token_timestamps.tolist()[0].map(O=>xs(O,2))):M.tokens=L[0].tolist(),M.stride=M.stride.map(O=>O/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 cs(n,o),i=[];for(let l of a){let c=await this.processor(l),p=Math.floor(l.length/o)*6,f=await this.model.generate({max_new_tokens:p,...r,...c}),m=this.processor.batch_decode(f,{skip_special_tokens:!0})[0];i.push({text:m})}return s?i[0]:i}};var _l=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 me.fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new R("float32",e,[e.length]);else if(!(e instanceof R))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,c=[];for(let p=0;p<a;++p){let f=l?Math.min(Math.ceil(l[p]),i):i,m=p*i;c.push(new Co(o.slice(m,m+f),s))}return Array.isArray(e)?c:c[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:c,durations:p}=await this.model.generate_speech({...i,style:r,num_inference_steps:s,speed:n});return this._postprocess_waveform(e,c,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||(Z.info("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await Tr.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 gl=class extends de{async _call(e,r={}){let s=Array.isArray(e),n=await et(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}),c=this.tokenizer.batch_decode(l,{skip_special_tokens:!0}).map(p=>({generated_text:p.trim()}));a.push(c)}return s?a:a[0]}};var wl=class extends de{async _call(e,{top_k:r=5}={}){let s=await et(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 c=await sr(new R("float32",Re(l.data),l.dims),r),p=c[0].tolist(),m=c[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 PT={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},Ys=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 c=await et(e),p=c.map(A=>[A.height,A.width]),f=await this.processor(c),{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=PT[i];else if(this.processor.image_processor){for(let[A,S]of Object.entries(PT))if(S in this.processor.image_processor){x=this.processor.image_processor[S].bind(this.processor.image_processor),i=A;break}}let v=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 M of A.segments_info){let L=new Uint8ClampedArray(S.data.length);for(let k=0;k<S.data.length;++k)S.data[k]===M.id&&(L[k]=255);let O=new Qe(L,S.dims[1],S.dims[0],1);E.push({score:M.score,label:v[M.label_id],mask:O})}}else if(i==="semantic"){let{segmentation:A,labels:S}=x(w,a??p)[0];for(let M of S){let L=new Uint8ClampedArray(A.data.length);for(let k=0;k<A.data.length;++k)A.data[k]===M&&(L[k]=255);let O=new Qe(L,A.dims[1],A.dims[0],1);E.push({score:null,label:v[M],mask:O})}}else throw Error(`Subtask ${i} not supported.`);else{let S=w[h[0]];for(let M=0;M<p.length;++M){let L=p[M],O=S[M];O.data.some(G=>G<-1e-5||G>1+1e-5)&&O.sigmoid_();let k=await Qe.fromTensor(O.mul_(255).to("uint8")).resize(L[1],L[0]);E.push({label:null,score:null,mask:k})}}return E}};var xl=class extends Ys{async _call(e,r={}){let s=await et(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 yl=class extends de{async _call(e,r,{hypothesis_template:s="This is a photo of {}"}={}){let n=Array.isArray(e),o=await et(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),c=await this.model({...i,pixel_values:l}),p=this.model.config.model_type==="siglip"?m=>m.sigmoid().data:m=>Re(m.data),f=[];for(let m of c.logits_per_image){let w=[...p(m)].map((x,v)=>({score:x,label:r[v]}));w.sort((x,v)=>v.score-x.score),f.push(w)}return n?f:f[0]}};var bl=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 et(e),a=s?null:o.map(h=>[h.height,h.width]),{pixel_values:i,pixel_mask:l}=await this.processor(o),c=await this.model({pixel_values:i,pixel_mask:l}),p=this.processor.image_processor.post_process_object_detection(c,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:nl(w,!s)})));return n?m:m[0]}};var vl=class extends de{async _call(e,r,{threshold:s=.1,top_k:n=null,percentage:o=!1}={}){let a=Array.isArray(e),i=await et(e),l=this.tokenizer(r,{padding:!0,truncation:!0}),c=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=c.pixel_values[f].unsqueeze_(0),x=await this.model({...l,pixel_values:w}),v;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];v=E.boxes.map((A,S)=>({score:E.scores[S],label:E.labels[S],box:nl(A,!o)}))}else{let E=this.processor.image_processor.post_process_object_detection(x,s,h,!0)[0];v=E.boxes.map((A,S)=>({score:E.scores[S],label:r[E.classes[S]],box:nl(A,!o)}))}v.sort((E,A)=>A.score-E.score),n!==null&&(v=v.slice(0,n)),p.push(v)}return a?p:p[0]}};var kl=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 et(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 El=class extends de{async _call(e){let r=await et(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(Qe.fromTensor(i))}return Array.isArray(e)?o:o[0]}};var Al=class extends de{async _call(e){let r=await et(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,c]=i.dims.slice(-2),[p,f]=r[a].size,m=(await Et(i.view(1,1,l,c),{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),v=Qe.fromTensor(x);o.push({predicted_depth:m,depth:v})}return Array.isArray(e)?o:o[0]}};var Tl=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=d2(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=h2(l,o)),l}};var Ml=class extends de{async _call(e,{pool:r=null}={}){let s=await et(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 Zn=Object.freeze({"text-classification":{pipeline:ol,model:el,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{pipeline:al,model:ip,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{pipeline:il,model:dp,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{pipeline:ll,model:fp,default:{model:"onnx-community/ettin-encoder-32m-ONNX",dtype:"fp32"},type:"text"},summarization:{pipeline:cl,model:Jn,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{pipeline:ul,model:Jn,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{pipeline:Mr,model:Jn,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{pipeline:pl,model:pp,default:{model:"onnx-community/Qwen3-0.6B-ONNX",dtype:"q4"},type:"text"},"zero-shot-classification":{pipeline:fl,model:el,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:dl,model:xp,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{pipeline:ml,model:Tr,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{pipeline:hl,model:[lp,wp],default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{pipeline:_l,model:[up,cp],default:{model:"onnx-community/Supertonic-TTS-ONNX",dtype:"fp32"},type:"text"},"image-to-text":{pipeline:gl,model:mp,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:wl,model:hp,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Ys,model:[tl,rl,sl],default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:xl,model:[tl,rl,sl],default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{pipeline:yl,model:Tr,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:bl,model:_p,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{pipeline:vl,model:gp,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{pipeline:kl,model:yp,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:El,model:bp,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Al,model:vp,default:{model:"onnx-community/depth-anything-v2-small"},type:"image"},"feature-extraction":{pipeline:Tl,model:Tr,default:{model:"onnx-community/all-MiniLM-L6-v2-ONNX",dtype:"fp32"},type:"text"},"image-feature-extraction":{pipeline:Ml,model:[kp,Tr],default:{model:"onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX",dtype:"fp32"},type:"image"}}),Ep=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});function az(t,{config:e=null,cache_dir:r=null,local_files_only:s=!1,revision:n="main"}={}){if(e!==null)return Wt.from_pretrained(t,{config:e,cache_dir:r,local_files_only:s,revision:n});let o=JSON.stringify([t,r,s,n]);return Yl(o,()=>Wt.from_pretrained(t,{config:e,cache_dir:r,local_files_only:s,revision:n}))}async function Ap(t,{config:e=null,dtype:r=null,device:s=null,model_file_name:n=null}={}){e=await az(t,{config:e});let o=["config.json"],a=e["transformers.js_config"]??{},i=a.use_external_data_format,l="onnx",c=s??a.device,p=r??a.dtype,f,m=e.architectures||[],h=!1;for(let E of m){let A=nr.get(E);if(A!==void 0){f=A,h=!0;break}}if(!h&&e.model_type){let E=nr.get(e.model_type);if(E!==void 0&&(f=E,h=!0),!h){for(let A of Object.values(zs))if(A.has(e.model_type)){f=nr.get(A.get(e.model_type)),h=!0;break}}}if(!h){let E=m.length>0?m.join(", "):"(none)";Z.warn(`[get_model_files] Architecture(s) not found in MODEL_TYPE_MAPPING: [${E}] for model type '${e.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${Wr}`),f=K.EncoderOnly}let w=(E,A=null)=>{A=A??E;let S=hc(c,E),M=_c(p,E,S),L=Ao[M]??"",O=`${A}${L}.onnx`,k=l?`${l}/${O}`:O;o.push(k);let G=Vh(i,O,E);for(let H of Hh(O,G)){let U=l?`${l}/${H}`:H;o.push(U)}},{sessions:x,optional_configs:v}=G2(f,e,{model_file_name:n});for(let[E,A]of Object.entries(x))w(E,A);if(v)for(let E of Object.values(v))o.push(E);return o}async function Tp(t){if(!t)throw new Error("modelId is required");return(await pr(t,Ar,{})).exists?[Ar]:[]}async function Sr(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 mn(t);i.push(...l)}if(a){let l=await Tp(t);i.push(...l)}return i}async function Or(t,e,r={}){t=Ep[t]??t;let s=Zn[t];if(!s)throw new Error(`Unsupported pipeline task: ${t}. Must be one of [${Object.keys(Zn).join(", ")}]`);let{type:n}=s;return Sr(e,{...r,include_tokenizer:n!=="audio"&&n!=="image",include_processor:n!=="text"})}async function Fae(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:c="onnx",use_external_data_format:p=null,model_file_name:f=null,session_options:m={}}={}){t=Ep[t]??t;let h=Zn[t.split("_",1)[0]];if(!h)throw Error(`Unsupported pipeline: ${t}. Must be one of [${Object.keys(Zn)}]`);e||(e=h.default.model,Z.info(`No model specified. Using default model: "${e}".`),!l&&h.default.dtype&&(l=h.default.dtype));let w=await Or(t,e,{device:i,dtype:l}),x={};r&&(await Promise.all(w.map(async V=>pr(e,V)))).forEach((V,q)=>{V.exists&&(x[w[q]]={loaded:0,total:V.size??0})});let v={progress_callback:r?U=>{if(U.status==="progress"){x[U.file]={loaded:U.loaded,total:U.total};let V=Object.values(x).reduce((B,C)=>B+C.loaded,0),q=Object.values(x).reduce((B,C)=>B+C.total,0),Y=q>0?V/q*100:0;r({status:"progress_total",name:U.name,progress:Y,loaded:V,total:q,files:structuredClone(x)})}r(U)}:void 0,config:s,cache_dir:n,local_files_only:o,revision:a,device:i,dtype:l,subfolder:c,use_external_data_format:p,model_file_name:f,session_options:m},E=w.includes("tokenizer.json"),A=w.includes("preprocessor_config.json"),S=h.model,M;if(Array.isArray(S)){let U=s??await Wt.from_pretrained(e,v),{model_type:V}=U,q=S.find(Y=>Y.supports(V));if(!q)throw Error(`Unsupported model type "${V}" for task "${t}". None of the candidate model classes support this type.`);M=q.from_pretrained(e,{...v,config:U})}else M=S.from_pretrained(e,v);let[L,O,k]=await Promise.all([E?oe.from_pretrained(e,v):null,A?Xc.from_pretrained(e,v):null,M]),G={task:t,model:k};L&&(G.tokenizer=L),O&&(G.processor=O),vr(r,{status:"ready",task:t,model:e});let H=h.pipeline;return new H(G)}var iz=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,l1=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},LT=ie.IS_PROCESS_AVAILABLE?t=>process.stdout.write(t):t=>console.log(t),c1=class extends l1{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??LT,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=xt(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&&iz(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===LT&&ie.IS_PROCESS_AVAILABLE&&this.callback_function?.(`
27
+ `)}},NT=class extends c1{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:c=!0,decode_kwargs:p={}}={}){super(e,{skip_prompt:r,skip_special_tokens:c,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 Sl=class{constructor(e,r){this.image=e,this.timestamp=r}},Mp=class{constructor(e,r){e.length>0&&e[0]instanceof Qe&&(e=e.map((s,n)=>new Sl(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 lz(t,{num_frames:e=null,fps:r=null}={}){if(!ie.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 me.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 c=document.createElement("canvas");c.width=n.videoWidth,c.height=n.videoHeight;let p=c.getContext("2d",{willReadFrequently:!0});for(let f of l){n.currentTime=f,await new Promise(x=>{n.onseeked=x}),p.drawImage(n,0,0,c.width,c.height);let m=p.getImageData(0,0,c.width,c.height),h=new Qe(m.data,c.width,c.height,4),w=new Sl(h,f);s.push(w)}return n.remove(),new Mp(s,o)}async function Sp(t,e,r={}){let s=await tr(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}=Rr(t,o,r,s),l=await $r(s,a,i);return{file:o,cached:!!l}}));return{allCached:n.every(o=>o.cached),files:n}}async function zT(t,e,r={}){let s=await tr(r?.cache_dir);if(!s)return!1;let{localPath:n,proposedCacheKey:o}=Rr(t,e,r,s);return!!await $r(s,n,o)}async function RT(t,e={}){if(!t)throw new Error("modelId is required");if(!await zT(t,"config.json",e))return!1;let r=await Sr(t,e);return(await Sp(t,r,e)).allCached}async function $T(t,e={}){if(!t)throw new Error("modelId is required");let r=await Sr(t,e);return await Sp(t,r,e)}async function DT(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");if(!await zT(e,"config.json",r))return!1;let s=await Or(t,e,r);return(await Sp(e,s,r)).allCached}async function BT(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await Or(t,e,r);return await Sp(e,s,r)}async function UT(t,e,r={}){let s=await tr(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}=Rr(t,o,r,s),c=!!await $r(s,a,i),p=!1;if(c){let f=await s.delete(i),m=!f&&i!==a?await s.delete(a):!1;p=f||m}return{file:o,deleted:p,wasCached:c}}));return{filesDeleted:n.filter(o=>o.deleted).length,filesCached:n.filter(o=>o.wasCached).length,files:n}}async function FT(t,e={}){if(!t)throw new Error("modelId is required");let r=await Sr(t,e);return await UT(t,r,e)}async function GT(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await Or(t,e,r);return await UT(e,s,r)}var u1=class{static async get_files(e,r={}){return Sr(e,r)}static async get_pipeline_files(e,r,s={}){return Or(e,r,s)}static async get_model_files(e,r={}){return Ap(e,r)}static async get_tokenizer_files(e){return mn(e)}static async get_processor_files(e){return Tp(e)}static async is_cached(e,r={}){return RT(e,r)}static async is_cached_files(e,r={}){return $T(e,r)}static async is_pipeline_cached(e,r,s={}){return DT(e,r,s)}static async is_pipeline_cached_files(e,r,s={}){return BT(e,r,s)}static async get_file_metadata(e,r,s={}){return pr(e,r,s)}static async clear_cache(e,r={}){return FT(e,r)}static async clear_pipeline_cache(e,r,s={}){return GT(e,r,s)}};export{_m as ASTFeatureExtractor,f_ as ASTForAudioClassification,p_ as ASTModel,Ho as ASTPreTrainedModel,l_ as AfmoeForCausalLM,i_ as AfmoeModel,Wo as AfmoePreTrainedModel,n_ as AlbertForMaskedLM,s_ as AlbertForQuestionAnswering,r_ as AlbertForSequenceClassification,t_ as AlbertModel,$s as AlbertPreTrainedModel,kd as AlbertTokenizer,a_ as ApertusForCausalLM,o_ as ApertusModel,qo as ApertusPreTrainedModel,u_ as ArceeForCausalLM,c_ as ArceeModel,Vo as ArceePreTrainedModel,dl as AudioClassificationPipeline,Wt as AutoConfig,Ke as AutoFeatureExtractor,Le as AutoImageProcessor,Tr as AutoModel,xp as AutoModelForAudioClassification,AT as AutoModelForAudioFrameClassification,IT as AutoModelForAudioTextToText,wp as AutoModelForCTC,pp as AutoModelForCausalLM,vp as AutoModelForDepthEstimation,yp as AutoModelForDocumentQuestionAnswering,hp as AutoModelForImageClassification,kp as AutoModelForImageFeatureExtraction,TT as AutoModelForImageMatting,tl as AutoModelForImageSegmentation,OT as AutoModelForImageTextToText,bp as AutoModelForImageToImage,kT as AutoModelForMaskGeneration,fp as AutoModelForMaskedLM,MT as AutoModelForNormalEstimation,_p as AutoModelForObjectDetection,ST as AutoModelForPoseEstimation,dp as AutoModelForQuestionAnswering,rl as AutoModelForSemanticSegmentation,Jn as AutoModelForSeq2SeqLM,el as AutoModelForSequenceClassification,lp as AutoModelForSpeechSeq2Seq,cp as AutoModelForTextToSpectrogram,up as AutoModelForTextToWaveform,ip as AutoModelForTokenClassification,sl as AutoModelForUniversalSegmentation,mp as AutoModelForVision2Seq,ET as AutoModelForXVector,gp as AutoModelForZeroShotObjectDetection,Xc as AutoProcessor,oe as AutoTokenizer,hl as AutomaticSpeechRecognitionPipeline,xl as BackgroundRemovalPipeline,m_ as BartForConditionalGeneration,h_ as BartForSequenceClassification,d_ as BartModel,In as BartPretrainedModel,Ed as BartTokenizer,l1 as BaseStreamer,Lm as BeitFeatureExtractor,g_ as BeitForImageClassification,__ as BeitModel,Xo as BeitPreTrainedModel,x_ as BertForMaskedLM,v_ as BertForQuestionAnswering,y_ as BertForSequenceClassification,b_ as BertForTokenClassification,w_ as BertModel,Kr as BertPreTrainedModel,Ad as BertTokenizer,Nm as BitImageProcessor,E_ as BlenderbotForConditionalGeneration,k_ as BlenderbotModel,Ko as BlenderbotPreTrainedModel,T_ as BlenderbotSmallForConditionalGeneration,A_ as BlenderbotSmallModel,Yo as BlenderbotSmallPreTrainedModel,Td as BlenderbotSmallTokenizer,Md as BlenderbotTokenizer,S_ as BloomForCausalLM,M_ as BloomModel,Qo as BloomPreTrainedModel,Sd as BloomTokenizer,Rm as CLIPFeatureExtractor,Sc as CLIPImageProcessor,R_ as CLIPModel,mr as CLIPPreTrainedModel,F_ as CLIPSegForImageSegmentation,U_ as CLIPSegModel,ra as CLIPSegPreTrainedModel,$_ as CLIPTextModel,ta as CLIPTextModelWithProjection,Id as CLIPTokenizer,D_ as CLIPVisionModel,B_ as CLIPVisionModelWithProjection,I_ as CamembertForMaskedLM,L_ as CamembertForQuestionAnswering,C_ as CamembertForSequenceClassification,P_ as CamembertForTokenClassification,O_ as CamembertModel,Yr as CamembertPreTrainedModel,Od as CamembertTokenizer,gm as ChatterboxFeatureExtractor,Jo as ChatterboxModel,pu as ChatterboxPreTrainedModel,Im as ChatterboxProcessor,zm as ChineseCLIPFeatureExtractor,N_ as ChineseCLIPModel,fu as ChineseCLIPPreTrainedModel,ea as ClapAudioModelWithProjection,wm as ClapFeatureExtractor,z_ as ClapModel,Cn as ClapPreTrainedModel,Zo as ClapTextModelWithProjection,nu as ClassifierFreeGuidanceLogitsProcessor,j_ as CodeGenForCausalLM,G_ as CodeGenModel,sa as CodeGenPreTrainedModel,Pd as CodeGenTokenizer,Cd as CodeLlamaTokenizer,H_ as Cohere2ForCausalLM,V_ as Cohere2Model,oa as Cohere2PreTrainedModel,W_ as CohereForCausalLM,q_ as CohereModel,na as CoherePreTrainedModel,Ld as CohereTokenizer,K_ as ConvBertForMaskedLM,J_ as ConvBertForQuestionAnswering,Y_ as ConvBertForSequenceClassification,Q_ as ConvBertForTokenClassification,X_ as ConvBertModel,Qr as ConvBertPreTrainedModel,Nd as ConvBertTokenizer,$m as ConvNextFeatureExtractor,eg as ConvNextForImageClassification,Oc as ConvNextImageProcessor,Z_ as ConvNextModel,aa as ConvNextPreTrainedModel,rg as ConvNextV2ForImageClassification,tg as ConvNextV2Model,ia as ConvNextV2PreTrainedModel,ag as DFineForObjectDetection,og as DFineModel,ca as DFinePreTrainedModel,Ig as DINOv3ConvNextModel,xu as DINOv3ConvNextPreTrainedModel,Um as DINOv3ViTImageProcessor,Cg as DINOv3ViTModel,yu as DINOv3ViTPreTrainedModel,Gm as DPTFeatureExtractor,Bg as DPTForDepthEstimation,Pc as DPTImageProcessor,Dg as DPTModel,ha as DPTPreTrainedModel,pa as DacDecoderModel,mu as DacDecoderOutput,ua as DacEncoderModel,du as DacEncoderOutput,Lo as DacFeatureExtractor,ig as DacModel,Pn as DacPreTrainedModel,cg as DebertaForMaskedLM,fg as DebertaForQuestionAnswering,ug as DebertaForSequenceClassification,pg as DebertaForTokenClassification,lg as DebertaModel,Jr as DebertaPreTrainedModel,Rd as DebertaTokenizer,mg as DebertaV2ForMaskedLM,gg as DebertaV2ForQuestionAnswering,hg as DebertaV2ForSequenceClassification,_g as DebertaV2ForTokenClassification,dg as DebertaV2Model,Zr as DebertaV2PreTrainedModel,zd as DebertaV2Tokenizer,wg as DecisionTransformerModel,hu as DecisionTransformerPreTrainedModel,Dm as DeiTFeatureExtractor,yg as DeiTForImageClassification,Ic as DeiTImageProcessor,xg as DeiTModel,fa as DeiTPreTrainedModel,bg as DepthAnythingForDepthEstimation,_u as DepthAnythingPreTrainedModel,Al as DepthEstimationPipeline,vg as DepthProForDepthEstimation,gu as DepthProPreTrainedModel,Bm as DetrFeatureExtractor,Eg as DetrForObjectDetection,Ag as DetrForSegmentation,Cc as DetrImageProcessor,kg as DetrModel,Nn as DetrObjectDetectionOutput,Ln as DetrPreTrainedModel,wu as DetrSegmentationOutput,Mg as Dinov2ForImageClassification,Tg as Dinov2Model,da as Dinov2PreTrainedModel,Og as Dinov2WithRegistersForImageClassification,Sg as Dinov2WithRegistersModel,ma as Dinov2WithRegistersPreTrainedModel,Rg as DistilBertForMaskedLM,zg as DistilBertForQuestionAnswering,Lg as DistilBertForSequenceClassification,Ng as DistilBertForTokenClassification,Pg as DistilBertModel,es as DistilBertPreTrainedModel,$d as DistilBertTokenizer,kl as DocumentQuestionAnsweringPipeline,Fm as DonutFeatureExtractor,_n as DonutImageProcessor,$g as DonutSwinModel,bu as DonutSwinPreTrainedModel,Fo as DynamicCache,L0 as EdgeTamModel,Fg as EfficientNetForImageClassification,jm as EfficientNetImageProcessor,Ug as EfficientNetModel,_a as EfficientNetPreTrainedModel,jg as ElectraForMaskedLM,Vg as ElectraForQuestionAnswering,qg as ElectraForSequenceClassification,Wg as ElectraForTokenClassification,Gg as ElectraModel,ts as ElectraPreTrainedModel,Dd as ElectraTokenizer,Po as EncodecFeatureExtractor,iu as EosTokenCriteria,Xg as Ernie4_5ForCausalLM,Hg as Ernie4_5Model,ga as Ernie4_5PretrainedModel,Yg as EsmForMaskedLM,Qg as EsmForSequenceClassification,Jg as EsmForTokenClassification,Kg as EsmModel,Ds as EsmPreTrainedModel,Bd as EsmTokenizer,ew as ExaoneForCausalLM,Zg as ExaoneModel,wa as ExaonePreTrainedModel,rw as FalconForCausalLM,nw as FalconH1ForCausalLM,sw as FalconH1Model,ya as FalconH1PreTrainedModel,tw as FalconModel,xa as FalconPreTrainedModel,Ud as FalconTokenizer,aw as FastViTForImageClassification,ow as FastViTModel,ba as FastViTPreTrainedModel,Tl as FeatureExtractionPipeline,Ae as FeatureExtractor,ll as FillMaskPipeline,iw as Florence2ForConditionalGeneration,vu as Florence2PreTrainedModel,bh as Florence2Processor,Yc as ForcedBOSTokenLogitsProcessor,Qc as ForcedEOSTokenLogitsProcessor,qm as GLPNFeatureExtractor,gw as GLPNForDepthEstimation,_w as GLPNModel,Ma as GLPNPreTrainedModel,Mw as GPT2LMHeadModel,Tw as GPT2Model,Pa as GPT2PreTrainedModel,jd as GPT2Tokenizer,xw as GPTBigCodeForCausalLM,ww as GPTBigCodeModel,Sa as GPTBigCodePreTrainedModel,Ow as GPTJForCausalLM,Sw as GPTJModel,La as GPTJPreTrainedModel,bw as GPTNeoForCausalLM,yw as GPTNeoModel,Oa as GPTNeoPreTrainedModel,kw as GPTNeoXForCausalLM,vw as GPTNeoXModel,Ia as GPTNeoXPreTrainedModel,Gd as GPTNeoXTokenizer,pw as Gemma2ForCausalLM,uw as Gemma2Model,ka as Gemma2PreTrainedModel,dw as Gemma3ForCausalLM,fw as Gemma3Model,Ea as Gemma3PreTrainedModel,xm as Gemma3nAudioFeatureExtractor,Aa as Gemma3nForCausalLM,zn as Gemma3nForConditionalGeneration,ku as Gemma3nPreTrainedModel,vh as Gemma3nProcessor,cw as GemmaForCausalLM,lw as GemmaModel,va as GemmaPreTrainedModel,Fd as GemmaTokenizer,hw as GlmForCausalLM,mw as GlmModel,Ta as GlmPreTrainedModel,Aw as GptOssForCausalLM,Ew as GptOssModel,Ca as GptOssPreTrainedModel,Cw as GraniteForCausalLM,Iw as GraniteModel,Lw as GraniteMoeHybridForCausalLM,Pw as GraniteMoeHybridModel,za as GraniteMoeHybridPreTrainedModel,Na as GranitePreTrainedModel,ym as GraniteSpeechFeatureExtractor,Nw as GraniteSpeechForConditionalGeneration,kh as GraniteSpeechProcessor,zw as GroundingDinoForObjectDetection,Wm as GroundingDinoImageProcessor,Au as GroundingDinoPreTrainedModel,Eh as GroundingDinoProcessor,Rw as GroupViTModel,Tu as GroupViTPreTrainedModel,Dw as HeliumForCausalLM,$w as HeliumModel,Ra as HeliumPreTrainedModel,qd as HerbertTokenizer,Uw as HieraForImageClassification,Bw as HieraModel,$a as HieraPreTrainedModel,Hw as HubertForCTC,Xw as HubertForSequenceClassification,Vw as HubertModel,Ww as HubertPreTrainedModel,Yw as HunYuanDenseV1ForCausalLM,Kw as HunYuanDenseV1Model,Da as HunYuanDenseV1PreTrainedModel,tx as IJepaForImageClassification,ex as IJepaModel,Ba as IJepaPreTrainedModel,Zw as Idefics3ForConditionalGeneration,Lc as Idefics3ImageProcessor,jc as Idefics3Processor,wl as ImageClassificationPipeline,Ml as ImageFeatureExtractionPipeline,X as ImageFeatureExtractor,X as ImageProcessor,Ys as ImageSegmentationPipeline,El as ImageToImagePipeline,gl as ImageToTextPipeline,B2 as InterruptableStoppingCriteria,sx as JAISLMHeadModel,rx as JAISModel,Ua as JAISPreTrainedModel,Hm as JinaCLIPImageProcessor,nx as JinaCLIPModel,Rn as JinaCLIPPreTrainedModel,Th as JinaCLIPProcessor,Fa as JinaCLIPTextModel,ox as JinaCLIPVisionModel,ix as Lfm2ForCausalLM,ax as Lfm2Model,cx as Lfm2MoeForCausalLM,lx as Lfm2MoeModel,ja as Lfm2MoePreTrainedModel,Ga as Lfm2PreTrainedModel,ux as Lfm2VlForConditionalGeneration,Xm as Lfm2VlImageProcessor,Mh as Lfm2VlProcessor,Vb as LiteWhisperForConditionalGeneration,dx as Llama4ForCausalLM,Su as Llama4PreTrainedModel,fx as LlamaForCausalLM,px as LlamaModel,qa as LlamaPreTrainedModel,Wd as LlamaTokenizer,Xt as LlavaForConditionalGeneration,Xt as LlavaOnevisionForConditionalGeneration,Km as LlavaOnevisionImageProcessor,Mu as LlavaPreTrainedModel,Sh as LlavaProcessor,Jw as LlavaQwen2ForCausalLM,Ct as LogLevel,Vt as LogitsProcessor,Ls as LogitsProcessorList,Uo as LogitsWarper,hx as LongT5ForConditionalGeneration,mx as LongT5Model,Wa as LongT5PreTrainedModel,gx as M2M100ForConditionalGeneration,_x as M2M100Model,Va as M2M100PreTrainedModel,Vd as M2M100Tokenizer,Xd as MBart50Tokenizer,Ax as MBartForCausalLM,kx as MBartForConditionalGeneration,Ex as MBartForSequenceClassification,vx as MBartModel,Us as MBartPreTrainedModel,So as MBartTokenizer,cy as MPNetForMaskedLM,fy as MPNetForQuestionAnswering,uy as MPNetForSequenceClassification,py as MPNetForTokenClassification,ly as MPNetModel,rs as MPNetPreTrainedModel,Qd as MPNetTokenizer,_y as MT5ForConditionalGeneration,hy as MT5Model,ni as MT5PreTrainedModel,xx as MarianMTModel,wx as MarianModel,Ha as MarianPreTrainedModel,Hd as MarianTokenizer,Qm as Mask2FormerImageProcessor,Ym as MaskFormerFeatureExtractor,bx as MaskFormerForInstanceSegmentation,gn as MaskFormerImageProcessor,yx as MaskFormerModel,Xa as MaskFormerPreTrainedModel,au as MaxLengthCriteria,Tx as Metric3DForDepthEstimation,Ou as Metric3DPreTrainedModel,Mx as Metric3Dv2ForDepthEstimation,Iu as Metric3Dv2PreTrainedModel,Sx as MgpstrForSceneTextRecognition,Cu as MgpstrModelOutput,Pu as MgpstrPreTrainedModel,Oh as MgpstrProcessor,Kd as MgpstrTokenizer,Ya as MimiDecoderModel,Nu as MimiDecoderOutput,Ka as MimiEncoderModel,Lu as MimiEncoderOutput,Ox as MimiModel,$n as MimiPreTrainedModel,tu as MinLengthLogitsProcessor,ru as MinNewTokensLengthLogitsProcessor,Cx as MistralForCausalLM,Ix as MistralModel,Qa as MistralPreTrainedModel,Lx as MobileBertForMaskedLM,zx as MobileBertForQuestionAnswering,Nx as MobileBertForSequenceClassification,Px as MobileBertModel,Fs as MobileBertPreTrainedModel,Yd as MobileBertTokenizer,$x as MobileLLMForCausalLM,Rx as MobileLLMModel,Ja as MobileLLMPreTrainedModel,Jm as MobileNetV1FeatureExtractor,Bx as MobileNetV1ForImageClassification,Ux as MobileNetV1ForSemanticSegmentation,Nc as MobileNetV1ImageProcessor,Dx as MobileNetV1Model,Dn as MobileNetV1PreTrainedModel,Zm as MobileNetV2FeatureExtractor,Gx as MobileNetV2ForImageClassification,jx as MobileNetV2ForSemanticSegmentation,zc as MobileNetV2ImageProcessor,Fx as MobileNetV2Model,Bn as MobileNetV2PreTrainedModel,eh as MobileNetV3FeatureExtractor,Wx as MobileNetV3ForImageClassification,Vx as MobileNetV3ForSemanticSegmentation,Rc as MobileNetV3ImageProcessor,qx as MobileNetV3Model,Un as MobileNetV3PreTrainedModel,th as MobileNetV4FeatureExtractor,Xx as MobileNetV4ForImageClassification,Kx as MobileNetV4ForSemanticSegmentation,$c as MobileNetV4ImageProcessor,Hx as MobileNetV4Model,Fn as MobileNetV4PreTrainedModel,rh as MobileViTFeatureExtractor,Qx as MobileViTForImageClassification,Dc as MobileViTImageProcessor,Yx as MobileViTModel,Za as MobileViTPreTrainedModel,Zx as MobileViTV2ForImageClassification,Jx as MobileViTV2Model,ei as MobileViTV2PreTrainedModel,u1 as ModelRegistry,oy as ModernBertDecoderForCausalLM,ny as ModernBertDecoderModel,ti as ModernBertDecoderPreTrainedModel,ty as ModernBertForMaskedLM,ry as ModernBertForSequenceClassification,sy as ModernBertForTokenClassification,ey as ModernBertModel,Gs as ModernBertPreTrainedModel,Qw as Moondream1ForConditionalGeneration,bm as MoonshineFeatureExtractor,iy as MoonshineForConditionalGeneration,ay as MoonshineModel,ri as MoonshinePreTrainedModel,Ih as MoonshineProcessor,my as MptForCausalLM,dy as MptModel,si as MptPreTrainedModel,gy as MultiModalityCausalLM,zu as MultiModalityPreTrainedModel,xy as MusicgenForCausalLM,ai as MusicgenForConditionalGeneration,wy as MusicgenModel,oi as MusicgenPreTrainedModel,by as NanoChatForCausalLM,yy as NanoChatModel,ii as NanoChatPreTrainedModel,ky as NeoBertForMaskedLM,Ty as NeoBertForQuestionAnswering,Ey as NeoBertForSequenceClassification,Ay as NeoBertForTokenClassification,vy as NeoBertModel,ss as NeoBertPreTrainedModel,Jd as NllbTokenizer,su as NoBadWordsLogitsProcessor,Zc as NoRepeatNGramLogitsProcessor,My as NomicBertModel,Ru as NomicBertPreTrainedModel,sh as NougatImageProcessor,Zd as NougatTokenizer,By as OPTForCausalLM,Dy as OPTModel,di as OPTPreTrainedModel,bl as ObjectDetectionPipeline,Cy as Olmo2ForCausalLM,Iy as Olmo2Model,ci as Olmo2PreTrainedModel,Ly as Olmo3ForCausalLM,Py as Olmo3Model,ui as Olmo3PreTrainedModel,Oy as OlmoForCausalLM,zy as OlmoHybridForCausalLM,Ny as OlmoHybridModel,pi as OlmoHybridPreTrainedModel,Sy as OlmoModel,li as OlmoPreTrainedModel,$y as OpenELMForCausalLM,Ry as OpenELMModel,fi as OpenELMPreTrainedModel,nh as OwlViTFeatureExtractor,jy as OwlViTForObjectDetection,wn as OwlViTImageProcessor,Gy as OwlViTModel,hi as OwlViTPreTrainedModel,Ch as OwlViTProcessor,Fy as Owlv2ForObjectDetection,oh as Owlv2ImageProcessor,Uy as Owlv2Model,mi as Owlv2PreTrainedModel,qy as PaliGemmaForConditionalGeneration,Ph as PaliGemmaProcessor,vm as ParakeetFeatureExtractor,Wy as ParakeetForCTC,$u as ParakeetPreTrainedModel,Hy as PatchTSMixerForPrediction,Vy as PatchTSMixerModel,_i as PatchTSMixerPreTrainedModel,Ky as PatchTSTForPrediction,Xy as PatchTSTModel,gi as PatchTSTPreTrainedModel,Zy as Phi3ForCausalLM,Jy as Phi3Model,xi as Phi3PreTrainedModel,yi as Phi3VForCausalLM,lh as Phi3VImageProcessor,Du as Phi3VPreTrainedModel,Lh as Phi3VProcessor,Qy as PhiForCausalLM,Yy as PhiModel,wi as PhiPreTrainedModel,ch as PixtralImageProcessor,Nh as PixtralProcessor,y as PreTrainedModel,W as PreTrainedTokenizer,kn as PretrainedConfig,re as Processor,t0 as PvtForImageClassification,uh as PvtImageProcessor,e0 as PvtModel,bi as PvtPreTrainedModel,No as PyAnnoteFeatureExtractor,s0 as PyAnnoteForAudioFrameClassification,r0 as PyAnnoteModel,vi as PyAnnotePreTrainedModel,zh as PyAnnoteProcessor,il as QuestionAnsweringPipeline,o0 as Qwen2ForCausalLM,n0 as Qwen2Model,i0 as Qwen2MoeForCausalLM,a0 as Qwen2MoeModel,Ei as Qwen2MoePreTrainedModel,ki as Qwen2PreTrainedModel,em as Qwen2Tokenizer,js as Qwen2VLForCausalLM,Gn as Qwen2VLForConditionalGeneration,ph as Qwen2VLImageProcessor,Bu as Qwen2VLPreTrainedModel,$o as Qwen2VLProcessor,qs as Qwen2_5_VLForCausalLM,Ai as Qwen2_5_VLForConditionalGeneration,Do as Qwen2_5_VLProcessor,c0 as Qwen3ForCausalLM,l0 as Qwen3Model,p0 as Qwen3MoeForCausalLM,u0 as Qwen3MoeModel,Mi as Qwen3MoePreTrainedModel,d0 as Qwen3NextForCausalLM,f0 as Qwen3NextModel,Si as Qwen3NextPreTrainedModel,Ti as Qwen3PreTrainedModel,Vs as Qwen3VLForCausalLM,Ws as Qwen3VLForConditionalGeneration,Oi as Qwen3VLMoeForCausalLM,m0 as Qwen3VLMoeForConditionalGeneration,Rh as Qwen3VLProcessor,Hs as Qwen3_5ForCausalLM,jn as Qwen3_5ForConditionalGeneration,Ii as Qwen3_5MoeForCausalLM,h0 as Qwen3_5MoeForConditionalGeneration,x0 as RFDetrForObjectDetection,w0 as RFDetrModel,Uu as RFDetrObjectDetectionOutput,Pi as RFDetrPreTrainedModel,ng as RTDetrForObjectDetection,fh as RTDetrImageProcessor,sg as RTDetrModel,hr as RTDetrObjectDetectionOutput,la as RTDetrPreTrainedModel,C0 as RTDetrV2ForObjectDetection,I0 as RTDetrV2Model,Fu as RTDetrV2ObjectDetectionOutput,Li as RTDetrV2PreTrainedModel,Co as RawAudio,Qe as RawImage,Mp as RawVideo,Sl as RawVideoFrame,eu as RepetitionPenaltyLogitsProcessor,g0 as ResNetForImageClassification,_0 as ResNetModel,Ci as ResNetPreTrainedModel,T0 as RoFormerForMaskedLM,O0 as RoFormerForQuestionAnswering,M0 as RoFormerForSequenceClassification,S0 as RoFormerForTokenClassification,A0 as RoFormerModel,os as RoFormerPreTrainedModel,rm as RoFormerTokenizer,b0 as RobertaForMaskedLM,E0 as RobertaForQuestionAnswering,v0 as RobertaForSequenceClassification,k0 as RobertaForTokenClassification,y0 as RobertaModel,ns as RobertaPreTrainedModel,tm as RobertaTokenizer,Ro as Sam2ImageProcessor,qu as Sam2ImageSegmentationOutput,Ni as Sam2Model,Wu as Sam2PreTrainedModel,qc as Sam2Processor,$h as Sam2VideoProcessor,Ro as Sam3ImageProcessor,N0 as Sam3TrackerModel,Ro as SamImageProcessor,Gu as SamImageSegmentationOutput,P0 as SamModel,ju as SamPreTrainedModel,Bo as SamProcessor,dh as SapiensFeatureExtractor,R0 as SapiensForDepthEstimation,$0 as SapiensForNormalEstimation,z0 as SapiensForSemanticSegmentation,Bc as SapiensImageProcessor,qn as SapiensPreTrainedModel,km as SeamlessM4TFeatureExtractor,mh as SegformerFeatureExtractor,B0 as SegformerForImageClassification,U0 as SegformerForSemanticSegmentation,Uc as SegformerImageProcessor,D0 as SegformerModel,Wn as SegformerPreTrainedModel,hh as SiglipImageProcessor,F0 as SiglipModel,zi as SiglipPreTrainedModel,Ri as SiglipTextModel,sm as SiglipTokenizer,G0 as SiglipVisionModel,q0 as SmolLM3ForCausalLM,j0 as SmolLM3Model,$i as SmolLM3PreTrainedModel,Lc as SmolVLMImageProcessor,jc as SmolVLMProcessor,Bi as SnacDecoderModel,Di as SnacEncoderModel,Em as SnacFeatureExtractor,W0 as SnacModel,Vn as SnacPreTrainedModel,Am as SpeechT5FeatureExtractor,H0 as SpeechT5ForSpeechToText,X0 as SpeechT5ForTextToSpeech,K0 as SpeechT5HifiGan,V0 as SpeechT5Model,Hn as SpeechT5PreTrainedModel,Dh as SpeechT5Processor,nm as SpeechT5Tokenizer,Q0 as SqueezeBertForMaskedLM,Z0 as SqueezeBertForQuestionAnswering,J0 as SqueezeBertForSequenceClassification,Y0 as SqueezeBertModel,Xs as SqueezeBertPreTrainedModel,om as SqueezeBertTokenizer,tb as StableLmForCausalLM,eb as StableLmModel,Ui as StableLmPreTrainedModel,sb as Starcoder2ForCausalLM,rb as Starcoder2Model,Fi as Starcoder2PreTrainedModel,Xr as StoppingCriteria,Tn as StoppingCriteriaList,nb as StyleTextToSpeech2Model,Vu as StyleTextToSpeech2PreTrainedModel,cl as SummarizationPipeline,Gi as SupertonicForConditionalGeneration,Hu as SupertonicPreTrainedModel,En as SuppressTokensAtBeginLogitsProcessor,cb as Swin2SRForImageSuperResolution,_h as Swin2SRImageProcessor,lb as Swin2SRModel,ji as Swin2SRPreTrainedModel,ab as SwinForImageClassification,ib as SwinForSemanticSegmentation,ob as SwinModel,Xn as SwinPreTrainedModel,pb as T5ForConditionalGeneration,ub as T5Model,qi as T5PreTrainedModel,am as T5Tokenizer,db as TableTransformerForObjectDetection,fb as TableTransformerModel,Xu as TableTransformerObjectDetectionOutput,Wi as TableTransformerPreTrainedModel,ou as TemperatureLogitsWarper,R as Tensor,Mr as Text2TextGenerationPipeline,ol as TextClassificationPipeline,pl as TextGenerationPipeline,c1 as TextStreamer,_l as TextToAudioPipeline,al as TokenClassificationPipeline,W as TokenizersBackend,D2 as TopKLogitsWarper,$2 as TopPLogitsWarper,mb as TrOCRForCausalLM,Ku as TrOCRPreTrainedModel,ul as TranslationPipeline,Bs as UltravoxModel,Eu as UltravoxPreTrainedModel,Bh as UltravoxProcessor,_b as UniSpeechForCTC,gb as UniSpeechForSequenceClassification,hb as UniSpeechModel,Kn as UniSpeechPreTrainedModel,bb as UniSpeechSatForAudioFrameClassification,xb as UniSpeechSatForCTC,yb as UniSpeechSatForSequenceClassification,wb as UniSpeechSatModel,Ks as UniSpeechSatPreTrainedModel,Ah as VLChatProcessor,Vm as VLMImageProcessor,kb as VaultGemmaForCausalLM,vb as VaultGemmaModel,Vi as VaultGemmaPreTrainedModel,gh as ViTFeatureExtractor,Tb as ViTForImageClassification,Fc as ViTImageProcessor,Mb as ViTMAEModel,Yu as ViTMAEPreTrainedModel,Ob as ViTMSNForImageClassification,Sb as ViTMSNModel,Xi as ViTMSNPreTrainedModel,Ab as ViTModel,Hi as ViTPreTrainedModel,Eb as VisionEncoderDecoderModel,Ib as VitMatteForImageMatting,wh as VitMatteImageProcessor,Qu as VitMattePreTrainedModel,Cb as VitPoseForPoseEstimation,xh as VitPoseImageProcessor,Ju as VitPosePreTrainedModel,Pb as VitsModel,Zu as VitsModelOutput,ep as VitsPreTrainedModel,lm as VitsTokenizer,Lb as VoxtralForConditionalGeneration,Uh as VoxtralProcessor,Sm as VoxtralRealtimeFeatureExtractor,Ki as VoxtralRealtimeForConditionalGeneration,tp as VoxtralRealtimePreTrainedModel,Gh as VoxtralRealtimeProcessor,$b as Wav2Vec2BertForCTC,Db as Wav2Vec2BertForSequenceClassification,Rb as Wav2Vec2BertModel,Yn as Wav2Vec2BertPreTrainedModel,cm as Wav2Vec2CTCTokenizer,Tm as Wav2Vec2FeatureExtractor,qw as Wav2Vec2ForAudioFrameClassification,Gw as Wav2Vec2ForCTC,jw as Wav2Vec2ForSequenceClassification,Fw as Wav2Vec2Model,or as Wav2Vec2PreTrainedModel,jh as Wav2Vec2Processor,qh as Wav2Vec2ProcessorWithLM,jb as WavLMForAudioFrameClassification,Ub as WavLMForCTC,Fb as WavLMForSequenceClassification,Gb as WavLMForXVector,Bb as WavLMModel,as as WavLMPreTrainedModel,Mm as WeSpeakerFeatureExtractor,qb as WeSpeakerResNetModel,sp as WeSpeakerResNetPreTrainedModel,Om as WhisperFeatureExtractor,op as WhisperForConditionalGeneration,Wb as WhisperModel,Yi as WhisperPreTrainedModel,Wh as WhisperProcessor,NT as WhisperTextStreamer,Jc as WhisperTimeStampLogitsProcessor,um as WhisperTokenizer,Qb as XLMForQuestionAnswering,Kb as XLMForSequenceClassification,Yb as XLMForTokenClassification,Hb as XLMModel,is as XLMPreTrainedModel,Zb as XLMRobertaForMaskedLM,r1 as XLMRobertaForQuestionAnswering,e1 as XLMRobertaForSequenceClassification,t1 as XLMRobertaForTokenClassification,Jb as XLMRobertaModel,ls as XLMRobertaPreTrainedModel,pm as XLMRobertaTokenizer,fm as XLMTokenizer,Xb as XLMWithLMHeadModel,rp as XVectorOutput,yh as YolosFeatureExtractor,n1 as YolosForObjectDetection,Gc as YolosImageProcessor,s1 as YolosModel,ap as YolosObjectDetectionOutput,Qi as YolosPreTrainedModel,a1 as YoutuForCausalLM,o1 as YoutuModel,Ji as YoutuPreTrainedModel,ml as ZeroShotAudioClassificationPipeline,fl as ZeroShotClassificationPipeline,yl as ZeroShotImageClassificationPipeline,vl as ZeroShotObjectDetectionPipeline,Ee as cat,hL as cos_sim,dE as dot,me as env,Xe as full,Mo as full_like,_d as interpolate,Et as interpolate_4d,N4 as layer_norm,wN as load_image,lz as load_video,xf as log_softmax,f2 as matmul,xc as mean,d2 as mean_pooling,st as ones,yc as ones_like,QL as permute,Fae as pipeline,h2 as quantize_embeddings,z4 as rand,m2 as randn,ws as random,hm as read_audio,L4 as rfft,wc as slice,Re as softmax,Pt as stack,gd as std_mean,sr as topk,xd as zeros,yd as zeros_like};