otherwise-cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +193 -0
  2. package/bin/otherwise.js +5 -0
  3. package/frontend/404.html +84 -0
  4. package/frontend/assets/OpenDyslexic3-Bold-CDyRs55Y.ttf +0 -0
  5. package/frontend/assets/OpenDyslexic3-Regular-CIBXa4WE.ttf +0 -0
  6. package/frontend/assets/__vite-browser-external-BIHI7g3E.js +1 -0
  7. package/frontend/assets/conversational-worker-CeKiciGk.js +2929 -0
  8. package/frontend/assets/dictation-worker-D0aYfq8b.js +29 -0
  9. package/frontend/assets/gemini-color-CgSQmmva.png +0 -0
  10. package/frontend/assets/index-BLux5ps4.js +21 -0
  11. package/frontend/assets/index-Blh8_TEM.js +5272 -0
  12. package/frontend/assets/index-BpQ1PuKu.js +18 -0
  13. package/frontend/assets/index-Df737c8w.css +1 -0
  14. package/frontend/assets/index-xaYHL6wb.js +113 -0
  15. package/frontend/assets/ort-wasm-simd-threaded.asyncify-BynIiDiv.wasm +0 -0
  16. package/frontend/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm +0 -0
  17. package/frontend/assets/transformers-tULNc5V3.js +31 -0
  18. package/frontend/assets/tts-worker-DPJWqT7N.js +2899 -0
  19. package/frontend/assets/voice-mode-worker-GzvIE_uh.js +2927 -0
  20. package/frontend/assets/worker-2d5ABSLU.js +31 -0
  21. package/frontend/banner.png +0 -0
  22. package/frontend/favicon.svg +3 -0
  23. package/frontend/google55e5ec47ee14a5f8.html +1 -0
  24. package/frontend/index.html +234 -0
  25. package/frontend/manifest.json +17 -0
  26. package/frontend/pdf.worker.min.mjs +21 -0
  27. package/frontend/robots.txt +5 -0
  28. package/frontend/sitemap.xml +27 -0
  29. package/package.json +81 -0
  30. package/src/agent/index.js +1066 -0
  31. package/src/agent/location.js +51 -0
  32. package/src/agent/prompt.js +548 -0
  33. package/src/agent/tools.js +4372 -0
  34. package/src/browser/detect.js +68 -0
  35. package/src/browser/session.js +1109 -0
  36. package/src/config.js +137 -0
  37. package/src/email/client.js +503 -0
  38. package/src/index.js +557 -0
  39. package/src/inference/anthropic.js +113 -0
  40. package/src/inference/google.js +373 -0
  41. package/src/inference/index.js +81 -0
  42. package/src/inference/ollama.js +383 -0
  43. package/src/inference/openai.js +140 -0
  44. package/src/inference/openrouter.js +378 -0
  45. package/src/inference/xai.js +200 -0
  46. package/src/logBridge.js +9 -0
  47. package/src/models.js +146 -0
  48. package/src/remote/client.js +225 -0
  49. package/src/scheduler/cron.js +243 -0
  50. package/src/server.js +3876 -0
  51. package/src/storage/db.js +1135 -0
  52. package/src/storage/supabase.js +364 -0
  53. package/src/tunnel/cloudflare.js +241 -0
  54. package/src/ui/components/App.jsx +687 -0
  55. package/src/ui/components/BrowserSelect.jsx +111 -0
  56. package/src/ui/components/FilePicker.jsx +472 -0
  57. package/src/ui/components/Header.jsx +444 -0
  58. package/src/ui/components/HelpPanel.jsx +173 -0
  59. package/src/ui/components/HistoryPanel.jsx +158 -0
  60. package/src/ui/components/MessageList.jsx +235 -0
  61. package/src/ui/components/ModelSelector.jsx +304 -0
  62. package/src/ui/components/PromptInput.jsx +515 -0
  63. package/src/ui/components/StreamingResponse.jsx +134 -0
  64. package/src/ui/components/ThinkingIndicator.jsx +365 -0
  65. package/src/ui/components/ToolExecution.jsx +714 -0
  66. package/src/ui/components/index.js +82 -0
  67. package/src/ui/context/TerminalContext.jsx +150 -0
  68. package/src/ui/context/index.js +13 -0
  69. package/src/ui/hooks/index.js +16 -0
  70. package/src/ui/hooks/useChatState.js +675 -0
  71. package/src/ui/hooks/useCommands.js +280 -0
  72. package/src/ui/hooks/useFileAttachments.js +216 -0
  73. package/src/ui/hooks/useKeyboardShortcuts.js +173 -0
  74. package/src/ui/hooks/useNotifications.js +185 -0
  75. package/src/ui/hooks/useTerminalSize.js +151 -0
  76. package/src/ui/hooks/useWebSocket.js +273 -0
  77. package/src/ui/index.js +94 -0
  78. package/src/ui/ink-runner.js +22 -0
  79. package/src/ui/utils/formatters.js +424 -0
  80. package/src/ui/utils/index.js +6 -0
  81. package/src/ui/utils/markdown.js +166 -0
@@ -0,0 +1,31 @@
1
+ /*!
2
+ * ONNX Runtime Web v1.25.0-dev.20260228-6e72d31970
3
+ * Copyright (c) Microsoft Corporation. All rights reserved.
4
+ * Licensed under the MIT License.
5
+ */var ri=Object.defineProperty,cy=Object.getOwnPropertyDescriptor,uy=Object.getOwnPropertyNames,dy=Object.prototype.hasOwnProperty,hy=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),fe=(e,t)=>()=>(e&&(t=e(e=0)),t),rs=(e,t)=>{for(var r in t)ri(e,r,{get:t[r],enumerable:!0})},fy=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of uy(t))!dy.call(e,s)&&s!==r&&ri(e,s,{get:()=>t[s],enumerable:!(n=cy(t,s))||n.enumerable});return e},Vs=e=>fy(ri({},"__esModule",{value:!0}),e),$n,fr,Or,Pd,Hh,Qh=fe(()=>{$n=new Map,fr=[],Or=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=$n.get(e);if(n===void 0)$n.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let s=fr.indexOf(e);s!==-1&&fr.splice(s,1);for(let a=0;a<fr.length;a++)if($n.get(fr[a]).priority<=r){fr.splice(a,0,e);return}fr.push(e)}return}throw new TypeError("not a valid backend")},Pd=async e=>{let t=$n.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},Hh=async e=>{let t=e.executionProviders||[],r=t.map(l=>typeof l=="string"?l:l.name),n=r.length===0?fr:r,s,a=[],o=new Set;for(let l of n){let u=await Pd(l);typeof u=="string"?a.push({name:l,err:u}):(s||(s=u),s===u&&o.add(l))}if(!s)throw new Error(`no available backend found. ERR: ${a.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:u}of a)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);let i=t.filter(l=>o.has(typeof l=="string"?l:l.name));return[s,new Proxy(e,{get:(l,u)=>u==="executionProviders"?i:Reflect.get(l,u)})]}}),py=fe(()=>{Qh()}),Xh,_y=fe(()=>{Xh="1.24.0-dev.20251116-b39e144322"}),co,Je,Yh=fe(()=>{_y(),co="warning",Je={wasm:{},webgl:{},webgpu:{},versions:{common:Xh},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);co=e}},get logLevel(){return co}},Object.defineProperty(Je,"logLevel",{enumerable:!0})}),Ne,my=fe(()=>{Yh(),Ne=Je}),Jh,Kh,gy=fe(()=>{Jh=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let s,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[3]):(s=e.dims[3],a=e.dims[2]);let o=t?.format!==void 0?t.format:"RGB",i=t?.norm,l,u;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?u=[0,0,0,0]:typeof i.bias=="number"?u=[i.bias,i.bias,i.bias,i.bias]:(u=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(u[3]=i.bias[3]));let h=a*s,f=0,p=h,g=h*2,v=-1;o==="RGBA"?(f=0,p=h,g=h*2,v=h*3):o==="RGB"?(f=0,p=h,g=h*2):o==="RBG"&&(f=0,g=h,p=h*2);for(let w=0;w<a;w++)for(let M=0;M<s;M++){let k=(e.data[f++]-u[0])*l[0],T=(e.data[p++]-u[1])*l[1],S=(e.data[g++]-u[2])*l[2],E=v===-1?255:(e.data[v++]-u[3])*l[3];n.fillStyle="rgba("+k+","+T+","+S+","+E+")",n.fillRect(M,w,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")},Kh=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let s,a,o;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[1],o=e.dims[3]):(s=e.dims[3],a=e.dims[2],o=e.dims[1]);let i=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t?.norm,u,h;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[3]=l.mean[3])),l===void 0||l.bias===void 0?h=[0,0,0,0]:typeof l.bias=="number"?h=[l.bias,l.bias,l.bias,l.bias]:(h=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(h[3]=l.bias[3]));let f=a*s;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let p=4,g=0,v=1,w=2,M=3,k=0,T=f,S=f*2,E=-1;i==="RGBA"?(k=0,T=f,S=f*2,E=f*3):i==="RGB"?(k=0,T=f,S=f*2):i==="RBG"&&(k=0,S=f,T=f*2),n=r.createImageData(s,a);for(let F=0;F<a*s;g+=p,v+=p,w+=p,M+=p,F++)n.data[g]=(e.data[k++]-h[0])*u[0],n.data[v]=(e.data[T++]-h[1])*u[1],n.data[w]=(e.data[S++]-h[2])*u[2],n.data[M]=E===-1?255:(e.data[E++]-h[3])*u[3]}else throw new Error("Can not access image data");return n}}),Ts,Zh,ef,tf,rf,nf,wy=fe(()=>{ni(),Ts=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=t,s=t.norm??{mean:255,bias:0},a,o;typeof s.mean=="number"?a=[s.mean,s.mean,s.mean,s.mean]:a=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?o=[s.bias,s.bias,s.bias,s.bias]:o=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let i=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",u=r*n,h=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3),f=4,p=0,g=1,v=2,w=3,M=0,k=u,T=u*2,S=-1;i==="RGB"&&(f=3,p=0,g=1,v=2,w=-1),l==="RGBA"?S=u*3:l==="RBG"?(M=0,T=u,k=u*2):l==="BGR"&&(T=0,k=u,M=u*2);for(let E=0;E<u;E++,p+=f,v+=f,g+=f,w+=f)h[M++]=(e[p]+o[0])/a[0],h[k++]=(e[g]+o[1])/a[1],h[T++]=(e[v]+o[2])/a[2],S!==-1&&w!==-1&&(h[S++]=(e[w]+o[3])/a[3]);return l==="RGBA"?new wt("float32",h,[1,4,r,n]):new wt("float32",h,[1,3,r,n])},Zh=async(e,t)=>{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,s=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",o,i=t??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},u=h=>typeof HTMLCanvasElement<"u"&&h instanceof HTMLCanvasElement||h instanceof OffscreenCanvas?h.getContext("2d"):null;if(r){let h=l();h.width=e.width,h.height=e.height;let f=u(h);if(f!=null){let p=e.height,g=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(p=t.resizedHeight,g=t.resizedWidth),t!==void 0){if(i=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=p,i.width=g}else i.tensorFormat="RGBA",i.height=p,i.width=g;f.drawImage(e,0,0),o=f.getImageData(0,0,g,p).data}else throw new Error("Can not access image data")}else if(n){let h,f;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(h=t.resizedHeight,f=t.resizedWidth):(h=e.height,f=e.width),t!==void 0&&(i=t),i.format="RGBA",i.height=h,i.width=f,t!==void 0){let p=l();p.width=f,p.height=h;let g=u(p);if(g!=null)g.putImageData(e,0,0),o=g.getImageData(0,0,f,h).data;else throw new Error("Can not access image data")}else o=e.data}else if(s){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let h=l();h.width=e.width,h.height=e.height;let f=u(h);if(f!=null){let p=e.height,g=e.width;return f.drawImage(e,0,0,g,p),o=f.getImageData(0,0,g,p).data,i.height=p,i.width=g,Ts(o,i)}else throw new Error("Can not access image data")}else{if(a)return new Promise((h,f)=>{let p=l(),g=u(p);if(!e||!g)return f();let v=new Image;v.crossOrigin="Anonymous",v.src=e,v.onload=()=>{p.width=v.width,p.height=v.height,g.drawImage(v,0,0,p.width,p.height);let w=g.getImageData(0,0,p.width,p.height);i.height=p.height,i.width=p.width,h(Ts(w.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return Ts(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},ef=(e,t)=>{let{width:r,height:n,download:s,dispose:a}=t,o=[1,n,r,4];return new wt({location:"texture",type:"float32",texture:e,dims:o,download:s,dispose:a})},tf=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new wt({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},rf=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new wt({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:s,dispose:a})},nf=(e,t,r)=>new wt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),Ir,Qn,uo,sf,vy=fe(()=>{Ir=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Qn=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),uo=!1,sf=()=>{if(!uo){uo=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,n=typeof r<"u"&&r.from;e&&(Ir.set("int64",BigInt64Array),Qn.set(BigInt64Array,"int64")),t&&(Ir.set("uint64",BigUint64Array),Qn.set(BigUint64Array,"uint64")),n?(Ir.set("float16",r),Qn.set(r,"float16")):Ir.set("float16",Uint16Array)}}}),af,of,yy=fe(()=>{ni(),af=e=>{let t=1;for(let r=0;r<e.length;r++){let n=e[r];if(typeof n!="number"||!Number.isSafeInteger(n))throw new TypeError(`dims[${r}] must be an integer, got: ${n}`);if(n<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${n}`);t*=n}return t},of=(e,t)=>{switch(e.location){case"cpu":return new wt(e.type,e.data,t);case"cpu-pinned":return new wt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new wt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new wt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new wt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),wt,ni=fe(()=>{gy(),wy(),vy(),yy(),wt=class{constructor(e,t,r){sf();let n,s;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,s=e.dims,e.location){case"cpu-pinned":{let o=Ir.get(n);if(!o)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw new TypeError(`buffer should be of type ${o.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 o,i;if(typeof e=="string")if(n=e,i=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");o=t}else{let l=Ir.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);e==="uint64"||e==="int64"?o=l.from(t,BigInt):o=l.from(t)}else if(t instanceof l)o=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")o=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&t instanceof Uint16Array&&l!==Uint16Array)o=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${n} tensor's data must be type of ${l}`)}else if(i=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")n="string",o=e;else if(l==="boolean")n="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",o=Uint8Array.from(e);else{let l=Qn.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=l,o=e}if(i===void 0)i=[o.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");s=i,this.cpuData=o,this.dataLocation="cpu"}let a=af(s);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=s,this.size=a}static async fromImage(e,t){return Zh(e,t)}static fromTexture(e,t){return ef(e,t)}static fromGpuBuffer(e,t){return tf(e,t)}static fromMLTensor(e,t){return rf(e,t)}static fromPinnedBuffer(e,t,r){return nf(e,t,r)}toDataURL(e){return Jh(this,e)}toImageData(e){return Kh(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 t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return of(this,e)}}}),Lt,lf=fe(()=>{ni(),Lt=wt}),Us,ho,Br,zr,vr,yr,cf=fe(()=>{Yh(),Us=(e,t)=>{(typeof Je.trace>"u"?!Je.wasm.trace:!Je.trace)||console.timeStamp(`${e}::ORT::${t}`)},ho=(e,t)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],n=!1;for(let s=0;s<r.length;s++){if(n&&!r[s].includes("TRACE_FUNC")){let a=`FUNC_${e}::${r[s].trim().split(" ")[1]}`;t&&(a+=`::${t}`),Us("CPU",a);return}r[s].includes("TRACE_FUNC")&&(n=!0)}},Br=e=>{(typeof Je.trace>"u"?!Je.wasm.trace:!Je.trace)||ho("BEGIN",e)},zr=e=>{(typeof Je.trace>"u"?!Je.wasm.trace:!Je.trace)||ho("END",e)},vr=e=>{(typeof Je.trace>"u"?!Je.wasm.trace:!Je.trace)||console.time(`ORT::${e}`)},yr=e=>{(typeof Je.trace>"u"?!Je.wasm.trace:!Je.trace)||console.timeEnd(`ORT::${e}`)}}),uf,by=fe(()=>{Qh(),lf(),cf(),uf=class df{constructor(t){this.handler=t}async run(t,r,n){Br(),vr("InferenceSession.run");let s={},a={};if(typeof t!="object"||t===null||t instanceof Lt||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Lt)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.");o=!1;for(let u of r){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);s[u]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let u=!1,h=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(h.indexOf(f)!==-1){let p=r[f];(p===null||p instanceof Lt)&&(u=!0,o=!1,s[f]=p)}if(u){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let u of this.inputNames)if(typeof t[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(o)for(let u of this.outputNames)s[u]=null;let i=await this.handler.run(t,s,a),l={};for(let u in i)if(Object.hasOwnProperty.call(i,u)){let h=i[u];h instanceof Lt?l[u]=h:l[u]=new Lt(h.type,h.data,h.dims)}return yr("InferenceSession.run"),zr(),l}async release(){return this.handler.dispose()}static async create(t,r,n,s){Br(),vr("InferenceSession.create");let a,o={};if(typeof t=="string"){if(a=t,typeof r=="object"&&r!==null)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof r=="object"&&r!==null)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let h=t,f=0,p=t.byteLength;if(typeof r=="object"&&r!==null)o=r;else if(typeof r=="number"){if(f=r,!Number.isSafeInteger(f))throw new RangeError("'byteOffset' must be an integer.");if(f<0||f>=h.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${h.byteLength}).`);if(p=t.byteLength-f,typeof n=="number"){if(p=n,!Number.isSafeInteger(p))throw new RangeError("'byteLength' must be an integer.");if(p<=0||f+p>h.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${h.byteLength-f}].`);if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(h,f,p)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await Hh(o),u=await i.createInferenceSessionHandler(a,l);return yr("InferenceSession.create"),zr(),new df(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),si,My=fe(()=>{by(),si=uf}),xy=fe(()=>{}),ky=fe(()=>{}),Ty=fe(()=>{}),Ey=fe(()=>{}),hf={};rs(hf,{InferenceSession:()=>si,TRACE:()=>Us,TRACE_EVENT_BEGIN:()=>vr,TRACE_EVENT_END:()=>yr,TRACE_FUNC_BEGIN:()=>Br,TRACE_FUNC_END:()=>zr,Tensor:()=>Lt,env:()=>Ne,registerBackend:()=>Or});var Gr=fe(()=>{py(),my(),My(),lf(),xy(),ky(),cf(),Ty(),Ey()}),ai=fe(()=>{}),ff={};rs(ff,{default:()=>pf});var fo,po,pf,Cy=fe(()=>{Pf(),$r(),oi(),fo="ort-wasm-proxy-worker",po=globalThis.self?.name===fo,po&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":ii(r.wasm).then(()=>{hi(r).then(()=>{postMessage({type:t})},n=>{postMessage({type:t,err:n})})},n=>{postMessage({type:t,err:n})});break;case"init-ep":{let{epName:n,env:s}=r;fi(s,n).then(()=>{postMessage({type:t})},a=>{postMessage({type:t,err:a})});break}case"copy-from":{let{buffer:n}=r,s=qs(n);postMessage({type:t,out:s});break}case"create":{let{model:n,options:s}=r;pi(n,s).then(a=>{postMessage({type:t,out:a})},a=>{postMessage({type:t,err:a})});break}case"release":_i(r),postMessage({type:t});break;case"run":{let{sessionId:n,inputIndices:s,inputs:a,outputIndices:o,options:i}=r;mi(n,s,a,o,new Array(o.length).fill(null),i).then(l=>{l.some(u=>u[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:l},wi([...a,...l]))},l=>{postMessage({type:t,err:l})});break}case"end-profiling":gi(r),postMessage({type:t});break;default:}}catch(n){postMessage({type:t,err:n})}}),pf=po?null:e=>new Worker(e??mt,{type:"module",name:fo})}),_f={};rs(_f,{default:()=>mf});async function Ad(e={}){var t=e,r=!!globalThis.window,n=!!globalThis.WorkerGlobalScope,s=n&&self.name?.startsWith("em-pthread");t.mountExternalData=(c,d)=>{c.startsWith("./")&&(c=c.substring(2)),(t.Uc||(t.Uc=new Map)).set(c,d)},t.unmountExternalData=()=>{delete t.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,Be:!0}).buffer.constructor;let a=()=>{let c=d=>(..._)=>{let m=Ut;return _=d(..._),Ut!=m?new Promise((y,x)=>{Ua={resolve:y,reject:x}}):_};(()=>{for(let d of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])t[d]=c(t[d])})(),typeof jsepRunAsync<"u"&&(t._OrtRun=jsepRunAsync(t._OrtRun),t._OrtRunWithBinding=jsepRunAsync(t._OrtRunWithBinding)),a=void 0};t.asyncInit=()=>{a?.()};var o,i,l=(c,d)=>{throw d},u=import.meta.url,h="";if(r||n){try{h=new URL(".",u).href}catch{}n&&(i=c=>{var d=new XMLHttpRequest;return d.open("GET",c,!1),d.responseType="arraybuffer",d.send(null),new Uint8Array(d.response)}),o=async c=>{if(z(c))return new Promise((_,m)=>{var y=new XMLHttpRequest;y.open("GET",c,!0),y.responseType="arraybuffer",y.onload=()=>{y.status==200||y.status==0&&y.response?_(y.response):m(y.status)},y.onerror=m,y.send(null)});var d=await fetch(c,{credentials:"same-origin"});if(d.ok)return d.arrayBuffer();throw Error(d.status+" : "+d.url)}}var f,p,g,v,w,M,k=console.log.bind(console),T=console.error.bind(console),S=k,E=T,F=!1,z=c=>c.startsWith("file://");function b(){dr.buffer!=G.buffer&&J()}if(s){let c=function(d){try{var _=d.data,m=_.Oc;if(m==="load"){let y=[];self.onmessage=x=>y.push(x),M=()=>{postMessage({Oc:"loaded"});for(let x of y)c(x);self.onmessage=c};for(let x of _.de)t[x]&&!t[x].proxy||(t[x]=(...C)=>{postMessage({Oc:"callHandler",ce:x,args:C})},x=="print"&&(S=t[x]),x=="printErr"&&(E=t[x]));dr=_.je,J(),p=_.ke,ct(),ks()}else if(m==="run"){(function(y){var x=(b(),O)[y+52>>>2>>>0];y=(b(),O)[y+56>>>2>>>0],Ru(x,x-y),te(x)})(_.Nc),to(_.Nc,0,0,1,0,0),Ec(),Ga(_.Nc),U||(bu(),U=!0);try{hg(_.he,_.Wc)}catch(y){if(y!="unwind")throw y}}else _.target!=="setimmediate"&&(m==="checkMailbox"?U&&ms():m&&(E(`worker: received unknown command ${m}`),E(_)))}catch(y){throw Ou(),y}};var U=!1;self.onunhandledrejection=d=>{throw d.reason||d},self.onmessage=c}var G,H,Z,W,B,O,$,ee,X,A,L,D=!1;function J(){var c=dr.buffer;t.HEAP8=G=new Int8Array(c),Z=new Int16Array(c),t.HEAPU8=H=new Uint8Array(c),W=new Uint16Array(c),t.HEAP32=B=new Int32Array(c),t.HEAPU32=O=new Uint32Array(c),$=new Float32Array(c),ee=new Float64Array(c),X=new BigInt64Array(c),A=new BigUint64Array(c)}function ie(){D=!0,s?M():nr._b()}function xe(c){throw E(c="Aborted("+c+")"),F=!0,c=new WebAssembly.RuntimeError(c+". Build with -sASSERTIONS for more info."),w?.(c),c}function Fe(){return{a:{f:fg,J:pg,k:_g,p:mg,l:gg,ta:wg,b:vg,ca:yg,Ka:Ic,s:bg,da:Dc,_a:Bc,Ga:zc,Ia:Rc,$a:Gc,Ya:$c,Ra:Vc,Xa:Uc,pa:Wc,Ha:jc,Yb:qc,Za:Hc,Fa:Qc,eb:Mg,Da:xg,Tb:kg,Rb:Eg,Ca:Sg,M:Pg,H:Ag,Sb:Fg,ka:zg,Ub:Rg,Ua:Gg,Wb:Vg,La:Ug,Pb:Wg,la:jg,Ta:Ga,bb:qg,U:Yg,n:tw,c:za,sb:rw,w:nw,L:sw,z:aw,j:ow,o:ru,tb:iw,G:lw,T:cw,g:uw,u:dw,m:hw,i:fw,Oa:pw,Pa:_w,Qa:mw,Ma:ou,Na:iu,Qb:lu,fb:ww,db:yw,Y:bw,rb:Mw,ma:xw,cb:vw,gb:kw,ab:Tw,Xb:Ew,N:gw,hb:Cw,X:Sw,Vb:Pw,ob:zw,C:Rw,sa:Gw,ra:$w,qb:Vw,W:Uw,v:Ww,nb:jw,mb:qw,lb:Hw,pb:Qw,kb:Xw,jb:Yw,ib:Jw,Va:pu,Wa:_u,Ja:ut,ea:mu,oa:gu,Sa:wu,na:vu,Db:iy,xa:Zv,Eb:oy,ya:Kv,F:Vv,e:Pv,r:Cv,x:Ev,D:Rv,Ib:Xv,ba:Hv,B:Fv,za:Yv,$:ey,ha:Qv,Fb:sy,Gb:ny,Ba:Uv,Aa:qv,Jb:Wv,wa:ay,aa:Jv,d:Av,A:Iv,q:Sv,Cb:ly,t:Ov,y:Gv,I:Lv,E:Nv,K:$v,S:ty,ja:zv,_:ry,Kb:Bv,Lb:Dv,P:jv,h:Zw,a:dr,Ob:ur,Hb:ev,ia:tv,O:rv,qa:nv,Mb:sv,Q:av,zb:ov,Ab:iv,ua:lv,fa:cv,R:uv,Ea:dv,va:hv,Z:fv,xb:pv,Zb:_v,V:mv,Bb:gv,ub:wv,vb:yv,wb:bv,ga:Mv,yb:xv,Nb:kv}}}async function ct(){function c(m,y){var x=nr=m.exports;m={};for(let[C,I]of Object.entries(x))typeof I=="function"?(x=Hg(I),m[C]=x):m[C]=I;return nr=m,nr=function(){var C=nr,I=j=>_e=>j(_e)>>>0,R=j=>()=>j()>>>0;return(C=Object.assign({},C)).$b=I(C.$b),C.Cc=R(C.Cc),C.Ec=I(C.Ec),C.rd=(j=>(_e,Q)=>j(_e,Q)>>>0)(C.rd),C.wd=I(C.wd),C.xd=R(C.xd),C.Bd=I(C.Bd),C}(),kc.push(nr.id),yu=(m=nr).$b,bu=m.ac,t._OrtInit=m.bc,t._OrtGetLastError=m.cc,t._OrtCreateSessionOptions=m.dc,t._OrtAppendExecutionProvider=m.ec,t._OrtAddFreeDimensionOverride=m.fc,t._OrtAddSessionConfigEntry=m.gc,t._OrtReleaseSessionOptions=m.hc,t._OrtCreateSession=m.ic,t._OrtReleaseSession=m.jc,t._OrtGetInputOutputCount=m.kc,t._OrtGetInputOutputMetadata=m.lc,t._OrtFree=m.mc,t._OrtCreateTensor=m.nc,t._OrtGetTensorData=m.oc,t._OrtReleaseTensor=m.pc,t._OrtCreateRunOptions=m.qc,t._OrtAddRunConfigEntry=m.rc,t._OrtReleaseRunOptions=m.sc,t._OrtCreateBinding=m.tc,t._OrtBindInput=m.uc,t._OrtBindOutput=m.vc,t._OrtClearBoundOutputs=m.wc,t._OrtReleaseBinding=m.xc,t._OrtRunWithBinding=m.yc,t._OrtRun=m.zc,t._OrtEndProfiling=m.Ac,Xa=t._OrtGetWebGpuDevice=m.Bc,Ms=m.Cc,Ft=t._free=m.Dc,Yr=t._malloc=m.Ec,Mu=t._wgpuBufferRelease=m.Fc,xu=t._wgpuCreateInstance=m.Gc,ku=m.Hc,Tu=m.Ic,Eu=m.Jc,Cu=m.Kc,Su=m.Lc,Pu=m.Pc,Au=m.Zc,Fu=m._c,Iu=m.$c,Ya=m.bd,Ja=m.cd,Ka=m.dd,Za=m.ed,zn=m.fd,eo=m.gd,Lu=m.hd,to=m.kd,Ou=m.ld,Nu=m.md,Du=m.nd,ro=m.od,Bu=m.pd,zu=m.qd,no=m.rd,ce=m.sd,Rn=m.td,Ru=m.ud,te=m.vd,xs=m.wd,re=m.xd,Gu=m.yd,so=m.zd,$u=m.Ad,Vu=m.Bd,Uu=m.Cd,ao=m.Dd,Wu=m.Ed,ju=m.Fd,qu=m.Gd,Hu=m.Hd,Qu=m.Id,Xu=m.Jd,Yu=m.Kd,Ju=m.Ld,Ku=m.Md,Zu=m.Nd,ed=m.Od,td=m.Pd,rd=m.Qd,nd=m.Rd,sd=m.Td,ad=m.Ud,od=m.Vd,id=m.Wd,ld=m.Yd,cd=m.Zd,ud=m._d,dd=m.$d,hd=m.ae,fd=m.be,pd=m.pe,_d=m.qe,md=m.re,gd=m.se,wd=m.te,vd=m.ue,yd=m.ve,bd=m.we,Md=m.xe,xd=m.ye,kd=m.ze,Td=m.Xe,Ed=m.Ye,Cd=m.Ze,Sd=m._e,p=y,nr}var d,_=Fe();return t.instantiateWasm?new Promise(m=>{t.instantiateWasm(_,(y,x)=>{m(c(y,x))})}):s?c(new WebAssembly.Instance(p,Fe()),p):(L??=t.locateFile?t.locateFile?t.locateFile("ort-wasm-simd-threaded.asyncify.wasm",h):h+"ort-wasm-simd-threaded.asyncify.wasm":new URL("/assets/ort-wasm-simd-threaded.asyncify-BynIiDiv.wasm",import.meta.url).href,d=await async function(m){var y=L;if(!f&&!z(y))try{var x=fetch(y,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(x,m)}catch(C){E(`wasm streaming compile failed: ${C}`),E("falling back to ArrayBuffer instantiation")}return async function(C,I){try{var R=await async function(j){if(!f)try{var _e=await o(j);return new Uint8Array(_e)}catch{}if(j==L&&f)j=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";j=i(j)}return j}(C);return await WebAssembly.instantiate(R,I)}catch(j){E(`failed to asynchronously prepare wasm: ${j}`),xe(j)}}(y,m)}(_),c(d.instance,d.module))}class $e{name="ExitStatus";constructor(d){this.message=`Program terminated with exit(${d})`,this.status=d}}var ze=c=>{c.terminate(),c.onmessage=()=>{}},Ve=[],ve=0,de=null,Ue=c=>{We.length==0&&(Sc(),Cc(We[0]));var d=We.pop();if(!d)return 6;Nn.push(d),Tr[c.Nc]=d,d.Nc=c.Nc;var _={Oc:"run",he:c.ge,Wc:c.Wc,Nc:c.Nc};return d.postMessage(_,c.Yc),0},pe=0,we=(c,d,..._)=>{var m,y=16*_.length,x=re(),C=xs(y),I=C>>>3;for(m of _)typeof m=="bigint"?((b(),X)[I++>>>0]=1n,(b(),X)[I++>>>0]=m):((b(),X)[I++>>>0]=0n,(b(),ee)[I++>>>0]=m);return c=Nu(c,0,y,C,d),te(x),c};function ur(c){if(s)return we(0,1,c);if(g=c,!(0<pe)){for(var d of Nn)ze(d);for(d of We)ze(d);We=[],Nn=[],Tr={},F=!0}l(0,new $e(c))}function kr(c){if(s)return we(1,0,c);ut(c)}var ut=c=>{if(g=c,s)throw kr(c),"unwind";ur(c)},We=[],Nn=[],kc=[],Tr={},Tc=c=>{var d=c.Nc;delete Tr[d],We.push(c),Nn.splice(Nn.indexOf(c),1),c.Nc=0,Du(d)};function Ec(){kc.forEach(c=>c())}var Cc=c=>new Promise(d=>{c.onmessage=y=>{var x=y.data;if(y=x.Oc,x.Vc&&x.Vc!=Ms()){var C=Tr[x.Vc];C?C.postMessage(x,x.Yc):E(`Internal error! Worker sent a message "${y}" to target pthread ${x.Vc}, but that thread no longer exists!`)}else y==="checkMailbox"?ms():y==="spawnThread"?Ue(x):y==="cleanupThread"?lt(()=>{Tc(Tr[x.ie])}):y==="loaded"?(c.loaded=!0,d(c)):x.target==="setimmediate"?c.postMessage(x):y==="uncaughtException"?c.onerror(x.error):y==="callHandler"?t[x.ce](...x.args):y&&E(`worker sent an unknown command ${y}`)},c.onerror=y=>{throw E(`worker sent an error! ${y.filename}:${y.lineno}: ${y.message}`),y};var _,m=[];for(_ of[])t.propertyIsEnumerable(_)&&m.push(_);c.postMessage({Oc:"load",de:m,je:dr,ke:p})});function Sc(){var c=new Worker((()=>{let d=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new d("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});We.push(c)}var dr,hg=(c,d)=>{pe=0,c=ao(c,d),0<pe?g=c:ro(c)},ps=[],_s=0,it=c=>-9007199254740992>c||9007199254740992<c?NaN:Number(c);function fg(c){var d=new Oa(c>>>=0);return(b(),G)[d.Qc+12>>>0]==0&&(Pc(d,!0),_s--),Ac(d,!1),ps.push(d),Vu(c)}var qr=0,pg=()=>{ce(0,0);var c=ps.pop();Gu(c.Xc),qr=0};function Pc(c,d){d=d?1:0,(b(),G)[c.Qc+12>>>0]=d}function Ac(c,d){d=d?1:0,(b(),G)[c.Qc+13>>>0]=d}class Oa{constructor(d){this.Xc=d,this.Qc=d-24}}var Na=c=>{var d=qr;if(!d)return Rn(0),0;var _=new Oa(d);(b(),O)[_.Qc+16>>>2>>>0]=d;var m=(b(),O)[_.Qc+4>>>2>>>0];if(!m)return Rn(0),d;for(var y of c){if(y===0||y===m)break;if($u(y,m,_.Qc+16))return Rn(y),d}return Rn(m),d};function _g(){return Na([])}function mg(c){return Na([c>>>0])}function gg(c,d,_,m){return Na([c>>>0,d>>>0,_>>>0,m>>>0])}var wg=()=>{var c=ps.pop();c||xe("no exception to throw");var d=c.Xc;throw(b(),G)[c.Qc+13>>>0]==0&&(ps.push(c),Ac(c,!0),Pc(c,!1),_s++),so(d),qr=d};function vg(c,d,_){var m=new Oa(c>>>=0);throw d>>>=0,_>>>=0,(b(),O)[m.Qc+16>>>2>>>0]=0,(b(),O)[m.Qc+4>>>2>>>0]=d,(b(),O)[m.Qc+8>>>2>>>0]=_,so(c),_s++,qr=c}var yg=()=>_s;function Fc(c,d,_,m){return s?we(2,1,c,d,_,m):Ic(c,d,_,m)}function Ic(c,d,_,m){if(c>>>=0,d>>>=0,_>>>=0,m>>>=0,!globalThis.SharedArrayBuffer)return 6;var y=[];return s&&y.length===0?Fc(c,d,_,m):(c={ge:_,Nc:c,Wc:m,Yc:y},s?(c.Oc="spawnThread",postMessage(c,y),0):Ue(c))}function bg(c){throw qr||=c>>>0,qr}var Lc=globalThis.TextDecoder&&new TextDecoder,Oc=(c,d,_,m)=>{if(_=d+_,m)return _;for(;c[d]&&!(d>=_);)++d;return d},Nc=(c,d=0,_,m)=>{if(16<(_=Oc(c,d>>>=0,_,m))-d&&c.buffer&&Lc)return Lc.decode(c.buffer instanceof ArrayBuffer?c.subarray(d,_):c.slice(d,_));for(m="";d<_;){var y=c[d++];if(128&y){var x=63&c[d++];if((224&y)==192)m+=String.fromCharCode((31&y)<<6|x);else{var C=63&c[d++];65536>(y=(240&y)==224?(15&y)<<12|x<<6|C:(7&y)<<18|x<<12|C<<6|63&c[d++])?m+=String.fromCharCode(y):(y-=65536,m+=String.fromCharCode(55296|y>>10,56320|1023&y))}}else m+=String.fromCharCode(y)}return m},Hr=(c,d,_)=>(c>>>=0)?Nc((b(),H),c,d,_):"";function Dc(c,d,_){return s?we(3,1,c,d,_):0}function Bc(c,d){if(s)return we(4,1,c,d)}function zc(c,d){if(s)return we(5,1,c,d)}function Rc(c,d,_){if(s)return we(6,1,c,d,_)}function Gc(c,d,_){return s?we(7,1,c,d,_):0}function $c(c,d){if(s)return we(8,1,c,d)}function Vc(c,d,_){if(s)return we(9,1,c,d,_)}function Uc(c,d,_,m){if(s)return we(10,1,c,d,_,m)}function Wc(c,d,_,m){if(s)return we(11,1,c,d,_,m)}function jc(c,d,_,m){if(s)return we(12,1,c,d,_,m)}function qc(c){if(s)return we(13,1,c)}function Hc(c,d){if(s)return we(14,1,c,d)}function Qc(c,d,_){if(s)return we(15,1,c,d,_)}var Mg=()=>xe(""),Vt=c=>{c>>>=0;for(var d="";;){var _=(b(),H)[c++>>>0];if(!_)return d;d+=String.fromCharCode(_)}},Da={},Ba={},Qr=class extends Error{constructor(c){super(c),this.name="BindingError"}};function Kt(c,d,_={}){return function(m,y,x={}){var C=y.name;if(!m)throw new Qr(`type "${C}" must have a positive integer typeid pointer`);if(Ba.hasOwnProperty(m)){if(x.ee)return;throw new Qr(`Cannot register type '${C}' twice`)}Ba[m]=y,Da.hasOwnProperty(m)&&(y=Da[m],delete Da[m],y.forEach(I=>I()))}(c,d,_)}var Xc=(c,d,_)=>{switch(d){case 1:return _?m=>(b(),G)[m>>>0]:m=>(b(),H)[m>>>0];case 2:return _?m=>(b(),Z)[m>>>1>>>0]:m=>(b(),W)[m>>>1>>>0];case 4:return _?m=>(b(),B)[m>>>2>>>0]:m=>(b(),O)[m>>>2>>>0];case 8:return _?m=>(b(),X)[m>>>3>>>0]:m=>(b(),A)[m>>>3>>>0];default:throw new TypeError(`invalid integer width (${d}): ${c}`)}};function xg(c,d,_,m,y){c>>>=0,_>>>=0,d=Vt(d>>>0);let x=C=>C;if(m=m===0n){let C=8*_;x=I=>BigInt.asUintN(C,I),y=x(y)}Kt(c,{name:d,Mc:x,Sc:(C,I)=>(typeof I=="number"&&(I=BigInt(I)),I),Rc:Xc(d,_,!m),Tc:null})}function kg(c,d,_,m){Kt(c>>>=0,{name:d=Vt(d>>>0),Mc:function(y){return!!y},Sc:function(y,x){return x?_:m},Rc:function(y){return this.Mc((b(),H)[y>>>0])},Tc:null})}var Yc=[],Er=[0,1,,1,null,1,!0,1,!1,1];function za(c){9<(c>>>=0)&&--Er[c+1]==0&&(Er[c]=void 0,Yc.push(c))}var yt=c=>{if(!c)throw new Qr(`Cannot use deleted val. handle = ${c}`);return Er[c]},At=c=>{switch(c){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let d=Yc.pop()||Er.length;return Er[d]=c,Er[d+1]=1,d}};function Ra(c){return this.Mc((b(),O)[c>>>2>>>0])}var Tg={name:"emscripten::val",Mc:c=>{var d=yt(c);return za(c),d},Sc:(c,d)=>At(d),Rc:Ra,Tc:null};function Eg(c){return Kt(c>>>0,Tg)}var Cg=(c,d)=>{switch(d){case 4:return function(_){return this.Mc((b(),$)[_>>>2>>>0])};case 8:return function(_){return this.Mc((b(),ee)[_>>>3>>>0])};default:throw new TypeError(`invalid float width (${d}): ${c}`)}};function Sg(c,d,_){_>>>=0,Kt(c>>>=0,{name:d=Vt(d>>>0),Mc:m=>m,Sc:(m,y)=>y,Rc:Cg(d,_),Tc:null})}function Pg(c,d,_,m,y){c>>>=0,_>>>=0,d=Vt(d>>>0);let x=I=>I;if(m===0){var C=32-8*_;x=I=>I<<C>>>C,y=x(y)}Kt(c,{name:d,Mc:x,Sc:(I,R)=>R,Rc:Xc(d,_,m!==0),Tc:null})}function Ag(c,d,_){function m(x){var C=(b(),O)[x>>>2>>>0];return x=(b(),O)[x+4>>>2>>>0],new y((b(),G).buffer,x,C)}var y=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][d];Kt(c>>>=0,{name:_=Vt(_>>>0),Mc:m,Rc:m},{ee:!0})}var Zt=(c,d,_)=>{var m=(b(),H);if(d>>>=0,0<_){var y=d;_=d+_-1;for(var x=0;x<c.length;++x){var C=c.codePointAt(x);if(127>=C){if(d>=_)break;m[d++>>>0]=C}else if(2047>=C){if(d+1>=_)break;m[d++>>>0]=192|C>>6,m[d++>>>0]=128|63&C}else if(65535>=C){if(d+2>=_)break;m[d++>>>0]=224|C>>12,m[d++>>>0]=128|C>>6&63,m[d++>>>0]=128|63&C}else{if(d+3>=_)break;m[d++>>>0]=240|C>>18,m[d++>>>0]=128|C>>12&63,m[d++>>>0]=128|C>>6&63,m[d++>>>0]=128|63&C,x++}}m[d>>>0]=0,c=d-y}else c=0;return c},er=c=>{for(var d=0,_=0;_<c.length;++_){var m=c.charCodeAt(_);127>=m?d++:2047>=m?d+=2:55296<=m&&57343>=m?(d+=4,++_):d+=3}return d};function Fg(c,d){Kt(c>>>=0,{name:d=Vt(d>>>0),Mc(_){var m=(b(),O)[_>>>2>>>0];return m=Hr(_+4,m,!0),Ft(_),m},Sc(_,m){m instanceof ArrayBuffer&&(m=new Uint8Array(m));var y=typeof m=="string";if(!(y||ArrayBuffer.isView(m)&&m.BYTES_PER_ELEMENT==1))throw new Qr("Cannot pass non-string to std::string");var x=y?er(m):m.length,C=Yr(4+x+1),I=C+4;return(b(),O)[C>>>2>>>0]=x,y?Zt(m,I,x+1):(b(),H).set(m,I>>>0),_!==null&&_.push(Ft,C),C},Rc:Ra,Tc(_){Ft(_)}})}var Jc=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,Ig=(c,d,_)=>{if(c>>>=1,16<(d=Oc((b(),W),c,d/2,_))-c&&Jc)return Jc.decode((b(),W).slice(c,d));for(_="";c<d;++c){var m=(b(),W)[c>>>0];_+=String.fromCharCode(m)}return _},Lg=(c,d,_)=>{if(_??=2147483647,2>_)return 0;var m=d;_=(_-=2)<2*c.length?_/2:c.length;for(var y=0;y<_;++y){var x=c.charCodeAt(y);(b(),Z)[d>>>1>>>0]=x,d+=2}return(b(),Z)[d>>>1>>>0]=0,d-m},Og=c=>2*c.length,Ng=(c,d,_)=>{var m="";c>>>=2;for(var y=0;!(y>=d/4);y++){var x=(b(),O)[c+y>>>0];if(!x&&!_)break;m+=String.fromCodePoint(x)}return m},Dg=(c,d,_)=>{if(d>>>=0,_??=2147483647,4>_)return 0;var m=d;_=m+_-4;for(var y=0;y<c.length;++y){var x=c.codePointAt(y);if(65535<x&&y++,(b(),B)[d>>>2>>>0]=x,(d+=4)+4>_)break}return(b(),B)[d>>>2>>>0]=0,d-m},Bg=c=>{for(var d=0,_=0;_<c.length;++_)65535<c.codePointAt(_)&&_++,d+=4;return d};function zg(c,d,_){if(c>>>=0,d>>>=0,_=Vt(_>>>=0),d===2)var m=Ig,y=Lg,x=Og;else m=Ng,y=Dg,x=Bg;Kt(c,{name:_,Mc:C=>{var I=(b(),O)[C>>>2>>>0];return I=m(C+4,I*d,!0),Ft(C),I},Sc:(C,I)=>{if(typeof I!="string")throw new Qr(`Cannot pass non-string to C++ string type ${_}`);var R=x(I),j=Yr(4+R+d);return(b(),O)[j>>>2>>>0]=R/d,y(I,j+4,R+d),C!==null&&C.push(Ft,j),j},Rc:Ra,Tc(C){Ft(C)}})}function Rg(c,d){Kt(c>>>=0,{fe:!0,name:d=Vt(d>>>0),Mc:()=>{},Sc:()=>{}})}function Gg(c){to(c>>>0,!n,1,!r,131072,!1),Ec()}var lt=c=>{if(!F)try{if(c(),!(0<pe))try{s?Ms()&&ro(g):ut(g)}catch(d){d instanceof $e||d=="unwind"||l(0,d)}}catch(d){d instanceof $e||d=="unwind"||l(0,d)}},$g=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Ga(c){c>>>=0,$g||(Atomics.waitAsync((b(),B),c>>>2,c).value.then(ms),c+=128,Atomics.store((b(),B),c>>>2,1))}var ms=()=>lt(()=>{var c=Ms();c&&(Ga(c),zu())});function Vg(c,d){(c>>>=0)==d>>>0?setTimeout(ms):s?postMessage({Vc:c,Oc:"checkMailbox"}):(c=Tr[c])&&c.postMessage({Oc:"checkMailbox"})}var $a=[];function Ug(c,d,_,m,y){for(d>>>=0,y>>>=0,$a.length=0,_=y>>>3,m=y+m>>>3;_<m;){var x;x=(b(),X)[_++>>>0]?(b(),X)[_++>>>0]:(b(),ee)[_++>>>0],$a.push(x)}return(d?oo[d]:Tv[c])(...$a)}var Wg=()=>{pe=0};function jg(c){c>>>=0,s?postMessage({Oc:"cleanupThread",ie:c}):Tc(Tr[c])}function qg(c){}var gs=c=>{try{c()}catch(d){xe(d)}};function Hg(c){var d=(..._)=>{ws.push(c);try{return c(..._)}finally{F||(ws.pop(),Ut&&hr===1&&ws.length===0&&(hr=0,pe+=1,gs(Ed),typeof Fibers<"u"&&Fibers.De()))}};return eu.set(c,d),d}var hr=0,Ut=null,Kc=0,ws=[],Va=new Map,Zc=new Map,eu=new Map,Qg=0,Ua=null,Xg=[],tu=c=>function(d){if(!F){if(hr===0){var _=!1,m=!1;d((y=0)=>{if(!F&&(Kc=y,_=!0,m)){hr=2,gs(()=>Cd(Ut)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),y=!1;try{var x=function(){var R=(b(),B)[Ut+8>>>2>>>0];return R=Zc.get(R),R=eu.get(R),--pe,R()}()}catch(R){x=R,y=!0}var C=!1;if(!Ut){var I=Ua;I&&(Ua=null,(y?I.reject:I.resolve)(x),C=!0)}if(y&&!C)throw x}}),m=!0,_||(hr=1,Ut=function(){var y=Yr(65548),x=y+12;if((b(),O)[y>>>2>>>0]=x,(b(),O)[y+4>>>2>>>0]=x+65536,x=ws[0],!Va.has(x)){var C=Qg++;Va.set(x,C),Zc.set(C,x)}return x=Va.get(x),(b(),B)[y+8>>>2>>>0]=x,y}(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),gs(()=>Td(Ut)))}else hr===2?(hr=0,gs(Sd),Ft(Ut),Ut=null,Xg.forEach(lt)):xe(`invalid state: ${hr}`);return Kc}}(d=>{c().then(d)});function Yg(c){return c>>>=0,tu(async()=>{var d=await yt(c);return At(d)})}var Wa=[],Jg=c=>{var d=Wa.length;return Wa.push(c),d},Kg=(c,d)=>{for(var _=Array(c),m=0;m<c;++m){var y=m,x=(b(),O)[d+4*m>>>2>>>0],C=Ba[x];if(C===void 0)throw c=`parameter ${m}`,x=yu(x),d=Vt(x),Ft(x),new Qr(`${c} has unknown type ${d}`);_[y]=C}return _},Zg=(c,d,_)=>{var m=[];return c=c(m,_),m.length&&((b(),O)[d>>>2>>>0]=At(m)),c},ew={},vs=c=>{var d=ew[c];return d===void 0?Vt(c):d};function tw(c,d,_){var[m,...y]=Kg(c,d>>>0);d=m.Sc.bind(m);var x=y.map(R=>R.Rc.bind(R));c--;var C={toValue:yt};switch(c=x.map((R,j)=>{var _e=`argFromPtr${j}`;return C[_e]=R,`${_e}(args${j?"+"+8*j:""})`}),_){case 0:var I="toValue(handle)";break;case 2:I="new (toValue(handle))";break;case 3:I="";break;case 1:C.getStringOrSymbol=vs,I="toValue(handle)[getStringOrSymbol(methodName)]"}return I+=`(${c})`,m.fe||(C.toReturnWire=d,C.emval_returnValue=Zg,I=`return emval_returnValue(toReturnWire, destructorsRef, ${I})`),I=`return function (handle, methodName, destructorsRef, args) {
6
+ ${I}
7
+ }`,_=new Function(Object.keys(C),I)(...Object.values(C)),I=`methodCaller<(${y.map(R=>R.name)}) => ${m.name}>`,Jg(Object.defineProperty(_,"name",{value:I}))}function rw(c,d){return d>>>=0,(c=yt(c>>>0))==yt(d)}function nw(c){return(c>>>=0)?(c=vs(c),At(globalThis[c])):At(globalThis)}function sw(c){return c=vs(c>>>0),At(t[c])}function aw(c,d){return d>>>=0,c=yt(c>>>0),d=yt(d),At(c[d])}function ow(c){9<(c>>>=0)&&(Er[c+1]+=1)}function ru(c,d,_,m,y){return Wa[c>>>0](d>>>0,_>>>0,m>>>0,y>>>0)}function iw(c,d,_,m,y){return ru(c>>>0,d>>>0,_>>>0,m>>>0,y>>>0)}function lw(){return At([])}function cw(c){c=yt(c>>>0);for(var d=Array(c.length),_=0;_<c.length;_++)d[_]=c[_];return At(d)}function uw(c){return At(vs(c>>>0))}function dw(){return At({})}function hw(c){for(var d=yt(c>>>=0);d.length;){var _=d.pop();d.pop()(_)}za(c)}function fw(c,d,_){d>>>=0,_>>>=0,c=yt(c>>>0),d=yt(d),_=yt(_),c[d]=_}function pw(c,d){c=it(c),d>>>=0,c=new Date(1e3*c),(b(),B)[d>>>2>>>0]=c.getUTCSeconds(),(b(),B)[d+4>>>2>>>0]=c.getUTCMinutes(),(b(),B)[d+8>>>2>>>0]=c.getUTCHours(),(b(),B)[d+12>>>2>>>0]=c.getUTCDate(),(b(),B)[d+16>>>2>>>0]=c.getUTCMonth(),(b(),B)[d+20>>>2>>>0]=c.getUTCFullYear()-1900,(b(),B)[d+24>>>2>>>0]=c.getUTCDay(),c=(c.getTime()-Date.UTC(c.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(b(),B)[d+28>>>2>>>0]=c}var nu=c=>c%4==0&&(c%100!=0||c%400==0),su=[0,31,60,91,121,152,182,213,244,274,305,335],au=[0,31,59,90,120,151,181,212,243,273,304,334];function _w(c,d){c=it(c),d>>>=0,c=new Date(1e3*c),(b(),B)[d>>>2>>>0]=c.getSeconds(),(b(),B)[d+4>>>2>>>0]=c.getMinutes(),(b(),B)[d+8>>>2>>>0]=c.getHours(),(b(),B)[d+12>>>2>>>0]=c.getDate(),(b(),B)[d+16>>>2>>>0]=c.getMonth(),(b(),B)[d+20>>>2>>>0]=c.getFullYear()-1900,(b(),B)[d+24>>>2>>>0]=c.getDay();var _=(nu(c.getFullYear())?su:au)[c.getMonth()]+c.getDate()-1|0;(b(),B)[d+28>>>2>>>0]=_,(b(),B)[d+36>>>2>>>0]=-60*c.getTimezoneOffset(),_=new Date(c.getFullYear(),6,1).getTimezoneOffset();var m=new Date(c.getFullYear(),0,1).getTimezoneOffset();c=0|(_!=m&&c.getTimezoneOffset()==Math.min(m,_)),(b(),B)[d+32>>>2>>>0]=c}function mw(c){c>>>=0;var d=new Date((b(),B)[c+20>>>2>>>0]+1900,(b(),B)[c+16>>>2>>>0],(b(),B)[c+12>>>2>>>0],(b(),B)[c+8>>>2>>>0],(b(),B)[c+4>>>2>>>0],(b(),B)[c>>>2>>>0],0),_=(b(),B)[c+32>>>2>>>0],m=d.getTimezoneOffset(),y=new Date(d.getFullYear(),6,1).getTimezoneOffset(),x=new Date(d.getFullYear(),0,1).getTimezoneOffset(),C=Math.min(x,y);return 0>_?(b(),B)[c+32>>>2>>>0]=+(y!=x&&C==m):0<_!=(C==m)&&(y=Math.max(x,y),d.setTime(d.getTime()+6e4*((0<_?C:y)-m))),(b(),B)[c+24>>>2>>>0]=d.getDay(),_=(nu(d.getFullYear())?su:au)[d.getMonth()]+d.getDate()-1|0,(b(),B)[c+28>>>2>>>0]=_,(b(),B)[c>>>2>>>0]=d.getSeconds(),(b(),B)[c+4>>>2>>>0]=d.getMinutes(),(b(),B)[c+8>>>2>>>0]=d.getHours(),(b(),B)[c+12>>>2>>>0]=d.getDate(),(b(),B)[c+16>>>2>>>0]=d.getMonth(),(b(),B)[c+20>>>2>>>0]=d.getYear(),c=d.getTime(),BigInt(isNaN(c)?-1:c/1e3)}function ou(c,d,_,m,y,x,C){return s?we(16,1,c,d,_,m,y,x,C):-52}function iu(c,d,_,m,y,x){if(s)return we(17,1,c,d,_,m,y,x)}var Dn={},gw=()=>performance.timeOrigin+performance.now();function lu(c,d){if(s)return we(18,1,c,d);if(Dn[c]&&(clearTimeout(Dn[c].id),delete Dn[c]),!d)return 0;var _=setTimeout(()=>{delete Dn[c],lt(()=>Bu(c,performance.timeOrigin+performance.now()))},d);return Dn[c]={id:_,Ce:d},0}function ww(c,d,_,m){c>>>=0,d>>>=0,_>>>=0,m>>>=0;var y=new Date().getFullYear(),x=new Date(y,0,1).getTimezoneOffset();y=new Date(y,6,1).getTimezoneOffset();var C=Math.max(x,y);(b(),O)[c>>>2>>>0]=60*C,(b(),B)[d>>>2>>>0]=+(x!=y),c=(d=I=>{var R=Math.abs(I);return`UTC${0<=I?"-":"+"}${String(Math.floor(R/60)).padStart(2,"0")}${String(R%60).padStart(2,"0")}`})(x),d=d(y),y<x?(Zt(c,_,17),Zt(d,m,17)):(Zt(c,m,17),Zt(d,_,17))}var vw=()=>Date.now();function yw(c,d,_){return _>>>=0,0<=c&&3>=c?(c===0?c=Date.now():c=performance.timeOrigin+performance.now(),c=Math.round(1e6*c),(b(),X)[_>>>3>>>0]=BigInt(c),0):28}var ja=[],cu=(c,d)=>{ja.length=0;for(var _;_=(b(),H)[c++>>>0];){var m=_!=105;d+=(m&=_!=112)&&d%8?4:0,ja.push(_==112?(b(),O)[d>>>2>>>0]:_==106?(b(),X)[d>>>3>>>0]:_==105?(b(),B)[d>>>2>>>0]:(b(),ee)[d>>>3>>>0]),d+=m?8:4}return ja};function bw(c,d,_){return c>>>=0,d=cu(d>>>0,_>>>0),oo[c](...d)}function Mw(c,d,_){return c>>>=0,d=cu(d>>>0,_>>>0),oo[c](...d)}var xw=()=>{};function kw(c,d){return E(Hr(c>>>0,d>>>0))}var Tw=()=>{throw pe+=1,"unwind"};function Ew(){return 4294901760}var Cw=()=>1,Sw=()=>navigator.hardwareConcurrency;function Pw(c){c>>>=0;var d=(b(),H).length;if(c<=d||4294901760<c)return!1;for(var _=1;4>=_;_*=2){var m=d*(1+.2/_);m=Math.min(m,c+100663296);e:{m=(Math.min(4294901760,65536*Math.ceil(Math.max(c,m)/65536))-dr.buffer.byteLength+65535)/65536|0;try{dr.grow(m),J();var y=1;break e}catch{}y=void 0}if(y)return!0}return!1}var Wt=c=>{var d=er(c)+1,_=xs(d);return Zt(c,_,d),_},qa=(c,d)=>{(b(),O)[c>>>2>>>0]=d;var _=(b(),O)[c>>>2>>>0];(b(),O)[c+4>>>2>>>0]=(d-_)/4294967296},Bn=c=>(b(),O)[c>>>2>>>0]+4294967296*(b(),B)[c+4>>>2>>>0],Ze=[],Aw=(c,d)=>{Ze[c>>>0]=d},tr=[],ys=[],Xr=(c,d)=>{ys[c]=new Promise(_=>d.finally(()=>_(c)))},K=c=>{if(c)return Ze[c>>>0]},Fw=(c,d)=>{for(c=(b(),O)[c>>>2>>>0];c;c=(b(),O)[c>>>2>>>0])d[(b(),B)[c+4>>>2>>>0]](c)},bs=(c,d,_)=>{(b(),O)[c>>>2>>>0]=d,(b(),O)[c+4>>>2>>>0]=_},uu=c=>{var d=(b(),O)[c>>>2>>>0];return c=(b(),O)[c+4>>>2>>>0],Hr(d,c)},rr=c=>{var d=(b(),O)[c>>>2>>>0];return c=(b(),O)[c+4>>>2>>>0],d?Hr(d,c):c===0?"":void 0},Iw=c=>{var d=rr(c+4),_=(_=(b(),O)[c+12>>>2>>>0])?K(_):"auto";if(c+=16){var m=K((b(),O)[c+4>>>2>>>0]),y=(b(),O)[c+16>>>2>>>0],x=(b(),O)[c+20>>>2>>>0];if(y){for(var C={},I=0;I<y;++I){var R=x+24*I;C[uu(R+4)]=(b(),ee)[R+16>>>3>>>0]}y=C}else y=void 0;c={module:m,constants:y,entryPoint:rr(c+8)}}else c=void 0;return{label:d,layout:_,compute:c}},du=(c,d)=>{function _(m,y){m=c[m],(b(),O)[d+y>>>2>>>0]=m}_("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),qa(d+64,c.maxUniformBufferBindingSize),qa(d+72,c.maxStorageBufferBindingSize),_("maxVertexBuffers",88),qa(d+96,c.maxBufferSize),_("maxVertexAttributes",104),_("maxVertexBufferArrayStride",108),_("maxInterStageShaderVariables",112),_("maxColorAttachments",116),_("maxColorAttachmentBytesPerSample",120),_("maxComputeWorkgroupStorageSize",124),_("maxComputeInvocationsPerWorkgroup",128),_("maxComputeWorkgroupSizeX",132),_("maxComputeWorkgroupSizeY",136),_("maxComputeWorkgroupSizeZ",140),_("maxComputeWorkgroupsPerDimension",144),c.Ae!==void 0&&_("maxImmediateSize",148)},Lw=[,"validation","out-of-memory","internal"],Ow=[,"compatibility","core"],hu={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"},Nw=[,"low-power","high-performance"],Dw=[,"occlusion","timestamp"],Bw={undefined:1,unknown:1,destroyed:2};function zw(c,d,_,m,y,x){d=it(d),_=it(_),m>>>=0,y>>>=0,x>>>=0;var C=K(c>>>0);if(c={},x){var I=(b(),O)[x+12>>>2>>>0];if(I){var R=(b(),O)[x+16>>>2>>>0];c.requiredFeatures=Array.from((b(),O).subarray(R>>>2>>>0,R+4*I>>>2>>>0),Q=>hu[Q])}var j=(b(),O)[x+20>>>2>>>0];if(j){let Q=function(Se,Ye,Gn=!1){Ye=j+Ye,(Ye=(b(),O)[Ye>>>2>>>0])==4294967295||Gn&&Ye==0||(_e[Se]=Ye)},ue=function(Se,Ye){Ye=j+Ye;var Gn=(b(),O)[Ye>>>2>>>0],io=(b(),O)[Ye+4>>>2>>>0];Gn==4294967295&&io==4294967295||(_e[Se]=Bn(Ye))};var _e={};Q("maxTextureDimension1D",4),Q("maxTextureDimension2D",8),Q("maxTextureDimension3D",12),Q("maxTextureArrayLayers",16),Q("maxBindGroups",20),Q("maxBindGroupsPlusVertexBuffers",24),Q("maxDynamicUniformBuffersPerPipelineLayout",32),Q("maxDynamicStorageBuffersPerPipelineLayout",36),Q("maxSampledTexturesPerShaderStage",40),Q("maxSamplersPerShaderStage",44),Q("maxStorageBuffersPerShaderStage",48),Q("maxStorageTexturesPerShaderStage",52),Q("maxUniformBuffersPerShaderStage",56),Q("minUniformBufferOffsetAlignment",80),Q("minStorageBufferOffsetAlignment",84),ue("maxUniformBufferBindingSize",64),ue("maxStorageBufferBindingSize",72),Q("maxVertexBuffers",88),ue("maxBufferSize",96),Q("maxVertexAttributes",104),Q("maxVertexBufferArrayStride",108),Q("maxInterStageShaderVariables",112),Q("maxColorAttachments",116),Q("maxColorAttachmentBytesPerSample",120),Q("maxComputeWorkgroupStorageSize",124),Q("maxComputeInvocationsPerWorkgroup",128),Q("maxComputeWorkgroupSizeX",132),Q("maxComputeWorkgroupSizeY",136),Q("maxComputeWorkgroupSizeZ",140),Q("maxComputeWorkgroupsPerDimension",144),Q("maxImmediateSize",148,!0),c.requiredLimits=_e}(I=(b(),O)[x+24>>>2>>>0])&&(I={label:rr(I+4)},c.defaultQueue=I),c.label=rr(x+4)}pe+=1,Xr(d,C.requestDevice(c).then(Q=>{--pe,lt(()=>{Ze[y>>>0]=Q.queue,Ze[m>>>0]=Q,Xr(_,Q.lost.then(ue=>{lt(()=>{Q.onuncapturederror=()=>{};var Se=re(),Ye=Wt(ue.message);Ja(_,Bw[ue.reason],Ye),te(Se)})})),Q.onuncapturederror=ue=>{var Se=5;ue.error instanceof GPUValidationError?Se=2:ue.error instanceof GPUOutOfMemoryError?Se=3:ue.error instanceof GPUInternalError&&(Se=4);var Ye=re();ue=Wt(ue.error.message),Lu(m,Se,ue),te(Ye)},"adapterInfo"in Q||(Q.adapterInfo=C.info),eo(d,1,m,0)})},Q=>{--pe,lt(()=>{var ue=re(),Se=Wt(Q.message);eo(d,3,m,Se),_&&Ja(_,4,Se),te(ue)})}))}function Rw(c){var d=K(c>>>=0),_=tr[c];if(_){for(var m=0;m<_.length;++m)_[m]();delete tr[c]}d.destroy()}function Gw(c,d,_){_>>>=0;var m=K(c>>>=0);_==4294967295&&(_=void 0);try{var y=m.getMappedRange(d>>>0,_)}catch{return 0}var x=no(16,y.byteLength);return(b(),H).set(new Uint8Array(y),x>>>0),tr[c].push(()=>Ft(x)),x}function $w(c,d,_){_>>>=0;var m=K(c>>>=0);_==4294967295&&(_=void 0);try{var y=m.getMappedRange(d>>>0,_)}catch{return 0}var x=no(16,y.byteLength);return(b(),H).fill(0,x,y.byteLength),tr[c].push(()=>{new Uint8Array(y).set((b(),H).subarray(x>>>0,x+y.byteLength>>>0)),Ft(x)}),x}function Vw(c,d,_,m,y){c>>>=0,d=it(d),_=it(_),y>>>=0;var x=K(c);tr[c]=[],y==4294967295&&(y=void 0),pe+=1,Xr(d,x.mapAsync(_,m>>>0,y).then(()=>{--pe,lt(()=>{Ka(d,1,0)})},C=>{--pe,lt(()=>{re();var I=Wt(C.message);Ka(d,C.name==="AbortError"?4:C.name==="OperationError"?3:0,I),delete tr[c]})}))}function Uw(c){var d=K(c>>>=0),_=tr[c];if(_){for(var m=0;m<_.length;++m)_[m]();delete tr[c],d.unmap()}}function Ww(c){delete Ze[c>>>0]}function jw(c,d,_){c>>>=0,d>>>=0,_>>>=0;var m=!!(b(),O)[d+32>>>2>>>0];d={label:rr(d+4),usage:(b(),O)[d+16>>>2>>>0],size:Bn(d+24),mappedAtCreation:m},c=K(c);try{var y=c.createBuffer(d)}catch{return!1}return Ze[_>>>0]=y,m&&(tr[_]=[]),!0}function qw(c,d,_,m){c>>>=0,d=it(d),m>>>=0,_=Iw(_>>>0),c=K(c),pe+=1,Xr(d,c.createComputePipelineAsync(_).then(y=>{--pe,lt(()=>{Ze[m>>>0]=y,Ya(d,1,m,0)})},y=>{--pe,lt(()=>{var x=re(),C=Wt(y.message);Ya(d,y.reason==="validation"?3:y.reason==="internal"?4:0,m,C),te(x)})}))}function Hw(c,d,_){c>>>=0,d>>>=0,_>>>=0;var m=(b(),O)[d>>>2>>>0],y=(b(),B)[m+4>>>2>>>0];d={label:rr(d+4),code:""},y===2&&(d.code=uu(m+8)),c=K(c).createShaderModule(d),Ze[_>>>0]=c}var Qw=c=>{(c=K(c)).onuncapturederror=null,c.destroy()};function Xw(c,d){d=it(d),c=K(c>>>0),pe+=1,Xr(d,c.popErrorScope().then(_=>{--pe,lt(()=>{var m=5;_?_ instanceof GPUValidationError?m=2:_ instanceof GPUOutOfMemoryError?m=3:_ instanceof GPUInternalError&&(m=4):m=1;var y=re(),x=_?Wt(_.message):0;Za(d,1,m,x),te(y)})},_=>{--pe,lt(()=>{var m=re(),y=Wt(_.message);Za(d,1,5,y),te(m)})}))}function Yw(c,d,_,m){if(d=it(d),m>>>=0,_>>>=0){var y={featureLevel:Ow[(b(),B)[_+4>>>2>>>0]],powerPreference:Nw[(b(),B)[_+8>>>2>>>0]],forceFallbackAdapter:!!(b(),O)[_+12>>>2>>>0]};(c=(b(),O)[_>>>2>>>0])!==0&&(b(),y.Fe=!!(b(),O)[c+8>>>2>>>0])}"gpu"in navigator?(pe+=1,Xr(d,navigator.gpu.requestAdapter(y).then(x=>{--pe,lt(()=>{if(x)Ze[m>>>0]=x,zn(d,1,m,0);else{var C=re(),I=Wt("WebGPU not available on this browser (requestAdapter returned null)");zn(d,3,m,I),te(C)}})},x=>{--pe,lt(()=>{var C=re(),I=Wt(x.message);zn(d,4,m,I),te(C)})}))):(y=re(),c=Wt("WebGPU not available on this browser (navigator.gpu is not available)"),zn(d,3,m,c),te(y))}function Jw(c,d,_){return c>>>=0,d>>>=0,_>>>=0,tu(async()=>{var m=[];if(_){var y=(b(),B)[_>>>2>>>0];m.length=d+1,m[d]=new Promise(I=>setTimeout(I,y,0))}else m.length=d;for(var x=0;x<d;++x){var C=Bn(c+8*x);if(!(C in ys))return C;m[x]=ys[C]}return m=await Promise.race(m),delete ys[m],m})}var Ha,Qa={},fu=()=>{if(!Ha){var c,d={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(c in Qa)Qa[c]===void 0?delete d[c]:d[c]=Qa[c];var _=[];for(c in d)_.push(`${c}=${d[c]}`);Ha=_}return Ha};function pu(c,d){if(s)return we(19,1,c,d);c>>>=0,d>>>=0;var _,m=0,y=0;for(_ of fu()){var x=d+m;(b(),O)[c+y>>>2>>>0]=x,m+=Zt(_,x,1/0)+1,y+=4}return 0}function _u(c,d){if(s)return we(20,1,c,d);c>>>=0,d>>>=0;var _=fu();for(var m of((b(),O)[c>>>2>>>0]=_.length,c=0,_))c+=er(m)+1;return(b(),O)[d>>>2>>>0]=c,0}function mu(c){return s?we(21,1,c):52}function gu(c,d,_,m){return s?we(22,1,c,d,_,m):52}function wu(c,d,_,m){return s?we(23,1,c,d,_,m):70}var Kw=[null,[],[]];function vu(c,d,_,m){if(s)return we(24,1,c,d,_,m);d>>>=0,_>>>=0,m>>>=0;for(var y=0,x=0;x<_;x++){var C=(b(),O)[d>>>2>>>0],I=(b(),O)[d+4>>>2>>>0];d+=8;for(var R=0;R<I;R++){var j=c,_e=(b(),H)[C+R>>>0],Q=Kw[j];_e===0||_e===10?((j===1?S:E)(Nc(Q)),Q.length=0):Q.push(_e)}y+=I}return(b(),O)[m>>>2>>>0]=y,0}function Zw(c){return c>>>0}function ev(c,d){return du(K(c>>>0).limits,d>>>0),1}function tv(c,d){return K(c>>>0).features.has(hu[d])}function rv(c){return BigInt(K(c>>>0).size)}function nv(c){return BigInt(K(c>>>0).usage)}function sv(c,d){if(c>>>=0,d>>>=0){var _=rr(d+4);_={label:_,timestampWrites:d=(d=(b(),O)[d+12>>>2>>>0])!==0?{querySet:K((b(),O)[d+4>>>2>>>0]),beginningOfPassWriteIndex:(b(),O)[d+8>>>2>>>0],endOfPassWriteIndex:(b(),O)[d+12>>>2>>>0]}:void 0}}return d=K(c),c=Su(0),_=d.beginComputePass(_),Ze[c>>>0]=_,c}function av(c,d,_,m,y,x){_=it(_),y=it(y),x=it(x),K(c>>>0).copyBufferToBuffer(K(d>>>0),_,K(m>>>0),y,x)}function ov(c){var d=K(c>>>0);return c=Eu(0),d=d.finish(),Ze[c>>>0]=d,c}function iv(c,d,_,m,y,x){x=it(x),K(c>>>0).resolveQuerySet(K(d>>>0),_,m,K(y>>>0),x)}function lv(c,d,_,m){K(c>>>0).dispatchWorkgroups(d,_,m)}function cv(c,d,_){_=it(_),K(c>>>0).dispatchWorkgroupsIndirect(K(d>>>0),_)}function uv(c){K(c>>>0).end()}function dv(c,d,_,m,y){m>>>=0,y>>>=0,c=K(c>>>0),_=K(_>>>0),m==0?c.setBindGroup(d,_):c.setBindGroup(d,_,(b(),O),y>>>2,m)}function hv(c,d){K(c>>>0).setPipeline(K(d>>>0))}function fv(c,d,_){K(c>>>0).Ee(K(d>>>0),_)}function pv(c,d){var _=K(c>>>0);return c=Tu(0),d=_.getBindGroupLayout(d),Ze[c>>>0]=d,c}function _v(c,d){function _(y){var x=(b(),O)[y+8>>>2>>>0],C=(b(),O)[y+32>>>2>>>0],I=(b(),O)[y+36>>>2>>>0],R=0;return Fw(y,{327681:j=>{R=(b(),O)[j+8>>>2>>>0]}}),x?((C=Bn(y+24))==-1&&(C=void 0),x={buffer:K(x),offset:Bn(y+16),size:C}):x=K(C||I||R),{binding:(b(),O)[y+4>>>2>>>0],resource:x}}c>>>=0,d={label:rr(4+(d>>>=0)),layout:K((b(),O)[d+12>>>2>>>0]),entries:function(y,x){for(var C=[],I=0;I<y;++I)C.push(_(x+40*I));return C}((b(),O)[d+16>>>2>>>0],(b(),O)[d+20>>>2>>>0])},c=K(c);var m=ku(0);return Aw(m,c.createBindGroup(d)),m}function mv(c,d){var _;return c>>>=0,(d>>>=0)&&(_={label:rr(d+4)}),d=K(c),c=Cu(0),_=d.createCommandEncoder(_),Ze[c>>>0]=_,c}function gv(c,d){c>>>=0,d>>>=0,d={type:Dw[(b(),B)[d+12>>>2>>>0]],count:(b(),O)[d+16>>>2>>>0]};var _=K(c);return c=Pu(0),d=_.createQuerySet(d),Ze[c>>>0]=d,c}function wv(c,d){c=K(c>>>0).adapterInfo,d>>>=0,(b(),O)[d+52>>>2>>>0]=c.subgroupMinSize,(b(),O)[d+56>>>2>>>0]=c.subgroupMaxSize;var _=c.vendor+c.architecture+c.device+c.description,m=er(_)+1,y=Yr(m);return y&&Zt(_,y,m),_=y,m=er(c.vendor),bs(d+4,_,m),_+=m,m=er(c.architecture),bs(d+12,_,m),_+=m,m=er(c.device),bs(d+20,_,m),bs(d+28,_+m,er(c.description)),(b(),B)[d+36>>>2>>>0]=2,c=c.isFallbackAdapter?3:4,(b(),B)[d+40>>>2>>>0]=c,(b(),O)[d+44>>>2>>>0]=0,(b(),O)[d+48>>>2>>>0]=0,1}var vv={"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 yv(c,d){d>>>=0;var _=K(c>>>0);c=Yr(4*_.features.size);var m=0,y=0;for(let x of _.features)0<=(_=vv[x])&&((b(),B)[c+m>>>2>>>0]=_,m+=4,y++);(b(),O)[d+4>>>2>>>0]=c,(b(),O)[d>>>2>>>0]=y}function bv(c,d){return du(K(c>>>0).limits,d>>>0),1}function Mv(c,d){K(c>>>0).pushErrorScope(Lw[d])}function xv(c,d,_){d>>>=0,_>>>=0,c=K(c>>>0),d=Array.from((b(),B).subarray(_>>>2>>>0,_+4*d>>>2>>>0),m=>K(m)),c.submit(d)}function kv(c,d,_,m,y){_=it(_),m>>>=0,y>>>=0,c=K(c>>>0),d=K(d>>>0),m=(b(),H).subarray(m>>>0,m+y>>>0),c.writeBuffer(d,_,m,0,y)}s||function(){for(var c=t.numThreads-1;c--;)Sc();Ve.push(async()=>{var d=async function(){if(!s)return Promise.all(We.map(Cc))}();ve++,await d,--ve==0&&de&&(d=de,de=null,d())})}(),s||(dr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),J()),t.wasmBinary&&(f=t.wasmBinary),t.stackSave=()=>re(),t.stackRestore=c=>te(c),t.stackAlloc=c=>xs(c),t.setValue=function(c,d,_="i8"){switch(_.endsWith("*")&&(_="*"),_){case"i1":case"i8":(b(),G)[c>>>0]=d;break;case"i16":(b(),Z)[c>>>1>>>0]=d;break;case"i32":(b(),B)[c>>>2>>>0]=d;break;case"i64":(b(),X)[c>>>3>>>0]=BigInt(d);break;case"float":(b(),$)[c>>>2>>>0]=d;break;case"double":(b(),ee)[c>>>3>>>0]=d;break;case"*":(b(),O)[c>>>2>>>0]=d;break;default:xe(`invalid type for setValue: ${_}`)}},t.getValue=function(c,d="i8"){switch(d.endsWith("*")&&(d="*"),d){case"i1":case"i8":return(b(),G)[c>>>0];case"i16":return(b(),Z)[c>>>1>>>0];case"i32":return(b(),B)[c>>>2>>>0];case"i64":return(b(),X)[c>>>3>>>0];case"float":return(b(),$)[c>>>2>>>0];case"double":return(b(),ee)[c>>>3>>>0];case"*":return(b(),O)[c>>>2>>>0];default:xe(`invalid type for getValue: ${d}`)}},t.UTF8ToString=Hr,t.stringToUTF8=Zt,t.lengthBytesUTF8=er;var yu,bu,Xa,Ms,Ft,Yr,Mu,xu,ku,Tu,Eu,Cu,Su,Pu,Au,Fu,Iu,Ya,Ja,Ka,Za,zn,eo,Lu,to,Ou,Nu,Du,ro,Bu,zu,no,ce,Rn,Ru,te,xs,re,Gu,so,$u,Vu,Uu,ao,Wu,ju,qu,Hu,Qu,Xu,Yu,Ju,Ku,Zu,ed,td,rd,nd,sd,ad,od,id,ld,cd,ud,dd,hd,fd,pd,_d,md,gd,wd,vd,yd,bd,Md,xd,kd,Td,Ed,Cd,Sd,nr,Tv=[ur,kr,Fc,Dc,Bc,zc,Rc,Gc,$c,Vc,Uc,Wc,jc,qc,Hc,Qc,ou,iu,lu,pu,_u,mu,gu,wu,vu],oo={922732:(c,d,_,m,y)=>{if(t===void 0||!t.Uc)return 1;if((c=Hr(Number(c>>>0))).startsWith("./")&&(c=c.substring(2)),!(c=t.Uc.get(c)))return 2;if(d=Number(d>>>0),_=Number(_>>>0),m=Number(m>>>0),d+_>c.byteLength)return 3;try{let x=c.subarray(d,d+_);switch(y){case 0:(b(),H).set(x,m>>>0);break;case 1:t.ad?t.ad(m,x):t.oe(m,x);break;default:return 4}return 0}catch{return 4}},923556:(c,d,_)=>{t.Sd(c,(b(),H).subarray(d>>>0,d+_>>>0))},923620:()=>t.me(),923662:c=>{t.jd(c)},923699:()=>typeof wasmOffsetConverter<"u"};function Ev(c,d,_,m){var y=re();try{return Ju(c,d,_,m)}catch(x){if(te(y),x!==x+0)throw x;ce(1,0)}}function Cv(c,d,_){var m=re();try{return Qu(c,d,_)}catch(y){if(te(m),y!==y+0)throw y;ce(1,0)}}function Sv(c,d,_){var m=re();try{Uu(c,d,_)}catch(y){if(te(m),y!==y+0)throw y;ce(1,0)}}function Pv(c,d){var _=re();try{return ao(c,d)}catch(m){if(te(_),m!==m+0)throw m;ce(1,0)}}function Av(c){var d=re();try{Wu(c)}catch(_){if(te(d),_!==_+0)throw _;ce(1,0)}}function Fv(c,d,_,m,y,x,C){var I=re();try{return Hu(c,d,_,m,y,x,C)}catch(R){if(te(I),R!==R+0)throw R;ce(1,0)}}function Iv(c,d){var _=re();try{Ku(c,d)}catch(m){if(te(_),m!==m+0)throw m;ce(1,0)}}function Lv(c,d,_,m,y,x){var C=re();try{ju(c,d,_,m,y,x)}catch(I){if(te(C),I!==I+0)throw I;ce(1,0)}}function Ov(c,d,_,m){var y=re();try{Yu(c,d,_,m)}catch(x){if(te(y),x!==x+0)throw x;ce(1,0)}}function Nv(c,d,_,m,y,x,C){var I=re();try{ed(c,d,_,m,y,x,C)}catch(R){if(te(I),R!==R+0)throw R;ce(1,0)}}function Dv(c,d,_,m,y,x,C){var I=re();try{td(c,d,_,m,y,x,C)}catch(R){if(te(I),R!==R+0)throw R;ce(1,0)}}function Bv(c,d,_,m,y,x,C,I){var R=re();try{ud(c,d,_,m,y,x,C,I)}catch(j){if(te(R),j!==j+0)throw j;ce(1,0)}}function zv(c,d,_,m,y,x,C,I,R,j,_e,Q){var ue=re();try{rd(c,d,_,m,y,x,C,I,R,j,_e,Q)}catch(Se){if(te(ue),Se!==Se+0)throw Se;ce(1,0)}}function Rv(c,d,_,m,y){var x=re();try{return Zu(c,d,_,m,y)}catch(C){if(te(x),C!==C+0)throw C;ce(1,0)}}function Gv(c,d,_,m,y){var x=re();try{qu(c,d,_,m,y)}catch(C){if(te(x),C!==C+0)throw C;ce(1,0)}}function $v(c,d,_,m,y,x,C,I){var R=re();try{Xu(c,d,_,m,y,x,C,I)}catch(j){if(te(R),j!==j+0)throw j;ce(1,0)}}function Vv(c){var d=re();try{return dd(c)}catch(_){if(te(d),_!==_+0)throw _;ce(1,0)}}function Uv(c,d,_){var m=re();try{return hd(c,d,_)}catch(y){if(te(m),y!==y+0)throw y;ce(1,0)}}function Wv(c,d){var _=re();try{return kd(c,d)}catch(m){if(te(_),m!==m+0)throw m;return ce(1,0),0n}}function jv(c,d,_,m,y){var x=re();try{fd(c,d,_,m,y)}catch(C){if(te(x),C!==C+0)throw C;ce(1,0)}}function qv(c){var d=re();try{return nd(c)}catch(_){if(te(d),_!==_+0)throw _;return ce(1,0),0n}}function Hv(c,d,_,m,y,x){var C=re();try{return ld(c,d,_,m,y,x)}catch(I){if(te(C),I!==I+0)throw I;ce(1,0)}}function Qv(c,d,_,m,y,x){var C=re();try{return pd(c,d,_,m,y,x)}catch(I){if(te(C),I!==I+0)throw I;ce(1,0)}}function Xv(c,d,_,m,y,x){var C=re();try{return _d(c,d,_,m,y,x)}catch(I){if(te(C),I!==I+0)throw I;ce(1,0)}}function Yv(c,d,_,m,y,x,C,I){var R=re();try{return cd(c,d,_,m,y,x,C,I)}catch(j){if(te(R),j!==j+0)throw j;ce(1,0)}}function Jv(c,d,_,m,y){var x=re();try{return md(c,d,_,m,y)}catch(C){if(te(x),C!==C+0)throw C;return ce(1,0),0n}}function Kv(c,d,_,m){var y=re();try{return gd(c,d,_,m)}catch(x){if(te(y),x!==x+0)throw x;ce(1,0)}}function Zv(c,d,_,m){var y=re();try{return wd(c,d,_,m)}catch(x){if(te(y),x!==x+0)throw x;ce(1,0)}}function ey(c,d,_,m,y,x,C,I,R,j,_e,Q){var ue=re();try{return vd(c,d,_,m,y,x,C,I,R,j,_e,Q)}catch(Se){if(te(ue),Se!==Se+0)throw Se;ce(1,0)}}function ty(c,d,_,m,y,x,C,I,R,j,_e){var Q=re();try{yd(c,d,_,m,y,x,C,I,R,j,_e)}catch(ue){if(te(Q),ue!==ue+0)throw ue;ce(1,0)}}function ry(c,d,_,m,y,x,C,I,R,j,_e,Q,ue,Se,Ye,Gn){var io=re();try{bd(c,d,_,m,y,x,C,I,R,j,_e,Q,ue,Se,Ye,Gn)}catch(lo){if(te(io),lo!==lo+0)throw lo;ce(1,0)}}function ny(c,d,_,m){var y=re();try{return Md(c,d,_,m)}catch(x){if(te(y),x!==x+0)throw x;ce(1,0)}}function sy(c,d,_,m,y){var x=re();try{return xd(c,d,_,m,y)}catch(C){if(te(x),C!==C+0)throw C;ce(1,0)}}function ay(c,d,_){var m=re();try{return ad(c,d,_)}catch(y){if(te(m),y!==y+0)throw y;return ce(1,0),0n}}function oy(c,d,_){var m=re();try{return sd(c,d,_)}catch(y){if(te(m),y!==y+0)throw y;ce(1,0)}}function iy(c,d,_){var m=re();try{return od(c,d,_)}catch(y){if(te(m),y!==y+0)throw y;ce(1,0)}}function ly(c,d,_,m){var y=re();try{id(c,d,_,m)}catch(x){if(te(y),x!==x+0)throw x;ce(1,0)}}function ks(){if(0<ve)de=ks;else if(s)v?.(t),ie();else{for(var c=Ve;0<c.length;)c.shift()(t);0<ve?de=ks:(t.calledRun=!0,F||(ie(),v?.(t)))}}return s||(nr=await ct(),ks()),t.PTR_SIZE=4,t.webgpuInit=c=>{let d=new WeakMap,_,m,y=1;t.webgpuRegisterDevice=I=>{if(m!==void 0)throw Error("another WebGPU EP inference session is being created.");if(I){var R=d.get(I);if(!R){let j=((_e,Q=0)=>{var ue=Iu(Q);return Q=Fu(Q,ue),Ze[ue>>>0]=_e.queue,Ze[Q>>>0]=_e,Q})(I,R=xu(0));R=[y++,R,j],d.set(I,R)}return _=I,m=R[0],R}_=void 0,m=0};let x=new Map;t.webgpuOnCreateSession=I=>{if(m!==void 0){var R=m;if(m=void 0,I){let j=Xa(R);x.set(I,j),R===0&&c(_??K(j))}_=void 0}},t.webgpuOnReleaseSession=I=>{x.delete(I)};let C=Symbol("gpuBufferMetadata");t.webgpuRegisterBuffer=(I,R,j)=>{if(j)return I[C]=[j,NaN],j;if(j=I[C])return j[1]++,j[0];if((R=x.get(R))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return R=((_e,Q=0)=>(_e.mapState==="unmapped"||xe(),Q=Au(Q),Ze[Q>>>0]=_e,Q))(I,R),I[C]=[R,1],R},t.webgpuUnregisterBuffer=I=>{let R=I[C];if(!R)throw Error("Buffer is not registered");R[1]--,R[1]===0&&(Mu(R[0]),delete I[C])},t.webgpuGetBuffer=I=>K(I),t.webgpuCreateDownloader=(I,R,j)=>{if((j=x.get(j))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let _e=K(j),Q=16*Math.ceil(Number(R)/16);return async()=>{let ue=_e.createBuffer({size:Q,usage:9});try{let Se=_e.createCommandEncoder();return Se.copyBufferToBuffer(I,0,ue,0,Q),_e.queue.submit([Se.finish()]),await ue.mapAsync(GPUMapMode.READ),ue.getMappedRange().slice(0,R)}finally{ue.destroy()}}},t.ad=(I,R)=>{var j=R.buffer;let _e=R.byteOffset,Q=R.byteLength;if(R=16*Math.ceil(Number(Q)/16),I=K(I),!_){var ue=Xa(m);_=K(ue)}let Se=(ue=_.createBuffer({mappedAtCreation:!0,size:R,usage:6})).getMappedRange();new Uint8Array(Se).set(new Uint8Array(j,_e,Q)),ue.unmap(),(j=_.createCommandEncoder()).copyBufferToBuffer(ue,0,I,0,R),_.queue.submit([j.finish()]),ue.destroy()}},t.webnnInit=c=>{let d=c[0];[t.me,t.jd,t.webnnEnsureTensor,t.Sd,t.webnnDownloadTensor,t.le,t.webnnEnableTraceEvent]=c.slice(1),t.webnnReleaseTensorId=t.jd,t.webnnUploadTensor=t.Sd,t.webnnRegisterMLContext=t.le,t.webnnOnRunStart=_=>d.onRunStart(_),t.webnnOnRunEnd=d.onRunEnd.bind(d),t.webnnOnReleaseSession=_=>{d.onReleaseSession(_)},t.webnnCreateMLTensorDownloader=(_,m)=>d.createMLTensorDownloader(_,m),t.webnnRegisterMLTensor=(_,m,y,x)=>d.registerMLTensor(_,m,y,x),t.webnnCreateMLContext=_=>d.createMLContext(_),t.webnnRegisterMLConstant=(_,m,y,x,C,I)=>d.registerMLConstant(_,m,y,x,C,t.Uc,I),t.webnnRegisterGraphInput=d.registerGraphInput.bind(d),t.webnnIsGraphInput=d.isGraphInput.bind(d),t.webnnRegisterGraphOutput=d.registerGraphOutput.bind(d),t.webnnIsGraphOutput=d.isGraphOutput.bind(d),t.webnnCreateTemporaryTensor=d.createTemporaryTensor.bind(d),t.webnnIsGraphInputOutputTypeSupported=d.isGraphInputOutputTypeSupported.bind(d)},D?t:new Promise((c,d)=>{v=c,w=d})}var mf,Fd,Sy=fe(()=>{mf=Ad,Fd=globalThis.self?.name?.startsWith("em-pthread"),Fd&&Ad()}),_o,$o,Id,mt,gf,Es,Ld,Od,mo,Nd,go,wf,wo,vf,oi=fe(()=>{ai(),_o=typeof location>"u"?void 0:location.origin,$o=import.meta.url>"file:"&&import.meta.url<"file;",Id=()=>{{if($o){let e=URL;return new URL(new e("ort.webgpu.bundle.min.mjs",import.meta.url).href,_o).href}return import.meta.url}},mt=Id(),gf=()=>{if(mt&&!mt.startsWith("blob:"))return mt.substring(0,mt.lastIndexOf("/")+1)},Es=(e,t)=>{try{let r=t??mt;return(r?new URL(e,r):new URL(e)).origin===_o}catch{return!1}},Ld=(e,t)=>{let r=t??mt;try{return(r?new URL(e,r):new URL(e)).href}catch{return}},Od=(e,t)=>`${t??"./"}${e}`,mo=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Nd=async e=>(await import(e)).default,go=(Cy(),Vs(ff)).default,wf=async()=>{if(!mt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Es(mt))return[void 0,go()];let e=await mo(mt);return[e,go(e)]},wo=(Sy(),Vs(_f)).default,vf=async(e,t,r,n)=>{let s=wo&&!(e||t);if(s)if(mt)s=Es(mt)||n&&!r;else if(n&&!r)s=!0;else throw new Error("cannot determine the script source URL.");if(s)return[void 0,wo];{let a="ort-wasm-simd-threaded.asyncify.mjs",o=e??Ld(a,t),i=r&&o&&!Es(o,t),l=i?await mo(o):o??Od(a,t);return[i?l:void 0,await Nd(l)]}}}),vo,Cs,Vn,yo,Dd,Bd,zd,ii,Ce,$r=fe(()=>{oi(),Cs=!1,Vn=!1,yo=!1,Dd=()=>{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}},Bd=()=>{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}},zd=()=>{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}},ii=async e=>{if(Cs)return Promise.resolve();if(Vn)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(yo)throw new Error("previous call to 'initializeWebAssembly()' failed.");Vn=!0;let t=e.initTimeout,r=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!zd())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Bd())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let n=Dd();r>1&&!n&&(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."),e.numThreads=r=1);let s=e.wasmPaths,a=typeof s=="string"?s:void 0,o=s?.mjs,i=o?.href??o,l=s?.wasm,u=l?.href??l,h=e.wasmBinary,[f,p]=await vf(i,a,r>1,!!h||!!u),g=!1,v=[];if(t>0&&v.push(new Promise(w=>{setTimeout(()=>{g=!0,w()},t)})),v.push(new Promise((w,M)=>{let k={numThreads:r};if(h)k.wasmBinary=h,k.locateFile=T=>T;else if(u||a)k.locateFile=T=>u??a+T;else if(i&&i.indexOf("blob:")!==0)k.locateFile=T=>new URL(T,i).href;else if(f){let T=gf();T&&(k.locateFile=S=>T+S)}p(k).then(T=>{Vn=!1,Cs=!0,vo=T,w(),f&&URL.revokeObjectURL(f)},T=>{Vn=!1,yo=!0,M(T)})})),await Promise.race(v),g)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Ce=()=>{if(Cs&&vo)return vo;throw new Error("WebAssembly is not initialized yet.")}}),gt,Ws,Me,li=fe(()=>{$r(),gt=(e,t)=>{let r=Ce(),n=r.lengthBytesUTF8(e)+1,s=r._malloc(n);return r.stringToUTF8(e,s,n),t.push(s),s},Ws=(e,t,r,n)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([s,a])=>{let o=t?t+s:s;if(typeof a=="object")Ws(a,o+".",r,n);else if(typeof a=="string"||typeof a=="number")n(o,a.toString());else if(typeof a=="boolean")n(o,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},Me=e=>{let t=Ce(),r=t.stackSave();try{let n=t.PTR_SIZE,s=t.stackAlloc(2*n);t._OrtGetLastError(s,s+n);let a=Number(t.getValue(s,n===4?"i32":"i64")),o=t.getValue(s+n,"*"),i=o?t.UTF8ToString(o):"";throw new Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${i}`)}finally{t.stackRestore(r)}}}),yf,Py=fe(()=>{$r(),li(),yf=e=>{let t=Ce(),r=0,n=[],s=e||{};try{if(e?.logSeverityLevel===void 0)s.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)s.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(s.terminate=!1);let a=0;return e?.tag!==void 0&&(a=gt(e.tag,n)),r=t._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,a),r===0&&Me("Can't create run options."),e?.extra!==void 0&&Ws(e.extra,"",new WeakSet,(o,i)=>{let l=gt(o,n),u=gt(i,n);t._OrtAddRunConfigEntry(r,l,u)!==0&&Me(`Can't set a run config entry: ${o} - ${i}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(o=>t._free(o)),a}}}),Rd,Gd,$d,Ss,pr,Vd,bf,Ay=fe(()=>{$r(),li(),Rd=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},Gd=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},$d=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},Ss=(e,t,r,n)=>{let s=gt(t,n),a=gt(r,n);Ce()._OrtAddSessionConfigEntry(e,s,a)!==0&&Me(`Can't set a session config entry: ${t} - ${r}.`)},pr=(e,t,r,n)=>{let s=gt(t,n),a=gt(r,n);e.push([s,a])},Vd=async(e,t,r)=>{let n=t.executionProviders;for(let s of n){let a=typeof s=="string"?s:s.name,o=[];switch(a){case"webnn":if(a="WEBNN",typeof s!="string"){let f=s?.deviceType;f&&Ss(e,"deviceType",f,r)}break;case"webgpu":{a="WebGPU";let f;if(typeof s!="string"){let g=s;if(g.device)if(typeof GPUDevice<"u"&&g.device instanceof GPUDevice)f=g.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:v}=t;if(typeof v=="boolean"&&v&&pr(o,"enableGraphCapture","1",r),typeof g.preferredLayout=="string"&&pr(o,"preferredLayout",g.preferredLayout,r),g.forceCpuNodeNames){let w=Array.isArray(g.forceCpuNodeNames)?g.forceCpuNodeNames:[g.forceCpuNodeNames];pr(o,"forceCpuNodeNames",w.join(`
8
+ `),r)}g.validationMode&&pr(o,"validationMode",g.validationMode,r)}let p=Ce().webgpuRegisterDevice(f);if(p){let[g,v,w]=p;pr(o,"deviceId",g.toString(),r),pr(o,"webgpuInstance",v.toString(),r),pr(o,"webgpuDevice",w.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${a}`)}let i=gt(a,r),l=o.length,u=0,h=0;if(l>0){u=Ce()._malloc(l*Ce().PTR_SIZE),r.push(u),h=Ce()._malloc(l*Ce().PTR_SIZE),r.push(h);for(let f=0;f<l;f++)Ce().setValue(u+f*Ce().PTR_SIZE,o[f][0],"*"),Ce().setValue(h+f*Ce().PTR_SIZE,o[f][1],"*")}await Ce()._OrtAppendExecutionProvider(e,i,u,h,l)!==0&&Me(`Can't append execution provider: ${a}.`)}},bf=async e=>{let t=Ce(),r=0,n=[],s=e||{};$d(s);try{let a=Rd(s.graphOptimizationLevel??"all"),o=Gd(s.executionMode??"sequential"),i=typeof s.logId=="string"?gt(s.logId,n):0,l=s.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let u=s.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let h=typeof s.optimizedModelFilePath=="string"?gt(s.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(a,!!s.enableCpuMemArena,!!s.enableMemPattern,o,!!s.enableProfiling,0,i,l,u,h),r===0&&Me("Can't create session options."),s.executionProviders&&await Vd(r,s,n),s.enableGraphCapture!==void 0){if(typeof s.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${s.enableGraphCapture}`);Ss(r,"enableGraphCapture",s.enableGraphCapture.toString(),n)}if(s.freeDimensionOverrides)for(let[f,p]of Object.entries(s.freeDimensionOverrides)){if(typeof f!="string")throw new Error(`free dimension override name must be a string: ${f}`);if(typeof p!="number"||!Number.isInteger(p)||p<0)throw new Error(`free dimension override value must be a non-negative integer: ${p}`);let g=gt(f,n);t._OrtAddFreeDimensionOverride(r,g,p)!==0&&Me(`Can't set a free dimension override: ${f} - ${p}.`)}return s.extra!==void 0&&Ws(s.extra,"",new WeakSet,(f,p)=>{Ss(r,f,p,n)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&Me("Can't release session options."),n.forEach(o=>t._free(o)),a}}}),Lr,zs,rn,Kn,js,ci,ui,Vo,pn=fe(()=>{Lr=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},zs=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},rn=(e,t)=>{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][e],n=typeof t=="number"?t:t.reduce((s,a)=>s*a,1);return r>0?Math.ceil(n*r):void 0},Kn=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},js=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},ci=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",ui=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Vo=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),di,Mf=fe(()=>{ai(),di=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let s=t.body.getReader(),a;try{a=new ArrayBuffer(n)}catch(i){if(i instanceof RangeError){let l=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let o=0;for(;;){let{done:i,value:l}=await s.read();if(i)break;let u=l.byteLength;new Uint8Array(a,o,u).set(l),o+=u}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),xf,Fy=fe(()=>{pn(),xf=(e,t)=>new(Kn(t))(e)}),Ud,Wd,jd,qd,kf,Hd,nt,Tf=fe(()=>{pn(),Ud=["V","I","W","E","F"],Wd=(e,t)=>{console.log(`[${Ud[e]},${new Date().toISOString()}]${t}`)},kf=(e,t)=>{jd=e,qd=t},Hd=(e,t)=>{let r=js(e),n=js(jd);r>=n&&Wd(r,typeof t=="function"?t():t)},nt=(...e)=>{qd&&Hd(...e)}}),bo,Uo,Mo,Qd,xo,Xd,ko,To,Eo,Yd,Ef,Iy=fe(()=>{pn(),Tf(),bo=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Uo=(e,t)=>{if(t==="int32")return e;let r=bo.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);let n=r/8;if(e.byteLength%n!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${n}.`);let s=e.byteLength/n,a=new(Kn(t))(e.buffer,e.byteOffset,s);switch(t){case"int64":case"uint64":{let o=new Int32Array(s);for(let i=0;i<s;i++){let l=a[i];if(l>2147483647n||l<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");o[i]=Number(l)}return new Uint8Array(o.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&a.some(i=>i>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let o=Int32Array.from(a,Number);return new Uint8Array(o.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},Mo=(e,t)=>{if(t==="int32")return e;if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=e.byteLength/4,n=new Int32Array(e.buffer,e.byteOffset,r);switch(t){case"int64":{let s=BigInt64Array.from(n,BigInt);return new Uint8Array(s.buffer)}case"uint64":{if(n.some(a=>a<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let s=BigUint64Array.from(n,BigInt);return new Uint8Array(s.buffer)}case"int8":{if(n.some(a=>a<-128||a>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let s=Int8Array.from(n,Number);return new Uint8Array(s.buffer)}case"uint8":{if(n.some(s=>s<0||s>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(n,Number)}case"uint32":{if(n.some(a=>a<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let s=Uint32Array.from(n,Number);return new Uint8Array(s.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},Qd=1,xo=()=>Qd++,Xd=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),ko=(e,t)=>{let r=bo.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((n,s)=>n*s)*r/8):0},To=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:r,tensor:n,dataType:s,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=r,this.mlTensor=n,this.dataType=s,this.tensorShape=a,this.fallbackDataType=o}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return ko(this.dataType,this.tensorShape)}destroy(){nt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),r=Mo(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(r);return}else return r.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,r){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===r.length&&this.tensorShape.every((n,s)=>n===r[s])}setIsDataConverted(e){this.isDataConverted=e}},Eo=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,r,n){let s=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!a?.input.dataTypes.includes(t)){if(o=Xd.get(t),!o||a?.input.dataTypes.includes(o))throw new Error(`WebNN backend does not support data type: ${t}`);nt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(s,t,r))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==ko(t,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(e,t,r,i,!0,!0,o),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")t=Uo(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else nt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?Mo(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}else return t.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Yd=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=xo();return this.tensorTrackersById.set(e,new Eo(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,r,n,s){nt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${r}, shape: ${n}, copyOld: ${s}}`);let a=this.tensorTrackersById.get(t);if(!a)throw new Error("Tensor not found.");return a.ensureTensor(e,r,n,s)}upload(e,t){let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");r.upload(t)}async download(e,t){nt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");return r.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,r,n){let s=this.getMLContext(e),a=xo(),o=new To({sessionId:e,context:s,tensor:t,dataType:r,shape:n});return this.tensorTrackersById.set(a,new Eo(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,r,n,s,a,o){let i=this.getMLContext(e);for(let[u,h]of this.freeTensors.entries())if(h.canReuseTensor(i,t,r)){nt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${r}`);let f=this.freeTensors.splice(u,1)[0];return f.sessionId=e,f}nt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${r}}`);let l=await i.createTensor({dataType:o??t,shape:r,dimensions:r,usage:n,writable:s,readable:a});return new To({sessionId:e,context:i,tensor:l,dataType:t,shape:r,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Ef=(...e)=>new Yd(...e)}),Cf={};rs(Cf,{WebNNBackend:()=>Sf});var Un,Jd,Sf,Ly=fe(()=>{pn(),$r(),Fy(),Iy(),Tf(),Un=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Jd=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),n=Object.keys(t).sort();return r.length===n.length&&r.every((s,a)=>s===n[a]&&e[s]===t[s])},Sf=class{constructor(e){this.tensorManager=Ef(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,kf(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){nt("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){nt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let r of t)nt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let r=this.mlContextCache.findIndex(n=>n.gpuDevice===e);if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:n}),n}}else if(e===void 0){let r=this.mlContextCache.findIndex(n=>n.options===void 0&&n.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:n}),n}}let t=this.mlContextCache.findIndex(r=>Jd(r.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let r=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:r}),r}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let r=this.sessionIdsByMLContext.get(t);r||(r=new Set,this.sessionIdsByMLContext.set(t,r)),r.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(t);if(r.delete(e),r.size===0){this.sessionIdsByMLContext.delete(t);let n=this.mlContextCache.findIndex(s=>s.mlContext===t);n!==-1&&this.mlContextCache.splice(n,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){nt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,n,s){let a=Un.get(r);if(!a)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,n,s)}async createTemporaryTensor(e,t,r){nt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${r}}`);let n=Un.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let s=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,s,n,r,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(s):this.temporarySessionTensorIds.set(e,[s]),s}uploadTensor(e,t){if(!Ce().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");nt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let r=await this.tensorManager.download(e);return xf(r,t)}}registerMLTensor(e,t,r,n){let s=Un.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let a=this.tensorManager.registerTensor(e,t,s,n);return nt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${s}, dimensions: ${n}} -> {tensorId: ${a}}`),a}registerMLConstant(e,t,r,n,s,a,o=!1){if(!a)throw new Error("External mounted files are not available.");let i=e;e.startsWith("./")&&(i=e.substring(2));let l=a.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(t+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let u=l.slice(t,t+r).buffer,h;switch(s.dataType){case"float32":h=new Float32Array(u);break;case"float16":h=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(u):new Uint16Array(u);break;case"int32":h=new Int32Array(u);break;case"uint32":h=new Uint32Array(u);break;case"int64":if(o){let f=Uo(new Uint8Array(u),"int64");h=new Int32Array(f.buffer),s.dataType="int32"}else h=new BigInt64Array(u);break;case"uint64":h=new BigUint64Array(u);break;case"int8":h=new Int8Array(u);break;case"int4":case"uint4":case"uint8":h=new Uint8Array(u);break;default:throw new Error(`Unsupported data type: ${s.dataType} in creating WebNN Constant from external data.`)}return nt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${s.dataType}, shape: ${s.shape}}} ${o?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),n.constant(s,h)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let r=this.sessionGraphInputs.get(e);return r?r.includes(t):!1}isGraphOutput(e,t){let r=this.sessionGraphOutputs.get(e);return r?r.includes(t):!1}isGraphInputOutputTypeSupported(e,t,r=!0){let n=Un.get(Lr(t)),s=this.mlOpSupportLimitsBySessionId.get(e);return typeof n>"u"?!1:r?!!s?.input.dataTypes.includes(n):!!s?.output.dataTypes.includes(n)}flush(){}}}),Kd,hi,fi,_r,Zd,Co,qs,pi,_i,So,mi,gi,wi,Pf=fe(()=>{Gr(),Py(),Ay(),pn(),$r(),li(),Mf(),Kd=(e,t)=>{Ce()._OrtInit(e,t)!==0&&Me("Can't initialize onnxruntime.")},hi=async e=>{Kd(e.wasm.numThreads,js(e.logLevel))},fi=async(e,t)=>{Ce().asyncInit?.();let r=e.webgpu.adapter;if(t==="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 n=e.webgpu.powerPreference;if(n!==void 0&&n!=="low-power"&&n!=="high-performance")throw new Error(`Invalid powerPreference setting: "${n}"`);let s=e.webgpu.forceFallbackAdapter;if(s!==void 0&&typeof s!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${s}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:n,forceFallbackAdapter:s}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(t==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(t==="webgpu"&&Ce().webgpuInit(n=>{e.webgpu.device=n}),t==="webnn"){let n=new(Ly(),Vs(Cf)).WebNNBackend(e);Ce().webnnInit([n,()=>n.reserveTensorId(),s=>n.releaseTensorId(s),async(s,a,o,i,l)=>n.ensureTensor(s,a,o,i,l),(s,a)=>{n.uploadTensor(s,a)},async(s,a)=>n.downloadTensor(s,a),(s,a)=>n.registerMLContext(s,a),!!e.trace])}},_r=new Map,Zd=e=>{let t=Ce(),r=t.stackSave();try{let n=t.PTR_SIZE,s=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,s,s+n)!==0&&Me("Can't get session input/output count.");let a=n===4?"i32":"i64";return[Number(t.getValue(s,a)),Number(t.getValue(s+n,a))]}finally{t.stackRestore(r)}},Co=(e,t)=>{let r=Ce(),n=r.stackSave(),s=0;try{let a=r.PTR_SIZE,o=r.stackAlloc(2*a);r._OrtGetInputOutputMetadata(e,t,o,o+a)!==0&&Me("Can't get session input/output metadata.");let i=Number(r.getValue(o,"*"));s=Number(r.getValue(o+a,"*"));let l=r.HEAP32[s/4];if(l===0)return[i,0];let u=r.HEAPU32[s/4+1],h=[];for(let f=0;f<u;f++){let p=Number(r.getValue(s+8+f*a,"*"));h.push(p!==0?r.UTF8ToString(p):Number(r.getValue(s+8+(f+u)*a,"*")))}return[i,l,h]}finally{r.stackRestore(n),s!==0&&r._OrtFree(s)}},qs=e=>{let t=Ce(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},pi=async(e,t)=>{let r,n,s=Ce();Array.isArray(e)?[r,n]=e:e.buffer===s.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=qs(e);let a=0,o=0,i=0,l=[],u=[],h=[];try{if([o,l]=await bf(t),t?.externalData&&s.mountExternalData){let E=[];for(let F of t.externalData){let z=typeof F=="string"?F:F.path;E.push(di(typeof F=="string"?F:F.data).then(b=>{s.mountExternalData(z,b)}))}await Promise.all(E)}for(let E of t?.executionProviders??[])if((typeof E=="string"?E:E.name)==="webnn"){if(s.shouldTransferToMLTensor=!1,typeof E!="string"){let F=E,z=F?.context,b=F?.gpuDevice,U=F?.deviceType,G=F?.powerPreference;z?s.currentContext=z:b?s.currentContext=await s.webnnCreateMLContext(b):s.currentContext=await s.webnnCreateMLContext({deviceType:U,powerPreference:G})}else s.currentContext=await s.webnnCreateMLContext();break}a=await s._OrtCreateSession(r,n,o),s.webgpuOnCreateSession?.(a),a===0&&Me("Can't create a session."),s.jsepOnCreateSession?.(),s.currentContext&&(s.webnnRegisterMLContext(a,s.currentContext),s.currentContext=void 0,s.shouldTransferToMLTensor=!0);let[f,p]=Zd(a),g=!!t?.enableGraphCapture,v=[],w=[],M=[],k=[],T=[];for(let E=0;E<f;E++){let[F,z,b]=Co(a,E);F===0&&Me("Can't get an input name."),u.push(F);let U=s.UTF8ToString(F);v.push(U),M.push(z===0?{name:U,isTensor:!1}:{name:U,isTensor:!0,type:zs(z),shape:b})}for(let E=0;E<p;E++){let[F,z,b]=Co(a,E+f);F===0&&Me("Can't get an output name."),h.push(F);let U=s.UTF8ToString(F);w.push(U),k.push(z===0?{name:U,isTensor:!1}:{name:U,isTensor:!0,type:zs(z),shape:b});{if(g&&t?.preferredOutputLocation===void 0){T.push("gpu-buffer");continue}let G=typeof t?.preferredOutputLocation=="string"?t.preferredOutputLocation:t?.preferredOutputLocation?.[U]??"cpu",H=s.webnnIsGraphOutput;if(G==="cpu"&&H&&H(a,U)){T.push("ml-tensor-cpu-output");continue}if(G!=="cpu"&&G!=="cpu-pinned"&&G!=="gpu-buffer"&&G!=="ml-tensor")throw new Error(`Not supported preferred output location: ${G}.`);if(g&&G!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${G}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);T.push(G)}}let S=null;return T.some(E=>E==="gpu-buffer"||E==="ml-tensor"||E==="ml-tensor-cpu-output")&&(i=s._OrtCreateBinding(a),i===0&&Me("Can't create IO binding."),S={handle:i,outputPreferredLocations:T,outputPreferredLocationsEncoded:T.map(E=>E==="ml-tensor-cpu-output"?"ml-tensor":E).map(E=>Vo(E))}),_r.set(a,[a,u,h,S,g,!1]),[a,v,w,M,k]}catch(f){throw u.forEach(p=>s._OrtFree(p)),h.forEach(p=>s._OrtFree(p)),i!==0&&s._OrtReleaseBinding(i)!==0&&Me("Can't release IO binding."),a!==0&&s._OrtReleaseSession(a)!==0&&Me("Can't release session."),f}finally{s._free(r),o!==0&&s._OrtReleaseSessionOptions(o)!==0&&Me("Can't release session options."),l.forEach(f=>s._free(f)),s.unmountExternalData?.()}},_i=e=>{let t=Ce(),r=_r.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,s,a,o,i]=r;o&&(i&&t._OrtClearBoundOutputs(o.handle)!==0&&Me("Can't clear bound outputs."),t._OrtReleaseBinding(o.handle)!==0&&Me("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),s.forEach(l=>t._OrtFree(l)),a.forEach(l=>t._OrtFree(l)),t._OrtReleaseSession(n)!==0&&Me("Can't release session."),_r.delete(e)},So=async(e,t,r,n,s,a,o=!1)=>{if(!e){t.push(0);return}let i=Ce(),l=i.PTR_SIZE,u=e[0],h=e[1],f=e[3],p=f,g,v;if(u==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(o&&f!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let k=e[2].gpuBuffer;v=rn(Lr(u),h);{let T=i.webgpuRegisterBuffer;if(!T)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');g=T(k,n)}}else if(f==="ml-tensor"){let k=e[2].mlTensor;v=rn(Lr(u),h);let T=i.webnnRegisterMLTensor;if(!T)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');g=T(n,k,Lr(u),h)}else{let k=e[2];if(Array.isArray(k)){v=l*k.length,g=i._malloc(v),r.push(g);for(let T=0;T<k.length;T++){if(typeof k[T]!="string")throw new TypeError(`tensor data at index ${T} is not a string`);i.setValue(g+T*l,gt(k[T],r),"*")}}else{let T=i.webnnIsGraphInput,S=i.webnnIsGraphOutput;if(u!=="string"&&T&&S){let E=i.UTF8ToString(s);if(T(n,E)||S(n,E)){let F=Lr(u);v=rn(F,h),p="ml-tensor";let z=i.webnnCreateTemporaryTensor,b=i.webnnUploadTensor;if(!z||!b)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let U=await z(n,F,h);b(U,new Uint8Array(k.buffer,k.byteOffset,k.byteLength)),g=U}else v=k.byteLength,g=i._malloc(v),r.push(g),i.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,v),g)}else v=k.byteLength,g=i._malloc(v),r.push(g),i.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,v),g)}}let w=i.stackSave(),M=i.stackAlloc(4*h.length);try{h.forEach((T,S)=>i.setValue(M+S*l,T,l===4?"i32":"i64"));let k=i._OrtCreateTensor(Lr(u),g,v,M,h.length,Vo(p));k===0&&Me(`Can't create tensor for input/output. session=${n}, index=${a}.`),t.push(k)}finally{i.stackRestore(w)}},mi=async(e,t,r,n,s,a)=>{let o=Ce(),i=o.PTR_SIZE,l=_r.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let u=l[0],h=l[1],f=l[2],p=l[3],g=l[4],v=l[5],w=t.length,M=n.length,k=0,T=[],S=[],E=[],F=[],z=[],b=o.stackSave(),U=o.stackAlloc(w*i),G=o.stackAlloc(w*i),H=o.stackAlloc(M*i),Z=o.stackAlloc(M*i);try{[k,T]=yf(a),vr("wasm prepareInputOutputTensor");for(let $=0;$<w;$++)await So(r[$],S,F,e,h[t[$]],t[$],g);for(let $=0;$<M;$++)await So(s[$],E,F,e,f[n[$]],w+n[$],g);yr("wasm prepareInputOutputTensor");for(let $=0;$<w;$++)o.setValue(U+$*i,S[$],"*"),o.setValue(G+$*i,h[t[$]],"*");for(let $=0;$<M;$++)o.setValue(H+$*i,E[$],"*"),o.setValue(Z+$*i,f[n[$]],"*");if(p&&!v){let{handle:$,outputPreferredLocations:ee,outputPreferredLocationsEncoded:X}=p;if(h.length!==w)throw new Error(`input count from feeds (${w}) is expected to be always equal to model's input count (${h.length}).`);vr("wasm bindInputsOutputs");for(let A=0;A<w;A++){let L=t[A];await o._OrtBindInput($,h[L],S[A])!==0&&Me(`Can't bind input[${A}] for session=${e}.`)}for(let A=0;A<M;A++){let L=n[A];s[A]?.[3]?(z.push(E[A]),o._OrtBindOutput($,f[L],E[A],0)!==0&&Me(`Can't bind pre-allocated output[${A}] for session=${e}.`)):o._OrtBindOutput($,f[L],0,X[L])!==0&&Me(`Can't bind output[${A}] to ${ee[A]} for session=${e}.`)}yr("wasm bindInputsOutputs"),_r.set(e,[u,h,f,p,g,!0])}o.jsepOnRunStart?.(u),o.webnnOnRunStart?.(u);let W;p?W=await o._OrtRunWithBinding(u,p.handle,M,H,k):W=await o._OrtRun(u,G,U,w,Z,M,H,k),W!==0&&Me("failed to call OrtRun().");let B=[],O=[];vr("wasm ProcessOutputTensor");for(let $=0;$<M;$++){let ee=Number(o.getValue(H+$*i,"*"));if(ee===E[$]||z.includes(E[$])){B.push(s[$]),ee!==E[$]&&o._OrtReleaseTensor(ee)!==0&&Me("Can't release tensor.");continue}let X=o.stackSave(),A=o.stackAlloc(4*i),L=!1,D,J=0;try{o._OrtGetTensorData(ee,A,A+i,A+2*i,A+3*i)!==0&&Me(`Can't access output tensor data on index ${$}.`);let ie=i===4?"i32":"i64",xe=Number(o.getValue(A,ie));J=o.getValue(A+i,"*");let Fe=o.getValue(A+i*2,"*"),ct=Number(o.getValue(A+i*3,ie)),$e=[];for(let ve=0;ve<ct;ve++)$e.push(Number(o.getValue(Fe+ve*i,ie)));o._OrtFree(Fe)!==0&&Me("Can't free memory for tensor dims.");let ze=$e.reduce((ve,de)=>ve*de,1);D=zs(xe);let Ve=p?.outputPreferredLocations[n[$]];if(D==="string"){if(Ve==="gpu-buffer"||Ve==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ve=[];for(let de=0;de<ze;de++){let Ue=o.getValue(J+de*i,"*"),pe=o.getValue(J+(de+1)*i,"*"),we=de===ze-1?void 0:pe-Ue;ve.push(o.UTF8ToString(Ue,we))}B.push([D,$e,ve,"cpu"])}else if(Ve==="gpu-buffer"&&ze>0){let ve=o.webgpuGetBuffer;if(!ve)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let de=ve(J),Ue=rn(xe,ze);if(Ue===void 0||!ci(D))throw new Error(`Unsupported data type: ${D}`);L=!0;{o.webgpuRegisterBuffer(de,e,J);let pe=o.webgpuCreateDownloader(de,Ue,e);B.push([D,$e,{gpuBuffer:de,download:async()=>{let we=await pe();return new(Kn(D))(we)},dispose:()=>{o._OrtReleaseTensor(ee)!==0&&Me("Can't release tensor.")}},"gpu-buffer"])}}else if(Ve==="ml-tensor"&&ze>0){let ve=o.webnnEnsureTensor,de=o.webnnIsGraphInputOutputTypeSupported;if(!ve||!de)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(rn(xe,ze)===void 0||!ui(D))throw new Error(`Unsupported data type: ${D}`);if(!de(e,D,!1))throw new Error(`preferredLocation "ml-tensor" for ${D} output is not supported by current WebNN Context.`);let Ue=await ve(e,J,xe,$e,!1);L=!0,B.push([D,$e,{mlTensor:Ue,download:o.webnnCreateMLTensorDownloader(J,D),dispose:()=>{o.webnnReleaseTensorId(J),o._OrtReleaseTensor(ee)}},"ml-tensor"])}else if(Ve==="ml-tensor-cpu-output"&&ze>0){let ve=o.webnnCreateMLTensorDownloader(J,D)(),de=B.length;L=!0,O.push((async()=>{let Ue=[de,await ve];return o.webnnReleaseTensorId(J),o._OrtReleaseTensor(ee),Ue})()),B.push([D,$e,[],"cpu"])}else{let ve=Kn(D),de=new ve(ze);new Uint8Array(de.buffer,de.byteOffset,de.byteLength).set(o.HEAPU8.subarray(J,J+de.byteLength)),B.push([D,$e,de,"cpu"])}}finally{o.stackRestore(X),D==="string"&&J&&o._free(J),L||o._OrtReleaseTensor(ee)}}p&&!g&&(o._OrtClearBoundOutputs(p.handle)!==0&&Me("Can't clear bound outputs."),_r.set(e,[u,h,f,p,g,!1]));for(let[$,ee]of await Promise.all(O))B[$][2]=ee;return yr("wasm ProcessOutputTensor"),B}finally{o.webnnOnRunEnd?.(u),o.stackRestore(b),r.forEach(W=>{W&&W[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(W[2].gpuBuffer)}),s.forEach(W=>{W&&W[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(W[2].gpuBuffer)}),S.forEach(W=>o._OrtReleaseTensor(W)),E.forEach(W=>o._OrtReleaseTensor(W)),F.forEach(W=>o._free(W)),k!==0&&o._OrtReleaseRunOptions(k),T.forEach(W=>o._free(W))}},gi=e=>{let t=Ce(),r=_r.get(e);if(!r)throw new Error("invalid session id");let n=r[0],s=t._OrtEndProfiling(n);s===0&&Me("Can't get an profile file name."),t._OrtFree(s)},wi=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),mr,bt,Jr,Wn,jn,Ps,Po,As,Cr,Sr,eh,Af,Ff,If,Lf,Of,Nf,Df,Bf=fe(()=>{Gr(),Pf(),$r(),oi(),mr=()=>!!Ne.wasm.proxy&&typeof document<"u",Jr=!1,Wn=!1,jn=!1,As=new Map,Cr=(e,t)=>{let r=As.get(e);r?r.push(t):As.set(e,[t])},Sr=()=>{if(Jr||!Wn||jn||!bt)throw new Error("worker not ready")},eh=e=>{switch(e.data.type){case"init-wasm":Jr=!1,e.data.err?(jn=!0,Po[1](e.data.err)):(Wn=!0,Po[0]()),Ps&&(URL.revokeObjectURL(Ps),Ps=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=As.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Af=async()=>{if(!Wn){if(Jr)throw new Error("multiple calls to 'initWasm()' detected.");if(jn)throw new Error("previous call to 'initWasm()' failed.");if(Jr=!0,mr())return new Promise((e,t)=>{bt?.terminate(),wf().then(([r,n])=>{try{bt=n,bt.onerror=a=>t(a),bt.onmessage=eh,Po=[e,t];let s={type:"init-wasm",in:Ne};!s.in.wasm.wasmPaths&&(r||$o)&&(s.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.asyncify-BynIiDiv.wasm",import.meta.url).href}),bt.postMessage(s),Ps=r}catch(s){t(s)}},t)});try{await ii(Ne.wasm),await hi(Ne),Wn=!0}catch(e){throw jn=!0,e}finally{Jr=!1}}},Ff=async e=>{if(mr())return Sr(),new Promise((t,r)=>{Cr("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:Ne}};bt.postMessage(n)});await fi(Ne,e)},If=async e=>mr()?(Sr(),new Promise((t,r)=>{Cr("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};bt.postMessage(n,[e.buffer])})):qs(e),Lf=async(e,t)=>{if(mr()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Sr(),new Promise((r,n)=>{Cr("create",[r,n]);let s={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),bt.postMessage(s,a)})}else return pi(e,t)},Of=async e=>{if(mr())return Sr(),new Promise((t,r)=>{Cr("release",[t,r]);let n={type:"release",in:e};bt.postMessage(n)});_i(e)},Nf=async(e,t,r,n,s,a)=>{if(mr()){if(r.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(s.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return Sr(),new Promise((o,i)=>{Cr("run",[o,i]);let l=r,u={type:"run",in:{sessionId:e,inputIndices:t,inputs:l,outputIndices:n,options:a}};bt.postMessage(u,wi(l))})}else return mi(e,t,r,n,s,a)},Df=async e=>{if(mr())return Sr(),new Promise((t,r)=>{Cr("end-profiling",[t,r]);let n={type:"end-profiling",in:e};bt.postMessage(n)});gi(e)}}),Ao,th,zf,Oy=fe(()=>{Gr(),Bf(),pn(),ai(),Mf(),Ao=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},th=e=>{switch(e[3]){case"cpu":return new Lt(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!ci(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:s}=e[2];return Lt.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:s})}case"ml-tensor":{let t=e[0];if(!ui(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:s}=e[2];return Lt.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:s})}default:throw new Error(`invalid data location: ${e[3]}`)}},zf=class{async fetchModelAndCopyToWasmMemory(e){return If(await di(e))}async loadModel(e,t){Br();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Lf(r,t),zr()}async dispose(){return Of(this.sessionId)}async run(e,t,r){Br();let n=[],s=[];Object.entries(e).forEach(f=>{let p=f[0],g=f[1],v=this.inputNames.indexOf(p);if(v===-1)throw new Error(`invalid input '${p}'`);n.push(g),s.push(v)});let a=[],o=[];Object.entries(t).forEach(f=>{let p=f[0],g=f[1],v=this.outputNames.indexOf(p);if(v===-1)throw new Error(`invalid output '${p}'`);a.push(g),o.push(v)});let i=n.map((f,p)=>Ao(f,()=>`input "${this.inputNames[s[p]]}"`)),l=a.map((f,p)=>f?Ao(f,()=>`output "${this.outputNames[o[p]]}"`):null),u=await Nf(this.sessionId,s,i,o,l,r),h={};for(let f=0;f<u.length;f++)h[this.outputNames[o[f]]]=a[f]??th(u[f]);return zr(),h}startProfiling(){}endProfiling(){Df(this.sessionId)}}}),Rf={};rs(Rf,{OnnxruntimeWebAssemblyBackend:()=>jo,initializeFlags:()=>Wo,wasmBackend:()=>Gf});var Wo,jo,Gf,Ny=fe(()=>{Gr(),Bf(),Oy(),Wo=()=>{(typeof Ne.wasm.initTimeout!="number"||Ne.wasm.initTimeout<0)&&(Ne.wasm.initTimeout=0);let e=Ne.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),Ne.wasm.simd=!1),typeof Ne.wasm.proxy!="boolean"&&(Ne.wasm.proxy=!1),typeof Ne.wasm.trace!="boolean"&&(Ne.wasm.trace=!1),typeof Ne.wasm.numThreads!="number"||!Number.isInteger(Ne.wasm.numThreads)||Ne.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Ne.wasm.numThreads=1;else{let t=typeof navigator>"u"?hy("node:os").cpus().length:navigator.hardwareConcurrency;Ne.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},jo=class{async init(e){Wo(),await Af(),await Ff(e)}async createInferenceSessionHandler(e,t){let r=new zf;return await r.loadModel(e,t),r}},Gf=new jo});Gr();Gr();Gr();var Dy="1.25.0-dev.20260228-6e72d31970",By=hf;{let e=(Ny(),Vs(Rf)).wasmBackend;Or("webgpu",e,5),Or("webnn",e,5),Or("cpu",e,10),Or("wasm",e,10)}Object.defineProperty(Ne.versions,"web",{value:Dy,enumerable:!0});var zy=Object.freeze({__proto__:null,get InferenceSession(){return si},get TRACE(){return Us},get TRACE_EVENT_BEGIN(){return vr},get TRACE_EVENT_END(){return yr},get TRACE_FUNC_BEGIN(){return Br},get TRACE_FUNC_END(){return zr},get Tensor(){return Lt},default:By,get env(){return Ne},get registerBackend(){return Or}});const Ry=(e,t)=>{const r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];const n=r.getContext("2d");if(n!=null){let s,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[3]):(s=e.dims[3],a=e.dims[2]);const o=t?.format!==void 0?t.format:"RGB",i=t?.norm;let l,u;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?u=[0,0,0,0]:typeof i.bias=="number"?u=[i.bias,i.bias,i.bias,i.bias]:(u=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(u[3]=i.bias[3]));const h=a*s;let f=0,p=h,g=h*2,v=-1;o==="RGBA"?(f=0,p=h,g=h*2,v=h*3):o==="RGB"?(f=0,p=h,g=h*2):o==="RBG"&&(f=0,g=h,p=h*2);for(let w=0;w<a;w++)for(let M=0;M<s;M++){const k=(e.data[f++]-u[0])*l[0],T=(e.data[p++]-u[1])*l[1],S=(e.data[g++]-u[2])*l[2],E=v===-1?255:(e.data[v++]-u[3])*l[3];n.fillStyle="rgba("+k+","+T+","+S+","+E+")",n.fillRect(M,w,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")},Gy=(e,t)=>{const r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let n;if(r!=null){let s,a,o;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[1],o=e.dims[3]):(s=e.dims[3],a=e.dims[2],o=e.dims[1]);const i=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t?.norm;let u,h;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[3]=l.mean[3])),l===void 0||l.bias===void 0?h=[0,0,0,0]:typeof l.bias=="number"?h=[l.bias,l.bias,l.bias,l.bias]:(h=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(h[3]=l.bias[3]));const f=a*s;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const p=4;let g=0,v=1,w=2,M=3,k=0,T=f,S=f*2,E=-1;i==="RGBA"?(k=0,T=f,S=f*2,E=f*3):i==="RGB"?(k=0,T=f,S=f*2):i==="RBG"&&(k=0,S=f,T=f*2),n=r.createImageData(s,a);for(let F=0;F<a*s;g+=p,v+=p,w+=p,M+=p,F++)n.data[g]=(e.data[k++]-h[0])*u[0],n.data[v]=(e.data[T++]-h[1])*u[1],n.data[w]=(e.data[S++]-h[2])*u[2],n.data[M]=E===-1?255:(e.data[E++]-h[3])*u[3]}else throw new Error("Can not access image data");return n},Fo=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:r,width:n}=t,s=t.norm??{mean:255,bias:0};let a,o;typeof s.mean=="number"?a=[s.mean,s.mean,s.mean,s.mean]:a=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?o=[s.bias,s.bias,s.bias,s.bias]:o=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];const i=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",u=r*n,h=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3);let f=4,p=0,g=1,v=2,w=3,M=0,k=u,T=u*2,S=-1;i==="RGB"&&(f=3,p=0,g=1,v=2,w=-1),l==="RGBA"?S=u*3:l==="RBG"?(M=0,T=u,k=u*2):l==="BGR"&&(T=0,k=u,M=u*2);for(let F=0;F<u;F++,p+=f,v+=f,g+=f,w+=f)h[M++]=(e[p]+o[0])/a[0],h[k++]=(e[g]+o[1])/a[1],h[T++]=(e[v]+o[2])/a[2],S!==-1&&w!==-1&&(h[S++]=(e[w]+o[3])/a[3]);return l==="RGBA"?new Tt("float32",h,[1,4,r,n]):new Tt("float32",h,[1,3,r,n])},$y=async(e,t)=>{const r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,s=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string";let o,i=t??{};const l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},u=h=>typeof HTMLCanvasElement<"u"&&h instanceof HTMLCanvasElement||h instanceof OffscreenCanvas?h.getContext("2d"):null;if(r){const h=l();h.width=e.width,h.height=e.height;const f=u(h);if(f!=null){let p=e.height,g=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(p=t.resizedHeight,g=t.resizedWidth),t!==void 0){if(i=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=p,i.width=g}else i.tensorFormat="RGBA",i.height=p,i.width=g;f.drawImage(e,0,0),o=f.getImageData(0,0,g,p).data}else throw new Error("Can not access image data")}else if(n){let h,f;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(h=t.resizedHeight,f=t.resizedWidth):(h=e.height,f=e.width),t!==void 0&&(i=t),i.format="RGBA",i.height=h,i.width=f,t!==void 0){const p=l();p.width=f,p.height=h;const g=u(p);if(g!=null)g.putImageData(e,0,0),o=g.getImageData(0,0,f,h).data;else throw new Error("Can not access image data")}else o=e.data}else if(s){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");const h=l();h.width=e.width,h.height=e.height;const f=u(h);if(f!=null){const p=e.height,g=e.width;return f.drawImage(e,0,0,g,p),o=f.getImageData(0,0,g,p).data,i.height=p,i.width=g,Fo(o,i)}else throw new Error("Can not access image data")}else{if(a)return new Promise((h,f)=>{const p=l(),g=u(p);if(!e||!g)return f();const v=new Image;v.crossOrigin="Anonymous",v.src=e,v.onload=()=>{p.width=v.width,p.height=v.height,g.drawImage(v,0,0,p.width,p.height);const w=g.getImageData(0,0,p.width,p.height);i.height=p.height,i.width=p.width,h(Fo(w.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return Fo(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},Vy=(e,t)=>{const{width:r,height:n,download:s,dispose:a}=t,o=[1,n,r,4];return new Tt({location:"texture",type:"float32",texture:e,dims:o,download:s,dispose:a})},Uy=(e,t)=>{const{dataType:r,dims:n,download:s,dispose:a}=t;return new Tt({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},Wy=(e,t)=>{const{dataType:r,dims:n,download:s,dispose:a}=t;return new Tt({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:s,dispose:a})},jy=(e,t,r)=>new Tt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]}),sn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Rs=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let rh=!1;const qy=()=>{if(!rh){rh=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,n=typeof r<"u"&&r.from;e&&(sn.set("int64",BigInt64Array),Rs.set(BigInt64Array,"int64")),t&&(sn.set("uint64",BigUint64Array),Rs.set(BigUint64Array,"uint64")),n?(sn.set("float16",r),Rs.set(r,"float16")):sn.set("float16",Uint16Array)}},Hy=e=>{let t=1;for(let r=0;r<e.length;r++){const n=e[r];if(typeof n!="number"||!Number.isSafeInteger(n))throw new TypeError(`dims[${r}] must be an integer, got: ${n}`);if(n<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${n}`);t*=n}return t},Qy=(e,t)=>{switch(e.location){case"cpu":return new Tt(e.type,e.data,t);case"cpu-pinned":return new Tt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Tt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Tt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Tt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let Tt=class{constructor(t,r,n){qy();let s,a;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,s=t.type,a=t.dims,t.location){case"cpu-pinned":{const i=sn.get(s);if(!i)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(t.data instanceof i))throw new TypeError(`buffer should be of type ${i.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 i,l;if(typeof t=="string")if(s=t,l=n,t==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{const u=sn.get(t);if(u===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t==="float16"&&u===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${u.name} as data.`);t==="uint64"||t==="int64"?i=u.from(r,BigInt):i=u.from(r)}else if(r instanceof u)i=r;else if(r instanceof Uint8ClampedArray)if(t==="uint8")i=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&r instanceof Uint16Array&&u!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${s} tensor's data must be type of ${u}`)}else if(l=r,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const u=typeof t[0];if(u==="string")s="string",i=t;else if(u==="boolean")s="bool",i=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${u}.`)}else if(t instanceof Uint8ClampedArray)s="uint8",i=Uint8Array.from(t);else{const u=Rs.get(t.constructor);if(u===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);s=u,i=t}if(l===void 0)l=[i.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");a=l,this.cpuData=i,this.dataLocation="cpu"}const o=Hy(a);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=a,this.size=o}static async fromImage(t,r){return $y(t,r)}static fromTexture(t,r){return Vy(t,r)}static fromGpuBuffer(t,r){return Uy(t,r)}static fromMLTensor(t,r){return Wy(t,r)}static fromPinnedBuffer(t,r,n){return jy(t,r,n)}toDataURL(t){return Ry(this,t)}toImageData(t){return Gy(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;const r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,t&&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(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Qy(this,t)}};const Xy=Tt;var Io={},Yy=Object.defineProperty,_n=(e,t)=>{for(var r in t)Yy(e,r,{get:t[r],enumerable:!0})},kt={},Qt={},Jy={},Ky="4.0.0-next.5",ln=!Hf(kt),$f=!Hf(Qt),Hs=typeof self<"u"&&"caches"in self,Zy=typeof globalThis.Deno<"u",Vf=Zy&&Hs&&!ln,Uf=typeof process<"u",Wf=Uf&&process?.release?.name==="node"&&!Vf,jf=typeof window<"u"&&typeof window.document<"u",qf=typeof self<"u"&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),eb=Wf||typeof navigator<"u"&&"gpu"in navigator,tb=typeof navigator<"u"&&"ml"in navigator,rb=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",nb=()=>{if(typeof navigator>"u")return!1;const e=navigator.userAgent,r=(navigator.vendor||"").indexOf("Apple")>-1,n=!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes("Chrome")&&!e.includes("Android");return r&&n},sb=nb(),Ae=Object.freeze({IS_BROWSER_ENV:jf,IS_WEBWORKER_ENV:qf,IS_WEB_CACHE_AVAILABLE:Hs,IS_WEBGPU_AVAILABLE:eb,IS_WEBNN_AVAILABLE:tb,IS_SAFARI:sb,IS_PROCESS_AVAILABLE:Uf,IS_NODE_ENV:Wf,IS_FS_AVAILABLE:ln,IS_PATH_AVAILABLE:$f,IS_CRYPTO_AVAILABLE:rb}),vi=ln&&$f,Qs="./";if(vi){const e=Object(import.meta).url;e?Qs=Qt.dirname(Qt.dirname(Jy.fileURLToPath(e))):typeof __dirname<"u"&&(Qs=Qt.dirname(__dirname))}var ab=vi?Qt.join(Qs,"/.cache/"):null,nh="/models/",ob=vi?Qt.join(Qs,nh):nh,ib=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,Ot=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),sh=Ot.WARNING,ye={version:Ky,backends:{onnx:{}},get logLevel(){return sh},set logLevel(e){sh=e,ye.backends.onnx?.setLogLevel?.(e)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(jf||qf||Vf),localModelPath:ob,useFS:ln,useBrowserCache:Hs,useFSCache:ln,cacheDir:ab,useCustomCache:!1,customCache:null,useWasmCache:Hs||ln,cacheKey:"transformers-cache",fetch:ib};function Hf(e){return Object.keys(e).length===0}function an(e,t){e&&e(t)}function lb(e){return Number.isInteger(e)||typeof e=="bigint"}function ah(e){return e==null||e===-1}function oh(e){const t=[];let r=e;for(;Array.isArray(r);)t.push(r.length),r=r[0];return t}function Nt(...e){return Array.prototype.concat.apply([],e)}function Xs(e,t){return Math.abs((e+t)%(2*t)-t)}function ht(e,t){return Object.assign({},...t.map(r=>{if(e[r]!==void 0)return{[r]:e[r]}}))}function cb(e,t){let r=0;for(const n of e)n===t&&++r;return r}var he={error(...e){ye.logLevel<=Ot.ERROR&&console.error(...e)},warn(...e){ye.logLevel<=Ot.WARNING&&console.warn(...e)},info(...e){ye.logLevel<=Ot.INFO&&console.log(...e)},debug(...e){ye.logLevel<=Ot.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},ub=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){const t=Object.create(null);for(const r of e){let n=t;for(let s=0;s<r.length;++s){const a=r[s];n=n[a]??=Object.create(null)}n.end=r}return t}split(e){const t=[],r=e.length;let n=0,s=0;for(;s<r;){let a=this.trie,o=null,i=s;for(;i<r&&(a=a[e[i]]);)a.end&&(o=a.end),++i;o?(s>n&&t.push(e.slice(n,s)),t.push(o),s+=o.length,n=s):++s}return n<r&&t.push(e.slice(n)),t}},ih=ub,db=class{constructor(e){this.content=e.content,this.id=e.id,this.single_word=e.single_word??!1,this.lstrip=e.lstrip??!1,this.rstrip=e.rstrip??!1,this.special=e.special??!1,this.normalized=e.normalized??!this.special}},hb=db,Qf=(()=>{const e=[...Array.from({length:94},(s,a)=>a+33),...Array.from({length:12},(s,a)=>a+161),...Array.from({length:82},(s,a)=>a+174)],t=e.slice();let r=0;for(let s=0;s<256;++s)e.includes(s)||(e.push(s),t.push(256+r),r+=1);const n=t.map(s=>String.fromCharCode(s));return Object.fromEntries(e.map((s,a)=>[s,n[a]]))})(),fb=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[r,t])),pb=fb(Qf),lh=".,!?…。,、।۔،",_b=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|[${lh}])]+`,` ?[^\\s${lh}]+`]]),Ys="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",yi=e=>e.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),ua=(e,t=!0)=>{if(e.Regex!==void 0){let r=e.Regex.replace(/\\([#&~])/g,"$1");r=r.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(const[n,s]of _b)r=r.replaceAll(n,s);try{return new RegExp(r,"gu")}catch(n){if(!(n instanceof SyntaxError)||!n.message.toLowerCase().includes("invalid property name"))throw n;let s=!1;const a=r.replace(/(\\[pP])\{([^}=]+)\}/g,(o,i,l)=>{try{return new RegExp(`\\p{${l}}`,"u"),`${i}{${l}}`}catch{return s=!0,`${i}{Script=${l}}`}});if(!s)throw n;try{return new RegExp(a,"gu")}catch{throw n}}}else if(e.String!==void 0){const r=mb(e.String);return new RegExp(t?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",e),null},mb=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),gb=(e,t,r)=>{const n=[];let s=0;for(;s<e.length;){if(n.push(e[s]),(t.get(e[s])??r)!==r){++s;continue}for(;++s<e.length&&(t.get(e[s])??r)===r;)t.get(n.at(-1))!==r&&(n[n.length-1]+=e[s])}return n},wb=e=>e>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,vb=e=>Number.isInteger(e)||typeof e=="bigint",yb=e=>{let t=0;for(const r of e)++t;return t},bb=e=>Xf(e.toLowerCase()),Dt=(...e)=>Array.prototype.concat.apply([],e),bi=e=>new Map(Object.entries(e)),Mb=(e,t)=>{const r=[];let n=0;for(const s of e.matchAll(t)){const a=s[0];n<s.index&&r.push(e.slice(n,s.index)),a.length>0&&r.push(a),n=s.index+a.length}return n<e.length&&r.push(e.slice(n)),r},Xf=e=>e.replace(/\p{M}/gu,""),ch=(e,t,r=[])=>{if(!e||Array.isArray(e)||typeof e!="object")return`${t} must be a valid object`;for(const n of r)if(!(n in e))return`${t} must contain a "${n}" property`;return null},xb=e=>e.match(/\S+/g)||[],kb=class{constructor(){const e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},ns=kb,Tb=class extends ns{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},or=Tb,Eb=class extends or{tokenize_chinese_chars(e){const t=[];for(let r=0;r<e.length;++r){const n=e[r],s=n.charCodeAt(0);wb(s)?(t.push(" "),t.push(n),t.push(" ")):t.push(n)}return t.join("")}strip_accents(e){return e.normalize("NFD").replace(/\p{Mn}/gu,"")}is_control(e){switch(e){case" ":case`
9
+ `:case"\r":return!1;default:return/^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(e)}}clean_text(e){const t=[];for(const r of e){const n=r.charCodeAt(0);n===0||n===65533||this.is_control(r)||(/^\s$/.test(r)?t.push(" "):t.push(r))}return t.join("")}normalize(e){return this.config.clean_text&&(e=this.clean_text(e)),this.config.handle_chinese_chars&&(e=this.tokenize_chinese_chars(e)),this.config.lowercase?(e=e.toLowerCase(),this.config.strip_accents!==!1&&(e=this.strip_accents(e))):this.config.strip_accents&&(e=this.strip_accents(e)),e}},Cb=Eb,Sb=class extends or{constructor(e){super(e),this.charsmap=e.precompiled_charsmap??null}normalize(e){return e=e.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),e=e.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),e.includes("~")?e=e.split("~").map(r=>r.normalize("NFKC")).join("~"):e=e.normalize("NFKC"),e}},Pb=Sb,Ab=class extends or{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(t=>Yf(t))}normalize(e){return this.normalizers.reduce((t,r)=>r?r.normalize(t):t,e)}},Fb=Ab,Ib=class extends or{normalize(e){const t=ua(this.config.pattern??{});return t===null?e:e.replaceAll(t,this.config.content??"")}},Lb=Ib,Ob=class extends or{constructor(){super(...arguments),this.form="NFC"}normalize(e){return e=e.normalize(this.form),e}},da=Ob,Nb=class extends da{constructor(){super(...arguments),this.form="NFC"}},Db=Nb,Bb=class extends da{constructor(){super(...arguments),this.form="NFD"}},zb=Bb,Rb=class extends da{constructor(){super(...arguments),this.form="NFKC"}},Gb=Rb,$b=class extends da{constructor(){super(...arguments),this.form="NFKD"}},Vb=$b,Ub=class extends or{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}},Wb=Ub,jb=class extends or{normalize(e){return Xf(e)}},qb=jb,Hb=class extends or{normalize(e){return e.toLowerCase()}},Qb=Hb,Xb=class extends or{normalize(e){return e=this.config.prepend+e,e}},Yb=Xb;function Jb(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new Cb(e);case"Precompiled":return new Pb(e);case"Sequence":return new Fb(e);case"Replace":return new Lb(e);case"NFC":return new Db(e);case"NFD":return new zb(e);case"NFKC":return new Gb(e);case"NFKD":return new Vb(e);case"Strip":return new Wb(e);case"StripAccents":return new qb(e);case"Lowercase":return new Qb(e);case"Prepend":return new Yb(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}var Yf=Jb,Kb=class extends ns{pre_tokenize(e,t){return(Array.isArray(e)?e.map(r=>this.pre_tokenize_text(r,t)):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}},zt=Kb,Zb=class extends zt{constructor(e){super(),this.config=e,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=Qf,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){return this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(n=>Array.from(this.text_encoder.encode(n),s=>this.byte_encoder[s]).join(""))}},e0=Zb,t0=class extends zt{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},r0=t0,n0=class extends zt{constructor(e){super(),this.replacement=e.replacement??"▁",this.str_rep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??"always"}pre_tokenize_text(e,t){const{section_index:r=void 0}=t??{};let n=e.replaceAll(" ",this.str_rep);return!n.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(n=this.str_rep+n),[n]}},s0=n0,a0=class extends zt{constructor(e){super(),this.config=e,this.pattern=ua(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?e.split(this.pattern).filter(t=>t):Mb(e,this.pattern)}},o0=a0,i0=class extends zt{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${Ys}]+|[${Ys}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},l0=i0,c0=class extends zt{constructor(e){super(),this.config=e;const t=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(t,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},u0=c0,d0=class extends zt{constructor(){super(),this.pattern=new RegExp(`[^\\s${Ys}]+|[${Ys}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},h0=d0,f0=class extends zt{constructor(e){super(),this.config=e,this.pattern=ua(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??"")]}},p0=f0,_0=class extends zt{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(t=>Jf(t))}pre_tokenize_text(e,t){return this.tokenizers.reduce((r,n)=>n?n.pre_tokenize(r,t):r,[e])}},m0=_0,g0=class extends zt{pre_tokenize_text(e){return xb(e)}},w0=g0,v0=class extends zt{constructor(e){super(),this.config=e,this._length=e.length}pre_tokenize_text(e){const t=[];for(let r=0;r<e.length;r+=this._length)t.push(e.slice(r,r+this._length));return t}},y0=v0;function b0(e){if(e===null)return null;switch(e.type){case"BertPreTokenizer":return new h0;case"Sequence":return new m0(e);case"Whitespace":return new r0;case"WhitespaceSplit":return new w0;case"Metaspace":return new s0(e);case"ByteLevel":return new e0(e);case"Split":return new o0(e);case"Punctuation":return new l0(e);case"Digits":return new u0(e);case"Replace":return new p0(e);case"FixedLength":return new y0(e);default:throw new Error(`Unknown PreTokenizer type: ${e.type}`)}}var Jf=b0,M0=class extends ns{constructor(e){super(),this.config=e,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(e){let t=this.encode(e);return this.fuse_unk&&(t=gb(t,this.tokens_to_ids,this.unk_token_id)),t}},ha=M0,x0=class extends ha{constructor(e){super(e),this.max_input_chars_per_word=100,this.tokens_to_ids=bi(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[t,r]of this.tokens_to_ids)this.vocab[r]=t}encode(e){const t=[];for(const r of e){const n=[...r];if(n.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let s=!1,a=0;const o=[];for(;a<n.length;){let i=n.length,l=null;for(;a<i;){let u=n.slice(a,i).join("");if(a>0&&(u=this.config.continuing_subword_prefix+u),this.tokens_to_ids.has(u)){l=u;break}--i}if(l===null){s=!0;break}o.push(l),a=i}s?t.push(this.unk_token):t.push(...o)}return t}},uh=x0,dh=class Kf{constructor(t,r){this.is_leaf=t,this.children=r}static default(){return new Kf(!1,new Map)}},k0=class{constructor(){this.root=dh.default()}extend(e){for(const t of e)this.push(t)}push(e){let t=this.root;for(const r of e){let n=t.children.get(r);n===void 0&&(n=dh.default(),t.children.set(r,n)),t=n}t.is_leaf=!0}*common_prefix_search(e){let t=this.root;if(t===void 0)return;let r="";for(const n of e){if(r+=n,t=t.children.get(n),t===void 0)return;t.is_leaf&&(yield r)}}},T0=k0,Lo=class Zf{constructor(t,r,n,s,a){this.token_id=t,this.node_id=r,this.pos=n,this.length=s,this.score=a,this.prev=null,this.backtrace_score=0}clone(){const t=new Zf(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},E0=class{constructor(e,t,r){this.chars=Array.from(e),this.len=this.chars.length,this.bos_token_id=t,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},()=>[]);const n=new Lo(this.bos_token_id??0,0,0,0,0),s=new Lo(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(n.clone()),this.nodes.push(s.clone()),this.begin_nodes[this.len].push(s),this.end_nodes[0].push(n)}insert(e,t,r,n){const s=this.nodes.length,a=new Lo(n,s,e,t,r);this.begin_nodes[e].push(a),this.end_nodes[e+t].push(a),this.nodes.push(a)}viterbi(){const e=this.len;let t=0;for(;t<=e;){if(this.begin_nodes[t].length==0)return[];for(let o of this.begin_nodes[t]){o.prev=null;let i=0,l=null;for(let u of this.end_nodes[t]){const h=u.backtrace_score+o.score;(l===null||h>i)&&(l=u.clone(),i=h)}if(l!==null)o.prev=l,o.backtrace_score=i;else return[]}++t}const r=[],s=this.begin_nodes[e][0].prev;if(s===null)return[];let a=s.clone();for(;a.prev!==null;)r.push(a.clone()),a=a.clone().prev.clone();return r.reverse(),r}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join("")}tokens(){return this.viterbi().map(t=>this.piece(t))}token_ids(){return this.viterbi().map(t=>t.token_id)}},C0=E0;function S0(e){if(e.length===0)throw new Error("Array must not be empty");let t=e[0],r=0;for(let n=1;n<e.length;++n)e[n]<t&&(t=e[n],r=n);return[t,r]}var P0=class extends ha{constructor(e,t){super(e);const r=e.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let n=0;n<r;++n)[this.vocab[n],this.scores[n]]=e.vocab[n];this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map((n,s)=>[n,s])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=S0(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new T0,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){const t=e.chars,r=1;let n=0;for(;n<t.length;){let s=!1;const a=t.slice(n).join(""),o=this.trie.common_prefix_search(a);for(const i of o){const l=this.tokens_to_ids.get(i),u=this.scores[l],h=yb(i);e.insert(n,h,u,l),!s&&h===r&&(s=!0)}s||e.insert(n,r,this.unk_score,this.unk_token_id),n+=r}}tokenize(e){const t=new C0(e,this.bos_token_id,this.eos_token_id);return this.populate_nodes(t),t.tokens()}encode(e){const t=[];for(const r of e){const n=this.tokenize(r);t.push(...n)}return t}},hh=P0,A0=class{constructor(e=(r,n)=>r>n,t=1/0){this._heap=[],this._comparator=e,this._max_size=t}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(const t of e)if(this.size<this._max_size)this._heap.push(t),this._sift_up();else{const r=this._smallest();this._comparator(t,this._heap[r])&&(this._heap[r]=t,this._sift_up_from(r))}return this.size}pop(){const e=this.peek(),t=this.size-1;return t>0&&this._swap(0,t),this._heap.pop(),this._sift_down(),e}replace(e){const t=this.peek();return this._heap[0]=e,this._sift_down(),t}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){const r=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(e){for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_sift_down(){let e=0;for(;this._left(e)<this.size&&this._greater(this._left(e),e)||this._right(e)<this.size&&this._greater(this._right(e),e);){const t=this._right(e)<this.size&&this._greater(this._right(e),this._left(e))?this._right(e):this._left(e);this._swap(e,t),e=t}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},F0=A0,I0=class{constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;const t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){this.cache.has(e)&&this.cache.delete(e),this.cache.set(e,t),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},L0=I0,O0=class extends ha{constructor(e){super(e),this.tokens_to_ids=bi(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[r,n]of this.tokens_to_ids)this.vocab[n]=r;const t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,n)=>[JSON.stringify(r),n])),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!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 L0(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(e){if(e.length===0)return[];const t=this.cache.get(e);if(t!==void 0)return t;const r=Array.from(e);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let n=[];if(r.length>1){const s=new F0((i,l)=>i.score<l.score);let a={token:r[0],bias:0,prev:null,next:null},o=a;for(let i=1;i<r.length;++i){const l={bias:i/r.length,token:r[i],prev:o,next:null};o.next=l,this.add_node(s,o),o=l}for(;!s.is_empty();){const i=s.pop();if(i.deleted||!i.next||i.next.deleted)continue;if(i.deleted=!0,i.next.deleted=!0,i.prev){const u={...i.prev};i.prev.deleted=!0,i.prev=u,u.prev?u.prev.next=u:a=u}const 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(s,l.prev)):a=l,l.next&&(l.next.prev=l,this.add_node(s,l))}for(let i=a;i!==null;i=i.next)n.push(i.token)}else n=r;if(this.continuing_subword_suffix)for(let s=0;s<n.length-1;++s)n[s]+=this.continuing_subword_suffix;return e.length<this.max_length_to_cache&&this.cache.put(e,n),n}add_node(e,t){const r=this.bpe_ranks.get(JSON.stringify([t.token,t.next.token]));r!==void 0&&(t.score=r+t.bias,e.push(t))}encode(e){const t=[];for(const r of e){if(this.ignore_merges&&this.tokens_to_ids.has(r)){t.push(r);continue}const n=this.bpe(r);for(const s of n)if(this.tokens_to_ids.has(s))t.push(s);else if(this.byte_fallback){const a=Array.from(this.text_encoder.encode(s)).map(o=>`<0x${o.toString(16).toUpperCase().padStart(2,"0")}>`);a.every(o=>this.tokens_to_ids.has(o))?t.push(...a):t.push(this.unk_token)}else t.push(this.unk_token)}return t}},fh=O0,N0=class extends ha{constructor(e,t){super(e);const r=e.vocab;this.tokens_to_ids=bi(t.target_lang?r[t.target_lang]:r),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[n,s]of this.tokens_to_ids)this.vocab[s]=n}encode(e){return e}},D0=N0;function B0(e,t){switch(e.type){case"WordPiece":return new uh(e);case"Unigram":return new hh(e,t.eos_token);case"BPE":return new fh(e);default:if(e.vocab)return Array.isArray(e.vocab)?new hh(e,t.eos_token):Object.hasOwn(e,"continuing_subword_prefix")&&Object.hasOwn(e,"unk_token")?Object.hasOwn(e,"merges")?new fh(e):new uh(e):new D0(e,{target_lang:t.target_lang,bos_token:t.bos_token,eos_token:t.eos_token,pad_token:t.pad_token,unk_token:t.unk_token});throw new Error(`Unknown TokenizerModel type: ${e?.type}`)}}var z0=B0,R0=class extends ns{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},ss=R0,G0=class extends ss{post_process(e,t=null,r=!0){const n=t===null?this.config.single:this.config.pair;let s=[],a=[];for(const o of n)"SpecialToken"in o?r&&(s.push(o.SpecialToken.id),a.push(o.SpecialToken.type_id)):"Sequence"in o&&(o.Sequence.id==="A"?(s=Dt(s,e),a=Dt(a,new Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id==="B"&&(s=Dt(s,t),a=Dt(a,new Array(t.length).fill(o.Sequence.type_id))));return{tokens:s,token_type_ids:a}}},$0=G0,V0=class extends ss{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},U0=V0,W0=class extends ss{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,r=!0){r&&(e=Dt([this.cls[0]],e,[this.sep[0]]));let n=new Array(e.length).fill(0);if(t){const s=[],a=r?[this.sep[0]]:[];e=Dt(e,s,t,a),n=Dt(n,new Array(t.length+s.length+a.length).fill(1))}return{tokens:e,token_type_ids:n}}},j0=W0,q0=class extends ss{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,r=!0){r&&(e=Dt([this.cls[0]],e,[this.sep[0]]));let n=new Array(e.length).fill(0);if(t){const s=r?[this.sep[0]]:[],a=r?[this.sep[0]]:[];e=Dt(e,s,t,a),n=Dt(n,new Array(t.length+s.length+a.length).fill(1))}return{tokens:e,token_type_ids:n}}},H0=q0,Q0=class extends ss{constructor(e){super(e),this.processors=(e.processors??[]).map(t=>ep(t))}post_process(e,t=null,r=!0){let n={tokens:e,tokens_pair:t};for(const s of this.processors)n=s.post_process(n.tokens,n.tokens_pair,r);return n}},X0=Q0;function Y0(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new $0(e);case"ByteLevel":return new U0(e);case"BertProcessing":return new j0(e);case"RobertaProcessing":return new H0(e);case"Sequence":return new X0(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}var ep=Y0,J0=class extends ns{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in e?e.trim_offsets:!1}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join("")}},Rt=J0,K0=class extends Rt{constructor(e){super(e),this.byte_decoder=pb,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){const t=e.join(""),r=new Uint8Array([...t].map(n=>this.byte_decoder[n]));return this.text_decoder.decode(r)}decode_chain(e){const t=[];let r=[];for(const n of e)this.added_tokens.find(s=>s.content===n)!==void 0?(r.length>0&&(t.push(this.convert_tokens_to_string(r)),r=[]),t.push(n)):r.push(n);return r.length>0&&t.push(this.convert_tokens_to_string(r)),t}},Z0=K0,eM=class extends Rt{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((t,r)=>{if(r!==0){const n=this.config.prefix;n&&t.startsWith(n)?t=t.replace(n,""):t=" "+t}return this.cleanup&&(t=yi(t)),t})}},tM=eM,rM=class extends Rt{constructor(e){super(e),this.replacement=e.replacement??"▁"}decode_chain(e){const t=[];for(let r=0;r<e.length;++r){let n=e[r].replaceAll(this.replacement," ");r==0&&n.startsWith(" ")&&(n=n.substring(1)),t.push(n)}return t}},nM=rM,sM=class extends Rt{constructor(e){super(e),this.suffix=e.suffix??""}decode_chain(e){return e.map((t,r)=>t.replaceAll(this.suffix,r===e.length-1?"":" "))}},aM=sM,oM=class extends Rt{constructor(e){super(e),this.pad_token=e.pad_token??"",this.word_delimiter_token=e.word_delimiter_token??"",this.cleanup=e.cleanup}convert_tokens_to_string(e){if(e.length===0)return"";const t=[e[0]];for(let s=1;s<e.length;++s)e[s]!==t.at(-1)&&t.push(e[s]);let n=t.filter(s=>s!==this.pad_token).join("");return this.cleanup&&(n=yi(n).replaceAll(this.word_delimiter_token," ").trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}},iM=oM,lM=class extends Rt{constructor(e){super(e),this.decoders=(e.decoders??[]).map(t=>tp(t))}decode_chain(e){return this.decoders.reduce((t,r)=>r.decode_chain(t),e)}},cM=lM,uM=class extends Rt{decode_chain(e){const t=ua(this.config.pattern),r=this.config.content??"";return t===null?e:e.map(n=>n.replaceAll(t,r))}},dM=uM,hM=class extends Rt{decode_chain(e){return[e.join("")]}},fM=hM,pM=class extends Rt{constructor(e){super(e),this.content=e.content??"",this.start=e.start??0,this.stop=e.stop??0}decode_chain(e){return e.map(t=>{let r=0;for(let s=0;s<this.start&&t[s]===this.content;++s){r=s+1;continue}let n=t.length;for(let s=0;s<this.stop;++s){const a=t.length-s-1;if(t[a]===this.content){n=a;continue}else break}return t.slice(r,n)})}},_M=pM,mM=class extends Rt{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){const t=[];let r=[];for(const n of e){let s=null;if(n.length===6&&n.startsWith("<0x")&&n.endsWith(">")){const a=parseInt(n.slice(3,5),16);isNaN(a)||(s=a)}if(s!==null)r.push(s);else{if(r.length>0){const a=this.text_decoder.decode(Uint8Array.from(r));t.push(a),r=[]}t.push(n)}}if(r.length>0){const n=this.text_decoder.decode(Uint8Array.from(r));t.push(n),r=[]}return t}},gM=mM;function wM(e){if(e===null)return null;switch(e.type){case"ByteLevel":return new Z0(e);case"WordPiece":return new tM(e);case"Metaspace":return new nM(e);case"BPEDecoder":return new aM(e);case"CTC":return new iM(e);case"Sequence":return new cM(e);case"Replace":return new dM(e);case"Fuse":return new fM(e);case"Strip":return new _M(e);case"ByteFallback":return new gM(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}var tp=wM,vM=class{constructor(e,t){const r=ch(e,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);const n=ch(t,"Config");if(n)throw new Error(n);this.tokenizer=e,this.config=t,this.normalizer=Yf(this.tokenizer.normalizer),this.pre_tokenizer=Jf(this.tokenizer.pre_tokenizer),this.model=z0(this.tokenizer.model,this.config),this.post_processor=ep(this.tokenizer.post_processor),this.decoder=tp(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];const s=[],a=[];this.added_tokens_map=new Map;for(const o of this.tokenizer.added_tokens){const i=new hb(o);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){const l=this.normalizer(i.content);a.push(l),this.added_tokens_map.set(l,i)}else s.push(i.content)}(this.config.additional_special_tokens??[]).forEach(o=>{this.special_tokens.includes(o)||this.special_tokens.push(o)}),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 ih(s),this.splitter_normalized=new ih(a),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(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){const{tokens:s,token_type_ids:a}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}),o=s.map(l=>this.added_tokens_map.get(l)?.id??this.model.tokens_to_ids.get(l)??this.model.unk_token_id),i={ids:o,tokens:s,attention_mask:new Array(o.length).fill(1)};return n&&a&&(i.token_type_ids=a),i}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!vb(e[0]))throw Error("token_ids must be a non-empty array of integers.");let r=e.map(s=>this.model.vocab[Number(s)]??this.model.unk_token);t.skip_special_tokens&&(r=r.filter(s=>!this.special_tokens.includes(s)));let n=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(n=n.replaceAll(this.decoder.end_of_word_suffix," "),t.skip_special_tokens&&(n=n.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(n=yi(n)),n}tokenize(e,{text_pair:t=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}).tokens}encode_text(e){if(e===null)return null;const t=this.splitter_unnormalized.split(e);return t.forEach((r,n)=>{const s=this.added_tokens_map.get(r);s&&(s.lstrip&&n>0&&(t[n-1]=t[n-1].trimEnd()),s.rstrip&&n<t.length-1&&(t[n+1]=t[n+1].trimStart()))}),t.flatMap((r,n)=>{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=bb(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];const s=this.splitter_normalized.split(r);return s.forEach((a,o)=>{const i=this.added_tokens_map.get(a);i&&(i.lstrip&&o>0&&(s[o-1]=s[o-1].trimEnd()),i.rstrip&&o<s.length-1&&(s[o+1]=s[o+1].trimStart()))}),s.flatMap(a=>{if(a.length===0)return[];if(this.added_tokens_map.has(a))return[a];const o=this.pre_tokenizer!==null?this.pre_tokenizer(a,{section_index:n}):[a];return this.model(o)})})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:r=!0}){const n=this.encode_text(e),s=this.encode_text(t||null);return this.post_processor?this.post_processor(n,s,r):{tokens:Dt(n??[],s??[])}}token_to_id(e){return this.model.tokens_to_ids.get(e)}id_to_token(e){return this.model.vocab[e]}get_added_tokens_decoder(){const e=new Map;for(const t of this.added_tokens)e.set(t.id,t);return e}get_vocab(e=!0){const t=new Map;for(let r=0;r<this.model.vocab.length;++r){const n=this.model.vocab[r];(e||!this.added_tokens_map.has(n))&&t.set(n,r)}return t}},yM=vM,N=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"}),Mt=class{constructor(e,t){this.value=e,this.type=t}};function ph(e){return/\w/.test(e)}function qn(e){return/[0-9]/.test(e)}function _h(e){return/\s/.test(e)}var bM=[["{%",N.OpenStatement],["%}",N.CloseStatement],["{{",N.OpenExpression],["}}",N.CloseExpression],["(",N.OpenParen],[")",N.CloseParen],["{",N.OpenCurlyBracket],["}",N.CloseCurlyBracket],["[",N.OpenSquareBracket],["]",N.CloseSquareBracket],[",",N.Comma],[".",N.Dot],[":",N.Colon],["|",N.Pipe],["<=",N.ComparisonBinaryOperator],[">=",N.ComparisonBinaryOperator],["==",N.ComparisonBinaryOperator],["!=",N.ComparisonBinaryOperator],["<",N.ComparisonBinaryOperator],[">",N.ComparisonBinaryOperator],["+",N.AdditiveBinaryOperator],["-",N.AdditiveBinaryOperator],["~",N.AdditiveBinaryOperator],["*",N.MultiplicativeBinaryOperator],["/",N.MultiplicativeBinaryOperator],["%",N.MultiplicativeBinaryOperator],["=",N.Equals]],MM=new Map([["n",`
10
+ `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function xM(e,t={}){return e.endsWith(`
11
+ `)&&(e=e.slice(0,-1)),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%-])/gm,"$1")),t.trim_blocks&&(e=e.replace(/([#%-]})\n/g,"$1")),e.replace(/{%\s*(end)?generation\s*%}/gs,"")}function kM(e,t={}){const r=[],n=xM(e,t);let s=0,a=0;const o=u=>{let h="";for(;u(n[s]);){if(n[s]==="\\"){if(++s,s>=n.length)throw new SyntaxError("Unexpected end of input");const f=n[s++],p=MM.get(f);if(p===void 0)throw new SyntaxError(`Unexpected escaped character: ${f}`);h+=p;continue}if(h+=n[s++],s>=n.length)throw new SyntaxError("Unexpected end of input")}return h},i=()=>{const u=r.at(-1);u&&u.type===N.Text&&(u.value=u.value.trimEnd(),u.value===""&&r.pop())},l=()=>{for(;s<n.length&&_h(n[s]);)++s};e:for(;s<n.length;){const u=r.at(-1)?.type;if(u===void 0||u===N.CloseStatement||u===N.CloseExpression||u===N.Comment){let f="";for(;s<n.length&&!(n[s]==="{"&&(n[s+1]==="%"||n[s+1]==="{"||n[s+1]==="#"));)f+=n[s++];if(f.length>0){r.push(new Mt(f,N.Text));continue}}if(n[s]==="{"&&n[s+1]==="#"){s+=2;const f=n[s]==="-";f&&++s;let p="";for(;n[s]!=="#"||n[s+1]!=="}";){if(s+2>=n.length)throw new SyntaxError("Missing end of comment tag");p+=n[s++]}const g=p.endsWith("-");g&&(p=p.slice(0,-1)),f&&i(),r.push(new Mt(p,N.Comment)),s+=2,g&&l();continue}if(n.slice(s,s+3)==="{%-"){i(),r.push(new Mt("{%",N.OpenStatement)),s+=3;continue}if(n.slice(s,s+3)==="{{-"){i(),r.push(new Mt("{{",N.OpenExpression)),a=0,s+=3;continue}if(o(_h),n.slice(s,s+3)==="-%}"){r.push(new Mt("%}",N.CloseStatement)),s+=3,l();continue}if(n.slice(s,s+3)==="-}}"){r.push(new Mt("}}",N.CloseExpression)),s+=3,l();continue}const h=n[s];if(h==="-"||h==="+"){const f=r.at(-1)?.type;if(f===N.Text||f===void 0)throw new SyntaxError(`Unexpected character: ${h}`);switch(f){case N.Identifier:case N.NumericLiteral:case N.StringLiteral:case N.CloseParen:case N.CloseSquareBracket:break;default:{++s;const p=o(qn);r.push(new Mt(`${h}${p}`,p.length>0?N.NumericLiteral:N.UnaryOperator));continue}}}for(const[f,p]of bM){if(f==="}}"&&a>0)continue;if(n.slice(s,s+f.length)===f){r.push(new Mt(f,p)),p===N.OpenExpression?a=0:p===N.OpenCurlyBracket?++a:p===N.CloseCurlyBracket&&--a,s+=f.length;continue e}}if(h==="'"||h==='"'){++s;const f=o(p=>p!==h);r.push(new Mt(f,N.StringLiteral)),++s;continue}if(qn(h)){let f=o(qn);if(n[s]==="."&&qn(n[s+1])){++s;const p=o(qn);f=`${f}.${p}`}r.push(new Mt(f,N.NumericLiteral));continue}if(ph(h)){const f=o(ph);r.push(new Mt(f,N.Identifier));continue}throw new SyntaxError(`Unexpected character: ${h}`)}return r}var Gt=class{type="Statement"},TM=class extends Gt{constructor(e){super(),this.body=e}type="Program"},EM=class extends Gt{constructor(e,t,r){super(),this.test=e,this.body=t,this.alternate=r}type="If"},CM=class extends Gt{constructor(e,t,r,n){super(),this.loopvar=e,this.iterable=t,this.body=r,this.defaultBlock=n}type="For"},SM=class extends Gt{type="Break"},PM=class extends Gt{type="Continue"},AM=class extends Gt{constructor(e,t,r){super(),this.assignee=e,this.value=t,this.body=r}type="Set"},FM=class extends Gt{constructor(e,t,r){super(),this.name=e,this.args=t,this.body=r}type="Macro"},IM=class extends Gt{constructor(e){super(),this.value=e}type="Comment"},vt=class extends Gt{type="Expression"},LM=class extends vt{constructor(e,t,r){super(),this.object=e,this.property=t,this.computed=r}type="MemberExpression"},mh=class extends vt{constructor(e,t){super(),this.callee=e,this.args=t}type="CallExpression"},Kr=class extends vt{constructor(e){super(),this.value=e}type="Identifier"},mn=class extends vt{constructor(e){super(),this.value=e}type="Literal"},OM=class extends mn{type="IntegerLiteral"},NM=class extends mn{type="FloatLiteral"},gh=class extends mn{type="StringLiteral"},DM=class extends mn{type="ArrayLiteral"},wh=class extends mn{type="TupleLiteral"},BM=class extends mn{type="ObjectLiteral"},Hn=class extends vt{constructor(e,t,r){super(),this.operator=e,this.left=t,this.right=r}type="BinaryExpression"},zM=class extends vt{constructor(e,t){super(),this.operand=e,this.filter=t}type="FilterExpression"},RM=class extends Gt{constructor(e,t){super(),this.filter=e,this.body=t}type="FilterStatement"},GM=class extends vt{constructor(e,t){super(),this.lhs=e,this.test=t}type="SelectExpression"},$M=class extends vt{constructor(e,t,r){super(),this.operand=e,this.negate=t,this.test=r}type="TestExpression"},VM=class extends vt{constructor(e,t){super(),this.operator=e,this.argument=t}type="UnaryExpression"},UM=class extends vt{constructor(e=void 0,t=void 0,r=void 0){super(),this.start=e,this.stop=t,this.step=r}type="SliceExpression"},WM=class extends vt{constructor(e,t){super(),this.key=e,this.value=t}type="KeywordArgumentExpression"},jM=class extends vt{constructor(e){super(),this.argument=e}type="SpreadExpression"},qM=class extends Gt{constructor(e,t,r){super(),this.call=e,this.callerArgs=t,this.body=r}type="CallStatement"},HM=class extends vt{constructor(e,t,r){super(),this.condition=e,this.trueExpr=t,this.falseExpr=r}type="Ternary"};function QM(e){const t=new TM([]);let r=0;function n(A,L){const D=e[r++];if(!D||D.type!==A)throw new Error(`Parser Error: ${L}. ${D.type} !== ${A}.`);return D}function s(A){if(!l(A))throw new SyntaxError(`Expected ${A}`);++r}function a(){switch(e[r].type){case N.Comment:return new IM(e[r++].value);case N.Text:return u();case N.OpenStatement:return h();case N.OpenExpression:return f();default:throw new SyntaxError(`Unexpected token type: ${e[r].type}`)}}function o(...A){return r+A.length<=e.length&&A.every((L,D)=>L===e[r+D].type)}function i(...A){return e[r]?.type===N.OpenStatement&&e[r+1]?.type===N.Identifier&&A.includes(e[r+1]?.value)}function l(...A){return r+A.length<=e.length&&A.every((L,D)=>e[r+D].type==="Identifier"&&L===e[r+D].value)}function u(){return new gh(n(N.Text,"Expected text token").value)}function h(){if(n(N.OpenStatement,"Expected opening statement token"),e[r].type!==N.Identifier)throw new SyntaxError(`Unknown statement, got ${e[r].type}`);const A=e[r].value;let L;switch(A){case"set":++r,L=p();break;case"if":++r,L=g(),n(N.OpenStatement,"Expected {% token"),s("endif"),n(N.CloseStatement,"Expected %} token");break;case"macro":++r,L=v(),n(N.OpenStatement,"Expected {% token"),s("endmacro"),n(N.CloseStatement,"Expected %} token");break;case"for":++r,L=M(),n(N.OpenStatement,"Expected {% token"),s("endfor"),n(N.CloseStatement,"Expected %} token");break;case"call":{++r;let D=null;o(N.OpenParen)&&(D=H());const J=X();if(J.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");const ie=H();n(N.CloseStatement,"Expected closing statement token");const xe=[];for(;!i("endcall");)xe.push(a());n(N.OpenStatement,"Expected '{%'"),s("endcall"),n(N.CloseStatement,"Expected closing statement token");const Fe=new mh(J,ie);L=new qM(Fe,D,xe);break}case"break":++r,n(N.CloseStatement,"Expected closing statement token"),L=new SM;break;case"continue":++r,n(N.CloseStatement,"Expected closing statement token"),L=new PM;break;case"filter":{++r;let D=X();D instanceof Kr&&o(N.OpenParen)&&(D=G(D)),n(N.CloseStatement,"Expected closing statement token");const J=[];for(;!i("endfilter");)J.push(a());n(N.OpenStatement,"Expected '{%'"),s("endfilter"),n(N.CloseStatement,"Expected '%}'"),L=new RM(D,J);break}default:throw new SyntaxError(`Unknown statement type: ${A}`)}return L}function f(){n(N.OpenExpression,"Expected opening expression token");const A=k();return n(N.CloseExpression,"Expected closing expression token"),A}function p(){const A=w();let L=null;const D=[];if(o(N.Equals))++r,L=w();else{for(n(N.CloseStatement,"Expected %} token");!i("endset");)D.push(a());n(N.OpenStatement,"Expected {% token"),s("endset")}return n(N.CloseStatement,"Expected closing statement token"),new AM(A,L,D)}function g(){const A=k();n(N.CloseStatement,"Expected closing statement token");const L=[],D=[];for(;!i("elif","else","endif");)L.push(a());if(i("elif")){++r,++r;const J=g();D.push(J)}else if(i("else"))for(++r,++r,n(N.CloseStatement,"Expected closing statement token");!i("endif");)D.push(a());return new EM(A,L,D)}function v(){const A=X();if(A.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const L=H();n(N.CloseStatement,"Expected closing statement token");const D=[];for(;!i("endmacro");)D.push(a());return new FM(A,L,D)}function w(A=!1){const L=A?X:k,D=[L()],J=o(N.Comma);for(;J&&(++r,D.push(L()),!!o(N.Comma)););return J?new wh(D):D[0]}function M(){const A=w(!0);if(!(A instanceof Kr||A instanceof wh))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${A.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;const L=k();n(N.CloseStatement,"Expected closing statement token");const D=[];for(;!i("endfor","else");)D.push(a());const J=[];if(i("else"))for(++r,++r,n(N.CloseStatement,"Expected closing statement token");!i("endfor");)J.push(a());return new CM(A,L,D,J)}function k(){return T()}function T(){const A=S();if(l("if")){++r;const L=S();if(l("else")){++r;const D=T();return new HM(L,A,D)}else return new GM(A,L)}return A}function S(){let A=E();for(;l("or");){const L=e[r];++r;const D=E();A=new Hn(L,A,D)}return A}function E(){let A=F();for(;l("and");){const L=e[r];++r;const D=F();A=new Hn(L,A,D)}return A}function F(){let A;for(;l("not");){const L=e[r];++r;const D=F();A=new VM(L,D)}return A??z()}function z(){let A=b();for(;;){let L;if(l("not","in"))L=new Mt("not in",N.Identifier),r+=2;else if(l("in"))L=e[r++];else if(o(N.ComparisonBinaryOperator))L=e[r++];else break;const D=b();A=new Hn(L,A,D)}return A}function b(){let A=O();for(;o(N.AdditiveBinaryOperator);){const L=e[r];++r;const D=O();A=new Hn(L,A,D)}return A}function U(){const A=B(X());return o(N.OpenParen)?G(A):A}function G(A){let L=new mh(A,H());return L=B(L),o(N.OpenParen)&&(L=G(L)),L}function H(){n(N.OpenParen,"Expected opening parenthesis for arguments list");const A=Z();return n(N.CloseParen,"Expected closing parenthesis for arguments list"),A}function Z(){const A=[];for(;!o(N.CloseParen);){let L;if(e[r].type===N.MultiplicativeBinaryOperator&&e[r].value==="*"){++r;const D=k();L=new jM(D)}else if(L=k(),o(N.Equals)){if(++r,!(L instanceof Kr))throw new SyntaxError("Expected identifier for keyword argument");const D=k();L=new WM(L,D)}A.push(L),o(N.Comma)&&++r}return A}function W(){const A=[];let L=!1;for(;!o(N.CloseSquareBracket);)o(N.Colon)?(A.push(void 0),++r,L=!0):(A.push(k()),o(N.Colon)&&(++r,L=!0));if(A.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(L){if(A.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new UM(...A)}return A[0]}function B(A){for(;o(N.Dot)||o(N.OpenSquareBracket);){const L=e[r];++r;let D;const J=L.type===N.OpenSquareBracket;if(J)D=W(),n(N.CloseSquareBracket,"Expected closing square bracket");else if(D=X(),D.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");A=new LM(A,D,J)}return A}function O(){let A=$();for(;o(N.MultiplicativeBinaryOperator);){const L=e[r++],D=$();A=new Hn(L,A,D)}return A}function $(){let A=ee();for(;l("is");){++r;const L=l("not");L&&++r;const D=X();if(!(D instanceof Kr))throw new SyntaxError("Expected identifier for the test");A=new $M(A,L,D)}return A}function ee(){let A=U();for(;o(N.Pipe);){++r;let L=X();if(!(L instanceof Kr))throw new SyntaxError("Expected identifier for the filter");o(N.OpenParen)&&(L=G(L)),A=new zM(A,L)}return A}function X(){const A=e[r++];switch(A.type){case N.NumericLiteral:{const L=A.value;return L.includes(".")?new NM(Number(L)):new OM(Number(L))}case N.StringLiteral:{let L=A.value;for(;o(N.StringLiteral);)L+=e[r++].value;return new gh(L)}case N.Identifier:return new Kr(A.value);case N.OpenParen:{const L=w();return n(N.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),L}case N.OpenSquareBracket:{const L=[];for(;!o(N.CloseSquareBracket);)L.push(k()),o(N.Comma)&&++r;return++r,new DM(L)}case N.OpenCurlyBracket:{const L=new Map;for(;!o(N.CloseCurlyBracket);){const D=k();n(N.Colon,"Expected colon between key and value in object literal");const J=k();L.set(D,J),o(N.Comma)&&++r}return++r,new BM(L)}default:throw new SyntaxError(`Unexpected token: ${A.type}`)}}for(;r<e.length;)t.body.push(a());return t}function XM(e,t,r=1){if(t===void 0&&(t=e,e=0),r===0)throw new Error("range() step must not be zero");const n=[];if(r>0)for(let s=e;s<t;s+=r)n.push(s);else for(let s=e;s>t;s+=r)n.push(s);return n}function vh(e,t,r,n=1){const s=Math.sign(n);s>=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),r=(r??=e.length)<0?Math.max(e.length+r,0):Math.min(r,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),r=(r??=-1)<-1?Math.max(e.length+r,-1):Math.min(r,e.length-1));const a=[];for(let o=t;s*o<s*r;o+=n)a.push(e[o]);return a}function YM(e){return e.replace(/\b\w/g,t=>t.toUpperCase())}function JM(e){return KM(new Date,e)}function KM(e,t){const r=new Intl.DateTimeFormat(void 0,{month:"long"}),n=new Intl.DateTimeFormat(void 0,{month:"short"}),s=a=>a<10?"0"+a:a.toString();return t.replace(/%[YmdbBHM%]/g,a=>{switch(a){case"%Y":return e.getFullYear().toString();case"%m":return s(e.getMonth()+1);case"%d":return s(e.getDate());case"%b":return n.format(e);case"%B":return r.format(e);case"%H":return s(e.getHours());case"%M":return s(e.getMinutes());case"%%":return"%";default:return a}})}function ZM(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ex(e,t,r,n){if(n===0)return e;let s=n==null||n<0?1/0:n;const a=t.length===0?new RegExp("(?=)","gu"):new RegExp(ZM(t),"gu");return e.replaceAll(a,o=>s>0?(--s,r):o)}var yh=class extends Error{},bh=class extends Error{},Xt=class{type="RuntimeValue";value;builtins=new Map;constructor(e=void 0){this.value=e}__bool__(){return new ne(!!this.value)}toString(){return String(this.value)}},oe=class extends Xt{type="IntegerValue"},Ge=class extends Xt{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},Y=class extends Xt{type="StringValue";builtins=new Map([["upper",new Le(()=>new Y(this.value.toUpperCase()))],["lower",new Le(()=>new Y(this.value.toLowerCase()))],["strip",new Le(()=>new Y(this.value.trim()))],["title",new Le(()=>new Y(YM(this.value)))],["capitalize",new Le(()=>new Y(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new oe(this.value.length)],["rstrip",new Le(()=>new Y(this.value.trimEnd()))],["lstrip",new Le(()=>new Y(this.value.trimStart()))],["startswith",new Le(e=>{if(e.length===0)throw new Error("startswith() requires at least one argument");const t=e[0];if(t instanceof Y)return new ne(this.value.startsWith(t.value));if(t instanceof me){for(const r of t.value){if(!(r instanceof Y))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(r.value))return new ne(!0)}return new ne(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Le(e=>{if(e.length===0)throw new Error("endswith() requires at least one argument");const t=e[0];if(t instanceof Y)return new ne(this.value.endsWith(t.value));if(t instanceof me){for(const r of t.value){if(!(r instanceof Y))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(r.value))return new ne(!0)}return new ne(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Le(e=>{const t=e[0]??new De;if(!(t instanceof Y||t instanceof De))throw new Error("sep argument must be a string or null");const r=e[1]??new oe(-1);if(!(r instanceof oe))throw new Error("maxsplit argument must be a number");let n=[];if(t instanceof De){const s=this.value.trimStart();for(const{0:a,index:o}of s.matchAll(/\S+/g)){if(r.value!==-1&&n.length>=r.value&&o!==void 0){n.push(a+s.slice(o+a.length));break}n.push(a)}}else{if(t.value==="")throw new Error("empty separator");n=this.value.split(t.value),r.value!==-1&&n.length>r.value&&n.push(n.splice(r.value).join(t.value))}return new me(n.map(s=>new Y(s)))})],["replace",new Le(e=>{if(e.length<2)throw new Error("replace() requires at least two arguments");const t=e[0],r=e[1];if(!(t instanceof Y&&r instanceof Y))throw new Error("replace() arguments must be strings");let n;if(e.length>2?e[2].type==="KeywordArgumentsValue"?n=e[2].value.get("count")??new De:n=e[2]:n=new De,!(n instanceof oe||n instanceof De))throw new Error("replace() count argument must be a number or null");return new Y(ex(this.value,t.value,r.value,n.value))})]])},ne=class extends Xt{type="BooleanValue"},tx=/[\x7f-\uffff]/g;function Mh(e){return e.replace(tx,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))}function Nr(e,t={},r=0,n=!0){const{indent:s=null,ensureAscii:a=!1,separators:o=null,sortKeys:i=!1}=t;let l,u;switch(o?[l,u]=o:s?(l=",",u=": "):(l=", ",u=": "),e.type){case"NullValue":return"null";case"UndefinedValue":return n?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(e.value);case"StringValue":{let h=JSON.stringify(e.value);return a&&(h=Mh(h)),h}case"ArrayValue":case"ObjectValue":{const h=s?" ".repeat(s):"",f=`
12
+ `+h.repeat(r),p=f+h;if(e.type==="ArrayValue"){const g=e.value.map(v=>Nr(v,t,r+1,n));return s?`[${p}${g.join(`${l}${p}`)}${f}]`:`[${g.join(l)}]`}else{let g=Array.from(e.value.entries());i&&(g=g.sort(([w],[M])=>w.localeCompare(M)));const v=g.map(([w,M])=>{let k=JSON.stringify(w);a&&(k=Mh(k));const T=`${k}${u}${Nr(M,t,r+1,n)}`;return s?`${p}${T}`:T});return s?`{${v.join(l)}${f}}`:`{${v.join(l)}}`}}default:throw new Error(`Cannot convert to JSON: ${e.type}`)}}var rt=class extends Xt{type="ObjectValue";__bool__(){return new ne(this.value.size>0)}builtins=new Map([["get",new Le(([e,t])=>{if(!(e instanceof Y))throw new Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new De})],["items",new Le(()=>this.items())],["keys",new Le(()=>this.keys())],["values",new Le(()=>this.values())],["dictsort",new Le(e=>{let t=new Map;const r=e.filter(i=>i instanceof Xn?(t=i.value,!1):!0),n=r.at(0)??t.get("case_sensitive")??new ne(!1);if(!(n instanceof ne))throw new Error("case_sensitive must be a boolean");const s=r.at(1)??t.get("by")??new Y("key");if(!(s instanceof Y))throw new Error("by must be a string");if(!["key","value"].includes(s.value))throw new Error("by must be either 'key' or 'value'");const a=r.at(2)??t.get("reverse")??new ne(!1);if(!(a instanceof ne))throw new Error("reverse must be a boolean");const o=Array.from(this.value.entries()).map(([i,l])=>new me([new Y(i),l])).sort((i,l)=>{const u=s.value==="key"?0:1,h=i.value[u],f=l.value[u],p=qo(h,f,n.value);return a.value?-p:p});return new me(o)})]]);items(){return new me(Array.from(this.value.entries()).map(([e,t])=>new me([new Y(e),t])))}keys(){return new me(Array.from(this.value.keys()).map(e=>new Y(e)))}values(){return new me(Array.from(this.value.values()))}toString(){return Nr(this,{},0,!1)}},Xn=class extends rt{type="KeywordArgumentsValue"},me=class extends Xt{type="ArrayValue";builtins=new Map([["length",new oe(this.value.length)]]);__bool__(){return new ne(this.value.length>0)}toString(){return Nr(this,{},0,!1)}},xh=class extends me{type="TupleValue"},Le=class extends Xt{type="FunctionValue"},De=class extends Xt{type="NullValue"},Ie=class extends Xt{type="UndefinedValue"},Ar=class{constructor(e){this.parent=e}variables=new Map([["namespace",new Le(e=>{if(e.length===0)return new rt(new Map);if(e.length!==1||!(e[0]instanceof rt))throw new Error("`namespace` expects either zero arguments or a single object argument");return e[0]})]]);tests=new Map([["boolean",e=>e.type==="BooleanValue"],["callable",e=>e instanceof Le],["odd",e=>{if(!(e instanceof oe))throw new Error(`cannot odd on ${e.type}`);return e.value%2!==0}],["even",e=>{if(!(e instanceof oe))throw new Error(`cannot even on ${e.type}`);return e.value%2===0}],["false",e=>e.type==="BooleanValue"&&!e.value],["true",e=>e.type==="BooleanValue"&&e.value],["none",e=>e.type==="NullValue"],["string",e=>e.type==="StringValue"],["number",e=>e instanceof oe||e instanceof Ge],["integer",e=>e instanceof oe],["iterable",e=>e.type==="ArrayValue"||e.type==="StringValue"],["mapping",e=>e.type==="ObjectValue"],["lower",e=>{const t=e.value;return e.type==="StringValue"&&t===t.toLowerCase()}],["upper",e=>{const t=e.value;return e.type==="StringValue"&&t===t.toUpperCase()}],["none",e=>e.type==="NullValue"],["defined",e=>e.type!=="UndefinedValue"],["undefined",e=>e.type==="UndefinedValue"],["equalto",(e,t)=>e.value===t.value],["eq",(e,t)=>e.value===t.value]]);set(e,t){return this.declareVariable(e,Gs(t))}declareVariable(e,t){if(this.variables.has(e))throw new SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw new Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new Ie}catch{return new Ie}}};function rx(e){e.set("false",!1),e.set("true",!0),e.set("none",null),e.set("raise_exception",t=>{throw new Error(t)}),e.set("range",XM),e.set("strftime_now",JM),e.set("True",!0),e.set("False",!1),e.set("None",null)}function kh(e,t){const r=t.split(".");let n=e;for(const s of r)if(n instanceof rt)n=n.value.get(s)??new Ie;else if(n instanceof me){const a=parseInt(s,10);if(!isNaN(a)&&a>=0&&a<n.value.length)n=n.value[a];else return new Ie}else return new Ie;return n}function qo(e,t,r=!1){if(e instanceof De&&t instanceof De)return 0;if(e instanceof De||t instanceof De)throw new Error(`Cannot compare ${e.type} with ${t.type}`);if(e instanceof Ie&&t instanceof Ie)return 0;if(e instanceof Ie||t instanceof Ie)throw new Error(`Cannot compare ${e.type} with ${t.type}`);const n=a=>a instanceof oe||a instanceof Ge||a instanceof ne,s=a=>a instanceof ne?a.value?1:0:a.value;if(n(e)&&n(t)){const a=s(e),o=s(t);return a<o?-1:a>o?1:0}if(e.type!==t.type)throw new Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case"StringValue":{let a=e.value,o=t.value;return r||(a=a.toLowerCase(),o=o.toLowerCase()),a<o?-1:a>o?1:0}default:throw new Error(`Cannot compare type: ${e.type}`)}}var nx=class{global;constructor(e){this.global=e??new Ar}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){const r=this.evaluate(e.left,t);switch(e.operator.value){case"and":return r.__bool__().value?this.evaluate(e.right,t):r;case"or":return r.__bool__().value?r:this.evaluate(e.right,t)}const n=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new ne(r.value==n.value);case"!=":return new ne(r.value!=n.value)}if(r instanceof Ie||n instanceof Ie){if(n instanceof Ie&&["in","not in"].includes(e.operator.value))return new ne(e.operator.value==="not in");throw new Error(`Cannot perform operation ${e.operator.value} on undefined values`)}else{if(r instanceof De||n instanceof De)throw new Error("Cannot perform operation on null values");if(e.operator.value==="~")return new Y(r.value.toString()+n.value.toString());if((r instanceof oe||r instanceof Ge)&&(n instanceof oe||n instanceof Ge)){const s=r.value,a=n.value;switch(e.operator.value){case"+":case"-":case"*":{const o=e.operator.value==="+"?s+a:e.operator.value==="-"?s-a:s*a;return r instanceof Ge||n instanceof Ge?new Ge(o):new oe(o)}case"/":return new Ge(s/a);case"%":{const o=s%a;return r instanceof Ge||n instanceof Ge?new Ge(o):new oe(o)}case"<":return new ne(s<a);case">":return new ne(s>a);case">=":return new ne(s>=a);case"<=":return new ne(s<=a)}}else if(r instanceof me&&n instanceof me)switch(e.operator.value){case"+":return new me(r.value.concat(n.value))}else if(n instanceof me){const s=n.value.find(a=>a.value===r.value)!==void 0;switch(e.operator.value){case"in":return new ne(s);case"not in":return new ne(!s)}}}if(r instanceof Y||n instanceof Y)switch(e.operator.value){case"+":return new Y(r.value.toString()+n.value.toString())}if(r instanceof Y&&n instanceof Y)switch(e.operator.value){case"in":return new ne(n.value.includes(r.value));case"not in":return new ne(!n.value.includes(r.value))}if(r instanceof Y&&n instanceof rt)switch(e.operator.value){case"in":return new ne(n.value.has(r.value));case"not in":return new ne(!n.value.has(r.value))}throw new SyntaxError(`Unknown operator "${e.operator.value}" between ${r.type} and ${n.type}`)}evaluateArguments(e,t){const r=[],n=new Map;for(const s of e)if(s.type==="SpreadExpression"){const a=s,o=this.evaluate(a.argument,t);if(!(o instanceof me))throw new Error(`Cannot unpack non-iterable type: ${o.type}`);for(const i of o.value)r.push(i)}else if(s.type==="KeywordArgumentExpression"){const a=s;n.set(a.key.value,this.evaluate(a.value,t))}else{if(n.size>0)throw new Error("Positional arguments must come before keyword arguments");r.push(this.evaluate(s,t))}return[r,n]}applyFilter(e,t,r){if(t.type==="Identifier"){const n=t;if(n.value==="tojson")return new Y(Nr(e,{}));if(e instanceof me)switch(n.value){case"list":return e;case"first":return e.value[0];case"last":return e.value[e.value.length-1];case"length":return new oe(e.value.length);case"reverse":return new me(e.value.slice().reverse());case"sort":return new me(e.value.slice().sort((s,a)=>qo(s,a,!1)));case"join":return new Y(e.value.map(s=>s.value).join(""));case"string":return new Y(Nr(e,{},0,!1));case"unique":{const s=new Set,a=[];for(const o of e.value)s.has(o.value)||(s.add(o.value),a.push(o));return new me(a)}default:throw new Error(`Unknown ArrayValue filter: ${n.value}`)}else if(e instanceof Y)switch(n.value){case"length":case"upper":case"lower":case"title":case"capitalize":{const s=e.builtins.get(n.value);if(s instanceof Le)return s.value([],r);if(s instanceof oe)return s;throw new Error(`Unknown StringValue filter: ${n.value}`)}case"trim":return new Y(e.value.trim());case"indent":return new Y(e.value.split(`
13
+ `).map((s,a)=>a===0||s.length===0?s:" "+s).join(`
14
+ `));case"join":case"string":return e;case"int":{const s=parseInt(e.value,10);return new oe(isNaN(s)?0:s)}case"float":{const s=parseFloat(e.value);return new Ge(isNaN(s)?0:s)}default:throw new Error(`Unknown StringValue filter: ${n.value}`)}else if(e instanceof oe||e instanceof Ge)switch(n.value){case"abs":return e instanceof oe?new oe(Math.abs(e.value)):new Ge(Math.abs(e.value));case"int":return new oe(Math.floor(e.value));case"float":return new Ge(e.value);default:throw new Error(`Unknown NumericValue filter: ${n.value}`)}else if(e instanceof rt)switch(n.value){case"items":return new me(Array.from(e.value.entries()).map(([s,a])=>new me([new Y(s),a])));case"length":return new oe(e.value.size);default:{const s=e.builtins.get(n.value);if(s)return s instanceof Le?s.value([],r):s;throw new Error(`Unknown ObjectValue filter: ${n.value}`)}}else if(e instanceof ne)switch(n.value){case"bool":return new ne(e.value);case"int":return new oe(e.value?1:0);case"float":return new Ge(e.value?1:0);case"string":return new Y(e.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${n.value}`)}throw new Error(`Cannot apply filter "${n.value}" to type: ${e.type}`)}else if(t.type==="CallExpression"){const n=t;if(n.callee.type!=="Identifier")throw new Error(`Unknown filter: ${n.callee.type}`);const s=n.callee.value;if(s==="tojson"){const[,a]=this.evaluateArguments(n.args,r),o=a.get("indent")??new De;if(!(o instanceof oe||o instanceof De))throw new Error("If set, indent must be a number");const i=a.get("ensure_ascii")??new ne(!1);if(!(i instanceof ne))throw new Error("If set, ensure_ascii must be a boolean");const l=a.get("sort_keys")??new ne(!1);if(!(l instanceof ne))throw new Error("If set, sort_keys must be a boolean");const u=a.get("separators")??new De;let h=null;if(u instanceof me||u instanceof xh){if(u.value.length!==2)throw new Error("separators must be a tuple of two strings");const[f,p]=u.value;if(!(f instanceof Y)||!(p instanceof Y))throw new Error("separators must be a tuple of two strings");h=[f.value,p.value]}else if(!(u instanceof De))throw new Error("If set, separators must be a tuple of two strings");return new Y(Nr(e,{indent:o.value,ensureAscii:i.value,sortKeys:l.value,separators:h}))}else if(s==="join"){let a;if(e instanceof Y)a=Array.from(e.value);else if(e instanceof me)a=e.value.map(u=>u.value);else throw new Error(`Cannot apply filter "${s}" to type: ${e.type}`);const[o,i]=this.evaluateArguments(n.args,r),l=o.at(0)??i.get("separator")??new Y("");if(!(l instanceof Y))throw new Error("separator must be a string");return new Y(a.join(l.value))}else if(s==="int"||s==="float"){const[a,o]=this.evaluateArguments(n.args,r),i=a.at(0)??o.get("default")??(s==="int"?new oe(0):new Ge(0));if(e instanceof Y){const l=s==="int"?parseInt(e.value,10):parseFloat(e.value);return isNaN(l)?i:s==="int"?new oe(l):new Ge(l)}else{if(e instanceof oe||e instanceof Ge)return e;if(e instanceof ne)return s==="int"?new oe(e.value?1:0):new Ge(e.value?1:0);throw new Error(`Cannot apply filter "${s}" to type: ${e.type}`)}}else if(s==="default"){const[a,o]=this.evaluateArguments(n.args,r),i=a[0]??new Y(""),l=a[1]??o.get("boolean")??new ne(!1);if(!(l instanceof ne))throw new Error("`default` filter flag must be a boolean");return e instanceof Ie||l.value&&!e.__bool__().value?i:e}if(e instanceof me){switch(s){case"sort":{const[a,o]=this.evaluateArguments(n.args,r),i=a.at(0)??o.get("reverse")??new ne(!1);if(!(i instanceof ne))throw new Error("reverse must be a boolean");const l=a.at(1)??o.get("case_sensitive")??new ne(!1);if(!(l instanceof ne))throw new Error("case_sensitive must be a boolean");const u=a.at(2)??o.get("attribute")??new De;if(!(u instanceof Y||u instanceof oe||u instanceof De))throw new Error("attribute must be a string, integer, or null");const h=f=>{if(u instanceof De)return f;const p=u instanceof oe?String(u.value):u.value;return kh(f,p)};return new me(e.value.slice().sort((f,p)=>{const g=h(f),v=h(p),w=qo(g,v,l.value);return i.value?-w:w}))}case"selectattr":case"rejectattr":{const a=s==="selectattr";if(e.value.some(f=>!(f instanceof rt)))throw new Error(`\`${s}\` can only be applied to array of objects`);if(n.args.some(f=>f.type!=="StringLiteral"))throw new Error(`arguments of \`${s}\` must be strings`);const[o,i,l]=n.args.map(f=>this.evaluate(f,r));let u;if(i){const f=r.tests.get(i.value);if(!f)throw new Error(`Unknown test: ${i.value}`);u=f}else u=(...f)=>f[0].__bool__().value;const h=e.value.filter(f=>{const p=f.value.get(o.value),g=p?u(p,l):!1;return a?g:!g});return new me(h)}case"map":{const[,a]=this.evaluateArguments(n.args,r);if(a.has("attribute")){const o=a.get("attribute");if(!(o instanceof Y))throw new Error("attribute must be a string");const i=a.get("default"),l=e.value.map(u=>{if(!(u instanceof rt))throw new Error("items in map must be an object");const h=kh(u,o.value);return h instanceof Ie?i??new Ie:h});return new me(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${s}`)}else if(e instanceof Y){switch(s){case"indent":{const[a,o]=this.evaluateArguments(n.args,r),i=a.at(0)??o.get("width")??new oe(4);if(!(i instanceof oe))throw new Error("width must be a number");const l=a.at(1)??o.get("first")??new ne(!1),u=a.at(2)??o.get("blank")??new ne(!1),h=e.value.split(`
15
+ `),f=" ".repeat(i.value),p=h.map((g,v)=>!l.value&&v===0||!u.value&&g.length===0?g:f+g);return new Y(p.join(`
16
+ `))}case"replace":{const a=e.builtins.get("replace");if(!(a instanceof Le))throw new Error("replace filter not available");const[o,i]=this.evaluateArguments(n.args,r);return a.value([...o,new Xn(i)],r)}}throw new Error(`Unknown StringValue filter: ${s}`)}else if(e instanceof rt){const a=e.builtins.get(s);if(a&&a instanceof Le){const[o,i]=this.evaluateArguments(n.args,r);return i.size>0&&o.push(new Xn(i)),a.value(o,r)}throw new Error(`Unknown ObjectValue filter: ${s}`)}else throw new Error(`Cannot apply filter "${s}" to type: ${e.type}`)}throw new Error(`Unknown filter: ${t.type}`)}evaluateFilterExpression(e,t){const r=this.evaluate(e.operand,t);return this.applyFilter(r,e.filter,t)}evaluateTestExpression(e,t){const r=this.evaluate(e.operand,t),n=t.tests.get(e.test.value);if(!n)throw new Error(`Unknown test: ${e.test.value}`);const s=n(r);return new ne(e.negate?!s:s)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new Ie}evaluateUnaryExpression(e,t){const r=this.evaluate(e.argument,t);switch(e.operator.value){case"not":return new ne(!r.value);default:throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}}evaluateTernaryExpression(e,t){return this.evaluate(e.condition,t).__bool__().value?this.evaluate(e.trueExpr,t):this.evaluate(e.falseExpr,t)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let r="";for(const n of e){const s=this.evaluate(n,t);s.type!=="NullValue"&&s.type!=="UndefinedValue"&&(r+=s.toString())}return new Y(r)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){const[r,n]=this.evaluateArguments(e.args,t);n.size>0&&r.push(new Xn(n));const s=this.evaluate(e.callee,t);if(s.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${s.type}`);return s.value(r,t)}evaluateSliceExpression(e,t,r){if(!(e instanceof me||e instanceof Y))throw new Error("Slice object must be an array or string");const n=this.evaluate(t.start,r),s=this.evaluate(t.stop,r),a=this.evaluate(t.step,r);if(!(n instanceof oe||n instanceof Ie))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof oe||s instanceof Ie))throw new Error("Slice stop must be numeric or undefined");if(!(a instanceof oe||a instanceof Ie))throw new Error("Slice step must be numeric or undefined");return e instanceof me?new me(vh(e.value,n.value,s.value,a.value)):new Y(vh(Array.from(e.value),n.value,s.value,a.value).join(""))}evaluateMemberExpression(e,t){const r=this.evaluate(e.object,t);let n;if(e.computed){if(e.property.type==="SliceExpression")return this.evaluateSliceExpression(r,e.property,t);n=this.evaluate(e.property,t)}else n=new Y(e.property.value);let s;if(r instanceof rt){if(!(n instanceof Y))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.value.get(n.value)??r.builtins.get(n.value)}else if(r instanceof me||r instanceof Y)if(n instanceof oe)s=r.value.at(n.value),r instanceof Y&&(s=new Y(r.value.at(n.value)));else if(n instanceof Y)s=r.builtins.get(n.value);else throw new Error(`Cannot access property with non-string/non-number: got ${n.type}`);else{if(!(n instanceof Y))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.builtins.get(n.value)}return s instanceof Xt?s:new Ie}evaluateSet(e,t){const r=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if(e.assignee.type==="Identifier"){const n=e.assignee.value;t.setVariable(n,r)}else if(e.assignee.type==="TupleLiteral"){const n=e.assignee;if(!(r instanceof me))throw new Error(`Cannot unpack non-iterable type in set: ${r.type}`);const s=r.value;if(s.length!==n.value.length)throw new Error(`Too ${n.value.length>s.length?"few":"many"} items to unpack in set`);for(let a=0;a<n.value.length;++a){const o=n.value[a];if(o.type!=="Identifier")throw new Error(`Cannot unpack to non-identifier in set: ${o.type}`);t.setVariable(o.value,s[a])}}else if(e.assignee.type==="MemberExpression"){const n=e.assignee,s=this.evaluate(n.object,t);if(!(s instanceof rt))throw new Error("Cannot assign to member of non-object");if(n.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");s.value.set(n.property.value,r)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);return new De}evaluateIf(e,t){const r=this.evaluate(e.test,t);return this.evaluateBlock(r.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){const r=new Ar(t);let n,s;if(e.iterable.type==="SelectExpression"){const u=e.iterable;s=this.evaluate(u.lhs,r),n=u.test}else s=this.evaluate(e.iterable,r);if(!(s instanceof me||s instanceof rt))throw new Error(`Expected iterable or object type in for loop: got ${s.type}`);s instanceof rt&&(s=s.keys());const a=[],o=[];for(let u=0;u<s.value.length;++u){const h=new Ar(r),f=s.value[u];let p;if(e.loopvar.type==="Identifier")p=g=>g.setVariable(e.loopvar.value,f);else if(e.loopvar.type==="TupleLiteral"){const g=e.loopvar;if(f.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${f.type}`);const v=f;if(g.value.length!==v.value.length)throw new Error(`Too ${g.value.length>v.value.length?"few":"many"} items to unpack`);p=w=>{for(let M=0;M<g.value.length;++M){if(g.value[M].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${g.value[M].type}`);w.setVariable(g.value[M].value,v.value[M])}}}else throw new Error(`Invalid loop variable(s): ${e.loopvar.type}`);n&&(p(h),!this.evaluate(n,h).__bool__().value)||(a.push(f),o.push(p))}let i="",l=!0;for(let u=0;u<a.length;++u){const h=new Map([["index",new oe(u+1)],["index0",new oe(u)],["revindex",new oe(a.length-u)],["revindex0",new oe(a.length-u-1)],["first",new ne(u===0)],["last",new ne(u===a.length-1)],["length",new oe(a.length)],["previtem",u>0?a[u-1]:new Ie],["nextitem",u<a.length-1?a[u+1]:new Ie]]);r.setVariable("loop",new rt(h)),o[u](r);try{const f=this.evaluateBlock(e.body,r);i+=f.value}catch(f){if(f instanceof bh)continue;if(f instanceof yh)break;throw f}l=!1}if(l){const u=this.evaluateBlock(e.defaultBlock,r);i+=u.value}return new Y(i)}evaluateMacro(e,t){return t.setVariable(e.name.value,new Le((r,n)=>{const s=new Ar(n);r=r.slice();let a;r.at(-1)?.type==="KeywordArgumentsValue"&&(a=r.pop());for(let o=0;o<e.args.length;++o){const i=e.args[o],l=r[o];if(i.type==="Identifier"){const u=i;if(!l)throw new Error(`Missing positional argument: ${u.value}`);s.setVariable(u.value,l)}else if(i.type==="KeywordArgumentExpression"){const u=i,h=l??a?.value.get(u.key.value)??this.evaluate(u.value,s);s.setVariable(u.key.value,h)}else throw new Error(`Unknown argument type: ${i.type}`)}return this.evaluateBlock(e.body,s)})),new De}evaluateCallStatement(e,t){const r=new Le((i,l)=>{const u=new Ar(l);if(e.callerArgs)for(let h=0;h<e.callerArgs.length;++h){const f=e.callerArgs[h];if(f.type!=="Identifier")throw new Error(`Caller parameter must be an identifier, got ${f.type}`);u.setVariable(f.value,i[h]??new Ie)}return this.evaluateBlock(e.body,u)}),[n,s]=this.evaluateArguments(e.call.args,t);n.push(new Xn(s));const a=this.evaluate(e.call.callee,t);if(a.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${a.type}`);const o=new Ar(t);return o.setVariable("caller",r),a.value(n,o)}evaluateFilterStatement(e,t){const r=this.evaluateBlock(e.body,t);return this.applyFilter(r,e.filter,t)}evaluate(e,t){if(!e)return new Ie;switch(e.type){case"Program":return this.evalProgram(e,t);case"Set":return this.evaluateSet(e,t);case"If":return this.evaluateIf(e,t);case"For":return this.evaluateFor(e,t);case"Macro":return this.evaluateMacro(e,t);case"CallStatement":return this.evaluateCallStatement(e,t);case"Break":throw new yh;case"Continue":throw new bh;case"IntegerLiteral":return new oe(e.value);case"FloatLiteral":return new Ge(e.value);case"StringLiteral":return new Y(e.value);case"ArrayLiteral":return new me(e.value.map(r=>this.evaluate(r,t)));case"TupleLiteral":return new xh(e.value.map(r=>this.evaluate(r,t)));case"ObjectLiteral":{const r=new Map;for(const[n,s]of e.value){const a=this.evaluate(n,t);if(!(a instanceof Y))throw new Error(`Object keys must be strings: got ${a.type}`);r.set(a.value,this.evaluate(s,t))}return new rt(r)}case"Identifier":return this.evaluateIdentifier(e,t);case"CallExpression":return this.evaluateCallExpression(e,t);case"MemberExpression":return this.evaluateMemberExpression(e,t);case"UnaryExpression":return this.evaluateUnaryExpression(e,t);case"BinaryExpression":return this.evaluateBinaryExpression(e,t);case"FilterExpression":return this.evaluateFilterExpression(e,t);case"FilterStatement":return this.evaluateFilterStatement(e,t);case"TestExpression":return this.evaluateTestExpression(e,t);case"SelectExpression":return this.evaluateSelectExpression(e,t);case"Ternary":return this.evaluateTernaryExpression(e,t);case"Comment":return new De;default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};function Gs(e){switch(typeof e){case"number":return Number.isInteger(e)?new oe(e):new Ge(e);case"string":return new Y(e);case"boolean":return new ne(e);case"undefined":return new Ie;case"object":return e===null?new De:Array.isArray(e)?new me(e.map(Gs)):new rt(new Map(Object.entries(e).map(([t,r])=>[t,Gs(r)])));case"function":return new Le((t,r)=>{const n=e(...t.map(s=>s.value))??null;return Gs(n)});default:throw new Error(`Cannot convert to runtime value: ${e}`)}}var qe=`
17
+ `,sx="{%- ",ax=" -%}";function ox(e){switch(e.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return e.operator.value==="and"?1:e.operator.value==="in"||e.operator.value==="not in"?2:0}return 0}function ix(e,t=" "){const r=typeof t=="number"?" ".repeat(t):t;return Bt(e.body,0,r).replace(/\n$/,"")}function tt(...e){return sx+e.join(" ")+ax}function Bt(e,t,r){return e.map(n=>lx(n,t,r)).join(qe)}function lx(e,t,r){const n=r.repeat(t);switch(e.type){case"Program":return Bt(e.body,t,r);case"If":return cx(e,t,r);case"For":return ux(e,t,r);case"Set":return dx(e,t,r);case"Macro":return hx(e,t,r);case"Break":return n+tt("break");case"Continue":return n+tt("continue");case"CallStatement":return fx(e,t,r);case"FilterStatement":return px(e,t,r);case"Comment":return n+"{# "+e.value+" #}";default:return n+"{{- "+ge(e)+" -}}"}}function cx(e,t,r){const n=r.repeat(t),s=[];let a=e;for(;a&&(s.push({test:a.test,body:a.body}),a.alternate.length===1&&a.alternate[0].type==="If");)a=a.alternate[0];let o=n+tt("if",ge(s[0].test))+qe+Bt(s[0].body,t+1,r);for(let i=1;i<s.length;++i)o+=qe+n+tt("elif",ge(s[i].test))+qe+Bt(s[i].body,t+1,r);return a&&a.alternate.length>0&&(o+=qe+n+tt("else")+qe+Bt(a.alternate,t+1,r)),o+=qe+n+tt("endif"),o}function ux(e,t,r){const n=r.repeat(t);let s="";if(e.iterable.type==="SelectExpression"){const o=e.iterable;s=`${ge(o.lhs)} if ${ge(o.test)}`}else s=ge(e.iterable);let a=n+tt("for",ge(e.loopvar),"in",s)+qe+Bt(e.body,t+1,r);return e.defaultBlock.length>0&&(a+=qe+n+tt("else")+qe+Bt(e.defaultBlock,t+1,r)),a+=qe+n+tt("endfor"),a}function dx(e,t,r){const n=r.repeat(t),s=ge(e.assignee),a=e.value?ge(e.value):"",o=n+tt("set",`${s}${e.value?" = "+a:""}`);return e.body.length===0?o:o+qe+Bt(e.body,t+1,r)+qe+n+tt("endset")}function hx(e,t,r){const n=r.repeat(t),s=e.args.map(ge).join(", ");return n+tt("macro",`${e.name.value}(${s})`)+qe+Bt(e.body,t+1,r)+qe+n+tt("endmacro")}function fx(e,t,r){const n=r.repeat(t),s=e.callerArgs&&e.callerArgs.length>0?`(${e.callerArgs.map(ge).join(", ")})`:"",a=ge(e.call);let o=n+tt(`call${s}`,a)+qe;return o+=Bt(e.body,t+1,r)+qe,o+=n+tt("endcall"),o}function px(e,t,r){const n=r.repeat(t),s=e.filter.type==="Identifier"?e.filter.value:ge(e.filter);let a=n+tt("filter",s)+qe;return a+=Bt(e.body,t+1,r)+qe,a+=n+tt("endfilter"),a}function ge(e,t=-1){switch(e.type){case"SpreadExpression":return`*${ge(e.argument)}`;case"Identifier":return e.value;case"IntegerLiteral":return`${e.value}`;case"FloatLiteral":return`${e.value}`;case"StringLiteral":return JSON.stringify(e.value);case"BinaryExpression":{const r=e,n=ox(r),s=ge(r.left,n),a=ge(r.right,n+1),o=`${s} ${r.operator.value} ${a}`;return n<t?`(${o})`:o}case"UnaryExpression":{const r=e;return r.operator.value+(r.operator.value==="not"?" ":"")+ge(r.argument,1/0)}case"CallExpression":{const r=e,n=r.args.map(ge).join(", ");return`${ge(r.callee)}(${n})`}case"MemberExpression":{const r=e;let n=ge(r.object);["Identifier","MemberExpression","CallExpression","StringLiteral","IntegerLiteral","FloatLiteral","ArrayLiteral","TupleLiteral","ObjectLiteral"].includes(r.object.type)||(n=`(${n})`);let s=ge(r.property);return!r.computed&&r.property.type!=="Identifier"&&(s=`(${s})`),r.computed?`${n}[${s}]`:`${n}.${s}`}case"FilterExpression":{const r=e,n=ge(r.operand,1/0);return r.filter.type==="CallExpression"?`${n} | ${ge(r.filter)}`:`${n} | ${r.filter.value}`}case"SelectExpression":{const r=e;return`${ge(r.lhs)} if ${ge(r.test)}`}case"TestExpression":{const r=e;return`${ge(r.operand)} is${r.negate?" not":""} ${r.test.value}`}case"ArrayLiteral":case"TupleLiteral":{const r=e.value.map(ge),n=e.type==="ArrayLiteral"?"[]":"()";return`${n[0]}${r.join(", ")}${n[1]}`}case"ObjectLiteral":return`{${Array.from(e.value.entries()).map(([n,s])=>`${ge(n)}: ${ge(s)}`).join(", ")}}`;case"SliceExpression":{const r=e,n=r.start?ge(r.start):"",s=r.stop?ge(r.stop):"",a=r.step?`:${ge(r.step)}`:"";return`${n}:${s}${a}`}case"KeywordArgumentExpression":{const r=e;return`${r.key.value}=${ge(r.value)}`}case"Ternary":{const r=e,n=`${ge(r.trueExpr)} if ${ge(r.condition,0)} else ${ge(r.falseExpr)}`;return t>-1?`(${n})`:n}default:throw new Error(`Unknown expression type: ${e.type}`)}}var _x=class{parsed;constructor(e){const t=kM(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=QM(t)}render(e){const t=new Ar;if(rx(t),e)for(const[s,a]of Object.entries(e))t.set(s,a);return new nx(t).run(this.parsed).value}format(e){return ix(this.parsed,e?.indent||" ")}},$t=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error("Must implement _call method in subclass")}},mx={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"},Js=class rp{constructor(t){if(this.filePath=t,this.headers=new Headers,this.exists=kt.existsSync(t),this.exists){this.status=200,this.statusText="OK";let r=kt.statSync(t);this.headers.set("content-length",r.size.toString()),this.updateContentType();const n=kt.createReadStream(t);this.body=new ReadableStream({start(s){n.on("data",a=>s.enqueue(a)),n.on("end",()=>s.close()),n.on("error",a=>s.error(a))},cancel(){n.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const t=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",mx[t]??"application/octet-stream")}clone(){let t=new rp(this.filePath);return t.exists=this.exists,t.status=this.status,t.statusText=this.statusText,t.headers=new Headers(this.headers),t}async arrayBuffer(){return(await kt.promises.readFile(this.filePath)).buffer}async blob(){const t=await kt.promises.readFile(this.filePath);return new Blob([t],{type:this.headers.get("content-type")})}async text(){return await kt.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},np=class{constructor(e){this.path=e}async match(e){let t=Qt.join(this.path,e),r=new Js(t);if(r.exists)return r}async put(e,t,r=void 0){let n=Qt.join(this.path,e);try{const s=t.headers.get("Content-Length"),a=parseInt(s??"0");let o=0;await kt.promises.mkdir(Qt.dirname(n),{recursive:!0});const i=kt.createWriteStream(n),l=t.body.getReader();for(;;){const{done:u,value:h}=await l.read();if(u)break;await new Promise((p,g)=>{i.write(h,v=>{if(v){g(v);return}p()})}),o+=h.length;const f=a?o/a*100:0;r?.({progress:f,loaded:o,total:a})}i.close()}catch(s){try{await kt.promises.unlink(n)}catch{}throw s}}async delete(e){let t=Qt.join(this.path,e);try{return await kt.promises.unlink(t),!0}catch{return!1}}},gx={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"},Th=100,wx=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Fs(...e){return e=e.map((t,r)=>(r&&(t=t.replace(new RegExp("^/"),"")),r!==e.length-1&&(t=t.replace(new RegExp("/$"),"")),t)),e.join("/")}function gn(e,t=null,r=null){let n;try{n=new URL(e)}catch{return!1}return!(t&&!t.includes(n.protocol)||r&&!r.includes(n.hostname))}function vx(e){return!(!wx.test(e)||e.includes("..")||e.includes("--")||e.endsWith(".git")||e.endsWith(".ipynb"))}function yx(e,t,r){if(!r)return null;const n=gx[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${n}: "${t}".`)}async function bx(e,t,r){const n=e.headers.get("Content-Length");let s=n?parseInt(n,10):r??0;n===null&&!r&&he.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let a=new Uint8Array(s),o=0;const i=e.body.getReader();async function l(){const{done:u,value:h}=await i.read();if(u)return;const f=o+h.length;if(f>s){s=f;const g=new Uint8Array(s);g.set(a),a=g}a.set(h,o),o=f;const p=o/s*100;return t({progress:p,loaded:o,total:s}),l()}return await l(),a}async function Mi(e=null){let t=null;if(ye.useCustomCache){if(!ye.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!ye.customCache.match||!ye.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");t=ye.customCache}if(!t&&ye.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{t=await caches.open(ye.cacheKey)}catch(r){he.warn("An error occurred while opening the browser cache:",r)}}if(!t&&ye.useFSCache){if(!Ae.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");t=new np(e??ye.cacheDir)}return t}async function Mx(e,...t){for(let r of t)try{let n=await e.match(r);if(n)return n}catch{continue}}async function xx(e){if(!gn(e,["http:","https:"]))return null;const t=ap(e);return t.set("Range","bytes=0-0"),ye.fetch(e,{method:"GET",headers:t})}async function sp(e,t,r={}){const n=await Mi(r?.cache_dir),{localPath:s,remoteURL:a,proposedCacheKey:o,validModelId:i}=op(e,t,r,n),l=await ip(n,s,o);if(l!==void 0&&typeof l!="string"){const u=l.headers.get("content-length"),h=l.headers.get("content-type");return{exists:!0,size:u?parseInt(u,10):void 0,contentType:h||void 0,fromCache:!0}}if(ye.allowLocalModels&&!gn(s,["http:","https:"]))try{const h=await Ks(s);if(typeof h!="string"&&h.status!==404){const f=h.headers.get("content-length"),p=h.headers.get("content-type");return{exists:!0,size:f?parseInt(f,10):void 0,contentType:p||void 0,fromCache:!1}}}catch{}if(ye.allowRemoteModels&&!r.local_files_only&&i)try{const u=await xx(a);if(u&&u.status>=200&&u.status<300){let h;const f=u.headers.get("content-type");if(u.status===206){const p=u.headers.get("content-range");if(p){const g=p.match(/bytes \d+-\d+\/(\d+)/);g&&(h=parseInt(g[1],10))}}else if(u.status===200)try{await u.body?.cancel()}catch{}if(h===void 0){const p=u.headers.get("content-length");h=p?parseInt(p,10):void 0}return{exists:!0,size:h,contentType:f||void 0,fromCache:!1}}}catch(u){he.warn(`Unable to fetch file metadata for "${a}": ${u}`)}return{exists:!1,fromCache:!1}}async function Ks(e){return ye.useFS&&!gn(e,["http:","https:","blob:"])?new Js(e instanceof URL?e.protocol==="file:"?e.pathname:e.toString():e):ye.fetch(e,{headers:ap(e)})}function ap(e){const t=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(t){const n=!!Io?.TESTING_REMOTELY,s=ye.version;if(r.set("User-Agent",`transformers.js/${s}; is_ci/${n};`),gn(e,["http:","https:"],["huggingface.co","hf.co"])){const o=Io?.HF_TOKEN??Io?.HF_ACCESS_TOKEN;o&&r.set("Authorization",`Bearer ${o}`)}}return r}function op(e,t,r={},n=null){const s=r.revision??"main",a=Fs(e,t),o=vx(e),i=o?Fs(ye.localModelPath,a):a,l=Fs(ye.remoteHost,ye.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(s)),t),u=n instanceof np?s==="main"?a:Fs(e,s,t):l;return{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:u,validModelId:o}}async function ip(e,t,r){if(e)return await Mx(e,t,r)}async function kx(e,t,r,n,s,a,o={}){if(await r.match(n)===void 0)if(a)typeof s!="string"&&await r.put(n,new Response(a,{headers:s.headers})).catch(i=>{he.warn(`Unable to add response to browser cache: ${i}.`)});else{const i=o.progress_callback?l=>an(o.progress_callback,{status:"progress",name:e,file:t,...l}):void 0;await r.put(n,s,i)}}async function Tx(e,t,r=!0,n={},s=!1,a=null){const{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:u,validModelId:h}=op(e,t,n,a);let f,p=!1,g;g=await ip(a,i,u);const v=g!==void 0;if(!v){if(ye.allowLocalModels)if(gn(o,["http:","https:"])){if(n.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${o}.`);if(!ye.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${o}.`)}else try{g=await Ks(i),f=i}catch(T){he.warn(`Unable to load from local path "${i}": "${T}"`)}if(g===void 0||typeof g!="string"&&g.status===404){if(n.local_files_only||!ye.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!h)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${e}".`);if(g=await Ks(l),g.status!==200)return yx(g.status,l,r);f=u}p=a&&typeof Response<"u"&&g instanceof Response&&g.status===200}an(n.progress_callback,{status:"download",name:e,file:t});let w;if(!(Ae.IS_NODE_ENV&&s)){let k;if(typeof g!="string")if(!n.progress_callback)k=new Uint8Array(await g.arrayBuffer());else if(v&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))k=new Uint8Array(await g.arrayBuffer()),an(n.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:k.length,total:k.length});else{let T;const S=g.headers.get("content-length");if(S)T=parseInt(S,10);else try{const E=await sp(e,t,n);E.size&&(T=E.size)}catch{}k=await bx(g,E=>{an(n.progress_callback,{status:"progress",name:e,file:t,...E})},T)}w=k}if(p&&f&&typeof g!="string"&&await kx(e,t,a,f,g,w,n),an(n.progress_callback,{status:"done",name:e,file:t}),w){if(!Ae.IS_NODE_ENV&&s)throw new Error("Cannot return path in a browser environment.");return w}if(g instanceof Js)return g.filePath;const M=await a?.match(f);if(M instanceof Js)return M.filePath;if(M instanceof Response)return new Uint8Array(await M.arrayBuffer());if(typeof M=="string")return M;throw new Error("Unable to get model file path or buffer.")}async function Zs(e,t,r=!0,n={},s=!1){if(!ye.allowLocalModels){if(n.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(!ye.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}an(n.progress_callback,{status:"initiate",name:e,file:t});const a=await Mi(n?.cache_dir);return await Tx(e,t,r,n,s,a)}async function lp(e,t,r=!0,n={}){const s=await Zs(e,t,r,n,!1);return s===null?null:new TextDecoder("utf-8").decode(s)}async function ir(e,t,r=!0,n={}){const s=await lp(e,t,r,n);return s===null?{}:JSON.parse(s)}function Ex(e,[t,r,n],[s,a],o="bilinear",i=!1){const l=a/n,u=s/r,h=new e.constructor(s*a*t),f=r*n,p=s*a;for(let g=0;g<s;++g)for(let v=0;v<a;++v){const w=g*a+v,M=(v+.5)/l-.5,k=(g+.5)/u-.5;let T=Math.floor(M),S=Math.floor(k);const E=Math.min(T+1,n-1),F=Math.min(S+1,r-1);T=Math.max(T,0),S=Math.max(S,0);const z=M-T,b=k-S,U=(1-z)*(1-b),G=z*(1-b),H=(1-z)*b,Z=z*b,W=S*n,B=F*n,O=W+T,$=W+E,ee=B+T,X=B+E;for(let A=0;A<t;++A){const L=A*f;h[A*p+w]=U*e[L+O]+G*e[L+$]+H*e[L+ee]+Z*e[L+X]}}return h}function Cx(e,t,r){const n=new Array(r.length),s=new Array(r.length);for(let i=r.length-1,l=1;i>=0;--i)s[i]=l,n[i]=t[r[i]],l*=n[i];const a=r.map((i,l)=>s[r.indexOf(l)]),o=new e.constructor(e.length);for(let i=0;i<e.length;++i){let l=0;for(let u=t.length-1,h=i;u>=0;--u)l+=h%t[u]*a[u],h=Math.floor(h/t[u]);o[l]=e[i]}return[o,n]}function wn(e){const t=He(e)[0],r=e.map(a=>Math.exp(a-t)),n=r.reduce((a,o)=>a+o,0);return r.map(a=>a/n)}function Sx(e){const t=He(e)[0];let r=0;for(let a=0;a<e.length;++a)r+=Math.exp(e[a]-t);const n=Math.log(r);return e.map(a=>a-t-n)}function Ho(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let n=1;n<e.length;++n)e[n]<t&&(t=e[n],r=n);return[t,r]}function He(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let n=1;n<e.length;++n)e[n]>t&&(t=e[n],r=n);return[t,r]}function cp(e){return e>0&&(e&e-1)===0}var up=class{constructor(e){if(this.size=e|0,this.size<=1||!cp(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 r=0;r<this.table.length;r+=2){const n=Math.PI*r/this.size;this.table[r]=Math.cos(n),this.table[r+1]=-Math.sin(n)}let t=0;for(let r=1;this.size>r;r<<=1)++t;this._width=t%2===0?t-1:t,this._bitrev=new Int32Array(1<<this._width);for(let r=0;r<this._bitrev.length;++r){this._bitrev[r]=0;for(let n=0;n<this._width;n+=2){const s=this._width-n-2;this._bitrev[r]|=(r>>>n&3)<<s}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,t){const r=t||new Array(e.length>>>1);for(let n=0;n<e.length;n+=2)r[n>>>1]=e[n];return r}toComplexArray(e,t){const r=t||this.createComplexArray();for(let n=0;n<r.length;n+=2)r[n]=e[n>>>1],r[n+1]=0;return r}transform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,-1);for(let r=0;r<e.length;++r)e[r]/=this.size}_transform4(e,t,r){const n=this._csize;let a=1<<this._width,o=n/a<<1,i,l;const u=this._bitrev;if(o===4)for(i=0,l=0;i<n;i+=o,++l){const f=u[l];this._singleTransform2(t,e,i,f,a)}else for(i=0,l=0;i<n;i+=o,++l){const f=u[l];this._singleTransform4(t,e,i,f,a,r)}const h=this.table;for(a>>=2;a>=2;a>>=2){o=n/a<<1;const f=o>>>2;for(i=0;i<n;i+=o){const p=i+f-1;for(let g=i,v=0;g<p;g+=2,v+=a){const w=g,M=w+f,k=M+f,T=k+f,S=e[w],E=e[w+1],F=e[M],z=e[M+1],b=e[k],U=e[k+1],G=e[T],H=e[T+1],Z=h[v],W=r*h[v+1],B=F*Z-z*W,O=F*W+z*Z,$=h[2*v],ee=r*h[2*v+1],X=b*$-U*ee,A=b*ee+U*$,L=h[3*v],D=r*h[3*v+1],J=G*L-H*D,ie=G*D+H*L,xe=S+X,Fe=E+A,ct=S-X,$e=E-A,ze=B+J,Ve=O+ie,ve=r*(B-J),de=r*(O-ie);e[w]=xe+ze,e[w+1]=Fe+Ve,e[M]=ct+de,e[M+1]=$e-ve,e[k]=xe-ze,e[k+1]=Fe-Ve,e[T]=ct-de,e[T+1]=$e+ve}}}}_singleTransform2(e,t,r,n,s){const a=e[n],o=e[n+1],i=e[n+s],l=e[n+s+1];t[r]=a+i,t[r+1]=o+l,t[r+2]=a-i,t[r+3]=o-l}_singleTransform4(e,t,r,n,s,a){const o=s*2,i=s*3,l=e[n],u=e[n+1],h=e[n+s],f=e[n+s+1],p=e[n+o],g=e[n+o+1],v=e[n+i],w=e[n+i+1],M=l+p,k=u+g,T=l-p,S=u-g,E=h+v,F=f+w,z=a*(h-v),b=a*(f-w);t[r]=M+E,t[r+1]=k+F,t[r+2]=T+b,t[r+3]=S-z,t[r+4]=M-E,t[r+5]=k-F,t[r+6]=T-b,t[r+7]=S+z}_realTransform4(e,t,r){const n=this._csize;let a=1<<this._width,o=n/a<<1,i,l;const u=this._bitrev;if(o===4)for(i=0,l=0;i<n;i+=o,++l){const p=u[l];this._singleRealTransform2(t,e,i,p>>>1,a>>>1)}else for(i=0,l=0;i<n;i+=o,++l){const p=u[l];this._singleRealTransform4(t,e,i,p>>>1,a>>>1,r)}const h=this.table;for(a>>=2;a>=2;a>>=2){o=n/a<<1;const p=o>>>1,g=p>>>1,v=g>>>1;for(i=0;i<n;i+=o)for(let w=0,M=0;w<=v;w+=2,M+=a){const k=i+w,T=k+g,S=T+g,E=S+g,F=e[k],z=e[k+1],b=e[T],U=e[T+1],G=e[S],H=e[S+1],Z=e[E],W=e[E+1],B=F,O=z,$=h[M],ee=r*h[M+1],X=b*$-U*ee,A=b*ee+U*$,L=h[2*M],D=r*h[2*M+1],J=G*L-H*D,ie=G*D+H*L,xe=h[3*M],Fe=r*h[3*M+1],ct=Z*xe-W*Fe,$e=Z*Fe+W*xe,ze=B+J,Ve=O+ie,ve=B-J,de=O-ie,Ue=X+ct,pe=A+$e,we=r*(X-ct),ur=r*(A-$e);if(e[k]=ze+Ue,e[k+1]=Ve+pe,e[T]=ve+ur,e[T+1]=de-we,w===0){e[S]=ze-Ue,e[S+1]=Ve-pe;continue}if(w===v)continue;const kr=i+g-w,ut=i+p-w;e[kr]=ve-r*ur,e[kr+1]=-de-r*we,e[ut]=ze-r*Ue,e[ut+1]=-Ve+r*pe}}const f=n>>>1;for(let p=2;p<f;p+=2)e[n-p]=e[p],e[n-p+1]=-e[p+1]}_singleRealTransform2(e,t,r,n,s){const a=e[n],o=e[n+s];t[r]=a+o,t[r+1]=0,t[r+2]=a-o,t[r+3]=0}_singleRealTransform4(e,t,r,n,s,a){const o=s*2,i=s*3,l=e[n],u=e[n+s],h=e[n+o],f=e[n+i],p=l+h,g=l-h,v=u+f,w=a*(u-f);t[r]=p+v,t[r+1]=0,t[r+2]=g,t[r+3]=-w,t[r+4]=p-v,t[r+5]=0,t[r+6]=g,t[r+7]=w}},Px=class{constructor(e){const t=2*(e-1),r=2*(2*e-1),n=2**Math.ceil(Math.log2(r));this.bufferSize=n,this._a=t;const s=new Float64Array(r),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);const o=-2*Math.PI/e,i=Math.cos(o),l=Math.sin(o);for(let u=0;u<r>>1;++u){const h=(u+1-e)**2/2,f=Math.sqrt(i**2+l**2)**h,p=h*Math.atan2(l,i),g=2*u;s[g]=f*Math.cos(p),s[g+1]=f*Math.sin(p),a[g]=s[g],a[g+1]=-s[g+1]}this._slicedChirpBuffer=s.subarray(t,r),this._f=new up(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,t,r){const n=this._buffer1,s=this._buffer2,a=this._outBuffer1,o=this._outBuffer2,i=this._chirpBuffer,l=this._slicedChirpBuffer,u=this._a;if(r)for(let h=0;h<l.length;h+=2){const f=h+1,p=h>>1,g=t[p];n[h]=g*l[h],n[f]=g*l[f]}else for(let h=0;h<l.length;h+=2){const f=h+1;n[h]=t[h]*l[h]-t[f]*l[f],n[f]=t[h]*l[f]+t[f]*l[h]}this._f.transform(a,n);for(let h=0;h<i.length;h+=2){const f=h+1;s[h]=a[h]*i[h]-a[f]*i[f],s[f]=a[h]*i[f]+a[f]*i[h]}this._f.inverseTransform(o,s);for(let h=0;h<o.length;h+=2){const f=o[h+u],p=o[h+u+1],g=l[h],v=l[h+1];e[h]=f*g-p*v,e[h+1]=f*v+p*g}}transform(e,t){this._transform(e,t,!1)}realTransform(e,t){this._transform(e,t,!0)}},Ax=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=cp(e),this.isPowerOfTwo?(this.fft=new up(e),this.outputBufferSize=2*e):(this.fft=new Px(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,t){this.fft.realTransform(e,t)}transform(e,t){this.fft.transform(e,t)}};function Fx(e,t){if(t%2===0||t<=0)throw new Error("Window size must be a positive odd number");const r=new e.constructor(e.length),n=new e.constructor(t),s=Math.floor(t/2);for(let a=0;a<e.length;++a){let o=0;for(let i=-s;i<=s;++i){let l=a+i;l<0?l=Math.abs(l):l>=e.length&&(l=2*(e.length-1)-l),n[o++]=e[l]}n.sort(),r[a]=n[s]}return r}function Is(e,t){const r=Math.pow(10,t);return Math.round(e*r)/r}function Ix(e){const t=Math.round(e);return Math.abs(e)%1===.5?t%2===0?t:t-1:t}function Lx(e){const t=e.length,r=e[0].length,n=[t+1,r+1],s=Array.from({length:n[0]},()=>Array(n[1]).fill(1/0));s[0][0]=0;const a=Array.from({length:n[0]},()=>Array(n[1]).fill(-1));for(let h=1;h<n[1];++h)for(let f=1;f<n[0];++f){const p=s[f-1][h-1],g=s[f-1][h],v=s[f][h-1];let w,M;p<g&&p<v?(w=p,M=0):g<p&&g<v?(w=g,M=1):(w=v,M=2),s[f][h]=e[f-1][h-1]+w,a[f][h]=M}for(let h=0;h<n[1];++h)a[0][h]=2;for(let h=0;h<n[0];++h)a[h][0]=1;let o=t,i=r,l=[],u=[];for(;o>0||i>0;)switch(l.push(o-1),u.push(i-1),a[o][i]){case 0:--o,--i;break;case 1:--o;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${o}, ${i}]. Please file a bug report.`)}return l.reverse(),u.reverse(),[l,u]}var Ox=function(){let e=null;return function(t){if(!e){e=new Float32Array(65536);const a=new ArrayBuffer(4),o=new Uint32Array(a),i=new Float32Array(a);for(let l=0;l<e.length;++l){let u=0;const h=(l&32768)<<16,f=(l&31744)>>10;let p=l&1023;if(f===31)u=h|2139095040|p<<13;else if(f===0)if(p===0)u=h;else{let g=113;for(;!(p&1024);)p<<=1,--g;p&=-1025,u=h|g<<23|p<<13}else u=h|f+112<<23|p<<13;o[0]=u,e[l]=i[0]}}const r=t.length,n=e,s=new Float32Array(r);for(let a=0;a<r;++a)s[a]=n[t[a]];return s}}(),dp={};_n(dp,{default:()=>Nx});var Nx={};async function hp(e){const t=e.split("/").pop();let r;try{if(r=await Mi(),r){const s=await r.match(e);if(s)return s}}catch(s){he.warn(`Failed to load ${t} from cache:`,s)}const n=await ye.fetch(e);if(!n.ok)throw new Error(`Failed to fetch ${t}: ${n.status} ${n.statusText}`);if(r)try{await r.put(e,n.clone())}catch(s){he.warn(`Failed to cache ${t}:`,s)}return n}async function Dx(e){const t=await hp(e);if(!t||typeof t=="string")return null;try{return await t.arrayBuffer()}catch(r){return he.warn("Failed to read WASM binary:",r),null}}async function Bx(e){const t=await hp(e);if(!t||typeof t=="string")return null;try{let r=await t.text();const n=e.split("/").slice(0,-1).join("/");r=r.replaceAll("import.meta.url",`"${n}"`),r=r.replaceAll("globalThis.process?.versions?.node","false");const s=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(s)}catch(r){return he.warn("Failed to read WASM binary:",r),null}}function Eh(e){return gn(e,["blob:"])}function Ch(e){let t;if(typeof location<"u"&&location.href)t=location.href;else if(typeof import.meta<"u"&&import.meta.url)t=import.meta.url;else return e;return new URL(e,t).href}var zx=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 fp(e){return e<=Ot.DEBUG?0:e<=Ot.INFO?2:e<=Ot.WARNING||e<=Ot.ERROR?3:4}var Rx={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},xt=[],Qo,cn,Sh=Symbol.for("onnxruntime");if(Sh in globalThis)cn=globalThis[Sh];else if(Ae.IS_NODE_ENV){switch(cn=dp,process.platform){case"win32":xt.push("dml");break;case"linux":process.arch==="x64"&&xt.push("cuda");break;case"darwin":xt.push("coreml");break}xt.push("webgpu"),xt.push("cpu"),Qo=["cpu"]}else cn=zy,Ae.IS_WEBNN_AVAILABLE&&xt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),Ae.IS_WEBGPU_AVAILABLE&&xt.push("webgpu"),xt.push("wasm"),Qo=["wasm"];var Gx=cn.InferenceSession;function $x(e=null){if(!e)return Qo;switch(e){case"auto":return xt;case"gpu":return xt.filter(t=>["webgpu","cuda","dml","webnn-gpu"].includes(t))}if(xt.includes(e))return[zx[e]??e];throw new Error(`Unsupported device: "${e}". Should be one of: ${xt.join(", ")}.`)}var pp=Ae.IS_BROWSER_ENV||Ae.IS_WEBWORKER_ENV,Ph=Promise.resolve(),Zr=null;async function Vx(){return Zr||(ye.useWasmCache&&typeof et?.wasm?.wasmPaths=="object"&&et?.wasm?.wasmPaths?.wasm&&et?.wasm?.wasmPaths?.mjs?(Zr=(async()=>{const t=et.wasm.wasmPaths;await Promise.all([t.wasm&&!Eh(t.wasm)?(async()=>{try{const r=await Dx(Ch(t.wasm));r&&(et.wasm.wasmBinary=r)}catch(r){he.warn("Failed to pre-load WASM binary:",r)}})():Promise.resolve(),t.mjs&&!Eh(t.mjs)?(async()=>{try{const r=await Bx(Ch(t.mjs));r&&(et.wasm.wasmPaths.mjs=r)}catch(r){he.warn("Failed to pre-load WASM factory:",r)}})():Promise.resolve()])})(),Zr):(Zr=Promise.resolve(),Zr))}async function _p(e,t,r){await Vx();const n=fp(ye.logLevel??Ot.WARNING),s=()=>Gx.create(e,{logSeverityLevel:n,...t}),a=await(pp?Ph=Ph.then(s):s());return a.config=r,a}var Ah=Promise.resolve();async function mp(e,t){const r=()=>e.run(t);return await(pp?Ah=Ah.then(r):r())}function gp(e){return e instanceof cn.Tensor}var et=cn?.env;if(et?.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&et.versions?.web&&!et.wasm.wasmPaths){const e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${et.versions.web}/dist/`;et.wasm.wasmPaths=Ae.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`}}et.wasm.proxy=!1}et?.webgpu&&(et.webgpu.powerPreference="high-performance");function xi(){return et?.wasm?.proxy}function wp(e){const t=fp(e);et.logLevel=Rx[t]}wp(ye.logLevel??Ot.WARNING);ye.backends.onnx={...et,setLogLevel:wp};var gr=async(e,t,r)=>{const n=await _p(new Uint8Array(e),t);return async s=>{const a=xi(),o=Object.fromEntries(Object.entries(s).map(([l,u])=>[l,(a?u.clone():u).ort_tensor])),i=await mp(n,o);return Array.isArray(r)?r.map(l=>new q(i[l])):new q(i[r])}},un=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=gr([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=gr([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=gr([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=gr([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=gr([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=gr([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=gr([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=gr([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}},Ux=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"}),Oo=Ae.IS_NODE_ENV?"cpu":"wasm";function Wx(e,t,{warn:r}={}){return e?typeof e=="string"?e:e.hasOwnProperty(t)?e[t]:(r&&r(`device not specified for "${t}". Using the default device (${Oo}).`),Oo):Oo}var jx=function(){let e;return async function(){if(e===void 0)if(!Ae.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{e=!1}return e}}(),st=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),Fh=st.fp32,Ih=Object.freeze({[Ux.wasm]:st.q8}),Lh=Object.freeze({[st.fp32]:"",[st.fp16]:"_fp16",[st.int8]:"_int8",[st.uint8]:"_uint8",[st.q8]:"_quantized",[st.q4]:"_q4",[st.q4f16]:"_q4f16",[st.bnb4]:"_bnb4"});function qx(e,t,r,{configDtype:n=null,warn:s}={}){let a,o=!1;e&&typeof e!="string"?e.hasOwnProperty(t)?a=e[t]:(a=null,o=!0):a=e;let i;if(a===st.auto){if(n){const l=typeof n=="string"?n:n?.[t];if(l&&l!==st.auto&&st.hasOwnProperty(l))return l}i=Ih[r]??Fh}else a&&st.hasOwnProperty(a)?i=a:i=Ih[r]??Fh;return o&&s&&s(`dtype not specified for "${t}". Using the default dtype (${i}) for this device (${r}).`),i}var ea=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}),vp=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(Ae.IS_CRYPTO_AVAILABLE){const o=new Uint32Array(1);crypto.getRandomValues(o),e=o[0]}else e=Date.now()>>>0;const t=this._mt,r=(o,i)=>Math.imul(o,i)>>>0,n=[];for(let o=e||0;o>0;o=Math.floor(o/4294967296))n.push(o&4294967295);n.length||n.push(0),t[0]=19650218;for(let o=1;o<624;++o)t[o]=r(1812433253,t[o-1]^t[o-1]>>>30)+o>>>0;let s=1,a=0;for(let o=Math.max(624,n.length);o>0;--o,++s,++a)s>=624&&(t[0]=t[623],s=1),a>=n.length&&(a=0),t[s]=(t[s]^r(t[s-1]^t[s-1]>>>30,1664525))+n[a]+a>>>0;for(let o=623;o>0;--o,++s)s>=624&&(t[0]=t[623],s=1),t[s]=(t[s]^r(t[s-1]^t[s-1]>>>30,1566083941))-s>>>0;t[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){const e=this._mt;if(this._idx>=624){for(let r=0;r<624;++r){const n=e[r]&2147483648|e[(r+1)%624]&2147483647;e[r]=(e[(r+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let t=e[this._idx++];return t^=t>>>11,t^=t<<7&2636928640,t^=t<<15&4022730752,t^=t>>>18,t>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,t=1){let r=this._gauss_next;if(this._gauss_next=null,r===null){const n=this.random()*2*Math.PI,s=Math.sqrt(-2*Math.log(1-this.random()));r=Math.cos(n)*s,this._gauss_next=Math.sin(n)*s}return e+r*t}shuffle(e){for(let t=e.length-1;t>0;--t){const r=32-Math.clz32(t+1);let n=this._int32()>>>32-r;for(;n>t;)n=this._int32()>>>32-r;const s=e[t];e[t]=e[n],e[n]=s}}choices(e,t){return e[yp(this._random_fn,t)]}};function yp(e,t){let r=0;for(let s=0;s<t.length;++s)r+=t[s];let n=e()*r;for(let s=0;s<t.length;++s)if(n-=t[s],n<0)return s;return t.length-1}var jt=new vp,ki=Object.freeze({Random:vp,seed:jt.seed.bind(jt),random:jt.random.bind(jt),gauss:jt.gauss.bind(jt),shuffle:jt.shuffle.bind(jt),choices:jt.choices.bind(jt)}),Hx=e=>yp(ki.random,e),q=class Re{get dims(){return this.ort_tensor.dims}set dims(t){this.ort_tensor.dims=t}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(...t){return gp(t[0])?this.ort_tensor=t[0]:this.ort_tensor=new Xy(t[0],t[1],t[2]),new Proxy(this,{get:(r,n)=>{if(typeof n=="string"){let s=Number(n);if(Number.isInteger(s))return r._getitem(s)}return r[n]},set:(r,n,s)=>r[n]=s})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[t,...r]=this.dims;if(r.length>0){const n=r.reduce((s,a)=>s*a);for(let s=0;s<t;++s)yield this._subarray(s,n,r)}else yield*this.data}_getitem(t){const[r,...n]=this.dims;if(t=Ht(t,r),n.length>0){const s=n.reduce((a,o)=>a*o);return this._subarray(t,s,n)}else return new Re(this.type,[this.data[t]],n)}indexOf(t){const r=this.data;for(let n=0;n<r.length;++n)if(r[n]==t)return n;return-1}_subarray(t,r,n){const s=t*r,a=(t+1)*r,o="subarray"in this.data?this.data.subarray(s,a):this.data.slice(s,a);return new Re(this.type,o,n)}item(){const t=this.data;if(t.length!==1)throw new Error(`a Tensor with ${t.length} elements cannot be converted to Scalar`);return t[0]}tolist(){return Qx(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){const t=this.data;for(let r=0;r<t.length;++r)t[r]=1/(1+Math.exp(-t[r]));return this}map(t){return this.clone().map_(t)}map_(t){const r=this.data;for(let n=0;n<r.length;++n)r[n]=t(r[n],n,r);return this}mul(t){return this.clone().mul_(t)}mul_(t){const r=this.data;for(let n=0;n<r.length;++n)r[n]*=t;return this}div(t){return this.clone().div_(t)}div_(t){const r=this.data;for(let n=0;n<r.length;++n)r[n]/=t;return this}add(t){return this.clone().add_(t)}add_(t){const r=this.data;for(let n=0;n<r.length;++n)r[n]+=t;return this}sub(t){return this.clone().sub_(t)}sub_(t){const r=this.data;for(let n=0;n<r.length;++n)r[n]-=t;return this}clone(){return new Re(this.type,this.data.slice(),this.dims.slice())}slice(...t){const r=[],n=[];for(let h=0;h<this.dims.length;++h){let f=t[h];if(f==null)n.push([0,this.dims[h]]),r.push(this.dims[h]);else if(typeof f=="number")f=Ht(f,this.dims[h],h),n.push([f,f+1]);else if(Array.isArray(f)&&f.length===2){let[p,g]=f;if(p=p===null?0:Ht(p,this.dims[h],h,!1),g=g===null?this.dims[h]:Ht(g,this.dims[h],h,!1),p>g)throw new Error(`Invalid slice: ${f}`);const v=[Math.max(p,0),Math.min(g,this.dims[h])];n.push(v),r.push(v[1]-v[0])}else throw new Error(`Invalid slice: ${f}`)}const s=n.map(([h,f])=>f-h),a=s.reduce((h,f)=>h*f),o=this.data,i=new o.constructor(a),l=this.stride();let u=!0;for(let h=1;h<s.length;++h)if(n[h][0]!==0||n[h][1]!==this.dims[h]){u=!1;break}if(u){const h=n[0][0]*l[0],f=n[0][1]*l[0];if(ArrayBuffer.isView(o))i.set(o.subarray(h,f));else if(Array.isArray(o)){const p=o.slice(h,f);for(let g=0;g<p.length;++g)i[g]=p[g]}else throw new Error("Unsupported data type for slicing")}else for(let h=0;h<a;++h){let f=0;for(let p=s.length-1,g=h;p>=0;--p){const v=s[p];f+=(g%v+n[p][0])*l[p],g=Math.floor(g/v)}i[h]=o[f]}return new Re(this.type,i,r)}permute(...t){return Xx(this,t)}transpose(...t){return this.permute(...t)}sum(t=null,r=!1){return this.norm(1,t,r)}norm(t="fro",r=null,n=!1){if(t==="fro")t=2;else if(typeof t=="string")throw Error(`Unsupported norm: ${t}`);const s=this.data,a=(u,h)=>u+h**t;if(r===null){const u=s.reduce(a,0)**(1/t);return new Re(this.type,[u],[])}const[o,i,l]=Jn(a,this,r,n);if(t!==1)for(let u=0;u<i.length;++u)i[u]=i[u]**(1/t);return new Re(o,i,l)}normalize_(t=2,r=1){r=Ht(r,this.dims.length);const n=this.norm(t,r,!0),s=this.data,a=n.data;for(let o=0;o<s.length;++o){let i=0;for(let l=this.dims.length-1,u=o,h=1;l>=0;--l){const f=this.dims[l];if(l!==r){const p=u%f;i+=p*h,h*=this.dims[l]}u=Math.floor(u/f)}s[o]/=a[i]}return this}normalize(t=2,r=1){return this.clone().normalize_(t,r)}stride(){return No(this.dims)}squeeze(t=null){return new Re(this.type,this.data,Oh(this.dims,t))}squeeze_(t=null){return this.dims=Oh(this.dims,t),this}unsqueeze(t){return new Re(this.type,this.data,Nh(this.dims,t))}unsqueeze_(t){return this.dims=Nh(this.dims,t),this}flatten_(t=0,r=-1){r=(r+this.dims.length)%this.dims.length;let n=this.dims.slice(0,t),s=this.dims.slice(t,r+1),a=this.dims.slice(r+1);return this.dims=[...n,s.reduce((o,i)=>o*i,1),...a],this}flatten(t=0,r=-1){return this.clone().flatten_(t,r)}view(...t){let r=-1;for(let s=0;s<t.length;++s)if(t[s]===-1){if(r!==-1)throw new Error("Only one dimension can be inferred");r=s}const n=this.data;if(r!==-1){const s=t.reduce((a,o,i)=>i!==r?a*o:a,1);t[r]=n.length/s}return new Re(this.type,n,t)}neg_(){const t=this.data;for(let r=0;r<t.length;++r)t[r]=-t[r];return this}neg(){return this.clone().neg_()}gt(t){const r=new Uint8Array(this.data.length),n=this.data;for(let s=0;s<n.length;++s)r[s]=n[s]>t?1:0;return new Re("bool",r,this.dims)}lt(t){const r=new Uint8Array(this.data.length),n=this.data;for(let s=0;s<n.length;++s)r[s]=n[s]<t?1:0;return new Re("bool",r,this.dims)}clamp_(t,r){const n=this.data;for(let s=0;s<n.length;++s)n[s]=Math.min(Math.max(n[s],t),r);return this}clamp(t,r){return this.clone().clamp_(t,r)}round_(){const t=this.data;for(let r=0;r<t.length;++r)t[r]=Math.round(t[r]);return this}round(){return this.clone().round_()}mean(t=null,r=!1){return Ti(this,t,r)}min(t=null,r=!1){if(t===null){const o=Ho(this.data)[0];return new Re(this.type,[o],[])}const[n,s,a]=Jn((o,i)=>Math.min(o,i),this,t,r,1/0);return new Re(n,s,a)}max(t=null,r=!1){if(t===null){const o=He(this.data)[0];return new Re(this.type,[o],[])}const[n,s,a]=Jn((o,i)=>Math.max(o,i),this,t,r,-1/0);return new Re(n,s,a)}argmin(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const n=Ho(this.data)[1];return new Re("int64",[BigInt(n)],[])}argmax(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const n=He(this.data)[1];return new Re("int64",[BigInt(n)],[])}repeat(...t){if(t.length<this.dims.length)throw new Error(`Number of dimensions of repeat dims (${t.length}) cannot be smaller than number of dimensions of tensor (${this.dims.length})`);if(t.every(h=>h===1)){if(t.length===this.dims.length)return this.clone();const h=t.length-this.dims.length,f=Array(h).fill(1).concat(this.dims);return new Re(this.type,this.data.slice(),f)}const r=t.length-this.dims.length,n=Array(r).fill(1).concat(this.dims),s=n.map((h,f)=>h*t[f]),a=s.reduce((h,f)=>h*f,1),o=this.data,i=new o.constructor(a),l=No(n),u=No(s);for(let h=0;h<a;++h){let f=h,p=0;for(let g=0;g<s.length;++g){const v=Math.floor(f/u[g]);f=f%u[g];const w=v%n[g];p+=w*l[g]}i[h]=o[p]}return new Re(this.type,i,s)}tile(...t){if(t.length<this.dims.length){const r=this.dims.length-t.length;t=Array(r).fill(1).concat(t)}return this.repeat(...t)}to(t){if(this.type===t)return this;if(!ea.hasOwnProperty(t))throw new Error(`Unsupported type: ${t}`);let r;const n=["int64","uint64"].includes(this.type),s=["int64","uint64"].includes(t);if(n&&!s)r=Number;else if(!n&&s)["float16","float32","float64"].includes(this.type)?r=a=>BigInt(Math.floor(a)):r=BigInt;else if(this.type==="float16"&&t=="float32"&&this.data instanceof Uint16Array)return new Re(t,Ox(this.data),this.dims);return new Re(t,ea[t].from(this.data,r),this.dims)}};function Qx(e,t){const r=e.length,n=t.reduce((a,o)=>a*o);if(r!==n)throw Error(`cannot reshape array of size ${r} into shape (${t})`);let s=e;for(let a=t.length-1;a>=0;a--)s=s.reduce((o,i)=>{let l=o[o.length-1];return l.length<t[a]?l.push(i):o.push([i]),o},[[]]);return s[0]}function Xx(e,t){const[r,n]=Cx(e.data,e.dims,t);return new q(e.type,r,n)}function bp(e,[t,r],n="bilinear",s=!1){const a=e.dims.at(-3)??1,o=e.dims.at(-2),i=e.dims.at(-1),l=Ex(e.data,[a,o,i],[t,r],n,s);return new q(e.type,l,[a,t,r])}async function Dr(e,{size:t=null,mode:r="bilinear"}={}){if(e.dims.length!==4)throw new Error("`interpolate_4d` currently only supports 4D input.");if(!t)throw new Error("`interpolate_4d` requires a `size` argument.");let n;if(t.length===2)n=[...e.dims.slice(0,2),...t];else if(t.length===3)n=[e.dims[0],...t];else if(t.length===4)n=t;else throw new Error("`size` must be of length 2, 3, or 4.");let s;if(r==="nearest")s=await un.nearest_interpolate_4d;else if(r==="bilinear")s=await un.bilinear_interpolate_4d;else if(r==="bicubic")s=await un.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${r}`);const a=new q("int64",new BigInt64Array(n.map(BigInt)),[n.length]);return await s({x:e,s:a})}async function Yx(e,t){return await(await un.matmul)({a:e,b:t})}async function Mp(e,t){const r=await un.top_k;return t==null?t=e.dims.at(-1):t=Math.min(t,e.dims.at(-1)),await r({x:e,k:new q("int64",[BigInt(t)],[1])})}var Ls=e=>new q("int64",e,[e.length]);async function xp(e,t,r,n,s){return await(await un.slice)({x:e,s:Ls(t),e:Ls(r),a:Ls(n),t:Ls(new Array(n.length).fill(1))})}function Oh(e,t){return e=e.slice(),t===null?e=e.filter(r=>r!==1):typeof t=="number"?e[t]===1&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((r,n)=>r!==1||!t.includes(n))),e}function Nh(e,t){return t=Ht(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function Ht(e,t,r=null,n=!0){if(e<-t||e>=t){if(n)throw new Error(`IndexError: index ${e} is out of bounds for dimension${r===null?"":" "+r} with size ${t}`);return e<-t?0:t}return e<0&&(e=(e%t+t)%t),e}function Be(e,t=0){t=Ht(t,e[0].dims.length);const r=e[0].dims.slice();r[t]=e.reduce((o,i)=>o+i.dims[t],0);const n=r.reduce((o,i)=>o*i,1),s=new e[0].data.constructor(n),a=e[0].type;if(t===0){let o=0;for(const i of e){const l=i.data;s.set(l,o),o+=l.length}}else{let o=0;for(let i=0;i<e.length;++i){const{data:l,dims:u}=e[i];for(let h=0;h<l.length;++h){let f=0;for(let p=u.length-1,g=h,v=1;p>=0;--p){const w=u[p];let M=g%w;p===t&&(M+=o),f+=M*v,v*=r[p],g=Math.floor(g/w)}s[f]=l[h]}o+=u[t]}}return new q(a,s,r)}function vn(e,t=0){return Be(e.map(r=>r.unsqueeze(t)),t)}function Jn(e,t,r,n=!1,s=null){const a=t.data,o=t.dims;r=Ht(r,o.length);const i=o.slice();i[r]=1;const l=new a.constructor(a.length/o[r]);s!==null&&l.fill(s);for(let u=0;u<a.length;++u){let h=0;for(let f=o.length-1,p=u,g=1;f>=0;--f){const v=o[f];if(f!==r){const w=p%v;h+=w*g,g*=i[f]}p=Math.floor(p/v)}l[h]=e(l[h],a[u],u,h)}return n||i.splice(r,1),[t.type,l,i]}function Jx(e,t=null,r=1,n=!1){const s=e.data,a=e.dims;if(t===null){const g=s.reduce((k,T)=>k+T,0)/s.length,v=Math.sqrt(s.reduce((k,T)=>k+(T-g)**2,0)/(s.length-r)),w=new q(e.type,[g],[]);return[new q(e.type,[v],[]),w]}t=Ht(t,a.length);const o=Ti(e,t,n),i=o.data,[l,u,h]=Jn((p,g,v,w)=>p+(g-i[w])**2,e,t,n);for(let p=0;p<u.length;++p)u[p]=Math.sqrt(u[p]/(a[t]-r));return[new q(l,u,h),o]}function Ti(e,t=null,r=!1){const n=e.dims,s=e.data;if(t===null){const l=s.reduce((u,h)=>u+h,0);return new q(e.type,[l/s.length],[])}t=Ht(t,n.length);const[a,o,i]=Jn((l,u)=>l+u,e,t,r);if(n[t]!==1)for(let l=0;l<o.length;++l)o[l]/=n[t];return new q(a,o,i)}function No(e){const t=new Array(e.length);for(let r=e.length-1,n=1;r>=0;--r)t[r]=n,n*=e[r];return t}function Ei(e,t,r,n){const s=e.reduce((a,o)=>a*o,1);return new q(r,new n(s).fill(t),e)}function at(e,t){let r,n;if(typeof t=="number")r="float32",n=Float32Array;else if(typeof t=="bigint")r="int64",n=BigInt64Array;else if(typeof t=="boolean")r="bool",n=Uint8Array;else throw new Error(`Unsupported data type: ${typeof t}`);return Ei(e,t,r,n)}function Xo(e,t){return at(e.dims,t)}function Et(e){return Ei(e,1n,"int64",BigInt64Array)}function kp(e){return Et(e.dims)}function Tp(e){return Ei(e,0n,"int64",BigInt64Array)}function Ep(e){return Tp(e.dims)}function Kx(e){const t=e.reduce((r,n)=>r*n,1);return new q("float32",Float32Array.from({length:t},()=>ki.gauss()),e)}async function Zx(e){if(!e)throw new Error("modelId is required for get_tokenizer_files");return(await sp(e,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function Cp(e,t){const r=await Zx(e);return await Promise.all(r.map(n=>ir(e,n,!0,t)))}function Sp(e){const t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(t[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return e.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}var e1=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function t1(e,t,r,n){for(const s of Object.keys(e)){const a=t-e[s].length,o=r(s),i=new Array(a).fill(o);e[s]=n==="right"?Nt(e[s],i):Nt(i,e[s])}}function r1(e,t){for(const r of Object.keys(e))e[r].length=t}function Pr(e,...t){for(const r of t){if(!Object.hasOwn(e,r))continue;const n=e[r];if(n)if(typeof n=="object"){if(n.__type==="AddedToken")return n.content;throw Error(`Unknown token: ${n}`)}else return n}return null}function n1(e){const t=[];for(const r of e.get_added_tokens_decoder().values())r.special&&t.push(r);return t}var ae=class extends $t{return_token_type_ids=!1;padding_side="right";constructor(e,t){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=t,this._tokenizer=new yM(e,t),this.config=t,this.padding_side=t.padding_side??this.padding_side,this.mask_token=Pr(t,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Pr(t,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Pr(t,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Pr(t,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Pr(t,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Pr(t,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=t.chat_template??null,Array.isArray(this.chat_template)){const n=Object.create(null);for(const{name:s,template:a}of this.chat_template){if(typeof s!="string"||typeof a!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');n[s]=a}this.chat_template=n}this._compiled_template_cache=new Map;const r=n1(this._tokenizer);this.all_special_ids=r.map(n=>n.id),this.all_special_tokens=r.map(n=>n.content)}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:n=null,local_files_only:s=!1,revision:a="main"}={}){const o=await Cp(e,{progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a});return new this(...o)}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(t=>this._tokenizer.token_to_id(t))}_call(e,{text_pair:t=null,add_special_tokens:r=!0,padding:n=!1,truncation:s=null,max_length:a=null,return_tensor:o=!0,return_token_type_ids:i=null}={}){const l=Array.isArray(e);let u;if(l){if(e.length===0)throw Error("text array must be non-empty");if(t!==null){if(Array.isArray(t)){if(e.length!==t.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");u=e.map((f,p)=>this._encode_plus(f,{text_pair:t[p],add_special_tokens:r,return_token_type_ids:i}))}else u=e.map(f=>this._encode_plus(f,{add_special_tokens:r,return_token_type_ids:i}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(t))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");u=[this._encode_plus(e,{text_pair:t,add_special_tokens:r,return_token_type_ids:i})]}if(a===null?a=this.model_max_length:s===null&&(n===!0?(he.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&&(he.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."),s=!0)),n===!0&&(a=Math.min(He(u.map(f=>f.input_ids.length))[0],a??1/0)),a=Math.min(a,this.model_max_length??1/0),n||s)for(let f=0;f<u.length;++f)u[f].input_ids.length!==a&&(u[f].input_ids.length>a?s&&r1(u[f],a):n&&t1(u[f],a,p=>p==="input_ids"?this.pad_token_id:0,this.padding_side));const h={};if(o){if(!(n&&s)&&u.some(p=>{for(const g of Object.keys(p))if(p[g].length!==u[0][g]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const f=[u.length,u[0].input_ids.length];for(const p of Object.keys(u[0]))h[p]=new q("int64",BigInt64Array.from(u.flatMap(g=>g[p]).map(BigInt)),f)}else{for(const f of Object.keys(u[0]))h[f]=u.map(p=>p[f]);if(!l)for(const f of Object.keys(h))h[f]=h[f][0]}return h}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){const{ids:s,attention_mask:a,token_type_ids:o}=this._tokenizer.encode(e,{text_pair:t,add_special_tokens:r,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:s,attention_mask:a,...o?{token_type_ids:o}:{}}}tokenize(e,{pair:t=null,add_special_tokens:r=!1}={}){return this._tokenizer.tokenize(e,{text_pair:t,add_special_tokens:r})}encode(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(e,{text_pair:t,add_special_tokens:r,return_token_type_ids:n}).ids}batch_decode(e,t={}){return e instanceof q&&(e=e.tolist()),e.map(r=>this.decode(r,t))}decode(e,t={}){if(e instanceof q&&(e=Sp(e)),!Array.isArray(e)||e.length===0||!lb(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,t)}decode_single(e,{skip_special_tokens:t=!1,clean_up_tokenization_spaces:r=null}){return this._tokenizer.decode(e,{skip_special_tokens:t,clean_up_tokenization_spaces:r})}get_chat_template({chat_template:e=null,tools:t=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const r=this.chat_template;if(e!==null&&Object.hasOwn(r,e))e=r[e];else if(e===null)if(t!==null&&"tool_use"in r)e=r.tool_use;else if("default"in r)e=r.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(r).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:t=null,documents:r=null,chat_template:n=null,add_generation_prompt:s=!1,tokenize:a=!0,padding:o=!1,truncation:i=!1,max_length:l=null,return_tensor:u=!0,return_dict:h=!0,tokenizer_kwargs:f={},...p}={}){if(n=this.get_chat_template({chat_template:n,tools:t}),typeof n!="string")throw Error(`chat_template must be a string, but got ${typeof n}`);let g=this._compiled_template_cache.get(n);g===void 0&&(g=new _x(n),this._compiled_template_cache.set(n,g));const v=Object.create(null);for(const M of e1){const k=Pr(this.config,M);k&&(v[M]=k)}const w=g.render({messages:e,add_generation_prompt:s,tools:t,documents:r,...v,...p});if(a){const M=this._call(w,{add_special_tokens:!1,padding:o,truncation:i,max_length:l,return_tensor:u,...f});return h?M:M.input_ids}return w}};function Ci(e,t,r,n){if(!("language_codes"in e)||!Array.isArray(e.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in e)||!(e.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in e)||typeof e.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const s=n.src_lang,a=n.tgt_lang;if(!e.language_codes.includes(a))throw new Error(`Target language code "${a}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);if(s!==void 0){if(!e.language_codes.includes(s))throw new Error(`Source language code "${s}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);for(const o of e._tokenizer.post_processor.config.single)if("SpecialToken"in o&&e.languageRegex.test(o.SpecialToken.id)){o.SpecialToken.id=e.lang_to_token(s);break}}return n.forced_bos_token_id=e._tokenizer.token_to_id(e.lang_to_token(a)),e._call(t,r)}var Pp={};_n(Pp,{AlbertTokenizer:()=>s1,AutoTokenizer:()=>Ee,BartTokenizer:()=>a1,BertTokenizer:()=>o1,BlenderbotSmallTokenizer:()=>i1,BlenderbotTokenizer:()=>l1,BloomTokenizer:()=>c1,CLIPTokenizer:()=>d1,CamembertTokenizer:()=>u1,CodeGenTokenizer:()=>f1,CodeLlamaTokenizer:()=>h1,CohereTokenizer:()=>p1,ConvBertTokenizer:()=>_1,DebertaTokenizer:()=>g1,DebertaV2Tokenizer:()=>m1,DistilBertTokenizer:()=>w1,ElectraTokenizer:()=>v1,EsmTokenizer:()=>y1,FalconTokenizer:()=>b1,GPT2Tokenizer:()=>k1,GPTNeoXTokenizer:()=>x1,GemmaTokenizer:()=>M1,HerbertTokenizer:()=>T1,LlamaTokenizer:()=>E1,M2M100Tokenizer:()=>C1,MBart50Tokenizer:()=>P1,MBartTokenizer:()=>Ap,MPNetTokenizer:()=>I1,MarianTokenizer:()=>S1,MgpstrTokenizer:()=>A1,MobileBertTokenizer:()=>F1,NllbTokenizer:()=>L1,NougatTokenizer:()=>O1,PreTrainedTokenizer:()=>ae,Qwen2Tokenizer:()=>N1,RoFormerTokenizer:()=>B1,RobertaTokenizer:()=>D1,SiglipTokenizer:()=>z1,SpeechT5Tokenizer:()=>R1,SqueezeBertTokenizer:()=>G1,T5Tokenizer:()=>$1,TokenizersBackend:()=>ae,VitsTokenizer:()=>U1,Wav2Vec2CTCTokenizer:()=>W1,WhisperTokenizer:()=>Q1,XLMRobertaTokenizer:()=>X1,XLMTokenizer:()=>Y1});var s1=class extends ae{return_token_type_ids=!0},a1=class extends ae{},o1=class extends ae{return_token_type_ids=!0},i1=class extends ae{},l1=class extends ae{},c1=class extends ae{},u1=class extends ae{},d1=class extends ae{},h1=class extends ae{},f1=class extends ae{},p1=class extends ae{},_1=class extends ae{return_token_type_ids=!0},m1=class extends ae{return_token_type_ids=!0},g1=class extends ae{return_token_type_ids=!0},w1=class extends ae{},v1=class extends ae{return_token_type_ids=!0},y1=class extends ae{},b1=class extends ae{},M1=class extends ae{},x1=class extends ae{},k1=class extends ae{},T1=class extends ae{return_token_type_ids=!0},E1=class extends ae{padding_side="left"},C1=class extends ae{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r.slice(2,-2)),this.lang_to_token=r=>`__${r}__`}_build_translation_inputs(e,t,r){return Ci(this,e,t,r)}},S1=class extends ae{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(r=>this.languageRegex.test(r)),he.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;const[t,...r]=e.trim().split(this.languageRegex);if(r.length===0)return super._encode_text(t);if(r.length===2){const[n,s]=r;return this.supported_language_codes.includes(n)||he.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),Nt([n],super._encode_text(s))}}},Ap=class extends ae{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r),this.lang_to_token=r=>r}_build_translation_inputs(e,t,r){return Ci(this,e,t,r)}},P1=class extends Ap{},A1=class extends ae{},F1=class extends ae{return_token_type_ids=!0},I1=class extends ae{},L1=class extends ae{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)),this.lang_to_token=r=>r}_build_translation_inputs(e,t,r){return Ci(this,e,t,r)}},O1=class extends ae{},N1=class extends ae{},D1=class extends ae{},B1=class extends ae{return_token_type_ids=!0},z1=class extends ae{},R1=class extends ae{},G1=class extends ae{return_token_type_ids=!0},$1=class extends ae{},V1=class extends Rt{decode_chain(e){let t="";for(let r=1;r<e.length;r+=2)t+=e[r];return[t]}},U1=class extends ae{constructor(e,t){super(e,t),this._tokenizer.decoder=new V1({type:"VitsDecoder"})}},W1=class extends ae{},Fp=[["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"]],$s=new Map(Fp),j1=new Map([...Fp.map(([e,t])=>[t,e]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function q1(e){e=e.toLowerCase();let t=j1.get(e);if(t===void 0){const r=e.match(/^<\|([a-z]{2})\|>$/);if(r&&(e=r[1]),$s.has(e))t=e;else{const s=e.length===2?$s.keys():$s.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(s))}`)}}return t}var H1="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Dh=new RegExp(`^[${H1}]+$`,"gu"),Q1=class extends ae{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:t=!1,return_language:r=!1,time_precision:n=null,force_full_sequences:s=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null;const o=t==="word";function i(){return{language:a,timestamp:[null,null],text:""}}const l=[];let u=i(),h=0;const f=this.timestamp_begin,g=f+1500;let v=[],w=[],M=!1,k=null;const T=new Set(this.all_special_ids);for(const F of e){const z=F.tokens,b=o?F.token_timestamps:null;let U=null,G=f;if("stride"in F){const[W,B,O]=F.stride;if(h-=B,k=W-O,B&&(G=B/n+f),O)for(let $=z.length-1;$>=0;--$){const ee=Number(z[$]);if(ee>=f){if(U!==null&&(ee-f)*n<k)break;U=ee}}}let H=[],Z=[];for(let W=0;W<z.length;++W){const B=Number(z[W]);if(T.has(B)){const O=this.decode([B]),$=$s.get(O.slice(2,-2));if($!==void 0){if(a!==null&&$!==a&&!t){v.push(H);const ee=this.findLongestCommonSequence(v)[0],X=this.decode(ee);u.text=X,l.push(u),v=[],H=[],u=i()}a=u.language=$}}else if(B>=f&&B<=g){const O=(B-f)*n+h,$=Is(O,2);if(U!==null&&B>=U)M=!0;else if(M||v.length>0&&B<G)M=!1;else if(u.timestamp[0]===null)u.timestamp[0]=$;else if($!==u.timestamp[0]){u.timestamp[1]=$,v.push(H),o&&w.push(Z);const[ee,X]=this.findLongestCommonSequence(v,w),A=this.decode(ee);u.text=A,o&&(u.words=this.collateWordTimestamps(ee,X,a)),l.push(u),v=[],H=[],w=[],Z=[],u=i()}}else if(H.push(B),o){let O=Is(b[W]+h,2),$;if(W+1<b.length){$=Is(b[W+1]+h,2);const ee=this.decode([B]);Dh.test(ee)&&($=Is(Math.min(O+n,$),2))}else $=null;Z.push([O,$])}}if("stride"in F){const[W,B,O]=F.stride;h+=W-O}H.length>0?(v.push(H),o&&w.push(Z)):v.every(W=>W.length===0)&&(u=i(),v=[],H=[],w=[],Z=[])}if(v.length>0){if(s&&t)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[F,z]=this.findLongestCommonSequence(v,w),b=this.decode(F);u.text=b,o&&(u.words=this.collateWordTimestamps(F,z,a)),l.push(u)}let S=Object.create(null);const E=l.map(F=>F.text).join("");if(t||r){for(let F=0;F<l.length;++F){const z=l[F];t||delete z.timestamp,r||delete z.language}if(o){const F=[];for(const z of l)for(const b of z.words)F.push(b);S={chunks:F}}else S={chunks:l}}return[E,S]}findLongestCommonSequence(e,t=null){let r=e[0],n=r.length,s=[];const a=Array.isArray(t)&&t.length>0;let o=a?[]:null,i=a?t[0]:null;for(let l=1;l<e.length;++l){const u=e[l];let h=0,f=[n,n,0,0];const p=u.length;for(let S=1;S<n+p;++S){const E=Math.max(0,n-S),F=Math.min(n,n+p-S),z=r.slice(E,F),b=Math.max(0,S-n),U=Math.min(p,S),G=u.slice(b,U);if(z.length!==G.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let H;a?H=z.filter((B,O)=>B===G[O]&&i[E+O]<=t[l][b+O]).length:H=z.filter((B,O)=>B===G[O]).length;const Z=S/1e4,W=H/S+Z;H>1&&W>h&&(h=W,f=[E,F,b,U])}const[g,v,w,M]=f,k=Math.floor((v+g)/2),T=Math.floor((M+w)/2);s.push(...r.slice(0,k)),r=u.slice(T),n=r.length,a&&(o.push(...i.slice(0,k)),i=t[l].slice(T))}return s.push(...r),a?(o.push(...i),[s,o]):[s,[]]}collateWordTimestamps(e,t,r){const[n,s,a]=this.combineTokensIntoWords(e,r),o=[];for(let i=0;i<n.length;++i){const l=a[i];o.push({text:n[i],timestamp:[t[l.at(0)][0],t[l.at(-1)][1]]})}return o}combineTokensIntoWords(e,t,r=`"'“¡¿([{-`,n=`"'.。,,!!??::”)]}、`){t=t??"english";let s,a,o;return["chinese","japanese","thai","lao","myanmar"].includes(t)?[s,a,o]=this.splitTokensOnUnicode(e):[s,a,o]=this.splitTokensOnSpaces(e),this.mergePunctuations(s,a,o,r,n)}decode(e,t){let r;return t?.decode_with_timestamps?(e instanceof q&&(e=Sp(e)),r=this.decodeWithTimestamps(e,t)):r=super.decode(e,t),r}decodeWithTimestamps(e,t){const r=t?.time_precision??.02,n=this.all_special_ids.at(-1)+1;let s=[[]];for(let a of e)if(a=Number(a),a>=n){const o=((a-n)*r).toFixed(2);s.push(`<|${o}|>`),s.push([])}else s[s.length-1].push(a);return s=s.map(a=>typeof a=="string"?a:super.decode(a,t)),s.join("")}splitTokensOnUnicode(e){const t=this.decode(e,{decode_with_timestamps:!0}),r="�",n=[],s=[],a=[];let o=[],i=[],l=0;for(let u=0;u<e.length;++u){const h=e[u];o.push(h),i.push(u);const f=this.decode(o,{decode_with_timestamps:!0});(!f.includes(r)||t[l+f.indexOf(r)]===r)&&(n.push(f),s.push(o),a.push(i),o=[],i=[],l+=f.length)}return[n,s,a]}splitTokensOnSpaces(e){const[t,r,n]=this.splitTokensOnUnicode(e),s=[],a=[],o=[];for(let i=0;i<t.length;++i){const l=t[i],u=r[i],h=n[i],f=u[0]>=this._tokenizer.token_to_id("<|endoftext|>"),p=l.startsWith(" "),g=l.trim(),v=Dh.test(g);if(f||p||v||s.length===0)s.push(l),a.push(u),o.push(h);else{const w=s.length-1;s[w]+=l,a[w].push(...u),o[w].push(...h)}}return[s,a,o]}mergePunctuations(e,t,r,n,s){const a=structuredClone(e),o=structuredClone(t),i=structuredClone(r);let l=a.length-2,u=a.length-1;for(;l>=0;)a[l].startsWith(" ")&&n.includes(a[l].trim())?(a[u]=a[l]+a[u],o[u]=Nt(o[l],o[u]),i[u]=Nt(i[l],i[u]),a[l]="",o[l]=[],i[l]=[]):u=l,--l;for(l=0,u=1;u<a.length;)!a[l].endsWith(" ")&&s.includes(a[u])?(a[l]+=a[u],o[l]=Nt(o[l],o[u]),i[l]=Nt(i[l],i[u]),a[u]="",o[u]=[],i[u]=[]):l=u,++u;return[a.filter(h=>h),o.filter(h=>h.length>0),i.filter(h=>h.length>0)]}},X1=class extends ae{},Y1=class extends ae{return_token_type_ids=!0;constructor(e,t){super(e,t),he.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},Ee=class{static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:n=null,local_files_only:s=!1,revision:a="main"}={}){const[o,i]=await Cp(e,{progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a}),l=i.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let u=Pp[l];return u||(he.warn(`Unknown tokenizer class "${l}", attempting to construct from base class.`),u=ae),new u(o,i)}},Si="https://github.com/huggingface/transformers.js/issues/new/choose",Pi="preprocessor_config.json",Ai=Pi,J1="processor_config.json",K1="chat_template.jinja",Oe=class extends $t{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,t,r){super(),this.config=e,this.components=t,this.chat_template=r}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,t={}){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,...t})}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,...t){for(const r of[this.image_processor,this.feature_extractor,this.tokenizer])if(r)return r(e,...t);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,t={}){const[r,n,s]=await Promise.all([this.uses_processor_config?ir(e,J1,!0,t):{},Promise.all(this.classes.filter(a=>a in this).map(async a=>{const o=await this[a].from_pretrained(e,t);return[a.replace(/_class$/,""),o]})).then(Object.fromEntries),this.uses_chat_template_file?lp(e,K1,!0,t):null]);return new this(r,n,s)}},Yo={};_n(Yo,{ChatterboxProcessor:()=>xk,Florence2Processor:()=>mT,Gemma3nProcessor:()=>gT,GroundingDinoProcessor:()=>vT,Idefics3Processor:()=>$h,JinaCLIPProcessor:()=>kT,LlavaProcessor:()=>TT,MgpstrProcessor:()=>ET,MoonshineProcessor:()=>CT,OwlViTProcessor:()=>ST,PaliGemmaProcessor:()=>AT,Phi3VProcessor:()=>IT,PixtralProcessor:()=>LT,Processor:()=>Oe,PyAnnoteProcessor:()=>OT,Qwen2VLProcessor:()=>r_,Qwen2_5_VLProcessor:()=>n_,Qwen3VLProcessor:()=>NT,Sam2Processor:()=>a_,Sam2VideoProcessor:()=>DT,SamProcessor:()=>s_,SmolVLMProcessor:()=>$h,SpeechT5Processor:()=>BT,UltravoxProcessor:()=>zT,VLChatProcessor:()=>xT,VoxtralProcessor:()=>VT,Wav2Vec2Processor:()=>UT,Wav2Vec2ProcessorWithLM:()=>WT,WhisperProcessor:()=>jT});var ft=class extends $t{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){const r=await ir(e,Pi,!0,t);return new this(r)}};function Pt(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw new Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var Fi={};_n(Fi,{ASTFeatureExtractor:()=>uk,ChatterboxFeatureExtractor:()=>dk,ClapFeatureExtractor:()=>hk,DacFeatureExtractor:()=>Np,EncodecFeatureExtractor:()=>Op,FeatureExtractor:()=>ft,Gemma3nAudioFeatureExtractor:()=>fk,MoonshineFeatureExtractor:()=>pk,ParakeetFeatureExtractor:()=>mk,PyAnnoteFeatureExtractor:()=>Dp,SeamlessM4TFeatureExtractor:()=>gk,SnacFeatureExtractor:()=>wk,SpeechT5FeatureExtractor:()=>vk,Wav2Vec2FeatureExtractor:()=>yk,WeSpeakerFeatureExtractor:()=>bk,WhisperFeatureExtractor:()=>Mk});var Z1=()=>{},ek=Z1;async function tk(e,t){if(Ae.IS_BROWSER_ENV){if(Ae.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");const r=URL.createObjectURL(t),n=document.createElement("a");n.href=r,n.download=e,n.click(),n.remove(),URL.revokeObjectURL(r)}else if(Ae.IS_FS_AVAILABLE)t.stream(),kt.createWriteStream(e),await ek();else throw new Error("Unable to save because filesystem is disabled in this environment.")}function Ip(e,t){if(e<1)return new Float64Array;if(e===1)return new Float64Array([1]);const r=1-t,n=2*Math.PI/(e-1),s=new Float64Array(e);for(let a=0;a<e;++a)s[a]=t-r*Math.cos(a*n);return s}function Bh(e){return Ip(e,.5)}function rk(e){return Ip(e,.54)}var nk={htk:e=>2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,r=15,n=27/Math.log(6.4))=>e>=t?r+Math.log(e/t)*n:3*e/200};function Do(e,t="htk"){const r=nk[t];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e=="number"?r(e):e.map(n=>r(n))}var sk={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,r=15,n=Math.log(6.4)/27)=>e>=r?t*Math.exp(n*(e-r)):200*e/3};function ak(e,t="htk"){const r=sk[t];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e=="number"?r(e):e.map(n=>r(n))}function ok(e,t){const r=Float64Array.from({length:t.length-1},(o,i)=>t[i+1]-t[i]),n=Array.from({length:e.length},()=>new Array(t.length));for(let o=0;o<e.length;++o){const i=n[o];for(let l=0;l<t.length;++l)i[l]=t[l]-e[o]}const s=t.length-2,a=Array.from({length:s},()=>new Array(e.length));for(let o=0;o<e.length;++o){const i=n[o];for(let l=0;l<s;++l){const u=-i[l]/r[l],h=i[l+2]/r[l+1];a[l][o]=Math.max(0,Math.min(u,h))}}return a}function zh(e,t,r){const n=(t-e)/(r-1);return Float64Array.from({length:r},(s,a)=>e+n*a)}function br(e,t,r,n,s,a=null,o="htk",i=!1){if(a!==null&&a!=="slaney")throw new Error('norm must be one of null or "slaney"');if(e<2)throw new Error(`Require num_frequency_bins: ${e} >= 2`);if(r>n)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${n}`);const l=Do(r,o),u=Do(n,o),h=zh(l,u,t+2);let f=ak(h,o),p;if(i){const v=s/((e-1)*2);p=Do(Float64Array.from({length:e},(w,M)=>M*v),o),f=h}else p=zh(0,Math.floor(s/2),e);const g=ok(p,f);if(a!==null&&a==="slaney")for(let v=0;v<t;++v){const w=g[v],M=2/(f[v+2]-f[v]);for(let k=0;k<e;++k)w[k]*=M}return g}function ik(e,t,r){const n=new e.constructor(e.length+t+r),s=e.length-1;for(let a=0;a<e.length;++a)n[t+a]=e[a];for(let a=1;a<=t;++a)n[t-a]=e[Xs(a,s)];for(let a=1;a<=r;++a)n[s+t+a]=e[Xs(s-a,s)];return n}function Lp(e,t,r,n,s){if(r<=0)throw new Error("reference must be greater than zero");if(n<=0)throw new Error("min_value must be greater than zero");r=Math.max(n,r);const a=Math.log10(r);for(let o=0;o<e.length;++o)e[o]=t*Math.log10(Math.max(n,e[o])-a);if(s!==null){if(s<=0)throw new Error("db_range must be greater than zero");const o=He(e)[0]-s;for(let i=0;i<e.length;++i)e[i]=Math.max(e[i],o)}return e}function lk(e,t=1,r=1e-5,n=null){return Lp(e,20,t,r,n)}function ck(e,t=1,r=1e-10,n=null){return Lp(e,10,t,r,n)}async function Vr(e,t,r,n,{fft_length:s=null,power:a=1,center:o=!0,pad_mode:i="reflect",onesided:l=!0,preemphasis:u=null,preemphasis_htk_flavor:h=!0,mel_filters:f=null,mel_floor:p=1e-10,log_mel:g=null,reference:v=1,min_value:w=1e-10,db_range:M=null,remove_dc_offset:k=null,min_num_frames:T=null,max_num_frames:S=null,do_pad:E=!0,transpose:F=!1,mel_offset:z=0}={}){const b=t.length;if(s===null&&(s=r),r>s)throw Error(`frame_length (${r}) may not be larger than fft_length (${s})`);if(b!==r)throw new Error(`Length of the window (${b}) must equal frame_length (${r})`);if(n<=0)throw new Error("hop_length must be greater than zero");if(a===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(!h)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(o)switch(i){case"reflect":{const L=Math.floor((s-1)/2)+1;e=ik(e,L,L);break}case"constant":{const L=Math.floor(s/2),D=new e.constructor(e.length+2*L);D.set(e,L),e=D;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}let U=Math.floor(1+Math.floor((e.length-r)/n));T!==null&&U<T&&(U=T);const G=l?Math.floor(s/2)+1:s;let H=U,Z=U;S!==null&&(S>U?E&&(Z=S):Z=H=S);const W=new Ax(s),B=new Float64Array(s),O=new Float64Array(W.outputBufferSize),$=new Float32Array(G*Z);for(let L=0;L<H;++L){const D=L*n,J=Math.min(e.length-D,r);J!==r&&B.fill(0,0,r);for(let ie=0;ie<J;++ie)B[ie]=e[D+ie];if(k){let ie=0;for(let Fe=0;Fe<J;++Fe)ie+=B[Fe];const xe=ie/J;for(let Fe=0;Fe<J;++Fe)B[Fe]-=xe}if(u!==null){for(let ie=J-1;ie>=1;--ie)B[ie]-=u*B[ie-1];B[0]*=1-u}for(let ie=0;ie<t.length;++ie)B[ie]*=t[ie];W.realTransform(O,B);for(let ie=0;ie<G;++ie){const xe=ie<<1;$[ie*Z+L]=O[xe]**2+O[xe+1]**2}}if(a!==null&&a!==2){const L=a/2;for(let D=0;D<$.length;++D)$[D]**=L}const ee=f.length;let X=await Yx(new q("float32",f.flat(),[ee,G]),new q("float32",$,[G,Z]));F&&(X=X.transpose(1,0));const A=X.data;for(let L=0;L<A.length;++L)A[L]=z+Math.max(p,A[L]);if(a!==null&&g!==null){const L=Math.min(A.length,H*ee);switch(g){case"log":for(let D=0;D<L;++D)A[D]=Math.log(A[D]);break;case"log10":for(let D=0;D<L;++D)A[D]=Math.log10(A[D]);break;case"dB":if(a===1)lk(A,v,w,M);else if(a===2)ck(A,v,w,M);else throw new Error(`Cannot use log_mel option '${g}' with power ${a}`);break;default:throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${g}'`)}}return X}function Ur(e,t,{periodic:r=!0,frame_length:n=null,center:s=!0}={}){const a=r?e+1:e;let o;switch(t){case"boxcar":o=new Float64Array(a).fill(1);break;case"hann":case"hann_window":o=Bh(a);break;case"hamming":o=rk(a);break;case"povey":o=Bh(a).map(i=>Math.pow(i,.85));break;default:throw new Error(`Unknown window type ${t}.`)}if(r&&(o=o.subarray(0,e)),n===null)return o;if(e>n)throw new Error(`Length of the window (${e}) may not be larger than frame_length (${n})`);return o}var uk=class extends ft{constructor(e){super(e);const t=this.config.sampling_rate,r=br(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=Ur(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return Vr(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:t,transpose:!0})}async _call(e){Pt(e,"ASTFeatureExtractor");const t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){const r=this.std*2,n=t.data;for(let s=0;s<n.length;++s)n[s]=(n[s]-this.mean)/r}return{input_values:t.unsqueeze_(0)}}},Op=class extends ft{async _call(e){Pt(e,"EncodecFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=this.config.feature_size;if(e.length%t!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${t}).`);const r=[1,t,e.length/t];return{input_values:new q("float32",e,r)}}},dk=class extends ft{async _call(e){Pt(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,e.length];return{input_values:new q("float32",e,t)}}},hk=class extends ft{constructor(e){super(e),this.mel_filters=br(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=br(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=Ur(this.config.fft_window_size,"hann")}async _get_input_mel(e,t,r,n){let s;const a=e.length-t;if(a>0)if(r==="rand_trunc"){const o=Math.floor(ki.random()*(a+1));e=e.subarray(o,o+t),s=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${r}" not implemented`);else{if(a<0){let o=new Float64Array(t);if(o.set(e),n==="repeat")for(let i=e.length;i<t;i+=e.length)o.set(e.subarray(0,Math.min(e.length,t-i)),i);else if(n==="repeatpad")for(let i=e.length;i<-a;i+=e.length)o.set(e,i);e=o}if(r==="fusion")throw new Error(`Truncation strategy "${r}" not implemented`);s=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return s.unsqueeze_(0)}async _extract_fbank_features(e,t,r=null){return Vr(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:t,log_mel:"dB",max_num_frames:r,do_pad:!1,transpose:!0})}async _call(e,{max_length:t=null}={}){return Pt(e,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(e,t??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}},Np=class extends Op{},fk=class extends ft{constructor(e){super(e);const{fft_length:t,feature_size:r,min_frequency:n,max_frequency:s,sampling_rate:a,frame_length:o}=this.config,i=br(Math.floor(1+t/2),r,n,s,a,null,"htk",!1);this.mel_filters=i,this.window=Ur(o,"hann")}async _extract_fbank_features(e,t){return Vr(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:t=48e4,truncation:r=!0,padding:n=!0,pad_to_multiple_of:s=128}={}){if(Pt(e,"Gemma3nAudioFeatureExtractor"),r&&e.length>t&&(e=e.slice(0,t)),n&&e.length%s!==0){const i=s-e.length%s,l=new Float64Array(e.length+i);l.set(e),this.config.padding_value!==0&&l.fill(this.config.padding_value,e.length),e=l}const a=await this._extract_fbank_features(e,this.config.max_length),o=at([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:o}}},pk=class extends ft{async _call(e){Pt(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,e.length];return{input_values:new q("float32",e,t)}}},_k=1e-5,mk=class extends ft{constructor(e){super(e),this.config.mel_filters??=br(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,"slaney","slaney");const t=Ur(this.config.win_length,"hann",{periodic:!1});this.window=new Float64Array(this.config.n_fft);const r=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(t,r)}async _extract_fbank_features(e){const t=this.config.preemphasis;e=new Float64Array(e);for(let n=e.length-1;n>=1;--n)e[n]-=t*e[n-1];return await Vr(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){Pt(e,"ParakeetFeatureExtractor");const t=await this._extract_fbank_features(e),r=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),n=t.data;n.fill(0,r*t.dims[1]);const[s,a]=t.dims,o=new Float64Array(a),i=new Float64Array(a);for(let h=0;h<r;++h){const f=h*a;for(let p=0;p<a;++p){const g=n[f+p];o[p]+=g,i[p]+=g*g}}const l=r>1?r-1:1;for(let h=0;h<a;++h){const f=o[h]/r,p=(i[h]-r*f*f)/l,v=1/(Math.sqrt(p)+_k);for(let w=0;w<r;++w){const M=w*a+h;n[M]=(n[M]-f)*v}}const u=new BigInt64Array(s);return u.fill(1n,0,r),{input_features:t.unsqueeze_(0),attention_mask:new q("int64",u,[1,s])}}},Dp=class extends ft{async _call(e){Pt(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,1,e.length];return{input_values:new q("float32",e,t)}}samples_to_frames(e){return(e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,t){const r=t/this.samples_to_frames(t)/this.config.sampling_rate,n=[];for(const s of e.tolist()){const a=[];let o=-1;for(let i=0;i<s.length;++i){const l=wn(s[i]),[u,h]=He(l),[f,p]=[i,i+1];h!==o?(o=h,a.push({id:h,start:f,end:p,score:u})):(a.at(-1).end=p,a.at(-1).score+=u)}n.push(a.map(({id:i,start:l,end:u,score:h})=>({id:i,start:l*r,end:u*r,confidence:h/(u-l)})))}return n}},gk=class extends ft{constructor(e){super(e);const t=this.config.sampling_rate,r=br(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=Ur(400,"povey",{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(r=>r*32768),Vr(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:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:r=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:s=!0}={}){Pt(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){const[g,v]=a.dims,w=a.data;for(let M=0;M<v;++M){let k=0;for(let F=0;F<g;++F)k+=w[F*v+M];const T=k/g;let S=0;for(let F=0;F<g;++F)S+=(w[F*v+M]-T)**2;S/=g-1;const E=Math.sqrt(S+1e-7);for(let F=0;F<g;++F){const z=F*v+M;w[z]=(w[z]-T)/E}}}let o;if(t){const[g,v]=a.dims,w=a.data,M=g%r;if(M>0){const k=new Float32Array(v*(g+M));k.set(w),k.fill(this.config.padding_value,w.length);const T=g+M;a=new q(a.type,k,[T,v]),s&&(o=new q("int64",new BigInt64Array(T),[1,T]),o.data.fill(1n,0,g))}}const[i,l]=a.dims,u=this.config.stride;if(i%u!==0)throw new Error(`The number of frames (${i}) must be a multiple of the stride (${u}).`);const f=a.view(1,Math.floor(i/u),l*u),p={input_features:f};if(s){const g=f.dims[1],v=new BigInt64Array(g);if(o){const w=o.data;for(let M=1,k=0;M<i;M+=u,++k)v[k]=w[M]}else v.fill(1n);p.attention_mask=new q("int64",v,[1,g])}return p}},wk=class extends Np{},vk=class extends ft{},yk=class extends ft{_zero_mean_unit_var_norm(e){const r=e.reduce((s,a)=>s+a,0)/e.length,n=e.reduce((s,a)=>s+(a-r)**2,0)/e.length;return e.map(s=>(s-r)/Math.sqrt(n+1e-7))}async _call(e){Pt(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));const r=[1,t.length];return{input_values:new q("float32",t,r),attention_mask:new q("int64",new BigInt64Array(t.length).fill(1n),r)}}},bk=class extends ft{constructor(e){super(e);const t=this.config.sampling_rate,r=br(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=Ur(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(t=>t*32768),Vr(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){Pt(e,"WeSpeakerFeatureExtractor");const t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const r=t.mean(1).data,n=t.data,[s,a,o]=t.dims;for(let i=0;i<s;++i){const l=i*a*o,u=i*o;for(let h=0;h<a;++h){const f=l+h*o;for(let p=0;p<o;++p)n[f+p]-=r[u+p]}}}return{input_features:t}}},Mk=class extends ft{constructor(e){super(e),this.config.mel_filters??=br(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=Ur(this.config.n_fft,"hann")}async _extract_fbank_features(e){const t=await Vr(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)}),r=t.data,n=He(r)[0];for(let s=0;s<r.length;++s)r[s]=(Math.max(r[s],n-8)+4)/4;return t}async _call(e,{max_length:t=null}={}){Pt(e,"WhisperFeatureExtractor");let r;const n=t??this.config.n_samples;return e.length>n?(e.length>this.config.n_samples&&he.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`."),r=e.slice(0,n)):(r=new Float32Array(n),r.set(e)),{input_features:(await this._extract_fbank_features(r)).unsqueeze_(0)}}},lr=class{static async from_pretrained(e,t={}){const r=await ir(e,Pi,!0,t),n=r.feature_extractor_type,s=Fi[n];if(!s)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${Si}.`);return new s(r)}},xk=class extends Oe{static tokenizer_class=Ee;static feature_extractor_class=lr;async _call(e,t=null){const r=this.tokenizer(e),n=t?await this.feature_extractor(t):{};return{...r,...n}}},Jo={},Fr,Bp,wr,It=Ae.IS_BROWSER_ENV||Ae.IS_WEBWORKER_ENV;if(It)Fr=(e,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(e,t)},wr=self.createImageBitmap,Bp=self.ImageData;else if(Jo)wr=async e=>{const r=(await e.metadata()).channels,{data:n,info:s}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),a=new Rr(new Uint8ClampedArray(n),s.width,s.height,s.channels);return r!==void 0&&r!==s.channels&&a.convert(r),a};else throw new Error("Unable to load image processing library.");var kk={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},Tk=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Rr=class qt{constructor(t,r,n,s){this.data=t,this.width=r,this.height=n,this.channels=s}get size(){return[this.width,this.height]}static async read(t){if(t instanceof qt)return t;if(typeof t=="string"||t instanceof URL)return await this.fromURL(t);if(t instanceof Blob)return await this.fromBlob(t);if(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)return this.fromCanvas(t);throw new Error(`Unsupported input type: ${typeof t}`)}static fromCanvas(t){if(!It)throw new Error("fromCanvas() is only supported in browser environments.");const n=t.getContext("2d").getImageData(0,0,t.width,t.height).data;return new qt(n,t.width,t.height,4)}static async fromURL(t){const r=await Ks(t);if(r.status!==200)throw new Error(`Unable to read image from "${t}" (${r.status} ${r.statusText})`);const n=await r.blob();return this.fromBlob(n)}static async fromBlob(t){if(It){const r=await wr(t),n=Fr(r.width,r.height).getContext("2d");return n.drawImage(r,0,0),new this(n.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{const r=Jo(await t.arrayBuffer());return await wr(r)}}static fromTensor(t,r="CHW"){if(t.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${t.dims.length} dimensions.`);if(r==="CHW")t=t.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${t.type}`);switch(t.dims[2]){case 1:case 2:case 3:case 4:return new qt(t.data,t.dims[1],t.dims[0],t.dims[2]);default:throw new Error(`Unsupported number of channels: ${t.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const t=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,n=0;r<this.data.length;r+=this.channels){const s=this.data[r],a=this.data[r+1],o=this.data[r+2];t[n++]=Math.round(.2989*s+.587*a+.114*o)}break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,1)}rgb(){if(this.channels===3)return this;const t=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let r=0,n=0;r<this.data.length;++r)t[n++]=this.data[r],t[n++]=this.data[r],t[n++]=this.data[r];break;case 4:for(let r=0,n=0;r<this.data.length;r+=4)t[n++]=this.data[r],t[n++]=this.data[r+1],t[n++]=this.data[r+2];break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,3)}rgba(){if(this.channels===4)return this;const t=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let r=0,n=0;r<this.data.length;++r)t[n++]=this.data[r],t[n++]=this.data[r],t[n++]=this.data[r],t[n++]=255;break;case 3:for(let r=0,n=0;r<this.data.length;r+=3)t[n++]=this.data[r],t[n++]=this.data[r+1],t[n++]=this.data[r+2],t[n++]=255;break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,4)}putAlpha(t){if(t.width!==this.width||t.height!==this.height)throw new Error(`Expected mask size to be ${this.width}x${this.height}, but got ${t.width}x${t.height}`);if(t.channels!==1)throw new Error(`Expected mask to have 1 channel, but got ${t.channels}`);const r=this.data,n=t.data,s=this.width*this.height;if(this.channels===3){const a=new Uint8ClampedArray(s*4);for(let o=0,i=0,l=0;o<s;++o)a[l++]=r[i++],a[l++]=r[i++],a[l++]=r[i++],a[l++]=n[o];return this._update(a,this.width,this.height,4)}else if(this.channels===4){for(let a=0;a<s;++a)r[4*a+3]=n[a];return this}throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(t,r,{resample:n=2}={}){if(this.width===t&&this.height===r)return this;let s=kk[n]??n;const a=ah(t),o=ah(r);if(a&&o)return this;if(a?t=r/this.height*this.width:o&&(r=t/this.width*this.height),It){const i=this.channels,l=this.toCanvas(),u=Fr(t,r).getContext("2d");return u.drawImage(l,0,0,t,r),new qt(u.getImageData(0,0,t,r).data,t,r,4).convert(i)}else{let i=this.toSharp();switch(s){case"box":case"hamming":(s==="box"||s==="hamming")&&(he.warn(`Resampling method ${s} is not yet supported. Using bilinear instead.`),s="bilinear");case"nearest":case"bilinear":case"bicubic":i=i.affine([t/this.width,0,0,r/this.height],{interpolator:s});break;case"lanczos":i=i.resize({width:t,height:r,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${s} is not supported.`)}return await wr(i)}}async pad([t,r,n,s]){if(t=Math.max(t,0),r=Math.max(r,0),n=Math.max(n,0),s=Math.max(s,0),t===0&&r===0&&n===0&&s===0)return this;if(It){const a=this.channels,o=this.toCanvas(),i=this.width+t+r,l=this.height+n+s,u=Fr(i,l).getContext("2d");return u.drawImage(o,0,0,this.width,this.height,t,n,this.width,this.height),new qt(u.getImageData(0,0,i,l).data,i,l,4).convert(a)}else{const a=this.toSharp().extend({left:t,right:r,top:n,bottom:s});return await wr(a)}}async crop([t,r,n,s]){if(t=Math.max(t,0),r=Math.max(r,0),n=Math.min(n,this.width-1),s=Math.min(s,this.height-1),t===0&&r===0&&n===this.width-1&&s===this.height-1)return this;const a=n-t+1,o=s-r+1;if(It){const i=this.channels,l=this.toCanvas(),u=Fr(a,o).getContext("2d");return u.drawImage(l,t,r,a,o,0,0,a,o),new qt(u.getImageData(0,0,a,o).data,a,o,4).convert(i)}else{const i=this.toSharp().extract({left:t,top:r,width:a,height:o});return await wr(i)}}async center_crop(t,r){if(this.width===t&&this.height===r)return this;const n=(this.width-t)/2,s=(this.height-r)/2;if(It){const a=this.channels,o=this.toCanvas(),i=Fr(t,r).getContext("2d");let l=0,u=0,h=0,f=0;return n>=0?l=n:h=-n,s>=0?u=s:f=-s,i.drawImage(o,l,u,t,r,h,f,t,r),new qt(i.getImageData(0,0,t,r).data,t,r,4).convert(a)}else{let a=this.toSharp();if(n>=0&&s>=0)a=a.extract({left:Math.floor(n),top:Math.floor(s),width:t,height:r});else if(n<=0&&s<=0){const o=Math.floor(-s),i=Math.floor(-n);a=a.extend({top:o,left:i,right:t-this.width-i,bottom:r-this.height-o})}else{let o=[0,0],i=0;s<0?(o[0]=Math.floor(-s),o[1]=r-this.height-o[0]):i=Math.floor(s);let l=[0,0],u=0;n<0?(l[0]=Math.floor(-n),l[1]=t-this.width-l[0]):u=Math.floor(n),a=a.extend({top:o[0],bottom:o[1],left:l[0],right:l[1]}).extract({left:u,top:i,width:t,height:r})}return await wr(a)}}async toBlob(t="image/png",r=1){if(!It)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:t,quality:r})}toTensor(t="CHW"){let r=new q("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(t!=="HWC")if(t==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${t}`);return r}toCanvas(){if(!It)throw new Error("toCanvas() is only supported in browser environments.");const t=this.clone().rgba(),r=Fr(t.width,t.height),n=new Bp(t.data,t.width,t.height);return r.getContext("2d").putImageData(n,0,0),r}split(){const{data:t,width:r,height:n,channels:s}=this,a=t.constructor,o=t.length/s,i=Array.from({length:s},()=>new a(o));for(let l=0;l<o;++l){const u=s*l;for(let h=0;h<s;++h)i[h][l]=t[u+h]}return i.map(l=>new qt(l,r,n,1))}_update(t,r,n,s=null){return this.data=t,this.width=r,this.height=n,s!==null&&(this.channels=s),this}clone(){return new qt(this.data.slice(),this.width,this.height,this.channels)}convert(t){if(this.channels===t)return this;switch(t){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(t){if(It){if(Ae.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const r=t.split(".").pop().toLowerCase(),n=Tk.get(r)??"image/png",s=await this.toBlob(n);return tk(t,s)}else if(Ae.IS_FS_AVAILABLE)await this.toSharp().toFile(t);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(It)throw new Error("toSharp() is only supported in server-side environments.");return Jo(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}};Rr.read.bind(Rr);function Rh(e,t,r=0,n=null){const s=e/t;let a=Ix(s)*t;return n!==null&&a>n&&(a=Math.floor(s)*t),a<r&&(a=Math.ceil(s)*t),a}function Bo([e,t],r){return[Math.max(Math.floor(e/r),1)*r,Math.max(Math.floor(t/r),1)*r]}function zp([e,t,r,n]){return[e-r/2,t-n/2,e+r/2,t+n/2]}function fa(e,t=.5,r=null,n=!1){const s=e.logits,a=e.pred_boxes,[o,i,l]=s.dims;if(r!==null&&r.length!==o)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let u=[];for(let h=0;h<o;++h){let f=r!==null?r[h]:null,p={boxes:[],classes:[],scores:[]},g=s[h],v=a[h];for(let w=0;w<i;++w){let M=g[w],k=[],T;if(n){T=M.sigmoid().data;for(let S=0;S<T.length;++S)T[S]>t&&k.push(S)}else{let S=He(M.data)[1];if(S===l-1||(T=wn(M.data),T[S]<t))continue;k.push(S)}for(const S of k){let E=v[w].data;E=zp(E),f!==null&&(E=E.map((F,z)=>F*f[(z+1)%2])),p.boxes.push(E),p.classes.push(S),p.scores.push(T[S])}}u.push(p)}return u}function Rp(e,t=null){const r=e.logits,n=r.dims[0];if(t!==null&&t.length!==n)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const s=[];for(let a=0;a<n;++a){const o=t!==null?t[a]:null;let i=r[a];o!==null&&(i=bp(i,o,"bilinear",!1));const[l,u]=o??i.dims.slice(-2),h=new q("int32",new Int32Array(l*u),[l,u]),f=i[0].data,p=h.data;for(let w=1;w<i.dims[0];++w){const M=i[w].data;for(let k=0;k<M.length;++k)M[k]>f[k]&&(f[k]=M[k],p[k]=w)}const g=new Array(i.dims[0]);for(let w=0;w<p.length;++w){const M=p[w];g[M]=M}const v=g.filter(w=>w!==void 0);s.push({segmentation:h,labels:v})}return s}function Ek(e,t,r,n){const s=[],a=[],o=[];for(let i=0;i<e.dims[0];++i){const l=e[i],u=t[i],h=He(l.data)[1];if(h===n)continue;const p=wn(l.data)[h];p>r&&(s.push(u),a.push(p),o.push(h))}return[s,a,o]}function Ck(e,t,r,n=.5,s=.8){const a=[];let o=0,i=0;const l=t[r].data;for(let h=0;h<e.length;++h)e[h]===r&&(a.push(h),++o),l[h]>=n&&++i;let u=o>0&&i>0;return u&&(u=o/i>s),[u,a]}function Sk(e,t,r,n,s,a=null,o=null){const[i,l]=o??e[0].dims,u=new q("int32",new Int32Array(i*l),[i,l]),h=[];if(o!==null)for(let w=0;w<e.length;++w)e[w]=bp(e[w],o,"bilinear",!1);const f=new Int32Array(e[0].data.length),p=new Float32Array(e[0].data.length);for(let w=0;w<e.length;++w){let M=t[w];const k=e[w].data;for(let T=0;T<k.length;++T)k[T]*=M,k[T]>p[T]&&(f[T]=w,p[T]=k[T])}let g=0;const v=u.data;for(let w=0;w<r.length;++w){const M=r[w],[k,T]=Ck(f,e,w,n,s);if(k){++g;for(const S of T)v[S]=g;h.push({id:g,label_id:M,score:t[w]})}}return[u,h]}function Gp(e,t=.5,r=.5,n=.8,s=null,a=null){s===null&&(he.warn("`label_ids_to_fuse` unset. No instance will be fused."),s=new Set);const o=e.class_queries_logits??e.logits,l=(e.masks_queries_logits??e.pred_masks).sigmoid();let[u,h,f]=o.dims;if(f-=1,a!==null&&a.length!==u)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let p=[];for(let g=0;g<u;++g){let v=a!==null?a[g]:null,w=o[g],M=l[g],[k,T,S]=Ek(w,M,t,f);if(S.length===0){let[z,b]=v??M.dims.slice(-2),U=new q("int32",new Int32Array(z*b).fill(-1),[z,b]);p.push({segmentation:U,segments_info:[]});continue}let[E,F]=Sk(k,T,S,r,n,s,v);p.push({segmentation:E,segments_info:F})}return p}function $p(e,t=.5,r=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}var le=class extends $t{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,t,r=2){const n=e.height,s=e.width,a=t.height,o=t.width;let i=Math.min(n,a),l=Math.min(s,o);return i===n&&l===s?e:(n>s?l=Math.floor(s*i/n):s>n&&(i=Math.floor(n*l/s)),await e.resize(l,i,{resample:r}))}async crop_margin(e,t=200){const r=e.clone().grayscale(),n=Ho(r.data)[0],a=He(r.data)[0]-n;if(a===0)return e;const o=t/255;let i=r.width,l=r.height,u=0,h=0;const f=r.data;for(let p=0;p<r.height;++p){const g=p*r.width;for(let v=0;v<r.width;++v)(f[g+v]-n)/a<o&&(i=Math.min(i,v),l=Math.min(l,p),u=Math.max(u,v),h=Math.max(h,p))}return e=await e.crop([i,l,u,h]),e}pad_image(e,t,r,{mode:n="constant",center:s=!1,constant_values:a=0}={}){const[o,i,l]=t;let u,h;if(typeof r=="number"?(u=r,h=r):r==="square"?u=h=Math.max(o,i):(u=r.width,h=r.height),u!==i||h!==o){const f=new Float32Array(u*h*l);if(Array.isArray(a))for(let v=0;v<f.length;++v)f[v]=a[v%l];else a!==0&&f.fill(a);const[p,g]=s?[Math.floor((u-i)/2),Math.floor((h-o)/2)]:[0,0];for(let v=0;v<o;++v){const w=(v+g)*u,M=v*i;for(let k=0;k<i;++k){const T=(w+k+p)*l,S=(M+k)*l;for(let E=0;E<l;++E)f[T+E]=e[S+E]}}if(n==="symmetric"){if(s)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");const v=o-1,w=i-1;for(let M=0;M<h;++M){const k=M*u,T=Xs(M,v)*i;for(let S=0;S<u;++S){if(M<o&&S<i)continue;const E=(k+S)*l,F=(T+Xs(S,w))*l;for(let z=0;z<l;++z)f[E+z]=e[F+z]}}}e=f,t=[h,u,l]}return[e,t]}rescale(e){for(let t=0;t<e.length;++t)e[t]=this.rescale_factor*e[t]}get_resize_output_image_size(e,t){const[r,n]=e.size;let s,a;if(this.do_thumbnail){const{height:o,width:i}=t;s=Math.min(o,i)}else Number.isInteger(t)?(s=t,a=this.config.max_size??s):t!==void 0&&(s=t.shortest_edge,a=t.longest_edge);if(s!==void 0||a!==void 0){const o=s===void 0?1:Math.max(s/r,s/n),i=r*o,l=n*o,u=a===void 0?1:Math.min(a/i,a/l);let h=Math.floor(Number((i*u).toFixed(2))),f=Math.floor(Number((l*u).toFixed(2)));return this.size_divisibility!==void 0&&([h,f]=Bo([h,f],this.size_divisibility)),[h,f]}else if(t!==void 0&&t.width!==void 0&&t.height!==void 0){let o=t.width,i=t.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let l=i/n,u=o/r;Math.abs(1-u)<Math.abs(1-l)?l=u:u=l,i=Rh(l*n,this.config.ensure_multiple_of),o=Rh(u*r,this.config.ensure_multiple_of)}return[o,i]}else{if(this.size_divisibility!==void 0)return Bo([r,n],this.size_divisibility);throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(t)}`)}}async resize(e){const[t,r]=this.get_resize_output_image_size(e,this.size);return await e.resize(t,r,{resample:this.resample})}async preprocess(e,{do_normalize:t=null,do_pad:r=null,do_convert_rgb:n=null,do_convert_grayscale:s=null,do_flip_channel_order:a=null}={}){this.do_crop_margin&&(e=await this.crop_margin(e));const[o,i]=e.size;if(n??this.do_convert_rgb?e=e.rgb():s&&(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 p,g;Number.isInteger(this.crop_size)?(p=this.crop_size,g=this.crop_size):(p=this.crop_size.width,g=this.crop_size.height),e=await e.center_crop(p,g)}const l=[e.height,e.width];let u=Float32Array.from(e.data),h=[e.height,e.width,e.channels];if(this.do_rescale&&this.rescale(u),t??this.do_normalize){let p=this.image_mean;Array.isArray(this.image_mean)||(p=new Array(e.channels).fill(p));let g=this.image_std;if(Array.isArray(this.image_std)||(g=new Array(e.channels).fill(g)),p.length!==e.channels||g.length!==e.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${p.length}) and \`image_std\` (${g.length}) must match the number of channels in the image (${e.channels}).`);for(let v=0;v<u.length;v+=e.channels)for(let w=0;w<e.channels;++w)u[v+w]=(u[v+w]-p[w])/g[w]}if(r??this.do_pad){if(this.pad_size)[u,h]=this.pad_image(u,[e.height,e.width,e.channels],this.pad_size);else if(this.size_divisibility){const[p,g]=Bo([h[1],h[0]],this.size_divisibility);[u,h]=this.pad_image(u,h,{width:p,height:g})}}if(a??this.do_flip_channel_order){if(h[2]!==3)throw new Error("Flipping channel order is only supported for RGB images.");for(let p=0;p<u.length;p+=3){const g=u[p];u[p]=u[p+2],u[p+2]=g}}const f=new q("float32",u,h).permute(2,0,1);return{original_size:[i,o],reshaped_input_size:l,pixel_values:f}}async _call(e,...t){Array.isArray(e)||(e=[e]);const r=await Promise.all(e.map(s=>this.preprocess(s)));return{pixel_values:vn(r.map(s=>s.pixel_values),0),original_sizes:r.map(s=>s.original_size),reshaped_input_sizes:r.map(s=>s.reshaped_input_size)}}static async from_pretrained(e,t={}){const r=await ir(e,Ai,!0,t);return new this(r)}},ta={};_n(ta,{BeitFeatureExtractor:()=>Pk,BitImageProcessor:()=>Ak,CLIPFeatureExtractor:()=>Ik,CLIPImageProcessor:()=>Vp,ChineseCLIPFeatureExtractor:()=>Fk,ConvNextFeatureExtractor:()=>Lk,ConvNextImageProcessor:()=>Up,DINOv3ViTImageProcessor:()=>Dk,DPTFeatureExtractor:()=>zk,DPTImageProcessor:()=>qp,DeiTFeatureExtractor:()=>Ok,DeiTImageProcessor:()=>Wp,DetrFeatureExtractor:()=>Nk,DetrImageProcessor:()=>jp,DonutFeatureExtractor:()=>Bk,DonutImageProcessor:()=>Ii,EfficientNetImageProcessor:()=>Rk,GLPNFeatureExtractor:()=>Gk,GroundingDinoImageProcessor:()=>$k,Idefics3ImageProcessor:()=>Gh,ImageFeatureExtractor:()=>le,ImageProcessor:()=>le,JinaCLIPImageProcessor:()=>Uk,LlavaOnevisionImageProcessor:()=>Wk,Mask2FormerImageProcessor:()=>qk,MaskFormerFeatureExtractor:()=>jk,MaskFormerImageProcessor:()=>Li,MobileNetV1FeatureExtractor:()=>Hk,MobileNetV1ImageProcessor:()=>Hp,MobileNetV2FeatureExtractor:()=>Qk,MobileNetV2ImageProcessor:()=>Qp,MobileNetV3FeatureExtractor:()=>Xk,MobileNetV3ImageProcessor:()=>Xp,MobileNetV4FeatureExtractor:()=>Yk,MobileNetV4ImageProcessor:()=>Yp,MobileViTFeatureExtractor:()=>Jk,MobileViTImageProcessor:()=>Jp,NougatImageProcessor:()=>Kk,OwlViTFeatureExtractor:()=>Zk,OwlViTImageProcessor:()=>Oi,Owlv2ImageProcessor:()=>eT,Phi3VImageProcessor:()=>rT,PixtralImageProcessor:()=>nT,PvtImageProcessor:()=>sT,Qwen2VLImageProcessor:()=>oT,RTDetrImageProcessor:()=>iT,Sam2ImageProcessor:()=>Go,Sam3ImageProcessor:()=>Go,SamImageProcessor:()=>Go,SapiensFeatureExtractor:()=>lT,SapiensImageProcessor:()=>Kp,SegformerFeatureExtractor:()=>cT,SegformerImageProcessor:()=>Zp,SiglipImageProcessor:()=>uT,SmolVLMImageProcessor:()=>Gh,Swin2SRImageProcessor:()=>dT,VLMImageProcessor:()=>Vk,ViTFeatureExtractor:()=>hT,ViTImageProcessor:()=>e_,VitMatteImageProcessor:()=>fT,VitPoseImageProcessor:()=>pT,YolosFeatureExtractor:()=>_T,YolosImageProcessor:()=>t_});var Pk=class extends le{},Ak=class extends le{},Fk=class extends le{},Vp=class extends le{},Ik=class extends Vp{},Up=class extends le{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){const t=this.size?.shortest_edge;if(t===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(t<384){const r=Math.floor(t/this.crop_pct),[n,s]=this.get_resize_output_image_size(e,{shortest_edge:r});e=await e.resize(n,s,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}},Lk=class extends Up{},Wp=class extends le{},Ok=class extends Wp{},jp=class extends le{async _call(e){const t=await super._call(e),r=[t.pixel_values.dims[0],64,64],n=at(r,1n);return{...t,pixel_mask:n}}post_process_object_detection(...e){return fa(...e)}post_process_panoptic_segmentation(...e){return Gp(...e)}post_process_instance_segmentation(...e){return $p(...e)}},Nk=class extends jp{},Dk=class extends le{},Ii=class extends le{pad_image(e,t,r,n={}){const[s,a,o]=t;let i=this.image_mean;Array.isArray(this.image_mean)||(i=new Array(o).fill(i));let l=this.image_std;Array.isArray(l)||(l=new Array(o).fill(i));const u=i.map((h,f)=>-h/l[f]);return super.pad_image(e,t,r,{center:!0,constant_values:u,...n})}},Bk=class extends Ii{},qp=class extends le{},zk=class extends qp{},Rk=class extends le{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(t=>t*t))}},Gk=class extends le{},$k=class extends le{async _call(e){const t=await super._call(e),r=t.pixel_values.dims,n=Et([r[0],r[2],r[3]]);return{...t,pixel_mask:n}}},Gh=class extends le{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,t){let[r,n]=e.dims.slice(-2);const s=n/r;return n>=r?(n=Math.ceil(n/t)*t,r=Math.floor(n/s),r=Math.ceil(r/t)*t):(r=Math.ceil(r/t)*t,n=Math.floor(r*s),n=Math.ceil(n/t)*t),{height:r,width:n}}async _call(e,{do_image_splitting:t=null,return_row_col_info:r=!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 s=[],a=[],o=[];const i=[],l=[];for(const M of n){let k=await Promise.all(M.map(E=>this.preprocess(E)));i.push(...k.map(E=>E.original_size)),l.push(...k.map(E=>E.reshaped_input_size)),k.forEach(E=>E.pixel_values.unsqueeze_(0));const{longest_edge:T}=this.max_image_size;let S;if(t??this.do_image_splitting){let E=new Array(k.length),F=new Array(k.length);S=await Promise.all(k.map(async(z,b)=>{const U=this.get_resize_for_vision_encoder(z.pixel_values,T),G=await Dr(z.pixel_values,{size:[U.height,U.width]}),{frames:H,num_splits_h:Z,num_splits_w:W}=await this.split_image(G,this.max_image_size);return E[b]=Z,F[b]=W,Be(H,0)})),a.push(E),o.push(F)}else{const E=[T,T];S=await Promise.all(k.map(F=>Dr(F.pixel_values,{size:E}))),a.push(new Array(k.length).fill(0)),o.push(new Array(k.length).fill(0))}s.push(Be(S,0))}const u=s.length,[h,f,p,g]=s[0].dims;let v,w;if(u===1)v=s[0].unsqueeze_(0),w=at([u,h,p,g],!0);else{const M=Math.max(...s.map(S=>S.dims.at(0)));w=at([u,M,p,g],!0);const k=w.data,T=M*p*g;for(let S=0;S<u;++S){const E=s[S].dims[0];if(E<M){s[S]=Be([s[S],at([M-E,f,p,g],0)],0);const F=S*T+E*p*g,z=(S+1)*T;k.fill(!1,F,z)}}v=vn(s,0)}return{pixel_values:v,pixel_attention_mask:w,original_sizes:i,reshaped_input_sizes:l,...r?{rows:a,cols:o}:{}}}async split_image(e,{longest_edge:t}){const r=t,n=t,s=[],[a,o]=e.dims.slice(-2);let i=0,l=0;if(a>r||o>n){i=Math.ceil(a/r),l=Math.ceil(o/n);const u=Math.ceil(a/i),h=Math.ceil(o/l);for(let g=0;g<i;++g)for(let v=0;v<l;++v){let w,M,k,T;g===i-1?(M=a-u,T=a):(M=g*u,T=(g+1)*u),v===l-1?(w=o-h,k=o):(w=v*h,k=(v+1)*h);const F=await xp(e,[M,w],[T,k],[2,3]);s.push(F)}const f=r,p=n;(a!==f||o!==p)&&(e=await Dr(e,{size:[f,p]}))}return s.push(e),{frames:s,num_splits_h:i,num_splits_w:l}}},Vk=class extends le{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(t=>t*this.rescale_factor)}pad_image(e,t,r,n){return super.pad_image(e,t,r,{constant_values:this.constant_values,center:!0,...n})}},Uk=class extends le{constructor(e){const{resize_mode:t,fill_color:r,interpolation:n,size:s,...a}=e,o=t==="squash"?{width:s,height:s}:t==="shortest"?{shortest_edge:s}:{longest_edge:s},i=n==="bicubic"?3:2;super({...a,size:o,resample:i,do_center_crop:!0,crop_size:s,do_normalize:!0})}},Wk=class extends le{},Li=class extends le{post_process_panoptic_segmentation(...e){return Gp(...e)}post_process_instance_segmentation(...e){return $p(...e)}},jk=class extends Li{},qk=class extends Li{},Hp=class extends le{},Hk=class extends Hp{},Qp=class extends le{},Qk=class extends Qp{},Xp=class extends le{},Xk=class extends Xp{},Yp=class extends le{},Yk=class extends Yp{},Jp=class extends le{},Jk=class extends Jp{},Kk=class extends Ii{},Oi=class extends le{post_process_object_detection(...e){return fa(...e)}},Zk=class extends Oi{},eT=class extends Oi{},_t=336,tT=[2,3],{ceil:zo,floor:en,sqrt:Ro}=Math,rT=class extends le{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,t){const{num_img_tokens:r}=this.config;return en((en(t/_t)*en(e/_t)+1)*r+1+(en(t/_t)+1)*Ro(r))}get_resize_output_image_size(e,t){const r=this._num_crops,[n,s]=e.size;let a=n/s,o=1;for(;o*Math.ceil(o/a)<=r;)o+=1;o-=1;const i=Math.floor(o*336),l=Math.floor(i/a);return[i,l]}pad_image(e,t,r,n={}){const[s,a]=t,o=_t*zo(s/_t),i=_t*zo(a/_t),l=[1,1,1].map((u,h)=>(u-this.image_mean[h])/this.image_std[h]);return super.pad_image(e,t,{width:i,height:o},{center:!0,constant_values:l,...n})}async _call(e,{num_crops:t=null}={}){if(this._num_crops=t??=this.config.num_crops,t<4||Ro(t)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);const r=e.length,n=await Promise.all(e.map(f=>this.preprocess(f))),s=n.map(f=>f.original_size),a=n.map(f=>f.reshaped_input_size),o=[];for(const{pixel_values:f}of n){f.unsqueeze_(0);const[p,g]=f.dims.slice(-2),v=await Dr(f,{size:[_t,_t],mode:"bicubic"});if(t>0){const w=[],M=Ro(t),k=en(g/M),T=en(p/M);for(let E=0;E<M;++E)for(let F=0;F<M;++F){let z,b,U,G;E===M-1?(b=p-T,G=p):(b=E*T,G=(E+1)*T),F===M-1?(z=g-k,U=g):(z=F*k,U=(F+1)*k);const W=await xp(f,[b,z],[G,U],tT);w.push(W)}const S=await Dr(Be(w,0),{size:[_t,_t],mode:"bicubic"});o.push(Be([v,S],0))}else o.push(v)}const i=vn(o,0),l=a.map(f=>f.map(p=>_t*zo(p/_t))),u=new q("int64",l.flat(),[r,2]),h=l.map(([f,p])=>this.calc_num_image_tokens_from_image_size(p,f));return{pixel_values:i,original_sizes:s,reshaped_input_sizes:a,image_sizes:u,num_img_tokens:h}}},nT=class extends le{get_resize_output_image_size(e,t){const{longest_edge:r}=t;if(r===void 0)throw new Error("size must contain 'longest_edge'");const[n,s]=e.size,a=Math.max(n,s)/r;let o=n,i=s;a>1&&(o=Math.floor(n/a),i=Math.floor(s/a));const{patch_size:l,spatial_merge_size:u}=this.config;if(!u)throw new Error("config must contain 'spatial_merge_size'");const h=l*u,f=Math.floor((o-1)/h)+1,p=Math.floor((i-1)/h)+1;return[f*h,p*h]}},sT=class extends le{};function aT(e,t,r=28,n=56*56,s=14*14*4*1280){if(e<r||t<r)throw new Error(`height:${e} or width:${t} must be larger than factor:${r}`);if(Math.max(e,t)/Math.min(e,t)>200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(e,t)/Math.min(e,t)}`);let a=Math.round(e/r)*r,o=Math.round(t/r)*r;if(a*o>s){const i=Math.sqrt(e*t/s);a=Math.floor(e/i/r)*r,o=Math.floor(t/i/r)*r}else if(a*o<n){const i=Math.sqrt(n/(e*t));a=Math.ceil(e*i/r)*r,o=Math.ceil(t*i/r)*r}return[a,o]}var oT=class extends le{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,t){const r=this.patch_size*this.merge_size;return aT(e.height,e.width,r,this.min_pixels,this.max_pixels)}async _call(e,...t){const{pixel_values:r,original_sizes:n,reshaped_input_sizes:s}=await super._call(e,...t);let a=r;const{temporal_patch_size:o,merge_size:i,patch_size:l}=this.config;a.dims[0]===1&&(a=Be(Array.from({length:o},()=>a),0));const u=a.dims[0]/o,h=a.dims[1],f=Math.floor(a.dims[2]/l),p=Math.floor(a.dims[3]/l),g=a.view(u,o,h,Math.floor(f/i),i,l,Math.floor(p/i),i,l).permute(0,3,6,4,7,2,1,5,8).view(u*f*p,h*o*l*l),v=new q("int64",[u,f,p],[1,3]);return{pixel_values:g,image_grid_thw:v,original_sizes:n,reshaped_input_sizes:s}}},iT=class extends le{post_process_object_detection(...e){return fa(...e)}},Go=class extends le{reshape_input_points(e,t,r,n=!1){e=structuredClone(e);let s=oh(e);if(s.length===3)n||(s=[1,...s]),e=[e];else if(s.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){const[o,i]=t[a],[l,u]=r[a],h=[u/i,l/o];for(let f=0;f<e[a].length;++f)for(let p=0;p<e[a][f].length;++p)for(let g=0;g<e[a][f][p].length;++g)e[a][f][p][g]*=h[g%2]}return new q("float32",Float32Array.from(e.flat(1/0)),s)}add_input_labels(e,t){let r=oh(e);if(r.length===2)r=[1,...r],e=[e];else if(r.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(r.some((n,s)=>n!==t.dims[s]))throw Error(`The first ${r.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new q("int64",e.flat(1/0).map(BigInt),r)}async _call(e,{input_points:t=null,input_labels:r=null,input_boxes:n=null}={}){const s=await super._call(e);if(t&&(s.input_points=this.reshape_input_points(t,s.original_sizes,s.reshaped_input_sizes)),r){if(!s.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");s.input_labels=this.add_input_labels(r,s.input_points)}return n&&(s.input_boxes=this.reshape_input_points(n,s.original_sizes,s.reshaped_input_sizes,!0)),s}async post_process_masks(e,t,r,{mask_threshold:n=0,binarize:s=!0,pad_size:a=null}={}){const o=[];a=a??this.pad_size??this.size;const i=[a.height,a.width];for(let l=0;l<t.length;++l){const u=t[l],h=r[l];let f=await Dr(e[l],{mode:"bilinear",size:i});if(f=f.slice(null,null,[0,h[0]],[0,h[1]]),f=await Dr(f,{mode:"bilinear",size:u}),s){const p=f.data,g=new Uint8Array(p.length);for(let v=0;v<p.length;++v)p[v]>n&&(g[v]=1);f=new q("bool",g,f.dims)}o.push(f)}return o}generate_crop_boxes(e,t,{crop_n_layers:r=0,overlap_ratio:n=512/1500,points_per_crop:s=32,crop_n_points_downscale_factor:a=1}={}){}},Kp=class extends le{post_process_semantic_segmentation(...e){return Rp(...e)}},lT=class extends Kp{},Zp=class extends le{post_process_semantic_segmentation(...e){return Rp(...e)}},cT=class extends Zp{},uT=class extends le{},dT=class extends le{pad_image(e,t,r,n={}){const[s,a,o]=t;return super.pad_image(e,t,{width:a+(r-a%r)%r,height:s+(r-s%r)%r},{mode:"symmetric",center:!1,constant_values:-1,...n})}},e_=class extends le{},hT=class extends e_{},fT=class extends le{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);const r=await Promise.all(e.map(a=>this.preprocess(a))),n=await Promise.all(t.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:vn(r.map((a,o)=>Be([a.pixel_values,n[o].pixel_values],0)),0),original_sizes:r.map(a=>a.original_size),reshaped_input_sizes:r.map(a=>a.reshaped_input_size)}}},pT=class extends le{post_process_pose_estimation(e,t,{threshold:r=null}={}){const n=e.tolist(),[s,a,o,i]=e.dims,l=[];for(let u=0;u<s;++u){const h=n[u],f=t[u],p=[];for(let g=0;g<f.length;++g){const v=f[g],w=[],M=[],k=[],T=v.at(-2)/i,S=v.at(-1)/o;for(let E=0;E<h.length;++E){let[F,z]=[0,0],b=0,U=-1/0;const G=h[E];for(let Z=0;Z<G.length;++Z){const W=G[Z];for(let B=0;B<W.length;++B){const O=W[B];b+=O,U=Math.max(U,O),F+=(B+.5)*O,z+=Z*O}}if(r!=null&&U<r)continue;const H=[T*F/b,S*z/b];w.push(H),k.push(E),M.push(U)}p.push({bbox:v,scores:M,labels:k,keypoints:w})}l.push(p)}return l}},t_=class extends le{post_process_object_detection(...e){return fa(...e)}},_T=class extends t_{},pt=class{static async from_pretrained(e,t={}){const r=await ir(e,Ai,!0,t),n=r.image_processor_type??r.feature_extractor_type;let s=ta[n?.replace(/Fast$/,"")];return s||(n!==void 0&&he.warn(`Image processor type '${n}' not found, assuming base ImageProcessor. Please report this at ${Si}.`),s=le),new s(r)}},mT=class extends Oe{static tokenizer_class=Ee;static image_processor_class=pt;constructor(e,t,r){super(e,t,r);const{tasks_answer_post_processing_type:n,task_prompts_without_inputs:s,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(s??{})),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]);const t=[];for(const r of e)if(this.task_prompts_without_inputs.has(r))t.push(this.task_prompts_without_inputs.get(r));else{for(const[n,s]of this.task_prompts_with_input)if(r.includes(n)){t.push(s.replaceAll("{input}",r).replaceAll(n,""));break}t.length!==e.length&&t.push(r)}return t}post_process_generation(e,t,r){const n=this.tasks_answer_post_processing_type.get(t)??"pure_text";e=e.replaceAll("<s>","").replaceAll("</s>","");let s;switch(n){case"pure_text":s=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const a=n==="ocr"?"quad_boxes":"bboxes",o=e.matchAll(this.regexes[a]),i=[],l=[];for(const[u,h,...f]of o)i.push(h?h.trim():i.at(-1)??""),l.push(f.map((p,g)=>(Number(p)+.5)/this.size_per_bin*r[g%2]));s={labels:i,[a]:l};break;default:throw new Error(`Task "${t}" (of type "${n}") not yet implemented.`)}return{[t]:s}}async _call(e,t=null,r={}){if(!e&&!t)throw new Error("Either text or images must be provided");const n=await this.image_processor(e,r),s=t?this.tokenizer(this.construct_prompts(t),r):{};return{...n,...s}}},gT=class extends Oe{static image_processor_class=pt;static feature_extractor_class=lr;static tokenizer_class=Ee;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,r){super(e,t,r),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;const{audio_token_id:n,boa_token:s,audio_token:a,eoa_token:o,image_token_id:i,boi_token:l,image_token:u,eoi_token:h}=this.tokenizer.config;this.audio_token_id=n,this.boa_token=s,this.audio_token=a;const f=a.repeat(this.audio_seq_length);this.full_audio_sequence=`
18
+
19
+ ${s}${f}${o}
20
+
21
+ `,this.image_token_id=i,this.boi_token=l,this.image_token=u;const p=u.repeat(this.image_seq_length);this.full_image_sequence=`
22
+
23
+ ${l}${p}${h}
24
+
25
+ `}async _call(e,t=null,r=null,n={}){typeof e=="string"&&(e=[e]);let s;r&&(s=await this.feature_extractor(r,n),e=e.map(i=>i.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return t&&(a=await this.image_processor(t,n),e=e.map(i=>i.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,n),...a,...s}}};function wT(e,t){const n=e.dims.at(-1)-1,s=e.tolist();s.fill(!1,0,1),s.fill(!1,n);const a=t.tolist();return s.map((o,i)=>o?i:null).filter(o=>o!==null).map(o=>a[o])}var vT=class extends Oe{static tokenizer_class=Ee;static image_processor_class=pt;async _call(e,t,r={}){const n=e?await this.image_processor(e,r):{};return{...t?this.tokenizer(t,r):{},...n}}post_process_grounded_object_detection(e,t,{box_threshold:r=.25,text_threshold:n=.25,target_sizes:s=null}={}){const{logits:a,pred_boxes:o}=e,i=a.dims[0];if(s!==null&&s.length!==i)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const l=a.dims.at(1),u=a.sigmoid(),h=u.max(-1).tolist(),f=o.tolist().map(g=>g.map(v=>zp(v))),p=[];for(let g=0;g<i;++g){const v=s!==null?s[g]:null;v!==null&&(f[g]=f[g].map(S=>S.map((E,F)=>E*v[(F+1)%2])));const w=h[g],M=[],k=[],T=[];for(let S=0;S<l;++S){const E=w[S];if(E<=r)continue;const F=f[g][S],z=u[g][S];M.push(E),T.push(F);const b=wT(z.gt(n),t[g]);k.push(b)}p.push({scores:M,boxes:T,labels:this.batch_decode(k)})}return p}};function yT(e,t,r,n,s,a){let o="";for(let i=0;i<t;++i){for(let l=0;l<r;++l)o+=n+`<row_${i+1}_col_${l+1}>`+s.repeat(e);o+=`
26
+ `}return o+=`
27
+ ${n}${a}`+s.repeat(e)+`${n}`,o}function bT(e,t,r,n){return`${t}${n}`+r.repeat(e)+`${t}`}function MT(e,t,r,n,s,a){return e===0&&t===0?bT(r,n,s,a):yT(r,e,t,n,s,a)}var $h=class extends Oe{static image_processor_class=pt;static tokenizer_class=Ee;static uses_processor_config=!0;fake_image_token="<fake_token_around_image>";image_token="<image>";global_img_token="<global-img>";async _call(e,t=null,r={}){r.return_row_col_info??=!0;let n;t&&(n=await this.image_processor(t,r)),Array.isArray(e)||(e=[e]);const s=n.rows??[new Array(e.length).fill(0)],a=n.cols??[new Array(e.length).fill(0)],o=this.config.image_seq_len,i=[],l=[];for(let h=0;h<e.length;++h){const f=e[h],p=s[h],g=a[h];i.push(cb(f,this.image_token));const v=p.map((k,T)=>MT(k,g[T],o,this.fake_image_token,this.image_token,this.global_img_token)),w=f.split(this.image_token);if(w.length===0)throw new Error("The image token should be present in the text.");let M=w[0];for(let k=0;k<v.length;++k)M+=v[k]+w[k+1];l.push(M)}return{...this.tokenizer(l),...n}}},xT=class extends Oe{static image_processor_class=pt;static tokenizer_class=Ee;static uses_processor_config=!0;constructor(e,t,r){super(e,t,r),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:t=null,chat_template:r="default"}={}){t?Array.isArray(t)||(t=[t]):t=await Promise.all(e.filter(w=>w.images).flatMap(w=>w.images).map(w=>Rr.read(w)));const n=this.tokenizer,s=n.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:r}),a=w=>n.encode(w,{add_special_tokens:!1}),o=s.split(this.image_tag),i=o.length-1;if(t.length!==i)throw new Error(`Number of images provided (${t.length}) does not match number of "${this.image_tag}" image tags (${i})`);const[l,u,h]=n.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let f=a(o[0]),p=new Array(f.length).fill(!1);for(let w=1;w<o.length;++w){const M=new Array(this.num_image_tokens).fill(l),k=a(o[w]);f=Nt(f,[u],M,[h],k);const T=new Array(this.num_image_tokens).fill(!0);p=Nt(p,[!1],T,[!1],new Array(k.length).fill(!1))}const g=[1,f.length],v={input_ids:new q("int64",f,g),attention_mask:new q("int64",new Array(f.length).fill(1),g),images_seq_mask:new q("bool",p,g),images_emb_mask:new q("bool",new Array(i*this.num_image_tokens).fill(!0),[1,i,this.num_image_tokens])};if(t&&t.length>0){const w=await this.image_processor(t);return w.pixel_values.unsqueeze_(0),{...v,...w}}return v}},kT=class extends Oe{static tokenizer_class=Ee;static image_processor_class=pt;async _call(e=null,t=null,r={}){if(!e&&!t)throw new Error("Either text or images must be provided");const n=e?this.tokenizer(e,r):{},s=t?await this.image_processor(t,r):{};return{...n,...s}}},TT=class extends Oe{static tokenizer_class=Ee;static image_processor_class=pt;static uses_processor_config=!0;async _call(e,t=null,r={}){const n=await this.image_processor(e,r);if(t){const[a,o]=n.pixel_values.dims.slice(-2),{image_token:i,patch_size:l,num_additional_image_tokens:u}=this.config,h=Math.floor(a/l)*Math.floor(o/l)+u;t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let f=0;f<t.length;++f)t[f]=t[f].replace(i,i.repeat(h))}const s=t?this.tokenizer(t,r):{};return{...n,...s}}},Vh={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]},ET=class extends Oe{static tokenizer_class=Ee;static image_processor_class=pt;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,t){if(!Vh.hasOwnProperty(t))throw new Error(`Format ${t} is not supported.`);const[r,n]=Vh[t],s=this[r].bind(this),[a,o]=e.dims,i=[],l=[],u=e.tolist();for(let f=0;f<a;++f){const p=u[f],g=[],v=[];for(let M=1;M<o;++M){const[k,T]=He(wn(p[M]));if(v.push(k),T==n)break;g.push(T)}const w=v.length>0?v.reduce((M,k)=>M*k,1):0;l.push(g),i.push(w)}return[s(l),i]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(t=>t.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(t=>t.replaceAll(" ",""))}batch_decode([e,t,r]){const[n,s]=this._decode_helper(e,"char"),[a,o]=this._decode_helper(t,"bpe"),[i,l]=this._decode_helper(r,"wp"),u=[],h=[];for(let f=0;f<n.length;++f){const[p,g]=He([s[f],o[f],l[f]]);u.push([n[f],a[f],i[f]][g]),h.push(p)}return{generated_text:u,scores:h,char_preds:n,bpe_preds:a,wp_preds:i}}static async from_pretrained(...e){const t=await super.from_pretrained(...e),r=await Ee.from_pretrained("Xenova/gpt2"),n=await Ee.from_pretrained("Xenova/bert-base-uncased");return t.components={image_processor:t.image_processor,char_tokenizer:t.tokenizer,bpe_tokenizer:r,wp_tokenizer:n},t}async _call(e,t=null){const r=await this.image_processor(e);return t&&(r.labels=this.tokenizer(t).input_ids),r}},CT=class extends Oe{static tokenizer_class=Ee;static feature_extractor_class=lr;async _call(e){return await this.feature_extractor(e)}},ST=class extends Oe{static tokenizer_class=Ee;static image_processor_class=pt},tn="<image>";function PT(e,t,r,n,s){return`${n.repeat(r*s)}${t}${e}
28
+ `}var AT=class extends Oe{static tokenizer_class=Ee;static image_processor_class=pt;static uses_processor_config=!1;async _call(e,t=null,r={}){t||(he.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),t=""),Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);const n=this.tokenizer.bos_token,s=this.image_processor.config.image_seq_length;let a;t.some(l=>l.includes(tn))?a=t.map(l=>{const u=l.replaceAll(tn,tn.repeat(s)),h=u.lastIndexOf(tn),f=h===-1?0:h+tn.length;return u.slice(0,f)+n+u.slice(f)+`
29
+ `}):(he.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=t.map(l=>PT(l,n,s,tn,e.length)));const o=this.tokenizer(a,r);return{...await this.image_processor(e,r),...o}}},Uh="<|image|>",FT=/<\|image_\d+\|>/g,IT=class extends Oe{static image_processor_class=pt;static tokenizer_class=Ee;async _call(e,t=null,{padding:r=!0,truncation:n=!0,num_crops:s=null}={}){Array.isArray(e)||(e=[e]);let a,o;if(t){o=await this.image_processor(t,{num_crops:s});const{num_img_tokens:i}=o,l=e.map((h,f)=>h.split(FT).join(Uh.repeat(i[f])));a=this.tokenizer(l,{padding:r,truncation:n});const u=this.tokenizer._tokenizer.token_to_id(Uh);a.input_ids.map_(h=>h==u?-h:h)}else a=this.tokenizer(e);return{...a,...o}}},LT=class extends Oe{static tokenizer_class=Ee;static image_processor_class=pt;static uses_processor_config=!0;async _call(e,t=null,r={}){const n=await this.image_processor(e,r);if(t){const[a,o]=n.pixel_values.dims.slice(-2),{image_token:i,image_break_token:l,image_end_token:u,patch_size:h,spatial_merge_size:f}=this.config,p=h*f,g=Math.floor(a/p),v=Math.floor(o/p);t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let w=0;w<t.length;++w){const M=i.repeat(v),k=M+l,T=M+u,S=k.repeat(g-1)+T;t[w]=t[w].replace(i,S)}}const s=t?this.tokenizer(t,r):{};return{...n,...s}}},OT=class extends Oe{static feature_extractor_class=Dp;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}},r_=class extends Oe{static image_processor_class=pt;static tokenizer_class=Ee;async _call(e,t=null,...r){Array.isArray(e)||(e=[e]);let n,s;if(t&&(n=await this.image_processor(t),s=n.image_grid_thw),s){let o=this.image_processor.config.merge_size**2,i=0;const l=s.tolist();e=e.map(u=>{for(;u.includes("<|image_pad|>");){const h=Number(l[i++].reduce((f,p)=>f*p,1n));u=u.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(h/o)))}return u.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(e),...n}}},n_=class extends r_{},NT=class extends n_{},s_=class extends Oe{static image_processor_class=pt;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)}},a_=class extends s_{},DT=class extends a_{},BT=class extends Oe{static tokenizer_class=Ee;static feature_extractor_class=lr;async _call(e){return await this.feature_extractor(e)}},zT=class extends Oe{static tokenizer_class=Ee;static feature_extractor_class=lr;static uses_processor_config=!0;async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(t){const a=t.length,{input_features:o}=await this.feature_extractor(t,{...r,max_length:a}),i=Math.round(a/this.config.encoder_ds_factor+1e-4),l=1+Math.ceil(i/this.config.stack_factor);n.audio_token_len=[l],n.audio_values=o;const u=this.config.audio_placeholder;if(!e.includes(u))throw new Error(`The input text does not contain the image token ${u}.`);e=e.replaceAll(u,u.repeat(l))}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...n}}},Os="[AUDIO]",RT="[BEGIN_AUDIO]",GT=375;function $T(e,t){const r=[];for(let n=0;n<e.length;n+=t)r.push(e.subarray(n,Math.min(n+t,e.length)));return r}var VT=class extends Oe{static tokenizer_class=Ee;static feature_extractor_class=lr;static uses_processor_config=!1;async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");const n={};if(t){if(!e.includes(Os))throw new Error(`The input text does not contain the audio token ${Os}.`);Array.isArray(t)||(t=[t]);const a=e.split(Os),o=a.length-1;if(o!==t.length)throw new Error(`The number of audio inputs (${t.length}) does not match the number of audio tokens in the text (${o}).`);const i=this.feature_extractor.config.n_samples,l=t.map(g=>$T(g,i)),u=l.map(g=>g.length),h=l.flat(),f=(await Promise.all(h.map(g=>this.feature_extractor(g,r)))).map(g=>g.input_features);n.audio_values=f.length>1?Be(f,0):f[0];let p=a[0];for(let g=0;g<u.length;++g){p+=RT;for(let v=0;v<u[g];++v)p+=Os.repeat(GT);p+=a[g+1]}e=p}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...n}}},UT=class extends Oe{static tokenizer_class=Ee;static feature_extractor_class=lr;async _call(e){return await this.feature_extractor(e)}},WT=class extends Oe{static tokenizer_class=Ee;static feature_extractor_class=lr;async _call(e){return await this.feature_extractor(e)}},jT=class extends Oe{static tokenizer_class=Ee;static feature_extractor_class=lr;async _call(e){return await this.feature_extractor(e)}},Ni=class{static async from_pretrained(e,t={}){const r=await ir(e,Ai,!0,t),{image_processor_type:n,feature_extractor_type:s,processor_class:a}=r;if(a&&Yo[a])return Yo[a].from_pretrained(e,t);if(!n&&!s)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const o={};if(n){const l=ta[n.replace(/Fast$/,"")];if(!l)throw new Error(`Unknown image_processor_type: '${n}'.`);o.image_processor=new l(r)}if(s){const l=ta[s];if(l)o.image_processor=new l(r);else{const u=Fi[s];if(!u)throw new Error(`Unknown feature_extractor_type: '${s}'.`);o.feature_extractor=new u(r)}}const i={};return new Oe(i,o,null)}};async function qT(e,t){return await ir(e,"config.json",!0,t)}function nn(e){const t={};let r={};switch(e.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=nn(e.text_config);break;case"moondream1":r=nn(e.phi_config);break;case"musicgen":r=nn(e.decoder);break;case"multi_modality":r=nn(e.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":case"modernbert-decoder":t.num_heads="num_attention_heads",t.num_layers="num_hidden_layers",t.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":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size",t.num_attention_heads="num_attention_heads",t.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":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv="head_dim";break;case"openelm":t.num_heads="num_kv_heads",t.num_layers="num_transformer_layers",t.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":t.num_heads="num_heads",t.num_layers="num_layers",t.hidden_size="hidden_size";break;case"bloom":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="hidden_size";break;case"mpt":t.num_heads="n_heads",t.num_layers="n_layers",t.hidden_size="d_model";break;case"exaone":t.num_heads="num_key_value_heads",t.num_layers="num_layers",t.dim_kv="head_dim",t.num_attention_heads="num_attention_heads";break;case"youtu":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv="qk_head_dim",t.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":t.num_decoder_layers="num_decoder_layers",t.num_decoder_heads="num_heads",t.decoder_dim_kv="d_kv",t.num_encoder_layers="num_layers",t.num_encoder_heads="num_heads",t.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":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="d_model",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="d_model";break;case"speecht5":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="hidden_size",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="hidden_size";break;case"trocr":t.num_encoder_layers=t.num_decoder_layers="decoder_layers",t.num_encoder_heads=t.num_decoder_heads="decoder_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="d_model";break;case"musicgen_decoder":t.num_encoder_layers=t.num_decoder_layers="num_hidden_layers",t.num_encoder_heads=t.num_decoder_heads="num_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case"moonshine":t.num_decoder_layers="decoder_num_hidden_layers",t.num_decoder_heads="decoder_num_key_value_heads",t.num_encoder_layers="encoder_num_hidden_layers",t.num_encoder_heads="encoder_num_key_value_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const s=nn(e.decoder),a="num_decoder_layers"in s,o=ht(e,["model_type","is_encoder_decoder"]);return a?(o.num_decoder_layers=s.num_decoder_layers,o.num_decoder_heads=s.num_decoder_heads,o.decoder_hidden_size=s.decoder_hidden_size,o.num_encoder_layers=s.num_encoder_layers,o.num_encoder_heads=s.num_encoder_heads,o.encoder_hidden_size=s.encoder_hidden_size):(o.num_layers=s.num_layers,o.num_heads=s.num_heads,o.hidden_size=s.hidden_size),o}const n={...r,...ht(e,["model_type","multi_query","is_encoder_decoder"])};for(const s in t)n[s]=e[t[s]];return n}function o_(e,t){if(["lfm2","lfm2_moe"].includes(e.model_type)){const r=t?.prefix??"past_key_values",n=r==="present"?"present":"past",s={},{layer_types:a,num_attention_heads:o,num_key_value_heads:i,hidden_size:l,conv_L_cache:u}=e,h=l/o,f=t?.batch_size??1;for(let p=0;p<a.length;++p)if(a[p]==="full_attention")for(const g of["key","value"])s[`${r}.${p}.${g}`]=[f,i,0,h];else if(a[p]==="conv")s[`${n}_conv.${p}`]=[f,l,u];else throw new Error(`Unsupported layer type: ${a[p]}`);return s}else if(["granitemoehybrid","falcon_h1"].includes(e.model_type)){const r=t?.prefix??"past_key_values",n=r==="present"?"present":"past",s={},{layer_types:a,num_hidden_layers:o,num_attention_heads:i,num_key_value_heads:l,hidden_size:u,mamba_d_conv:h,mamba_n_heads:f,mamba_d_head:p,mamba_d_state:g,mamba_n_groups:v,mamba_expand:w,mamba_d_ssm:M}=e,k=u/i,T=t?.batch_size??1,S=(M??w*u)+2*v*g;for(let E=0;E<o;++E)if((!a||a[E]==="mamba")&&(s[`${n}_conv.${E}`]=[T,S,h],s[`${n}_ssm.${E}`]=[T,f,p,g]),!a||a[E]==="attention")for(const F of["key","value"])s[`${r}.${E}.${F}`]=[T,l,0,k];return s}else if(["qwen3_5","qwen3_5_moe"].includes(e.model_type)){const r=t?.prefix??"past_key_values",n=r==="present"?"present":"past",s={},{head_dim:a,layer_types:o,num_attention_heads:i,num_key_value_heads:l,hidden_size:u,linear_num_value_heads:h,linear_num_key_heads:f,linear_key_head_dim:p,linear_value_head_dim:g,linear_conv_kernel_dim:v}=e.text_config,w=p*f,M=g*h,k=w*2+M,T=a??u/i,S=t?.batch_size??1;for(let E=0;E<o.length;++E)if(o[E]==="full_attention")for(const F of["key","value"])s[`${r}.${E}.${F}`]=[S,l,0,T];else if(o[E]==="linear_attention")s[`${n}_conv.${E}`]=[S,k,v],s[`${n}_recurrent.${E}`]=[S,h,p,g];else throw new Error(`Unsupported layer type: ${o[E]}`);return s}return HT(e,t)}function HT(e,{prefix:t="past_key_values",batch_size:r=1}={}){const n={},s=e.normalized_config;if(s.is_encoder_decoder&&"num_encoder_heads"in s&&"num_decoder_heads"in s){const a=s.encoder_dim_kv??s.encoder_hidden_size/s.num_encoder_heads,o=s.decoder_dim_kv??s.decoder_hidden_size/s.num_decoder_heads,i=[r,s.num_encoder_heads,0,a],l=[r,s.num_decoder_heads,0,o];for(let u=0;u<s.num_decoder_layers;++u)n[`${t}.${u}.encoder.key`]=i,n[`${t}.${u}.encoder.value`]=i,n[`${t}.${u}.decoder.key`]=l,n[`${t}.${u}.decoder.value`]=l}else{const a=s.num_heads,o=s.num_layers,i=s.dim_kv??s.hidden_size/(s.num_attention_heads??a);if(s.model_type==="falcon"){const l=[r*a,0,i];for(let u=0;u<o;++u)n[`${t}.${u}.key`]=l,n[`${t}.${u}.value`]=l}else if(s.multi_query){const l=[r*a,0,2*i];for(let u=0;u<o;++u)n[`${t}.${u}.key_value`]=l}else if(s.model_type==="bloom"){const l=[r*a,i,0],u=[r*a,0,i];for(let h=0;h<o;++h)n[`${t}.${h}.key`]=l,n[`${t}.${h}.value`]=u}else if(s.model_type==="openelm")for(let l=0;l<o;++l){const u=[r,a[l],0,i];n[`${t}.${l}.key`]=u,n[`${t}.${l}.value`]=u}else{const l=[r,a,0,i];for(let u=0;u<o;++u)n[`${t}.${u}.key`]=l,n[`${t}.${u}.value`]=l}}return n}var QT=class Ko{model_type=null;is_encoder_decoder=!1;max_position_embeddings;"transformers.js_config";constructor(t){Object.assign(this,t),this.normalized_config=nn(this)}static async from_pretrained(t,{progress_callback:r=null,config:n=null,cache_dir:s=null,local_files_only:a=!1,revision:o="main"}={}){n&&!(n instanceof Ko)&&(n=new Ko(n));const i=n??await qT(t,{progress_callback:r,config:n,cache_dir:s,local_files_only:a,revision:o});return new this(i)}},i_=class{static async from_pretrained(...e){return QT.from_pretrained(...e)}};function XT(e,t,r){return e?typeof e=="object"&&e!==null?e.hasOwnProperty(t)?+e[t]:e.hasOwnProperty(r)?+e[r]:0:+e:0}function YT(e,t){const r=[];for(let n=0;n<t;++n)r.push(`${e}_data${n===0?"":"_"+n}`);return r}async function JT(e,t,r,n){const s=`${t}${n}.onnx`,a=`${r.subfolder??""}/${s}`;return await Zs(e,a,!0,r,Ae.IS_NODE_ENV)}async function KT(e,t,r,n,s,a={}){const o=`${t}${r}.onnx`,i=Ae.IS_NODE_ENV;let l=[];const u=XT(s,o,t);if(u>0){if(u>Th)throw new Error(`The number of external data chunks (${u}) exceeds the maximum allowed value (${Th}).`);const h=YT(o,u);for(const f of h){const p=`${n.subfolder??""}/${f}`;l.push(new Promise(async(g,v)=>{const w=await Zs(e,p,!0,n,i);g(w instanceof Uint8Array?{path:f,data:w}:f)}))}}else a.externalData!==void 0&&(l=a.externalData.map(async h=>{if(typeof h.data=="string"){const f=await Zs(e,h.data,!0,n);return{...h,data:f}}return h}));return Promise.all(l)}async function ZT(e,t,r,n=!1){let s=r.config?.["transformers.js_config"]??{};const a=Wx(r.device??s.device,t,{warn:S=>he.info(S)}),o=$x(a),i=s.device_config??{};i.hasOwnProperty(a)&&(s={...s,...i[a]});const l=qx(r.dtype??s.dtype,t,a,{configDtype:s.dtype,warn:S=>he.info(S)});if(Lh.hasOwnProperty(l)){if(a==="webgpu"&&!Ae.IS_NODE_ENV&&l===st.fp16&&!await jx())throw new Error(`The device (${a}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${l}. Should be one of: ${Object.keys(st).join(", ")}`);const u=s.kv_cache_dtype,h=u?typeof u=="string"?u:u[l]??"float32":void 0;if(h&&!["float32","float16"].includes(h))throw new Error(`Invalid kv_cache_dtype: ${h}. Should be one of: float32, float16`);const f=Lh[l],p={...r.session_options};p.executionProviders??=o;const g=s.free_dimension_overrides;g?p.freeDimensionOverrides??=g:a.startsWith("webnn")&&!p.freeDimensionOverrides&&he.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.`);const v=JT(e,t,r,f),w=r.use_external_data_format??s.use_external_data_format,M=await KT(e,t,f,r,w,p);if(M.length>0&&!Ae.IS_NODE_ENV&&(p.externalData=M),n&&a==="webgpu"&&u!==!1){const S=o_(r.config,{prefix:"present"});if(Object.keys(S).length>0&&!xi()){const E={};for(const F in S)E[F]="gpu-buffer";p.preferredOutputLocation=E}}return{buffer_or_path:await v,session_options:p,session_config:{dtype:l,kv_cache_dtype:h,device:a}}}async function dt(e,t,r,n=void 0){return Object.fromEntries(await Promise.all(Object.keys(t).map(async s=>{const{buffer_or_path:a,session_options:o,session_config:i}=await ZT(e,t[s],r,s===n),l=await _p(a,o,i);return[s,l]})))}function l_(e){for(let t in e)gp(e[t])?e[t]=new q(e[t]):typeof e[t]=="object"&&l_(e[t]);return e}async function be(e,t){const r=eE(e,t);try{const n=Object.fromEntries(Object.entries(r).map(([a,o])=>{const i=o.ort_tensor;return Ae.IS_NODE_ENV&&typeof Float16Array<"u"&&i.cpuData instanceof Float16Array&&(i.cpuData=new Uint16Array(i.cpuData.buffer)),[a,i]})),s=await mp(e,n);return l_(s)}catch(n){const s=Object.fromEntries(Object.entries(r).map(([a,o])=>{const i={type:o.type,dims:o.dims,location:o.location};return i.location!=="gpu-buffer"&&(i.data=o.data),[a,i]}));throw he.error(`An error occurred during model execution: "${n}".`),he.error("Inputs given to model:",s),n}}function eE(e,t){const r=Object.create(null),n=[];for(const o of e.inputNames){const i=t[o];if(!(i instanceof q)){n.push(o);continue}r[o]=xi()?i.clone():i}if(n.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${n.join(", ")}.`);const s=Object.keys(t).length,a=e.inputNames.length;if(s>a){let o=Object.keys(t).filter(i=>!e.inputNames.includes(i));he.warn(`WARNING: Too many inputs were provided (${s} > ${a}). The following inputs will be ignored: "${o.join(", ")}".`)}return r}var Qe=class{},se=class extends Qe{constructor({logits:e,...t}){super(),this.logits=e;const r=Object.values(t);r.length>0&&(this.attentions=r)}},Xe=class extends Qe{constructor({logits:e}){super(),this.logits=e}},Ke=class extends Qe{constructor({logits:e}){super(),this.logits=e}},ot=class extends Qe{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},Wr=class extends Qe{constructor({logits:e}){super(),this.logits=e}},tE=class extends Qe{constructor({alphas:e}){super(),this.alphas=e}},Yt=class extends $t{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},rE=class extends $t{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},Zo=class extends $t{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let r=t;for(const n of this.processors)r=n(e,r);return r}[Symbol.iterator](){return this.processors.values()}},nE=class extends Yt{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===1){const n=t[r].data;n.fill(-1/0),n[this.bos_token_id]=0}return t}},sE=class extends Yt{constructor(e,t){super(),this.max_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===this.max_length-1){const n=t[r].data;n.fill(-1/0);for(const s of this.eos_token_id)n[s]=0}return t}},c_=class extends Yt{constructor(e,t){super(),this.begin_suppress_tokens=e,this.begin_index=t}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===this.begin_index){const n=t[r].data;for(const s of this.begin_suppress_tokens)n[s]=-1/0}return t}},aE=class extends Yt{constructor(e,t){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=t.length,t.at(-1)===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,t){for(let r=0;r<e.length;++r){const n=t[r].data;if(n[this.no_timestamps_token_id]=-1/0,e[r].length===this.begin_index-1){n.fill(-1/0),n[this.timestamp_begin]=0;continue}const s=e[r].slice(this.begin_index),a=s.length>=1&&s[s.length-1]>=this.timestamp_begin,o=s.length<2||s[s.length-2]>=this.timestamp_begin;if(a&&(o?n.subarray(this.timestamp_begin).fill(-1/0):n.subarray(0,this.eos_token_id).fill(-1/0)),e[r].length===this.begin_index&&this.max_initial_timestamp_index!==null){const h=this.timestamp_begin+this.max_initial_timestamp_index;n.subarray(h+1).fill(-1/0)}const i=Sx(n),l=Math.log(i.subarray(this.timestamp_begin).map(Math.exp).reduce((h,f)=>h+f)),u=He(i.subarray(0,this.timestamp_begin))[0];l>u&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},oE=class extends Yt{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const t=e.length,r=[];for(let s=0;s<t+1-this.no_repeat_ngram_size;++s){const a=[];for(let o=0;o<this.no_repeat_ngram_size;++o)a.push(e[s+o]);r.push(a.map(Number))}const n=new Map;for(const s of r){const a=s.slice(0,s.length-1),o=JSON.stringify(a),i=n.get(o)??[];i.push(s[s.length-1]),n.set(o,i)}return n}getGeneratedNgrams(e,t){const r=t.slice(t.length+1-this.no_repeat_ngram_size,t.length);return e.get(JSON.stringify(r.map(Number)))??[]}calcBannedNgramTokens(e){const t=[];if(e.length+1<this.no_repeat_ngram_size)return t;{const r=this.getNgrams(e);return this.getGeneratedNgrams(r,e)}}_call(e,t){for(let r=0;r<e.length;++r){const n=t[r].data,s=this.calcBannedNgramTokens(e[r]);for(const a of s)n[a]=-1/0}return t}},iE=class extends Yt{constructor(e){super(),this.penalty=e}_call(e,t){for(let r=0;r<e.length;++r){const n=t[r].data;for(const s of new Set(e[r])){const a=Number(s);n[a]<0?n[a]*=this.penalty:n[a]/=this.penalty}}return t}},lE=class extends Yt{constructor(e,t){super(),this.min_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length<this.min_length){const n=t[r].data;for(const s of this.eos_token_id)n[s]=-1/0}return t}},cE=class extends Yt{constructor(e,t,r){super(),this.prompt_length_to_skip=e,this.min_new_tokens=t,this.eos_token_id=Array.isArray(r)?r:[r]}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length-this.prompt_length_to_skip<this.min_new_tokens){const s=t[r].data;for(const a of this.eos_token_id)s[a]=-1/0}return t}},uE=class extends Yt{constructor(e,t){super(),this.bad_words_ids=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let r=0;r<e.length;++r){const n=t[r].data,s=e[r];for(const a of this.bad_words_ids){if(s.length<a.length-1)continue;let o=!0;for(let i=1;i<=a.length-1;++i)if(a.at(-i-1)!=s.at(-i)){o=!1;break}o&&(n[a.at(-1)]=-1/0)}}return t}},dE=class extends Yt{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,t){if(t.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 ${t.dims[0]} for the logits and ${e.length} for the input ids.`);const r=e.length,n=t.slice([0,r],null),s=t.slice([r,t.dims[0]],null);for(let a=0;a<s.data.length;++a)s.data[a]+=(n.data[a]-s.data[a])*this.guidance_scale;return s}},hE=class extends rE{constructor(e){super(),this.temperature=e}_call(e,t){const r=t.data;for(let n=0;n<r.length;++n)r[n]/=this.temperature;return t}},u_=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,ht(e,Object.getOwnPropertyNames(this)))}},pa=class extends $t{_call(e,t){throw Error("StoppingCriteria needs to be subclassed")}},fE=class d_ extends $t{constructor(){super(),this.criteria=[]}push(t){this.criteria.push(t)}extend(t){t instanceof d_?t=t.criteria:t instanceof pa&&(t=[t]),this.criteria.push(...t)}_call(t,r){const n=new Array(t.length).fill(!1);for(const s of this.criteria){const a=s(t,r);for(let o=0;o<n.length;++o)n[o]||=a[o]}return n}[Symbol.iterator](){return this.criteria.values()}},pE=class extends pa{constructor(e,t=null){super(),this.max_length=e,this.max_position_embeddings=t}_call(e){return e.map(t=>t.length>=this.max_length)}},_E=class extends pa{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map(r=>{const n=r.at(-1);return this.eos_token_id.some(s=>n==s)})}},mE=class extends pa{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(e,t){return new Array(e.length).fill(this.interrupted)}},_a=class extends $t{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,t){let r=e.dims.at(-1),n=e.data;if(t===-1)n=n.slice(-r);else{let s=t*r;n=n.slice(s,s+r)}return n}randomSelect(e){return Hx(e)}static getSampler(e){if(e.do_sample)return new wE(e);if(e.num_beams>1)return new vE(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 gE(e)}},gE=class extends _a{async sample(e){const t=He(e.data)[1];return[[BigInt(t),0]]}},wE=class extends _a{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));const[r,n]=await Mp(e,t),s=wn(r.data);return Array.from({length:this.generation_config.num_beams},()=>{const a=this.randomSelect(s);return[n.data[a],Math.log(s[a])]})}},vE=class extends _a{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));const[r,n]=await Mp(e,t),s=wn(r.data);return Array.from({length:this.generation_config.num_beams},(a,o)=>[n.data[o],Math.log(s[o])])}},Yn=null;function yE(e){Yn=e}function ei(e){if(e instanceof q)return e;if(e.length===0)throw Error("items must be non-empty");if(Array.isArray(e[0])){if(e.some(t=>t.length!==e[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new q("int64",BigInt64Array.from(e.flat().map(t=>BigInt(t))),[e.length,e[0].length])}else return new q("int64",BigInt64Array.from(e.map(t=>BigInt(t))),[1,e.length])}function h_(e){return new q("bool",[e],[1])}var V={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},Wh={[V.DecoderOnly]:{can_generate:!0,forward:ar,prepare_inputs:ra},[V.DecoderOnlyWithoutHead]:{can_generate:!1,forward:ar,prepare_inputs:ra},[V.Seq2Seq]:{can_generate:!0,forward:Ns,prepare_inputs:na},[V.Vision2Seq]:{can_generate:!0,forward:Ns,prepare_inputs:na},[V.Musicgen]:{can_generate:!0,forward:Ns},[V.EncoderDecoder]:{can_generate:!1,forward:Ns},[V.ImageTextToText]:{can_generate:!0,forward:xE,prepare_inputs:Ds},[V.AudioTextToText]:{can_generate:!0,forward:ME,prepare_inputs:Ds},[V.Phi3V]:{can_generate:!0,prepare_inputs:Ds},[V.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:Ds},[V.MultiModality]:{can_generate:!0},[V.AutoEncoder]:{can_generate:!1,forward:bE},[V.Chatterbox]:{can_generate:!0,forward:Mr},default:{can_generate:!1,forward:Mr}},fn=new Map,Di=new Map,dn=new Map,P=class extends $t{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];_return_dict_in_generate_keys=null;constructor(e,t,r){super(),this.config=e,this.sessions=t,this.configs=r;const n=dn.get(this.constructor),s=fn.get(n),a=Wh[s]??Wh.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(){const e=[];for(const t of Object.values(this.sessions))e.push(t.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:n=null,local_files_only:s=!1,revision:a="main",model_file_name:o=null,subfolder:i="onnx",device:l=null,dtype:u=null,use_external_data_format:h=null,session_options:f={}}={}){const p={progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a,model_file_name:o,subfolder:i,device:l,dtype:u,use_external_data_format:h,session_options:f},g=dn.get(this),v=fn.get(g);r=p.config=await i_.from_pretrained(e,p);let w;if(v===V.DecoderOnly)w=await Promise.all([dt(e,{model:p.model_file_name??"model"},p,"model"),sr(e,{generation_config:"generation_config.json"},p)]);else if(v===V.Seq2Seq||v===V.Vision2Seq)w=await Promise.all([dt(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},p,"decoder_model_merged"),sr(e,{generation_config:"generation_config.json"},p)]);else if(v===V.MaskGeneration)w=await Promise.all([dt(e,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},p)]);else if(v===V.EncoderDecoder)w=await Promise.all([dt(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},p,"decoder_model_merged")]);else if(v===V.ImageTextToText){const M={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};r.is_encoder_decoder&&(M.model="encoder_model"),w=await Promise.all([dt(e,M,p,"decoder_model_merged"),sr(e,{generation_config:"generation_config.json"},p)])}else if(v===V.AudioTextToText){const M={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};w=await Promise.all([dt(e,M,p,"decoder_model_merged"),sr(e,{generation_config:"generation_config.json"},p)])}else if(v===V.ImageAudioTextToText){const M={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};w=await Promise.all([dt(e,M,p),sr(e,{generation_config:"generation_config.json"},p)])}else if(v===V.Musicgen)w=await Promise.all([dt(e,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},p,"decoder_model_merged"),sr(e,{generation_config:"generation_config.json"},p)]);else if(v===V.MultiModality)w=await Promise.all([dt(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"},p,"model"),sr(e,{generation_config:"generation_config.json"},p)]);else if(v===V.Phi3V)w=await Promise.all([dt(e,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},p,"model"),sr(e,{generation_config:"generation_config.json"},p)]);else if(v===V.Chatterbox)w=await Promise.all([dt(e,{embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"},p,"model"),sr(e,{generation_config:"generation_config.json"},p)]);else if(v===V.AutoEncoder)w=await Promise.all([dt(e,{encoder_model:"encoder_model",decoder_model:"decoder_model"},p)]);else if(v===V.Supertonic)w=await Promise.all([dt(e,{text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"},p)]);else{if(v===void 0){const M=g??r?.model_type;M!=="custom"&&he.warn(`Model type for '${M}' not found, assuming encoder-only architecture. Please report this at ${Si}.`)}w=await Promise.all([dt(e,{model:p.model_file_name??"model"},p)])}return new this(r,...w)}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,t,r=null){const n=new Zo;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&n.push(new iE(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&n.push(new oE(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&n.push(new uE(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&n.push(new lE(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 cE(t,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&n.push(new nE(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&n.push(new sE(e.max_length,e.forced_eos_token_id)),e.begin_suppress_tokens!==null){const s=t>1||e.forced_bos_token_id===null?t:t+1;n.push(new c_(e.begin_suppress_tokens,s))}return e.guidance_scale!==null&&e.guidance_scale>1&&n.push(new dE(e.guidance_scale)),e.temperature===0&&e.do_sample&&(he.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 hE(e.temperature)),r!==null&&n.extend(r),n}_prepare_generation_config(e,t,r=u_){const n={...this.config};for(const a of["decoder","generator","text_config"])a in n&&Object.assign(n,n[a]);const s=new r(n);return Object.assign(s,this.generation_config??{}),e&&Object.assign(s,e),t&&Object.assign(s,ht(t,Object.getOwnPropertyNames(s))),s}_get_stopping_criteria(e,t=null){const r=new fE;return e.max_length!==null&&r.push(new pE(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&r.push(new _E(e.eos_token_id)),t&&r.extend(t),r}_validate_model_class(){if(!this.can_generate){const e=[Yn.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,Yn.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,Yn.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,Yn.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),t=dn.get(this.constructor),r=new Set,n=this.config.model_type;for(const a of e){const o=a?.get(n);o&&r.add(o)}let s=`The current model class (${t}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw r.size>0&&(s+=` Please use the following class instead: ${[...r].join(", ")}`),Error(s)}}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:t,model_inputs:r,is_encoder_decoder:n}){return r.past_key_values=this.getPastKeyValues(t,r.past_key_values),r.input_ids=new q("int64",e.flat(),[e.length,1]),n||(r.attention_mask=Be([r.attention_mask,Et([r.attention_mask.dims[0],1])],1)),r.position_ids=null,r}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:r}){const n=ht(r,this.forward_params),s=this.main_input_name;if(s 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[s]=e;return{inputs_tensor:n[s],model_inputs:n,model_input_name:s}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:r,generation_config:n}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!t.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:a,pixel_values:o,attention_mask:i,...l}=t,u=await this._prepare_inputs_embeds(t);t={...l,...ht(u,["inputs_embeds","attention_mask"])}}let{last_hidden_state:s}=await Mr(this,t);if(n.guidance_scale!==null&&n.guidance_scale>1)s=Be([s,Xo(s,0)],0),"attention_mask"in t&&(t.attention_mask=Be([t.attention_mask,Ep(t.attention_mask)],0));else if(t.decoder_input_ids){const a=ei(t.decoder_input_ids).dims[0];if(a!==s.dims[0]){if(s.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${s.dims[0]}) than the decoder inputs (${a}).`);s=Be(Array.from({length:a},()=>s),0)}}return t.encoder_outputs=s,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:r,decoder_start_token_id:n,bos_token_id:s,generation_config:a}){let{decoder_input_ids:o,...i}=r;if(!(o instanceof q)){if(o)Array.isArray(o[0])||(o=Array.from({length:e},()=>o));else if(n??=s,this.config.model_type==="musicgen")o=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}`);o=n}else o=Array.from({length:e},()=>[n]);o=ei(o)}return r.decoder_attention_mask=kp(o),{input_ids:o,model_inputs:i}}async generate({inputs:e=null,generation_config:t=null,logits_processor:r=null,stopping_criteria:n=null,streamer:s=null,...a}){this._validate_model_class(),t=this._prepare_generation_config(t,a);let{inputs_tensor:o,model_inputs:i,model_input_name:l}=this._prepare_model_inputs({inputs:e,model_kwargs:a});const u=this.config.is_encoder_decoder;u&&("encoder_outputs"in i||(i=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:o,model_inputs:i,model_input_name:l,generation_config:t})));let h;u?{input_ids:h,model_inputs:i}=this._prepare_decoder_input_ids_for_generation({batch_size:i[l].dims.at(0),model_input_name:l,model_kwargs:i,decoder_start_token_id:t.decoder_start_token_id,bos_token_id:t.bos_token_id,generation_config:t}):h=i[l];let f=h.dims.at(-1);t.max_new_tokens!==null&&(t.max_length=f+t.max_new_tokens);const p=this._get_logits_processor(t,f,r),g=this._get_stopping_criteria(t,n),v=i[l].dims.at(0),w=_a.getSampler(t),M=new Array(v).fill(0),k=h.tolist();s&&s.put(k);let T,S={},E={};for(;;){if(i=this.prepare_inputs_for_generation(k,i,t),T=await this.forward(i),t.return_dict_in_generate)if(t.output_attentions){const Z=this.getAttentions(T);for(const W in Z)W in S||(S[W]=[]),S[W].push(Z[W])}else this._return_dict_in_generate_keys&&Object.assign(E,ht(T,this._return_dict_in_generate_keys));const b=T.logits.slice(null,-1,null).to("float32"),U=p(k,b),G=[];for(let Z=0;Z<U.dims.at(0);++Z){const W=U[Z],B=await w(W);for(const[O,$]of B){const ee=BigInt(O);M[Z]+=$,k[Z].push(ee),G.push([ee]);break}}if(s&&s.put(G),g(k).every(Z=>Z))break;i=this._update_model_kwargs_for_generation({generated_input_ids:G,outputs:T,model_inputs:i,is_encoder_decoder:u})}s&&s.end();const F=this.getPastKeyValues(T,i.past_key_values,!0),z=new q("int64",k.flat(),[k.length,k[0].length]);if(t.return_dict_in_generate)return{sequences:z,past_key_values:F,...S,...E};for(const b of Object.values(T))b.location==="gpu-buffer"&&b.dispose();return z}getPastKeyValues(e,t,r=!1){const n=Object.create(null);for(const s in e)if(s.startsWith("present")){const a=s.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present_recurrent","past_recurrent").replace("present","past_key_values"),o=s.includes("encoder");if(o&&t?n[a]=t[a]:n[a]=e[s],t&&(!o||r)){const i=t[a];i.location==="gpu-buffer"&&i.dispose()}}return n}getAttentions(e){const t={};for(const r of["cross_attentions","encoder_attentions","decoder_attentions"])for(const n in e)n.startsWith(r)&&(r in t||(t[r]=[]),t[r].push(e[n]));return t}addPastKeyValues(e,t){if(t)Object.assign(e,t);else{const r=this.sessions.decoder_model_merged??this.sessions.model,n=(e[this.main_input_name]??e.attention_mask)?.dims?.[0]??1,s=r?.config?.kv_cache_dtype??"float32",a=s==="float16"?ea.float16:ea.float32,o=o_(this.config,{batch_size:n});for(const i in o){const l=o[i].reduce((u,h)=>u*h,1);e[i]=new q(s,new a(l),o[i])}}}async encode_image({pixel_values:e}){return(await be(this.sessions.vision_encoder,{pixel_values:e})).image_features}async encode_text({input_ids:e}){return(await be(this.sessions.embed_tokens,{input_ids:e})).inputs_embeds}async encode_audio({audio_values:e}){return(await be(this.sessions.audio_encoder,{audio_values:e})).audio_features}};async function Ns(e,t){let{encoder_outputs:r,input_ids:n,decoder_input_ids:s,...a}=t;if(!r){const o=ht(t,e.sessions.model.inputNames);r=(await Mr(e,o)).last_hidden_state}return a.input_ids=s,a.encoder_hidden_states=r,e.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(a.encoder_attention_mask=t.attention_mask),await ar(e,a,!0)}async function Mr(e,t){const r=e.sessions.model,n=ht(t,r.inputNames);if(r.inputNames.includes("inputs_embeds")&&!n.inputs_embeds){if(!t.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");n.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}if(r.inputNames.includes("token_type_ids")&&!n.token_type_ids){if(!n.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");n.token_type_ids=Ep(n.input_ids)}if(r.inputNames.includes("pixel_mask")&&!n.pixel_mask){if(!n.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const s=n.pixel_values.dims;n.pixel_mask=Et([s[0],s[2],s[3]])}return await be(r,n)}async function bE(e,t){const r=await e.encode(t);return await e.decode(r)}async function ar(e,t,r=!1){const n=e.sessions[r?"decoder_model_merged":"model"],{past_key_values:s,...a}=t;if(n.inputNames.includes("use_cache_branch")&&(a.use_cache_branch=h_(!!s)),n.inputNames.includes("position_ids")&&a.attention_mask&&!a.position_ids){const i=["paligemma","gemma3_text","gemma3"].includes(e.config.model_type)?1:0;a.position_ids=kE(a,s,i)}e.addPastKeyValues(a,s);const o=ht(a,n.inputNames);return await be(n,o)}async function f_(e,{encode_function:t,merge_function:r,modality_input_name:n,modality_output_name:s,input_ids:a=null,attention_mask:o=null,position_ids:i=null,inputs_embeds:l=null,past_key_values:u=null,generation_config:h=null,logits_processor:f=null,...p}){const g=p[n];if(!l){if(l=await e.encode_text({input_ids:a,...p}),g&&a.dims[1]!==1){const w=await t({[n]:g,...p});({inputs_embeds:l,attention_mask:o}=r({[s]:w,inputs_embeds:l,input_ids:a,attention_mask:o}))}else if(u&&g&&a.dims[1]===1){const w=a.dims[1],M=Object.values(u)[0].dims.at(-2);o=Be([Et([a.dims[0],M]),o.slice(null,[o.dims[1]-w,o.dims[1]])],1)}}if(!i&&["qwen2_vl","qwen2_5_vl_text","qwen3_vl_text","qwen3_5_text","qwen3_5_moe_text"].includes(e.config.model_type)){const{image_grid_thw:w,video_grid_thw:M}=p;[i]=e.get_rope_index(a,w,M,o)}return await ar(e,{inputs_embeds:l,past_key_values:u,attention_mask:o,position_ids:i,generation_config:h,logits_processor:f},!0)}async function ME(e,t){return await f_(e,{...t,modality_input_name:"audio_values",modality_output_name:"audio_features",encode_function:e.encode_audio.bind(e),merge_function:e._merge_input_ids_with_audio_features.bind(e)})}async function xE(e,t){return await f_(e,{...t,modality_input_name:"pixel_values",modality_output_name:"image_features",encode_function:e.encode_image.bind(e),merge_function:e._merge_input_ids_with_image_features.bind(e)})}function p_(e,t=0){const[r,n]=e.dims,s=e.data,a=new BigInt64Array(s.length);for(let o=0;o<r;++o){const i=o*n;let l=BigInt(t);for(let u=0;u<n;++u){const h=i+u;s[h]===0n?a[h]=BigInt(1):(a[h]=l,l+=s[h])}}return{data:a,dims:e.dims}}function kE(e,t=null,r=0){const{input_ids:n,inputs_embeds:s,attention_mask:a}=e,{data:o,dims:i}=p_(a,r);let l=new q("int64",o,i);if(t){const u=-(n??s).dims.at(1);l=l.slice(null,[u,null])}return l}function ra(e,t,r,n){const s=r.past_key_values?Object.values(r.past_key_values)[0].dims.at(-2):0;if(!r.attention_mask){let a;for(const o of["input_ids","inputs_embeds","position_ids"])if(r[o]){a=r[o].dims;break}if(!a)throw new Error("attention_mask is not provided, and unable to infer its shape from model inputs.");r.attention_mask=Et([a[0],s+a[1]])}if(r.past_key_values){const{input_ids:a,attention_mask:o}=r;o&&o.dims[1]>a.dims[1]||s<a.dims[1]&&(r.input_ids=a.slice(null,[s,null]))}return r}function na(e,t,r,n){return r.past_key_values&&(t=t.map(s=>[s.at(-1)])),{...r,decoder_input_ids:ei(t)}}function Ds(e,...t){return e.config.is_encoder_decoder?na(e,...t):ra(e,...t)}function __({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:n,attention_mask:s}){const a=n.tolist().map(u=>u.reduce((h,f,p)=>(f==e&&h.push(p),h),[])),o=a.reduce((u,h)=>u+h.length,0),i=r.dims[0];if(o!==i)throw new Error(`Number of tokens and features do not match: tokens: ${o}, features ${i}`);let l=0;for(let u=0;u<a.length;++u){const h=a[u],f=t[u];for(let p=0;p<h.length;++p)f[h[p]].data.set(r[l++].data)}return{inputs_embeds:t,attention_mask:s}}function as({image_token_id:e,inputs_embeds:t,image_features:r,input_ids:n,attention_mask:s}){return __({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:n,attention_mask:s})}function m_({audio_token_id:e,inputs_embeds:t,audio_features:r,input_ids:n,attention_mask:s}){return __({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:n,attention_mask:s})}async function sr(e,t,r){return Object.fromEntries(await Promise.all(Object.keys(t).map(async n=>{const s=await ir(e,t[n],!1,r);return[n,s]})))}var Bi={};_n(Bi,{ASTForAudioClassification:()=>DE,ASTModel:()=>NE,ASTPreTrainedModel:()=>$i,AfmoeForCausalLM:()=>IE,AfmoeModel:()=>FE,AfmoePreTrainedModel:()=>Ri,AlbertForMaskedLM:()=>SE,AlbertForQuestionAnswering:()=>CE,AlbertForSequenceClassification:()=>EE,AlbertModel:()=>TE,AlbertPreTrainedModel:()=>os,ApertusForCausalLM:()=>AE,ApertusModel:()=>PE,ApertusPreTrainedModel:()=>zi,ArceeForCausalLM:()=>OE,ArceeModel:()=>LE,ArceePreTrainedModel:()=>Gi,BartForConditionalGeneration:()=>zE,BartForSequenceClassification:()=>RE,BartModel:()=>BE,BartPretrainedModel:()=>ma,BeitForImageClassification:()=>$E,BeitModel:()=>GE,BeitPreTrainedModel:()=>Vi,BertForMaskedLM:()=>UE,BertForQuestionAnswering:()=>qE,BertForSequenceClassification:()=>WE,BertForTokenClassification:()=>jE,BertModel:()=>VE,BertPreTrainedModel:()=>yn,BlenderbotForConditionalGeneration:()=>QE,BlenderbotModel:()=>HE,BlenderbotPreTrainedModel:()=>Ui,BlenderbotSmallForConditionalGeneration:()=>YE,BlenderbotSmallModel:()=>XE,BlenderbotSmallPreTrainedModel:()=>Wi,BloomForCausalLM:()=>KE,BloomModel:()=>JE,BloomPreTrainedModel:()=>ji,CLIPModel:()=>i2,CLIPPreTrainedModel:()=>jr,CLIPSegForImageSegmentation:()=>h2,CLIPSegModel:()=>d2,CLIPSegPreTrainedModel:()=>qi,CLIPTextModel:()=>l2,CLIPTextModelWithProjection:()=>M_,CLIPVisionModel:()=>c2,CLIPVisionModelWithProjection:()=>u2,CamembertForMaskedLM:()=>e2,CamembertForQuestionAnswering:()=>n2,CamembertForSequenceClassification:()=>t2,CamembertForTokenClassification:()=>r2,CamembertModel:()=>ZE,CamembertPreTrainedModel:()=>bn,ChatterboxModel:()=>w_,ChatterboxPreTrainedModel:()=>g_,ChineseCLIPModel:()=>a2,ChineseCLIPPreTrainedModel:()=>v_,ClapAudioModelWithProjection:()=>b_,ClapModel:()=>o2,ClapPreTrainedModel:()=>ga,ClapTextModelWithProjection:()=>y_,CodeGenForCausalLM:()=>p2,CodeGenModel:()=>f2,CodeGenPreTrainedModel:()=>Hi,Cohere2ForCausalLM:()=>w2,Cohere2Model:()=>g2,Cohere2PreTrainedModel:()=>Xi,CohereForCausalLM:()=>m2,CohereModel:()=>_2,CoherePreTrainedModel:()=>Qi,ConvBertForMaskedLM:()=>y2,ConvBertForQuestionAnswering:()=>x2,ConvBertForSequenceClassification:()=>b2,ConvBertForTokenClassification:()=>M2,ConvBertModel:()=>v2,ConvBertPreTrainedModel:()=>Mn,ConvNextForImageClassification:()=>T2,ConvNextModel:()=>k2,ConvNextPreTrainedModel:()=>Yi,ConvNextV2ForImageClassification:()=>C2,ConvNextV2Model:()=>E2,ConvNextV2PreTrainedModel:()=>Ji,DFineForObjectDetection:()=>F2,DFineModel:()=>A2,DFinePreTrainedModel:()=>Zi,DINOv3ConvNextModel:()=>tC,DINOv3ConvNextPreTrainedModel:()=>F_,DINOv3ViTModel:()=>rC,DINOv3ViTPreTrainedModel:()=>I_,DPTForDepthEstimation:()=>uC,DPTModel:()=>cC,DPTPreTrainedModel:()=>sl,DacDecoderModel:()=>E_,DacDecoderOutput:()=>k_,DacEncoderModel:()=>T_,DacEncoderOutput:()=>x_,DacModel:()=>I2,DacPreTrainedModel:()=>wa,DebertaForMaskedLM:()=>O2,DebertaForQuestionAnswering:()=>B2,DebertaForSequenceClassification:()=>N2,DebertaForTokenClassification:()=>D2,DebertaModel:()=>L2,DebertaPreTrainedModel:()=>xn,DebertaV2ForMaskedLM:()=>R2,DebertaV2ForQuestionAnswering:()=>V2,DebertaV2ForSequenceClassification:()=>G2,DebertaV2ForTokenClassification:()=>$2,DebertaV2Model:()=>z2,DebertaV2PreTrainedModel:()=>kn,DecisionTransformerModel:()=>U2,DecisionTransformerPreTrainedModel:()=>C_,DeiTForImageClassification:()=>j2,DeiTModel:()=>W2,DeiTPreTrainedModel:()=>el,DepthAnythingForDepthEstimation:()=>q2,DepthAnythingPreTrainedModel:()=>S_,DepthProForDepthEstimation:()=>H2,DepthProPreTrainedModel:()=>P_,DetrForObjectDetection:()=>X2,DetrForSegmentation:()=>Y2,DetrModel:()=>Q2,DetrObjectDetectionOutput:()=>tl,DetrPreTrainedModel:()=>va,DetrSegmentationOutput:()=>A_,Dinov2ForImageClassification:()=>K2,Dinov2Model:()=>J2,Dinov2PreTrainedModel:()=>rl,Dinov2WithRegistersForImageClassification:()=>eC,Dinov2WithRegistersModel:()=>Z2,Dinov2WithRegistersPreTrainedModel:()=>nl,DistilBertForMaskedLM:()=>iC,DistilBertForQuestionAnswering:()=>oC,DistilBertForSequenceClassification:()=>sC,DistilBertForTokenClassification:()=>aC,DistilBertModel:()=>nC,DistilBertPreTrainedModel:()=>Tn,DonutSwinModel:()=>lC,DonutSwinPreTrainedModel:()=>L_,EdgeTamModel:()=>qA,EfficientNetForImageClassification:()=>hC,EfficientNetModel:()=>dC,EfficientNetPreTrainedModel:()=>al,ElectraForMaskedLM:()=>pC,ElectraForQuestionAnswering:()=>gC,ElectraForSequenceClassification:()=>_C,ElectraForTokenClassification:()=>mC,ElectraModel:()=>fC,ElectraPreTrainedModel:()=>En,Ernie4_5ForCausalLM:()=>vC,Ernie4_5Model:()=>wC,Ernie4_5PretrainedModel:()=>ol,EsmForMaskedLM:()=>bC,EsmForSequenceClassification:()=>MC,EsmForTokenClassification:()=>xC,EsmModel:()=>yC,EsmPreTrainedModel:()=>ls,ExaoneForCausalLM:()=>TC,ExaoneModel:()=>kC,ExaonePreTrainedModel:()=>il,FalconForCausalLM:()=>CC,FalconH1ForCausalLM:()=>PC,FalconH1Model:()=>SC,FalconH1PreTrainedModel:()=>cl,FalconModel:()=>EC,FalconPreTrainedModel:()=>ll,FastViTForImageClassification:()=>FC,FastViTModel:()=>AC,FastViTPreTrainedModel:()=>ul,Florence2ForConditionalGeneration:()=>IC,Florence2PreTrainedModel:()=>O_,GLPNForDepthEstimation:()=>VC,GLPNModel:()=>$C,GLPNPreTrainedModel:()=>_l,GPT2LMHeadModel:()=>KC,GPT2Model:()=>JC,GPT2PreTrainedModel:()=>yl,GPTBigCodeForCausalLM:()=>WC,GPTBigCodeModel:()=>UC,GPTBigCodePreTrainedModel:()=>ml,GPTJForCausalLM:()=>eS,GPTJModel:()=>ZC,GPTJPreTrainedModel:()=>bl,GPTNeoForCausalLM:()=>qC,GPTNeoModel:()=>jC,GPTNeoPreTrainedModel:()=>gl,GPTNeoXForCausalLM:()=>QC,GPTNeoXModel:()=>HC,GPTNeoXPreTrainedModel:()=>wl,Gemma2ForCausalLM:()=>DC,Gemma2Model:()=>NC,Gemma2PreTrainedModel:()=>hl,Gemma3ForCausalLM:()=>zC,Gemma3Model:()=>BC,Gemma3PreTrainedModel:()=>fl,Gemma3nForConditionalGeneration:()=>D_,Gemma3nPreTrainedModel:()=>N_,GemmaForCausalLM:()=>OC,GemmaModel:()=>LC,GemmaPreTrainedModel:()=>dl,GlmForCausalLM:()=>GC,GlmModel:()=>RC,GlmPreTrainedModel:()=>pl,GptOssForCausalLM:()=>YC,GptOssModel:()=>XC,GptOssPreTrainedModel:()=>vl,GraniteForCausalLM:()=>rS,GraniteModel:()=>tS,GraniteMoeHybridForCausalLM:()=>sS,GraniteMoeHybridModel:()=>nS,GraniteMoeHybridPreTrainedModel:()=>xl,GranitePreTrainedModel:()=>Ml,GroundingDinoForObjectDetection:()=>aS,GroundingDinoPreTrainedModel:()=>B_,GroupViTModel:()=>oS,GroupViTPreTrainedModel:()=>z_,HeliumForCausalLM:()=>lS,HeliumModel:()=>iS,HeliumPreTrainedModel:()=>kl,HieraForImageClassification:()=>uS,HieraModel:()=>cS,HieraPreTrainedModel:()=>Tl,HubertForCTC:()=>gS,HubertForSequenceClassification:()=>wS,HubertModel:()=>mS,HubertPreTrainedModel:()=>_S,HunYuanDenseV1ForCausalLM:()=>yS,HunYuanDenseV1Model:()=>vS,HunYuanDenseV1PreTrainedModel:()=>El,IJepaForImageClassification:()=>xS,IJepaModel:()=>MS,IJepaPreTrainedModel:()=>Cl,Idefics3ForConditionalGeneration:()=>G_,Idefics3PreTrainedModel:()=>R_,JAISLMHeadModel:()=>TS,JAISModel:()=>kS,JAISPreTrainedModel:()=>Sl,JinaCLIPModel:()=>ES,JinaCLIPPreTrainedModel:()=>ya,JinaCLIPTextModel:()=>$_,JinaCLIPVisionModel:()=>CS,Lfm2ForCausalLM:()=>PS,Lfm2Model:()=>SS,Lfm2MoeForCausalLM:()=>FS,Lfm2MoeModel:()=>AS,Lfm2MoePreTrainedModel:()=>Al,Lfm2PreTrainedModel:()=>Pl,LiteWhisperForConditionalGeneration:()=>sI,Llama4ForCausalLM:()=>OS,Llama4PreTrainedModel:()=>V_,LlamaForCausalLM:()=>LS,LlamaModel:()=>IS,LlamaPreTrainedModel:()=>Fl,LlavaForConditionalGeneration:()=>sa,LlavaOnevisionForConditionalGeneration:()=>sa,LlavaPreTrainedModel:()=>U_,LlavaQwen2ForCausalLM:()=>DS,LongT5ForConditionalGeneration:()=>zS,LongT5Model:()=>BS,LongT5PreTrainedModel:()=>Il,M2M100ForConditionalGeneration:()=>GS,M2M100Model:()=>RS,M2M100PreTrainedModel:()=>Ll,MBartForCausalLM:()=>QS,MBartForConditionalGeneration:()=>qS,MBartForSequenceClassification:()=>HS,MBartModel:()=>jS,MBartPreTrainedModel:()=>cs,MPNetForMaskedLM:()=>IP,MPNetForQuestionAnswering:()=>NP,MPNetForSequenceClassification:()=>LP,MPNetForTokenClassification:()=>OP,MPNetModel:()=>FP,MPNetPreTrainedModel:()=>Cn,MT5ForConditionalGeneration:()=>RP,MT5Model:()=>zP,MT5PreTrainedModel:()=>Ul,MarianMTModel:()=>VS,MarianModel:()=>$S,MarianPreTrainedModel:()=>Ol,MaskFormerForInstanceSegmentation:()=>WS,MaskFormerModel:()=>US,MaskFormerPreTrainedModel:()=>Nl,Metric3DForDepthEstimation:()=>XS,Metric3DPreTrainedModel:()=>W_,Metric3Dv2ForDepthEstimation:()=>YS,Metric3Dv2PreTrainedModel:()=>j_,MgpstrForSceneTextRecognition:()=>JS,MgpstrModelOutput:()=>q_,MgpstrPreTrainedModel:()=>H_,MimiDecoderModel:()=>J_,MimiDecoderOutput:()=>X_,MimiEncoderModel:()=>Y_,MimiEncoderOutput:()=>Q_,MimiModel:()=>KS,MimiPreTrainedModel:()=>ba,MistralForCausalLM:()=>eP,MistralModel:()=>ZS,MistralPreTrainedModel:()=>Dl,MobileBertForMaskedLM:()=>rP,MobileBertForQuestionAnswering:()=>sP,MobileBertForSequenceClassification:()=>nP,MobileBertModel:()=>tP,MobileBertPreTrainedModel:()=>us,MobileLLMForCausalLM:()=>oP,MobileLLMModel:()=>aP,MobileLLMPreTrainedModel:()=>Bl,MobileNetV1ForImageClassification:()=>lP,MobileNetV1ForSemanticSegmentation:()=>cP,MobileNetV1Model:()=>iP,MobileNetV1PreTrainedModel:()=>Ma,MobileNetV2ForImageClassification:()=>dP,MobileNetV2ForSemanticSegmentation:()=>hP,MobileNetV2Model:()=>uP,MobileNetV2PreTrainedModel:()=>xa,MobileNetV3ForImageClassification:()=>pP,MobileNetV3ForSemanticSegmentation:()=>_P,MobileNetV3Model:()=>fP,MobileNetV3PreTrainedModel:()=>ka,MobileNetV4ForImageClassification:()=>gP,MobileNetV4ForSemanticSegmentation:()=>wP,MobileNetV4Model:()=>mP,MobileNetV4PreTrainedModel:()=>Ta,MobileViTForImageClassification:()=>yP,MobileViTModel:()=>vP,MobileViTPreTrainedModel:()=>zl,MobileViTV2ForImageClassification:()=>MP,MobileViTV2Model:()=>bP,MobileViTV2PreTrainedModel:()=>Rl,ModernBertDecoderForCausalLM:()=>SP,ModernBertDecoderModel:()=>CP,ModernBertDecoderPreTrainedModel:()=>Gl,ModernBertForMaskedLM:()=>kP,ModernBertForSequenceClassification:()=>TP,ModernBertForTokenClassification:()=>EP,ModernBertModel:()=>xP,ModernBertPreTrainedModel:()=>ds,Moondream1ForConditionalGeneration:()=>NS,MoonshineForConditionalGeneration:()=>AP,MoonshineModel:()=>PP,MoonshinePreTrainedModel:()=>$l,MptForCausalLM:()=>BP,MptModel:()=>DP,MptPreTrainedModel:()=>Vl,MultiModalityCausalLM:()=>Z_,MultiModalityPreTrainedModel:()=>K_,MusicgenForCausalLM:()=>$P,MusicgenForConditionalGeneration:()=>em,MusicgenModel:()=>GP,MusicgenPreTrainedModel:()=>Wl,NanoChatForCausalLM:()=>UP,NanoChatModel:()=>VP,NanoChatPreTrainedModel:()=>jl,NeoBertForMaskedLM:()=>jP,NeoBertForQuestionAnswering:()=>QP,NeoBertForSequenceClassification:()=>qP,NeoBertForTokenClassification:()=>HP,NeoBertModel:()=>WP,NeoBertPreTrainedModel:()=>Sn,NomicBertModel:()=>XP,NomicBertPreTrainedModel:()=>tm,OPTForCausalLM:()=>aA,OPTModel:()=>sA,OPTPreTrainedModel:()=>Yl,Olmo2ForCausalLM:()=>ZP,Olmo2Model:()=>KP,Olmo2PreTrainedModel:()=>Hl,Olmo3ForCausalLM:()=>tA,Olmo3Model:()=>eA,Olmo3PreTrainedModel:()=>Ql,OlmoForCausalLM:()=>JP,OlmoModel:()=>YP,OlmoPreTrainedModel:()=>ql,OpenELMForCausalLM:()=>nA,OpenELMModel:()=>rA,OpenELMPreTrainedModel:()=>Xl,OwlViTForObjectDetection:()=>cA,OwlViTModel:()=>lA,OwlViTPreTrainedModel:()=>Kl,Owlv2ForObjectDetection:()=>iA,Owlv2Model:()=>oA,Owlv2PreTrainedModel:()=>Jl,PaliGemmaForConditionalGeneration:()=>uA,PaliGemmaPreTrainedModel:()=>rm,ParakeetForCTC:()=>dA,ParakeetPreTrainedModel:()=>nm,PatchTSMixerForPrediction:()=>fA,PatchTSMixerModel:()=>hA,PatchTSMixerPreTrainedModel:()=>Zl,PatchTSTForPrediction:()=>_A,PatchTSTModel:()=>pA,PatchTSTPreTrainedModel:()=>ec,Phi3ForCausalLM:()=>vA,Phi3Model:()=>wA,Phi3PreTrainedModel:()=>rc,Phi3VForCausalLM:()=>am,Phi3VPreTrainedModel:()=>sm,PhiForCausalLM:()=>gA,PhiModel:()=>mA,PhiPreTrainedModel:()=>tc,PreTrainedModel:()=>P,PvtForImageClassification:()=>bA,PvtModel:()=>yA,PvtPreTrainedModel:()=>nc,PyAnnoteForAudioFrameClassification:()=>xA,PyAnnoteModel:()=>MA,PyAnnotePreTrainedModel:()=>sc,Qwen2ForCausalLM:()=>TA,Qwen2Model:()=>kA,Qwen2PreTrainedModel:()=>ac,Qwen2VLForConditionalGeneration:()=>im,Qwen2VLPreTrainedModel:()=>om,Qwen2_5_VLForConditionalGeneration:()=>lm,Qwen3ForCausalLM:()=>CA,Qwen3Model:()=>EA,Qwen3PreTrainedModel:()=>oc,Qwen3VLForConditionalGeneration:()=>cm,Qwen3_5ForConditionalGeneration:()=>Ea,Qwen3_5MoeForConditionalGeneration:()=>SA,RFDetrForObjectDetection:()=>IA,RFDetrModel:()=>FA,RFDetrObjectDetectionOutput:()=>um,RFDetrPreTrainedModel:()=>lc,RTDetrForObjectDetection:()=>P2,RTDetrModel:()=>S2,RTDetrObjectDetectionOutput:()=>is,RTDetrPreTrainedModel:()=>Ki,RTDetrV2ForObjectDetection:()=>WA,RTDetrV2Model:()=>UA,RTDetrV2ObjectDetectionOutput:()=>dm,RTDetrV2PreTrainedModel:()=>cc,ResNetForImageClassification:()=>AA,ResNetModel:()=>PA,ResNetPreTrainedModel:()=>ic,RoFormerForMaskedLM:()=>RA,RoFormerForQuestionAnswering:()=>VA,RoFormerForSequenceClassification:()=>GA,RoFormerForTokenClassification:()=>$A,RoFormerModel:()=>zA,RoFormerPreTrainedModel:()=>An,RobertaForMaskedLM:()=>OA,RobertaForQuestionAnswering:()=>BA,RobertaForSequenceClassification:()=>NA,RobertaForTokenClassification:()=>DA,RobertaModel:()=>LA,RobertaPreTrainedModel:()=>Pn,Sam2ImageSegmentationOutput:()=>pm,Sam2Model:()=>uc,Sam2PreTrainedModel:()=>_m,Sam3TrackerModel:()=>HA,SamImageSegmentationOutput:()=>hm,SamModel:()=>jA,SamPreTrainedModel:()=>fm,SapiensForDepthEstimation:()=>XA,SapiensForNormalEstimation:()=>YA,SapiensForSemanticSegmentation:()=>QA,SapiensPreTrainedModel:()=>Ca,SegformerForImageClassification:()=>KA,SegformerForSemanticSegmentation:()=>ZA,SegformerModel:()=>JA,SegformerPreTrainedModel:()=>Sa,SiglipModel:()=>eF,SiglipPreTrainedModel:()=>dc,SiglipTextModel:()=>mm,SiglipVisionModel:()=>tF,SmolLM3ForCausalLM:()=>nF,SmolLM3Model:()=>rF,SmolLM3PreTrainedModel:()=>hc,SmolVLMForConditionalGeneration:()=>bS,SnacDecoderModel:()=>wm,SnacEncoderModel:()=>gm,SnacModel:()=>sF,SnacPreTrainedModel:()=>Pa,SpeechT5ForSpeechToText:()=>oF,SpeechT5ForTextToSpeech:()=>iF,SpeechT5HifiGan:()=>lF,SpeechT5Model:()=>aF,SpeechT5PreTrainedModel:()=>Aa,SqueezeBertForMaskedLM:()=>uF,SqueezeBertForQuestionAnswering:()=>hF,SqueezeBertForSequenceClassification:()=>dF,SqueezeBertModel:()=>cF,SqueezeBertPreTrainedModel:()=>hs,StableLmForCausalLM:()=>pF,StableLmModel:()=>fF,StableLmPreTrainedModel:()=>fc,Starcoder2ForCausalLM:()=>mF,Starcoder2Model:()=>_F,Starcoder2PreTrainedModel:()=>pc,StyleTextToSpeech2Model:()=>gF,StyleTextToSpeech2PreTrainedModel:()=>vm,SupertonicForConditionalGeneration:()=>bm,SupertonicPreTrainedModel:()=>ym,Swin2SRForImageSuperResolution:()=>MF,Swin2SRModel:()=>bF,Swin2SRPreTrainedModel:()=>_c,SwinForImageClassification:()=>vF,SwinForSemanticSegmentation:()=>yF,SwinModel:()=>wF,SwinPreTrainedModel:()=>Fa,T5ForConditionalGeneration:()=>kF,T5Model:()=>xF,T5PreTrainedModel:()=>mc,TableTransformerForObjectDetection:()=>EF,TableTransformerModel:()=>TF,TableTransformerObjectDetectionOutput:()=>Mm,TableTransformerPreTrainedModel:()=>gc,TrOCRForCausalLM:()=>CF,TrOCRPreTrainedModel:()=>xm,UltravoxModel:()=>Tm,UltravoxPreTrainedModel:()=>km,UniSpeechForCTC:()=>AF,UniSpeechForSequenceClassification:()=>FF,UniSpeechModel:()=>PF,UniSpeechPreTrainedModel:()=>Ia,UniSpeechSatForAudioFrameClassification:()=>NF,UniSpeechSatForCTC:()=>LF,UniSpeechSatForSequenceClassification:()=>OF,UniSpeechSatModel:()=>IF,UniSpeechSatPreTrainedModel:()=>fs,VaultGemmaForCausalLM:()=>BF,VaultGemmaModel:()=>DF,VaultGemmaPreTrainedModel:()=>wc,ViTForImageClassification:()=>GF,ViTMAEModel:()=>$F,ViTMAEPreTrainedModel:()=>Em,ViTMSNForImageClassification:()=>UF,ViTMSNModel:()=>VF,ViTMSNPreTrainedModel:()=>yc,ViTModel:()=>RF,ViTPreTrainedModel:()=>vc,VisionEncoderDecoderModel:()=>zF,VitMatteForImageMatting:()=>WF,VitMattePreTrainedModel:()=>Cm,VitPoseForPoseEstimation:()=>jF,VitPosePreTrainedModel:()=>Sm,VitsModel:()=>qF,VitsModelOutput:()=>Pm,VitsPreTrainedModel:()=>Am,VoxtralForConditionalGeneration:()=>SF,Wav2Vec2BertForCTC:()=>QF,Wav2Vec2BertForSequenceClassification:()=>XF,Wav2Vec2BertModel:()=>HF,Wav2Vec2BertPreTrainedModel:()=>La,Wav2Vec2ForAudioFrameClassification:()=>pS,Wav2Vec2ForCTC:()=>hS,Wav2Vec2ForSequenceClassification:()=>fS,Wav2Vec2Model:()=>dS,Wav2Vec2PreTrainedModel:()=>xr,WavLMForAudioFrameClassification:()=>eI,WavLMForCTC:()=>JF,WavLMForSequenceClassification:()=>KF,WavLMForXVector:()=>ZF,WavLMModel:()=>YF,WavLMPreTrainedModel:()=>Fn,WeSpeakerResNetModel:()=>tI,WeSpeakerResNetPreTrainedModel:()=>Im,WhisperForConditionalGeneration:()=>Lm,WhisperModel:()=>nI,WhisperPreTrainedModel:()=>bc,XLMForQuestionAnswering:()=>cI,XLMForSequenceClassification:()=>iI,XLMForTokenClassification:()=>lI,XLMModel:()=>aI,XLMPreTrainedModel:()=>In,XLMRobertaForMaskedLM:()=>dI,XLMRobertaForQuestionAnswering:()=>pI,XLMRobertaForSequenceClassification:()=>hI,XLMRobertaForTokenClassification:()=>fI,XLMRobertaModel:()=>uI,XLMRobertaPreTrainedModel:()=>Ln,XLMWithLMHeadModel:()=>oI,XVectorOutput:()=>Fm,YolosForObjectDetection:()=>mI,YolosModel:()=>_I,YolosObjectDetectionOutput:()=>Om,YolosPreTrainedModel:()=>Mc,YoutuForCausalLM:()=>wI,YoutuModel:()=>gI,YoutuPreTrainedModel:()=>xc});var os=class extends P{},TE=class extends os{},EE=class extends os{async _call(e){return new se(await super._call(e))}},CE=class extends os{async _call(e){return new ot(await super._call(e))}},SE=class extends os{async _call(e){return new Ke(await super._call(e))}},zi=class extends P{},PE=class extends zi{},AE=class extends zi{},Ri=class extends P{},FE=class extends Ri{},IE=class extends Ri{},Gi=class extends P{},LE=class extends Gi{},OE=class extends Gi{},$i=class extends P{},NE=class extends $i{},DE=class extends $i{},ma=class extends P{},BE=class extends ma{},zE=class extends ma{},RE=class extends ma{async _call(e){return new se(await super._call(e))}},Vi=class extends P{},GE=class extends Vi{},$E=class extends Vi{async _call(e){return new se(await super._call(e))}},yn=class extends P{},VE=class extends yn{},UE=class extends yn{async _call(e){return new Ke(await super._call(e))}},WE=class extends yn{async _call(e){return new se(await super._call(e))}},jE=class extends yn{async _call(e){return new Xe(await super._call(e))}},qE=class extends yn{async _call(e){return new ot(await super._call(e))}},Ui=class extends P{},HE=class extends Ui{},QE=class extends Ui{},Wi=class extends P{},XE=class extends Wi{},YE=class extends Wi{},ji=class extends P{},JE=class extends ji{},KE=class extends ji{},bn=class extends P{},ZE=class extends bn{},e2=class extends bn{async _call(e){return new Ke(await super._call(e))}},t2=class extends bn{async _call(e){return new se(await super._call(e))}},r2=class extends bn{async _call(e){return new Xe(await super._call(e))}},n2=class extends bn{async _call(e){return new ot(await super._call(e))}},s2=4299n,jh=6561n,g_=class extends P{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"]},w_=class extends g_{async encode_speech(e){return be(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:t=null,audio_values:r=null,exaggeration:n=null,position_ids:s=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:i=null,logits_processor:l=null,audio_features:u=null,audio_tokens:h=null,speaker_embeddings:f=null,speaker_features:p=null,...g}){let v;if(!a){const M=this.sessions.embed_tokens.inputNames,k={input_ids:e};if(M.includes("exaggeration")){if(!(n instanceof q)){const T=e.dims[0];if(n==null)n=at([T],.5);else if(typeof n=="number")n=at([T],n);else if(Array.isArray(n))n=new q("float32",n,[T]);else throw new Error("Unsupported type for `exaggeration` input")}k.exaggeration=n}if(M.includes("position_ids")&&(k.position_ids=s),{inputs_embeds:a}=await be(this.sessions.embed_tokens,k),u&&h&&f&&p&&(v={audio_features:u,audio_tokens:h,speaker_embeddings:f,speaker_features:p}),v||r)v??=await this.encode_speech(r),a=Be([v.audio_features,a],1),t=Et([a.dims[0],a.dims[1]]);else{const T=a.dims[1];if(!o||T!==1)throw new Error("Incorrect state encountered during generation.");const S=Object.values(o)[0].dims.at(-2);t=Et([a.dims[0],S+T])}}return{...await ar(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,generation_config:i,logits_processor:l},!1),...v}}prepare_inputs_for_generation(e,t,r){if(!t.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(t.input_ids.dims[1]===1){const n=Array.from({length:e.length},(s,a)=>e[a].length-e[a].findLastIndex(o=>o==jh)-1);t.position_ids=new q("int64",n,[e.length,1])}else{const s=t.input_ids.tolist().map(a=>{let o=0;return a.map(i=>i>=jh?0:o++)});t.position_ids=new q("int64",s.flat(),t.input_ids.dims)}return t.input_ids.dims[1]===1&&(delete t.audio_values,delete t.audio_features,delete t.audio_tokens,delete t.speaker_embeddings,delete t.speaker_features),ra(this,e,t)}async generate(e){const{sequences:t,audio_tokens:r,speaker_embeddings:n,speaker_features:s}=await super.generate({...e,return_dict_in_generate:!0}),a=t.slice(null,[e.input_ids.dims[1],-1]),o=at([a.dims[0],3],s2),i=Be([r,a,o],1),{waveform:l}=await be(this.sessions.conditional_decoder,{speech_tokens:i,speaker_features:s,speaker_embeddings:n});return l}},v_=class extends P{},a2=class extends v_{},ga=class extends P{},o2=class extends ga{},y_=class extends ga{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},b_=class extends ga{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"audio_model"})}},jr=class extends P{},i2=class extends jr{},l2=class extends jr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},M_=class extends jr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},c2=class extends jr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},u2=class extends jr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},qi=class extends P{},d2=class extends qi{},h2=class extends qi{},Hi=class extends P{},f2=class extends Hi{},p2=class extends Hi{},Qi=class extends P{},_2=class extends Qi{},m2=class extends Qi{},Xi=class extends P{},g2=class extends Xi{},w2=class extends Xi{},Mn=class extends P{},v2=class extends Mn{},y2=class extends Mn{async _call(e){return new Ke(await super._call(e))}},b2=class extends Mn{async _call(e){return new se(await super._call(e))}},M2=class extends Mn{async _call(e){return new Xe(await super._call(e))}},x2=class extends Mn{async _call(e){return new ot(await super._call(e))}},Yi=class extends P{},k2=class extends Yi{},T2=class extends Yi{async _call(e){return new se(await super._call(e))}},Ji=class extends P{},E2=class extends Ji{},C2=class extends Ji{async _call(e){return new se(await super._call(e))}},Ki=class extends P{},S2=class extends Ki{},P2=class extends Ki{async _call(e){return new is(await super._call(e))}},is=class extends Qe{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Zi=class extends P{},A2=class extends Zi{},F2=class extends Zi{async _call(e){return new is(await super._call(e))}},x_=class extends Qe{constructor({audio_codes:e}){super(),this.audio_codes=e}},k_=class extends Qe{constructor({audio_values:e}){super(),this.audio_values=e}},wa=class extends P{main_input_name="input_values";forward_params=["input_values"]},I2=class extends wa{async encode(e){return new x_(await be(this.sessions.encoder_model,e))}async decode(e){return new k_(await be(this.sessions.decoder_model,e))}},T_=class extends wa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},E_=class extends wa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},xn=class extends P{},L2=class extends xn{},O2=class extends xn{async _call(e){return new Ke(await super._call(e))}},N2=class extends xn{async _call(e){return new se(await super._call(e))}},D2=class extends xn{async _call(e){return new Xe(await super._call(e))}},B2=class extends xn{async _call(e){return new ot(await super._call(e))}},kn=class extends P{},z2=class extends kn{},R2=class extends kn{async _call(e){return new Ke(await super._call(e))}},G2=class extends kn{async _call(e){return new se(await super._call(e))}},$2=class extends kn{async _call(e){return new Xe(await super._call(e))}},V2=class extends kn{async _call(e){return new ot(await super._call(e))}},C_=class extends P{},U2=class extends C_{},el=class extends P{},W2=class extends el{},j2=class extends el{async _call(e){return new se(await super._call(e))}},S_=class extends P{},q2=class extends S_{},P_=class extends P{},H2=class extends P_{},va=class extends P{},Q2=class extends va{},X2=class extends va{async _call(e){return new tl(await super._call(e))}},Y2=class extends va{async _call(e){return new A_(await super._call(e))}},tl=class extends Qe{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},A_=class extends Qe{constructor({logits:e,pred_boxes:t,pred_masks:r}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=r}},rl=class extends P{},J2=class extends rl{},K2=class extends rl{async _call(e){return new se(await super._call(e))}},nl=class extends P{},Z2=class extends nl{},eC=class extends nl{async _call(e){return new se(await super._call(e))}},F_=class extends P{},tC=class extends F_{},I_=class extends P{},rC=class extends I_{},Tn=class extends P{},nC=class extends Tn{},sC=class extends Tn{async _call(e){return new se(await super._call(e))}},aC=class extends Tn{async _call(e){return new Xe(await super._call(e))}},oC=class extends Tn{async _call(e){return new ot(await super._call(e))}},iC=class extends Tn{async _call(e){return new Ke(await super._call(e))}},L_=class extends P{},lC=class extends L_{},sl=class extends P{},cC=class extends sl{},uC=class extends sl{},al=class extends P{},dC=class extends al{},hC=class extends al{async _call(e){return new se(await super._call(e))}},En=class extends P{},fC=class extends En{},pC=class extends En{async _call(e){return new Ke(await super._call(e))}},_C=class extends En{async _call(e){return new se(await super._call(e))}},mC=class extends En{async _call(e){return new Xe(await super._call(e))}},gC=class extends En{async _call(e){return new ot(await super._call(e))}},ol=class extends P{},wC=class extends ol{},vC=class extends ol{},ls=class extends P{},yC=class extends ls{},bC=class extends ls{async _call(e){return new Ke(await super._call(e))}},MC=class extends ls{async _call(e){return new se(await super._call(e))}},xC=class extends ls{async _call(e){return new Xe(await super._call(e))}},il=class extends P{},kC=class extends il{},TC=class extends il{},ll=class extends P{},EC=class extends ll{},CC=class extends ll{},cl=class extends P{},SC=class extends cl{},PC=class extends cl{},ul=class extends P{},AC=class extends ul{},FC=class extends ul{async _call(e){return new se(await super._call(e))}},O_=class extends P{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"},IC=class extends O_{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:r,attention_mask:n}){return{inputs_embeds:Be([t,e],1),attention_mask:Be([Et(t.dims.slice(0,2)),n],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:r,attention_mask:n}){if(!e&&!t)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let s,a;return e&&(s=await this.encode_text({input_ids:e})),t&&(a=await this.encode_image({pixel_values:t})),s&&a?{inputs_embeds:r,attention_mask:n}=this._merge_input_ids_with_image_features({inputs_embeds:s,image_features:a,input_ids:e,attention_mask:n}):r=s||a,{inputs_embeds:r,attention_mask:n}}async forward({input_ids:e,pixel_values:t,attention_mask:r,decoder_input_ids:n,decoder_attention_mask:s,encoder_outputs:a,past_key_values:o,inputs_embeds:i,decoder_inputs_embeds:l}){if(i||({inputs_embeds:i,attention_mask:r}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:i,attention_mask:r})),!a){let{last_hidden_state:h}=await Mr(this,{inputs_embeds:i,attention_mask:r});a=h}if(!l){if(!n)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");l=await this.encode_text({input_ids:n})}return await ar(this,{inputs_embeds:l,attention_mask:s,encoder_attention_mask:r,encoder_hidden_states:a,past_key_values:o},!0)}},dl=class extends P{},LC=class extends dl{},OC=class extends dl{},hl=class extends P{},NC=class extends hl{},DC=class extends hl{},fl=class extends P{},BC=class extends fl{},zC=class extends fl{},N_=class extends P{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"]},D_=class extends N_{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,input_features:n=null,input_features_mask:s=null,position_ids:a=null,inputs_embeds:o=null,per_layer_inputs:i=null,past_key_values:l=null,generation_config:u=null,logits_processor:h=null,...f}){if((!o||!i)&&({inputs_embeds:o,per_layer_inputs:i}=await be(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(r){const{image_features:g}=await be(this.sessions.vision_encoder,{pixel_values:r});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:g,inputs_embeds:o,input_ids:e,attention_mask:t}))}if(n){const{audio_features:g}=await be(this.sessions.audio_encoder,{input_features:n,input_features_mask:s});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_audio_features({audio_features:g,inputs_embeds:o,input_ids:e,attention_mask:t}))}}return await ar(this,{inputs_embeds:o,per_layer_inputs:i,past_key_values:l,attention_mask:t,position_ids:a,generation_config:u,logits_processor:h},!0)}_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return as({image_token_id:this.config.image_token_id,...e,image_features:r})}_merge_input_ids_with_audio_features(e){const t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return m_({audio_token_id:this.config.audio_token_id,...e,audio_features:r})}},pl=class extends P{},RC=class extends pl{},GC=class extends pl{},_l=class extends P{},$C=class extends _l{},VC=class extends _l{},ml=class extends P{},UC=class extends ml{},WC=class extends ml{},gl=class extends P{},jC=class extends gl{},qC=class extends gl{},wl=class extends P{},HC=class extends wl{},QC=class extends wl{},vl=class extends P{},XC=class extends vl{},YC=class extends vl{},yl=class extends P{},JC=class extends yl{},KC=class extends yl{},bl=class extends P{},ZC=class extends bl{},eS=class extends bl{},Ml=class extends P{},tS=class extends Ml{},rS=class extends Ml{},xl=class extends P{},nS=class extends xl{},sS=class extends xl{},B_=class extends P{},aS=class extends B_{},z_=class extends P{},oS=class extends z_{},kl=class extends P{},iS=class extends kl{},lS=class extends kl{},Tl=class extends P{},cS=class extends Tl{},uS=class extends Tl{async _call(e){return new se(await super._call(e))}},xr=class extends P{},dS=class extends xr{},hS=class extends xr{async _call(e){return new Wr(await super._call(e))}},fS=class extends xr{async _call(e){return new se(await super._call(e))}},pS=class extends xr{async _call(e){return new Xe(await super._call(e))}},_S=class extends P{},mS=class extends xr{},gS=class extends xr{async _call(e){return new Wr(await super._call(e))}},wS=class extends xr{async _call(e){return new se(await super._call(e))}},El=class extends P{},vS=class extends El{},yS=class extends El{},R_=class extends P{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]},G_=class extends R_{async encode_image({pixel_values:e,pixel_attention_mask:t}){return(await be(this.sessions.vision_encoder,{pixel_values:e,pixel_attention_mask:t})).image_features}_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return as({image_token_id:this.config.image_token_id,...e,image_features:r})}},bS=class extends G_{},Cl=class extends P{},MS=class extends Cl{},xS=class extends Cl{async _call(e){return new se(await super._call(e))}},Sl=class extends P{},kS=class extends Sl{},TS=class extends Sl{},ya=class extends P{},ES=class extends ya{async forward(e){const t=!e.input_ids,r=!e.pixel_values;if(t&&r)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(t&&(e.input_ids=Et([e.pixel_values.dims[0],1])),r){const{image_size:l}=this.config.vision_config;e.pixel_values=at([0,3,l,l],0)}const{text_embeddings:n,image_embeddings:s,l2norm_text_embeddings:a,l2norm_image_embeddings:o}=await super.forward(e),i={};return t||(i.text_embeddings=n,i.l2norm_text_embeddings=a),r||(i.image_embeddings=s,i.l2norm_image_embeddings=o),i}},$_=class extends ya{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},CS=class extends ya{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Pl=class extends P{},SS=class extends Pl{},PS=class extends Pl{},Al=class extends P{},AS=class extends Al{},FS=class extends Al{},Fl=class extends P{},IS=class extends Fl{},LS=class extends Fl{},V_=class extends P{},OS=class extends V_{},U_=class extends P{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},sa=class extends U_{_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return as({image_token_id:this.config.image_token_index,...e,image_features:r})}},NS=class extends sa{},DS=class extends sa{},Il=class extends P{},BS=class extends Il{},zS=class extends Il{},Ll=class extends P{},RS=class extends Ll{},GS=class extends Ll{},Ol=class extends P{},$S=class extends Ol{},VS=class extends Ol{},Nl=class extends P{},US=class extends Nl{},WS=class extends Nl{},cs=class extends P{},jS=class extends cs{},qS=class extends cs{},HS=class extends cs{async _call(e){return new se(await super._call(e))}},QS=class extends cs{},W_=class extends P{},XS=class extends W_{},j_=class extends P{},YS=class extends j_{},q_=class extends Qe{constructor({char_logits:e,bpe_logits:t,wp_logits:r}){super(),this.char_logits=e,this.bpe_logits=t,this.wp_logits=r}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},H_=class extends P{},JS=class extends H_{async _call(e){return new q_(await super._call(e))}},Q_=class extends Qe{constructor({audio_codes:e}){super(),this.audio_codes=e}},X_=class extends Qe{constructor({audio_values:e}){super(),this.audio_values=e}},ba=class extends P{main_input_name="input_values";forward_params=["input_values"]},KS=class extends ba{async encode(e){return new Q_(await be(this.sessions.encoder_model,e))}async decode(e){return new X_(await be(this.sessions.decoder_model,e))}},Y_=class extends ba{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},J_=class extends ba{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Dl=class extends P{},ZS=class extends Dl{},eP=class extends Dl{},us=class extends P{},tP=class extends us{},rP=class extends us{async _call(e){return new Ke(await super._call(e))}},nP=class extends us{async _call(e){return new se(await super._call(e))}},sP=class extends us{async _call(e){return new ot(await super._call(e))}},Bl=class extends P{},aP=class extends Bl{},oP=class extends Bl{},Ma=class extends P{},iP=class extends Ma{},lP=class extends Ma{async _call(e){return new se(await super._call(e))}},cP=class extends Ma{},xa=class extends P{},uP=class extends xa{},dP=class extends xa{async _call(e){return new se(await super._call(e))}},hP=class extends xa{},ka=class extends P{},fP=class extends ka{},pP=class extends ka{async _call(e){return new se(await super._call(e))}},_P=class extends ka{},Ta=class extends P{},mP=class extends Ta{},gP=class extends Ta{async _call(e){return new se(await super._call(e))}},wP=class extends Ta{},zl=class extends P{},vP=class extends zl{},yP=class extends zl{async _call(e){return new se(await super._call(e))}},Rl=class extends P{},bP=class extends Rl{},MP=class extends Rl{async _call(e){return new se(await super._call(e))}},ds=class extends P{},xP=class extends ds{},kP=class extends ds{async _call(e){return new Ke(await super._call(e))}},TP=class extends ds{async _call(e){return new se(await super._call(e))}},EP=class extends ds{async _call(e){return new Xe(await super._call(e))}},Gl=class extends P{},CP=class extends Gl{},SP=class extends Gl{},$l=class extends P{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},PP=class extends $l{},AP=class extends $l{},Cn=class extends P{},FP=class extends Cn{},IP=class extends Cn{async _call(e){return new Ke(await super._call(e))}},LP=class extends Cn{async _call(e){return new se(await super._call(e))}},OP=class extends Cn{async _call(e){return new Xe(await super._call(e))}},NP=class extends Cn{async _call(e){return new ot(await super._call(e))}},Vl=class extends P{},DP=class extends Vl{},BP=class extends Vl{},Ul=class extends P{},zP=class extends Ul{},RP=class extends Ul{},K_=class extends P{},Z_=class extends K_{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){const t=this._generation_mode??"text";let r;if(t==="text"||!e.past_key_values){const i=this.sessions.prepare_inputs_embeds,l=ht(e,i.inputNames);r=await be(i,l)}else{const i=this.sessions.gen_img_embeds,l=ht({image_ids:e.input_ids},i.inputNames);r=await be(i,l)}const n={...e,...r},s=await ar(this,n),a=this.sessions[t==="text"?"lm_head":"gen_head"];if(!a)throw new Error(`Unable to find "${a}" generation head`);const o=await be(a,ht(s,a.inputNames));return{...r,...s,...o}}prepare_inputs_for_generation(e,t,r){const n=!!t.past_key_values;return r.guidance_scale!==null&&r.guidance_scale>1&&(n?t.input_ids=Be([t.input_ids,t.input_ids],0):(t.input_ids=Be([t.input_ids,Xo(t.input_ids,BigInt(r.pad_token_id))],0),t.attention_mask=Be([t.attention_mask,Xo(t.attention_mask,0n)],0))),(n||!t.pixel_values)&&(t.pixel_values=at([0,0,3,384,384],1)),n&&(t.images_seq_mask=new q("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),t.images_emb_mask=new q("bool",new Array(0).fill(!1),[1,1,0])),t}async generate(e){return this._generation_mode="text",super.generate(e)}async generate_images(e){this._generation_mode="image";const t=(e.inputs??e[this.main_input_name]).dims[1],n=(await super.generate(e)).slice(null,[t,null]),s=this.sessions.image_decode,{decoded_image:a}=await be(s,{generated_tokens:n}),o=a.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),i=[];for(const l of o){const u=Rr.fromTensor(l);i.push(u)}return i}},Wl=class extends P{},GP=class extends Wl{},$P=class extends Wl{},em=class extends P{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){const[t,r]=e.dims,n=this.config.decoder.num_codebooks,s=r-n;let a=0;for(let l=0;l<e.size;++l){if(e.data[l]==this.config.decoder.pad_token_id)continue;const u=l%r,h=Math.floor(l/r)%n,f=u-h;f>0&&f<=s&&(e.data[a++]=e.data[l])}const o=Math.floor(t/n),i=a/(o*n);return new q(e.type,e.data.slice(0,a),[o,n,i])}prepare_inputs_for_generation(e,t,r){const n=BigInt(this.config.decoder.pad_token_id);let s=structuredClone(e);for(let a=0;a<s.length;++a)for(let o=0;o<s[a].length;++o)a%this.config.decoder.num_codebooks>=o&&(s[a][o]=n);return r.guidance_scale!==null&&r.guidance_scale>1&&(s=s.concat(s)),na(this,s,t)}async generate(e){const t=await super.generate(e),r=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:n}=await be(this.sessions.encodec_decode,{audio_codes:r});return n}},jl=class extends P{},VP=class extends jl{},UP=class extends jl{},Sn=class extends P{},WP=class extends Sn{},jP=class extends Sn{async _call(e){return new Ke(await super._call(e))}},qP=class extends Sn{async _call(e){return new se(await super._call(e))}},HP=class extends Sn{async _call(e){return new Xe(await super._call(e))}},QP=class extends Sn{async _call(e){return new ot(await super._call(e))}},tm=class extends P{},XP=class extends tm{},ql=class extends P{},YP=class extends ql{},JP=class extends ql{},Hl=class extends P{},KP=class extends Hl{},ZP=class extends Hl{},Ql=class extends P{},eA=class extends Ql{},tA=class extends Ql{},Xl=class extends P{},rA=class extends Xl{},nA=class extends Xl{},Yl=class extends P{},sA=class extends Yl{},aA=class extends Yl{},Jl=class extends P{},oA=class extends Jl{},iA=class extends Jl{},Kl=class extends P{},lA=class extends Kl{},cA=class extends Kl{},rm=class extends P{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},uA=class extends rm{_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return as({image_token_id:this.config.image_token_index,...e,image_features:r})}},nm=class extends P{},dA=class extends nm{async _call(e){return new Wr(await super._call(e))}},Zl=class extends P{},hA=class extends Zl{},fA=class extends Zl{},ec=class extends P{},pA=class extends ec{},_A=class extends ec{},tc=class extends P{},mA=class extends tc{},gA=class extends tc{},rc=class extends P{},wA=class extends rc{},vA=class extends rc{},sm=class extends P{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},am=class extends sm{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,image_sizes:n=null,position_ids:s=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:i=null,logits_processor:l=null,...u}){if(!a){let f;if(r&&e.dims[1]!==1){if(!n)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:f}=await be(this.sessions.vision_encoder,{pixel_values:r,image_sizes:n}))}else{const p=this.config.normalized_config.hidden_size;f=new q("float32",[],[0,p])}({inputs_embeds:a}=await be(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:f}))}return await ar(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,position_ids:s,generation_config:i,logits_processor:l},!1)}},nc=class extends P{},yA=class extends nc{},bA=class extends nc{async _call(e){return new se(await super._call(e))}},sc=class extends P{},MA=class extends sc{},xA=class extends sc{async _call(e){return new Xe(await super._call(e))}},ac=class extends P{},kA=class extends ac{},TA=class extends ac{},om=class extends P{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},im=class extends om{image_grid_thw_name="grid_thw";get_rope_index(e,t,r,n){const{vision_config:s,image_token_id:a,video_token_id:o,vision_start_token_id:i}=this.config,l=s.spatial_merge_size??2,u=[];if(t||r){let h=e.tolist();n||(n=kp(e));const f=n.tolist(),p=Array.from({length:3},k=>Array.from({length:e.dims[0]},T=>Array.from({length:e.dims[1]},S=>1))),g=t?t.tolist():[],v=r?r.tolist():[];let w=0,M=0;for(let k=0;k<h.length;++k){const T=h[k].filter((X,A)=>f[k][A]==1),E=T.reduce((X,A,L)=>(A==i&&X.push(L),X),[]).map(X=>T[X+1]),F=E.filter(X=>X==a).length,z=E.filter(X=>X==o).length;let b=[],U=0,G=F,H=z;for(let X=0;X<E.length;++X){const A=T.findIndex((ut,We)=>We>U&&ut==a),L=T.findIndex((ut,We)=>We>U&&ut==o),D=G>0&&A!==-1?A:T.length+1,J=H>0&&L!==-1?L:T.length+1;let ie,xe,Fe,ct;D<J?([xe,Fe,ct]=g[w],++w,--G,ie=D):([xe,Fe,ct]=v[M],++M,--H,ie=J);const[$e,ze,Ve]=[Number(xe),Math.floor(Number(Fe)/l),Math.floor(Number(ct)/l)],ve=ie-U,de=b.length>0?He(b.at(-1))[0]+1:0;b.push(Array.from({length:3*ve},(ut,We)=>de+We%ve));const Ue=ve+de,pe=$e*ze*Ve,we=Array.from({length:pe},(ut,We)=>Ue+Math.floor(We/(ze*Ve))),ur=Array.from({length:pe},(ut,We)=>Ue+Math.floor(We/Ve)%ze),kr=Array.from({length:pe},(ut,We)=>Ue+We%Ve);b.push([we,ur,kr].flat()),U=ie+pe}if(U<T.length){const X=b.length>0?He(b.at(-1))[0]+1:0,A=T.length-U;b.push(Array.from({length:3*A},(L,D)=>X+D%A))}const Z=b.reduce((X,A)=>X+A.length,0),W=new Array(Z);let B=0;for(let X=0;X<3;++X)for(let A=0;A<b.length;++A){const L=b[A],D=L.length/3;for(let J=X*D;J<(X+1)*D;++J)W[B++]=L[J]}let O=0;const $=f[k];for(let X=0;X<$.length;++X)if($[X]==1){for(let A=0;A<3;++A)p[A][k][X]=W[A*Z/3+O];++O}const ee=He(W)[0];u.push(ee+1-h[k].length)}return[new q("int64",p.flat(1/0),[3,e.dims[0],e.dims[1]]),new q("int64",u,[u.length,1])]}else if(n){const{data:h,dims:f}=p_(n),p=BigInt64Array.from({length:3*h.length},(v,w)=>h[w%h.length]),g=Array.from({length:f[0]},(v,w)=>He(h.subarray(f[1]*w,f[1]*(w+1)))[0]+1n+BigInt(f[1]));return[new q("int64",p,[3,...f]),new q("int64",g,[g.length,1])]}else{const[h,f]=e.dims,p=BigInt64Array.from({length:3*h*f},(g,v)=>BigInt(Math.floor(v%f/h)));return[new q("int64",p,[3,...e.dims]),Tp([h,1])]}}async encode_image({pixel_values:e,image_grid_thw:t}){return(await be(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:t})).image_features}_merge_input_ids_with_image_features(e){return as({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,t,r){if(t.attention_mask&&!t.position_ids)if(!t.past_key_values)[t.position_ids,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);else{t.pixel_values=null;const n=BigInt(Object.values(t.past_key_values)[0].dims.at(-2)),s=t.rope_deltas.map(a=>n+a);t.position_ids=vn([s,s,s],0)}return t}},lm=class extends im{image_grid_thw_name="image_grid_thw"},oc=class extends P{},EA=class extends oc{},CA=class extends oc{},cm=class extends lm{},Ea=class extends cm{},SA=class extends Ea{},ic=class extends P{},PA=class extends ic{},AA=class extends ic{async _call(e){return new se(await super._call(e))}},lc=class extends P{},FA=class extends lc{},IA=class extends lc{async _call(e){return new um(await super._call(e))}},um=class extends is{},Pn=class extends P{},LA=class extends Pn{},OA=class extends Pn{async _call(e){return new Ke(await super._call(e))}},NA=class extends Pn{async _call(e){return new se(await super._call(e))}},DA=class extends Pn{async _call(e){return new Xe(await super._call(e))}},BA=class extends Pn{async _call(e){return new ot(await super._call(e))}},An=class extends P{},zA=class extends An{},RA=class extends An{async _call(e){return new Ke(await super._call(e))}},GA=class extends An{async _call(e){return new se(await super._call(e))}},$A=class extends An{async _call(e){return new Xe(await super._call(e))}},VA=class extends An{async _call(e){return new ot(await super._call(e))}},cc=class extends P{},UA=class extends cc{},WA=class extends cc{async _call(e){return new dm(await super._call(e))}},dm=class extends is{},hm=class extends Qe{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},fm=class extends P{},jA=class extends fm{async get_image_embeddings({pixel_values:e}){return await Mr(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??=Et(e.input_points.dims.slice(0,-1));const t={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(t.input_points=e.input_points),e.input_labels&&(t.input_labels=e.input_labels),e.input_boxes&&(t.input_boxes=e.input_boxes),await be(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new hm(await super._call(e))}},pm=class extends Qe{constructor({iou_scores:e,pred_masks:t,object_score_logits:r}){super(),this.iou_scores=e,this.pred_masks=t,this.object_score_logits=r}},_m=class extends P{},uc=class extends _m{async get_image_embeddings({pixel_values:e}){return await Mr(this,{pixel_values:e})}async forward(e){const{num_feature_levels:t}=this.config.vision_config;if(Array.from({length:t},(a,o)=>`image_embeddings.${o}`).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.");const a=e.input_points.dims;e.input_labels??=Et(a.slice(0,-1)),e.input_boxes??=at([a[0],0,4],0)}else if(e.input_boxes){const a=e.input_boxes.dims;e.input_labels=at([a[0],a[1],0],-1n),e.input_points=at([a[0],1,0,2],0)}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");const n=this.sessions.prompt_encoder_mask_decoder,s=ht(e,n.inputNames);return await be(n,s)}async _call(e){return new pm(await super._call(e))}},qA=class extends uc{},HA=class extends uc{},Ca=class extends P{},QA=class extends Ca{},XA=class extends Ca{},YA=class extends Ca{},Sa=class extends P{},JA=class extends Sa{},KA=class extends Sa{},ZA=class extends Sa{},dc=class extends P{},eF=class extends dc{},mm=class extends dc{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},tF=class extends jr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},hc=class extends P{},rF=class extends hc{},nF=class extends hc{},Pa=class extends P{main_input_name="input_values";forward_params=["input_values"]},sF=class extends Pa{async encode(e){return await be(this.sessions.encoder_model,e)}async decode(e){return await be(this.sessions.decoder_model,e)}},gm=class extends Pa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},wm=class extends Pa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Aa=class extends P{},aF=class extends Aa{},oF=class extends Aa{},iF=class extends Aa{async generate_speech(e,t,{threshold:r=.5,minlenratio:n=0,maxlenratio:s=20,vocoder:a=null}={}){const o={input_ids:e},{encoder_outputs:i,encoder_attention_mask:l}=await Mr(this,o),u=i.dims[1]/this.config.reduction_factor,h=Math.floor(u*s),f=Math.floor(u*n),p=this.config.num_mel_bins;let g=[],v=null,w=null,M=0;for(;;){++M;const S=h_(!!w);let E;w?E=w.output_sequence_out:E=new q("float32",new Float32Array(p),[1,1,p]);let F={use_cache_branch:S,output_sequence:E,encoder_attention_mask:l,speaker_embeddings:t,encoder_hidden_states:i};this.addPastKeyValues(F,v),w=await be(this.sessions.decoder_model_merged,F),v=this.getPastKeyValues(w,v);const{prob:z,spectrum:b}=w;if(g.push(b),M>=f&&(Array.from(z.data).filter(U=>U>=r).length>0||M>=h))break}const k=Be(g),{waveform:T}=await be(a.sessions.model,{spectrogram:k});return{spectrogram:k,waveform:T}}},lF=class extends P{main_input_name="spectrogram"},hs=class extends P{},cF=class extends hs{},uF=class extends hs{async _call(e){return new Ke(await super._call(e))}},dF=class extends hs{async _call(e){return new se(await super._call(e))}},hF=class extends hs{async _call(e){return new ot(await super._call(e))}},fc=class extends P{},fF=class extends fc{},pF=class extends fc{},pc=class extends P{},_F=class extends pc{},mF=class extends pc{},vm=class extends P{},gF=class extends vm{},ym=class extends P{},bm=class extends ym{async generate_speech({input_ids:e,attention_mask:t,style:r,num_inference_steps:n=5,speed:s=1.05}){const{sampling_rate:a,chunk_compress_factor:o,base_chunk_size:i,latent_dim:l}=this.config,{last_hidden_state:u,durations:h}=await be(this.sessions.text_encoder,{input_ids:e,attention_mask:t,style:r}),f=h.div(s).mul_(a),p=i*o,g=f.data,v=Int32Array.from(g,G=>Math.ceil(G/p)),w=Math.max(...v),M=e.dims[0],k=new BigInt64Array(M*w);for(let G=0;G<M;++G)k.fill(1n,G*w,G*w+v[G]);const T=new q("int64",k,[M,w]),S=l*o,E=S*w;let F=Kx([M,S,w]);const z=F.data;for(let G=0;G<M;++G)if(v[G]!==w)for(let H=0;H<S;++H)z.fill(0,G*E+H*w+v[G],G*E+(H+1)*w);const b=at([M],n);for(let G=0;G<n;++G){const H=at([M],G);({denoised_latents:F}=await be(this.sessions.latent_denoiser,{style:r,noisy_latents:F,latent_mask:T,encoder_outputs:u,attention_mask:t,timestep:H,num_inference_steps:b}))}const{waveform:U}=await be(this.sessions.voice_decoder,{latents:F});return{waveform:U,durations:f}}},Fa=class extends P{},wF=class extends Fa{},vF=class extends Fa{async _call(e){return new se(await super._call(e))}},yF=class extends Fa{},_c=class extends P{},bF=class extends _c{},MF=class extends _c{},mc=class extends P{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]},xF=class extends mc{},kF=class extends mc{},gc=class extends P{},TF=class extends gc{},EF=class extends gc{async _call(e){return new Mm(await super._call(e))}},Mm=class extends tl{},xm=class extends P{},CF=class extends xm{},km=class extends P{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},Tm=class extends km{_merge_input_ids_with_audio_features(e){const t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return m_({audio_token_id:this.config.ignore_index??this.config.audio_token_id,...e,audio_features:r})}},SF=class extends Tm{},Ia=class extends P{},PF=class extends Ia{},AF=class extends Ia{async _call(e){return new Wr(await super._call(e))}},FF=class extends Ia{async _call(e){return new se(await super._call(e))}},fs=class extends P{},IF=class extends fs{},LF=class extends fs{async _call(e){return new Wr(await super._call(e))}},OF=class extends fs{async _call(e){return new se(await super._call(e))}},NF=class extends fs{async _call(e){return new Xe(await super._call(e))}},wc=class extends P{},DF=class extends wc{},BF=class extends wc{},zF=class extends P{main_input_name="pixel_values";forward_params=["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"]},vc=class extends P{},RF=class extends vc{},GF=class extends vc{async _call(e){return new se(await super._call(e))}},Em=class extends P{},$F=class extends Em{},yc=class extends P{},VF=class extends yc{},UF=class extends yc{async _call(e){return new se(await super._call(e))}},Cm=class extends P{},WF=class extends Cm{async _call(e){return new tE(await super._call(e))}},Sm=class extends P{},jF=class extends Sm{},Pm=class extends Qe{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}},Am=class extends P{},qF=class extends Am{async _call(e){return new Pm(await super._call(e))}},La=class extends P{},HF=class extends La{},QF=class extends La{async _call(e){return new Wr(await super._call(e))}},XF=class extends La{async _call(e){return new se(await super._call(e))}},Fm=class extends Qe{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},Fn=class extends P{},YF=class extends Fn{},JF=class extends Fn{async _call(e){return new Wr(await super._call(e))}},KF=class extends Fn{async _call(e){return new se(await super._call(e))}},ZF=class extends Fn{async _call(e){return new Fm(await super._call(e))}},eI=class extends Fn{async _call(e){return new Xe(await super._call(e))}},Im=class extends P{},tI=class extends Im{},rI=class extends u_{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},bc=class extends P{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]},nI=class extends bc{},Lm=class extends bc{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,rI)}_retrieve_init_tokens(e){const t=[e.decoder_start_token_id];let r=e.language;const n=e.task;if(e.is_multilingual){r||(he.warn("No language specified - defaulting to English (en)."),r="en");const a=`<|${q1(r)}|>`;t.push(e.lang_to_id[a]),t.push(e.task_to_id[n??"transcribe"])}else if(r||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&&t.at(-1)!==e.no_timestamps_token_id?t.push(e.no_timestamps_token_id):e.return_timestamps&&t.at(-1)===e.no_timestamps_token_id&&(he.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter(s=>s!=null)}async generate({inputs:e=null,generation_config:t=null,logits_processor:r=null,stopping_criteria:n=null,...s}){t=this._prepare_generation_config(t,s);const a=s.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(r??=new Zo,r.push(new aE(t,a))),t.begin_suppress_tokens&&(r??=new Zo,r.push(new c_(t.begin_suppress_tokens,a.length))),t.return_token_timestamps){if(!t.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");t.task==="translate"&&he.warn("Token-level timestamps may not be reliable for task 'translate'."),t.output_attentions=!0,t.return_dict_in_generate=!0}const o=await super.generate({inputs:e,generation_config:t,logits_processor:r,decoder_input_ids:a,...s});return t.return_token_timestamps&&(o.token_timestamps=this._extract_token_timestamps(o,t.alignment_heads,t.num_frames)),o}_extract_token_timestamps(e,t,r=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`.");r==null&&he.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 s=this.config.median_filter_width;s===void 0&&(he.warn("Model config has no `median_filter_width`, using default value of 7."),s=7);const a=e.cross_attentions,o=Array.from({length:this.config.decoder_layers},(v,w)=>Be(a.map(M=>M[w]),2)),i=vn(t.map(([v,w])=>{if(v>=o.length)throw new Error(`Layer index ${v} is out of bounds for cross attentions (length ${o.length}).`);return r?o[v].slice(null,w,null,[0,r]):o[v].slice(null,w)})).transpose(1,0,2,3),[l,u]=Jx(i,-2,0,!0),h=i.clone();for(let v=0;v<h.dims[0];++v){const w=h[v];for(let M=0;M<w.dims[0];++M){const k=w[M],T=l[v][M][0].data,S=u[v][M][0].data;for(let E=0;E<k.dims[0];++E){let F=k[E].data;for(let z=0;z<F.length;++z)F[z]=(F[z]-S[z])/T[z];F.set(Fx(F,s))}}}const f=[Ti(h,1)],p=e.sequences.dims,g=new q("float32",new Float32Array(p[0]*p[1]),p);for(let v=0;v<p[0];++v){const w=f[v].neg().squeeze_(0),[M,k]=Lx(w.tolist()),T=Array.from({length:M.length-1},(F,z)=>M[z+1]-M[z]),S=Nt([1],T).map(F=>!!F),E=[];for(let F=0;F<S.length;++F)S[F]&&E.push(k[F]*n);g[v].data.set(E,1)}return g}},sI=class extends Lm{},In=class extends P{},aI=class extends In{},oI=class extends In{async _call(e){return new Ke(await super._call(e))}},iI=class extends In{async _call(e){return new se(await super._call(e))}},lI=class extends In{async _call(e){return new Xe(await super._call(e))}},cI=class extends In{async _call(e){return new ot(await super._call(e))}},Ln=class extends P{},uI=class extends Ln{},dI=class extends Ln{async _call(e){return new Ke(await super._call(e))}},hI=class extends Ln{async _call(e){return new se(await super._call(e))}},fI=class extends Ln{async _call(e){return new Xe(await super._call(e))}},pI=class extends Ln{async _call(e){return new ot(await super._call(e))}},Mc=class extends P{},_I=class extends Mc{},mI=class extends Mc{async _call(e){return new Om(await super._call(e))}},Om=class extends Qe{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},xc=class extends P{},gI=class extends xc{},wI=class extends xc{},vI=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"]]),yI=new Map([["t5","T5Model"],["longt5","LongT5Model"],["mt5","MT5Model"],["bart","BartModel"],["mbart","MBartModel"],["marian","MarianModel"],["whisper","WhisperModel"],["m2m_100","M2M100Model"],["blenderbot","BlenderbotModel"],["blenderbot-small","BlenderbotSmallModel"]]),bI=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),MI=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"]]),Nm=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"]]),Dm=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),Bm=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),zm=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"]]),Rm=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"]]),Gm=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),$m=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"]]),xI=new Map([["multi_modality","MultiModalityCausalLM"]]),Vm=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"]]),Um=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"]]),Wm=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),jm=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"]]),qm=new Map([["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"]]),kI=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),Hm=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"]]),Qm=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),Xm=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),on=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),Ym=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),Jm=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),Km=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),Zm=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),eg=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),tg=new Map([["wavlm","WavLMForXVector"]]),rg=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),ng=new Map([["vitmatte","VitMatteForImageMatting"]]),TI=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),sg=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),ag=new Map([["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),og=new Map([["sapiens","SapiensForNormalEstimation"]]),ig=new Map([["vitpose","VitPoseForPoseEstimation"]]),lg=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),cg=[[vI,V.EncoderOnly],[yI,V.EncoderDecoder],[MI,V.DecoderOnlyWithoutHead],[bI,V.AutoEncoder],[zm,V.EncoderOnly],[Rm,V.EncoderOnly],[Gm,V.Seq2Seq],[Nm,V.Seq2Seq],[$m,V.DecoderOnly],[xI,V.MultiModality],[Vm,V.EncoderOnly],[Um,V.EncoderOnly],[Wm,V.Vision2Seq],[jm,V.ImageTextToText],[qm,V.AudioTextToText],[Hm,V.EncoderOnly],[on,V.EncoderOnly],[Jm,V.EncoderOnly],[Ym,V.EncoderOnly],[ng,V.EncoderOnly],[TI,V.EncoderOnly],[sg,V.EncoderOnly],[ag,V.EncoderOnly],[og,V.EncoderOnly],[ig,V.EncoderOnly],[Qm,V.EncoderOnly],[Xm,V.EncoderOnly],[Km,V.MaskGeneration],[Zm,V.EncoderOnly],[eg,V.EncoderOnly],[Dm,V.Seq2Seq],[Bm,V.EncoderOnly],[tg,V.EncoderOnly],[rg,V.EncoderOnly],[lg,V.EncoderOnly]];for(const[e,t]of cg)for(const r of e.values()){fn.set(r,t);const n=Bi[r];dn.set(n,r),Di.set(r,n)}var EI=[["MusicgenForConditionalGeneration",em,V.Musicgen],["Phi3VForCausalLM",am,V.Phi3V],["CLIPTextModelWithProjection",M_,V.EncoderOnly],["SiglipTextModel",mm,V.EncoderOnly],["JinaCLIPTextModel",$_,V.EncoderOnly],["ClapTextModelWithProjection",y_,V.EncoderOnly],["ClapAudioModelWithProjection",b_,V.EncoderOnly],["DacEncoderModel",T_,V.EncoderOnly],["DacDecoderModel",E_,V.EncoderOnly],["MimiEncoderModel",Y_,V.EncoderOnly],["MimiDecoderModel",J_,V.EncoderOnly],["SnacEncoderModel",gm,V.EncoderOnly],["SnacDecoderModel",wm,V.EncoderOnly],["Gemma3nForConditionalGeneration",D_,V.ImageAudioTextToText],["SupertonicForConditionalGeneration",bm,V.Supertonic],["ChatterboxModel",w_,V.Chatterbox]];for(const[e,t,r]of EI)fn.set(e,r),dn.set(t,e),Di.set(e,t);var ug=new Map([["modnet",on],["birefnet",on],["isnet",on],["ben",on]]);for(const[e,t]of ug.entries())t.set(e,"PreTrainedModel"),fn.set(e,V.EncoderOnly),Di.set(e,P);fn.set("PreTrainedModel",V.EncoderOnly);dn.set(P,"PreTrainedModel");var ke={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:zm,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:Rm,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:Dm,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:Bm,MODEL_FOR_MASKED_LM_MAPPING_NAMES:Vm,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:Um,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:Hm,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:on,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:Ym,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:Jm,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:Qm,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:Xm,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:Km,MODEL_FOR_CTC_MAPPING_NAMES:Zm,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:eg,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:tg,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:rg,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:kI,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:ng,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:sg,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:ag,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:og,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:ig,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:lg,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:jm,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:qm,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:Gm,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:Nm,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:$m,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:Wm};yE(ke);var Te=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:n=null,local_files_only:s=!1,revision:a="main",model_file_name:o=null,subfolder:i="onnx",device:l=null,dtype:u=null,use_external_data_format:h=null,session_options:f={}}={}){const p={progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a,model_file_name:o,subfolder:i,device:l,dtype:u,use_external_data_format:h,session_options:f};if(p.config=await i_.from_pretrained(e,p),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const g=p.config.model_type;for(const v of this.MODEL_CLASS_MAPPINGS){let w=v.get(g);if(!w){for(const M of v.values())if(M[0]===g){w=M;break}if(!w)continue}return await Bi[w].from_pretrained(e,p)}if(this.BASE_IF_FAIL)return ug.has(g)||he.warn(`Unknown model class "${g}", attempting to construct from base class.`),await P.from_pretrained(e,p);throw Error(`Unsupported model type: ${g}`)}};(class extends Te{static MODEL_CLASS_MAPPINGS=cg.map(e=>e[0]);static BASE_IF_FAIL=!0});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]});var On=class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]};(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_MASKED_LM_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_CTC_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]});(class extends Te{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]});var CI=e=>e>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,dg=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},qh=Ae.IS_PROCESS_AVAILABLE?e=>process.stdout.write(e):e=>console.log(e),cr=class extends dg{constructor(e,{skip_prompt:t=!1,callback_function:r=null,token_callback_function:n=null,skip_special_tokens:s=!0,decode_kwargs:a={},...o}={}){super(),this.tokenizer=e,this.skip_prompt=t,this.callback_function=r??qh,this.token_callback_function=n,this.decode_kwargs={skip_special_tokens:s,...a,...o},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");const t=this.next_tokens_are_prompt;if(t&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;const r=e[0];if(this.token_callback_function?.(r),r.length===1&&this.special_ids.has(r[0])){if(this.decode_kwargs.skip_special_tokens)return;if(this.token_cache.length>0){const i=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len);this.on_finalized_text(i,!1),this.token_cache=[],this.print_len=0}const a=this.tokenizer.decode(r,this.decode_kwargs);this.on_finalized_text(a,!1);return}this.token_cache=Nt(this.token_cache,r);const n=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let s;t||n.endsWith(`
30
+ `)?(s=n.slice(this.print_len),this.token_cache=[],this.print_len=0):n.length>0&&CI(n.charCodeAt(n.length-1))?(s=n.slice(this.print_len),this.print_len+=s.length):(s=n.slice(this.print_len,n.lastIndexOf(" ")+1),this.print_len+=s.length),this.on_finalized_text(s,!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,t){e.length>0&&this.callback_function?.(e),t&&this.callback_function===qh&&Ae.IS_PROCESS_AVAILABLE&&this.callback_function?.(`
31
+ `)}};const SI=[{id:"Qwen3.5-2B",name:"Qwen 3.5",type:["reasoning","image-input"],provider:"Local",parameters:"2B",maxTokens:8192,contextLength:32768},{id:"Qwen3.5-4B",name:"Qwen 3.5 4B",type:["reasoning","image-input"],provider:"Local",parameters:"4B",maxTokens:8192,contextLength:32768},{id:"GPT-OSS-20B",name:"GPT-OSS 20B",type:["reasoning"],provider:"Local",parameters:"20B",maxTokens:8192,contextLength:32768},{id:"Llama-3.2",name:"Llama-3.2",type:[""],provider:"Local",parameters:"1B",maxTokens:8192,contextLength:131072},{id:"Janus-Pro",name:"Janus-Pro",type:["image-input","image-output"],provider:"Local",parameters:"1B",maxTokens:4096,contextLength:4096},{id:"Phi-3.5",name:"Phi-3.5",type:[""],provider:"Local",parameters:"3.8B",maxTokens:8192,contextLength:131072},{id:"SmoLlm",name:"SmoLlm",type:[""],provider:"Local",parameters:"1.7B",maxTokens:4096,contextLength:8192},{id:"Deepseek-R1",name:"Deepseek-R1",type:["reasoning"],provider:"Local",parameters:"1.5B",maxTokens:8192,contextLength:65536},{id:"Zyphra-ZR1",name:"Zyphra-ZR1",type:["reasoning"],provider:"Local",parameters:"1.5B",maxTokens:8192,contextLength:4096},{id:"MusicGen",name:"MusicGen",type:["music"],path:"/musicgen",provider:"Local",parameters:"300M",maxTokens:4096,contextLength:4096},{id:"Voice",name:"Voice",type:["conversational"],path:"/conversational",provider:"Local",parameters:null,maxTokens:4096,contextLength:4096},{id:"API",name:"API",provider:"Local",parameters:null,maxTokens:8192,contextLength:8192}];var PI={localModels:SI};self.onerror=(e,t,r,n,s)=>(console.error("Worker global error:",{message:e,source:t,lineno:r,colno:n,error:s}),self.postMessage({status:"error",data:`Worker initialization error: ${e}`}),!0);self.onunhandledrejection=e=>{console.error("Worker unhandled rejection:",e.reason),self.postMessage({status:"error",data:`Worker unhandled rejection: ${e.reason}`})};console.log("Worker: Starting imports...");console.log("Worker: Transformers imported successfully");console.log("Worker: ModelIDs imported successfully");const AI=e=>PI.localModels.find(r=>r.id===e)?.parameters||null,ti="/imagine ",FI=4096,II=2048;let je=null,Bs=!1,Jt=FI,Pe=.7,Ct=!1;async function LI(){try{const e=await navigator.gpu.requestAdapter();if(!e)throw new Error("WebGPU is not supported (no adapter found)");Ct=e.features.has("shader-f16"),self.postMessage({status:"success",data:Ct})}catch(e){self.postMessage({status:"error",data:e.toString()})}}class aa{static model_id="onnx-community/Janus-Pro-1B-ONNX";static processor=null;static model=null;static async getInstance(t=null){return this.processor??=Ni.from_pretrained(this.model_id,{progress_callback:t}),this.model??=Z_.from_pretrained(this.model_id,{dtype:Ct?{prepare_inputs_embeds:"q4",language_model:"q4f16",lm_head:"fp16",gen_head:"fp16",gen_img_embeds:"fp16",image_decode:"fp32"}:{prepare_inputs_embeds:"fp32",language_model:"q4",lm_head:"fp32",gen_head:"fp32",gen_img_embeds:"fp32",image_decode:"fp32"},device:{prepare_inputs_embeds:"wasm",language_model:"webgpu",lm_head:"webgpu",gen_head:"webgpu",gen_img_embeds:"webgpu",image_decode:"webgpu"},progress_callback:t}),Promise.all([this.processor,this.model])}static reset(){this.processor=null,this.model=null}}class hn{static model_id="HuggingFaceTB/SmolLM2-1.7B-Instruct";static tokenizer=null;static model=null;static past_key_values_cache=null;static async getInstance(t=null){return this.tokenizer??=Ee.from_pretrained(this.model_id,{progress_callback:t}),this.model??=On.from_pretrained(this.model_id,{dtype:"q4f16",device:"webgpu",progress_callback:t}),Promise.all([this.tokenizer,this.model])}static reset(){this.past_key_values_cache=null,this.tokenizer=null,this.model=null}}class Zn{static model_id="onnx-community/Phi-3.5-mini-instruct-onnx-web";static instance=null;static past_key_values_cache=null;static async getInstance(t=null){if(this.instance)return this.instance;const r=Ee.from_pretrained(this.model_id,{progress_callback:t}),n=On.from_pretrained(this.model_id,{dtype:Ct?"q4f16":"q4",device:"webgpu",use_external_data_format:!0,progress_callback:t});return this.instance=await Promise.all([r,n]),this.instance}static reset(){this.past_key_values_cache=null,this.instance=null}}class es{static model_id="onnx-community/Llama-3.2-1B-Instruct-q4f16";static instance=null;static past_key_values_cache=null;static async getInstance(t=null){if(this.instance)return this.instance;const r=Ee.from_pretrained(this.model_id,{progress_callback:t}),n=On.from_pretrained(this.model_id,{dtype:Ct?"q4f16":"q4",device:"webgpu",progress_callback:t});return this.instance=await Promise.all([r,n]),this.instance}static reset(){this.past_key_values_cache=null,this.instance=null}}class ts{static model_id="onnx-community/DeepSeek-R1-Distill-Qwen-1.5B-ONNX";static instance=null;static past_key_values_cache=null;static async getInstance(t=null){if(this.instance)return this.instance;const r=Ee.from_pretrained(this.model_id,{progress_callback:t}),n=On.from_pretrained(this.model_id,{dtype:Ct?"q4f16":"q4",device:"webgpu",progress_callback:t});return this.instance=await Promise.all([r,n]),this.instance}static reset(){this.past_key_values_cache=null,this.instance=null}}class oa{static model_id="onnx-community/ZR1-1.5B-ONNX";static instance=null;static past_key_values_cache=null;static async getInstance(t=null){if(this.instance)return this.instance;const r=Ee.from_pretrained(this.model_id,{progress_callback:t}),n=On.from_pretrained(this.model_id,{dtype:Ct?"q4f16":"q4",device:"webgpu",progress_callback:t});return this.instance=await Promise.all([r,n]),this.instance}static reset(){this.past_key_values_cache=null,this.instance=null}}class ia{static model_id="onnx-community/Qwen3.5-4B-ONNX";static processor=null;static model=null;static async getInstance(t=null){return this.processor??=Ni.from_pretrained(this.model_id,{progress_callback:t}),this.model??=Ea.from_pretrained(this.model_id,{dtype:{embed_tokens:"q4",vision_encoder:Ct?"fp16":"fp32",decoder_model_merged:Ct?"q4f16":"q4"},device:"webgpu",progress_callback:t}),Promise.all([this.processor,this.model])}static reset(){this.processor=null,this.model=null}}class la{static model_id="onnx-community/Qwen3.5-2B-ONNX";static processor=null;static model=null;static async getInstance(t=null){return this.processor??=Ni.from_pretrained(this.model_id,{progress_callback:t}),this.model??=Ea.from_pretrained(this.model_id,{dtype:{embed_tokens:"q4",vision_encoder:Ct?"fp16":"fp32",decoder_model_merged:Ct?"q4f16":"q4"},device:"webgpu",progress_callback:t}),Promise.all([this.processor,this.model])}static reset(){this.processor=null,this.model=null}}function OI(){const e=/<\|(start|end|message|channel|constrain|call|return)\|>/g;let t="",r="",n="idle",s="",a="",o=!1;function i(l){if(!l)return{thinkingDelta:"",answerDelta:""};t+=l;const u={thinkingDelta:"",answerDelta:""},h=s.length,f=a.length;let p=0;e.lastIndex=0;let g;const v=[];for(;(g=e.exec(t))!==null;)v.push({name:g[1],index:g.index,length:g[0].length});if(v.length>0&&(o=!0),!o&&t.length>0)return a+=t,t="",u.answerDelta=a.slice(f),u;for(const w of v){const M=t.slice(p,w.index);n==="content"&&r==="analysis"?s+=M:n==="content"&&r==="final"?a+=M:n==="channel"&&M.length>0&&(r=M.trim().toLowerCase().split(/\s/)[0]||""),w.name==="start"?(n="idle",r=""):w.name==="channel"?(n="channel",r=""):w.name==="constrain"?n="constrain":w.name==="message"?n="content":(w.name==="end"||w.name==="return"||w.name==="call")&&(n="idle",r=""),p=w.index+w.length}if(n==="channel"&&p<t.length){const M=t.slice(p).match(/^\s*(\w+)/);M&&(r=M[1].toLowerCase(),p+=M[0].length)}else if(n==="content"&&p<t.length){const w=t.slice(p);r==="analysis"?s+=w:r==="final"&&(a+=w),p=t.length}return t=t.slice(p),e.lastIndex=0,u.thinkingDelta=s.slice(h),u.answerDelta=a.slice(f),u}return{parse:i,getThinking:()=>s,getAnswer:()=>a}}class ca{static model_id="onnx-community/gpt-oss-20b-ONNX";static instance=null;static async getInstance(t=null){if(this.instance)return this.instance;const r=await Ee.from_pretrained(this.model_id,{progress_callback:t}),n=await On.from_pretrained(this.model_id,{dtype:Ct?"q4f16":"q4",device:"webgpu",progress_callback:t});return this.instance={tokenizer:r,model:n},this.instance}static reset(){this.instance=null}}class NI extends dg{constructor(t,r){super(),this.total=t,this.on_progress=r,this.count=null,this.start_time=null}put(t){if(this.count===null){this.count=0,this.start_time=performance.now();return}const r=++this.count/this.total;this.on_progress({count:this.count,total:this.total,progress:r,time:performance.now()-this.start_time})}end(){}}const St=new mE;async function DI(e){e.find(s=>s.role==="system")?.content;const t=e.filter(s=>s.role!=="system").at(-1);self.postMessage({status:"start"});const[r,n]=await aa.getInstance();if(t.content.startsWith(ti)){const a=[{role:"<|User|>",content:t.content.replace(ti,"")}],o=await r(a,{chat_template:"text_to_image"}),i=p=>{self.postMessage({status:"image-update",...p})},l=r.num_image_tokens,u=new NI(l,i),f=await(await n.generate_images({...o,min_new_tokens:l,max_new_tokens:l,do_sample:!0,streamer:u}))[0].toBlob();self.postMessage({status:"image-update",blob:f})}else{const s=await r(t.image?[{role:"<|User|>",content:"<image_placeholder>\\n"+t.content,images:[t.image]}]:[{role:"<|System|>",content:"You are a helpful assistant. Answer the user's questions in a concise manner."},{role:"<|User|>",content:t.content}]);let a,o=0,i;const l=()=>{a??=performance.now(),o++>0&&(i=o/(performance.now()-a)*1e3)},u=f=>{self.postMessage({status:"text-update",output:f,tps:i,numTokens:o})},h=new cr(r.tokenizer,{skip_prompt:!0,skip_special_tokens:!0,callback_function:u,token_callback_function:l});await n.generate({...s,max_new_tokens:Jt,do_sample:Pe>0,...Pe>0&&{temperature:Pe},streamer:h,stopping_criteria:St})}self.postMessage({status:"complete"})}async function BI(e){self.postMessage({status:"start"});const[t,r]=await hn.getInstance(),n=t.apply_chat_template(e,{add_generation_prompt:!0,return_dict:!0});let s,a=0,o;const i=()=>{s??=performance.now(),a++>0&&(o=a/(performance.now()-s)*1e3)},l=p=>{self.postMessage({status:"update",output:p,tps:o,numTokens:a})},u=new cr(t,{skip_prompt:!0,skip_special_tokens:!0,callback_function:l,token_callback_function:i}),{past_key_values:h,sequences:f}=await r.generate({...n,past_key_values:hn.past_key_values_cache,do_sample:Pe>0,...Pe>0&&{temperature:Pe},max_new_tokens:Jt,streamer:u,stopping_criteria:St,return_dict_in_generate:!0});hn.past_key_values_cache=h,self.postMessage({status:"complete"})}async function zI(e){self.postMessage({status:"start"});const[t,r]=await Zn.getInstance(),n=e.find(w=>w.role==="system")?.content||"You are a helpful assistant. Answer the user's questions in a concise manner.",s=e.filter(w=>w.role!=="system"),a=[{role:"user",content:`IMPORTANT INSTRUCTION: ${n}. You must follow this instruction for all your responses.`},...s],o=t.apply_chat_template(a,{add_generation_prompt:!0,return_dict:!0});let i,l=0,u;const h=()=>{i??=performance.now(),l++>0&&(u=l/(performance.now()-i)*1e3)},f=w=>{self.postMessage({status:"text-update",output:w,tps:u,numTokens:l})},p=new cr(t,{skip_prompt:!0,skip_special_tokens:!0,callback_function:f,token_callback_function:h}),{past_key_values:g,sequences:v}=await r.generate({...o,do_sample:Pe>0,...Pe>0&&{temperature:Pe},max_new_tokens:Jt,streamer:p,stopping_criteria:St,return_dict_in_generate:!0});Zn.past_key_values_cache=g,self.postMessage({status:"complete"})}async function RI(e){self.postMessage({status:"start"});const[t,r]=await es.getInstance(),n=t.apply_chat_template(e,{add_generation_prompt:!0,return_dict:!0});let s,a=0,o;const i=()=>{s??=performance.now(),a++>0&&(o=a/(performance.now()-s)*1e3)},l=p=>{self.postMessage({status:"text-update",output:p,tps:o,numTokens:a})},u=new cr(t,{skip_prompt:!0,skip_special_tokens:!0,callback_function:l,token_callback_function:i}),{past_key_values:h,sequences:f}=await r.generate({...n,do_sample:Pe>0,...Pe>0&&{temperature:Pe},max_new_tokens:Jt,streamer:u,stopping_criteria:St,return_dict_in_generate:!0});es.past_key_values_cache=h,self.postMessage({status:"complete"})}async function GI(e){self.postMessage({status:"start"});const[t,r]=await ts.getInstance(),n=e.find(T=>T.role==="system")?.content||"You are a helpful assistant. Answer the user's questions in a concise manner.",s=e.filter(T=>T.role!=="system"),a=[{role:"user",content:`IMPORTANT INSTRUCTION: ${n}. You must follow this instruction for all your responses.`},...s],o=t.apply_chat_template(a,{add_generation_prompt:!0,return_dict:!0}),[i,l]=t.encode("<think></think>",{add_special_tokens:!1});let u="thinking",h,f=0,p;const g=T=>{h??=performance.now(),f++>0&&(p=f/(performance.now()-h)*1e3),T[0]==l&&(u="answering")},v=T=>{self.postMessage({status:"text-update",output:T,tps:p,numTokens:f,state:u})},w=new cr(t,{skip_prompt:!0,skip_special_tokens:!0,callback_function:v,token_callback_function:g}),{past_key_values:M,sequences:k}=await r.generate({...o,do_sample:Pe>0,...Pe>0&&{temperature:Pe},max_new_tokens:Jt,streamer:w,stopping_criteria:St,return_dict_in_generate:!0});ts.past_key_values_cache=M,self.postMessage({status:"complete"})}async function $I(e){self.postMessage({status:"start"});const[t,r]=await oa.getInstance(),n=t.apply_chat_template(e,{add_generation_prompt:!0,return_dict:!0}),[s,a]=t.encode("<think></think>",{add_special_tokens:!1});let o="thinking",i,l=0,u;const h=w=>{i??=performance.now(),l++>0&&(u=l/(performance.now()-i)*1e3),w[0]==a&&(o="answering")},f=w=>{self.postMessage({status:"text-update",output:w,tps:u,numTokens:l,state:o})},p=new cr(t,{skip_prompt:!0,skip_special_tokens:!0,callback_function:f,token_callback_function:h}),{past_key_values:g,sequences:v}=await r.generate({...n,do_sample:Pe>0,...Pe>0&&{temperature:Pe},max_new_tokens:Jt,streamer:p,stopping_criteria:St,return_dict_in_generate:!0});self.postMessage({status:"complete"})}async function VI(e){self.postMessage({status:"start"});try{const[t,r]=await ia.getInstance(),{tokenizer:n}=t,s=e.at(-1),a=s.image&&s.role==="user";let o;if(a){const S=e.map(z=>z.image&&z.role==="user"?{role:z.role,content:[{type:"image"},{type:"text",text:z.content}]}:{role:z.role,content:z.content}),E=t.apply_chat_template(S,{add_generation_prompt:!0}),F=await Rr.read(s.image).then(z=>z.resize(448,448));o=await t(E,F)}else o=n.apply_chat_template(e,{add_generation_prompt:!0,return_dict:!0});const i="<think>",l="</think>";let u=!1,h=!1,f,p=0,g;const v=()=>{f??=performance.now(),p++>0&&(g=p/(performance.now()-f)*1e3)};let w="";const M=S=>{if(w+=S,!u&&w.includes(i)){u=!0;const E=w.slice(w.indexOf(i)+i.length);w="",E&&self.postMessage({status:"thinking",content:E,tps:g,numTokens:p});return}if(u&&!h){if(w.includes(l)){h=!0;const E=w.slice(0,w.indexOf(l));E&&self.postMessage({status:"thinking",content:E,tps:g,numTokens:p});const F=w.slice(w.indexOf(l)+l.length);w="",F.trim()&&self.postMessage({status:"text-update",output:F,tps:g,numTokens:p,state:"answering"});return}self.postMessage({status:"thinking",content:S,tps:g,numTokens:p}),w="";return}self.postMessage({status:"text-update",output:S,tps:g,numTokens:p,state:h?"answering":void 0}),w=""},k=new cr(n,{skip_prompt:!0,skip_special_tokens:!0,callback_function:M,token_callback_function:v}),T=await r.generate({...o,past_key_values:null,max_new_tokens:Jt,do_sample:Pe>0,...Pe>0&&{temperature:Pe},streamer:k,stopping_criteria:St,return_dict_in_generate:!0});console.log("[Worker] Qwen3.5-4B generation done, output length:",T?.sequences?.dims?.[1]??T?.length??"unknown","input length:",o?.input_ids?.dims?.[1]??"unknown"),self.postMessage({status:"complete"})}catch(t){console.error("Qwen3.5-4B generation error:",t),self.postMessage({status:"complete",error:t?.message||"Generation failed"})}}async function UI(e){self.postMessage({status:"start"});try{const[t,r]=await la.getInstance(),{tokenizer:n}=t,s=e.at(-1),a=s.image&&s.role==="user";let o;if(a){const k=e.map(E=>E.image&&E.role==="user"?{role:E.role,content:[{type:"image"},{type:"text",text:E.content}]}:{role:E.role,content:E.content}),T=t.apply_chat_template(k,{add_generation_prompt:!0}),S=await Rr.read(s.image).then(E=>E.resize(448,448));o=await t(T,S)}else o=n.apply_chat_template(e,{add_generation_prompt:!0,return_dict:!0});const[i,l]=n.encode("<think></think>",{add_special_tokens:!1});let u="thinking",h,f=0,p;const g=k=>{h??=performance.now(),f++>0&&(p=f/(performance.now()-h)*1e3),k[0]==l&&(u="answering")},v=k=>{self.postMessage({status:"text-update",output:k,tps:p,numTokens:f,state:u})},w=new cr(n,{skip_prompt:!0,skip_special_tokens:!0,callback_function:v,token_callback_function:g}),M=await r.generate({...o,past_key_values:null,max_new_tokens:Jt,do_sample:Pe>0,...Pe>0&&{temperature:Pe},streamer:w,stopping_criteria:St,return_dict_in_generate:!0});console.log("[Worker] Qwen3.5-2B generation done, output length:",M?.sequences?.dims?.[1]??M?.length??"unknown","input length:",o?.input_ids?.dims?.[1]??"unknown"),self.postMessage({status:"complete"})}catch(t){console.error("Qwen3.5-2B generation error:",t),self.postMessage({status:"complete",error:t?.message||"Generation failed"})}}async function WI(e){self.postMessage({status:"start"});try{const{tokenizer:t,model:r}=await ca.getInstance(),n=OI(),s=t.apply_chat_template(e,{add_generation_prompt:!0,return_dict:!0}),a=Math.min(Jt,II);let o,i=0,l;const u=()=>{o??=performance.now(),i++>0&&(l=i/(performance.now()-o)*1e3)},h=p=>{const{thinkingDelta:g,answerDelta:v}=n.parse(p);g.length>0&&self.postMessage({status:"thinking",content:g,tps:l,numTokens:i}),v.length>0&&self.postMessage({status:"text-update",output:v,tps:l,numTokens:i,state:"answering"})},f=new cr(t,{skip_prompt:!0,skip_special_tokens:!1,callback_function:h,token_callback_function:u});await r.generate({...s,do_sample:Pe>0,...Pe>0&&{temperature:Pe},max_new_tokens:a,streamer:f,stopping_criteria:St,return_dict_in_generate:!0}),self.postMessage({status:"complete"})}catch(t){console.error("GPT-OSS-20B generation error:",t),self.postMessage({status:"complete",error:t?.message||"Generation failed (possible GPU memory issue)"})}}async function jI(e){console.log(`[Worker] Generating with model: ${je}, ${e.length} messages`),console.log("[Worker] Messages:",e.map(r=>({role:r.role,contentLen:r.content?.length??0,contentPreview:(r.content||"").slice(0,80)}))),St.reset();const t=e.at(-1);if((je==="SmoLlm"||je==="Phi-3.5"||je==="Llama-3.2"||je==="Deepseek-R1"||je==="Zyphra-ZR1"||je==="Qwen3.5-4B"||je==="Qwen3.5-2B"||je==="GPT-OSS-20B")&&t.content.startsWith(ti)){self.postMessage({status:"start"}),self.postMessage({status:"text-update",output:`Sorry, ${je} doesn't support image generation. Please try with a different model like Janus-Pro.`,tps:0,numTokens:0}),self.postMessage({status:"complete"});return}if((je==="SmoLlm"||je==="Phi-3.5"||je==="Llama-3.2"||je==="Deepseek-R1"||je==="Zyphra-ZR1"||je==="GPT-OSS-20B")&&t.image){self.postMessage({status:"start"}),self.postMessage({status:"text-update",output:`Sorry, ${je} doesn't support image input. Please try with a different model like Janus-Pro.`,tps:0,numTokens:0}),self.postMessage({status:"complete"});return}switch(je){case"SmoLlm":await BI(e);break;case"Phi-3.5":await zI(e);break;case"Llama-3.2":await RI(e);break;case"Deepseek-R1":await GI(e);break;case"Zyphra-ZR1":await $I(e);break;case"Qwen3.5-4B":await VI(e);break;case"Qwen3.5-2B":await UI(e);break;case"GPT-OSS-20B":await WI(e);break;default:await DI(e);break}}async function qI(e="Janus-Pro"){if(console.log(`Loading model: ${e}`),Bs){console.log(`Already loading a model, skipping load request for ${e}`);return}Bs=!0;try{aa.reset(),hn.reset(),Zn.reset(),es.reset(),ts.reset(),oa.reset(),ia.reset(),la.reset(),ca.reset(),je=e;const t=AI(e);switch(self.postMessage({status:"loading",data:`Loading ${e}${t?` [${t}]`:""} model...`}),e){case"SmoLlm":{const[r,n]=await hn.getInstance(a=>{self.postMessage(a)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const s=r("a");await n.generate({...s,max_new_tokens:1});break}case"Phi-3.5":{const[r,n]=await Zn.getInstance(a=>{self.postMessage(a)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const s=r("a");await n.generate({...s,max_new_tokens:1});break}case"Llama-3.2":{const[r,n]=await es.getInstance(a=>{self.postMessage(a)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const s=r("a");await n.generate({...s,max_new_tokens:1});break}case"Deepseek-R1":{const[r,n]=await ts.getInstance(a=>{self.postMessage(a)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const s=r("a");await n.generate({...s,max_new_tokens:1});break}case"Zyphra-ZR1":{const[r,n]=await oa.getInstance(a=>{self.postMessage(a)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const s=r("a");await n.generate({...s,max_new_tokens:1});break}case"Qwen3.5-4B":{const[r,n]=await ia.getInstance(a=>{self.postMessage(a)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const s=r.tokenizer("a");await n.generate({...s,past_key_values:null,max_new_tokens:1});break}case"Qwen3.5-2B":{const[r,n]=await la.getInstance(a=>{self.postMessage(a)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const s=r.tokenizer("a");await n.generate({...s,past_key_values:null,max_new_tokens:1});break}case"GPT-OSS-20B":{const{tokenizer:r,model:n}=await ca.getInstance(a=>{self.postMessage(a)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const s=r("a");await n.generate({...s,max_new_tokens:1});break}default:{await aa.getInstance(r=>{self.postMessage(r)});break}}Bs=!1,self.postMessage({status:"ready"})}catch(t){Bs=!1,console.error(`Error loading model ${e}:`,t),self.postMessage({status:"error",data:t.toString()})}}self.addEventListener("message",async e=>{const{type:t,data:r,model:n,maxTokens:s,temp:a}=e.data;switch(t){case"check":await LI();break;case"load":await qI(n);break;case"generate":s&&typeof s=="number"&&(Jt=s),a!==void 0&&typeof a=="number"&&(Pe=a),await jI(r);break;case"interrupt":St.interrupt();break;case"reset":switch(St.reset(),je){case"SmoLlm":hn.reset();break;case"Phi-3.5":Zn.reset();break;case"Llama-3.2":es.reset();break;case"Deepseek-R1":ts.reset();break;case"Zyphra-ZR1":oa.reset();break;case"Qwen3.5-4B":ia.reset();break;case"Qwen3.5-2B":la.reset();break;case"GPT-OSS-20B":ca.reset();break;case"Janus-Pro":break;default:aa.reset();break}break}});