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,29 @@
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 Yo=Object.defineProperty,fy=Object.getOwnPropertyDescriptor,hy=Object.getOwnPropertyNames,py=Object.prototype.hasOwnProperty,_y=(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')}),pe=(e,t)=>()=>(e&&(t=e(e=0)),t),es=(e,t)=>{for(var r in t)Yo(e,r,{get:t[r],enumerable:!0})},my=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of hy(t))!py.call(e,s)&&s!==r&&Yo(e,s,{get:()=>t[s],enumerable:!(n=fy(t,s))||n.enumerable});return e},Rs=e=>my(Yo({},"__esModule",{value:!0}),e),zn,fr,Nr,xd,qf,Hf=pe(()=>{zn=new Map,fr=[],Nr=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=zn.get(e);if(n===void 0)zn.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(zn.get(fr[a]).priority<=r){fr.splice(a,0,e);return}fr.push(e)}return}throw new TypeError("not a valid backend")},xd=async e=>{let t=zn.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}}},qf=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 xd(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)})]}}),gy=pe(()=>{Hf()}),Qf,wy=pe(()=>{Qf="1.24.0-dev.20251116-b39e144322"}),to,Ye,Xf=pe(()=>{wy(),to="warning",Ye={wasm:{},webgl:{},webgpu:{},versions:{common:Qf},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}`);to=e}},get logLevel(){return to}},Object.defineProperty(Ye,"logLevel",{enumerable:!0})}),Oe,vy=pe(()=>{Xf(),Oe=Ye}),Yf,Jf,yy=pe(()=>{Yf=(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 d=a*s,h=0,p=d,m=d*2,w=-1;o==="RGBA"?(h=0,p=d,m=d*2,w=d*3):o==="RGB"?(h=0,p=d,m=d*2):o==="RBG"&&(h=0,m=d,p=d*2);for(let v=0;v<a;v++)for(let b=0;b<s;b++){let M=(e.data[h++]-u[0])*l[0],k=(e.data[p++]-u[1])*l[1],A=(e.data[m++]-u[2])*l[2],E=w===-1?255:(e.data[w++]-u[3])*l[3];n.fillStyle="rgba("+M+","+k+","+A+","+E+")",n.fillRect(b,v,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")},Jf=(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,d;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[3]=l.mean[3])),l===void 0||l.bias===void 0?d=[0,0,0,0]:typeof l.bias=="number"?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(d[3]=l.bias[3]));let h=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,m=0,w=1,v=2,b=3,M=0,k=h,A=h*2,E=-1;i==="RGBA"?(M=0,k=h,A=h*2,E=h*3):i==="RGB"?(M=0,k=h,A=h*2):i==="RBG"&&(M=0,A=h,k=h*2),n=r.createImageData(s,a);for(let C=0;C<a*s;m+=p,w+=p,v+=p,b+=p,C++)n.data[m]=(e.data[M++]-d[0])*u[0],n.data[w]=(e.data[k++]-d[1])*u[1],n.data[v]=(e.data[A++]-d[2])*u[2],n.data[b]=E===-1?255:(e.data[E++]-d[3])*u[3]}else throw new Error("Can not access image data");return n}}),xs,Kf,Zf,eh,th,rh,by=pe(()=>{Jo(),xs=(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,d=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3),h=4,p=0,m=1,w=2,v=3,b=0,M=u,k=u*2,A=-1;i==="RGB"&&(h=3,p=0,m=1,w=2,v=-1),l==="RGBA"?A=u*3:l==="RBG"?(b=0,k=u,M=u*2):l==="BGR"&&(k=0,M=u,b=u*2);for(let E=0;E<u;E++,p+=h,w+=h,m+=h,v+=h)d[b++]=(e[p]+o[0])/a[0],d[M++]=(e[m]+o[1])/a[1],d[k++]=(e[w]+o[2])/a[2],A!==-1&&v!==-1&&(d[A++]=(e[v]+o[3])/a[3]);return l==="RGBA"?new vt("float32",d,[1,4,r,n]):new vt("float32",d,[1,3,r,n])},Kf=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=d=>typeof HTMLCanvasElement<"u"&&d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?d.getContext("2d"):null;if(r){let d=l();d.width=e.width,d.height=e.height;let h=u(d);if(h!=null){let p=e.height,m=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(p=t.resizedHeight,m=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=m}else i.tensorFormat="RGBA",i.height=p,i.width=m;h.drawImage(e,0,0),o=h.getImageData(0,0,m,p).data}else throw new Error("Can not access image data")}else if(n){let d,h;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(d=t.resizedHeight,h=t.resizedWidth):(d=e.height,h=e.width),t!==void 0&&(i=t),i.format="RGBA",i.height=d,i.width=h,t!==void 0){let p=l();p.width=h,p.height=d;let m=u(p);if(m!=null)m.putImageData(e,0,0),o=m.getImageData(0,0,h,d).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 d=l();d.width=e.width,d.height=e.height;let h=u(d);if(h!=null){let p=e.height,m=e.width;return h.drawImage(e,0,0,m,p),o=h.getImageData(0,0,m,p).data,i.height=p,i.width=m,xs(o,i)}else throw new Error("Can not access image data")}else{if(a)return new Promise((d,h)=>{let p=l(),m=u(p);if(!e||!m)return h();let w=new Image;w.crossOrigin="Anonymous",w.src=e,w.onload=()=>{p.width=w.width,p.height=w.height,m.drawImage(w,0,0,p.width,p.height);let v=m.getImageData(0,0,p.width,p.height);i.height=p.height,i.width=p.width,d(xs(v.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return xs(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},Zf=(e,t)=>{let{width:r,height:n,download:s,dispose:a}=t,o=[1,n,r,4];return new vt({location:"texture",type:"float32",texture:e,dims:o,download:s,dispose:a})},eh=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new vt({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},th=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new vt({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:s,dispose:a})},rh=(e,t,r)=>new vt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),Lr,jn,ro,nh,My=pe(()=>{Lr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),jn=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ro=!1,nh=()=>{if(!ro){ro=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,n=typeof r<"u"&&r.from;e&&(Lr.set("int64",BigInt64Array),jn.set(BigInt64Array,"int64")),t&&(Lr.set("uint64",BigUint64Array),jn.set(BigUint64Array,"uint64")),n?(Lr.set("float16",r),jn.set(r,"float16")):Lr.set("float16",Uint16Array)}}}),sh,ah,xy=pe(()=>{Jo(),sh=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},ah=(e,t)=>{switch(e.location){case"cpu":return new vt(e.type,e.data,t);case"cpu-pinned":return new vt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new vt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new vt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new vt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),vt,Jo=pe(()=>{yy(),by(),My(),xy(),vt=class{constructor(e,t,r){nh();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=Lr.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=Lr.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=jn.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=sh(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 Kf(e,t)}static fromTexture(e,t){return Zf(e,t)}static fromGpuBuffer(e,t){return eh(e,t)}static fromMLTensor(e,t){return th(e,t)}static fromPinnedBuffer(e,t,r){return rh(e,t,r)}toDataURL(e){return Yf(this,e)}toImageData(e){return Jf(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 ah(this,e)}}}),Lt,oh=pe(()=>{Jo(),Lt=vt}),$s,no,Br,Rr,wr,vr,ih=pe(()=>{Xf(),$s=(e,t)=>{(typeof Ye.trace>"u"?!Ye.wasm.trace:!Ye.trace)||console.timeStamp(`${e}::ORT::${t}`)},no=(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}`),$s("CPU",a);return}r[s].includes("TRACE_FUNC")&&(n=!0)}},Br=e=>{(typeof Ye.trace>"u"?!Ye.wasm.trace:!Ye.trace)||no("BEGIN",e)},Rr=e=>{(typeof Ye.trace>"u"?!Ye.wasm.trace:!Ye.trace)||no("END",e)},wr=e=>{(typeof Ye.trace>"u"?!Ye.wasm.trace:!Ye.trace)||console.time(`ORT::${e}`)},vr=e=>{(typeof Ye.trace>"u"?!Ye.wasm.trace:!Ye.trace)||console.timeEnd(`ORT::${e}`)}}),lh,Ty=pe(()=>{Hf(),oh(),ih(),lh=class ch{constructor(t){this.handler=t}async run(t,r,n){Br(),wr("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,d=Object.getOwnPropertyNames(r);for(let h of this.outputNames)if(d.indexOf(h)!==-1){let p=r[h];(p===null||p instanceof Lt)&&(u=!0,o=!1,s[h]=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 d=i[u];d instanceof Lt?l[u]=d:l[u]=new Lt(d.type,d.data,d.dims)}return vr("InferenceSession.run"),Rr(),l}async release(){return this.handler.dispose()}static async create(t,r,n,s){Br(),wr("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 d=t,h=0,p=t.byteLength;if(typeof r=="object"&&r!==null)o=r;else if(typeof r=="number"){if(h=r,!Number.isSafeInteger(h))throw new RangeError("'byteOffset' must be an integer.");if(h<0||h>=d.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${d.byteLength}).`);if(p=t.byteLength-h,typeof n=="number"){if(p=n,!Number.isSafeInteger(p))throw new RangeError("'byteLength' must be an integer.");if(p<=0||h+p>d.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${d.byteLength-h}].`);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(d,h,p)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await qf(o),u=await i.createInferenceSessionHandler(a,l);return vr("InferenceSession.create"),Rr(),new ch(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}}}),Ko,ky=pe(()=>{Ty(),Ko=lh}),Ey=pe(()=>{}),Ay=pe(()=>{}),Cy=pe(()=>{}),Sy=pe(()=>{}),uh={};es(uh,{InferenceSession:()=>Ko,TRACE:()=>$s,TRACE_EVENT_BEGIN:()=>wr,TRACE_EVENT_END:()=>vr,TRACE_FUNC_BEGIN:()=>Br,TRACE_FUNC_END:()=>Rr,Tensor:()=>Lt,env:()=>Oe,registerBackend:()=>Nr});var $r=pe(()=>{gy(),vy(),ky(),oh(),Ey(),Ay(),ih(),Cy(),Sy()}),Zo=pe(()=>{}),dh={};es(dh,{default:()=>fh});var so,ao,fh,Py=pe(()=>{Ah(),Gr(),ei(),so="ort-wasm-proxy-worker",ao=globalThis.self?.name===so,ao&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":ti(r.wasm).then(()=>{oi(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;ii(s,n).then(()=>{postMessage({type:t})},a=>{postMessage({type:t,err:a})});break}case"copy-from":{let{buffer:n}=r,s=Vs(n);postMessage({type:t,out:s});break}case"create":{let{model:n,options:s}=r;li(n,s).then(a=>{postMessage({type:t,out:a})},a=>{postMessage({type:t,err:a})});break}case"release":ci(r),postMessage({type:t});break;case"run":{let{sessionId:n,inputIndices:s,inputs:a,outputIndices:o,options:i}=r;ui(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},fi([...a,...l]))},l=>{postMessage({type:t,err:l})});break}case"end-profiling":di(r),postMessage({type:t});break;default:}}catch(n){postMessage({type:t,err:n})}}),fh=ao?null:e=>new Worker(e??gt,{type:"module",name:so})}),hh={};es(hh,{default:()=>ph});async function Td(e={}){var t=e,r=!!globalThis.window,n=!!globalThis.WorkerGlobalScope,s=n&&self.name?.startsWith("em-pthread");t.mountExternalData=(c,f)=>{c.startsWith("./")&&(c=c.substring(2)),(t.Uc||(t.Uc=new Map)).set(c,f)},t.unmountExternalData=()=>{delete t.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,Be:!0}).buffer.constructor;let a=()=>{let c=f=>(..._)=>{let g=Vt;return _=f(..._),Vt!=g?new Promise((y,T)=>{Na={resolve:y,reject:T}}):_};(()=>{for(let f of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])t[f]=c(t[f])})(),typeof jsepRunAsync<"u"&&(t._OrtRun=jsepRunAsync(t._OrtRun),t._OrtRunWithBinding=jsepRunAsync(t._OrtRunWithBinding)),a=void 0};t.asyncInit=()=>{a?.()};var o,i,l=(c,f)=>{throw f},u=import.meta.url,d="";if(r||n){try{d=new URL(".",u).href}catch{}n&&(i=c=>{var f=new XMLHttpRequest;return f.open("GET",c,!1),f.responseType="arraybuffer",f.send(null),new Uint8Array(f.response)}),o=async c=>{if(O(c))return new Promise((_,g)=>{var y=new XMLHttpRequest;y.open("GET",c,!0),y.responseType="arraybuffer",y.onload=()=>{y.status==200||y.status==0&&y.response?_(y.response):g(y.status)},y.onerror=g,y.send(null)});var f=await fetch(c,{credentials:"same-origin"});if(f.ok)return f.arrayBuffer();throw Error(f.status+" : "+f.url)}}var h,p,m,w,v,b,M=console.log.bind(console),k=console.error.bind(console),A=M,E=k,C=!1,O=c=>c.startsWith("file://");function x(){ur.buffer!=G.buffer&&K()}if(s){let c=function(f){try{var _=f.data,g=_.Oc;if(g==="load"){let y=[];self.onmessage=T=>y.push(T),b=()=>{postMessage({Oc:"loaded"});for(let T of y)c(T);self.onmessage=c};for(let T of _.de)t[T]&&!t[T].proxy||(t[T]=(...S)=>{postMessage({Oc:"callHandler",ce:T,args:S})},T=="print"&&(A=t[T]),T=="printErr"&&(E=t[T]));ur=_.je,K(),p=_.ke,ut(),Ms()}else if(g==="run"){(function(y){var T=(x(),N)[y+52>>>2>>>0];y=(x(),N)[y+56>>>2>>>0],Lu(T,T-y),te(T)})(_.Nc),Ha(_.Nc,0,0,1,0,0),yc(),Ia(_.Nc),V||(_u(),V=!0);try{_g(_.he,_.Wc)}catch(y){if(y!="unwind")throw y}}else _.target!=="setimmediate"&&(g==="checkMailbox"?V&&ps():g&&(E(`worker: received unknown command ${g}`),E(_)))}catch(y){throw Cu(),y}};var V=!1;self.onunhandledrejection=f=>{throw f.reason||f},self.onmessage=c}var G,W,J,q,B,N,U,ee,X,F,L,z=!1;function K(){var c=ur.buffer;t.HEAP8=G=new Int8Array(c),J=new Int16Array(c),t.HEAPU8=W=new Uint8Array(c),q=new Uint16Array(c),t.HEAP32=B=new Int32Array(c),t.HEAPU32=N=new Uint32Array(c),U=new Float32Array(c),ee=new Float64Array(c),X=new BigInt64Array(c),F=new BigUint64Array(c)}function le(){z=!0,s?b():nr._b()}function Te(c){throw E(c="Aborted("+c+")"),C=!0,c=new WebAssembly.RuntimeError(c+". Build with -sASSERTIONS for more info."),v?.(c),c}function Se(){return{a:{f:mg,J:gg,k:wg,p:vg,l:yg,ta:bg,b:Mg,ca:xg,Ka:Ec,s:Tg,da:Pc,_a:Fc,Ga:Ic,Ia:Lc,$a:Oc,Ya:Nc,Ra:Dc,Xa:zc,pa:Bc,Ha:Rc,Yb:$c,Za:Gc,Fa:Uc,eb:kg,Da:Eg,Tb:Ag,Rb:Sg,Ca:Fg,M:Ig,H:Lg,Sb:Og,ka:Gg,Ub:Ug,Ua:Vg,Wb:Wg,La:qg,Pb:Hg,la:Qg,Ta:Ia,bb:Xg,U:Zg,n:sw,c:Pa,sb:aw,w:ow,L:iw,z:lw,j:cw,o:Yc,tb:uw,G:dw,T:fw,g:hw,u:pw,m:_w,i:mw,Oa:gw,Pa:ww,Qa:vw,Ma:eu,Na:tu,Qb:ru,fb:bw,db:xw,Y:Tw,rb:kw,ma:Ew,cb:Mw,gb:Aw,ab:Cw,Xb:Sw,N:yw,hb:Pw,X:Fw,Vb:Iw,ob:Gw,C:Uw,sa:Vw,ra:jw,qb:Ww,W:qw,v:Hw,nb:Qw,mb:Xw,lb:Yw,pb:Jw,kb:Kw,jb:Zw,ib:ev,Va:lu,Wa:cu,Ja:dt,ea:uu,oa:du,Sa:fu,na:hu,Db:uy,xa:ry,Eb:cy,ya:ty,F:Wv,e:Iv,r:Pv,x:Sv,D:Uv,Ib:Kv,ba:Yv,B:Ov,za:Zv,$:ny,ha:Jv,Fb:iy,Gb:oy,Ba:qv,Aa:Xv,Jb:Hv,wa:ly,aa:ey,d:Lv,A:Nv,q:Fv,Cb:dy,t:zv,y:Vv,I:Dv,E:Bv,K:jv,S:sy,ja:Gv,_:ay,Kb:$v,Lb:Rv,P:Qv,h:rv,a:ur,Ob:cr,Hb:nv,ia:sv,O:av,qa:ov,Mb:iv,Q:lv,zb:cv,Ab:uv,ua:dv,fa:fv,R:hv,Ea:pv,va:_v,Z:mv,xb:gv,Zb:wv,V:vv,Bb:yv,ub:bv,vb:xv,wb:Tv,ga:kv,yb:Ev,Nb:Av}}}async function ut(){function c(g,y){var T=nr=g.exports;g={};for(let[S,I]of Object.entries(T))typeof I=="function"?(T=Yg(I),g[S]=T):g[S]=I;return nr=g,nr=function(){var S=nr,I=H=>me=>H(me)>>>0,R=H=>()=>H()>>>0;return(S=Object.assign({},S)).$b=I(S.$b),S.Cc=R(S.Cc),S.Ec=I(S.Ec),S.rd=(H=>(me,Q)=>H(me,Q)>>>0)(S.rd),S.wd=I(S.wd),S.xd=R(S.xd),S.Bd=I(S.Bd),S}(),wc.push(nr.id),pu=(g=nr).$b,_u=g.ac,t._OrtInit=g.bc,t._OrtGetLastError=g.cc,t._OrtCreateSessionOptions=g.dc,t._OrtAppendExecutionProvider=g.ec,t._OrtAddFreeDimensionOverride=g.fc,t._OrtAddSessionConfigEntry=g.gc,t._OrtReleaseSessionOptions=g.hc,t._OrtCreateSession=g.ic,t._OrtReleaseSession=g.jc,t._OrtGetInputOutputCount=g.kc,t._OrtGetInputOutputMetadata=g.lc,t._OrtFree=g.mc,t._OrtCreateTensor=g.nc,t._OrtGetTensorData=g.oc,t._OrtReleaseTensor=g.pc,t._OrtCreateRunOptions=g.qc,t._OrtAddRunConfigEntry=g.rc,t._OrtReleaseRunOptions=g.sc,t._OrtCreateBinding=g.tc,t._OrtBindInput=g.uc,t._OrtBindOutput=g.vc,t._OrtClearBoundOutputs=g.wc,t._OrtReleaseBinding=g.xc,t._OrtRunWithBinding=g.yc,t._OrtRun=g.zc,t._OrtEndProfiling=g.Ac,Ga=t._OrtGetWebGpuDevice=g.Bc,ys=g.Cc,Ft=t._free=g.Dc,Yr=t._malloc=g.Ec,mu=t._wgpuBufferRelease=g.Fc,gu=t._wgpuCreateInstance=g.Gc,wu=g.Hc,vu=g.Ic,yu=g.Jc,bu=g.Kc,Mu=g.Lc,xu=g.Pc,Tu=g.Zc,ku=g._c,Eu=g.$c,Ua=g.bd,Va=g.cd,ja=g.dd,Wa=g.ed,On=g.fd,qa=g.gd,Au=g.hd,Ha=g.kd,Cu=g.ld,Su=g.md,Pu=g.nd,Qa=g.od,Fu=g.pd,Iu=g.qd,Xa=g.rd,de=g.sd,Nn=g.td,Lu=g.ud,te=g.vd,bs=g.wd,re=g.xd,Ou=g.yd,Ya=g.zd,Nu=g.Ad,Du=g.Bd,zu=g.Cd,Ja=g.Dd,Bu=g.Ed,Ru=g.Fd,$u=g.Gd,Gu=g.Hd,Uu=g.Id,Vu=g.Jd,ju=g.Kd,Wu=g.Ld,qu=g.Md,Hu=g.Nd,Qu=g.Od,Xu=g.Pd,Yu=g.Qd,Ju=g.Rd,Ku=g.Td,Zu=g.Ud,ed=g.Vd,td=g.Wd,rd=g.Yd,nd=g.Zd,sd=g._d,ad=g.$d,od=g.ae,id=g.be,ld=g.pe,cd=g.qe,ud=g.re,dd=g.se,fd=g.te,hd=g.ue,pd=g.ve,_d=g.we,md=g.xe,gd=g.ye,wd=g.ze,vd=g.Xe,yd=g.Ye,bd=g.Ze,Md=g._e,p=y,nr}var f,_=Se();return t.instantiateWasm?new Promise(g=>{t.instantiateWasm(_,(y,T)=>{g(c(y,T))})}):s?c(new WebAssembly.Instance(p,Se()),p):(L??=t.locateFile?t.locateFile?t.locateFile("ort-wasm-simd-threaded.asyncify.wasm",d):d+"ort-wasm-simd-threaded.asyncify.wasm":new URL("/assets/ort-wasm-simd-threaded.asyncify-BynIiDiv.wasm",import.meta.url).href,f=await async function(g){var y=L;if(!h&&!O(y))try{var T=fetch(y,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(T,g)}catch(S){E(`wasm streaming compile failed: ${S}`),E("falling back to ArrayBuffer instantiation")}return async function(S,I){try{var R=await async function(H){if(!h)try{var me=await o(H);return new Uint8Array(me)}catch{}if(H==L&&h)H=new Uint8Array(h);else{if(!i)throw"both async and sync fetching of the wasm failed";H=i(H)}return H}(S);return await WebAssembly.instantiate(R,I)}catch(H){E(`failed to asynchronously prepare wasm: ${H}`),Te(H)}}(y,g)}(_),c(f.instance,f.module))}class Ue{name="ExitStatus";constructor(f){this.message=`Program terminated with exit(${f})`,this.status=f}}var ze=c=>{c.terminate(),c.onmessage=()=>{}},Ve=[],be=0,he=null,je=c=>{We.length==0&&(Mc(),bc(We[0]));var f=We.pop();if(!f)return 6;Fn.push(f),Er[c.Nc]=f,f.Nc=c.Nc;var _={Oc:"run",he:c.ge,Wc:c.Wc,Nc:c.Nc};return f.postMessage(_,c.Yc),0},_e=0,ve=(c,f,..._)=>{var g,y=16*_.length,T=re(),S=bs(y),I=S>>>3;for(g of _)typeof g=="bigint"?((x(),X)[I++>>>0]=1n,(x(),X)[I++>>>0]=g):((x(),X)[I++>>>0]=0n,(x(),ee)[I++>>>0]=g);return c=Su(c,0,y,S,f),te(T),c};function cr(c){if(s)return ve(0,1,c);if(m=c,!(0<_e)){for(var f of Fn)ze(f);for(f of We)ze(f);We=[],Fn=[],Er={},C=!0}l(0,new Ue(c))}function kr(c){if(s)return ve(1,0,c);dt(c)}var dt=c=>{if(m=c,s)throw kr(c),"unwind";cr(c)},We=[],Fn=[],wc=[],Er={},vc=c=>{var f=c.Nc;delete Er[f],We.push(c),Fn.splice(Fn.indexOf(c),1),c.Nc=0,Pu(f)};function yc(){wc.forEach(c=>c())}var bc=c=>new Promise(f=>{c.onmessage=y=>{var T=y.data;if(y=T.Oc,T.Vc&&T.Vc!=ys()){var S=Er[T.Vc];S?S.postMessage(T,T.Yc):E(`Internal error! Worker sent a message "${y}" to target pthread ${T.Vc}, but that thread no longer exists!`)}else y==="checkMailbox"?ps():y==="spawnThread"?je(T):y==="cleanupThread"?lt(()=>{vc(Er[T.ie])}):y==="loaded"?(c.loaded=!0,f(c)):T.target==="setimmediate"?c.postMessage(T):y==="uncaughtException"?c.onerror(T.error):y==="callHandler"?t[T.ce](...T.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 _,g=[];for(_ of[])t.propertyIsEnumerable(_)&&g.push(_);c.postMessage({Oc:"load",de:g,je:ur,ke:p})});function Mc(){var c=new Worker((()=>{let f=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new f("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 ur,_g=(c,f)=>{_e=0,c=Ja(c,f),0<_e?m=c:Qa(c)},fs=[],hs=0,it=c=>-9007199254740992>c||9007199254740992<c?NaN:Number(c);function mg(c){var f=new Ea(c>>>=0);return(x(),G)[f.Qc+12>>>0]==0&&(xc(f,!0),hs--),Tc(f,!1),fs.push(f),Du(c)}var qr=0,gg=()=>{de(0,0);var c=fs.pop();Ou(c.Xc),qr=0};function xc(c,f){f=f?1:0,(x(),G)[c.Qc+12>>>0]=f}function Tc(c,f){f=f?1:0,(x(),G)[c.Qc+13>>>0]=f}class Ea{constructor(f){this.Xc=f,this.Qc=f-24}}var Aa=c=>{var f=qr;if(!f)return Nn(0),0;var _=new Ea(f);(x(),N)[_.Qc+16>>>2>>>0]=f;var g=(x(),N)[_.Qc+4>>>2>>>0];if(!g)return Nn(0),f;for(var y of c){if(y===0||y===g)break;if(Nu(y,g,_.Qc+16))return Nn(y),f}return Nn(g),f};function wg(){return Aa([])}function vg(c){return Aa([c>>>0])}function yg(c,f,_,g){return Aa([c>>>0,f>>>0,_>>>0,g>>>0])}var bg=()=>{var c=fs.pop();c||Te("no exception to throw");var f=c.Xc;throw(x(),G)[c.Qc+13>>>0]==0&&(fs.push(c),Tc(c,!0),xc(c,!1),hs++),Ya(f),qr=f};function Mg(c,f,_){var g=new Ea(c>>>=0);throw f>>>=0,_>>>=0,(x(),N)[g.Qc+16>>>2>>>0]=0,(x(),N)[g.Qc+4>>>2>>>0]=f,(x(),N)[g.Qc+8>>>2>>>0]=_,Ya(c),hs++,qr=c}var xg=()=>hs;function kc(c,f,_,g){return s?ve(2,1,c,f,_,g):Ec(c,f,_,g)}function Ec(c,f,_,g){if(c>>>=0,f>>>=0,_>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var y=[];return s&&y.length===0?kc(c,f,_,g):(c={ge:_,Nc:c,Wc:g,Yc:y},s?(c.Oc="spawnThread",postMessage(c,y),0):je(c))}function Tg(c){throw qr||=c>>>0,qr}var Ac=globalThis.TextDecoder&&new TextDecoder,Cc=(c,f,_,g)=>{if(_=f+_,g)return _;for(;c[f]&&!(f>=_);)++f;return f},Sc=(c,f=0,_,g)=>{if(16<(_=Cc(c,f>>>=0,_,g))-f&&c.buffer&&Ac)return Ac.decode(c.buffer instanceof ArrayBuffer?c.subarray(f,_):c.slice(f,_));for(g="";f<_;){var y=c[f++];if(128&y){var T=63&c[f++];if((224&y)==192)g+=String.fromCharCode((31&y)<<6|T);else{var S=63&c[f++];65536>(y=(240&y)==224?(15&y)<<12|T<<6|S:(7&y)<<18|T<<12|S<<6|63&c[f++])?g+=String.fromCharCode(y):(y-=65536,g+=String.fromCharCode(55296|y>>10,56320|1023&y))}}else g+=String.fromCharCode(y)}return g},Hr=(c,f,_)=>(c>>>=0)?Sc((x(),W),c,f,_):"";function Pc(c,f,_){return s?ve(3,1,c,f,_):0}function Fc(c,f){if(s)return ve(4,1,c,f)}function Ic(c,f){if(s)return ve(5,1,c,f)}function Lc(c,f,_){if(s)return ve(6,1,c,f,_)}function Oc(c,f,_){return s?ve(7,1,c,f,_):0}function Nc(c,f){if(s)return ve(8,1,c,f)}function Dc(c,f,_){if(s)return ve(9,1,c,f,_)}function zc(c,f,_,g){if(s)return ve(10,1,c,f,_,g)}function Bc(c,f,_,g){if(s)return ve(11,1,c,f,_,g)}function Rc(c,f,_,g){if(s)return ve(12,1,c,f,_,g)}function $c(c){if(s)return ve(13,1,c)}function Gc(c,f){if(s)return ve(14,1,c,f)}function Uc(c,f,_){if(s)return ve(15,1,c,f,_)}var kg=()=>Te(""),Ut=c=>{c>>>=0;for(var f="";;){var _=(x(),W)[c++>>>0];if(!_)return f;f+=String.fromCharCode(_)}},Ca={},Sa={},Qr=class extends Error{constructor(c){super(c),this.name="BindingError"}};function Kt(c,f,_={}){return function(g,y,T={}){var S=y.name;if(!g)throw new Qr(`type "${S}" must have a positive integer typeid pointer`);if(Sa.hasOwnProperty(g)){if(T.ee)return;throw new Qr(`Cannot register type '${S}' twice`)}Sa[g]=y,Ca.hasOwnProperty(g)&&(y=Ca[g],delete Ca[g],y.forEach(I=>I()))}(c,f,_)}var Vc=(c,f,_)=>{switch(f){case 1:return _?g=>(x(),G)[g>>>0]:g=>(x(),W)[g>>>0];case 2:return _?g=>(x(),J)[g>>>1>>>0]:g=>(x(),q)[g>>>1>>>0];case 4:return _?g=>(x(),B)[g>>>2>>>0]:g=>(x(),N)[g>>>2>>>0];case 8:return _?g=>(x(),X)[g>>>3>>>0]:g=>(x(),F)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${f}): ${c}`)}};function Eg(c,f,_,g,y){c>>>=0,_>>>=0,f=Ut(f>>>0);let T=S=>S;if(g=g===0n){let S=8*_;T=I=>BigInt.asUintN(S,I),y=T(y)}Kt(c,{name:f,Mc:T,Sc:(S,I)=>(typeof I=="number"&&(I=BigInt(I)),I),Rc:Vc(f,_,!g),Tc:null})}function Ag(c,f,_,g){Kt(c>>>=0,{name:f=Ut(f>>>0),Mc:function(y){return!!y},Sc:function(y,T){return T?_:g},Rc:function(y){return this.Mc((x(),W)[y>>>0])},Tc:null})}var jc=[],Ar=[0,1,,1,null,1,!0,1,!1,1];function Pa(c){9<(c>>>=0)&&--Ar[c+1]==0&&(Ar[c]=void 0,jc.push(c))}var bt=c=>{if(!c)throw new Qr(`Cannot use deleted val. handle = ${c}`);return Ar[c]},Pt=c=>{switch(c){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let f=jc.pop()||Ar.length;return Ar[f]=c,Ar[f+1]=1,f}};function Fa(c){return this.Mc((x(),N)[c>>>2>>>0])}var Cg={name:"emscripten::val",Mc:c=>{var f=bt(c);return Pa(c),f},Sc:(c,f)=>Pt(f),Rc:Fa,Tc:null};function Sg(c){return Kt(c>>>0,Cg)}var Pg=(c,f)=>{switch(f){case 4:return function(_){return this.Mc((x(),U)[_>>>2>>>0])};case 8:return function(_){return this.Mc((x(),ee)[_>>>3>>>0])};default:throw new TypeError(`invalid float width (${f}): ${c}`)}};function Fg(c,f,_){_>>>=0,Kt(c>>>=0,{name:f=Ut(f>>>0),Mc:g=>g,Sc:(g,y)=>y,Rc:Pg(f,_),Tc:null})}function Ig(c,f,_,g,y){c>>>=0,_>>>=0,f=Ut(f>>>0);let T=I=>I;if(g===0){var S=32-8*_;T=I=>I<<S>>>S,y=T(y)}Kt(c,{name:f,Mc:T,Sc:(I,R)=>R,Rc:Vc(f,_,g!==0),Tc:null})}function Lg(c,f,_){function g(T){var S=(x(),N)[T>>>2>>>0];return T=(x(),N)[T+4>>>2>>>0],new y((x(),G).buffer,T,S)}var y=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][f];Kt(c>>>=0,{name:_=Ut(_>>>0),Mc:g,Rc:g},{ee:!0})}var Zt=(c,f,_)=>{var g=(x(),W);if(f>>>=0,0<_){var y=f;_=f+_-1;for(var T=0;T<c.length;++T){var S=c.codePointAt(T);if(127>=S){if(f>=_)break;g[f++>>>0]=S}else if(2047>=S){if(f+1>=_)break;g[f++>>>0]=192|S>>6,g[f++>>>0]=128|63&S}else if(65535>=S){if(f+2>=_)break;g[f++>>>0]=224|S>>12,g[f++>>>0]=128|S>>6&63,g[f++>>>0]=128|63&S}else{if(f+3>=_)break;g[f++>>>0]=240|S>>18,g[f++>>>0]=128|S>>12&63,g[f++>>>0]=128|S>>6&63,g[f++>>>0]=128|63&S,T++}}g[f>>>0]=0,c=f-y}else c=0;return c},er=c=>{for(var f=0,_=0;_<c.length;++_){var g=c.charCodeAt(_);127>=g?f++:2047>=g?f+=2:55296<=g&&57343>=g?(f+=4,++_):f+=3}return f};function Og(c,f){Kt(c>>>=0,{name:f=Ut(f>>>0),Mc(_){var g=(x(),N)[_>>>2>>>0];return g=Hr(_+4,g,!0),Ft(_),g},Sc(_,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var y=typeof g=="string";if(!(y||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new Qr("Cannot pass non-string to std::string");var T=y?er(g):g.length,S=Yr(4+T+1),I=S+4;return(x(),N)[S>>>2>>>0]=T,y?Zt(g,I,T+1):(x(),W).set(g,I>>>0),_!==null&&_.push(Ft,S),S},Rc:Fa,Tc(_){Ft(_)}})}var Wc=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,Ng=(c,f,_)=>{if(c>>>=1,16<(f=Cc((x(),q),c,f/2,_))-c&&Wc)return Wc.decode((x(),q).slice(c,f));for(_="";c<f;++c){var g=(x(),q)[c>>>0];_+=String.fromCharCode(g)}return _},Dg=(c,f,_)=>{if(_??=2147483647,2>_)return 0;var g=f;_=(_-=2)<2*c.length?_/2:c.length;for(var y=0;y<_;++y){var T=c.charCodeAt(y);(x(),J)[f>>>1>>>0]=T,f+=2}return(x(),J)[f>>>1>>>0]=0,f-g},zg=c=>2*c.length,Bg=(c,f,_)=>{var g="";c>>>=2;for(var y=0;!(y>=f/4);y++){var T=(x(),N)[c+y>>>0];if(!T&&!_)break;g+=String.fromCodePoint(T)}return g},Rg=(c,f,_)=>{if(f>>>=0,_??=2147483647,4>_)return 0;var g=f;_=g+_-4;for(var y=0;y<c.length;++y){var T=c.codePointAt(y);if(65535<T&&y++,(x(),B)[f>>>2>>>0]=T,(f+=4)+4>_)break}return(x(),B)[f>>>2>>>0]=0,f-g},$g=c=>{for(var f=0,_=0;_<c.length;++_)65535<c.codePointAt(_)&&_++,f+=4;return f};function Gg(c,f,_){if(c>>>=0,f>>>=0,_=Ut(_>>>=0),f===2)var g=Ng,y=Dg,T=zg;else g=Bg,y=Rg,T=$g;Kt(c,{name:_,Mc:S=>{var I=(x(),N)[S>>>2>>>0];return I=g(S+4,I*f,!0),Ft(S),I},Sc:(S,I)=>{if(typeof I!="string")throw new Qr(`Cannot pass non-string to C++ string type ${_}`);var R=T(I),H=Yr(4+R+f);return(x(),N)[H>>>2>>>0]=R/f,y(I,H+4,R+f),S!==null&&S.push(Ft,H),H},Rc:Fa,Tc(S){Ft(S)}})}function Ug(c,f){Kt(c>>>=0,{fe:!0,name:f=Ut(f>>>0),Mc:()=>{},Sc:()=>{}})}function Vg(c){Ha(c>>>0,!n,1,!r,131072,!1),yc()}var lt=c=>{if(!C)try{if(c(),!(0<_e))try{s?ys()&&Qa(m):dt(m)}catch(f){f instanceof Ue||f=="unwind"||l(0,f)}}catch(f){f instanceof Ue||f=="unwind"||l(0,f)}},jg=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Ia(c){c>>>=0,jg||(Atomics.waitAsync((x(),B),c>>>2,c).value.then(ps),c+=128,Atomics.store((x(),B),c>>>2,1))}var ps=()=>lt(()=>{var c=ys();c&&(Ia(c),Iu())});function Wg(c,f){(c>>>=0)==f>>>0?setTimeout(ps):s?postMessage({Vc:c,Oc:"checkMailbox"}):(c=Er[c])&&c.postMessage({Oc:"checkMailbox"})}var La=[];function qg(c,f,_,g,y){for(f>>>=0,y>>>=0,La.length=0,_=y>>>3,g=y+g>>>3;_<g;){var T;T=(x(),X)[_++>>>0]?(x(),X)[_++>>>0]:(x(),ee)[_++>>>0],La.push(T)}return(f?Ka[f]:Cv[c])(...La)}var Hg=()=>{_e=0};function Qg(c){c>>>=0,s?postMessage({Oc:"cleanupThread",ie:c}):vc(Er[c])}function Xg(c){}var _s=c=>{try{c()}catch(f){Te(f)}};function Yg(c){var f=(..._)=>{ms.push(c);try{return c(..._)}finally{C||(ms.pop(),Vt&&dr===1&&ms.length===0&&(dr=0,_e+=1,_s(yd),typeof Fibers<"u"&&Fibers.De()))}};return Qc.set(c,f),f}var dr=0,Vt=null,qc=0,ms=[],Oa=new Map,Hc=new Map,Qc=new Map,Jg=0,Na=null,Kg=[],Xc=c=>function(f){if(!C){if(dr===0){var _=!1,g=!1;f((y=0)=>{if(!C&&(qc=y,_=!0,g)){dr=2,_s(()=>bd(Vt)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),y=!1;try{var T=function(){var R=(x(),B)[Vt+8>>>2>>>0];return R=Hc.get(R),R=Qc.get(R),--_e,R()}()}catch(R){T=R,y=!0}var S=!1;if(!Vt){var I=Na;I&&(Na=null,(y?I.reject:I.resolve)(T),S=!0)}if(y&&!S)throw T}}),g=!0,_||(dr=1,Vt=function(){var y=Yr(65548),T=y+12;if((x(),N)[y>>>2>>>0]=T,(x(),N)[y+4>>>2>>>0]=T+65536,T=ms[0],!Oa.has(T)){var S=Jg++;Oa.set(T,S),Hc.set(S,T)}return T=Oa.get(T),(x(),B)[y+8>>>2>>>0]=T,y}(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),_s(()=>vd(Vt)))}else dr===2?(dr=0,_s(Md),Ft(Vt),Vt=null,Kg.forEach(lt)):Te(`invalid state: ${dr}`);return qc}}(f=>{c().then(f)});function Zg(c){return c>>>=0,Xc(async()=>{var f=await bt(c);return Pt(f)})}var Da=[],ew=c=>{var f=Da.length;return Da.push(c),f},tw=(c,f)=>{for(var _=Array(c),g=0;g<c;++g){var y=g,T=(x(),N)[f+4*g>>>2>>>0],S=Sa[T];if(S===void 0)throw c=`parameter ${g}`,T=pu(T),f=Ut(T),Ft(T),new Qr(`${c} has unknown type ${f}`);_[y]=S}return _},rw=(c,f,_)=>{var g=[];return c=c(g,_),g.length&&((x(),N)[f>>>2>>>0]=Pt(g)),c},nw={},gs=c=>{var f=nw[c];return f===void 0?Ut(c):f};function sw(c,f,_){var[g,...y]=tw(c,f>>>0);f=g.Sc.bind(g);var T=y.map(R=>R.Rc.bind(R));c--;var S={toValue:bt};switch(c=T.map((R,H)=>{var me=`argFromPtr${H}`;return S[me]=R,`${me}(args${H?"+"+8*H:""})`}),_){case 0:var I="toValue(handle)";break;case 2:I="new (toValue(handle))";break;case 3:I="";break;case 1:S.getStringOrSymbol=gs,I="toValue(handle)[getStringOrSymbol(methodName)]"}return I+=`(${c})`,g.fe||(S.toReturnWire=f,S.emval_returnValue=rw,I=`return emval_returnValue(toReturnWire, destructorsRef, ${I})`),I=`return function (handle, methodName, destructorsRef, args) {
6
+ ${I}
7
+ }`,_=new Function(Object.keys(S),I)(...Object.values(S)),I=`methodCaller<(${y.map(R=>R.name)}) => ${g.name}>`,ew(Object.defineProperty(_,"name",{value:I}))}function aw(c,f){return f>>>=0,(c=bt(c>>>0))==bt(f)}function ow(c){return(c>>>=0)?(c=gs(c),Pt(globalThis[c])):Pt(globalThis)}function iw(c){return c=gs(c>>>0),Pt(t[c])}function lw(c,f){return f>>>=0,c=bt(c>>>0),f=bt(f),Pt(c[f])}function cw(c){9<(c>>>=0)&&(Ar[c+1]+=1)}function Yc(c,f,_,g,y){return Da[c>>>0](f>>>0,_>>>0,g>>>0,y>>>0)}function uw(c,f,_,g,y){return Yc(c>>>0,f>>>0,_>>>0,g>>>0,y>>>0)}function dw(){return Pt([])}function fw(c){c=bt(c>>>0);for(var f=Array(c.length),_=0;_<c.length;_++)f[_]=c[_];return Pt(f)}function hw(c){return Pt(gs(c>>>0))}function pw(){return Pt({})}function _w(c){for(var f=bt(c>>>=0);f.length;){var _=f.pop();f.pop()(_)}Pa(c)}function mw(c,f,_){f>>>=0,_>>>=0,c=bt(c>>>0),f=bt(f),_=bt(_),c[f]=_}function gw(c,f){c=it(c),f>>>=0,c=new Date(1e3*c),(x(),B)[f>>>2>>>0]=c.getUTCSeconds(),(x(),B)[f+4>>>2>>>0]=c.getUTCMinutes(),(x(),B)[f+8>>>2>>>0]=c.getUTCHours(),(x(),B)[f+12>>>2>>>0]=c.getUTCDate(),(x(),B)[f+16>>>2>>>0]=c.getUTCMonth(),(x(),B)[f+20>>>2>>>0]=c.getUTCFullYear()-1900,(x(),B)[f+24>>>2>>>0]=c.getUTCDay(),c=(c.getTime()-Date.UTC(c.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(x(),B)[f+28>>>2>>>0]=c}var Jc=c=>c%4==0&&(c%100!=0||c%400==0),Kc=[0,31,60,91,121,152,182,213,244,274,305,335],Zc=[0,31,59,90,120,151,181,212,243,273,304,334];function ww(c,f){c=it(c),f>>>=0,c=new Date(1e3*c),(x(),B)[f>>>2>>>0]=c.getSeconds(),(x(),B)[f+4>>>2>>>0]=c.getMinutes(),(x(),B)[f+8>>>2>>>0]=c.getHours(),(x(),B)[f+12>>>2>>>0]=c.getDate(),(x(),B)[f+16>>>2>>>0]=c.getMonth(),(x(),B)[f+20>>>2>>>0]=c.getFullYear()-1900,(x(),B)[f+24>>>2>>>0]=c.getDay();var _=(Jc(c.getFullYear())?Kc:Zc)[c.getMonth()]+c.getDate()-1|0;(x(),B)[f+28>>>2>>>0]=_,(x(),B)[f+36>>>2>>>0]=-60*c.getTimezoneOffset(),_=new Date(c.getFullYear(),6,1).getTimezoneOffset();var g=new Date(c.getFullYear(),0,1).getTimezoneOffset();c=0|(_!=g&&c.getTimezoneOffset()==Math.min(g,_)),(x(),B)[f+32>>>2>>>0]=c}function vw(c){c>>>=0;var f=new Date((x(),B)[c+20>>>2>>>0]+1900,(x(),B)[c+16>>>2>>>0],(x(),B)[c+12>>>2>>>0],(x(),B)[c+8>>>2>>>0],(x(),B)[c+4>>>2>>>0],(x(),B)[c>>>2>>>0],0),_=(x(),B)[c+32>>>2>>>0],g=f.getTimezoneOffset(),y=new Date(f.getFullYear(),6,1).getTimezoneOffset(),T=new Date(f.getFullYear(),0,1).getTimezoneOffset(),S=Math.min(T,y);return 0>_?(x(),B)[c+32>>>2>>>0]=+(y!=T&&S==g):0<_!=(S==g)&&(y=Math.max(T,y),f.setTime(f.getTime()+6e4*((0<_?S:y)-g))),(x(),B)[c+24>>>2>>>0]=f.getDay(),_=(Jc(f.getFullYear())?Kc:Zc)[f.getMonth()]+f.getDate()-1|0,(x(),B)[c+28>>>2>>>0]=_,(x(),B)[c>>>2>>>0]=f.getSeconds(),(x(),B)[c+4>>>2>>>0]=f.getMinutes(),(x(),B)[c+8>>>2>>>0]=f.getHours(),(x(),B)[c+12>>>2>>>0]=f.getDate(),(x(),B)[c+16>>>2>>>0]=f.getMonth(),(x(),B)[c+20>>>2>>>0]=f.getYear(),c=f.getTime(),BigInt(isNaN(c)?-1:c/1e3)}function eu(c,f,_,g,y,T,S){return s?ve(16,1,c,f,_,g,y,T,S):-52}function tu(c,f,_,g,y,T){if(s)return ve(17,1,c,f,_,g,y,T)}var In={},yw=()=>performance.timeOrigin+performance.now();function ru(c,f){if(s)return ve(18,1,c,f);if(In[c]&&(clearTimeout(In[c].id),delete In[c]),!f)return 0;var _=setTimeout(()=>{delete In[c],lt(()=>Fu(c,performance.timeOrigin+performance.now()))},f);return In[c]={id:_,Ce:f},0}function bw(c,f,_,g){c>>>=0,f>>>=0,_>>>=0,g>>>=0;var y=new Date().getFullYear(),T=new Date(y,0,1).getTimezoneOffset();y=new Date(y,6,1).getTimezoneOffset();var S=Math.max(T,y);(x(),N)[c>>>2>>>0]=60*S,(x(),B)[f>>>2>>>0]=+(T!=y),c=(f=I=>{var R=Math.abs(I);return`UTC${0<=I?"-":"+"}${String(Math.floor(R/60)).padStart(2,"0")}${String(R%60).padStart(2,"0")}`})(T),f=f(y),y<T?(Zt(c,_,17),Zt(f,g,17)):(Zt(c,g,17),Zt(f,_,17))}var Mw=()=>Date.now();function xw(c,f,_){return _>>>=0,0<=c&&3>=c?(c===0?c=Date.now():c=performance.timeOrigin+performance.now(),c=Math.round(1e6*c),(x(),X)[_>>>3>>>0]=BigInt(c),0):28}var za=[],nu=(c,f)=>{za.length=0;for(var _;_=(x(),W)[c++>>>0];){var g=_!=105;f+=(g&=_!=112)&&f%8?4:0,za.push(_==112?(x(),N)[f>>>2>>>0]:_==106?(x(),X)[f>>>3>>>0]:_==105?(x(),B)[f>>>2>>>0]:(x(),ee)[f>>>3>>>0]),f+=g?8:4}return za};function Tw(c,f,_){return c>>>=0,f=nu(f>>>0,_>>>0),Ka[c](...f)}function kw(c,f,_){return c>>>=0,f=nu(f>>>0,_>>>0),Ka[c](...f)}var Ew=()=>{};function Aw(c,f){return E(Hr(c>>>0,f>>>0))}var Cw=()=>{throw _e+=1,"unwind"};function Sw(){return 4294901760}var Pw=()=>1,Fw=()=>navigator.hardwareConcurrency;function Iw(c){c>>>=0;var f=(x(),W).length;if(c<=f||4294901760<c)return!1;for(var _=1;4>=_;_*=2){var g=f*(1+.2/_);g=Math.min(g,c+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(c,g)/65536))-ur.buffer.byteLength+65535)/65536|0;try{ur.grow(g),K();var y=1;break e}catch{}y=void 0}if(y)return!0}return!1}var jt=c=>{var f=er(c)+1,_=bs(f);return Zt(c,_,f),_},Ba=(c,f)=>{(x(),N)[c>>>2>>>0]=f;var _=(x(),N)[c>>>2>>>0];(x(),N)[c+4>>>2>>>0]=(f-_)/4294967296},Ln=c=>(x(),N)[c>>>2>>>0]+4294967296*(x(),B)[c+4>>>2>>>0],Ke=[],Lw=(c,f)=>{Ke[c>>>0]=f},tr=[],ws=[],Xr=(c,f)=>{ws[c]=new Promise(_=>f.finally(()=>_(c)))},Z=c=>{if(c)return Ke[c>>>0]},Ow=(c,f)=>{for(c=(x(),N)[c>>>2>>>0];c;c=(x(),N)[c>>>2>>>0])f[(x(),B)[c+4>>>2>>>0]](c)},vs=(c,f,_)=>{(x(),N)[c>>>2>>>0]=f,(x(),N)[c+4>>>2>>>0]=_},su=c=>{var f=(x(),N)[c>>>2>>>0];return c=(x(),N)[c+4>>>2>>>0],Hr(f,c)},rr=c=>{var f=(x(),N)[c>>>2>>>0];return c=(x(),N)[c+4>>>2>>>0],f?Hr(f,c):c===0?"":void 0},Nw=c=>{var f=rr(c+4),_=(_=(x(),N)[c+12>>>2>>>0])?Z(_):"auto";if(c+=16){var g=Z((x(),N)[c+4>>>2>>>0]),y=(x(),N)[c+16>>>2>>>0],T=(x(),N)[c+20>>>2>>>0];if(y){for(var S={},I=0;I<y;++I){var R=T+24*I;S[su(R+4)]=(x(),ee)[R+16>>>3>>>0]}y=S}else y=void 0;c={module:g,constants:y,entryPoint:rr(c+8)}}else c=void 0;return{label:f,layout:_,compute:c}},au=(c,f)=>{function _(g,y){g=c[g],(x(),N)[f+y>>>2>>>0]=g}_("maxTextureDimension1D",4),_("maxTextureDimension2D",8),_("maxTextureDimension3D",12),_("maxTextureArrayLayers",16),_("maxBindGroups",20),_("maxBindGroupsPlusVertexBuffers",24),_("maxBindingsPerBindGroup",28),_("maxDynamicUniformBuffersPerPipelineLayout",32),_("maxDynamicStorageBuffersPerPipelineLayout",36),_("maxSampledTexturesPerShaderStage",40),_("maxSamplersPerShaderStage",44),_("maxStorageBuffersPerShaderStage",48),_("maxStorageTexturesPerShaderStage",52),_("maxUniformBuffersPerShaderStage",56),_("minUniformBufferOffsetAlignment",80),_("minStorageBufferOffsetAlignment",84),Ba(f+64,c.maxUniformBufferBindingSize),Ba(f+72,c.maxStorageBufferBindingSize),_("maxVertexBuffers",88),Ba(f+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)},Dw=[,"validation","out-of-memory","internal"],zw=[,"compatibility","core"],ou={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"},Bw=[,"low-power","high-performance"],Rw=[,"occlusion","timestamp"],$w={undefined:1,unknown:1,destroyed:2};function Gw(c,f,_,g,y,T){f=it(f),_=it(_),g>>>=0,y>>>=0,T>>>=0;var S=Z(c>>>0);if(c={},T){var I=(x(),N)[T+12>>>2>>>0];if(I){var R=(x(),N)[T+16>>>2>>>0];c.requiredFeatures=Array.from((x(),N).subarray(R>>>2>>>0,R+4*I>>>2>>>0),Q=>ou[Q])}var H=(x(),N)[T+20>>>2>>>0];if(H){let Q=function(Ce,Xe,Dn=!1){Xe=H+Xe,(Xe=(x(),N)[Xe>>>2>>>0])==4294967295||Dn&&Xe==0||(me[Ce]=Xe)},fe=function(Ce,Xe){Xe=H+Xe;var Dn=(x(),N)[Xe>>>2>>>0],Za=(x(),N)[Xe+4>>>2>>>0];Dn==4294967295&&Za==4294967295||(me[Ce]=Ln(Xe))};var me={};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),fe("maxUniformBufferBindingSize",64),fe("maxStorageBufferBindingSize",72),Q("maxVertexBuffers",88),fe("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=me}(I=(x(),N)[T+24>>>2>>>0])&&(I={label:rr(I+4)},c.defaultQueue=I),c.label=rr(T+4)}_e+=1,Xr(f,S.requestDevice(c).then(Q=>{--_e,lt(()=>{Ke[y>>>0]=Q.queue,Ke[g>>>0]=Q,Xr(_,Q.lost.then(fe=>{lt(()=>{Q.onuncapturederror=()=>{};var Ce=re(),Xe=jt(fe.message);Va(_,$w[fe.reason],Xe),te(Ce)})})),Q.onuncapturederror=fe=>{var Ce=5;fe.error instanceof GPUValidationError?Ce=2:fe.error instanceof GPUOutOfMemoryError?Ce=3:fe.error instanceof GPUInternalError&&(Ce=4);var Xe=re();fe=jt(fe.error.message),Au(g,Ce,fe),te(Xe)},"adapterInfo"in Q||(Q.adapterInfo=S.info),qa(f,1,g,0)})},Q=>{--_e,lt(()=>{var fe=re(),Ce=jt(Q.message);qa(f,3,g,Ce),_&&Va(_,4,Ce),te(fe)})}))}function Uw(c){var f=Z(c>>>=0),_=tr[c];if(_){for(var g=0;g<_.length;++g)_[g]();delete tr[c]}f.destroy()}function Vw(c,f,_){_>>>=0;var g=Z(c>>>=0);_==4294967295&&(_=void 0);try{var y=g.getMappedRange(f>>>0,_)}catch{return 0}var T=Xa(16,y.byteLength);return(x(),W).set(new Uint8Array(y),T>>>0),tr[c].push(()=>Ft(T)),T}function jw(c,f,_){_>>>=0;var g=Z(c>>>=0);_==4294967295&&(_=void 0);try{var y=g.getMappedRange(f>>>0,_)}catch{return 0}var T=Xa(16,y.byteLength);return(x(),W).fill(0,T,y.byteLength),tr[c].push(()=>{new Uint8Array(y).set((x(),W).subarray(T>>>0,T+y.byteLength>>>0)),Ft(T)}),T}function Ww(c,f,_,g,y){c>>>=0,f=it(f),_=it(_),y>>>=0;var T=Z(c);tr[c]=[],y==4294967295&&(y=void 0),_e+=1,Xr(f,T.mapAsync(_,g>>>0,y).then(()=>{--_e,lt(()=>{ja(f,1,0)})},S=>{--_e,lt(()=>{re();var I=jt(S.message);ja(f,S.name==="AbortError"?4:S.name==="OperationError"?3:0,I),delete tr[c]})}))}function qw(c){var f=Z(c>>>=0),_=tr[c];if(_){for(var g=0;g<_.length;++g)_[g]();delete tr[c],f.unmap()}}function Hw(c){delete Ke[c>>>0]}function Qw(c,f,_){c>>>=0,f>>>=0,_>>>=0;var g=!!(x(),N)[f+32>>>2>>>0];f={label:rr(f+4),usage:(x(),N)[f+16>>>2>>>0],size:Ln(f+24),mappedAtCreation:g},c=Z(c);try{var y=c.createBuffer(f)}catch{return!1}return Ke[_>>>0]=y,g&&(tr[_]=[]),!0}function Xw(c,f,_,g){c>>>=0,f=it(f),g>>>=0,_=Nw(_>>>0),c=Z(c),_e+=1,Xr(f,c.createComputePipelineAsync(_).then(y=>{--_e,lt(()=>{Ke[g>>>0]=y,Ua(f,1,g,0)})},y=>{--_e,lt(()=>{var T=re(),S=jt(y.message);Ua(f,y.reason==="validation"?3:y.reason==="internal"?4:0,g,S),te(T)})}))}function Yw(c,f,_){c>>>=0,f>>>=0,_>>>=0;var g=(x(),N)[f>>>2>>>0],y=(x(),B)[g+4>>>2>>>0];f={label:rr(f+4),code:""},y===2&&(f.code=su(g+8)),c=Z(c).createShaderModule(f),Ke[_>>>0]=c}var Jw=c=>{(c=Z(c)).onuncapturederror=null,c.destroy()};function Kw(c,f){f=it(f),c=Z(c>>>0),_e+=1,Xr(f,c.popErrorScope().then(_=>{--_e,lt(()=>{var g=5;_?_ instanceof GPUValidationError?g=2:_ instanceof GPUOutOfMemoryError?g=3:_ instanceof GPUInternalError&&(g=4):g=1;var y=re(),T=_?jt(_.message):0;Wa(f,1,g,T),te(y)})},_=>{--_e,lt(()=>{var g=re(),y=jt(_.message);Wa(f,1,5,y),te(g)})}))}function Zw(c,f,_,g){if(f=it(f),g>>>=0,_>>>=0){var y={featureLevel:zw[(x(),B)[_+4>>>2>>>0]],powerPreference:Bw[(x(),B)[_+8>>>2>>>0]],forceFallbackAdapter:!!(x(),N)[_+12>>>2>>>0]};(c=(x(),N)[_>>>2>>>0])!==0&&(x(),y.Fe=!!(x(),N)[c+8>>>2>>>0])}"gpu"in navigator?(_e+=1,Xr(f,navigator.gpu.requestAdapter(y).then(T=>{--_e,lt(()=>{if(T)Ke[g>>>0]=T,On(f,1,g,0);else{var S=re(),I=jt("WebGPU not available on this browser (requestAdapter returned null)");On(f,3,g,I),te(S)}})},T=>{--_e,lt(()=>{var S=re(),I=jt(T.message);On(f,4,g,I),te(S)})}))):(y=re(),c=jt("WebGPU not available on this browser (navigator.gpu is not available)"),On(f,3,g,c),te(y))}function ev(c,f,_){return c>>>=0,f>>>=0,_>>>=0,Xc(async()=>{var g=[];if(_){var y=(x(),B)[_>>>2>>>0];g.length=f+1,g[f]=new Promise(I=>setTimeout(I,y,0))}else g.length=f;for(var T=0;T<f;++T){var S=Ln(c+8*T);if(!(S in ws))return S;g[T]=ws[S]}return g=await Promise.race(g),delete ws[g],g})}var Ra,$a={},iu=()=>{if(!Ra){var c,f={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 $a)$a[c]===void 0?delete f[c]:f[c]=$a[c];var _=[];for(c in f)_.push(`${c}=${f[c]}`);Ra=_}return Ra};function lu(c,f){if(s)return ve(19,1,c,f);c>>>=0,f>>>=0;var _,g=0,y=0;for(_ of iu()){var T=f+g;(x(),N)[c+y>>>2>>>0]=T,g+=Zt(_,T,1/0)+1,y+=4}return 0}function cu(c,f){if(s)return ve(20,1,c,f);c>>>=0,f>>>=0;var _=iu();for(var g of((x(),N)[c>>>2>>>0]=_.length,c=0,_))c+=er(g)+1;return(x(),N)[f>>>2>>>0]=c,0}function uu(c){return s?ve(21,1,c):52}function du(c,f,_,g){return s?ve(22,1,c,f,_,g):52}function fu(c,f,_,g){return s?ve(23,1,c,f,_,g):70}var tv=[null,[],[]];function hu(c,f,_,g){if(s)return ve(24,1,c,f,_,g);f>>>=0,_>>>=0,g>>>=0;for(var y=0,T=0;T<_;T++){var S=(x(),N)[f>>>2>>>0],I=(x(),N)[f+4>>>2>>>0];f+=8;for(var R=0;R<I;R++){var H=c,me=(x(),W)[S+R>>>0],Q=tv[H];me===0||me===10?((H===1?A:E)(Sc(Q)),Q.length=0):Q.push(me)}y+=I}return(x(),N)[g>>>2>>>0]=y,0}function rv(c){return c>>>0}function nv(c,f){return au(Z(c>>>0).limits,f>>>0),1}function sv(c,f){return Z(c>>>0).features.has(ou[f])}function av(c){return BigInt(Z(c>>>0).size)}function ov(c){return BigInt(Z(c>>>0).usage)}function iv(c,f){if(c>>>=0,f>>>=0){var _=rr(f+4);_={label:_,timestampWrites:f=(f=(x(),N)[f+12>>>2>>>0])!==0?{querySet:Z((x(),N)[f+4>>>2>>>0]),beginningOfPassWriteIndex:(x(),N)[f+8>>>2>>>0],endOfPassWriteIndex:(x(),N)[f+12>>>2>>>0]}:void 0}}return f=Z(c),c=Mu(0),_=f.beginComputePass(_),Ke[c>>>0]=_,c}function lv(c,f,_,g,y,T){_=it(_),y=it(y),T=it(T),Z(c>>>0).copyBufferToBuffer(Z(f>>>0),_,Z(g>>>0),y,T)}function cv(c){var f=Z(c>>>0);return c=yu(0),f=f.finish(),Ke[c>>>0]=f,c}function uv(c,f,_,g,y,T){T=it(T),Z(c>>>0).resolveQuerySet(Z(f>>>0),_,g,Z(y>>>0),T)}function dv(c,f,_,g){Z(c>>>0).dispatchWorkgroups(f,_,g)}function fv(c,f,_){_=it(_),Z(c>>>0).dispatchWorkgroupsIndirect(Z(f>>>0),_)}function hv(c){Z(c>>>0).end()}function pv(c,f,_,g,y){g>>>=0,y>>>=0,c=Z(c>>>0),_=Z(_>>>0),g==0?c.setBindGroup(f,_):c.setBindGroup(f,_,(x(),N),y>>>2,g)}function _v(c,f){Z(c>>>0).setPipeline(Z(f>>>0))}function mv(c,f,_){Z(c>>>0).Ee(Z(f>>>0),_)}function gv(c,f){var _=Z(c>>>0);return c=vu(0),f=_.getBindGroupLayout(f),Ke[c>>>0]=f,c}function wv(c,f){function _(y){var T=(x(),N)[y+8>>>2>>>0],S=(x(),N)[y+32>>>2>>>0],I=(x(),N)[y+36>>>2>>>0],R=0;return Ow(y,{327681:H=>{R=(x(),N)[H+8>>>2>>>0]}}),T?((S=Ln(y+24))==-1&&(S=void 0),T={buffer:Z(T),offset:Ln(y+16),size:S}):T=Z(S||I||R),{binding:(x(),N)[y+4>>>2>>>0],resource:T}}c>>>=0,f={label:rr(4+(f>>>=0)),layout:Z((x(),N)[f+12>>>2>>>0]),entries:function(y,T){for(var S=[],I=0;I<y;++I)S.push(_(T+40*I));return S}((x(),N)[f+16>>>2>>>0],(x(),N)[f+20>>>2>>>0])},c=Z(c);var g=wu(0);return Lw(g,c.createBindGroup(f)),g}function vv(c,f){var _;return c>>>=0,(f>>>=0)&&(_={label:rr(f+4)}),f=Z(c),c=bu(0),_=f.createCommandEncoder(_),Ke[c>>>0]=_,c}function yv(c,f){c>>>=0,f>>>=0,f={type:Rw[(x(),B)[f+12>>>2>>>0]],count:(x(),N)[f+16>>>2>>>0]};var _=Z(c);return c=xu(0),f=_.createQuerySet(f),Ke[c>>>0]=f,c}function bv(c,f){c=Z(c>>>0).adapterInfo,f>>>=0,(x(),N)[f+52>>>2>>>0]=c.subgroupMinSize,(x(),N)[f+56>>>2>>>0]=c.subgroupMaxSize;var _=c.vendor+c.architecture+c.device+c.description,g=er(_)+1,y=Yr(g);return y&&Zt(_,y,g),_=y,g=er(c.vendor),vs(f+4,_,g),_+=g,g=er(c.architecture),vs(f+12,_,g),_+=g,g=er(c.device),vs(f+20,_,g),vs(f+28,_+g,er(c.description)),(x(),B)[f+36>>>2>>>0]=2,c=c.isFallbackAdapter?3:4,(x(),B)[f+40>>>2>>>0]=c,(x(),N)[f+44>>>2>>>0]=0,(x(),N)[f+48>>>2>>>0]=0,1}var Mv={"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 xv(c,f){f>>>=0;var _=Z(c>>>0);c=Yr(4*_.features.size);var g=0,y=0;for(let T of _.features)0<=(_=Mv[T])&&((x(),B)[c+g>>>2>>>0]=_,g+=4,y++);(x(),N)[f+4>>>2>>>0]=c,(x(),N)[f>>>2>>>0]=y}function Tv(c,f){return au(Z(c>>>0).limits,f>>>0),1}function kv(c,f){Z(c>>>0).pushErrorScope(Dw[f])}function Ev(c,f,_){f>>>=0,_>>>=0,c=Z(c>>>0),f=Array.from((x(),B).subarray(_>>>2>>>0,_+4*f>>>2>>>0),g=>Z(g)),c.submit(f)}function Av(c,f,_,g,y){_=it(_),g>>>=0,y>>>=0,c=Z(c>>>0),f=Z(f>>>0),g=(x(),W).subarray(g>>>0,g+y>>>0),c.writeBuffer(f,_,g,0,y)}s||function(){for(var c=t.numThreads-1;c--;)Mc();Ve.push(async()=>{var f=async function(){if(!s)return Promise.all(We.map(bc))}();be++,await f,--be==0&&he&&(f=he,he=null,f())})}(),s||(ur=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),K()),t.wasmBinary&&(h=t.wasmBinary),t.stackSave=()=>re(),t.stackRestore=c=>te(c),t.stackAlloc=c=>bs(c),t.setValue=function(c,f,_="i8"){switch(_.endsWith("*")&&(_="*"),_){case"i1":case"i8":(x(),G)[c>>>0]=f;break;case"i16":(x(),J)[c>>>1>>>0]=f;break;case"i32":(x(),B)[c>>>2>>>0]=f;break;case"i64":(x(),X)[c>>>3>>>0]=BigInt(f);break;case"float":(x(),U)[c>>>2>>>0]=f;break;case"double":(x(),ee)[c>>>3>>>0]=f;break;case"*":(x(),N)[c>>>2>>>0]=f;break;default:Te(`invalid type for setValue: ${_}`)}},t.getValue=function(c,f="i8"){switch(f.endsWith("*")&&(f="*"),f){case"i1":case"i8":return(x(),G)[c>>>0];case"i16":return(x(),J)[c>>>1>>>0];case"i32":return(x(),B)[c>>>2>>>0];case"i64":return(x(),X)[c>>>3>>>0];case"float":return(x(),U)[c>>>2>>>0];case"double":return(x(),ee)[c>>>3>>>0];case"*":return(x(),N)[c>>>2>>>0];default:Te(`invalid type for getValue: ${f}`)}},t.UTF8ToString=Hr,t.stringToUTF8=Zt,t.lengthBytesUTF8=er;var pu,_u,Ga,ys,Ft,Yr,mu,gu,wu,vu,yu,bu,Mu,xu,Tu,ku,Eu,Ua,Va,ja,Wa,On,qa,Au,Ha,Cu,Su,Pu,Qa,Fu,Iu,Xa,de,Nn,Lu,te,bs,re,Ou,Ya,Nu,Du,zu,Ja,Bu,Ru,$u,Gu,Uu,Vu,ju,Wu,qu,Hu,Qu,Xu,Yu,Ju,Ku,Zu,ed,td,rd,nd,sd,ad,od,id,ld,cd,ud,dd,fd,hd,pd,_d,md,gd,wd,vd,yd,bd,Md,nr,Cv=[cr,kr,kc,Pc,Fc,Ic,Lc,Oc,Nc,Dc,zc,Bc,Rc,$c,Gc,Uc,eu,tu,ru,lu,cu,uu,du,fu,hu],Ka={922732:(c,f,_,g,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(f=Number(f>>>0),_=Number(_>>>0),g=Number(g>>>0),f+_>c.byteLength)return 3;try{let T=c.subarray(f,f+_);switch(y){case 0:(x(),W).set(T,g>>>0);break;case 1:t.ad?t.ad(g,T):t.oe(g,T);break;default:return 4}return 0}catch{return 4}},923556:(c,f,_)=>{t.Sd(c,(x(),W).subarray(f>>>0,f+_>>>0))},923620:()=>t.me(),923662:c=>{t.jd(c)},923699:()=>typeof wasmOffsetConverter<"u"};function Sv(c,f,_,g){var y=re();try{return Wu(c,f,_,g)}catch(T){if(te(y),T!==T+0)throw T;de(1,0)}}function Pv(c,f,_){var g=re();try{return Uu(c,f,_)}catch(y){if(te(g),y!==y+0)throw y;de(1,0)}}function Fv(c,f,_){var g=re();try{zu(c,f,_)}catch(y){if(te(g),y!==y+0)throw y;de(1,0)}}function Iv(c,f){var _=re();try{return Ja(c,f)}catch(g){if(te(_),g!==g+0)throw g;de(1,0)}}function Lv(c){var f=re();try{Bu(c)}catch(_){if(te(f),_!==_+0)throw _;de(1,0)}}function Ov(c,f,_,g,y,T,S){var I=re();try{return Gu(c,f,_,g,y,T,S)}catch(R){if(te(I),R!==R+0)throw R;de(1,0)}}function Nv(c,f){var _=re();try{qu(c,f)}catch(g){if(te(_),g!==g+0)throw g;de(1,0)}}function Dv(c,f,_,g,y,T){var S=re();try{Ru(c,f,_,g,y,T)}catch(I){if(te(S),I!==I+0)throw I;de(1,0)}}function zv(c,f,_,g){var y=re();try{ju(c,f,_,g)}catch(T){if(te(y),T!==T+0)throw T;de(1,0)}}function Bv(c,f,_,g,y,T,S){var I=re();try{Qu(c,f,_,g,y,T,S)}catch(R){if(te(I),R!==R+0)throw R;de(1,0)}}function Rv(c,f,_,g,y,T,S){var I=re();try{Xu(c,f,_,g,y,T,S)}catch(R){if(te(I),R!==R+0)throw R;de(1,0)}}function $v(c,f,_,g,y,T,S,I){var R=re();try{sd(c,f,_,g,y,T,S,I)}catch(H){if(te(R),H!==H+0)throw H;de(1,0)}}function Gv(c,f,_,g,y,T,S,I,R,H,me,Q){var fe=re();try{Yu(c,f,_,g,y,T,S,I,R,H,me,Q)}catch(Ce){if(te(fe),Ce!==Ce+0)throw Ce;de(1,0)}}function Uv(c,f,_,g,y){var T=re();try{return Hu(c,f,_,g,y)}catch(S){if(te(T),S!==S+0)throw S;de(1,0)}}function Vv(c,f,_,g,y){var T=re();try{$u(c,f,_,g,y)}catch(S){if(te(T),S!==S+0)throw S;de(1,0)}}function jv(c,f,_,g,y,T,S,I){var R=re();try{Vu(c,f,_,g,y,T,S,I)}catch(H){if(te(R),H!==H+0)throw H;de(1,0)}}function Wv(c){var f=re();try{return ad(c)}catch(_){if(te(f),_!==_+0)throw _;de(1,0)}}function qv(c,f,_){var g=re();try{return od(c,f,_)}catch(y){if(te(g),y!==y+0)throw y;de(1,0)}}function Hv(c,f){var _=re();try{return wd(c,f)}catch(g){if(te(_),g!==g+0)throw g;return de(1,0),0n}}function Qv(c,f,_,g,y){var T=re();try{id(c,f,_,g,y)}catch(S){if(te(T),S!==S+0)throw S;de(1,0)}}function Xv(c){var f=re();try{return Ju(c)}catch(_){if(te(f),_!==_+0)throw _;return de(1,0),0n}}function Yv(c,f,_,g,y,T){var S=re();try{return rd(c,f,_,g,y,T)}catch(I){if(te(S),I!==I+0)throw I;de(1,0)}}function Jv(c,f,_,g,y,T){var S=re();try{return ld(c,f,_,g,y,T)}catch(I){if(te(S),I!==I+0)throw I;de(1,0)}}function Kv(c,f,_,g,y,T){var S=re();try{return cd(c,f,_,g,y,T)}catch(I){if(te(S),I!==I+0)throw I;de(1,0)}}function Zv(c,f,_,g,y,T,S,I){var R=re();try{return nd(c,f,_,g,y,T,S,I)}catch(H){if(te(R),H!==H+0)throw H;de(1,0)}}function ey(c,f,_,g,y){var T=re();try{return ud(c,f,_,g,y)}catch(S){if(te(T),S!==S+0)throw S;return de(1,0),0n}}function ty(c,f,_,g){var y=re();try{return dd(c,f,_,g)}catch(T){if(te(y),T!==T+0)throw T;de(1,0)}}function ry(c,f,_,g){var y=re();try{return fd(c,f,_,g)}catch(T){if(te(y),T!==T+0)throw T;de(1,0)}}function ny(c,f,_,g,y,T,S,I,R,H,me,Q){var fe=re();try{return hd(c,f,_,g,y,T,S,I,R,H,me,Q)}catch(Ce){if(te(fe),Ce!==Ce+0)throw Ce;de(1,0)}}function sy(c,f,_,g,y,T,S,I,R,H,me){var Q=re();try{pd(c,f,_,g,y,T,S,I,R,H,me)}catch(fe){if(te(Q),fe!==fe+0)throw fe;de(1,0)}}function ay(c,f,_,g,y,T,S,I,R,H,me,Q,fe,Ce,Xe,Dn){var Za=re();try{_d(c,f,_,g,y,T,S,I,R,H,me,Q,fe,Ce,Xe,Dn)}catch(eo){if(te(Za),eo!==eo+0)throw eo;de(1,0)}}function oy(c,f,_,g){var y=re();try{return md(c,f,_,g)}catch(T){if(te(y),T!==T+0)throw T;de(1,0)}}function iy(c,f,_,g,y){var T=re();try{return gd(c,f,_,g,y)}catch(S){if(te(T),S!==S+0)throw S;de(1,0)}}function ly(c,f,_){var g=re();try{return Zu(c,f,_)}catch(y){if(te(g),y!==y+0)throw y;return de(1,0),0n}}function cy(c,f,_){var g=re();try{return Ku(c,f,_)}catch(y){if(te(g),y!==y+0)throw y;de(1,0)}}function uy(c,f,_){var g=re();try{return ed(c,f,_)}catch(y){if(te(g),y!==y+0)throw y;de(1,0)}}function dy(c,f,_,g){var y=re();try{td(c,f,_,g)}catch(T){if(te(y),T!==T+0)throw T;de(1,0)}}function Ms(){if(0<be)he=Ms;else if(s)w?.(t),le();else{for(var c=Ve;0<c.length;)c.shift()(t);0<be?he=Ms:(t.calledRun=!0,C||(le(),w?.(t)))}}return s||(nr=await ut(),Ms()),t.PTR_SIZE=4,t.webgpuInit=c=>{let f=new WeakMap,_,g,y=1;t.webgpuRegisterDevice=I=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(I){var R=f.get(I);if(!R){let H=((me,Q=0)=>{var fe=Eu(Q);return Q=ku(Q,fe),Ke[fe>>>0]=me.queue,Ke[Q>>>0]=me,Q})(I,R=gu(0));R=[y++,R,H],f.set(I,R)}return _=I,g=R[0],R}_=void 0,g=0};let T=new Map;t.webgpuOnCreateSession=I=>{if(g!==void 0){var R=g;if(g=void 0,I){let H=Ga(R);T.set(I,H),R===0&&c(_??Z(H))}_=void 0}},t.webgpuOnReleaseSession=I=>{T.delete(I)};let S=Symbol("gpuBufferMetadata");t.webgpuRegisterBuffer=(I,R,H)=>{if(H)return I[S]=[H,NaN],H;if(H=I[S])return H[1]++,H[0];if((R=T.get(R))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return R=((me,Q=0)=>(me.mapState==="unmapped"||Te(),Q=Tu(Q),Ke[Q>>>0]=me,Q))(I,R),I[S]=[R,1],R},t.webgpuUnregisterBuffer=I=>{let R=I[S];if(!R)throw Error("Buffer is not registered");R[1]--,R[1]===0&&(mu(R[0]),delete I[S])},t.webgpuGetBuffer=I=>Z(I),t.webgpuCreateDownloader=(I,R,H)=>{if((H=T.get(H))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let me=Z(H),Q=16*Math.ceil(Number(R)/16);return async()=>{let fe=me.createBuffer({size:Q,usage:9});try{let Ce=me.createCommandEncoder();return Ce.copyBufferToBuffer(I,0,fe,0,Q),me.queue.submit([Ce.finish()]),await fe.mapAsync(GPUMapMode.READ),fe.getMappedRange().slice(0,R)}finally{fe.destroy()}}},t.ad=(I,R)=>{var H=R.buffer;let me=R.byteOffset,Q=R.byteLength;if(R=16*Math.ceil(Number(Q)/16),I=Z(I),!_){var fe=Ga(g);_=Z(fe)}let Ce=(fe=_.createBuffer({mappedAtCreation:!0,size:R,usage:6})).getMappedRange();new Uint8Array(Ce).set(new Uint8Array(H,me,Q)),fe.unmap(),(H=_.createCommandEncoder()).copyBufferToBuffer(fe,0,I,0,R),_.queue.submit([H.finish()]),fe.destroy()}},t.webnnInit=c=>{let f=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=_=>f.onRunStart(_),t.webnnOnRunEnd=f.onRunEnd.bind(f),t.webnnOnReleaseSession=_=>{f.onReleaseSession(_)},t.webnnCreateMLTensorDownloader=(_,g)=>f.createMLTensorDownloader(_,g),t.webnnRegisterMLTensor=(_,g,y,T)=>f.registerMLTensor(_,g,y,T),t.webnnCreateMLContext=_=>f.createMLContext(_),t.webnnRegisterMLConstant=(_,g,y,T,S,I)=>f.registerMLConstant(_,g,y,T,S,t.Uc,I),t.webnnRegisterGraphInput=f.registerGraphInput.bind(f),t.webnnIsGraphInput=f.isGraphInput.bind(f),t.webnnRegisterGraphOutput=f.registerGraphOutput.bind(f),t.webnnIsGraphOutput=f.isGraphOutput.bind(f),t.webnnCreateTemporaryTensor=f.createTemporaryTensor.bind(f),t.webnnIsGraphInputOutputTypeSupported=f.isGraphInputOutputTypeSupported.bind(f)},z?t:new Promise((c,f)=>{w=c,v=f})}var ph,kd,Fy=pe(()=>{ph=Td,kd=globalThis.self?.name?.startsWith("em-pthread"),kd&&Td()}),oo,Oo,Ed,gt,_h,Ts,Ad,Cd,io,Sd,lo,mh,co,gh,ei=pe(()=>{Zo(),oo=typeof location>"u"?void 0:location.origin,Oo=import.meta.url>"file:"&&import.meta.url<"file;",Ed=()=>{{if(Oo){let e=URL;return new URL(new e("ort.webgpu.bundle.min.mjs",import.meta.url).href,oo).href}return import.meta.url}},gt=Ed(),_h=()=>{if(gt&&!gt.startsWith("blob:"))return gt.substring(0,gt.lastIndexOf("/")+1)},Ts=(e,t)=>{try{let r=t??gt;return(r?new URL(e,r):new URL(e)).origin===oo}catch{return!1}},Ad=(e,t)=>{let r=t??gt;try{return(r?new URL(e,r):new URL(e)).href}catch{return}},Cd=(e,t)=>`${t??"./"}${e}`,io=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Sd=async e=>(await import(e)).default,lo=(Py(),Rs(dh)).default,mh=async()=>{if(!gt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Ts(gt))return[void 0,lo()];let e=await io(gt);return[e,lo(e)]},co=(Fy(),Rs(hh)).default,gh=async(e,t,r,n)=>{let s=co&&!(e||t);if(s)if(gt)s=Ts(gt)||n&&!r;else if(n&&!r)s=!0;else throw new Error("cannot determine the script source URL.");if(s)return[void 0,co];{let a="ort-wasm-simd-threaded.asyncify.mjs",o=e??Ad(a,t),i=r&&o&&!Ts(o,t),l=i?await io(o):o??Cd(a,t);return[i?l:void 0,await Sd(l)]}}}),uo,ks,Bn,fo,Pd,Fd,Id,ti,Ae,Gr=pe(()=>{ei(),ks=!1,Bn=!1,fo=!1,Pd=()=>{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}},Fd=()=>{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}},Id=()=>{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}},ti=async e=>{if(ks)return Promise.resolve();if(Bn)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(fo)throw new Error("previous call to 'initializeWebAssembly()' failed.");Bn=!0;let t=e.initTimeout,r=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!Id())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Fd())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let n=Pd();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,d=e.wasmBinary,[h,p]=await gh(i,a,r>1,!!d||!!u),m=!1,w=[];if(t>0&&w.push(new Promise(v=>{setTimeout(()=>{m=!0,v()},t)})),w.push(new Promise((v,b)=>{let M={numThreads:r};if(d)M.wasmBinary=d,M.locateFile=k=>k;else if(u||a)M.locateFile=k=>u??a+k;else if(i&&i.indexOf("blob:")!==0)M.locateFile=k=>new URL(k,i).href;else if(h){let k=_h();k&&(M.locateFile=A=>k+A)}p(M).then(k=>{Bn=!1,ks=!0,uo=k,v(),h&&URL.revokeObjectURL(h)},k=>{Bn=!1,fo=!0,b(k)})})),await Promise.race(w),m)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Ae=()=>{if(ks&&uo)return uo;throw new Error("WebAssembly is not initialized yet.")}}),wt,Gs,xe,ri=pe(()=>{Gr(),wt=(e,t)=>{let r=Ae(),n=r.lengthBytesUTF8(e)+1,s=r._malloc(n);return r.stringToUTF8(e,s,n),t.push(s),s},Gs=(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")Gs(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}`)})},xe=e=>{let t=Ae(),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)}}}),wh,Iy=pe(()=>{Gr(),ri(),wh=e=>{let t=Ae(),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=wt(e.tag,n)),r=t._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,a),r===0&&xe("Can't create run options."),e?.extra!==void 0&&Gs(e.extra,"",new WeakSet,(o,i)=>{let l=wt(o,n),u=wt(i,n);t._OrtAddRunConfigEntry(r,l,u)!==0&&xe(`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}}}),Ld,Od,Nd,Es,hr,Dd,vh,Ly=pe(()=>{Gr(),ri(),Ld=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}`)}},Od=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Nd=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)},Es=(e,t,r,n)=>{let s=wt(t,n),a=wt(r,n);Ae()._OrtAddSessionConfigEntry(e,s,a)!==0&&xe(`Can't set a session config entry: ${t} - ${r}.`)},hr=(e,t,r,n)=>{let s=wt(t,n),a=wt(r,n);e.push([s,a])},Dd=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 h=s?.deviceType;h&&Es(e,"deviceType",h,r)}break;case"webgpu":{a="WebGPU";let h;if(typeof s!="string"){let m=s;if(m.device)if(typeof GPUDevice<"u"&&m.device instanceof GPUDevice)h=m.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=t;if(typeof w=="boolean"&&w&&hr(o,"enableGraphCapture","1",r),typeof m.preferredLayout=="string"&&hr(o,"preferredLayout",m.preferredLayout,r),m.forceCpuNodeNames){let v=Array.isArray(m.forceCpuNodeNames)?m.forceCpuNodeNames:[m.forceCpuNodeNames];hr(o,"forceCpuNodeNames",v.join(`
8
+ `),r)}m.validationMode&&hr(o,"validationMode",m.validationMode,r)}let p=Ae().webgpuRegisterDevice(h);if(p){let[m,w,v]=p;hr(o,"deviceId",m.toString(),r),hr(o,"webgpuInstance",w.toString(),r),hr(o,"webgpuDevice",v.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${a}`)}let i=wt(a,r),l=o.length,u=0,d=0;if(l>0){u=Ae()._malloc(l*Ae().PTR_SIZE),r.push(u),d=Ae()._malloc(l*Ae().PTR_SIZE),r.push(d);for(let h=0;h<l;h++)Ae().setValue(u+h*Ae().PTR_SIZE,o[h][0],"*"),Ae().setValue(d+h*Ae().PTR_SIZE,o[h][1],"*")}await Ae()._OrtAppendExecutionProvider(e,i,u,d,l)!==0&&xe(`Can't append execution provider: ${a}.`)}},vh=async e=>{let t=Ae(),r=0,n=[],s=e||{};Nd(s);try{let a=Ld(s.graphOptimizationLevel??"all"),o=Od(s.executionMode??"sequential"),i=typeof s.logId=="string"?wt(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 d=typeof s.optimizedModelFilePath=="string"?wt(s.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(a,!!s.enableCpuMemArena,!!s.enableMemPattern,o,!!s.enableProfiling,0,i,l,u,d),r===0&&xe("Can't create session options."),s.executionProviders&&await Dd(r,s,n),s.enableGraphCapture!==void 0){if(typeof s.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${s.enableGraphCapture}`);Es(r,"enableGraphCapture",s.enableGraphCapture.toString(),n)}if(s.freeDimensionOverrides)for(let[h,p]of Object.entries(s.freeDimensionOverrides)){if(typeof h!="string")throw new Error(`free dimension override name must be a string: ${h}`);if(typeof p!="number"||!Number.isInteger(p)||p<0)throw new Error(`free dimension override value must be a non-negative integer: ${p}`);let m=wt(h,n);t._OrtAddFreeDimensionOverride(r,m,p)!==0&&xe(`Can't set a free dimension override: ${h} - ${p}.`)}return s.extra!==void 0&&Gs(s.extra,"",new WeakSet,(h,p)=>{Es(r,h,p,n)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&xe("Can't release session options."),n.forEach(o=>t._free(o)),a}}}),Or,Ns,rn,Jn,Us,ni,si,No,dn=pe(()=>{Or=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}`)}},Ns=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},Jn=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}`)}},Us=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}`)}},ni=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",si=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",No=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}`)}}}),ai,yh=pe(()=>{Zo(),ai=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)}}),bh,Oy=pe(()=>{dn(),bh=(e,t)=>new(Jn(t))(e)}),zd,Bd,Rd,$d,Mh,Gd,nt,xh=pe(()=>{dn(),zd=["V","I","W","E","F"],Bd=(e,t)=>{console.log(`[${zd[e]},${new Date().toISOString()}]${t}`)},Mh=(e,t)=>{Rd=e,$d=t},Gd=(e,t)=>{let r=Us(e),n=Us(Rd);r>=n&&Bd(r,typeof t=="function"?t():t)},nt=(...e)=>{$d&&Gd(...e)}}),ho,Do,po,Ud,_o,Vd,mo,go,wo,jd,Th,Ny=pe(()=>{dn(),xh(),ho=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Do=(e,t)=>{if(t==="int32")return e;let r=ho.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(Jn(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'`)}},po=(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}`)}},Ud=1,_o=()=>Ud++,Vd=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),mo=(e,t)=>{let r=ho.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},go=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 mo(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=po(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}},wo=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=Vd.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!==mo(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=Do(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?po(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()}},jd=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=_o();return this.tensorTrackersById.set(e,new wo(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=_o(),o=new go({sessionId:e,context:s,tensor:t,dataType:r,shape:n});return this.tensorTrackersById.set(a,new wo(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,r,n,s,a,o){let i=this.getMLContext(e);for(let[u,d]of this.freeTensors.entries())if(d.canReuseTensor(i,t,r)){nt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${r}`);let h=this.freeTensors.splice(u,1)[0];return h.sessionId=e,h}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 go({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)}},Th=(...e)=>new jd(...e)}),kh={};es(kh,{WebNNBackend:()=>Eh});var Rn,Wd,Eh,Dy=pe(()=>{dn(),Gr(),Oy(),Ny(),xh(),Rn=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Wd=(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])},Eh=class{constructor(e){this.tensorManager=Th(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,Mh(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=>Wd(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=Rn.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=Rn.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(!Ae().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 bh(r,t)}}registerMLTensor(e,t,r,n){let s=Rn.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,d;switch(s.dataType){case"float32":d=new Float32Array(u);break;case"float16":d=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(u):new Uint16Array(u);break;case"int32":d=new Int32Array(u);break;case"uint32":d=new Uint32Array(u);break;case"int64":if(o){let h=Do(new Uint8Array(u),"int64");d=new Int32Array(h.buffer),s.dataType="int32"}else d=new BigInt64Array(u);break;case"uint64":d=new BigUint64Array(u);break;case"int8":d=new Int8Array(u);break;case"int4":case"uint4":case"uint8":d=new Uint8Array(u);break;default:throw new Error(`Unsupported data type: ${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,d)}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=Rn.get(Or(t)),s=this.mlOpSupportLimitsBySessionId.get(e);return typeof n>"u"?!1:r?!!s?.input.dataTypes.includes(n):!!s?.output.dataTypes.includes(n)}flush(){}}}),qd,oi,ii,pr,Hd,vo,Vs,li,ci,yo,ui,di,fi,Ah=pe(()=>{$r(),Iy(),Ly(),dn(),Gr(),ri(),yh(),qd=(e,t)=>{Ae()._OrtInit(e,t)!==0&&xe("Can't initialize onnxruntime.")},oi=async e=>{qd(e.wasm.numThreads,Us(e.logLevel))},ii=async(e,t)=>{Ae().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"&&Ae().webgpuInit(n=>{e.webgpu.device=n}),t==="webnn"){let n=new(Dy(),Rs(kh)).WebNNBackend(e);Ae().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])}},pr=new Map,Hd=e=>{let t=Ae(),r=t.stackSave();try{let n=t.PTR_SIZE,s=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,s,s+n)!==0&&xe("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)}},vo=(e,t)=>{let r=Ae(),n=r.stackSave(),s=0;try{let a=r.PTR_SIZE,o=r.stackAlloc(2*a);r._OrtGetInputOutputMetadata(e,t,o,o+a)!==0&&xe("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],d=[];for(let h=0;h<u;h++){let p=Number(r.getValue(s+8+h*a,"*"));d.push(p!==0?r.UTF8ToString(p):Number(r.getValue(s+8+(h+u)*a,"*")))}return[i,l,d]}finally{r.stackRestore(n),s!==0&&r._OrtFree(s)}},Vs=e=>{let t=Ae(),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]},li=async(e,t)=>{let r,n,s=Ae();Array.isArray(e)?[r,n]=e:e.buffer===s.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=Vs(e);let a=0,o=0,i=0,l=[],u=[],d=[];try{if([o,l]=await vh(t),t?.externalData&&s.mountExternalData){let E=[];for(let C of t.externalData){let O=typeof C=="string"?C:C.path;E.push(ai(typeof C=="string"?C:C.data).then(x=>{s.mountExternalData(O,x)}))}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 C=E,O=C?.context,x=C?.gpuDevice,V=C?.deviceType,G=C?.powerPreference;O?s.currentContext=O:x?s.currentContext=await s.webnnCreateMLContext(x):s.currentContext=await s.webnnCreateMLContext({deviceType:V,powerPreference:G})}else s.currentContext=await s.webnnCreateMLContext();break}a=await s._OrtCreateSession(r,n,o),s.webgpuOnCreateSession?.(a),a===0&&xe("Can't create a session."),s.jsepOnCreateSession?.(),s.currentContext&&(s.webnnRegisterMLContext(a,s.currentContext),s.currentContext=void 0,s.shouldTransferToMLTensor=!0);let[h,p]=Hd(a),m=!!t?.enableGraphCapture,w=[],v=[],b=[],M=[],k=[];for(let E=0;E<h;E++){let[C,O,x]=vo(a,E);C===0&&xe("Can't get an input name."),u.push(C);let V=s.UTF8ToString(C);w.push(V),b.push(O===0?{name:V,isTensor:!1}:{name:V,isTensor:!0,type:Ns(O),shape:x})}for(let E=0;E<p;E++){let[C,O,x]=vo(a,E+h);C===0&&xe("Can't get an output name."),d.push(C);let V=s.UTF8ToString(C);v.push(V),M.push(O===0?{name:V,isTensor:!1}:{name:V,isTensor:!0,type:Ns(O),shape:x});{if(m&&t?.preferredOutputLocation===void 0){k.push("gpu-buffer");continue}let G=typeof t?.preferredOutputLocation=="string"?t.preferredOutputLocation:t?.preferredOutputLocation?.[V]??"cpu",W=s.webnnIsGraphOutput;if(G==="cpu"&&W&&W(a,V)){k.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(m&&G!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${G}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);k.push(G)}}let A=null;return k.some(E=>E==="gpu-buffer"||E==="ml-tensor"||E==="ml-tensor-cpu-output")&&(i=s._OrtCreateBinding(a),i===0&&xe("Can't create IO binding."),A={handle:i,outputPreferredLocations:k,outputPreferredLocationsEncoded:k.map(E=>E==="ml-tensor-cpu-output"?"ml-tensor":E).map(E=>No(E))}),pr.set(a,[a,u,d,A,m,!1]),[a,w,v,b,M]}catch(h){throw u.forEach(p=>s._OrtFree(p)),d.forEach(p=>s._OrtFree(p)),i!==0&&s._OrtReleaseBinding(i)!==0&&xe("Can't release IO binding."),a!==0&&s._OrtReleaseSession(a)!==0&&xe("Can't release session."),h}finally{s._free(r),o!==0&&s._OrtReleaseSessionOptions(o)!==0&&xe("Can't release session options."),l.forEach(h=>s._free(h)),s.unmountExternalData?.()}},ci=e=>{let t=Ae(),r=pr.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&&xe("Can't clear bound outputs."),t._OrtReleaseBinding(o.handle)!==0&&xe("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&&xe("Can't release session."),pr.delete(e)},yo=async(e,t,r,n,s,a,o=!1)=>{if(!e){t.push(0);return}let i=Ae(),l=i.PTR_SIZE,u=e[0],d=e[1],h=e[3],p=h,m,w;if(u==="string"&&(h==="gpu-buffer"||h==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(o&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let M=e[2].gpuBuffer;w=rn(Or(u),d);{let k=i.webgpuRegisterBuffer;if(!k)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');m=k(M,n)}}else if(h==="ml-tensor"){let M=e[2].mlTensor;w=rn(Or(u),d);let k=i.webnnRegisterMLTensor;if(!k)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');m=k(n,M,Or(u),d)}else{let M=e[2];if(Array.isArray(M)){w=l*M.length,m=i._malloc(w),r.push(m);for(let k=0;k<M.length;k++){if(typeof M[k]!="string")throw new TypeError(`tensor data at index ${k} is not a string`);i.setValue(m+k*l,wt(M[k],r),"*")}}else{let k=i.webnnIsGraphInput,A=i.webnnIsGraphOutput;if(u!=="string"&&k&&A){let E=i.UTF8ToString(s);if(k(n,E)||A(n,E)){let C=Or(u);w=rn(C,d),p="ml-tensor";let O=i.webnnCreateTemporaryTensor,x=i.webnnUploadTensor;if(!O||!x)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let V=await O(n,C,d);x(V,new Uint8Array(M.buffer,M.byteOffset,M.byteLength)),m=V}else w=M.byteLength,m=i._malloc(w),r.push(m),i.HEAPU8.set(new Uint8Array(M.buffer,M.byteOffset,w),m)}else w=M.byteLength,m=i._malloc(w),r.push(m),i.HEAPU8.set(new Uint8Array(M.buffer,M.byteOffset,w),m)}}let v=i.stackSave(),b=i.stackAlloc(4*d.length);try{d.forEach((k,A)=>i.setValue(b+A*l,k,l===4?"i32":"i64"));let M=i._OrtCreateTensor(Or(u),m,w,b,d.length,No(p));M===0&&xe(`Can't create tensor for input/output. session=${n}, index=${a}.`),t.push(M)}finally{i.stackRestore(v)}},ui=async(e,t,r,n,s,a)=>{let o=Ae(),i=o.PTR_SIZE,l=pr.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let u=l[0],d=l[1],h=l[2],p=l[3],m=l[4],w=l[5],v=t.length,b=n.length,M=0,k=[],A=[],E=[],C=[],O=[],x=o.stackSave(),V=o.stackAlloc(v*i),G=o.stackAlloc(v*i),W=o.stackAlloc(b*i),J=o.stackAlloc(b*i);try{[M,k]=wh(a),wr("wasm prepareInputOutputTensor");for(let U=0;U<v;U++)await yo(r[U],A,C,e,d[t[U]],t[U],m);for(let U=0;U<b;U++)await yo(s[U],E,C,e,h[n[U]],v+n[U],m);vr("wasm prepareInputOutputTensor");for(let U=0;U<v;U++)o.setValue(V+U*i,A[U],"*"),o.setValue(G+U*i,d[t[U]],"*");for(let U=0;U<b;U++)o.setValue(W+U*i,E[U],"*"),o.setValue(J+U*i,h[n[U]],"*");if(p&&!w){let{handle:U,outputPreferredLocations:ee,outputPreferredLocationsEncoded:X}=p;if(d.length!==v)throw new Error(`input count from feeds (${v}) is expected to be always equal to model's input count (${d.length}).`);wr("wasm bindInputsOutputs");for(let F=0;F<v;F++){let L=t[F];await o._OrtBindInput(U,d[L],A[F])!==0&&xe(`Can't bind input[${F}] for session=${e}.`)}for(let F=0;F<b;F++){let L=n[F];s[F]?.[3]?(O.push(E[F]),o._OrtBindOutput(U,h[L],E[F],0)!==0&&xe(`Can't bind pre-allocated output[${F}] for session=${e}.`)):o._OrtBindOutput(U,h[L],0,X[L])!==0&&xe(`Can't bind output[${F}] to ${ee[F]} for session=${e}.`)}vr("wasm bindInputsOutputs"),pr.set(e,[u,d,h,p,m,!0])}o.jsepOnRunStart?.(u),o.webnnOnRunStart?.(u);let q;p?q=await o._OrtRunWithBinding(u,p.handle,b,W,M):q=await o._OrtRun(u,G,V,v,J,b,W,M),q!==0&&xe("failed to call OrtRun().");let B=[],N=[];wr("wasm ProcessOutputTensor");for(let U=0;U<b;U++){let ee=Number(o.getValue(W+U*i,"*"));if(ee===E[U]||O.includes(E[U])){B.push(s[U]),ee!==E[U]&&o._OrtReleaseTensor(ee)!==0&&xe("Can't release tensor.");continue}let X=o.stackSave(),F=o.stackAlloc(4*i),L=!1,z,K=0;try{o._OrtGetTensorData(ee,F,F+i,F+2*i,F+3*i)!==0&&xe(`Can't access output tensor data on index ${U}.`);let le=i===4?"i32":"i64",Te=Number(o.getValue(F,le));K=o.getValue(F+i,"*");let Se=o.getValue(F+i*2,"*"),ut=Number(o.getValue(F+i*3,le)),Ue=[];for(let be=0;be<ut;be++)Ue.push(Number(o.getValue(Se+be*i,le)));o._OrtFree(Se)!==0&&xe("Can't free memory for tensor dims.");let ze=Ue.reduce((be,he)=>be*he,1);z=Ns(Te);let Ve=p?.outputPreferredLocations[n[U]];if(z==="string"){if(Ve==="gpu-buffer"||Ve==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let be=[];for(let he=0;he<ze;he++){let je=o.getValue(K+he*i,"*"),_e=o.getValue(K+(he+1)*i,"*"),ve=he===ze-1?void 0:_e-je;be.push(o.UTF8ToString(je,ve))}B.push([z,Ue,be,"cpu"])}else if(Ve==="gpu-buffer"&&ze>0){let be=o.webgpuGetBuffer;if(!be)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let he=be(K),je=rn(Te,ze);if(je===void 0||!ni(z))throw new Error(`Unsupported data type: ${z}`);L=!0;{o.webgpuRegisterBuffer(he,e,K);let _e=o.webgpuCreateDownloader(he,je,e);B.push([z,Ue,{gpuBuffer:he,download:async()=>{let ve=await _e();return new(Jn(z))(ve)},dispose:()=>{o._OrtReleaseTensor(ee)!==0&&xe("Can't release tensor.")}},"gpu-buffer"])}}else if(Ve==="ml-tensor"&&ze>0){let be=o.webnnEnsureTensor,he=o.webnnIsGraphInputOutputTypeSupported;if(!be||!he)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(rn(Te,ze)===void 0||!si(z))throw new Error(`Unsupported data type: ${z}`);if(!he(e,z,!1))throw new Error(`preferredLocation "ml-tensor" for ${z} output is not supported by current WebNN Context.`);let je=await be(e,K,Te,Ue,!1);L=!0,B.push([z,Ue,{mlTensor:je,download:o.webnnCreateMLTensorDownloader(K,z),dispose:()=>{o.webnnReleaseTensorId(K),o._OrtReleaseTensor(ee)}},"ml-tensor"])}else if(Ve==="ml-tensor-cpu-output"&&ze>0){let be=o.webnnCreateMLTensorDownloader(K,z)(),he=B.length;L=!0,N.push((async()=>{let je=[he,await be];return o.webnnReleaseTensorId(K),o._OrtReleaseTensor(ee),je})()),B.push([z,Ue,[],"cpu"])}else{let be=Jn(z),he=new be(ze);new Uint8Array(he.buffer,he.byteOffset,he.byteLength).set(o.HEAPU8.subarray(K,K+he.byteLength)),B.push([z,Ue,he,"cpu"])}}finally{o.stackRestore(X),z==="string"&&K&&o._free(K),L||o._OrtReleaseTensor(ee)}}p&&!m&&(o._OrtClearBoundOutputs(p.handle)!==0&&xe("Can't clear bound outputs."),pr.set(e,[u,d,h,p,m,!1]));for(let[U,ee]of await Promise.all(N))B[U][2]=ee;return vr("wasm ProcessOutputTensor"),B}finally{o.webnnOnRunEnd?.(u),o.stackRestore(x),r.forEach(q=>{q&&q[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(q[2].gpuBuffer)}),s.forEach(q=>{q&&q[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(q[2].gpuBuffer)}),A.forEach(q=>o._OrtReleaseTensor(q)),E.forEach(q=>o._OrtReleaseTensor(q)),C.forEach(q=>o._free(q)),M!==0&&o._OrtReleaseRunOptions(M),k.forEach(q=>o._free(q))}},di=e=>{let t=Ae(),r=pr.get(e);if(!r)throw new Error("invalid session id");let n=r[0],s=t._OrtEndProfiling(n);s===0&&xe("Can't get an profile file name."),t._OrtFree(s)},fi=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),_r,Mt,Jr,$n,Gn,As,bo,Cs,Cr,Sr,Qd,Ch,Sh,Ph,Fh,Ih,Lh,Oh,Nh=pe(()=>{$r(),Ah(),Gr(),ei(),_r=()=>!!Oe.wasm.proxy&&typeof document<"u",Jr=!1,$n=!1,Gn=!1,Cs=new Map,Cr=(e,t)=>{let r=Cs.get(e);r?r.push(t):Cs.set(e,[t])},Sr=()=>{if(Jr||!$n||Gn||!Mt)throw new Error("worker not ready")},Qd=e=>{switch(e.data.type){case"init-wasm":Jr=!1,e.data.err?(Gn=!0,bo[1](e.data.err)):($n=!0,bo[0]()),As&&(URL.revokeObjectURL(As),As=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Cs.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Ch=async()=>{if(!$n){if(Jr)throw new Error("multiple calls to 'initWasm()' detected.");if(Gn)throw new Error("previous call to 'initWasm()' failed.");if(Jr=!0,_r())return new Promise((e,t)=>{Mt?.terminate(),mh().then(([r,n])=>{try{Mt=n,Mt.onerror=a=>t(a),Mt.onmessage=Qd,bo=[e,t];let s={type:"init-wasm",in:Oe};!s.in.wasm.wasmPaths&&(r||Oo)&&(s.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.asyncify-BynIiDiv.wasm",import.meta.url).href}),Mt.postMessage(s),As=r}catch(s){t(s)}},t)});try{await ti(Oe.wasm),await oi(Oe),$n=!0}catch(e){throw Gn=!0,e}finally{Jr=!1}}},Sh=async e=>{if(_r())return Sr(),new Promise((t,r)=>{Cr("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:Oe}};Mt.postMessage(n)});await ii(Oe,e)},Ph=async e=>_r()?(Sr(),new Promise((t,r)=>{Cr("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};Mt.postMessage(n,[e.buffer])})):Vs(e),Fh=async(e,t)=>{if(_r()){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),Mt.postMessage(s,a)})}else return li(e,t)},Ih=async e=>{if(_r())return Sr(),new Promise((t,r)=>{Cr("release",[t,r]);let n={type:"release",in:e};Mt.postMessage(n)});ci(e)},Lh=async(e,t,r,n,s,a)=>{if(_r()){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}};Mt.postMessage(u,fi(l))})}else return ui(e,t,r,n,s,a)},Oh=async e=>{if(_r())return Sr(),new Promise((t,r)=>{Cr("end-profiling",[t,r]);let n={type:"end-profiling",in:e};Mt.postMessage(n)});di(e)}}),Mo,Xd,Dh,zy=pe(()=>{$r(),Nh(),dn(),Zo(),yh(),Mo=(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()}`)}},Xd=e=>{switch(e[3]){case"cpu":return new Lt(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!ni(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(!si(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]}`)}},Dh=class{async fetchModelAndCopyToWasmMemory(e){return Ph(await ai(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 Fh(r,t),Rr()}async dispose(){return Ih(this.sessionId)}async run(e,t,r){Br();let n=[],s=[];Object.entries(e).forEach(h=>{let p=h[0],m=h[1],w=this.inputNames.indexOf(p);if(w===-1)throw new Error(`invalid input '${p}'`);n.push(m),s.push(w)});let a=[],o=[];Object.entries(t).forEach(h=>{let p=h[0],m=h[1],w=this.outputNames.indexOf(p);if(w===-1)throw new Error(`invalid output '${p}'`);a.push(m),o.push(w)});let i=n.map((h,p)=>Mo(h,()=>`input "${this.inputNames[s[p]]}"`)),l=a.map((h,p)=>h?Mo(h,()=>`output "${this.outputNames[o[p]]}"`):null),u=await Lh(this.sessionId,s,i,o,l,r),d={};for(let h=0;h<u.length;h++)d[this.outputNames[o[h]]]=a[h]??Xd(u[h]);return Rr(),d}startProfiling(){}endProfiling(){Oh(this.sessionId)}}}),zh={};es(zh,{OnnxruntimeWebAssemblyBackend:()=>Bo,initializeFlags:()=>zo,wasmBackend:()=>Bh});var zo,Bo,Bh,By=pe(()=>{$r(),Nh(),zy(),zo=()=>{(typeof Oe.wasm.initTimeout!="number"||Oe.wasm.initTimeout<0)&&(Oe.wasm.initTimeout=0);let e=Oe.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.`),Oe.wasm.simd=!1),typeof Oe.wasm.proxy!="boolean"&&(Oe.wasm.proxy=!1),typeof Oe.wasm.trace!="boolean"&&(Oe.wasm.trace=!1),typeof Oe.wasm.numThreads!="number"||!Number.isInteger(Oe.wasm.numThreads)||Oe.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Oe.wasm.numThreads=1;else{let t=typeof navigator>"u"?_y("node:os").cpus().length:navigator.hardwareConcurrency;Oe.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Bo=class{async init(e){zo(),await Ch(),await Sh(e)}async createInferenceSessionHandler(e,t){let r=new Dh;return await r.loadModel(e,t),r}},Bh=new Bo});$r();$r();$r();var Ry="1.25.0-dev.20260228-6e72d31970",$y=uh;{let e=(By(),Rs(zh)).wasmBackend;Nr("webgpu",e,5),Nr("webnn",e,5),Nr("cpu",e,10),Nr("wasm",e,10)}Object.defineProperty(Oe.versions,"web",{value:Ry,enumerable:!0});var Gy=Object.freeze({__proto__:null,get InferenceSession(){return Ko},get TRACE(){return $s},get TRACE_EVENT_BEGIN(){return wr},get TRACE_EVENT_END(){return vr},get TRACE_FUNC_BEGIN(){return Br},get TRACE_FUNC_END(){return Rr},get Tensor(){return Lt},default:$y,get env(){return Oe},get registerBackend(){return Nr}});const Uy=(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 d=a*s;let h=0,p=d,m=d*2,w=-1;o==="RGBA"?(h=0,p=d,m=d*2,w=d*3):o==="RGB"?(h=0,p=d,m=d*2):o==="RBG"&&(h=0,m=d,p=d*2);for(let v=0;v<a;v++)for(let b=0;b<s;b++){const M=(e.data[h++]-u[0])*l[0],k=(e.data[p++]-u[1])*l[1],A=(e.data[m++]-u[2])*l[2],E=w===-1?255:(e.data[w++]-u[3])*l[3];n.fillStyle="rgba("+M+","+k+","+A+","+E+")",n.fillRect(b,v,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")},Vy=(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,d;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[3]=l.mean[3])),l===void 0||l.bias===void 0?d=[0,0,0,0]:typeof l.bias=="number"?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(d[3]=l.bias[3]));const h=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 m=0,w=1,v=2,b=3,M=0,k=h,A=h*2,E=-1;i==="RGBA"?(M=0,k=h,A=h*2,E=h*3):i==="RGB"?(M=0,k=h,A=h*2):i==="RBG"&&(M=0,A=h,k=h*2),n=r.createImageData(s,a);for(let C=0;C<a*s;m+=p,w+=p,v+=p,b+=p,C++)n.data[m]=(e.data[M++]-d[0])*u[0],n.data[w]=(e.data[k++]-d[1])*u[1],n.data[v]=(e.data[A++]-d[2])*u[2],n.data[b]=E===-1?255:(e.data[E++]-d[3])*u[3]}else throw new Error("Can not access image data");return n},xo=(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,d=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3);let h=4,p=0,m=1,w=2,v=3,b=0,M=u,k=u*2,A=-1;i==="RGB"&&(h=3,p=0,m=1,w=2,v=-1),l==="RGBA"?A=u*3:l==="RBG"?(b=0,k=u,M=u*2):l==="BGR"&&(k=0,M=u,b=u*2);for(let C=0;C<u;C++,p+=h,w+=h,m+=h,v+=h)d[b++]=(e[p]+o[0])/a[0],d[M++]=(e[m]+o[1])/a[1],d[k++]=(e[w]+o[2])/a[2],A!==-1&&v!==-1&&(d[A++]=(e[v]+o[3])/a[3]);return l==="RGBA"?new Et("float32",d,[1,4,r,n]):new Et("float32",d,[1,3,r,n])},jy=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=d=>typeof HTMLCanvasElement<"u"&&d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?d.getContext("2d"):null;if(r){const d=l();d.width=e.width,d.height=e.height;const h=u(d);if(h!=null){let p=e.height,m=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(p=t.resizedHeight,m=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=m}else i.tensorFormat="RGBA",i.height=p,i.width=m;h.drawImage(e,0,0),o=h.getImageData(0,0,m,p).data}else throw new Error("Can not access image data")}else if(n){let d,h;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(d=t.resizedHeight,h=t.resizedWidth):(d=e.height,h=e.width),t!==void 0&&(i=t),i.format="RGBA",i.height=d,i.width=h,t!==void 0){const p=l();p.width=h,p.height=d;const m=u(p);if(m!=null)m.putImageData(e,0,0),o=m.getImageData(0,0,h,d).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 d=l();d.width=e.width,d.height=e.height;const h=u(d);if(h!=null){const p=e.height,m=e.width;return h.drawImage(e,0,0,m,p),o=h.getImageData(0,0,m,p).data,i.height=p,i.width=m,xo(o,i)}else throw new Error("Can not access image data")}else{if(a)return new Promise((d,h)=>{const p=l(),m=u(p);if(!e||!m)return h();const w=new Image;w.crossOrigin="Anonymous",w.src=e,w.onload=()=>{p.width=w.width,p.height=w.height,m.drawImage(w,0,0,p.width,p.height);const v=m.getImageData(0,0,p.width,p.height);i.height=p.height,i.width=p.width,d(xo(v.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return xo(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},Wy=(e,t)=>{const{width:r,height:n,download:s,dispose:a}=t,o=[1,n,r,4];return new Et({location:"texture",type:"float32",texture:e,dims:o,download:s,dispose:a})},qy=(e,t)=>{const{dataType:r,dims:n,download:s,dispose:a}=t;return new Et({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},Hy=(e,t)=>{const{dataType:r,dims:n,download:s,dispose:a}=t;return new Et({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:s,dispose:a})},Qy=(e,t,r)=>new Et({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]]),Ds=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Yd=!1;const Xy=()=>{if(!Yd){Yd=!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),Ds.set(BigInt64Array,"int64")),t&&(sn.set("uint64",BigUint64Array),Ds.set(BigUint64Array,"uint64")),n?(sn.set("float16",r),Ds.set(r,"float16")):sn.set("float16",Uint16Array)}},Yy=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},Jy=(e,t)=>{switch(e.location){case"cpu":return new Et(e.type,e.data,t);case"cpu-pinned":return new Et({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Et({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Et({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Et({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let Et=class{constructor(t,r,n){Xy();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=Ds.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=Yy(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 jy(t,r)}static fromTexture(t,r){return Wy(t,r)}static fromGpuBuffer(t,r){return qy(t,r)}static fromMLTensor(t,r){return Hy(t,r)}static fromPinnedBuffer(t,r,n){return Qy(t,r,n)}toDataURL(t){return Uy(this,t)}toImageData(t){return Vy(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 Jy(this,t)}};const Ky=Et;var To={},Zy=Object.defineProperty,fn=(e,t)=>{for(var r in t)Zy(e,r,{get:t[r],enumerable:!0})},kt={},Qt={},eb={},tb="4.0.0-next.5",on=!Wh(kt),Rh=!Wh(Qt),js=typeof self<"u"&&"caches"in self,rb=typeof globalThis.Deno<"u",$h=rb&&js&&!on,Gh=typeof process<"u",Uh=Gh&&process?.release?.name==="node"&&!$h,Vh=typeof window<"u"&&typeof window.document<"u",jh=typeof self<"u"&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),nb=Uh||typeof navigator<"u"&&"gpu"in navigator,sb=typeof navigator<"u"&&"ml"in navigator,ab=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",ob=()=>{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},ib=ob(),Ie=Object.freeze({IS_BROWSER_ENV:Vh,IS_WEBWORKER_ENV:jh,IS_WEB_CACHE_AVAILABLE:js,IS_WEBGPU_AVAILABLE:nb,IS_WEBNN_AVAILABLE:sb,IS_SAFARI:ib,IS_PROCESS_AVAILABLE:Gh,IS_NODE_ENV:Uh,IS_FS_AVAILABLE:on,IS_PATH_AVAILABLE:Rh,IS_CRYPTO_AVAILABLE:ab}),hi=on&&Rh,Ws="./";if(hi){const e=Object(import.meta).url;e?Ws=Qt.dirname(Qt.dirname(eb.fileURLToPath(e))):typeof __dirname<"u"&&(Ws=Qt.dirname(__dirname))}var lb=hi?Qt.join(Ws,"/.cache/"):null,Jd="/models/",cb=hi?Qt.join(Ws,Jd):Jd,ub=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,Ot=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),Kd=Ot.WARNING,ye={version:tb,backends:{onnx:{}},get logLevel(){return Kd},set logLevel(e){Kd=e,ye.backends.onnx?.setLogLevel?.(e)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(Vh||jh||$h),localModelPath:cb,useFS:on,useBrowserCache:js,useFSCache:on,cacheDir:lb,useCustomCache:!1,customCache:null,useWasmCache:js||on,cacheKey:"transformers-cache",fetch:ub};function Wh(e){return Object.keys(e).length===0}function Dr(e,t){e&&e(t)}function db(e){return Number.isInteger(e)||typeof e=="bigint"}function Zd(e){return e==null||e===-1}function ef(e){const t=[];let r=e;for(;Array.isArray(r);)t.push(r.length),r=r[0];return t}function Xt(...e){return Array.prototype.concat.apply([],e)}function fb(...e){return e.reduce((t,r)=>t.flatMap(n=>r.map(s=>[n,s])))}function qs(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 hb(e,t){let r=0;for(const n of e)n===t&&++r;return r}var oe={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)}},pb=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}},tf=pb,_b=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}},mb=_b,qh=(()=>{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]]))})(),gb=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[r,t])),wb=gb(qh),rf=".,!?…。,、।۔،",vb=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|[${rf}])]+`,` ?[^\\s${rf}]+`]]),Hs="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",pi=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"),ra=(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 vb)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=yb(e.String);return new RegExp(t?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",e),null},yb=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),bb=(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},Mb=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,xb=e=>Number.isInteger(e)||typeof e=="bigint",Tb=e=>{let t=0;for(const r of e)++t;return t},kb=e=>Hh(e.toLowerCase()),Nt=(...e)=>Array.prototype.concat.apply([],e),_i=e=>new Map(Object.entries(e)),Eb=(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},Hh=e=>e.replace(/\p{M}/gu,""),nf=(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},Ab=e=>e.match(/\S+/g)||[],Cb=class{constructor(){const e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},ts=Cb,Sb=class extends ts{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},or=Sb,Pb=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);Mb(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}},Fb=Pb,Ib=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}},Lb=Ib,Ob=class extends or{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(t=>Qh(t))}normalize(e){return this.normalizers.reduce((t,r)=>r?r.normalize(t):t,e)}},Nb=Ob,Db=class extends or{normalize(e){const t=ra(this.config.pattern??{});return t===null?e:e.replaceAll(t,this.config.content??"")}},zb=Db,Bb=class extends or{constructor(){super(...arguments),this.form="NFC"}normalize(e){return e=e.normalize(this.form),e}},na=Bb,Rb=class extends na{constructor(){super(...arguments),this.form="NFC"}},$b=Rb,Gb=class extends na{constructor(){super(...arguments),this.form="NFD"}},Ub=Gb,Vb=class extends na{constructor(){super(...arguments),this.form="NFKC"}},jb=Vb,Wb=class extends na{constructor(){super(...arguments),this.form="NFKD"}},qb=Wb,Hb=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}},Qb=Hb,Xb=class extends or{normalize(e){return Hh(e)}},Yb=Xb,Jb=class extends or{normalize(e){return e.toLowerCase()}},Kb=Jb,Zb=class extends or{normalize(e){return e=this.config.prepend+e,e}},e0=Zb;function t0(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new Fb(e);case"Precompiled":return new Lb(e);case"Sequence":return new Nb(e);case"Replace":return new zb(e);case"NFC":return new $b(e);case"NFD":return new Ub(e);case"NFKC":return new jb(e);case"NFKD":return new qb(e);case"Strip":return new Qb(e);case"StripAccents":return new Yb(e);case"Lowercase":return new Kb(e);case"Prepend":return new e0(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}var Qh=t0,r0=class extends ts{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)}},Bt=r0,n0=class extends Bt{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=qh,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(""))}},s0=n0,a0=class extends Bt{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},o0=a0,i0=class extends Bt{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]}},l0=i0,c0=class extends Bt{constructor(e){super(),this.config=e,this.pattern=ra(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):Eb(e,this.pattern)}},u0=c0,d0=class extends Bt{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${Hs}]+|[${Hs}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},f0=d0,h0=class extends Bt{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)||[]}},p0=h0,_0=class extends Bt{constructor(){super(),this.pattern=new RegExp(`[^\\s${Hs}]+|[${Hs}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},m0=_0,g0=class extends Bt{constructor(e){super(),this.config=e,this.pattern=ra(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??"")]}},w0=g0,v0=class extends Bt{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(t=>Xh(t))}pre_tokenize_text(e,t){return this.tokenizers.reduce((r,n)=>n?n.pre_tokenize(r,t):r,[e])}},y0=v0,b0=class extends Bt{pre_tokenize_text(e){return Ab(e)}},M0=b0,x0=class extends Bt{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}},T0=x0;function k0(e){if(e===null)return null;switch(e.type){case"BertPreTokenizer":return new m0;case"Sequence":return new y0(e);case"Whitespace":return new o0;case"WhitespaceSplit":return new M0;case"Metaspace":return new l0(e);case"ByteLevel":return new s0(e);case"Split":return new u0(e);case"Punctuation":return new f0(e);case"Digits":return new p0(e);case"Replace":return new w0(e);case"FixedLength":return new T0(e);default:throw new Error(`Unknown PreTokenizer type: ${e.type}`)}}var Xh=k0,E0=class extends ts{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=bb(t,this.tokens_to_ids,this.unk_token_id)),t}},sa=E0,A0=class extends sa{constructor(e){super(e),this.max_input_chars_per_word=100,this.tokens_to_ids=_i(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}},sf=A0,af=class Yh{constructor(t,r){this.is_leaf=t,this.children=r}static default(){return new Yh(!1,new Map)}},C0=class{constructor(){this.root=af.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=af.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)}}},S0=C0,ko=class Jh{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 Jh(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},P0=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 ko(this.bos_token_id??0,0,0,0,0),s=new ko(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 ko(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 d=u.backtrace_score+o.score;(l===null||d>i)&&(l=u.clone(),i=d)}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)}},F0=P0;function I0(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 L0=class extends sa{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=I0(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new S0,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],d=Tb(i);e.insert(n,d,u,l),!s&&d===r&&(s=!0)}s||e.insert(n,r,this.unk_score,this.unk_token_id),n+=r}}tokenize(e){const t=new F0(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}},of=L0,O0=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}},N0=O0,D0=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()}},z0=D0,B0=class extends sa{constructor(e){super(e),this.tokens_to_ids=_i(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 z0(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 N0((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}},lf=B0,R0=class extends sa{constructor(e,t){super(e);const r=e.vocab;this.tokens_to_ids=_i(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}},$0=R0;function G0(e,t){switch(e.type){case"WordPiece":return new sf(e);case"Unigram":return new of(e,t.eos_token);case"BPE":return new lf(e);default:if(e.vocab)return Array.isArray(e.vocab)?new of(e,t.eos_token):Object.hasOwn(e,"continuing_subword_prefix")&&Object.hasOwn(e,"unk_token")?Object.hasOwn(e,"merges")?new lf(e):new sf(e):new $0(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 U0=G0,V0=class extends ts{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},rs=V0,j0=class extends rs{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=Nt(s,e),a=Nt(a,new Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id==="B"&&(s=Nt(s,t),a=Nt(a,new Array(t.length).fill(o.Sequence.type_id))));return{tokens:s,token_type_ids:a}}},W0=j0,q0=class extends rs{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},H0=q0,Q0=class extends rs{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,r=!0){r&&(e=Nt([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=Nt(e,s,t,a),n=Nt(n,new Array(t.length+s.length+a.length).fill(1))}return{tokens:e,token_type_ids:n}}},X0=Q0,Y0=class extends rs{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,r=!0){r&&(e=Nt([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=Nt(e,s,t,a),n=Nt(n,new Array(t.length+s.length+a.length).fill(1))}return{tokens:e,token_type_ids:n}}},J0=Y0,K0=class extends rs{constructor(e){super(e),this.processors=(e.processors??[]).map(t=>Kh(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}},Z0=K0;function eM(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new W0(e);case"ByteLevel":return new H0(e);case"BertProcessing":return new X0(e);case"RobertaProcessing":return new J0(e);case"Sequence":return new Z0(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}var Kh=eM,tM=class extends ts{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=tM,rM=class extends Rt{constructor(e){super(e),this.byte_decoder=wb,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}},nM=rM,sM=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=pi(t)),t})}},aM=sM,oM=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}},iM=oM,lM=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?"":" "))}},cM=lM,uM=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=pi(n).replaceAll(this.word_delimiter_token," ").trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}},dM=uM,fM=class extends Rt{constructor(e){super(e),this.decoders=(e.decoders??[]).map(t=>Zh(t))}decode_chain(e){return this.decoders.reduce((t,r)=>r.decode_chain(t),e)}},hM=fM,pM=class extends Rt{decode_chain(e){const t=ra(this.config.pattern),r=this.config.content??"";return t===null?e:e.map(n=>n.replaceAll(t,r))}},_M=pM,mM=class extends Rt{decode_chain(e){return[e.join("")]}},gM=mM,wM=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)})}},vM=wM,yM=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}},bM=yM;function MM(e){if(e===null)return null;switch(e.type){case"ByteLevel":return new nM(e);case"WordPiece":return new aM(e);case"Metaspace":return new iM(e);case"BPEDecoder":return new cM(e);case"CTC":return new dM(e);case"Sequence":return new hM(e);case"Replace":return new _M(e);case"Fuse":return new gM(e);case"Strip":return new vM(e);case"ByteFallback":return new bM(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}var Zh=MM,xM=class{constructor(e,t){const r=nf(e,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);const n=nf(t,"Config");if(n)throw new Error(n);this.tokenizer=e,this.config=t,this.normalizer=Qh(this.tokenizer.normalizer),this.pre_tokenizer=Xh(this.tokenizer.pre_tokenizer),this.model=U0(this.tokenizer.model,this.config),this.post_processor=Kh(this.tokenizer.post_processor),this.decoder=Zh(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 mb(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 tf(s),this.splitter_normalized=new tf(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||!xb(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=pi(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=kb(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:Nt(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}},TM=xM,D=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),xt=class{constructor(e,t){this.value=e,this.type=t}};function cf(e){return/\w/.test(e)}function Un(e){return/[0-9]/.test(e)}function uf(e){return/\s/.test(e)}var kM=[["{%",D.OpenStatement],["%}",D.CloseStatement],["{{",D.OpenExpression],["}}",D.CloseExpression],["(",D.OpenParen],[")",D.CloseParen],["{",D.OpenCurlyBracket],["}",D.CloseCurlyBracket],["[",D.OpenSquareBracket],["]",D.CloseSquareBracket],[",",D.Comma],[".",D.Dot],[":",D.Colon],["|",D.Pipe],["<=",D.ComparisonBinaryOperator],[">=",D.ComparisonBinaryOperator],["==",D.ComparisonBinaryOperator],["!=",D.ComparisonBinaryOperator],["<",D.ComparisonBinaryOperator],[">",D.ComparisonBinaryOperator],["+",D.AdditiveBinaryOperator],["-",D.AdditiveBinaryOperator],["~",D.AdditiveBinaryOperator],["*",D.MultiplicativeBinaryOperator],["/",D.MultiplicativeBinaryOperator],["%",D.MultiplicativeBinaryOperator],["=",D.Equals]],EM=new Map([["n",`
10
+ `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function AM(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 CM(e,t={}){const r=[],n=AM(e,t);let s=0,a=0;const o=u=>{let d="";for(;u(n[s]);){if(n[s]==="\\"){if(++s,s>=n.length)throw new SyntaxError("Unexpected end of input");const h=n[s++],p=EM.get(h);if(p===void 0)throw new SyntaxError(`Unexpected escaped character: ${h}`);d+=p;continue}if(d+=n[s++],s>=n.length)throw new SyntaxError("Unexpected end of input")}return d},i=()=>{const u=r.at(-1);u&&u.type===D.Text&&(u.value=u.value.trimEnd(),u.value===""&&r.pop())},l=()=>{for(;s<n.length&&uf(n[s]);)++s};e:for(;s<n.length;){const u=r.at(-1)?.type;if(u===void 0||u===D.CloseStatement||u===D.CloseExpression||u===D.Comment){let h="";for(;s<n.length&&!(n[s]==="{"&&(n[s+1]==="%"||n[s+1]==="{"||n[s+1]==="#"));)h+=n[s++];if(h.length>0){r.push(new xt(h,D.Text));continue}}if(n[s]==="{"&&n[s+1]==="#"){s+=2;const h=n[s]==="-";h&&++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 m=p.endsWith("-");m&&(p=p.slice(0,-1)),h&&i(),r.push(new xt(p,D.Comment)),s+=2,m&&l();continue}if(n.slice(s,s+3)==="{%-"){i(),r.push(new xt("{%",D.OpenStatement)),s+=3;continue}if(n.slice(s,s+3)==="{{-"){i(),r.push(new xt("{{",D.OpenExpression)),a=0,s+=3;continue}if(o(uf),n.slice(s,s+3)==="-%}"){r.push(new xt("%}",D.CloseStatement)),s+=3,l();continue}if(n.slice(s,s+3)==="-}}"){r.push(new xt("}}",D.CloseExpression)),s+=3,l();continue}const d=n[s];if(d==="-"||d==="+"){const h=r.at(-1)?.type;if(h===D.Text||h===void 0)throw new SyntaxError(`Unexpected character: ${d}`);switch(h){case D.Identifier:case D.NumericLiteral:case D.StringLiteral:case D.CloseParen:case D.CloseSquareBracket:break;default:{++s;const p=o(Un);r.push(new xt(`${d}${p}`,p.length>0?D.NumericLiteral:D.UnaryOperator));continue}}}for(const[h,p]of kM){if(h==="}}"&&a>0)continue;if(n.slice(s,s+h.length)===h){r.push(new xt(h,p)),p===D.OpenExpression?a=0:p===D.OpenCurlyBracket?++a:p===D.CloseCurlyBracket&&--a,s+=h.length;continue e}}if(d==="'"||d==='"'){++s;const h=o(p=>p!==d);r.push(new xt(h,D.StringLiteral)),++s;continue}if(Un(d)){let h=o(Un);if(n[s]==="."&&Un(n[s+1])){++s;const p=o(Un);h=`${h}.${p}`}r.push(new xt(h,D.NumericLiteral));continue}if(cf(d)){const h=o(cf);r.push(new xt(h,D.Identifier));continue}throw new SyntaxError(`Unexpected character: ${d}`)}return r}var $t=class{type="Statement"},SM=class extends $t{constructor(e){super(),this.body=e}type="Program"},PM=class extends $t{constructor(e,t,r){super(),this.test=e,this.body=t,this.alternate=r}type="If"},FM=class extends $t{constructor(e,t,r,n){super(),this.loopvar=e,this.iterable=t,this.body=r,this.defaultBlock=n}type="For"},IM=class extends $t{type="Break"},LM=class extends $t{type="Continue"},OM=class extends $t{constructor(e,t,r){super(),this.assignee=e,this.value=t,this.body=r}type="Set"},NM=class extends $t{constructor(e,t,r){super(),this.name=e,this.args=t,this.body=r}type="Macro"},DM=class extends $t{constructor(e){super(),this.value=e}type="Comment"},yt=class extends $t{type="Expression"},zM=class extends yt{constructor(e,t,r){super(),this.object=e,this.property=t,this.computed=r}type="MemberExpression"},df=class extends yt{constructor(e,t){super(),this.callee=e,this.args=t}type="CallExpression"},Kr=class extends yt{constructor(e){super(),this.value=e}type="Identifier"},hn=class extends yt{constructor(e){super(),this.value=e}type="Literal"},BM=class extends hn{type="IntegerLiteral"},RM=class extends hn{type="FloatLiteral"},ff=class extends hn{type="StringLiteral"},$M=class extends hn{type="ArrayLiteral"},hf=class extends hn{type="TupleLiteral"},GM=class extends hn{type="ObjectLiteral"},Vn=class extends yt{constructor(e,t,r){super(),this.operator=e,this.left=t,this.right=r}type="BinaryExpression"},UM=class extends yt{constructor(e,t){super(),this.operand=e,this.filter=t}type="FilterExpression"},VM=class extends $t{constructor(e,t){super(),this.filter=e,this.body=t}type="FilterStatement"},jM=class extends yt{constructor(e,t){super(),this.lhs=e,this.test=t}type="SelectExpression"},WM=class extends yt{constructor(e,t,r){super(),this.operand=e,this.negate=t,this.test=r}type="TestExpression"},qM=class extends yt{constructor(e,t){super(),this.operator=e,this.argument=t}type="UnaryExpression"},HM=class extends yt{constructor(e=void 0,t=void 0,r=void 0){super(),this.start=e,this.stop=t,this.step=r}type="SliceExpression"},QM=class extends yt{constructor(e,t){super(),this.key=e,this.value=t}type="KeywordArgumentExpression"},XM=class extends yt{constructor(e){super(),this.argument=e}type="SpreadExpression"},YM=class extends $t{constructor(e,t,r){super(),this.call=e,this.callerArgs=t,this.body=r}type="CallStatement"},JM=class extends yt{constructor(e,t,r){super(),this.condition=e,this.trueExpr=t,this.falseExpr=r}type="Ternary"};function KM(e){const t=new SM([]);let r=0;function n(F,L){const z=e[r++];if(!z||z.type!==F)throw new Error(`Parser Error: ${L}. ${z.type} !== ${F}.`);return z}function s(F){if(!l(F))throw new SyntaxError(`Expected ${F}`);++r}function a(){switch(e[r].type){case D.Comment:return new DM(e[r++].value);case D.Text:return u();case D.OpenStatement:return d();case D.OpenExpression:return h();default:throw new SyntaxError(`Unexpected token type: ${e[r].type}`)}}function o(...F){return r+F.length<=e.length&&F.every((L,z)=>L===e[r+z].type)}function i(...F){return e[r]?.type===D.OpenStatement&&e[r+1]?.type===D.Identifier&&F.includes(e[r+1]?.value)}function l(...F){return r+F.length<=e.length&&F.every((L,z)=>e[r+z].type==="Identifier"&&L===e[r+z].value)}function u(){return new ff(n(D.Text,"Expected text token").value)}function d(){if(n(D.OpenStatement,"Expected opening statement token"),e[r].type!==D.Identifier)throw new SyntaxError(`Unknown statement, got ${e[r].type}`);const F=e[r].value;let L;switch(F){case"set":++r,L=p();break;case"if":++r,L=m(),n(D.OpenStatement,"Expected {% token"),s("endif"),n(D.CloseStatement,"Expected %} token");break;case"macro":++r,L=w(),n(D.OpenStatement,"Expected {% token"),s("endmacro"),n(D.CloseStatement,"Expected %} token");break;case"for":++r,L=b(),n(D.OpenStatement,"Expected {% token"),s("endfor"),n(D.CloseStatement,"Expected %} token");break;case"call":{++r;let z=null;o(D.OpenParen)&&(z=W());const K=X();if(K.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");const le=W();n(D.CloseStatement,"Expected closing statement token");const Te=[];for(;!i("endcall");)Te.push(a());n(D.OpenStatement,"Expected '{%'"),s("endcall"),n(D.CloseStatement,"Expected closing statement token");const Se=new df(K,le);L=new YM(Se,z,Te);break}case"break":++r,n(D.CloseStatement,"Expected closing statement token"),L=new IM;break;case"continue":++r,n(D.CloseStatement,"Expected closing statement token"),L=new LM;break;case"filter":{++r;let z=X();z instanceof Kr&&o(D.OpenParen)&&(z=G(z)),n(D.CloseStatement,"Expected closing statement token");const K=[];for(;!i("endfilter");)K.push(a());n(D.OpenStatement,"Expected '{%'"),s("endfilter"),n(D.CloseStatement,"Expected '%}'"),L=new VM(z,K);break}default:throw new SyntaxError(`Unknown statement type: ${F}`)}return L}function h(){n(D.OpenExpression,"Expected opening expression token");const F=M();return n(D.CloseExpression,"Expected closing expression token"),F}function p(){const F=v();let L=null;const z=[];if(o(D.Equals))++r,L=v();else{for(n(D.CloseStatement,"Expected %} token");!i("endset");)z.push(a());n(D.OpenStatement,"Expected {% token"),s("endset")}return n(D.CloseStatement,"Expected closing statement token"),new OM(F,L,z)}function m(){const F=M();n(D.CloseStatement,"Expected closing statement token");const L=[],z=[];for(;!i("elif","else","endif");)L.push(a());if(i("elif")){++r,++r;const K=m();z.push(K)}else if(i("else"))for(++r,++r,n(D.CloseStatement,"Expected closing statement token");!i("endif");)z.push(a());return new PM(F,L,z)}function w(){const F=X();if(F.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const L=W();n(D.CloseStatement,"Expected closing statement token");const z=[];for(;!i("endmacro");)z.push(a());return new NM(F,L,z)}function v(F=!1){const L=F?X:M,z=[L()],K=o(D.Comma);for(;K&&(++r,z.push(L()),!!o(D.Comma)););return K?new hf(z):z[0]}function b(){const F=v(!0);if(!(F instanceof Kr||F instanceof hf))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${F.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;const L=M();n(D.CloseStatement,"Expected closing statement token");const z=[];for(;!i("endfor","else");)z.push(a());const K=[];if(i("else"))for(++r,++r,n(D.CloseStatement,"Expected closing statement token");!i("endfor");)K.push(a());return new FM(F,L,z,K)}function M(){return k()}function k(){const F=A();if(l("if")){++r;const L=A();if(l("else")){++r;const z=k();return new JM(L,F,z)}else return new jM(F,L)}return F}function A(){let F=E();for(;l("or");){const L=e[r];++r;const z=E();F=new Vn(L,F,z)}return F}function E(){let F=C();for(;l("and");){const L=e[r];++r;const z=C();F=new Vn(L,F,z)}return F}function C(){let F;for(;l("not");){const L=e[r];++r;const z=C();F=new qM(L,z)}return F??O()}function O(){let F=x();for(;;){let L;if(l("not","in"))L=new xt("not in",D.Identifier),r+=2;else if(l("in"))L=e[r++];else if(o(D.ComparisonBinaryOperator))L=e[r++];else break;const z=x();F=new Vn(L,F,z)}return F}function x(){let F=N();for(;o(D.AdditiveBinaryOperator);){const L=e[r];++r;const z=N();F=new Vn(L,F,z)}return F}function V(){const F=B(X());return o(D.OpenParen)?G(F):F}function G(F){let L=new df(F,W());return L=B(L),o(D.OpenParen)&&(L=G(L)),L}function W(){n(D.OpenParen,"Expected opening parenthesis for arguments list");const F=J();return n(D.CloseParen,"Expected closing parenthesis for arguments list"),F}function J(){const F=[];for(;!o(D.CloseParen);){let L;if(e[r].type===D.MultiplicativeBinaryOperator&&e[r].value==="*"){++r;const z=M();L=new XM(z)}else if(L=M(),o(D.Equals)){if(++r,!(L instanceof Kr))throw new SyntaxError("Expected identifier for keyword argument");const z=M();L=new QM(L,z)}F.push(L),o(D.Comma)&&++r}return F}function q(){const F=[];let L=!1;for(;!o(D.CloseSquareBracket);)o(D.Colon)?(F.push(void 0),++r,L=!0):(F.push(M()),o(D.Colon)&&(++r,L=!0));if(F.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(L){if(F.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new HM(...F)}return F[0]}function B(F){for(;o(D.Dot)||o(D.OpenSquareBracket);){const L=e[r];++r;let z;const K=L.type===D.OpenSquareBracket;if(K)z=q(),n(D.CloseSquareBracket,"Expected closing square bracket");else if(z=X(),z.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");F=new zM(F,z,K)}return F}function N(){let F=U();for(;o(D.MultiplicativeBinaryOperator);){const L=e[r++],z=U();F=new Vn(L,F,z)}return F}function U(){let F=ee();for(;l("is");){++r;const L=l("not");L&&++r;const z=X();if(!(z instanceof Kr))throw new SyntaxError("Expected identifier for the test");F=new WM(F,L,z)}return F}function ee(){let F=V();for(;o(D.Pipe);){++r;let L=X();if(!(L instanceof Kr))throw new SyntaxError("Expected identifier for the filter");o(D.OpenParen)&&(L=G(L)),F=new UM(F,L)}return F}function X(){const F=e[r++];switch(F.type){case D.NumericLiteral:{const L=F.value;return L.includes(".")?new RM(Number(L)):new BM(Number(L))}case D.StringLiteral:{let L=F.value;for(;o(D.StringLiteral);)L+=e[r++].value;return new ff(L)}case D.Identifier:return new Kr(F.value);case D.OpenParen:{const L=v();return n(D.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),L}case D.OpenSquareBracket:{const L=[];for(;!o(D.CloseSquareBracket);)L.push(M()),o(D.Comma)&&++r;return++r,new $M(L)}case D.OpenCurlyBracket:{const L=new Map;for(;!o(D.CloseCurlyBracket);){const z=M();n(D.Colon,"Expected colon between key and value in object literal");const K=M();L.set(z,K),o(D.Comma)&&++r}return++r,new GM(L)}default:throw new SyntaxError(`Unexpected token: ${F.type}`)}}for(;r<e.length;)t.body.push(a());return t}function ZM(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 pf(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 ex(e){return e.replace(/\b\w/g,t=>t.toUpperCase())}function tx(e){return rx(new Date,e)}function rx(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 nx(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function sx(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(nx(t),"gu");return e.replaceAll(a,o=>s>0?(--s,r):o)}var _f=class extends Error{},mf=class extends Error{},Yt=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)}},ie=class extends Yt{type="IntegerValue"},Re=class extends Yt{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},Y=class extends Yt{type="StringValue";builtins=new Map([["upper",new Fe(()=>new Y(this.value.toUpperCase()))],["lower",new Fe(()=>new Y(this.value.toLowerCase()))],["strip",new Fe(()=>new Y(this.value.trim()))],["title",new Fe(()=>new Y(ex(this.value)))],["capitalize",new Fe(()=>new Y(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new ie(this.value.length)],["rstrip",new Fe(()=>new Y(this.value.trimEnd()))],["lstrip",new Fe(()=>new Y(this.value.trimStart()))],["startswith",new Fe(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 ge){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 Fe(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 ge){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 Fe(e=>{const t=e[0]??new Ne;if(!(t instanceof Y||t instanceof Ne))throw new Error("sep argument must be a string or null");const r=e[1]??new ie(-1);if(!(r instanceof ie))throw new Error("maxsplit argument must be a number");let n=[];if(t instanceof Ne){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 ge(n.map(s=>new Y(s)))})],["replace",new Fe(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 Ne:n=e[2]:n=new Ne,!(n instanceof ie||n instanceof Ne))throw new Error("replace() count argument must be a number or null");return new Y(sx(this.value,t.value,r.value,n.value))})]])},ne=class extends Yt{type="BooleanValue"},ax=/[\x7f-\uffff]/g;function gf(e){return e.replace(ax,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))}function zr(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 d=JSON.stringify(e.value);return a&&(d=gf(d)),d}case"ArrayValue":case"ObjectValue":{const d=s?" ".repeat(s):"",h=`
12
+ `+d.repeat(r),p=h+d;if(e.type==="ArrayValue"){const m=e.value.map(w=>zr(w,t,r+1,n));return s?`[${p}${m.join(`${l}${p}`)}${h}]`:`[${m.join(l)}]`}else{let m=Array.from(e.value.entries());i&&(m=m.sort(([v],[b])=>v.localeCompare(b)));const w=m.map(([v,b])=>{let M=JSON.stringify(v);a&&(M=gf(M));const k=`${M}${u}${zr(b,t,r+1,n)}`;return s?`${p}${k}`:k});return s?`{${w.join(l)}${h}}`:`{${w.join(l)}}`}}default:throw new Error(`Cannot convert to JSON: ${e.type}`)}}var rt=class extends Yt{type="ObjectValue";__bool__(){return new ne(this.value.size>0)}builtins=new Map([["get",new Fe(([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 Ne})],["items",new Fe(()=>this.items())],["keys",new Fe(()=>this.keys())],["values",new Fe(()=>this.values())],["dictsort",new Fe(e=>{let t=new Map;const r=e.filter(i=>i instanceof Wn?(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 ge([new Y(i),l])).sort((i,l)=>{const u=s.value==="key"?0:1,d=i.value[u],h=l.value[u],p=Ro(d,h,n.value);return a.value?-p:p});return new ge(o)})]]);items(){return new ge(Array.from(this.value.entries()).map(([e,t])=>new ge([new Y(e),t])))}keys(){return new ge(Array.from(this.value.keys()).map(e=>new Y(e)))}values(){return new ge(Array.from(this.value.values()))}toString(){return zr(this,{},0,!1)}},Wn=class extends rt{type="KeywordArgumentsValue"},ge=class extends Yt{type="ArrayValue";builtins=new Map([["length",new ie(this.value.length)]]);__bool__(){return new ne(this.value.length>0)}toString(){return zr(this,{},0,!1)}},wf=class extends ge{type="TupleValue"},Fe=class extends Yt{type="FunctionValue"},Ne=class extends Yt{type="NullValue"},Pe=class extends Yt{type="UndefinedValue"},Fr=class{constructor(e){this.parent=e}variables=new Map([["namespace",new Fe(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 Fe],["odd",e=>{if(!(e instanceof ie))throw new Error(`cannot odd on ${e.type}`);return e.value%2!==0}],["even",e=>{if(!(e instanceof ie))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 ie||e instanceof Re],["integer",e=>e instanceof ie],["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,zs(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 Pe}catch{return new Pe}}};function ox(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",ZM),e.set("strftime_now",tx),e.set("True",!0),e.set("False",!1),e.set("None",null)}function vf(e,t){const r=t.split(".");let n=e;for(const s of r)if(n instanceof rt)n=n.value.get(s)??new Pe;else if(n instanceof ge){const a=parseInt(s,10);if(!isNaN(a)&&a>=0&&a<n.value.length)n=n.value[a];else return new Pe}else return new Pe;return n}function Ro(e,t,r=!1){if(e instanceof Ne&&t instanceof Ne)return 0;if(e instanceof Ne||t instanceof Ne)throw new Error(`Cannot compare ${e.type} with ${t.type}`);if(e instanceof Pe&&t instanceof Pe)return 0;if(e instanceof Pe||t instanceof Pe)throw new Error(`Cannot compare ${e.type} with ${t.type}`);const n=a=>a instanceof ie||a instanceof Re||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 ix=class{global;constructor(e){this.global=e??new Fr}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 Pe||n instanceof Pe){if(n instanceof Pe&&["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 Ne||n instanceof Ne)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 ie||r instanceof Re)&&(n instanceof ie||n instanceof Re)){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 Re||n instanceof Re?new Re(o):new ie(o)}case"/":return new Re(s/a);case"%":{const o=s%a;return r instanceof Re||n instanceof Re?new Re(o):new ie(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 ge&&n instanceof ge)switch(e.operator.value){case"+":return new ge(r.value.concat(n.value))}else if(n instanceof ge){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 ge))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(zr(e,{}));if(e instanceof ge)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 ie(e.value.length);case"reverse":return new ge(e.value.slice().reverse());case"sort":return new ge(e.value.slice().sort((s,a)=>Ro(s,a,!1)));case"join":return new Y(e.value.map(s=>s.value).join(""));case"string":return new Y(zr(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 ge(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 Fe)return s.value([],r);if(s instanceof ie)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 ie(isNaN(s)?0:s)}case"float":{const s=parseFloat(e.value);return new Re(isNaN(s)?0:s)}default:throw new Error(`Unknown StringValue filter: ${n.value}`)}else if(e instanceof ie||e instanceof Re)switch(n.value){case"abs":return e instanceof ie?new ie(Math.abs(e.value)):new Re(Math.abs(e.value));case"int":return new ie(Math.floor(e.value));case"float":return new Re(e.value);default:throw new Error(`Unknown NumericValue filter: ${n.value}`)}else if(e instanceof rt)switch(n.value){case"items":return new ge(Array.from(e.value.entries()).map(([s,a])=>new ge([new Y(s),a])));case"length":return new ie(e.value.size);default:{const s=e.builtins.get(n.value);if(s)return s instanceof Fe?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 ie(e.value?1:0);case"float":return new Re(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 Ne;if(!(o instanceof ie||o instanceof Ne))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 Ne;let d=null;if(u instanceof ge||u instanceof wf){if(u.value.length!==2)throw new Error("separators must be a tuple of two strings");const[h,p]=u.value;if(!(h instanceof Y)||!(p instanceof Y))throw new Error("separators must be a tuple of two strings");d=[h.value,p.value]}else if(!(u instanceof Ne))throw new Error("If set, separators must be a tuple of two strings");return new Y(zr(e,{indent:o.value,ensureAscii:i.value,sortKeys:l.value,separators:d}))}else if(s==="join"){let a;if(e instanceof Y)a=Array.from(e.value);else if(e instanceof ge)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 ie(0):new Re(0));if(e instanceof Y){const l=s==="int"?parseInt(e.value,10):parseFloat(e.value);return isNaN(l)?i:s==="int"?new ie(l):new Re(l)}else{if(e instanceof ie||e instanceof Re)return e;if(e instanceof ne)return s==="int"?new ie(e.value?1:0):new Re(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 Pe||l.value&&!e.__bool__().value?i:e}if(e instanceof ge){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 Ne;if(!(u instanceof Y||u instanceof ie||u instanceof Ne))throw new Error("attribute must be a string, integer, or null");const d=h=>{if(u instanceof Ne)return h;const p=u instanceof ie?String(u.value):u.value;return vf(h,p)};return new ge(e.value.slice().sort((h,p)=>{const m=d(h),w=d(p),v=Ro(m,w,l.value);return i.value?-v:v}))}case"selectattr":case"rejectattr":{const a=s==="selectattr";if(e.value.some(h=>!(h instanceof rt)))throw new Error(`\`${s}\` can only be applied to array of objects`);if(n.args.some(h=>h.type!=="StringLiteral"))throw new Error(`arguments of \`${s}\` must be strings`);const[o,i,l]=n.args.map(h=>this.evaluate(h,r));let u;if(i){const h=r.tests.get(i.value);if(!h)throw new Error(`Unknown test: ${i.value}`);u=h}else u=(...h)=>h[0].__bool__().value;const d=e.value.filter(h=>{const p=h.value.get(o.value),m=p?u(p,l):!1;return a?m:!m});return new ge(d)}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 d=vf(u,o.value);return d instanceof Pe?i??new Pe:d});return new ge(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 ie(4);if(!(i instanceof ie))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),d=e.value.split(`
15
+ `),h=" ".repeat(i.value),p=d.map((m,w)=>!l.value&&w===0||!u.value&&m.length===0?m:h+m);return new Y(p.join(`
16
+ `))}case"replace":{const a=e.builtins.get("replace");if(!(a instanceof Fe))throw new Error("replace filter not available");const[o,i]=this.evaluateArguments(n.args,r);return a.value([...o,new Wn(i)],r)}}throw new Error(`Unknown StringValue filter: ${s}`)}else if(e instanceof rt){const a=e.builtins.get(s);if(a&&a instanceof Fe){const[o,i]=this.evaluateArguments(n.args,r);return i.size>0&&o.push(new Wn(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 Pe}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 Wn(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 ge||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 ie||n instanceof Pe))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof ie||s instanceof Pe))throw new Error("Slice stop must be numeric or undefined");if(!(a instanceof ie||a instanceof Pe))throw new Error("Slice step must be numeric or undefined");return e instanceof ge?new ge(pf(e.value,n.value,s.value,a.value)):new Y(pf(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 ge||r instanceof Y)if(n instanceof ie)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 Yt?s:new Pe}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 ge))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 Ne}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 Fr(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 ge||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 d=new Fr(r),h=s.value[u];let p;if(e.loopvar.type==="Identifier")p=m=>m.setVariable(e.loopvar.value,h);else if(e.loopvar.type==="TupleLiteral"){const m=e.loopvar;if(h.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${h.type}`);const w=h;if(m.value.length!==w.value.length)throw new Error(`Too ${m.value.length>w.value.length?"few":"many"} items to unpack`);p=v=>{for(let b=0;b<m.value.length;++b){if(m.value[b].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${m.value[b].type}`);v.setVariable(m.value[b].value,w.value[b])}}}else throw new Error(`Invalid loop variable(s): ${e.loopvar.type}`);n&&(p(d),!this.evaluate(n,d).__bool__().value)||(a.push(h),o.push(p))}let i="",l=!0;for(let u=0;u<a.length;++u){const d=new Map([["index",new ie(u+1)],["index0",new ie(u)],["revindex",new ie(a.length-u)],["revindex0",new ie(a.length-u-1)],["first",new ne(u===0)],["last",new ne(u===a.length-1)],["length",new ie(a.length)],["previtem",u>0?a[u-1]:new Pe],["nextitem",u<a.length-1?a[u+1]:new Pe]]);r.setVariable("loop",new rt(d)),o[u](r);try{const h=this.evaluateBlock(e.body,r);i+=h.value}catch(h){if(h instanceof mf)continue;if(h instanceof _f)break;throw h}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 Fe((r,n)=>{const s=new Fr(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,d=l??a?.value.get(u.key.value)??this.evaluate(u.value,s);s.setVariable(u.key.value,d)}else throw new Error(`Unknown argument type: ${i.type}`)}return this.evaluateBlock(e.body,s)})),new Ne}evaluateCallStatement(e,t){const r=new Fe((i,l)=>{const u=new Fr(l);if(e.callerArgs)for(let d=0;d<e.callerArgs.length;++d){const h=e.callerArgs[d];if(h.type!=="Identifier")throw new Error(`Caller parameter must be an identifier, got ${h.type}`);u.setVariable(h.value,i[d]??new Pe)}return this.evaluateBlock(e.body,u)}),[n,s]=this.evaluateArguments(e.call.args,t);n.push(new Wn(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 Fr(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 Pe;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 _f;case"Continue":throw new mf;case"IntegerLiteral":return new ie(e.value);case"FloatLiteral":return new Re(e.value);case"StringLiteral":return new Y(e.value);case"ArrayLiteral":return new ge(e.value.map(r=>this.evaluate(r,t)));case"TupleLiteral":return new wf(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 Ne;default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};function zs(e){switch(typeof e){case"number":return Number.isInteger(e)?new ie(e):new Re(e);case"string":return new Y(e);case"boolean":return new ne(e);case"undefined":return new Pe;case"object":return e===null?new Ne:Array.isArray(e)?new ge(e.map(zs)):new rt(new Map(Object.entries(e).map(([t,r])=>[t,zs(r)])));case"function":return new Fe((t,r)=>{const n=e(...t.map(s=>s.value))??null;return zs(n)});default:throw new Error(`Cannot convert to runtime value: ${e}`)}}var qe=`
17
+ `,lx="{%- ",cx=" -%}";function ux(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 dx(e,t=" "){const r=typeof t=="number"?" ".repeat(t):t;return Dt(e.body,0,r).replace(/\n$/,"")}function et(...e){return lx+e.join(" ")+cx}function Dt(e,t,r){return e.map(n=>fx(n,t,r)).join(qe)}function fx(e,t,r){const n=r.repeat(t);switch(e.type){case"Program":return Dt(e.body,t,r);case"If":return hx(e,t,r);case"For":return px(e,t,r);case"Set":return _x(e,t,r);case"Macro":return mx(e,t,r);case"Break":return n+et("break");case"Continue":return n+et("continue");case"CallStatement":return gx(e,t,r);case"FilterStatement":return wx(e,t,r);case"Comment":return n+"{# "+e.value+" #}";default:return n+"{{- "+we(e)+" -}}"}}function hx(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+et("if",we(s[0].test))+qe+Dt(s[0].body,t+1,r);for(let i=1;i<s.length;++i)o+=qe+n+et("elif",we(s[i].test))+qe+Dt(s[i].body,t+1,r);return a&&a.alternate.length>0&&(o+=qe+n+et("else")+qe+Dt(a.alternate,t+1,r)),o+=qe+n+et("endif"),o}function px(e,t,r){const n=r.repeat(t);let s="";if(e.iterable.type==="SelectExpression"){const o=e.iterable;s=`${we(o.lhs)} if ${we(o.test)}`}else s=we(e.iterable);let a=n+et("for",we(e.loopvar),"in",s)+qe+Dt(e.body,t+1,r);return e.defaultBlock.length>0&&(a+=qe+n+et("else")+qe+Dt(e.defaultBlock,t+1,r)),a+=qe+n+et("endfor"),a}function _x(e,t,r){const n=r.repeat(t),s=we(e.assignee),a=e.value?we(e.value):"",o=n+et("set",`${s}${e.value?" = "+a:""}`);return e.body.length===0?o:o+qe+Dt(e.body,t+1,r)+qe+n+et("endset")}function mx(e,t,r){const n=r.repeat(t),s=e.args.map(we).join(", ");return n+et("macro",`${e.name.value}(${s})`)+qe+Dt(e.body,t+1,r)+qe+n+et("endmacro")}function gx(e,t,r){const n=r.repeat(t),s=e.callerArgs&&e.callerArgs.length>0?`(${e.callerArgs.map(we).join(", ")})`:"",a=we(e.call);let o=n+et(`call${s}`,a)+qe;return o+=Dt(e.body,t+1,r)+qe,o+=n+et("endcall"),o}function wx(e,t,r){const n=r.repeat(t),s=e.filter.type==="Identifier"?e.filter.value:we(e.filter);let a=n+et("filter",s)+qe;return a+=Dt(e.body,t+1,r)+qe,a+=n+et("endfilter"),a}function we(e,t=-1){switch(e.type){case"SpreadExpression":return`*${we(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=ux(r),s=we(r.left,n),a=we(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"?" ":"")+we(r.argument,1/0)}case"CallExpression":{const r=e,n=r.args.map(we).join(", ");return`${we(r.callee)}(${n})`}case"MemberExpression":{const r=e;let n=we(r.object);["Identifier","MemberExpression","CallExpression","StringLiteral","IntegerLiteral","FloatLiteral","ArrayLiteral","TupleLiteral","ObjectLiteral"].includes(r.object.type)||(n=`(${n})`);let s=we(r.property);return!r.computed&&r.property.type!=="Identifier"&&(s=`(${s})`),r.computed?`${n}[${s}]`:`${n}.${s}`}case"FilterExpression":{const r=e,n=we(r.operand,1/0);return r.filter.type==="CallExpression"?`${n} | ${we(r.filter)}`:`${n} | ${r.filter.value}`}case"SelectExpression":{const r=e;return`${we(r.lhs)} if ${we(r.test)}`}case"TestExpression":{const r=e;return`${we(r.operand)} is${r.negate?" not":""} ${r.test.value}`}case"ArrayLiteral":case"TupleLiteral":{const r=e.value.map(we),n=e.type==="ArrayLiteral"?"[]":"()";return`${n[0]}${r.join(", ")}${n[1]}`}case"ObjectLiteral":return`{${Array.from(e.value.entries()).map(([n,s])=>`${we(n)}: ${we(s)}`).join(", ")}}`;case"SliceExpression":{const r=e,n=r.start?we(r.start):"",s=r.stop?we(r.stop):"",a=r.step?`:${we(r.step)}`:"";return`${n}:${s}${a}`}case"KeywordArgumentExpression":{const r=e;return`${r.key.value}=${we(r.value)}`}case"Ternary":{const r=e,n=`${we(r.trueExpr)} if ${we(r.condition,0)} else ${we(r.falseExpr)}`;return t>-1?`(${n})`:n}default:throw new Error(`Unknown expression type: ${e.type}`)}}var vx=class{parsed;constructor(e){const t=CM(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=KM(t)}render(e){const t=new Fr;if(ox(t),e)for(const[s,a]of Object.entries(e))t.set(s,a);return new ix(t).run(this.parsed).value}format(e){return dx(this.parsed,e?.indent||" ")}},Ct=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")}},yx={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"},Qs=class ep{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",yx[t]??"application/octet-stream")}clone(){let t=new ep(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())}},tp=class{constructor(e){this.path=e}async match(e){let t=Qt.join(this.path,e),r=new Qs(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:d}=await l.read();if(u)break;await new Promise((p,m)=>{i.write(d,w=>{if(w){m(w);return}p()})}),o+=d.length;const h=a?o/a*100:0;r?.({progress:h,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}}},bx={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"},yf=100,Mx=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Ss(...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 pn(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 xx(e){return!(!Mx.test(e)||e.includes("..")||e.includes("--")||e.endsWith(".git")||e.endsWith(".ipynb"))}function Tx(e,t,r){if(!r)return null;const n=bx[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${n}: "${t}".`)}async function kx(e,t,r){const n=e.headers.get("Content-Length");let s=n?parseInt(n,10):r??0;n===null&&!r&&oe.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:d}=await i.read();if(u)return;const h=o+d.length;if(h>s){s=h;const m=new Uint8Array(s);m.set(a),a=m}a.set(d,o),o=h;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){oe.warn("An error occurred while opening the browser cache:",r)}}if(!t&&ye.useFSCache){if(!Ie.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");t=new tp(e??ye.cacheDir)}return t}async function Ex(e,...t){for(let r of t)try{let n=await e.match(r);if(n)return n}catch{continue}}async function Ax(e){if(!pn(e,["http:","https:"]))return null;const t=rp(e);return t.set("Range","bytes=0-0"),ye.fetch(e,{method:"GET",headers:t})}async function aa(e,t,r={}){const n=await mi(r?.cache_dir),{localPath:s,remoteURL:a,proposedCacheKey:o,validModelId:i}=np(e,t,r,n),l=await sp(n,s,o);if(l!==void 0&&typeof l!="string"){const u=l.headers.get("content-length"),d=l.headers.get("content-type");return{exists:!0,size:u?parseInt(u,10):void 0,contentType:d||void 0,fromCache:!0}}if(ye.allowLocalModels&&!pn(s,["http:","https:"]))try{const d=await Kn(s);if(typeof d!="string"&&d.status!==404){const h=d.headers.get("content-length"),p=d.headers.get("content-type");return{exists:!0,size:h?parseInt(h,10):void 0,contentType:p||void 0,fromCache:!1}}}catch{}if(ye.allowRemoteModels&&!r.local_files_only&&i)try{const u=await Ax(a);if(u&&u.status>=200&&u.status<300){let d;const h=u.headers.get("content-type");if(u.status===206){const p=u.headers.get("content-range");if(p){const m=p.match(/bytes \d+-\d+\/(\d+)/);m&&(d=parseInt(m[1],10))}}else if(u.status===200)try{await u.body?.cancel()}catch{}if(d===void 0){const p=u.headers.get("content-length");d=p?parseInt(p,10):void 0}return{exists:!0,size:d,contentType:h||void 0,fromCache:!1}}}catch(u){oe.warn(`Unable to fetch file metadata for "${a}": ${u}`)}return{exists:!1,fromCache:!1}}async function Kn(e){return ye.useFS&&!pn(e,["http:","https:","blob:"])?new Qs(e instanceof URL?e.protocol==="file:"?e.pathname:e.toString():e):ye.fetch(e,{headers:rp(e)})}function rp(e){const t=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(t){const n=!!To?.TESTING_REMOTELY,s=ye.version;if(r.set("User-Agent",`transformers.js/${s}; is_ci/${n};`),pn(e,["http:","https:"],["huggingface.co","hf.co"])){const o=To?.HF_TOKEN??To?.HF_ACCESS_TOKEN;o&&r.set("Authorization",`Bearer ${o}`)}}return r}function np(e,t,r={},n=null){const s=r.revision??"main",a=Ss(e,t),o=xx(e),i=o?Ss(ye.localModelPath,a):a,l=Ss(ye.remoteHost,ye.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(s)),t),u=n instanceof tp?s==="main"?a:Ss(e,s,t):l;return{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:u,validModelId:o}}async function sp(e,t,r){if(e)return await Ex(e,t,r)}async function Cx(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=>{oe.warn(`Unable to add response to browser cache: ${i}.`)});else{const i=o.progress_callback?l=>Dr(o.progress_callback,{status:"progress",name:e,file:t,...l}):void 0;await r.put(n,s,i)}}async function Sx(e,t,r=!0,n={},s=!1,a=null){const{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:u,validModelId:d}=np(e,t,n,a);let h,p=!1,m;m=await sp(a,i,u);const w=m!==void 0;if(!w){if(ye.allowLocalModels)if(pn(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{m=await Kn(i),h=i}catch(k){oe.warn(`Unable to load from local path "${i}": "${k}"`)}if(m===void 0||typeof m!="string"&&m.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(!d)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${e}".`);if(m=await Kn(l),m.status!==200)return Tx(m.status,l,r);h=u}p=a&&typeof Response<"u"&&m instanceof Response&&m.status===200}Dr(n.progress_callback,{status:"download",name:e,file:t});let v;if(!(Ie.IS_NODE_ENV&&s)){let M;if(typeof m!="string")if(!n.progress_callback)M=new Uint8Array(await m.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))M=new Uint8Array(await m.arrayBuffer()),Dr(n.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:M.length,total:M.length});else{let k;const A=m.headers.get("content-length");if(A)k=parseInt(A,10);else try{const E=await aa(e,t,n);E.size&&(k=E.size)}catch{}M=await kx(m,E=>{Dr(n.progress_callback,{status:"progress",name:e,file:t,...E})},k)}v=M}if(p&&h&&typeof m!="string"&&await Cx(e,t,a,h,m,v,n),Dr(n.progress_callback,{status:"done",name:e,file:t}),v){if(!Ie.IS_NODE_ENV&&s)throw new Error("Cannot return path in a browser environment.");return v}if(m instanceof Qs)return m.filePath;const b=await a?.match(h);if(b instanceof Qs)return b.filePath;if(b instanceof Response)return new Uint8Array(await b.arrayBuffer());if(typeof b=="string")return b;throw new Error("Unable to get model file path or buffer.")}async function Xs(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`.")}Dr(n.progress_callback,{status:"initiate",name:e,file:t});const a=await mi(n?.cache_dir);return await Sx(e,t,r,n,s,a)}async function ap(e,t,r=!0,n={}){const s=await Xs(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 ap(e,t,r,n);return s===null?{}:JSON.parse(s)}function Px(e,[t,r,n],[s,a],o="bilinear",i=!1){const l=a/n,u=s/r,d=new e.constructor(s*a*t),h=r*n,p=s*a;for(let m=0;m<s;++m)for(let w=0;w<a;++w){const v=m*a+w,b=(w+.5)/l-.5,M=(m+.5)/u-.5;let k=Math.floor(b),A=Math.floor(M);const E=Math.min(k+1,n-1),C=Math.min(A+1,r-1);k=Math.max(k,0),A=Math.max(A,0);const O=b-k,x=M-A,V=(1-O)*(1-x),G=O*(1-x),W=(1-O)*x,J=O*x,q=A*n,B=C*n,N=q+k,U=q+E,ee=B+k,X=B+E;for(let F=0;F<t;++F){const L=F*h;d[F*p+v]=V*e[L+N]+G*e[L+U]+W*e[L+ee]+J*e[L+X]}}return d}function Fx(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,d=i;u>=0;--u)l+=d%t[u]*a[u],d=Math.floor(d/t[u]);o[l]=e[i]}return[o,n]}function tt(e){const t=Ge(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 Ix(e){const t=Ge(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 $o(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 Ge(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 op(e){return e>0&&(e&e-1)===0}var ip=class{constructor(e){if(this.size=e|0,this.size<=1||!op(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 h=u[l];this._singleTransform2(t,e,i,h,a)}else for(i=0,l=0;i<n;i+=o,++l){const h=u[l];this._singleTransform4(t,e,i,h,a,r)}const d=this.table;for(a>>=2;a>=2;a>>=2){o=n/a<<1;const h=o>>>2;for(i=0;i<n;i+=o){const p=i+h-1;for(let m=i,w=0;m<p;m+=2,w+=a){const v=m,b=v+h,M=b+h,k=M+h,A=e[v],E=e[v+1],C=e[b],O=e[b+1],x=e[M],V=e[M+1],G=e[k],W=e[k+1],J=d[w],q=r*d[w+1],B=C*J-O*q,N=C*q+O*J,U=d[2*w],ee=r*d[2*w+1],X=x*U-V*ee,F=x*ee+V*U,L=d[3*w],z=r*d[3*w+1],K=G*L-W*z,le=G*z+W*L,Te=A+X,Se=E+F,ut=A-X,Ue=E-F,ze=B+K,Ve=N+le,be=r*(B-K),he=r*(N-le);e[v]=Te+ze,e[v+1]=Se+Ve,e[b]=ut+he,e[b+1]=Ue-be,e[M]=Te-ze,e[M+1]=Se-Ve,e[k]=ut-he,e[k+1]=Ue+be}}}}_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],d=e[n+s],h=e[n+s+1],p=e[n+o],m=e[n+o+1],w=e[n+i],v=e[n+i+1],b=l+p,M=u+m,k=l-p,A=u-m,E=d+w,C=h+v,O=a*(d-w),x=a*(h-v);t[r]=b+E,t[r+1]=M+C,t[r+2]=k+x,t[r+3]=A-O,t[r+4]=b-E,t[r+5]=M-C,t[r+6]=k-x,t[r+7]=A+O}_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 d=this.table;for(a>>=2;a>=2;a>>=2){o=n/a<<1;const p=o>>>1,m=p>>>1,w=m>>>1;for(i=0;i<n;i+=o)for(let v=0,b=0;v<=w;v+=2,b+=a){const M=i+v,k=M+m,A=k+m,E=A+m,C=e[M],O=e[M+1],x=e[k],V=e[k+1],G=e[A],W=e[A+1],J=e[E],q=e[E+1],B=C,N=O,U=d[b],ee=r*d[b+1],X=x*U-V*ee,F=x*ee+V*U,L=d[2*b],z=r*d[2*b+1],K=G*L-W*z,le=G*z+W*L,Te=d[3*b],Se=r*d[3*b+1],ut=J*Te-q*Se,Ue=J*Se+q*Te,ze=B+K,Ve=N+le,be=B-K,he=N-le,je=X+ut,_e=F+Ue,ve=r*(X-ut),cr=r*(F-Ue);if(e[M]=ze+je,e[M+1]=Ve+_e,e[k]=be+cr,e[k+1]=he-ve,v===0){e[A]=ze-je,e[A+1]=Ve-_e;continue}if(v===w)continue;const kr=i+m-v,dt=i+p-v;e[kr]=be-r*cr,e[kr+1]=-he-r*ve,e[dt]=ze-r*je,e[dt+1]=-Ve+r*_e}}const h=n>>>1;for(let p=2;p<h;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],d=e[n+o],h=e[n+i],p=l+d,m=l-d,w=u+h,v=a*(u-h);t[r]=p+w,t[r+1]=0,t[r+2]=m,t[r+3]=-v,t[r+4]=p-w,t[r+5]=0,t[r+6]=m,t[r+7]=v}},Lx=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 d=(u+1-e)**2/2,h=Math.sqrt(i**2+l**2)**d,p=d*Math.atan2(l,i),m=2*u;s[m]=h*Math.cos(p),s[m+1]=h*Math.sin(p),a[m]=s[m],a[m+1]=-s[m+1]}this._slicedChirpBuffer=s.subarray(t,r),this._f=new ip(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 d=0;d<l.length;d+=2){const h=d+1,p=d>>1,m=t[p];n[d]=m*l[d],n[h]=m*l[h]}else for(let d=0;d<l.length;d+=2){const h=d+1;n[d]=t[d]*l[d]-t[h]*l[h],n[h]=t[d]*l[h]+t[h]*l[d]}this._f.transform(a,n);for(let d=0;d<i.length;d+=2){const h=d+1;s[d]=a[d]*i[d]-a[h]*i[h],s[h]=a[d]*i[h]+a[h]*i[d]}this._f.inverseTransform(o,s);for(let d=0;d<o.length;d+=2){const h=o[d+u],p=o[d+u+1],m=l[d],w=l[d+1];e[d]=h*m-p*w,e[d+1]=h*w+p*m}}transform(e,t){this._transform(e,t,!1)}realTransform(e,t){this._transform(e,t,!0)}},Ox=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=op(e),this.isPowerOfTwo?(this.fft=new ip(e),this.outputBufferSize=2*e):(this.fft=new Lx(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,t){this.fft.realTransform(e,t)}transform(e,t){this.fft.transform(e,t)}};function Nx(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 qn(e,t){const r=Math.pow(10,t);return Math.round(e*r)/r}function Dx(e){const t=Math.round(e);return Math.abs(e)%1===.5?t%2===0?t:t-1:t}function zx(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 d=1;d<n[1];++d)for(let h=1;h<n[0];++h){const p=s[h-1][d-1],m=s[h-1][d],w=s[h][d-1];let v,b;p<m&&p<w?(v=p,b=0):m<p&&m<w?(v=m,b=1):(v=w,b=2),s[h][d]=e[h-1][d-1]+v,a[h][d]=b}for(let d=0;d<n[1];++d)a[0][d]=2;for(let d=0;d<n[0];++d)a[d][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 Bx=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 d=(l&32768)<<16,h=(l&31744)>>10;let p=l&1023;if(h===31)u=d|2139095040|p<<13;else if(h===0)if(p===0)u=d;else{let m=113;for(;!(p&1024);)p<<=1,--m;p&=-1025,u=d|m<<23|p<<13}else u=d|h+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}}(),lp={};fn(lp,{default:()=>Rx});var Rx={};async function cp(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){oe.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){oe.warn(`Failed to cache ${t}:`,s)}return n}async function $x(e){const t=await cp(e);if(!t||typeof t=="string")return null;try{return await t.arrayBuffer()}catch(r){return oe.warn("Failed to read WASM binary:",r),null}}async function Gx(e){const t=await cp(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 oe.warn("Failed to read WASM binary:",r),null}}function bf(e){return pn(e,["blob:"])}function Mf(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 Ux=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 up(e){return e<=Ot.DEBUG?0:e<=Ot.INFO?2:e<=Ot.WARNING||e<=Ot.ERROR?3:4}var Vx={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},Tt=[],Go,ln,xf=Symbol.for("onnxruntime");if(xf in globalThis)ln=globalThis[xf];else if(Ie.IS_NODE_ENV){switch(ln=lp,process.platform){case"win32":Tt.push("dml");break;case"linux":process.arch==="x64"&&Tt.push("cuda");break;case"darwin":Tt.push("coreml");break}Tt.push("webgpu"),Tt.push("cpu"),Go=["cpu"]}else ln=Gy,Ie.IS_WEBNN_AVAILABLE&&Tt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),Ie.IS_WEBGPU_AVAILABLE&&Tt.push("webgpu"),Tt.push("wasm"),Go=["wasm"];var jx=ln.InferenceSession;function Wx(e=null){if(!e)return Go;switch(e){case"auto":return Tt;case"gpu":return Tt.filter(t=>["webgpu","cuda","dml","webnn-gpu"].includes(t))}if(Tt.includes(e))return[Ux[e]??e];throw new Error(`Unsupported device: "${e}". Should be one of: ${Tt.join(", ")}.`)}var dp=Ie.IS_BROWSER_ENV||Ie.IS_WEBWORKER_ENV,Tf=Promise.resolve(),Zr=null;async function qx(){return Zr||(ye.useWasmCache&&typeof Ze?.wasm?.wasmPaths=="object"&&Ze?.wasm?.wasmPaths?.wasm&&Ze?.wasm?.wasmPaths?.mjs?(Zr=(async()=>{const t=Ze.wasm.wasmPaths;await Promise.all([t.wasm&&!bf(t.wasm)?(async()=>{try{const r=await $x(Mf(t.wasm));r&&(Ze.wasm.wasmBinary=r)}catch(r){oe.warn("Failed to pre-load WASM binary:",r)}})():Promise.resolve(),t.mjs&&!bf(t.mjs)?(async()=>{try{const r=await Gx(Mf(t.mjs));r&&(Ze.wasm.wasmPaths.mjs=r)}catch(r){oe.warn("Failed to pre-load WASM factory:",r)}})():Promise.resolve()])})(),Zr):(Zr=Promise.resolve(),Zr))}async function fp(e,t,r){await qx();const n=up(ye.logLevel??Ot.WARNING),s=()=>jx.create(e,{logSeverityLevel:n,...t}),a=await(dp?Tf=Tf.then(s):s());return a.config=r,a}var kf=Promise.resolve();async function hp(e,t){const r=()=>e.run(t);return await(dp?kf=kf.then(r):r())}function pp(e){return e instanceof ln.Tensor}var Ze=ln?.env;if(Ze?.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&Ze.versions?.web&&!Ze.wasm.wasmPaths){const e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${Ze.versions.web}/dist/`;Ze.wasm.wasmPaths=Ie.IS_SAFARI?{mjs:`${e}ort-wasm-simd-threaded.mjs`,wasm:`${e}ort-wasm-simd-threaded.wasm`}:{mjs:`${e}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${e}ort-wasm-simd-threaded.asyncify.wasm`}}Ze.wasm.proxy=!1}Ze?.webgpu&&(Ze.webgpu.powerPreference="high-performance");function gi(){return Ze?.wasm?.proxy}function _p(e){const t=up(e);Ze.logLevel=Vx[t]}_p(ye.logLevel??Ot.WARNING);ye.backends.onnx={...Ze,setLogLevel:_p};var mr=async(e,t,r)=>{const n=await fp(new Uint8Array(e),t);return async s=>{const a=gi(),o=Object.fromEntries(Object.entries(s).map(([l,u])=>[l,(a?u.clone():u).ort_tensor])),i=await hp(n,o);return Array.isArray(r)?r.map(l=>new j(i[l])):new j(i[r])}},cn=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=mr([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=mr([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=mr([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=mr([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=mr([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=mr([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=mr([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=mr([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}},Hx=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"}),Eo=Ie.IS_NODE_ENV?"cpu":"wasm";function mp(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 (${Eo}).`),Eo):Eo}var Qx=function(){let e;return async function(){if(e===void 0)if(!Ie.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"}),Ef=st.fp32,Af=Object.freeze({[Hx.wasm]:st.q8}),Uo=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 gp(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=Af[r]??Ef}else a&&st.hasOwnProperty(a)?i=a:i=Af[r]??Ef;return o&&s&&s(`dtype not specified for "${t}". Using the default dtype (${i}) for this device (${r}).`),i}var Ys=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}),wp=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(Ie.IS_CRYPTO_AVAILABLE){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[vp(this._random_fn,t)]}};function vp(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 Wt=new wp,wi=Object.freeze({Random:wp,seed:Wt.seed.bind(Wt),random:Wt.random.bind(Wt),gauss:Wt.gauss.bind(Wt),shuffle:Wt.shuffle.bind(Wt),choices:Wt.choices.bind(Wt)}),Xx=e=>vp(wi.random,e),j=class Be{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 pp(t[0])?this.ort_tensor=t[0]:this.ort_tensor=new Ky(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 Be(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 Be(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 Yx(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 Be(this.type,this.data.slice(),this.dims.slice())}slice(...t){const r=[],n=[];for(let d=0;d<this.dims.length;++d){let h=t[d];if(h==null)n.push([0,this.dims[d]]),r.push(this.dims[d]);else if(typeof h=="number")h=Ht(h,this.dims[d],d),n.push([h,h+1]);else if(Array.isArray(h)&&h.length===2){let[p,m]=h;if(p=p===null?0:Ht(p,this.dims[d],d,!1),m=m===null?this.dims[d]:Ht(m,this.dims[d],d,!1),p>m)throw new Error(`Invalid slice: ${h}`);const w=[Math.max(p,0),Math.min(m,this.dims[d])];n.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${h}`)}const s=n.map(([d,h])=>h-d),a=s.reduce((d,h)=>d*h),o=this.data,i=new o.constructor(a),l=this.stride();let u=!0;for(let d=1;d<s.length;++d)if(n[d][0]!==0||n[d][1]!==this.dims[d]){u=!1;break}if(u){const d=n[0][0]*l[0],h=n[0][1]*l[0];if(ArrayBuffer.isView(o))i.set(o.subarray(d,h));else if(Array.isArray(o)){const p=o.slice(d,h);for(let m=0;m<p.length;++m)i[m]=p[m]}else throw new Error("Unsupported data type for slicing")}else for(let d=0;d<a;++d){let h=0;for(let p=s.length-1,m=d;p>=0;--p){const w=s[p];h+=(m%w+n[p][0])*l[p],m=Math.floor(m/w)}i[d]=o[h]}return new Be(this.type,i,r)}permute(...t){return Jx(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,d)=>u+d**t;if(r===null){const u=s.reduce(a,0)**(1/t);return new Be(this.type,[u],[])}const[o,i,l]=Xn(a,this,r,n);if(t!==1)for(let u=0;u<i.length;++u)i[u]=i[u]**(1/t);return new Be(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,d=1;l>=0;--l){const h=this.dims[l];if(l!==r){const p=u%h;i+=p*d,d*=this.dims[l]}u=Math.floor(u/h)}s[o]/=a[i]}return this}normalize(t=2,r=1){return this.clone().normalize_(t,r)}stride(){return Ao(this.dims)}squeeze(t=null){return new Be(this.type,this.data,Cf(this.dims,t))}squeeze_(t=null){return this.dims=Cf(this.dims,t),this}unsqueeze(t){return new Be(this.type,this.data,Sf(this.dims,t))}unsqueeze_(t){return this.dims=Sf(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 Be(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 Be("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 Be("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 vi(this,t,r)}min(t=null,r=!1){if(t===null){const o=$o(this.data)[0];return new Be(this.type,[o],[])}const[n,s,a]=Xn((o,i)=>Math.min(o,i),this,t,r,1/0);return new Be(n,s,a)}max(t=null,r=!1){if(t===null){const o=Ge(this.data)[0];return new Be(this.type,[o],[])}const[n,s,a]=Xn((o,i)=>Math.max(o,i),this,t,r,-1/0);return new Be(n,s,a)}argmin(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const n=$o(this.data)[1];return new Be("int64",[BigInt(n)],[])}argmax(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const n=Ge(this.data)[1];return new Be("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(d=>d===1)){if(t.length===this.dims.length)return this.clone();const d=t.length-this.dims.length,h=Array(d).fill(1).concat(this.dims);return new Be(this.type,this.data.slice(),h)}const r=t.length-this.dims.length,n=Array(r).fill(1).concat(this.dims),s=n.map((d,h)=>d*t[h]),a=s.reduce((d,h)=>d*h,1),o=this.data,i=new o.constructor(a),l=Ao(n),u=Ao(s);for(let d=0;d<a;++d){let h=d,p=0;for(let m=0;m<s.length;++m){const w=Math.floor(h/u[m]);h=h%u[m];const v=w%n[m];p+=v*l[m]}i[d]=o[p]}return new Be(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(!Ys.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 Be(t,Bx(this.data),this.dims);return new Be(t,Ys[t].from(this.data,r),this.dims)}};function Yx(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 Jx(e,t){const[r,n]=Fx(e.data,e.dims,t);return new j(e.type,r,n)}function yp(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=Px(e.data,[a,o,i],[t,r],n,s);return new j(e.type,l,[a,t,r])}async function yr(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 cn.nearest_interpolate_4d;else if(r==="bilinear")s=await cn.bilinear_interpolate_4d;else if(r==="bicubic")s=await cn.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${r}`);const a=new j("int64",new BigInt64Array(n.map(BigInt)),[n.length]);return await s({x:e,s:a})}async function Kx(e,t){return await(await cn.matmul)({a:e,b:t})}async function _n(e,t){const r=await cn.top_k;return t==null?t=e.dims.at(-1):t=Math.min(t,e.dims.at(-1)),await r({x:e,k:new j("int64",[BigInt(t)],[1])})}var Ps=e=>new j("int64",e,[e.length]);async function bp(e,t,r,n,s){return await(await cn.slice)({x:e,s:Ps(t),e:Ps(r),a:Ps(n),t:Ps(new Array(n.length).fill(1))})}function Zx(e,t){const r=e.data,n=t.data,s=[e.dims[0],e.dims[2]],a=new r.constructor(s[0]*s[1]),[o,i,l]=e.dims;let u=0;for(let d=0;d<o;++d){const h=d*l*i;for(let p=0;p<l;++p){let m=0,w=0;const v=d*i,b=h+p;for(let k=0;k<i;++k){const A=Number(n[v+k]);w+=A,m+=r[b+k*l]*A}const M=m/w;a[u++]=M}}return new j(e.type,a,s)}function Cf(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 Sf(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 De(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 d=0;d<l.length;++d){let h=0;for(let p=u.length-1,m=d,w=1;p>=0;--p){const v=u[p];let b=m%v;p===t&&(b+=o),h+=b*w,w*=r[p],m=Math.floor(m/v)}s[h]=l[d]}o+=u[t]}}return new j(a,s,r)}function mn(e,t=0){return De(e.map(r=>r.unsqueeze(t)),t)}function Xn(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 d=0;for(let h=o.length-1,p=u,m=1;h>=0;--h){const w=o[h];if(h!==r){const v=p%w;d+=v*m,m*=i[h]}p=Math.floor(p/w)}l[d]=e(l[d],a[u],u,d)}return n||i.splice(r,1),[t.type,l,i]}function e1(e,t=null,r=1,n=!1){const s=e.data,a=e.dims;if(t===null){const m=s.reduce((M,k)=>M+k,0)/s.length,w=Math.sqrt(s.reduce((M,k)=>M+(k-m)**2,0)/(s.length-r)),v=new j(e.type,[m],[]);return[new j(e.type,[w],[]),v]}t=Ht(t,a.length);const o=vi(e,t,n),i=o.data,[l,u,d]=Xn((p,m,w,v)=>p+(m-i[v])**2,e,t,n);for(let p=0;p<u.length;++p)u[p]=Math.sqrt(u[p]/(a[t]-r));return[new j(l,u,d),o]}function vi(e,t=null,r=!1){const n=e.dims,s=e.data;if(t===null){const l=s.reduce((u,d)=>u+d,0);return new j(e.type,[l/s.length],[])}t=Ht(t,n.length);const[a,o,i]=Xn((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 j(a,o,i)}function Ao(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 yi(e,t,r,n){const s=e.reduce((a,o)=>a*o,1);return new j(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 yi(e,t,r,n)}function Vo(e,t){return at(e.dims,t)}function At(e){return yi(e,1n,"int64",BigInt64Array)}function Mp(e){return At(e.dims)}function xp(e){return yi(e,0n,"int64",BigInt64Array)}function Tp(e){return xp(e.dims)}function t1(e){const t=e.reduce((r,n)=>r*n,1);return new j("float32",Float32Array.from({length:t},()=>wi.gauss()),e)}function r1(e,t){if(e.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(e.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(t))throw new Error("The precision must be either 'binary' or 'ubinary'");const r=t==="binary",n=r?"int8":"uint8",s=r?Int8Array:Uint8Array,a=e.data,o=new s(a.length/8);for(let i=0;i<a.length;++i){const l=a[i]>0?1:0,u=Math.floor(i/8),d=i%8;o[u]|=l<<7-d,r&&d===0&&(o[u]-=128)}return new j(n,o,[e.dims[0],e.dims[1]/8])}async function kp(e){if(!e)throw new Error("modelId is required for get_tokenizer_files");return(await aa(e,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function Ep(e,t){const r=await kp(e);return await Promise.all(r.map(n=>ir(e,n,!0,t)))}function Ap(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 n1=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function s1(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"?Xt(e[s],i):Xt(i,e[s])}}function a1(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 o1(e){const t=[];for(const r of e.get_added_tokens_decoder().values())r.special&&t.push(r);return t}var ae=class extends Ct{return_token_type_ids=!1;padding_side="right";constructor(e,t){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=t,this._tokenizer=new TM(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=o1(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 Ep(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((h,p)=>this._encode_plus(h,{text_pair:t[p],add_special_tokens:r,return_token_type_ids:i}))}else u=e.map(h=>this._encode_plus(h,{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?(oe.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&&(oe.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(Ge(u.map(h=>h.input_ids.length))[0],a??1/0)),a=Math.min(a,this.model_max_length??1/0),n||s)for(let h=0;h<u.length;++h)u[h].input_ids.length!==a&&(u[h].input_ids.length>a?s&&a1(u[h],a):n&&s1(u[h],a,p=>p==="input_ids"?this.pad_token_id:0,this.padding_side));const d={};if(o){if(!(n&&s)&&u.some(p=>{for(const m of Object.keys(p))if(p[m].length!==u[0][m]?.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 h=[u.length,u[0].input_ids.length];for(const p of Object.keys(u[0]))d[p]=new j("int64",BigInt64Array.from(u.flatMap(m=>m[p]).map(BigInt)),h)}else{for(const h of Object.keys(u[0]))d[h]=u.map(p=>p[h]);if(!l)for(const h of Object.keys(d))d[h]=d[h][0]}return d}_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 j&&(e=e.tolist()),e.map(r=>this.decode(r,t))}decode(e,t={}){if(e instanceof j&&(e=Ap(e)),!Array.isArray(e)||e.length===0||!db(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:d=!0,tokenizer_kwargs:h={},...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 m=this._compiled_template_cache.get(n);m===void 0&&(m=new vx(n),this._compiled_template_cache.set(n,m));const w=Object.create(null);for(const b of n1){const M=Pr(this.config,b);M&&(w[b]=M)}const v=m.render({messages:e,add_generation_prompt:s,tools:t,documents:r,...w,...p});if(a){const b=this._call(v,{add_special_tokens:!1,padding:o,truncation:i,max_length:l,return_tensor:u,...h});return d?b:b.input_ids}return v}};function bi(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 Cp={};fn(Cp,{AlbertTokenizer:()=>i1,AutoTokenizer:()=>ce,BartTokenizer:()=>l1,BertTokenizer:()=>c1,BlenderbotSmallTokenizer:()=>u1,BlenderbotTokenizer:()=>d1,BloomTokenizer:()=>f1,CLIPTokenizer:()=>p1,CamembertTokenizer:()=>h1,CodeGenTokenizer:()=>m1,CodeLlamaTokenizer:()=>_1,CohereTokenizer:()=>g1,ConvBertTokenizer:()=>w1,DebertaTokenizer:()=>y1,DebertaV2Tokenizer:()=>v1,DistilBertTokenizer:()=>b1,ElectraTokenizer:()=>M1,EsmTokenizer:()=>x1,FalconTokenizer:()=>T1,GPT2Tokenizer:()=>A1,GPTNeoXTokenizer:()=>E1,GemmaTokenizer:()=>k1,HerbertTokenizer:()=>C1,LlamaTokenizer:()=>S1,M2M100Tokenizer:()=>P1,MBart50Tokenizer:()=>I1,MBartTokenizer:()=>Sp,MPNetTokenizer:()=>N1,MarianTokenizer:()=>F1,MgpstrTokenizer:()=>L1,MobileBertTokenizer:()=>O1,NllbTokenizer:()=>D1,NougatTokenizer:()=>z1,PreTrainedTokenizer:()=>ae,Qwen2Tokenizer:()=>B1,RoFormerTokenizer:()=>$1,RobertaTokenizer:()=>R1,SiglipTokenizer:()=>G1,SpeechT5Tokenizer:()=>U1,SqueezeBertTokenizer:()=>V1,T5Tokenizer:()=>j1,TokenizersBackend:()=>ae,VitsTokenizer:()=>q1,Wav2Vec2CTCTokenizer:()=>H1,WhisperTokenizer:()=>J1,XLMRobertaTokenizer:()=>K1,XLMTokenizer:()=>Z1});var i1=class extends ae{return_token_type_ids=!0},l1=class extends ae{},c1=class extends ae{return_token_type_ids=!0},u1=class extends ae{},d1=class extends ae{},f1=class extends ae{},h1=class extends ae{},p1=class extends ae{},_1=class extends ae{},m1=class extends ae{},g1=class extends ae{},w1=class extends ae{return_token_type_ids=!0},v1=class extends ae{return_token_type_ids=!0},y1=class extends ae{return_token_type_ids=!0},b1=class extends ae{},M1=class extends ae{return_token_type_ids=!0},x1=class extends ae{},T1=class extends ae{},k1=class extends ae{},E1=class extends ae{},A1=class extends ae{},C1=class extends ae{return_token_type_ids=!0},S1=class extends ae{padding_side="left"},P1=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 bi(this,e,t,r)}},F1=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)),oe.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)||oe.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),Xt([n],super._encode_text(s))}}},Sp=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 bi(this,e,t,r)}},I1=class extends Sp{},L1=class extends ae{},O1=class extends ae{return_token_type_ids=!0},N1=class extends ae{},D1=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 bi(this,e,t,r)}},z1=class extends ae{},B1=class extends ae{},R1=class extends ae{},$1=class extends ae{return_token_type_ids=!0},G1=class extends ae{},U1=class extends ae{},V1=class extends ae{return_token_type_ids=!0},j1=class extends ae{},W1=class extends Rt{decode_chain(e){let t="";for(let r=1;r<e.length;r+=2)t+=e[r];return[t]}},q1=class extends ae{constructor(e,t){super(e,t),this._tokenizer.decoder=new W1({type:"VitsDecoder"})}},H1=class extends ae{},Pp=[["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"]],Bs=new Map(Pp),Q1=new Map([...Pp.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 X1(e){e=e.toLowerCase();let t=Q1.get(e);if(t===void 0){const r=e.match(/^<\|([a-z]{2})\|>$/);if(r&&(e=r[1]),Bs.has(e))t=e;else{const s=e.length===2?Bs.keys():Bs.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(s))}`)}}return t}var Y1="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Pf=new RegExp(`^[${Y1}]+$`,"gu"),J1=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(),d=0;const h=this.timestamp_begin,m=h+1500;let w=[],v=[],b=!1,M=null;const k=new Set(this.all_special_ids);for(const C of e){const O=C.tokens,x=o?C.token_timestamps:null;let V=null,G=h;if("stride"in C){const[q,B,N]=C.stride;if(d-=B,M=q-N,B&&(G=B/n+h),N)for(let U=O.length-1;U>=0;--U){const ee=Number(O[U]);if(ee>=h){if(V!==null&&(ee-h)*n<M)break;V=ee}}}let W=[],J=[];for(let q=0;q<O.length;++q){const B=Number(O[q]);if(k.has(B)){const N=this.decode([B]),U=Bs.get(N.slice(2,-2));if(U!==void 0){if(a!==null&&U!==a&&!t){w.push(W);const ee=this.findLongestCommonSequence(w)[0],X=this.decode(ee);u.text=X,l.push(u),w=[],W=[],u=i()}a=u.language=U}}else if(B>=h&&B<=m){const N=(B-h)*n+d,U=qn(N,2);if(V!==null&&B>=V)b=!0;else if(b||w.length>0&&B<G)b=!1;else if(u.timestamp[0]===null)u.timestamp[0]=U;else if(U!==u.timestamp[0]){u.timestamp[1]=U,w.push(W),o&&v.push(J);const[ee,X]=this.findLongestCommonSequence(w,v),F=this.decode(ee);u.text=F,o&&(u.words=this.collateWordTimestamps(ee,X,a)),l.push(u),w=[],W=[],v=[],J=[],u=i()}}else if(W.push(B),o){let N=qn(x[q]+d,2),U;if(q+1<x.length){U=qn(x[q+1]+d,2);const ee=this.decode([B]);Pf.test(ee)&&(U=qn(Math.min(N+n,U),2))}else U=null;J.push([N,U])}}if("stride"in C){const[q,B,N]=C.stride;d+=q-N}W.length>0?(w.push(W),o&&v.push(J)):w.every(q=>q.length===0)&&(u=i(),w=[],W=[],v=[],J=[])}if(w.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[C,O]=this.findLongestCommonSequence(w,v),x=this.decode(C);u.text=x,o&&(u.words=this.collateWordTimestamps(C,O,a)),l.push(u)}let A=Object.create(null);const E=l.map(C=>C.text).join("");if(t||r){for(let C=0;C<l.length;++C){const O=l[C];t||delete O.timestamp,r||delete O.language}if(o){const C=[];for(const O of l)for(const x of O.words)C.push(x);A={chunks:C}}else A={chunks:l}}return[E,A]}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 d=0,h=[n,n,0,0];const p=u.length;for(let A=1;A<n+p;++A){const E=Math.max(0,n-A),C=Math.min(n,n+p-A),O=r.slice(E,C),x=Math.max(0,A-n),V=Math.min(p,A),G=u.slice(x,V);if(O.length!==G.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let W;a?W=O.filter((B,N)=>B===G[N]&&i[E+N]<=t[l][x+N]).length:W=O.filter((B,N)=>B===G[N]).length;const J=A/1e4,q=W/A+J;W>1&&q>d&&(d=q,h=[E,C,x,V])}const[m,w,v,b]=h,M=Math.floor((w+m)/2),k=Math.floor((b+v)/2);s.push(...r.slice(0,M)),r=u.slice(k),n=r.length,a&&(o.push(...i.slice(0,M)),i=t[l].slice(k))}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 j&&(e=Ap(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 d=e[u];o.push(d),i.push(u);const h=this.decode(o,{decode_with_timestamps:!0});(!h.includes(r)||t[l+h.indexOf(r)]===r)&&(n.push(h),s.push(o),a.push(i),o=[],i=[],l+=h.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],d=n[i],h=u[0]>=this._tokenizer.token_to_id("<|endoftext|>"),p=l.startsWith(" "),m=l.trim(),w=Pf.test(m);if(h||p||w||s.length===0)s.push(l),a.push(u),o.push(d);else{const v=s.length-1;s[v]+=l,a[v].push(...u),o[v].push(...d)}}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]=Xt(o[l],o[u]),i[u]=Xt(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]=Xt(o[l],o[u]),i[l]=Xt(i[l],i[u]),a[u]="",o[u]=[],i[u]=[]):l=u,++u;return[a.filter(d=>d),o.filter(d=>d.length>0),i.filter(d=>d.length>0)]}},K1=class extends ae{},Z1=class extends ae{return_token_type_ids=!0;constructor(e,t){super(e,t),oe.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},ce=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 Ep(e,{progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a}),l=i.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let u=Cp[l];return u||(oe.warn(`Unknown tokenizer class "${l}", attempting to construct from base class.`),u=ae),new u(o,i)}},oa="https://github.com/huggingface/transformers.js/issues/new/choose",Mi="preprocessor_config.json",Zn=Mi,eT="processor_config.json",tT="chat_template.jinja",Le=class extends Ct{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,eT,!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?ap(e,tT,!0,t):null]);return new this(r,n,s)}},jo={};fn(jo,{ChatterboxProcessor:()=>CT,Florence2Processor:()=>bk,Gemma3nProcessor:()=>Mk,GroundingDinoProcessor:()=>Tk,Idefics3Processor:()=>Nf,JinaCLIPProcessor:()=>Sk,LlavaProcessor:()=>Pk,MgpstrProcessor:()=>Fk,MoonshineProcessor:()=>Ik,OwlViTProcessor:()=>Lk,PaliGemmaProcessor:()=>Nk,Phi3VProcessor:()=>zk,PixtralProcessor:()=>Bk,Processor:()=>Le,PyAnnoteProcessor:()=>Rk,Qwen2VLProcessor:()=>r_,Qwen2_5_VLProcessor:()=>n_,Qwen3VLProcessor:()=>$k,Sam2Processor:()=>a_,Sam2VideoProcessor:()=>Gk,SamProcessor:()=>s_,SmolVLMProcessor:()=>Nf,SpeechT5Processor:()=>Uk,UltravoxProcessor:()=>Vk,VLChatProcessor:()=>Ck,VoxtralProcessor:()=>Hk,Wav2Vec2Processor:()=>Qk,Wav2Vec2ProcessorWithLM:()=>Xk,WhisperProcessor:()=>Yk});var pt=class extends Ct{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){const r=await ir(e,Mi,!0,t);return new this(r)}};function St(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 xi={};fn(xi,{ASTFeatureExtractor:()=>_T,ChatterboxFeatureExtractor:()=>mT,ClapFeatureExtractor:()=>gT,DacFeatureExtractor:()=>Np,EncodecFeatureExtractor:()=>Op,FeatureExtractor:()=>pt,Gemma3nAudioFeatureExtractor:()=>wT,MoonshineFeatureExtractor:()=>vT,ParakeetFeatureExtractor:()=>bT,PyAnnoteFeatureExtractor:()=>Dp,SeamlessM4TFeatureExtractor:()=>MT,SnacFeatureExtractor:()=>xT,SpeechT5FeatureExtractor:()=>TT,Wav2Vec2FeatureExtractor:()=>kT,WeSpeakerFeatureExtractor:()=>ET,WhisperFeatureExtractor:()=>AT});var rT=()=>{},nT=rT;async function Fp(e,t){if(Ie.IS_BROWSER_ENV){if(Ie.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(Ie.IS_FS_AVAILABLE)t.stream(),kt.createWriteStream(e),await nT();else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function sT(e,t){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const r=await(await Kn(e)).arrayBuffer(),n=new AudioContext({sampleRate:t});typeof t>"u"&&oe.warn(`No sampling rate provided, using default of ${n.sampleRate}Hz.`);const s=await n.decodeAudioData(r);let a;if(s.numberOfChannels===2){const o=Math.sqrt(2),i=s.getChannelData(0),l=s.getChannelData(1);a=new Float32Array(i.length);for(let u=0;u<s.length;++u)a[u]=o*(i[u]+l[u])/2}else a=s.getChannelData(0);return a}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 Ff(e){return Ip(e,.5)}function aT(e){return Ip(e,.54)}var oT={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 Co(e,t="htk"){const r=oT[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 iT={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 lT(e,t="htk"){const r=iT[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 cT(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],d=i[l+2]/r[l+1];a[l][o]=Math.max(0,Math.min(u,d))}}return a}function If(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=Co(r,o),u=Co(n,o),d=If(l,u,t+2);let h=lT(d,o),p;if(i){const w=s/((e-1)*2);p=Co(Float64Array.from({length:e},(v,b)=>b*w),o),h=d}else p=If(0,Math.floor(s/2),e);const m=cT(p,h);if(a!==null&&a==="slaney")for(let w=0;w<t;++w){const v=m[w],b=2/(h[w+2]-h[w]);for(let M=0;M<e;++M)v[M]*=b}return m}function uT(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[qs(a,s)];for(let a=1;a<=r;++a)n[s+t+a]=e[qs(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=Ge(e)[0]-s;for(let i=0;i<e.length;++i)e[i]=Math.max(e[i],o)}return e}function dT(e,t=1,r=1e-5,n=null){return Lp(e,20,t,r,n)}function fT(e,t=1,r=1e-10,n=null){return Lp(e,10,t,r,n)}async function Ur(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:d=!0,mel_filters:h=null,mel_floor:p=1e-10,log_mel:m=null,reference:w=1,min_value:v=1e-10,db_range:b=null,remove_dc_offset:M=null,min_num_frames:k=null,max_num_frames:A=null,do_pad:E=!0,transpose:C=!1,mel_offset:O=0}={}){const x=t.length;if(s===null&&(s=r),r>s)throw Error(`frame_length (${r}) may not be larger than fft_length (${s})`);if(x!==r)throw new Error(`Length of the window (${x}) must equal frame_length (${r})`);if(n<=0)throw new Error("hop_length must be greater than zero");if(a===null&&h!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!d)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(o)switch(i){case"reflect":{const L=Math.floor((s-1)/2)+1;e=uT(e,L,L);break}case"constant":{const L=Math.floor(s/2),z=new e.constructor(e.length+2*L);z.set(e,L),e=z;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}let V=Math.floor(1+Math.floor((e.length-r)/n));k!==null&&V<k&&(V=k);const G=l?Math.floor(s/2)+1:s;let W=V,J=V;A!==null&&(A>V?E&&(J=A):J=W=A);const q=new Ox(s),B=new Float64Array(s),N=new Float64Array(q.outputBufferSize),U=new Float32Array(G*J);for(let L=0;L<W;++L){const z=L*n,K=Math.min(e.length-z,r);K!==r&&B.fill(0,0,r);for(let le=0;le<K;++le)B[le]=e[z+le];if(M){let le=0;for(let Se=0;Se<K;++Se)le+=B[Se];const Te=le/K;for(let Se=0;Se<K;++Se)B[Se]-=Te}if(u!==null){for(let le=K-1;le>=1;--le)B[le]-=u*B[le-1];B[0]*=1-u}for(let le=0;le<t.length;++le)B[le]*=t[le];q.realTransform(N,B);for(let le=0;le<G;++le){const Te=le<<1;U[le*J+L]=N[Te]**2+N[Te+1]**2}}if(a!==null&&a!==2){const L=a/2;for(let z=0;z<U.length;++z)U[z]**=L}const ee=h.length;let X=await Kx(new j("float32",h.flat(),[ee,G]),new j("float32",U,[G,J]));C&&(X=X.transpose(1,0));const F=X.data;for(let L=0;L<F.length;++L)F[L]=O+Math.max(p,F[L]);if(a!==null&&m!==null){const L=Math.min(F.length,W*ee);switch(m){case"log":for(let z=0;z<L;++z)F[z]=Math.log(F[z]);break;case"log10":for(let z=0;z<L;++z)F[z]=Math.log10(F[z]);break;case"dB":if(a===1)dT(F,w,v,b);else if(a===2)fT(F,w,v,b);else throw new Error(`Cannot use log_mel option '${m}' with power ${a}`);break;default:throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${m}'`)}}return X}function Vr(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=Ff(a);break;case"hamming":o=aT(a);break;case"povey":o=Ff(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}function hT(e,t){const r=e.reduce((a,o)=>a+o.length,0),n=new ArrayBuffer(44),s=new DataView(n);return Fs(s,0,"RIFF"),s.setUint32(4,36+r*4,!0),Fs(s,8,"WAVE"),Fs(s,12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,3,!0),s.setUint16(22,1,!0),s.setUint32(24,t,!0),s.setUint32(28,t*4,!0),s.setUint16(32,4,!0),s.setUint16(34,32,!0),Fs(s,36,"data"),s.setUint32(40,r*4,!0),new Blob([n,...e.map(a=>a.buffer)],{type:"audio/wav"})}function Fs(e,t,r){for(let n=0;n<r.length;++n)e.setUint8(t+n,r.charCodeAt(n))}var pT=class{constructor(e,t){this.audio=e,this.sampling_rate=t}get data(){if(Array.isArray(this.audio)){if(this.audio.length===0)return new Float32Array(0);if(this.audio.length===1)return this.audio[0];const e=this.audio.reduce((n,s)=>n+s.length,0),t=new Float32Array(e);let r=0;for(const n of this.audio)t.set(n,r),r+=n.length;return t}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),hT(e,this.sampling_rate)}async save(e){return Fp(e,this.toBlob())}},_T=class extends pt{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=Vr(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return Ur(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){St(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 pt{async _call(e){St(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 j("float32",e,r)}}},mT=class extends pt{async _call(e){St(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,e.length];return{input_values:new j("float32",e,t)}}},gT=class extends pt{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=Vr(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(wi.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 Ur(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 St(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{},wT=class extends pt{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=Vr(o,"hann")}async _extract_fbank_features(e,t){return Ur(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(St(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}}},vT=class extends pt{async _call(e){St(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,e.length];return{input_values:new j("float32",e,t)}}},yT=1e-5,bT=class extends pt{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=Vr(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 Ur(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){St(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 d=0;d<r;++d){const h=d*a;for(let p=0;p<a;++p){const m=n[h+p];o[p]+=m,i[p]+=m*m}}const l=r>1?r-1:1;for(let d=0;d<a;++d){const h=o[d]/r,p=(i[d]-r*h*h)/l,w=1/(Math.sqrt(p)+yT);for(let v=0;v<r;++v){const b=v*a+d;n[b]=(n[b]-h)*w}}const u=new BigInt64Array(s);return u.fill(1n,0,r),{input_features:t.unsqueeze_(0),attention_mask:new j("int64",u,[1,s])}}},Dp=class extends pt{async _call(e){St(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,1,e.length];return{input_values:new j("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=tt(s[i]),[u,d]=Ge(l),[h,p]=[i,i+1];d!==o?(o=d,a.push({id:d,start:h,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:d})=>({id:i,start:l*r,end:u*r,confidence:d/(u-l)})))}return n}},MT=class extends pt{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=Vr(400,"povey",{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(r=>r*32768),Ur(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}={}){St(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){const[m,w]=a.dims,v=a.data;for(let b=0;b<w;++b){let M=0;for(let C=0;C<m;++C)M+=v[C*w+b];const k=M/m;let A=0;for(let C=0;C<m;++C)A+=(v[C*w+b]-k)**2;A/=m-1;const E=Math.sqrt(A+1e-7);for(let C=0;C<m;++C){const O=C*w+b;v[O]=(v[O]-k)/E}}}let o;if(t){const[m,w]=a.dims,v=a.data,b=m%r;if(b>0){const M=new Float32Array(w*(m+b));M.set(v),M.fill(this.config.padding_value,v.length);const k=m+b;a=new j(a.type,M,[k,w]),s&&(o=new j("int64",new BigInt64Array(k),[1,k]),o.data.fill(1n,0,m))}}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 h=a.view(1,Math.floor(i/u),l*u),p={input_features:h};if(s){const m=h.dims[1],w=new BigInt64Array(m);if(o){const v=o.data;for(let b=1,M=0;b<i;b+=u,++M)w[M]=v[b]}else w.fill(1n);p.attention_mask=new j("int64",w,[1,m])}return p}},xT=class extends Np{},TT=class extends pt{},kT=class extends pt{_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){St(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 j("float32",t,r),attention_mask:new j("int64",new BigInt64Array(t.length).fill(1n),r)}}},ET=class extends pt{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=Vr(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),Ur(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){St(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 d=0;d<a;++d){const h=l+d*o;for(let p=0;p<o;++p)n[h+p]-=r[u+p]}}}return{input_features:t}}},AT=class extends pt{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=Vr(this.config.n_fft,"hann")}async _extract_fbank_features(e){const t=await Ur(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=Ge(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}={}){St(e,"WhisperFeatureExtractor");let r;const n=t??this.config.n_samples;return e.length>n?(e.length>this.config.n_samples&&oe.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,Mi,!0,t),n=r.feature_extractor_type,s=xi[n];if(!s)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${oa}.`);return new s(r)}},CT=class extends Le{static tokenizer_class=ce;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}}},Wo={},Ir,zp,gr,It=Ie.IS_BROWSER_ENV||Ie.IS_WEBWORKER_ENV;if(It)Ir=(e,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(e,t)},gr=self.createImageBitmap,zp=self.ImageData;else if(Wo)gr=async e=>{const r=(await e.metadata()).channels,{data:n,info:s}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),a=new zt(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 ST={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},PT=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),zt=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 Kn(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 gr(t),n=Ir(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=Wo(await t.arrayBuffer());return await gr(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=ST[n]??n;const a=Zd(t),o=Zd(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=Ir(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")&&(oe.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 gr(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=Ir(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 gr(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=Ir(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 gr(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=Ir(t,r).getContext("2d");let l=0,u=0,d=0,h=0;return n>=0?l=n:d=-n,s>=0?u=s:h=-s,i.drawImage(o,l,u,t,r,d,h,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 gr(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 j("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=Ir(t.width,t.height),n=new zp(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 d=0;d<s;++d)i[d][l]=t[u+d]}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(Ie.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const r=t.split(".").pop().toLowerCase(),n=PT.get(r)??"image/png",s=await this.toBlob(n);return Fp(t,s)}else if(Ie.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 Wo(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}};zt.read.bind(zt);function Lf(e,t,r=0,n=null){const s=e/t;let a=Dx(s)*t;return n!==null&&a>n&&(a=Math.floor(s)*t),a<r&&(a=Math.ceil(s)*t),a}function So([e,t],r){return[Math.max(Math.floor(e/r),1)*r,Math.max(Math.floor(t/r),1)*r]}function Bp([e,t,r,n]){return[e-r/2,t-n/2,e+r/2,t+n/2]}function ia(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 d=0;d<o;++d){let h=r!==null?r[d]:null,p={boxes:[],classes:[],scores:[]},m=s[d],w=a[d];for(let v=0;v<i;++v){let b=m[v],M=[],k;if(n){k=b.sigmoid().data;for(let A=0;A<k.length;++A)k[A]>t&&M.push(A)}else{let A=Ge(b.data)[1];if(A===l-1||(k=tt(b.data),k[A]<t))continue;M.push(A)}for(const A of M){let E=w[v].data;E=Bp(E),h!==null&&(E=E.map((C,O)=>C*h[(O+1)%2])),p.boxes.push(E),p.classes.push(A),p.scores.push(k[A])}}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=yp(i,o,"bilinear",!1));const[l,u]=o??i.dims.slice(-2),d=new j("int32",new Int32Array(l*u),[l,u]),h=i[0].data,p=d.data;for(let v=1;v<i.dims[0];++v){const b=i[v].data;for(let M=0;M<b.length;++M)b[M]>h[M]&&(h[M]=b[M],p[M]=v)}const m=new Array(i.dims[0]);for(let v=0;v<p.length;++v){const b=p[v];m[b]=b}const w=m.filter(v=>v!==void 0);s.push({segmentation:d,labels:w})}return s}function FT(e,t,r,n){const s=[],a=[],o=[];for(let i=0;i<e.dims[0];++i){const l=e[i],u=t[i],d=Ge(l.data)[1];if(d===n)continue;const p=tt(l.data)[d];p>r&&(s.push(u),a.push(p),o.push(d))}return[s,a,o]}function IT(e,t,r,n=.5,s=.8){const a=[];let o=0,i=0;const l=t[r].data;for(let d=0;d<e.length;++d)e[d]===r&&(a.push(d),++o),l[d]>=n&&++i;let u=o>0&&i>0;return u&&(u=o/i>s),[u,a]}function LT(e,t,r,n,s,a=null,o=null){const[i,l]=o??e[0].dims,u=new j("int32",new Int32Array(i*l),[i,l]),d=[];if(o!==null)for(let v=0;v<e.length;++v)e[v]=yp(e[v],o,"bilinear",!1);const h=new Int32Array(e[0].data.length),p=new Float32Array(e[0].data.length);for(let v=0;v<e.length;++v){let b=t[v];const M=e[v].data;for(let k=0;k<M.length;++k)M[k]*=b,M[k]>p[k]&&(h[k]=v,p[k]=M[k])}let m=0;const w=u.data;for(let v=0;v<r.length;++v){const b=r[v],[M,k]=IT(h,e,v,n,s);if(M){++m;for(const A of k)w[A]=m;d.push({id:m,label_id:b,score:t[v]})}}return[u,d]}function $p(e,t=.5,r=.5,n=.8,s=null,a=null){s===null&&(oe.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,d,h]=o.dims;if(h-=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 m=0;m<u;++m){let w=a!==null?a[m]:null,v=o[m],b=l[m],[M,k,A]=FT(v,b,t,h);if(A.length===0){let[O,x]=w??b.dims.slice(-2),V=new j("int32",new Int32Array(O*x).fill(-1),[O,x]);p.push({segmentation:V,segments_info:[]});continue}let[E,C]=LT(M,k,A,r,n,s,w);p.push({segmentation:E,segments_info:C})}return p}function Gp(e,t=.5,r=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}var ue=class extends Ct{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=$o(r.data)[0],a=Ge(r.data)[0]-n;if(a===0)return e;const o=t/255;let i=r.width,l=r.height,u=0,d=0;const h=r.data;for(let p=0;p<r.height;++p){const m=p*r.width;for(let w=0;w<r.width;++w)(h[m+w]-n)/a<o&&(i=Math.min(i,w),l=Math.min(l,p),u=Math.max(u,w),d=Math.max(d,p))}return e=await e.crop([i,l,u,d]),e}pad_image(e,t,r,{mode:n="constant",center:s=!1,constant_values:a=0}={}){const[o,i,l]=t;let u,d;if(typeof r=="number"?(u=r,d=r):r==="square"?u=d=Math.max(o,i):(u=r.width,d=r.height),u!==i||d!==o){const h=new Float32Array(u*d*l);if(Array.isArray(a))for(let w=0;w<h.length;++w)h[w]=a[w%l];else a!==0&&h.fill(a);const[p,m]=s?[Math.floor((u-i)/2),Math.floor((d-o)/2)]:[0,0];for(let w=0;w<o;++w){const v=(w+m)*u,b=w*i;for(let M=0;M<i;++M){const k=(v+M+p)*l,A=(b+M)*l;for(let E=0;E<l;++E)h[k+E]=e[A+E]}}if(n==="symmetric"){if(s)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");const w=o-1,v=i-1;for(let b=0;b<d;++b){const M=b*u,k=qs(b,w)*i;for(let A=0;A<u;++A){if(b<o&&A<i)continue;const E=(M+A)*l,C=(k+qs(A,v))*l;for(let O=0;O<l;++O)h[E+O]=e[C+O]}}}e=h,t=[d,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 d=Math.floor(Number((i*u).toFixed(2))),h=Math.floor(Number((l*u).toFixed(2)));return this.size_divisibility!==void 0&&([d,h]=So([d,h],this.size_divisibility)),[d,h]}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=Lf(l*n,this.config.ensure_multiple_of),o=Lf(u*r,this.config.ensure_multiple_of)}return[o,i]}else{if(this.size_divisibility!==void 0)return So([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,m;Number.isInteger(this.crop_size)?(p=this.crop_size,m=this.crop_size):(p=this.crop_size.width,m=this.crop_size.height),e=await e.center_crop(p,m)}const l=[e.height,e.width];let u=Float32Array.from(e.data),d=[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 m=this.image_std;if(Array.isArray(this.image_std)||(m=new Array(e.channels).fill(m)),p.length!==e.channels||m.length!==e.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${p.length}) and \`image_std\` (${m.length}) must match the number of channels in the image (${e.channels}).`);for(let w=0;w<u.length;w+=e.channels)for(let v=0;v<e.channels;++v)u[w+v]=(u[w+v]-p[v])/m[v]}if(r??this.do_pad){if(this.pad_size)[u,d]=this.pad_image(u,[e.height,e.width,e.channels],this.pad_size);else if(this.size_divisibility){const[p,m]=So([d[1],d[0]],this.size_divisibility);[u,d]=this.pad_image(u,d,{width:p,height:m})}}if(a??this.do_flip_channel_order){if(d[2]!==3)throw new Error("Flipping channel order is only supported for RGB images.");for(let p=0;p<u.length;p+=3){const m=u[p];u[p]=u[p+2],u[p+2]=m}}const h=new j("float32",u,d).permute(2,0,1);return{original_size:[i,o],reshaped_input_size:l,pixel_values:h}}async _call(e,...t){Array.isArray(e)||(e=[e]);const r=await Promise.all(e.map(s=>this.preprocess(s)));return{pixel_values:mn(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,Zn,!0,t);return new this(r)}},Js={};fn(Js,{BeitFeatureExtractor:()=>OT,BitImageProcessor:()=>NT,CLIPFeatureExtractor:()=>zT,CLIPImageProcessor:()=>Up,ChineseCLIPFeatureExtractor:()=>DT,ConvNextFeatureExtractor:()=>BT,ConvNextImageProcessor:()=>Vp,DINOv3ViTImageProcessor:()=>GT,DPTFeatureExtractor:()=>VT,DPTImageProcessor:()=>qp,DeiTFeatureExtractor:()=>RT,DeiTImageProcessor:()=>jp,DetrFeatureExtractor:()=>$T,DetrImageProcessor:()=>Wp,DonutFeatureExtractor:()=>UT,DonutImageProcessor:()=>Ti,EfficientNetImageProcessor:()=>jT,GLPNFeatureExtractor:()=>WT,GroundingDinoImageProcessor:()=>qT,Idefics3ImageProcessor:()=>Of,ImageFeatureExtractor:()=>ue,ImageProcessor:()=>ue,JinaCLIPImageProcessor:()=>QT,LlavaOnevisionImageProcessor:()=>XT,Mask2FormerImageProcessor:()=>JT,MaskFormerFeatureExtractor:()=>YT,MaskFormerImageProcessor:()=>ki,MobileNetV1FeatureExtractor:()=>KT,MobileNetV1ImageProcessor:()=>Hp,MobileNetV2FeatureExtractor:()=>ZT,MobileNetV2ImageProcessor:()=>Qp,MobileNetV3FeatureExtractor:()=>ek,MobileNetV3ImageProcessor:()=>Xp,MobileNetV4FeatureExtractor:()=>tk,MobileNetV4ImageProcessor:()=>Yp,MobileViTFeatureExtractor:()=>rk,MobileViTImageProcessor:()=>Jp,NougatImageProcessor:()=>nk,OwlViTFeatureExtractor:()=>sk,OwlViTImageProcessor:()=>Ei,Owlv2ImageProcessor:()=>ak,Phi3VImageProcessor:()=>ik,PixtralImageProcessor:()=>lk,PvtImageProcessor:()=>ck,Qwen2VLImageProcessor:()=>dk,RTDetrImageProcessor:()=>fk,Sam2ImageProcessor:()=>Io,Sam3ImageProcessor:()=>Io,SamImageProcessor:()=>Io,SapiensFeatureExtractor:()=>hk,SapiensImageProcessor:()=>Kp,SegformerFeatureExtractor:()=>pk,SegformerImageProcessor:()=>Zp,SiglipImageProcessor:()=>_k,SmolVLMImageProcessor:()=>Of,Swin2SRImageProcessor:()=>mk,VLMImageProcessor:()=>HT,ViTFeatureExtractor:()=>gk,ViTImageProcessor:()=>e_,VitMatteImageProcessor:()=>wk,VitPoseImageProcessor:()=>vk,YolosFeatureExtractor:()=>yk,YolosImageProcessor:()=>t_});var OT=class extends ue{},NT=class extends ue{},DT=class extends ue{},Up=class extends ue{},zT=class extends Up{},Vp=class extends ue{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}},BT=class extends Vp{},jp=class extends ue{},RT=class extends jp{},Wp=class extends ue{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 ia(...e)}post_process_panoptic_segmentation(...e){return $p(...e)}post_process_instance_segmentation(...e){return Gp(...e)}},$T=class extends Wp{},GT=class extends ue{},Ti=class extends ue{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((d,h)=>-d/l[h]);return super.pad_image(e,t,r,{center:!0,constant_values:u,...n})}},UT=class extends Ti{},qp=class extends ue{},VT=class extends qp{},jT=class extends ue{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))}},WT=class extends ue{},qT=class extends ue{async _call(e){const t=await super._call(e),r=t.pixel_values.dims,n=At([r[0],r[2],r[3]]);return{...t,pixel_mask:n}}},Of=class extends ue{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 b of n){let M=await Promise.all(b.map(E=>this.preprocess(E)));i.push(...M.map(E=>E.original_size)),l.push(...M.map(E=>E.reshaped_input_size)),M.forEach(E=>E.pixel_values.unsqueeze_(0));const{longest_edge:k}=this.max_image_size;let A;if(t??this.do_image_splitting){let E=new Array(M.length),C=new Array(M.length);A=await Promise.all(M.map(async(O,x)=>{const V=this.get_resize_for_vision_encoder(O.pixel_values,k),G=await yr(O.pixel_values,{size:[V.height,V.width]}),{frames:W,num_splits_h:J,num_splits_w:q}=await this.split_image(G,this.max_image_size);return E[x]=J,C[x]=q,De(W,0)})),a.push(E),o.push(C)}else{const E=[k,k];A=await Promise.all(M.map(C=>yr(C.pixel_values,{size:E}))),a.push(new Array(M.length).fill(0)),o.push(new Array(M.length).fill(0))}s.push(De(A,0))}const u=s.length,[d,h,p,m]=s[0].dims;let w,v;if(u===1)w=s[0].unsqueeze_(0),v=at([u,d,p,m],!0);else{const b=Math.max(...s.map(A=>A.dims.at(0)));v=at([u,b,p,m],!0);const M=v.data,k=b*p*m;for(let A=0;A<u;++A){const E=s[A].dims[0];if(E<b){s[A]=De([s[A],at([b-E,h,p,m],0)],0);const C=A*k+E*p*m,O=(A+1)*k;M.fill(!1,C,O)}}w=mn(s,0)}return{pixel_values:w,pixel_attention_mask:v,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),d=Math.ceil(o/l);for(let m=0;m<i;++m)for(let w=0;w<l;++w){let v,b,M,k;m===i-1?(b=a-u,k=a):(b=m*u,k=(m+1)*u),w===l-1?(v=o-d,M=o):(v=w*d,M=(w+1)*d);const C=await bp(e,[b,v],[k,M],[2,3]);s.push(C)}const h=r,p=n;(a!==h||o!==p)&&(e=await yr(e,{size:[h,p]}))}return s.push(e),{frames:s,num_splits_h:i,num_splits_w:l}}},HT=class extends ue{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})}},QT=class extends ue{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})}},XT=class extends ue{},ki=class extends ue{post_process_panoptic_segmentation(...e){return $p(...e)}post_process_instance_segmentation(...e){return Gp(...e)}},YT=class extends ki{},JT=class extends ki{},Hp=class extends ue{},KT=class extends Hp{},Qp=class extends ue{},ZT=class extends Qp{},Xp=class extends ue{},ek=class extends Xp{},Yp=class extends ue{},tk=class extends Yp{},Jp=class extends ue{},rk=class extends Jp{},nk=class extends Ti{},Ei=class extends ue{post_process_object_detection(...e){return ia(...e)}},sk=class extends Ei{},ak=class extends Ei{},mt=336,ok=[2,3],{ceil:Po,floor:en,sqrt:Fo}=Math,ik=class extends ue{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/mt)*en(e/mt)+1)*r+1+(en(t/mt)+1)*Fo(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=mt*Po(s/mt),i=mt*Po(a/mt),l=[1,1,1].map((u,d)=>(u-this.image_mean[d])/this.image_std[d]);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||Fo(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(h=>this.preprocess(h))),s=n.map(h=>h.original_size),a=n.map(h=>h.reshaped_input_size),o=[];for(const{pixel_values:h}of n){h.unsqueeze_(0);const[p,m]=h.dims.slice(-2),w=await yr(h,{size:[mt,mt],mode:"bicubic"});if(t>0){const v=[],b=Fo(t),M=en(m/b),k=en(p/b);for(let E=0;E<b;++E)for(let C=0;C<b;++C){let O,x,V,G;E===b-1?(x=p-k,G=p):(x=E*k,G=(E+1)*k),C===b-1?(O=m-M,V=m):(O=C*M,V=(C+1)*M);const q=await bp(h,[x,O],[G,V],ok);v.push(q)}const A=await yr(De(v,0),{size:[mt,mt],mode:"bicubic"});o.push(De([w,A],0))}else o.push(w)}const i=mn(o,0),l=a.map(h=>h.map(p=>mt*Po(p/mt))),u=new j("int64",l.flat(),[r,2]),d=l.map(([h,p])=>this.calc_num_image_tokens_from_image_size(p,h));return{pixel_values:i,original_sizes:s,reshaped_input_sizes:a,image_sizes:u,num_img_tokens:d}}},lk=class extends ue{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 d=l*u,h=Math.floor((o-1)/d)+1,p=Math.floor((i-1)/d)+1;return[h*d,p*d]}},ck=class extends ue{};function uk(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 dk=class extends ue{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 uk(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=De(Array.from({length:o},()=>a),0));const u=a.dims[0]/o,d=a.dims[1],h=Math.floor(a.dims[2]/l),p=Math.floor(a.dims[3]/l),m=a.view(u,o,d,Math.floor(h/i),i,l,Math.floor(p/i),i,l).permute(0,3,6,4,7,2,1,5,8).view(u*h*p,d*o*l*l),w=new j("int64",[u,h,p],[1,3]);return{pixel_values:m,image_grid_thw:w,original_sizes:n,reshaped_input_sizes:s}}},fk=class extends ue{post_process_object_detection(...e){return ia(...e)}},Io=class extends ue{reshape_input_points(e,t,r,n=!1){e=structuredClone(e);let s=ef(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],d=[u/i,l/o];for(let h=0;h<e[a].length;++h)for(let p=0;p<e[a][h].length;++p)for(let m=0;m<e[a][h][p].length;++m)e[a][h][p][m]*=d[m%2]}return new j("float32",Float32Array.from(e.flat(1/0)),s)}add_input_labels(e,t){let r=ef(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 j("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],d=r[l];let h=await yr(e[l],{mode:"bilinear",size:i});if(h=h.slice(null,null,[0,d[0]],[0,d[1]]),h=await yr(h,{mode:"bilinear",size:u}),s){const p=h.data,m=new Uint8Array(p.length);for(let w=0;w<p.length;++w)p[w]>n&&(m[w]=1);h=new j("bool",m,h.dims)}o.push(h)}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 ue{post_process_semantic_segmentation(...e){return Rp(...e)}},hk=class extends Kp{},Zp=class extends ue{post_process_semantic_segmentation(...e){return Rp(...e)}},pk=class extends Zp{},_k=class extends ue{},mk=class extends ue{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 ue{},gk=class extends e_{},wk=class extends ue{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:mn(r.map((a,o)=>De([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)}}},vk=class extends ue{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 d=n[u],h=t[u],p=[];for(let m=0;m<h.length;++m){const w=h[m],v=[],b=[],M=[],k=w.at(-2)/i,A=w.at(-1)/o;for(let E=0;E<d.length;++E){let[C,O]=[0,0],x=0,V=-1/0;const G=d[E];for(let J=0;J<G.length;++J){const q=G[J];for(let B=0;B<q.length;++B){const N=q[B];x+=N,V=Math.max(V,N),C+=(B+.5)*N,O+=J*N}}if(r!=null&&V<r)continue;const W=[k*C/x,A*O/x];v.push(W),M.push(E),b.push(V)}p.push({bbox:w,scores:b,labels:M,keypoints:v})}l.push(p)}return l}},t_=class extends ue{post_process_object_detection(...e){return ia(...e)}},yk=class extends t_{},_t=class{static async from_pretrained(e,t={}){const r=await ir(e,Zn,!0,t),n=r.image_processor_type??r.feature_extractor_type;let s=Js[n?.replace(/Fast$/,"")];return s||(n!==void 0&&oe.warn(`Image processor type '${n}' not found, assuming base ImageProcessor. Please report this at ${oa}.`),s=ue),new s(r)}},bk=class extends Le{static tokenizer_class=ce;static image_processor_class=_t;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,d,...h]of o)i.push(d?d.trim():i.at(-1)??""),l.push(h.map((p,m)=>(Number(p)+.5)/this.size_per_bin*r[m%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}}},Mk=class extends Le{static image_processor_class=_t;static feature_extractor_class=lr;static tokenizer_class=ce;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:d}=this.tokenizer.config;this.audio_token_id=n,this.boa_token=s,this.audio_token=a;const h=a.repeat(this.audio_seq_length);this.full_audio_sequence=`
18
+
19
+ ${s}${h}${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}${d}
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 xk(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 Tk=class extends Le{static tokenizer_class=ce;static image_processor_class=_t;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(),d=u.max(-1).tolist(),h=o.tolist().map(m=>m.map(w=>Bp(w))),p=[];for(let m=0;m<i;++m){const w=s!==null?s[m]:null;w!==null&&(h[m]=h[m].map(A=>A.map((E,C)=>E*w[(C+1)%2])));const v=d[m],b=[],M=[],k=[];for(let A=0;A<l;++A){const E=v[A];if(E<=r)continue;const C=h[m][A],O=u[m][A];b.push(E),k.push(C);const x=xk(O.gt(n),t[m]);M.push(x)}p.push({scores:b,boxes:k,labels:this.batch_decode(M)})}return p}};function kk(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 Ek(e,t,r,n){return`${t}${n}`+r.repeat(e)+`${t}`}function Ak(e,t,r,n,s,a){return e===0&&t===0?Ek(r,n,s,a):kk(r,e,t,n,s,a)}var Nf=class extends Le{static image_processor_class=_t;static tokenizer_class=ce;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 d=0;d<e.length;++d){const h=e[d],p=s[d],m=a[d];i.push(hb(h,this.image_token));const w=p.map((M,k)=>Ak(M,m[k],o,this.fake_image_token,this.image_token,this.global_img_token)),v=h.split(this.image_token);if(v.length===0)throw new Error("The image token should be present in the text.");let b=v[0];for(let M=0;M<w.length;++M)b+=w[M]+v[M+1];l.push(b)}return{...this.tokenizer(l),...n}}},Ck=class extends Le{static image_processor_class=_t;static tokenizer_class=ce;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(v=>v.images).flatMap(v=>v.images).map(v=>zt.read(v)));const n=this.tokenizer,s=n.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:r}),a=v=>n.encode(v,{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,d]=n.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let h=a(o[0]),p=new Array(h.length).fill(!1);for(let v=1;v<o.length;++v){const b=new Array(this.num_image_tokens).fill(l),M=a(o[v]);h=Xt(h,[u],b,[d],M);const k=new Array(this.num_image_tokens).fill(!0);p=Xt(p,[!1],k,[!1],new Array(M.length).fill(!1))}const m=[1,h.length],w={input_ids:new j("int64",h,m),attention_mask:new j("int64",new Array(h.length).fill(1),m),images_seq_mask:new j("bool",p,m),images_emb_mask:new j("bool",new Array(i*this.num_image_tokens).fill(!0),[1,i,this.num_image_tokens])};if(t&&t.length>0){const v=await this.image_processor(t);return v.pixel_values.unsqueeze_(0),{...w,...v}}return w}},Sk=class extends Le{static tokenizer_class=ce;static image_processor_class=_t;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}}},Pk=class extends Le{static tokenizer_class=ce;static image_processor_class=_t;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,d=Math.floor(a/l)*Math.floor(o/l)+u;t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let h=0;h<t.length;++h)t[h]=t[h].replace(i,i.repeat(d))}const s=t?this.tokenizer(t,r):{};return{...n,...s}}},Df={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]},Fk=class extends Le{static tokenizer_class=ce;static image_processor_class=_t;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(!Df.hasOwnProperty(t))throw new Error(`Format ${t} is not supported.`);const[r,n]=Df[t],s=this[r].bind(this),[a,o]=e.dims,i=[],l=[],u=e.tolist();for(let h=0;h<a;++h){const p=u[h],m=[],w=[];for(let b=1;b<o;++b){const[M,k]=Ge(tt(p[b]));if(w.push(M),k==n)break;m.push(k)}const v=w.length>0?w.reduce((b,M)=>b*M,1):0;l.push(m),i.push(v)}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=[],d=[];for(let h=0;h<n.length;++h){const[p,m]=Ge([s[h],o[h],l[h]]);u.push([n[h],a[h],i[h]][m]),d.push(p)}return{generated_text:u,scores:d,char_preds:n,bpe_preds:a,wp_preds:i}}static async from_pretrained(...e){const t=await super.from_pretrained(...e),r=await ce.from_pretrained("Xenova/gpt2"),n=await ce.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}},Ik=class extends Le{static tokenizer_class=ce;static feature_extractor_class=lr;async _call(e){return await this.feature_extractor(e)}},Lk=class extends Le{static tokenizer_class=ce;static image_processor_class=_t},tn="<image>";function Ok(e,t,r,n,s){return`${n.repeat(r*s)}${t}${e}
28
+ `}var Nk=class extends Le{static tokenizer_class=ce;static image_processor_class=_t;static uses_processor_config=!1;async _call(e,t=null,r={}){t||(oe.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)),d=u.lastIndexOf(tn),h=d===-1?0:d+tn.length;return u.slice(0,h)+n+u.slice(h)+`
29
+ `}):(oe.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=>Ok(l,n,s,tn,e.length)));const o=this.tokenizer(a,r);return{...await this.image_processor(e,r),...o}}},zf="<|image|>",Dk=/<\|image_\d+\|>/g,zk=class extends Le{static image_processor_class=_t;static tokenizer_class=ce;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((d,h)=>d.split(Dk).join(zf.repeat(i[h])));a=this.tokenizer(l,{padding:r,truncation:n});const u=this.tokenizer._tokenizer.token_to_id(zf);a.input_ids.map_(d=>d==u?-d:d)}else a=this.tokenizer(e);return{...a,...o}}},Bk=class extends Le{static tokenizer_class=ce;static image_processor_class=_t;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:d,spatial_merge_size:h}=this.config,p=d*h,m=Math.floor(a/p),w=Math.floor(o/p);t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let v=0;v<t.length;++v){const b=i.repeat(w),M=b+l,k=b+u,A=M.repeat(m-1)+k;t[v]=t[v].replace(i,A)}}const s=t?this.tokenizer(t,r):{};return{...n,...s}}},Rk=class extends Le{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 Le{static image_processor_class=_t;static tokenizer_class=ce;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 d=Number(l[i++].reduce((h,p)=>h*p,1n));u=u.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(d/o)))}return u.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(e),...n}}},n_=class extends r_{},$k=class extends n_{},s_=class extends Le{static image_processor_class=_t;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_{},Gk=class extends a_{},Uk=class extends Le{static tokenizer_class=ce;static feature_extractor_class=lr;async _call(e){return await this.feature_extractor(e)}},Vk=class extends Le{static tokenizer_class=ce;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}}},Is="[AUDIO]",jk="[BEGIN_AUDIO]",Wk=375;function qk(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 Hk=class extends Le{static tokenizer_class=ce;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(Is))throw new Error(`The input text does not contain the audio token ${Is}.`);Array.isArray(t)||(t=[t]);const a=e.split(Is),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(m=>qk(m,i)),u=l.map(m=>m.length),d=l.flat(),h=(await Promise.all(d.map(m=>this.feature_extractor(m,r)))).map(m=>m.input_features);n.audio_values=h.length>1?De(h,0):h[0];let p=a[0];for(let m=0;m<u.length;++m){p+=jk;for(let w=0;w<u[m];++w)p+=Is.repeat(Wk);p+=a[m+1]}e=p}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...n}}},Qk=class extends Le{static tokenizer_class=ce;static feature_extractor_class=lr;async _call(e){return await this.feature_extractor(e)}},Xk=class extends Le{static tokenizer_class=ce;static feature_extractor_class=lr;async _call(e){return await this.feature_extractor(e)}},Yk=class extends Le{static tokenizer_class=ce;static feature_extractor_class=lr;async _call(e){return await this.feature_extractor(e)}},ct=class{static async from_pretrained(e,t={}){const r=await ir(e,Zn,!0,t),{image_processor_type:n,feature_extractor_type:s,processor_class:a}=r;if(a&&jo[a])return jo[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=Js[n.replace(/Fast$/,"")];if(!l)throw new Error(`Unknown image_processor_type: '${n}'.`);o.image_processor=new l(r)}if(s){const l=Js[s];if(l)o.image_processor=new l(r);else{const u=xi[s];if(!u)throw new Error(`Unknown feature_extractor_type: '${s}'.`);o.feature_extractor=new u(r)}}const i={};return new Le(i,o,null)}};async function Jk(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,d=l/o,h=t?.batch_size??1;for(let p=0;p<a.length;++p)if(a[p]==="full_attention")for(const m of["key","value"])s[`${r}.${p}.${m}`]=[h,i,0,d];else if(a[p]==="conv")s[`${n}_conv.${p}`]=[h,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:d,mamba_n_heads:h,mamba_d_head:p,mamba_d_state:m,mamba_n_groups:w,mamba_expand:v,mamba_d_ssm:b}=e,M=u/i,k=t?.batch_size??1,A=(b??v*u)+2*w*m;for(let E=0;E<o;++E)if((!a||a[E]==="mamba")&&(s[`${n}_conv.${E}`]=[k,A,d],s[`${n}_ssm.${E}`]=[k,h,p,m]),!a||a[E]==="attention")for(const C of["key","value"])s[`${r}.${E}.${C}`]=[k,l,0,M];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:d,linear_num_key_heads:h,linear_key_head_dim:p,linear_value_head_dim:m,linear_conv_kernel_dim:w}=e.text_config,v=p*h,b=m*d,M=v*2+b,k=a??u/i,A=t?.batch_size??1;for(let E=0;E<o.length;++E)if(o[E]==="full_attention")for(const C of["key","value"])s[`${r}.${E}.${C}`]=[A,l,0,k];else if(o[E]==="linear_attention")s[`${n}_conv.${E}`]=[A,M,w],s[`${n}_recurrent.${E}`]=[A,d,p,m];else throw new Error(`Unsupported layer type: ${o[E]}`);return s}return Kk(e,t)}function Kk(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 d=0;d<o;++d)n[`${t}.${d}.key`]=l,n[`${t}.${d}.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 Zk=class qo{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 qo)&&(n=new qo(n));const i=n??await Jk(t,{progress_callback:r,config:n,cache_dir:s,local_files_only:a,revision:o});return new this(i)}},Ai=class{static async from_pretrained(...e){return Zk.from_pretrained(...e)}};function i_(e,t,r){return e?typeof e=="object"&&e!==null?e.hasOwnProperty(t)?+e[t]:e.hasOwnProperty(r)?+e[r]:0:+e:0}function l_(e,t){const r=[];for(let n=0;n<t;++n)r.push(`${e}_data${n===0?"":"_"+n}`);return r}async function eE(e,t,r,n){const s=`${t}${n}.onnx`,a=`${r.subfolder??""}/${s}`;return await Xs(e,a,!0,r,Ie.IS_NODE_ENV)}async function tE(e,t,r,n,s,a={}){const o=`${t}${r}.onnx`,i=Ie.IS_NODE_ENV;let l=[];const u=i_(s,o,t);if(u>0){if(u>yf)throw new Error(`The number of external data chunks (${u}) exceeds the maximum allowed value (${yf}).`);const d=l_(o,u);for(const h of d){const p=`${n.subfolder??""}/${h}`;l.push(new Promise(async(m,w)=>{const v=await Xs(e,p,!0,n,i);m(v instanceof Uint8Array?{path:h,data:v}:h)}))}}else a.externalData!==void 0&&(l=a.externalData.map(async d=>{if(typeof d.data=="string"){const h=await Xs(e,d.data,!0,n);return{...d,data:h}}return d}));return Promise.all(l)}async function rE(e,t,r,n=!1){let s=r.config?.["transformers.js_config"]??{};const a=mp(r.device??s.device,t,{warn:A=>oe.info(A)}),o=Wx(a),i=s.device_config??{};i.hasOwnProperty(a)&&(s={...s,...i[a]});const l=gp(r.dtype??s.dtype,t,a,{configDtype:s.dtype,warn:A=>oe.info(A)});if(Uo.hasOwnProperty(l)){if(a==="webgpu"&&!Ie.IS_NODE_ENV&&l===st.fp16&&!await Qx())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,d=u?typeof u=="string"?u:u[l]??"float32":void 0;if(d&&!["float32","float16"].includes(d))throw new Error(`Invalid kv_cache_dtype: ${d}. Should be one of: float32, float16`);const h=Uo[l],p={...r.session_options};p.executionProviders??=o;const m=s.free_dimension_overrides;m?p.freeDimensionOverrides??=m:a.startsWith("webnn")&&!p.freeDimensionOverrides&&oe.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 w=eE(e,t,r,h),v=r.use_external_data_format??s.use_external_data_format,b=await tE(e,t,h,r,v,p);if(b.length>0&&!Ie.IS_NODE_ENV&&(p.externalData=b),n&&a==="webgpu"&&u!==!1){const A=o_(r.config,{prefix:"present"});if(Object.keys(A).length>0&&!gi()){const E={};for(const C in A)E[C]="gpu-buffer";p.preferredOutputLocation=E}}return{buffer_or_path:await w,session_options:p,session_config:{dtype:l,kv_cache_dtype:d,device:a}}}async function ft(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 rE(e,t[s],r,s===n),l=await fp(a,o,i);return[s,l]})))}function c_(e){for(let t in e)pp(e[t])?e[t]=new j(e[t]):typeof e[t]=="object"&&c_(e[t]);return e}async function Me(e,t){const r=nE(e,t);try{const n=Object.fromEntries(Object.entries(r).map(([a,o])=>{const i=o.ort_tensor;return Ie.IS_NODE_ENV&&typeof Float16Array<"u"&&i.cpuData instanceof Float16Array&&(i.cpuData=new Uint16Array(i.cpuData.buffer)),[a,i]})),s=await hp(e,n);return c_(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 oe.error(`An error occurred during model execution: "${n}".`),oe.error("Inputs given to model:",s),n}}function nE(e,t){const r=Object.create(null),n=[];for(const o of e.inputNames){const i=t[o];if(!(i instanceof j)){n.push(o);continue}r[o]=gi()?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));oe.warn(`WARNING: Too many inputs were provided (${s} > ${a}). The following inputs will be ignored: "${o.join(", ")}".`)}return r}var He=class{},se=class extends He{constructor({logits:e,...t}){super(),this.logits=e;const r=Object.values(t);r.length>0&&(this.attentions=r)}},Qe=class extends He{constructor({logits:e}){super(),this.logits=e}},Je=class extends He{constructor({logits:e}){super(),this.logits=e}},ot=class extends He{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},jr=class extends He{constructor({logits:e}){super(),this.logits=e}},sE=class extends He{constructor({alphas:e}){super(),this.alphas=e}},Jt=class extends Ct{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},aE=class extends Ct{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},Ho=class extends Ct{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()}},oE=class extends Jt{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}},iE=class extends Jt{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}},u_=class extends Jt{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}},lE=class extends Jt{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 d=this.timestamp_begin+this.max_initial_timestamp_index;n.subarray(d+1).fill(-1/0)}const i=Ix(n),l=Math.log(i.subarray(this.timestamp_begin).map(Math.exp).reduce((d,h)=>d+h)),u=Ge(i.subarray(0,this.timestamp_begin))[0];l>u&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},cE=class extends Jt{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}},uE=class extends Jt{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}},dE=class extends Jt{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}},fE=class extends Jt{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}},hE=class extends Jt{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}},pE=class extends Jt{constructor(e){if(super(),e<=1)throw new Error(`Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,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}},_E=class extends aE{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}},d_=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)))}},Ci=class extends Ct{_call(e,t){throw Error("StoppingCriteria needs to be subclassed")}},mE=class f_ extends Ct{constructor(){super(),this.criteria=[]}push(t){this.criteria.push(t)}extend(t){t instanceof f_?t=t.criteria:t instanceof Ci&&(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()}},gE=class extends Ci{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)}},wE=class extends Ci{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)})}},la=class extends Ct{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 Xx(e)}static getSampler(e){if(e.do_sample)return new yE(e);if(e.num_beams>1)return new bE(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 vE(e)}},vE=class extends la{async sample(e){const t=Ge(e.data)[1];return[[BigInt(t),0]]}},yE=class extends la{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 _n(e,t),s=tt(r.data);return Array.from({length:this.generation_config.num_beams},()=>{const a=this.randomSelect(s);return[n.data[a],Math.log(s[a])]})}},bE=class extends la{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 _n(e,t),s=tt(r.data);return Array.from({length:this.generation_config.num_beams},(a,o)=>[n.data[o],Math.log(s[o])])}},Hn=null;function ME(e){Hn=e}function Qo(e){if(e instanceof j)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 j("int64",BigInt64Array.from(e.flat().map(t=>BigInt(t))),[e.length,e[0].length])}else return new j("int64",BigInt64Array.from(e.map(t=>BigInt(t))),[1,e.length])}function h_(e){return new j("bool",[e],[1])}var $={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},Bf={[$.DecoderOnly]:{can_generate:!0,forward:ar,prepare_inputs:Ks},[$.DecoderOnlyWithoutHead]:{can_generate:!1,forward:ar,prepare_inputs:Ks},[$.Seq2Seq]:{can_generate:!0,forward:Ls,prepare_inputs:Zs},[$.Vision2Seq]:{can_generate:!0,forward:Ls,prepare_inputs:Zs},[$.Musicgen]:{can_generate:!0,forward:Ls},[$.EncoderDecoder]:{can_generate:!1,forward:Ls},[$.ImageTextToText]:{can_generate:!0,forward:kE,prepare_inputs:Os},[$.AudioTextToText]:{can_generate:!0,forward:TE,prepare_inputs:Os},[$.Phi3V]:{can_generate:!0,prepare_inputs:Os},[$.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:Os},[$.MultiModality]:{can_generate:!0},[$.AutoEncoder]:{can_generate:!1,forward:xE},[$.Chatterbox]:{can_generate:!0,forward:xr},default:{can_generate:!1,forward:xr}},Mr=new Map,Si=new Map,un=new Map,P=class extends Ct{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=un.get(this.constructor),s=Mr.get(n),a=Bf[s]??Bf.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:d=null,session_options:h={}}={}){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:d,session_options:h},m=un.get(this),w=Mr.get(m);r=p.config=await Ai.from_pretrained(e,p);let v;if(w===$.DecoderOnly)v=await Promise.all([ft(e,{model:p.model_file_name??"model"},p,"model"),sr(e,{generation_config:"generation_config.json"},p)]);else if(w===$.Seq2Seq||w===$.Vision2Seq)v=await Promise.all([ft(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},p,"decoder_model_merged"),sr(e,{generation_config:"generation_config.json"},p)]);else if(w===$.MaskGeneration)v=await Promise.all([ft(e,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},p)]);else if(w===$.EncoderDecoder)v=await Promise.all([ft(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},p,"decoder_model_merged")]);else if(w===$.ImageTextToText){const b={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};r.is_encoder_decoder&&(b.model="encoder_model"),v=await Promise.all([ft(e,b,p,"decoder_model_merged"),sr(e,{generation_config:"generation_config.json"},p)])}else if(w===$.AudioTextToText){const b={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};v=await Promise.all([ft(e,b,p,"decoder_model_merged"),sr(e,{generation_config:"generation_config.json"},p)])}else if(w===$.ImageAudioTextToText){const b={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};v=await Promise.all([ft(e,b,p),sr(e,{generation_config:"generation_config.json"},p)])}else if(w===$.Musicgen)v=await Promise.all([ft(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(w===$.MultiModality)v=await Promise.all([ft(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(w===$.Phi3V)v=await Promise.all([ft(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(w===$.Chatterbox)v=await Promise.all([ft(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(w===$.AutoEncoder)v=await Promise.all([ft(e,{encoder_model:"encoder_model",decoder_model:"decoder_model"},p)]);else if(w===$.Supertonic)v=await Promise.all([ft(e,{text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"},p)]);else{if(w===void 0){const b=m??r?.model_type;b!=="custom"&&oe.warn(`Model type for '${b}' not found, assuming encoder-only architecture. Please report this at ${oa}.`)}v=await Promise.all([ft(e,{model:p.model_file_name??"model"},p)])}return new this(r,...v)}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 Ho;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&n.push(new uE(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&n.push(new cE(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&n.push(new hE(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&n.push(new dE(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 fE(t,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&n.push(new oE(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&n.push(new iE(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 u_(e.begin_suppress_tokens,s))}return e.guidance_scale!==null&&e.guidance_scale>1&&n.push(new pE(e.guidance_scale)),e.temperature===0&&e.do_sample&&(oe.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 _E(e.temperature)),r!==null&&n.extend(r),n}_prepare_generation_config(e,t,r=d_){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 mE;return e.max_length!==null&&r.push(new gE(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&r.push(new wE(e.eos_token_id)),t&&r.extend(t),r}_validate_model_class(){if(!this.can_generate){const e=[Hn.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,Hn.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,Hn.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,Hn.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),t=un.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 j("int64",e.flat(),[e.length,1]),n||(r.attention_mask=De([r.attention_mask,At([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 xr(this,t);if(n.guidance_scale!==null&&n.guidance_scale>1)s=De([s,Vo(s,0)],0),"attention_mask"in t&&(t.attention_mask=De([t.attention_mask,Tp(t.attention_mask)],0));else if(t.decoder_input_ids){const a=Qo(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=De(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 j)){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=Qo(o)}return r.decoder_attention_mask=Mp(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 d;u?{input_ids:d,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}):d=i[l];let h=d.dims.at(-1);t.max_new_tokens!==null&&(t.max_length=h+t.max_new_tokens);const p=this._get_logits_processor(t,h,r),m=this._get_stopping_criteria(t,n),w=i[l].dims.at(0),v=la.getSampler(t),b=new Array(w).fill(0),M=d.tolist();s&&s.put(M);let k,A={},E={};for(;;){if(i=this.prepare_inputs_for_generation(M,i,t),k=await this.forward(i),t.return_dict_in_generate)if(t.output_attentions){const J=this.getAttentions(k);for(const q in J)q in A||(A[q]=[]),A[q].push(J[q])}else this._return_dict_in_generate_keys&&Object.assign(E,ht(k,this._return_dict_in_generate_keys));const x=k.logits.slice(null,-1,null).to("float32"),V=p(M,x),G=[];for(let J=0;J<V.dims.at(0);++J){const q=V[J],B=await v(q);for(const[N,U]of B){const ee=BigInt(N);b[J]+=U,M[J].push(ee),G.push([ee]);break}}if(s&&s.put(G),m(M).every(J=>J))break;i=this._update_model_kwargs_for_generation({generated_input_ids:G,outputs:k,model_inputs:i,is_encoder_decoder:u})}s&&s.end();const C=this.getPastKeyValues(k,i.past_key_values,!0),O=new j("int64",M.flat(),[M.length,M[0].length]);if(t.return_dict_in_generate)return{sequences:O,past_key_values:C,...A,...E};for(const x of Object.values(k))x.location==="gpu-buffer"&&x.dispose();return O}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"?Ys.float16:Ys.float32,o=o_(this.config,{batch_size:n});for(const i in o){const l=o[i].reduce((u,d)=>u*d,1);e[i]=new j(s,new a(l),o[i])}}}async encode_image({pixel_values:e}){return(await Me(this.sessions.vision_encoder,{pixel_values:e})).image_features}async encode_text({input_ids:e}){return(await Me(this.sessions.embed_tokens,{input_ids:e})).inputs_embeds}async encode_audio({audio_values:e}){return(await Me(this.sessions.audio_encoder,{audio_values:e})).audio_features}};async function Ls(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 xr(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 xr(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=Tp(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=At([s[0],s[2],s[3]])}return await Me(r,n)}async function xE(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=EE(a,s,i)}e.addPastKeyValues(a,s);const o=ht(a,n.inputNames);return await Me(n,o)}async function p_(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:d=null,logits_processor:h=null,...p}){const m=p[n];if(!l){if(l=await e.encode_text({input_ids:a,...p}),m&&a.dims[1]!==1){const v=await t({[n]:m,...p});({inputs_embeds:l,attention_mask:o}=r({[s]:v,inputs_embeds:l,input_ids:a,attention_mask:o}))}else if(u&&m&&a.dims[1]===1){const v=a.dims[1],b=Object.values(u)[0].dims.at(-2);o=De([At([a.dims[0],b]),o.slice(null,[o.dims[1]-v,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:v,video_grid_thw:b}=p;[i]=e.get_rope_index(a,v,b,o)}return await ar(e,{inputs_embeds:l,past_key_values:u,attention_mask:o,position_ids:i,generation_config:d,logits_processor:h},!0)}async function TE(e,t){return await p_(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 kE(e,t){return await p_(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 __(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 d=i+u;s[d]===0n?a[d]=BigInt(1):(a[d]=l,l+=s[d])}}return{data:a,dims:e.dims}}function EE(e,t=null,r=0){const{input_ids:n,inputs_embeds:s,attention_mask:a}=e,{data:o,dims:i}=__(a,r);let l=new j("int64",o,i);if(t){const u=-(n??s).dims.at(1);l=l.slice(null,[u,null])}return l}function Ks(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=At([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 Zs(e,t,r,n){return r.past_key_values&&(t=t.map(s=>[s.at(-1)])),{...r,decoder_input_ids:Qo(t)}}function Os(e,...t){return e.config.is_encoder_decoder?Zs(e,...t):Ks(e,...t)}function m_({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:n,attention_mask:s}){const a=n.tolist().map(u=>u.reduce((d,h,p)=>(h==e&&d.push(p),d),[])),o=a.reduce((u,d)=>u+d.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 d=a[u],h=t[u];for(let p=0;p<d.length;++p)h[d[p]].data.set(r[l++].data)}return{inputs_embeds:t,attention_mask:s}}function ns({image_token_id:e,inputs_embeds:t,image_features:r,input_ids:n,attention_mask:s}){return m_({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:n,attention_mask:s})}function g_({audio_token_id:e,inputs_embeds:t,audio_features:r,input_ids:n,attention_mask:s}){return m_({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 Pi={};fn(Pi,{ASTForAudioClassification:()=>BE,ASTModel:()=>zE,ASTPreTrainedModel:()=>Oi,AfmoeForCausalLM:()=>OE,AfmoeModel:()=>LE,AfmoePreTrainedModel:()=>Ii,AlbertForMaskedLM:()=>PE,AlbertForQuestionAnswering:()=>SE,AlbertForSequenceClassification:()=>CE,AlbertModel:()=>AE,AlbertPreTrainedModel:()=>ss,ApertusForCausalLM:()=>IE,ApertusModel:()=>FE,ApertusPreTrainedModel:()=>Fi,ArceeForCausalLM:()=>DE,ArceeModel:()=>NE,ArceePreTrainedModel:()=>Li,BartForConditionalGeneration:()=>$E,BartForSequenceClassification:()=>GE,BartModel:()=>RE,BartPretrainedModel:()=>ca,BeitForImageClassification:()=>VE,BeitModel:()=>UE,BeitPreTrainedModel:()=>Ni,BertForMaskedLM:()=>WE,BertForQuestionAnswering:()=>QE,BertForSequenceClassification:()=>qE,BertForTokenClassification:()=>HE,BertModel:()=>jE,BertPreTrainedModel:()=>gn,BlenderbotForConditionalGeneration:()=>YE,BlenderbotModel:()=>XE,BlenderbotPreTrainedModel:()=>Di,BlenderbotSmallForConditionalGeneration:()=>KE,BlenderbotSmallModel:()=>JE,BlenderbotSmallPreTrainedModel:()=>zi,BloomForCausalLM:()=>e2,BloomModel:()=>ZE,BloomPreTrainedModel:()=>Bi,CLIPModel:()=>c2,CLIPPreTrainedModel:()=>Wr,CLIPSegForImageSegmentation:()=>p2,CLIPSegModel:()=>h2,CLIPSegPreTrainedModel:()=>Ri,CLIPTextModel:()=>u2,CLIPTextModelWithProjection:()=>x_,CLIPVisionModel:()=>d2,CLIPVisionModelWithProjection:()=>f2,CamembertForMaskedLM:()=>r2,CamembertForQuestionAnswering:()=>a2,CamembertForSequenceClassification:()=>n2,CamembertForTokenClassification:()=>s2,CamembertModel:()=>t2,CamembertPreTrainedModel:()=>wn,ChatterboxModel:()=>v_,ChatterboxPreTrainedModel:()=>w_,ChineseCLIPModel:()=>i2,ChineseCLIPPreTrainedModel:()=>y_,ClapAudioModelWithProjection:()=>M_,ClapModel:()=>l2,ClapPreTrainedModel:()=>ua,ClapTextModelWithProjection:()=>b_,CodeGenForCausalLM:()=>m2,CodeGenModel:()=>_2,CodeGenPreTrainedModel:()=>$i,Cohere2ForCausalLM:()=>y2,Cohere2Model:()=>v2,Cohere2PreTrainedModel:()=>Ui,CohereForCausalLM:()=>w2,CohereModel:()=>g2,CoherePreTrainedModel:()=>Gi,ConvBertForMaskedLM:()=>M2,ConvBertForQuestionAnswering:()=>k2,ConvBertForSequenceClassification:()=>x2,ConvBertForTokenClassification:()=>T2,ConvBertModel:()=>b2,ConvBertPreTrainedModel:()=>vn,ConvNextForImageClassification:()=>A2,ConvNextModel:()=>E2,ConvNextPreTrainedModel:()=>Vi,ConvNextV2ForImageClassification:()=>S2,ConvNextV2Model:()=>C2,ConvNextV2PreTrainedModel:()=>ji,DFineForObjectDetection:()=>L2,DFineModel:()=>I2,DFinePreTrainedModel:()=>qi,DINOv3ConvNextModel:()=>nA,DINOv3ConvNextPreTrainedModel:()=>I_,DINOv3ViTModel:()=>sA,DINOv3ViTPreTrainedModel:()=>L_,DPTForDepthEstimation:()=>fA,DPTModel:()=>dA,DPTPreTrainedModel:()=>Ji,DacDecoderModel:()=>A_,DacDecoderOutput:()=>k_,DacEncoderModel:()=>E_,DacEncoderOutput:()=>T_,DacModel:()=>O2,DacPreTrainedModel:()=>da,DebertaForMaskedLM:()=>D2,DebertaForQuestionAnswering:()=>R2,DebertaForSequenceClassification:()=>z2,DebertaForTokenClassification:()=>B2,DebertaModel:()=>N2,DebertaPreTrainedModel:()=>yn,DebertaV2ForMaskedLM:()=>G2,DebertaV2ForQuestionAnswering:()=>j2,DebertaV2ForSequenceClassification:()=>U2,DebertaV2ForTokenClassification:()=>V2,DebertaV2Model:()=>$2,DebertaV2PreTrainedModel:()=>bn,DecisionTransformerModel:()=>W2,DecisionTransformerPreTrainedModel:()=>C_,DeiTForImageClassification:()=>H2,DeiTModel:()=>q2,DeiTPreTrainedModel:()=>Hi,DepthAnythingForDepthEstimation:()=>Q2,DepthAnythingPreTrainedModel:()=>S_,DepthProForDepthEstimation:()=>X2,DepthProPreTrainedModel:()=>P_,DetrForObjectDetection:()=>J2,DetrForSegmentation:()=>K2,DetrModel:()=>Y2,DetrObjectDetectionOutput:()=>Qi,DetrPreTrainedModel:()=>fa,DetrSegmentationOutput:()=>F_,Dinov2ForImageClassification:()=>eA,Dinov2Model:()=>Z2,Dinov2PreTrainedModel:()=>Xi,Dinov2WithRegistersForImageClassification:()=>rA,Dinov2WithRegistersModel:()=>tA,Dinov2WithRegistersPreTrainedModel:()=>Yi,DistilBertForMaskedLM:()=>cA,DistilBertForQuestionAnswering:()=>lA,DistilBertForSequenceClassification:()=>oA,DistilBertForTokenClassification:()=>iA,DistilBertModel:()=>aA,DistilBertPreTrainedModel:()=>Mn,DonutSwinModel:()=>uA,DonutSwinPreTrainedModel:()=>O_,EdgeTamModel:()=>XP,EfficientNetForImageClassification:()=>pA,EfficientNetModel:()=>hA,EfficientNetPreTrainedModel:()=>Ki,ElectraForMaskedLM:()=>mA,ElectraForQuestionAnswering:()=>vA,ElectraForSequenceClassification:()=>gA,ElectraForTokenClassification:()=>wA,ElectraModel:()=>_A,ElectraPreTrainedModel:()=>xn,Ernie4_5ForCausalLM:()=>bA,Ernie4_5Model:()=>yA,Ernie4_5PretrainedModel:()=>Zi,EsmForMaskedLM:()=>xA,EsmForSequenceClassification:()=>TA,EsmForTokenClassification:()=>kA,EsmModel:()=>MA,EsmPreTrainedModel:()=>os,ExaoneForCausalLM:()=>AA,ExaoneModel:()=>EA,ExaonePreTrainedModel:()=>el,FalconForCausalLM:()=>SA,FalconH1ForCausalLM:()=>FA,FalconH1Model:()=>PA,FalconH1PreTrainedModel:()=>rl,FalconModel:()=>CA,FalconPreTrainedModel:()=>tl,FastViTForImageClassification:()=>LA,FastViTModel:()=>IA,FastViTPreTrainedModel:()=>nl,Florence2ForConditionalGeneration:()=>OA,Florence2PreTrainedModel:()=>N_,GLPNForDepthEstimation:()=>jA,GLPNModel:()=>VA,GLPNPreTrainedModel:()=>ll,GPT2LMHeadModel:()=>eC,GPT2Model:()=>ZA,GPT2PreTrainedModel:()=>hl,GPTBigCodeForCausalLM:()=>qA,GPTBigCodeModel:()=>WA,GPTBigCodePreTrainedModel:()=>cl,GPTJForCausalLM:()=>rC,GPTJModel:()=>tC,GPTJPreTrainedModel:()=>pl,GPTNeoForCausalLM:()=>QA,GPTNeoModel:()=>HA,GPTNeoPreTrainedModel:()=>ul,GPTNeoXForCausalLM:()=>YA,GPTNeoXModel:()=>XA,GPTNeoXPreTrainedModel:()=>dl,Gemma2ForCausalLM:()=>BA,Gemma2Model:()=>zA,Gemma2PreTrainedModel:()=>al,Gemma3ForCausalLM:()=>$A,Gemma3Model:()=>RA,Gemma3PreTrainedModel:()=>ol,Gemma3nForConditionalGeneration:()=>z_,Gemma3nPreTrainedModel:()=>D_,GemmaForCausalLM:()=>DA,GemmaModel:()=>NA,GemmaPreTrainedModel:()=>sl,GlmForCausalLM:()=>UA,GlmModel:()=>GA,GlmPreTrainedModel:()=>il,GptOssForCausalLM:()=>KA,GptOssModel:()=>JA,GptOssPreTrainedModel:()=>fl,GraniteForCausalLM:()=>sC,GraniteModel:()=>nC,GraniteMoeHybridForCausalLM:()=>oC,GraniteMoeHybridModel:()=>aC,GraniteMoeHybridPreTrainedModel:()=>ml,GranitePreTrainedModel:()=>_l,GroundingDinoForObjectDetection:()=>iC,GroundingDinoPreTrainedModel:()=>B_,GroupViTModel:()=>lC,GroupViTPreTrainedModel:()=>R_,HeliumForCausalLM:()=>uC,HeliumModel:()=>cC,HeliumPreTrainedModel:()=>gl,HieraForImageClassification:()=>fC,HieraModel:()=>dC,HieraPreTrainedModel:()=>wl,HubertForCTC:()=>vC,HubertForSequenceClassification:()=>yC,HubertModel:()=>wC,HubertPreTrainedModel:()=>gC,HunYuanDenseV1ForCausalLM:()=>MC,HunYuanDenseV1Model:()=>bC,HunYuanDenseV1PreTrainedModel:()=>vl,IJepaForImageClassification:()=>kC,IJepaModel:()=>TC,IJepaPreTrainedModel:()=>yl,Idefics3ForConditionalGeneration:()=>G_,Idefics3PreTrainedModel:()=>$_,JAISLMHeadModel:()=>AC,JAISModel:()=>EC,JAISPreTrainedModel:()=>bl,JinaCLIPModel:()=>CC,JinaCLIPPreTrainedModel:()=>ha,JinaCLIPTextModel:()=>U_,JinaCLIPVisionModel:()=>SC,Lfm2ForCausalLM:()=>FC,Lfm2Model:()=>PC,Lfm2MoeForCausalLM:()=>LC,Lfm2MoeModel:()=>IC,Lfm2MoePreTrainedModel:()=>xl,Lfm2PreTrainedModel:()=>Ml,LiteWhisperForConditionalGeneration:()=>iI,Llama4ForCausalLM:()=>DC,Llama4PreTrainedModel:()=>V_,LlamaForCausalLM:()=>NC,LlamaModel:()=>OC,LlamaPreTrainedModel:()=>Tl,LlavaForConditionalGeneration:()=>ea,LlavaOnevisionForConditionalGeneration:()=>ea,LlavaPreTrainedModel:()=>j_,LlavaQwen2ForCausalLM:()=>BC,LongT5ForConditionalGeneration:()=>$C,LongT5Model:()=>RC,LongT5PreTrainedModel:()=>kl,M2M100ForConditionalGeneration:()=>UC,M2M100Model:()=>GC,M2M100PreTrainedModel:()=>El,MBartForCausalLM:()=>YC,MBartForConditionalGeneration:()=>QC,MBartForSequenceClassification:()=>XC,MBartModel:()=>HC,MBartPreTrainedModel:()=>is,MPNetForMaskedLM:()=>OS,MPNetForQuestionAnswering:()=>zS,MPNetForSequenceClassification:()=>NS,MPNetForTokenClassification:()=>DS,MPNetModel:()=>LS,MPNetPreTrainedModel:()=>Tn,MT5ForConditionalGeneration:()=>GS,MT5Model:()=>$S,MT5PreTrainedModel:()=>Dl,MarianMTModel:()=>jC,MarianModel:()=>VC,MarianPreTrainedModel:()=>Al,MaskFormerForInstanceSegmentation:()=>qC,MaskFormerModel:()=>WC,MaskFormerPreTrainedModel:()=>Cl,Metric3DForDepthEstimation:()=>JC,Metric3DPreTrainedModel:()=>W_,Metric3Dv2ForDepthEstimation:()=>KC,Metric3Dv2PreTrainedModel:()=>q_,MgpstrForSceneTextRecognition:()=>ZC,MgpstrModelOutput:()=>H_,MgpstrPreTrainedModel:()=>Q_,MimiDecoderModel:()=>K_,MimiDecoderOutput:()=>Y_,MimiEncoderModel:()=>J_,MimiEncoderOutput:()=>X_,MimiModel:()=>eS,MimiPreTrainedModel:()=>pa,MistralForCausalLM:()=>rS,MistralModel:()=>tS,MistralPreTrainedModel:()=>Sl,MobileBertForMaskedLM:()=>sS,MobileBertForQuestionAnswering:()=>oS,MobileBertForSequenceClassification:()=>aS,MobileBertModel:()=>nS,MobileBertPreTrainedModel:()=>ls,MobileLLMForCausalLM:()=>lS,MobileLLMModel:()=>iS,MobileLLMPreTrainedModel:()=>Pl,MobileNetV1ForImageClassification:()=>uS,MobileNetV1ForSemanticSegmentation:()=>dS,MobileNetV1Model:()=>cS,MobileNetV1PreTrainedModel:()=>_a,MobileNetV2ForImageClassification:()=>hS,MobileNetV2ForSemanticSegmentation:()=>pS,MobileNetV2Model:()=>fS,MobileNetV2PreTrainedModel:()=>ma,MobileNetV3ForImageClassification:()=>mS,MobileNetV3ForSemanticSegmentation:()=>gS,MobileNetV3Model:()=>_S,MobileNetV3PreTrainedModel:()=>ga,MobileNetV4ForImageClassification:()=>vS,MobileNetV4ForSemanticSegmentation:()=>yS,MobileNetV4Model:()=>wS,MobileNetV4PreTrainedModel:()=>wa,MobileViTForImageClassification:()=>MS,MobileViTModel:()=>bS,MobileViTPreTrainedModel:()=>Fl,MobileViTV2ForImageClassification:()=>TS,MobileViTV2Model:()=>xS,MobileViTV2PreTrainedModel:()=>Il,ModernBertDecoderForCausalLM:()=>PS,ModernBertDecoderModel:()=>SS,ModernBertDecoderPreTrainedModel:()=>Ll,ModernBertForMaskedLM:()=>ES,ModernBertForSequenceClassification:()=>AS,ModernBertForTokenClassification:()=>CS,ModernBertModel:()=>kS,ModernBertPreTrainedModel:()=>cs,Moondream1ForConditionalGeneration:()=>zC,MoonshineForConditionalGeneration:()=>IS,MoonshineModel:()=>FS,MoonshinePreTrainedModel:()=>Ol,MptForCausalLM:()=>RS,MptModel:()=>BS,MptPreTrainedModel:()=>Nl,MultiModalityCausalLM:()=>US,MultiModalityPreTrainedModel:()=>Z_,MusicgenForCausalLM:()=>jS,MusicgenForConditionalGeneration:()=>em,MusicgenModel:()=>VS,MusicgenPreTrainedModel:()=>zl,NanoChatForCausalLM:()=>qS,NanoChatModel:()=>WS,NanoChatPreTrainedModel:()=>Bl,NeoBertForMaskedLM:()=>QS,NeoBertForQuestionAnswering:()=>JS,NeoBertForSequenceClassification:()=>XS,NeoBertForTokenClassification:()=>YS,NeoBertModel:()=>HS,NeoBertPreTrainedModel:()=>kn,NomicBertModel:()=>KS,NomicBertPreTrainedModel:()=>tm,OPTForCausalLM:()=>lP,OPTModel:()=>iP,OPTPreTrainedModel:()=>Vl,Olmo2ForCausalLM:()=>rP,Olmo2Model:()=>tP,Olmo2PreTrainedModel:()=>$l,Olmo3ForCausalLM:()=>sP,Olmo3Model:()=>nP,Olmo3PreTrainedModel:()=>Gl,OlmoForCausalLM:()=>eP,OlmoModel:()=>ZS,OlmoPreTrainedModel:()=>Rl,OpenELMForCausalLM:()=>oP,OpenELMModel:()=>aP,OpenELMPreTrainedModel:()=>Ul,OwlViTForObjectDetection:()=>fP,OwlViTModel:()=>dP,OwlViTPreTrainedModel:()=>Wl,Owlv2ForObjectDetection:()=>uP,Owlv2Model:()=>cP,Owlv2PreTrainedModel:()=>jl,PaliGemmaForConditionalGeneration:()=>hP,PaliGemmaPreTrainedModel:()=>rm,ParakeetForCTC:()=>pP,ParakeetPreTrainedModel:()=>nm,PatchTSMixerForPrediction:()=>mP,PatchTSMixerModel:()=>_P,PatchTSMixerPreTrainedModel:()=>ql,PatchTSTForPrediction:()=>wP,PatchTSTModel:()=>gP,PatchTSTPreTrainedModel:()=>Hl,Phi3ForCausalLM:()=>MP,Phi3Model:()=>bP,Phi3PreTrainedModel:()=>Xl,Phi3VForCausalLM:()=>am,Phi3VPreTrainedModel:()=>sm,PhiForCausalLM:()=>yP,PhiModel:()=>vP,PhiPreTrainedModel:()=>Ql,PreTrainedModel:()=>P,PvtForImageClassification:()=>TP,PvtModel:()=>xP,PvtPreTrainedModel:()=>Yl,PyAnnoteForAudioFrameClassification:()=>EP,PyAnnoteModel:()=>kP,PyAnnotePreTrainedModel:()=>Jl,Qwen2ForCausalLM:()=>CP,Qwen2Model:()=>AP,Qwen2PreTrainedModel:()=>Kl,Qwen2VLForConditionalGeneration:()=>im,Qwen2VLPreTrainedModel:()=>om,Qwen2_5_VLForConditionalGeneration:()=>lm,Qwen3ForCausalLM:()=>PP,Qwen3Model:()=>SP,Qwen3PreTrainedModel:()=>Zl,Qwen3VLForConditionalGeneration:()=>cm,Qwen3_5ForConditionalGeneration:()=>um,Qwen3_5MoeForConditionalGeneration:()=>FP,RFDetrForObjectDetection:()=>NP,RFDetrModel:()=>OP,RFDetrObjectDetectionOutput:()=>dm,RFDetrPreTrainedModel:()=>tc,RTDetrForObjectDetection:()=>F2,RTDetrModel:()=>P2,RTDetrObjectDetectionOutput:()=>as,RTDetrPreTrainedModel:()=>Wi,RTDetrV2ForObjectDetection:()=>HP,RTDetrV2Model:()=>qP,RTDetrV2ObjectDetectionOutput:()=>fm,RTDetrV2PreTrainedModel:()=>rc,ResNetForImageClassification:()=>LP,ResNetModel:()=>IP,ResNetPreTrainedModel:()=>ec,RoFormerForMaskedLM:()=>UP,RoFormerForQuestionAnswering:()=>WP,RoFormerForSequenceClassification:()=>VP,RoFormerForTokenClassification:()=>jP,RoFormerModel:()=>GP,RoFormerPreTrainedModel:()=>An,RobertaForMaskedLM:()=>zP,RobertaForQuestionAnswering:()=>$P,RobertaForSequenceClassification:()=>BP,RobertaForTokenClassification:()=>RP,RobertaModel:()=>DP,RobertaPreTrainedModel:()=>En,Sam2ImageSegmentationOutput:()=>_m,Sam2Model:()=>nc,Sam2PreTrainedModel:()=>mm,Sam3TrackerModel:()=>YP,SamImageSegmentationOutput:()=>hm,SamModel:()=>QP,SamPreTrainedModel:()=>pm,SapiensForDepthEstimation:()=>KP,SapiensForNormalEstimation:()=>ZP,SapiensForSemanticSegmentation:()=>JP,SapiensPreTrainedModel:()=>va,SegformerForImageClassification:()=>tF,SegformerForSemanticSegmentation:()=>rF,SegformerModel:()=>eF,SegformerPreTrainedModel:()=>ya,SiglipModel:()=>nF,SiglipPreTrainedModel:()=>sc,SiglipTextModel:()=>gm,SiglipVisionModel:()=>sF,SmolLM3ForCausalLM:()=>oF,SmolLM3Model:()=>aF,SmolLM3PreTrainedModel:()=>ac,SmolVLMForConditionalGeneration:()=>xC,SnacDecoderModel:()=>vm,SnacEncoderModel:()=>wm,SnacModel:()=>iF,SnacPreTrainedModel:()=>ba,SpeechT5ForSpeechToText:()=>cF,SpeechT5ForTextToSpeech:()=>uF,SpeechT5HifiGan:()=>dF,SpeechT5Model:()=>lF,SpeechT5PreTrainedModel:()=>Ma,SqueezeBertForMaskedLM:()=>hF,SqueezeBertForQuestionAnswering:()=>_F,SqueezeBertForSequenceClassification:()=>pF,SqueezeBertModel:()=>fF,SqueezeBertPreTrainedModel:()=>us,StableLmForCausalLM:()=>gF,StableLmModel:()=>mF,StableLmPreTrainedModel:()=>oc,Starcoder2ForCausalLM:()=>vF,Starcoder2Model:()=>wF,Starcoder2PreTrainedModel:()=>ic,StyleTextToSpeech2Model:()=>yF,StyleTextToSpeech2PreTrainedModel:()=>ym,SupertonicForConditionalGeneration:()=>Mm,SupertonicPreTrainedModel:()=>bm,Swin2SRForImageSuperResolution:()=>kF,Swin2SRModel:()=>TF,Swin2SRPreTrainedModel:()=>lc,SwinForImageClassification:()=>MF,SwinForSemanticSegmentation:()=>xF,SwinModel:()=>bF,SwinPreTrainedModel:()=>xa,T5ForConditionalGeneration:()=>AF,T5Model:()=>EF,T5PreTrainedModel:()=>cc,TableTransformerForObjectDetection:()=>SF,TableTransformerModel:()=>CF,TableTransformerObjectDetectionOutput:()=>xm,TableTransformerPreTrainedModel:()=>uc,TrOCRForCausalLM:()=>PF,TrOCRPreTrainedModel:()=>Tm,UltravoxModel:()=>Em,UltravoxPreTrainedModel:()=>km,UniSpeechForCTC:()=>LF,UniSpeechForSequenceClassification:()=>OF,UniSpeechModel:()=>IF,UniSpeechPreTrainedModel:()=>Ta,UniSpeechSatForAudioFrameClassification:()=>BF,UniSpeechSatForCTC:()=>DF,UniSpeechSatForSequenceClassification:()=>zF,UniSpeechSatModel:()=>NF,UniSpeechSatPreTrainedModel:()=>ds,VaultGemmaForCausalLM:()=>$F,VaultGemmaModel:()=>RF,VaultGemmaPreTrainedModel:()=>dc,ViTForImageClassification:()=>VF,ViTMAEModel:()=>jF,ViTMAEPreTrainedModel:()=>Am,ViTMSNForImageClassification:()=>qF,ViTMSNModel:()=>WF,ViTMSNPreTrainedModel:()=>hc,ViTModel:()=>UF,ViTPreTrainedModel:()=>fc,VisionEncoderDecoderModel:()=>GF,VitMatteForImageMatting:()=>HF,VitMattePreTrainedModel:()=>Cm,VitPoseForPoseEstimation:()=>QF,VitPosePreTrainedModel:()=>Sm,VitsModel:()=>XF,VitsModelOutput:()=>Pm,VitsPreTrainedModel:()=>Fm,VoxtralForConditionalGeneration:()=>FF,Wav2Vec2BertForCTC:()=>JF,Wav2Vec2BertForSequenceClassification:()=>KF,Wav2Vec2BertModel:()=>YF,Wav2Vec2BertPreTrainedModel:()=>ka,Wav2Vec2ForAudioFrameClassification:()=>mC,Wav2Vec2ForCTC:()=>pC,Wav2Vec2ForSequenceClassification:()=>_C,Wav2Vec2Model:()=>hC,Wav2Vec2PreTrainedModel:()=>Tr,WavLMForAudioFrameClassification:()=>nI,WavLMForCTC:()=>eI,WavLMForSequenceClassification:()=>tI,WavLMForXVector:()=>rI,WavLMModel:()=>ZF,WavLMPreTrainedModel:()=>Cn,WeSpeakerResNetModel:()=>sI,WeSpeakerResNetPreTrainedModel:()=>Lm,WhisperForConditionalGeneration:()=>Om,WhisperModel:()=>oI,WhisperPreTrainedModel:()=>pc,XLMForQuestionAnswering:()=>fI,XLMForSequenceClassification:()=>uI,XLMForTokenClassification:()=>dI,XLMModel:()=>lI,XLMPreTrainedModel:()=>Sn,XLMRobertaForMaskedLM:()=>pI,XLMRobertaForQuestionAnswering:()=>gI,XLMRobertaForSequenceClassification:()=>_I,XLMRobertaForTokenClassification:()=>mI,XLMRobertaModel:()=>hI,XLMRobertaPreTrainedModel:()=>Pn,XLMWithLMHeadModel:()=>cI,XVectorOutput:()=>Im,YolosForObjectDetection:()=>vI,YolosModel:()=>wI,YolosObjectDetectionOutput:()=>Nm,YolosPreTrainedModel:()=>_c,YoutuForCausalLM:()=>bI,YoutuModel:()=>yI,YoutuPreTrainedModel:()=>mc});var ss=class extends P{},AE=class extends ss{},CE=class extends ss{async _call(e){return new se(await super._call(e))}},SE=class extends ss{async _call(e){return new ot(await super._call(e))}},PE=class extends ss{async _call(e){return new Je(await super._call(e))}},Fi=class extends P{},FE=class extends Fi{},IE=class extends Fi{},Ii=class extends P{},LE=class extends Ii{},OE=class extends Ii{},Li=class extends P{},NE=class extends Li{},DE=class extends Li{},Oi=class extends P{},zE=class extends Oi{},BE=class extends Oi{},ca=class extends P{},RE=class extends ca{},$E=class extends ca{},GE=class extends ca{async _call(e){return new se(await super._call(e))}},Ni=class extends P{},UE=class extends Ni{},VE=class extends Ni{async _call(e){return new se(await super._call(e))}},gn=class extends P{},jE=class extends gn{},WE=class extends gn{async _call(e){return new Je(await super._call(e))}},qE=class extends gn{async _call(e){return new se(await super._call(e))}},HE=class extends gn{async _call(e){return new Qe(await super._call(e))}},QE=class extends gn{async _call(e){return new ot(await super._call(e))}},Di=class extends P{},XE=class extends Di{},YE=class extends Di{},zi=class extends P{},JE=class extends zi{},KE=class extends zi{},Bi=class extends P{},ZE=class extends Bi{},e2=class extends Bi{},wn=class extends P{},t2=class extends wn{},r2=class extends wn{async _call(e){return new Je(await super._call(e))}},n2=class extends wn{async _call(e){return new se(await super._call(e))}},s2=class extends wn{async _call(e){return new Qe(await super._call(e))}},a2=class extends wn{async _call(e){return new ot(await super._call(e))}},o2=4299n,Rf=6561n,w_=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"]},v_=class extends w_{async encode_speech(e){return Me(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:d=null,speaker_embeddings:h=null,speaker_features:p=null,...m}){let w;if(!a){const b=this.sessions.embed_tokens.inputNames,M={input_ids:e};if(b.includes("exaggeration")){if(!(n instanceof j)){const k=e.dims[0];if(n==null)n=at([k],.5);else if(typeof n=="number")n=at([k],n);else if(Array.isArray(n))n=new j("float32",n,[k]);else throw new Error("Unsupported type for `exaggeration` input")}M.exaggeration=n}if(b.includes("position_ids")&&(M.position_ids=s),{inputs_embeds:a}=await Me(this.sessions.embed_tokens,M),u&&d&&h&&p&&(w={audio_features:u,audio_tokens:d,speaker_embeddings:h,speaker_features:p}),w||r)w??=await this.encode_speech(r),a=De([w.audio_features,a],1),t=At([a.dims[0],a.dims[1]]);else{const k=a.dims[1];if(!o||k!==1)throw new Error("Incorrect state encountered during generation.");const A=Object.values(o)[0].dims.at(-2);t=At([a.dims[0],A+k])}}return{...await ar(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,generation_config:i,logits_processor:l},!1),...w}}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==Rf)-1);t.position_ids=new j("int64",n,[e.length,1])}else{const s=t.input_ids.tolist().map(a=>{let o=0;return a.map(i=>i>=Rf?0:o++)});t.position_ids=new j("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),Ks(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],o2),i=De([r,a,o],1),{waveform:l}=await Me(this.sessions.conditional_decoder,{speech_tokens:i,speaker_features:s,speaker_embeddings:n});return l}},y_=class extends P{},i2=class extends y_{},ua=class extends P{},l2=class extends ua{},b_=class extends ua{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},M_=class extends ua{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"audio_model"})}},Wr=class extends P{},c2=class extends Wr{},u2=class extends Wr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},x_=class extends Wr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},d2=class extends Wr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},f2=class extends Wr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Ri=class extends P{},h2=class extends Ri{},p2=class extends Ri{},$i=class extends P{},_2=class extends $i{},m2=class extends $i{},Gi=class extends P{},g2=class extends Gi{},w2=class extends Gi{},Ui=class extends P{},v2=class extends Ui{},y2=class extends Ui{},vn=class extends P{},b2=class extends vn{},M2=class extends vn{async _call(e){return new Je(await super._call(e))}},x2=class extends vn{async _call(e){return new se(await super._call(e))}},T2=class extends vn{async _call(e){return new Qe(await super._call(e))}},k2=class extends vn{async _call(e){return new ot(await super._call(e))}},Vi=class extends P{},E2=class extends Vi{},A2=class extends Vi{async _call(e){return new se(await super._call(e))}},ji=class extends P{},C2=class extends ji{},S2=class extends ji{async _call(e){return new se(await super._call(e))}},Wi=class extends P{},P2=class extends Wi{},F2=class extends Wi{async _call(e){return new as(await super._call(e))}},as=class extends He{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},qi=class extends P{},I2=class extends qi{},L2=class extends qi{async _call(e){return new as(await super._call(e))}},T_=class extends He{constructor({audio_codes:e}){super(),this.audio_codes=e}},k_=class extends He{constructor({audio_values:e}){super(),this.audio_values=e}},da=class extends P{main_input_name="input_values";forward_params=["input_values"]},O2=class extends da{async encode(e){return new T_(await Me(this.sessions.encoder_model,e))}async decode(e){return new k_(await Me(this.sessions.decoder_model,e))}},E_=class extends da{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},A_=class extends da{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},yn=class extends P{},N2=class extends yn{},D2=class extends yn{async _call(e){return new Je(await super._call(e))}},z2=class extends yn{async _call(e){return new se(await super._call(e))}},B2=class extends yn{async _call(e){return new Qe(await super._call(e))}},R2=class extends yn{async _call(e){return new ot(await super._call(e))}},bn=class extends P{},$2=class extends bn{},G2=class extends bn{async _call(e){return new Je(await super._call(e))}},U2=class extends bn{async _call(e){return new se(await super._call(e))}},V2=class extends bn{async _call(e){return new Qe(await super._call(e))}},j2=class extends bn{async _call(e){return new ot(await super._call(e))}},C_=class extends P{},W2=class extends C_{},Hi=class extends P{},q2=class extends Hi{},H2=class extends Hi{async _call(e){return new se(await super._call(e))}},S_=class extends P{},Q2=class extends S_{},P_=class extends P{},X2=class extends P_{},fa=class extends P{},Y2=class extends fa{},J2=class extends fa{async _call(e){return new Qi(await super._call(e))}},K2=class extends fa{async _call(e){return new F_(await super._call(e))}},Qi=class extends He{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},F_=class extends He{constructor({logits:e,pred_boxes:t,pred_masks:r}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=r}},Xi=class extends P{},Z2=class extends Xi{},eA=class extends Xi{async _call(e){return new se(await super._call(e))}},Yi=class extends P{},tA=class extends Yi{},rA=class extends Yi{async _call(e){return new se(await super._call(e))}},I_=class extends P{},nA=class extends I_{},L_=class extends P{},sA=class extends L_{},Mn=class extends P{},aA=class extends Mn{},oA=class extends Mn{async _call(e){return new se(await super._call(e))}},iA=class extends Mn{async _call(e){return new Qe(await super._call(e))}},lA=class extends Mn{async _call(e){return new ot(await super._call(e))}},cA=class extends Mn{async _call(e){return new Je(await super._call(e))}},O_=class extends P{},uA=class extends O_{},Ji=class extends P{},dA=class extends Ji{},fA=class extends Ji{},Ki=class extends P{},hA=class extends Ki{},pA=class extends Ki{async _call(e){return new se(await super._call(e))}},xn=class extends P{},_A=class extends xn{},mA=class extends xn{async _call(e){return new Je(await super._call(e))}},gA=class extends xn{async _call(e){return new se(await super._call(e))}},wA=class extends xn{async _call(e){return new Qe(await super._call(e))}},vA=class extends xn{async _call(e){return new ot(await super._call(e))}},Zi=class extends P{},yA=class extends Zi{},bA=class extends Zi{},os=class extends P{},MA=class extends os{},xA=class extends os{async _call(e){return new Je(await super._call(e))}},TA=class extends os{async _call(e){return new se(await super._call(e))}},kA=class extends os{async _call(e){return new Qe(await super._call(e))}},el=class extends P{},EA=class extends el{},AA=class extends el{},tl=class extends P{},CA=class extends tl{},SA=class extends tl{},rl=class extends P{},PA=class extends rl{},FA=class extends rl{},nl=class extends P{},IA=class extends nl{},LA=class extends nl{async _call(e){return new se(await super._call(e))}},N_=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"},OA=class extends N_{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:r,attention_mask:n}){return{inputs_embeds:De([t,e],1),attention_mask:De([At(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:d}=await xr(this,{inputs_embeds:i,attention_mask:r});a=d}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)}},sl=class extends P{},NA=class extends sl{},DA=class extends sl{},al=class extends P{},zA=class extends al{},BA=class extends al{},ol=class extends P{},RA=class extends ol{},$A=class extends ol{},D_=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"]},z_=class extends D_{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:d=null,...h}){if((!o||!i)&&({inputs_embeds:o,per_layer_inputs:i}=await Me(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(r){const{image_features:m}=await Me(this.sessions.vision_encoder,{pixel_values:r});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:m,inputs_embeds:o,input_ids:e,attention_mask:t}))}if(n){const{audio_features:m}=await Me(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:m,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:d},!0)}_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return ns({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 g_({audio_token_id:this.config.audio_token_id,...e,audio_features:r})}},il=class extends P{},GA=class extends il{},UA=class extends il{},ll=class extends P{},VA=class extends ll{},jA=class extends ll{},cl=class extends P{},WA=class extends cl{},qA=class extends cl{},ul=class extends P{},HA=class extends ul{},QA=class extends ul{},dl=class extends P{},XA=class extends dl{},YA=class extends dl{},fl=class extends P{},JA=class extends fl{},KA=class extends fl{},hl=class extends P{},ZA=class extends hl{},eC=class extends hl{},pl=class extends P{},tC=class extends pl{},rC=class extends pl{},_l=class extends P{},nC=class extends _l{},sC=class extends _l{},ml=class extends P{},aC=class extends ml{},oC=class extends ml{},B_=class extends P{},iC=class extends B_{},R_=class extends P{},lC=class extends R_{},gl=class extends P{},cC=class extends gl{},uC=class extends gl{},wl=class extends P{},dC=class extends wl{},fC=class extends wl{async _call(e){return new se(await super._call(e))}},Tr=class extends P{},hC=class extends Tr{},pC=class extends Tr{async _call(e){return new jr(await super._call(e))}},_C=class extends Tr{async _call(e){return new se(await super._call(e))}},mC=class extends Tr{async _call(e){return new Qe(await super._call(e))}},gC=class extends P{},wC=class extends Tr{},vC=class extends Tr{async _call(e){return new jr(await super._call(e))}},yC=class extends Tr{async _call(e){return new se(await super._call(e))}},vl=class extends P{},bC=class extends vl{},MC=class extends vl{},$_=class extends P{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]},G_=class extends $_{async encode_image({pixel_values:e,pixel_attention_mask:t}){return(await Me(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 ns({image_token_id:this.config.image_token_id,...e,image_features:r})}},xC=class extends G_{},yl=class extends P{},TC=class extends yl{},kC=class extends yl{async _call(e){return new se(await super._call(e))}},bl=class extends P{},EC=class extends bl{},AC=class extends bl{},ha=class extends P{},CC=class extends ha{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=At([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}},U_=class extends ha{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},SC=class extends ha{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Ml=class extends P{},PC=class extends Ml{},FC=class extends Ml{},xl=class extends P{},IC=class extends xl{},LC=class extends xl{},Tl=class extends P{},OC=class extends Tl{},NC=class extends Tl{},V_=class extends P{},DC=class extends V_{},j_=class extends P{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},ea=class extends j_{_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return ns({image_token_id:this.config.image_token_index,...e,image_features:r})}},zC=class extends ea{},BC=class extends ea{},kl=class extends P{},RC=class extends kl{},$C=class extends kl{},El=class extends P{},GC=class extends El{},UC=class extends El{},Al=class extends P{},VC=class extends Al{},jC=class extends Al{},Cl=class extends P{},WC=class extends Cl{},qC=class extends Cl{},is=class extends P{},HC=class extends is{},QC=class extends is{},XC=class extends is{async _call(e){return new se(await super._call(e))}},YC=class extends is{},W_=class extends P{},JC=class extends W_{},q_=class extends P{},KC=class extends q_{},H_=class extends He{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]}},Q_=class extends P{},ZC=class extends Q_{async _call(e){return new H_(await super._call(e))}},X_=class extends He{constructor({audio_codes:e}){super(),this.audio_codes=e}},Y_=class extends He{constructor({audio_values:e}){super(),this.audio_values=e}},pa=class extends P{main_input_name="input_values";forward_params=["input_values"]},eS=class extends pa{async encode(e){return new X_(await Me(this.sessions.encoder_model,e))}async decode(e){return new Y_(await Me(this.sessions.decoder_model,e))}},J_=class extends pa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},K_=class extends pa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Sl=class extends P{},tS=class extends Sl{},rS=class extends Sl{},ls=class extends P{},nS=class extends ls{},sS=class extends ls{async _call(e){return new Je(await super._call(e))}},aS=class extends ls{async _call(e){return new se(await super._call(e))}},oS=class extends ls{async _call(e){return new ot(await super._call(e))}},Pl=class extends P{},iS=class extends Pl{},lS=class extends Pl{},_a=class extends P{},cS=class extends _a{},uS=class extends _a{async _call(e){return new se(await super._call(e))}},dS=class extends _a{},ma=class extends P{},fS=class extends ma{},hS=class extends ma{async _call(e){return new se(await super._call(e))}},pS=class extends ma{},ga=class extends P{},_S=class extends ga{},mS=class extends ga{async _call(e){return new se(await super._call(e))}},gS=class extends ga{},wa=class extends P{},wS=class extends wa{},vS=class extends wa{async _call(e){return new se(await super._call(e))}},yS=class extends wa{},Fl=class extends P{},bS=class extends Fl{},MS=class extends Fl{async _call(e){return new se(await super._call(e))}},Il=class extends P{},xS=class extends Il{},TS=class extends Il{async _call(e){return new se(await super._call(e))}},cs=class extends P{},kS=class extends cs{},ES=class extends cs{async _call(e){return new Je(await super._call(e))}},AS=class extends cs{async _call(e){return new se(await super._call(e))}},CS=class extends cs{async _call(e){return new Qe(await super._call(e))}},Ll=class extends P{},SS=class extends Ll{},PS=class extends Ll{},Ol=class extends P{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},FS=class extends Ol{},IS=class extends Ol{},Tn=class extends P{},LS=class extends Tn{},OS=class extends Tn{async _call(e){return new Je(await super._call(e))}},NS=class extends Tn{async _call(e){return new se(await super._call(e))}},DS=class extends Tn{async _call(e){return new Qe(await super._call(e))}},zS=class extends Tn{async _call(e){return new ot(await super._call(e))}},Nl=class extends P{},BS=class extends Nl{},RS=class extends Nl{},Dl=class extends P{},$S=class extends Dl{},GS=class extends Dl{},Z_=class extends P{},US=class extends Z_{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 Me(i,l)}else{const i=this.sessions.gen_img_embeds,l=ht({image_ids:e.input_ids},i.inputNames);r=await Me(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 Me(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=De([t.input_ids,t.input_ids],0):(t.input_ids=De([t.input_ids,Vo(t.input_ids,BigInt(r.pad_token_id))],0),t.attention_mask=De([t.attention_mask,Vo(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 j("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),t.images_emb_mask=new j("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 Me(s,{generated_tokens:n}),o=a.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),i=[];for(const l of o){const u=zt.fromTensor(l);i.push(u)}return i}},zl=class extends P{},VS=class extends zl{},jS=class extends zl{},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,d=Math.floor(l/r)%n,h=u-d;h>0&&h<=s&&(e.data[a++]=e.data[l])}const o=Math.floor(t/n),i=a/(o*n);return new j(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)),Zs(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 Me(this.sessions.encodec_decode,{audio_codes:r});return n}},Bl=class extends P{},WS=class extends Bl{},qS=class extends Bl{},kn=class extends P{},HS=class extends kn{},QS=class extends kn{async _call(e){return new Je(await super._call(e))}},XS=class extends kn{async _call(e){return new se(await super._call(e))}},YS=class extends kn{async _call(e){return new Qe(await super._call(e))}},JS=class extends kn{async _call(e){return new ot(await super._call(e))}},tm=class extends P{},KS=class extends tm{},Rl=class extends P{},ZS=class extends Rl{},eP=class extends Rl{},$l=class extends P{},tP=class extends $l{},rP=class extends $l{},Gl=class extends P{},nP=class extends Gl{},sP=class extends Gl{},Ul=class extends P{},aP=class extends Ul{},oP=class extends Ul{},Vl=class extends P{},iP=class extends Vl{},lP=class extends Vl{},jl=class extends P{},cP=class extends jl{},uP=class extends jl{},Wl=class extends P{},dP=class extends Wl{},fP=class extends Wl{},rm=class extends P{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},hP=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 ns({image_token_id:this.config.image_token_index,...e,image_features:r})}},nm=class extends P{},pP=class extends nm{async _call(e){return new jr(await super._call(e))}},ql=class extends P{},_P=class extends ql{},mP=class extends ql{},Hl=class extends P{},gP=class extends Hl{},wP=class extends Hl{},Ql=class extends P{},vP=class extends Ql{},yP=class extends Ql{},Xl=class extends P{},bP=class extends Xl{},MP=class extends Xl{},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 h;if(r&&e.dims[1]!==1){if(!n)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:h}=await Me(this.sessions.vision_encoder,{pixel_values:r,image_sizes:n}))}else{const p=this.config.normalized_config.hidden_size;h=new j("float32",[],[0,p])}({inputs_embeds:a}=await Me(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:h}))}return await ar(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,position_ids:s,generation_config:i,logits_processor:l},!1)}},Yl=class extends P{},xP=class extends Yl{},TP=class extends Yl{async _call(e){return new se(await super._call(e))}},Jl=class extends P{},kP=class extends Jl{},EP=class extends Jl{async _call(e){return new Qe(await super._call(e))}},Kl=class extends P{},AP=class extends Kl{},CP=class extends Kl{},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 d=e.tolist();n||(n=Mp(e));const h=n.tolist(),p=Array.from({length:3},M=>Array.from({length:e.dims[0]},k=>Array.from({length:e.dims[1]},A=>1))),m=t?t.tolist():[],w=r?r.tolist():[];let v=0,b=0;for(let M=0;M<d.length;++M){const k=d[M].filter((X,F)=>h[M][F]==1),E=k.reduce((X,F,L)=>(F==i&&X.push(L),X),[]).map(X=>k[X+1]),C=E.filter(X=>X==a).length,O=E.filter(X=>X==o).length;let x=[],V=0,G=C,W=O;for(let X=0;X<E.length;++X){const F=k.findIndex((dt,We)=>We>V&&dt==a),L=k.findIndex((dt,We)=>We>V&&dt==o),z=G>0&&F!==-1?F:k.length+1,K=W>0&&L!==-1?L:k.length+1;let le,Te,Se,ut;z<K?([Te,Se,ut]=m[v],++v,--G,le=z):([Te,Se,ut]=w[b],++b,--W,le=K);const[Ue,ze,Ve]=[Number(Te),Math.floor(Number(Se)/l),Math.floor(Number(ut)/l)],be=le-V,he=x.length>0?Ge(x.at(-1))[0]+1:0;x.push(Array.from({length:3*be},(dt,We)=>he+We%be));const je=be+he,_e=Ue*ze*Ve,ve=Array.from({length:_e},(dt,We)=>je+Math.floor(We/(ze*Ve))),cr=Array.from({length:_e},(dt,We)=>je+Math.floor(We/Ve)%ze),kr=Array.from({length:_e},(dt,We)=>je+We%Ve);x.push([ve,cr,kr].flat()),V=le+_e}if(V<k.length){const X=x.length>0?Ge(x.at(-1))[0]+1:0,F=k.length-V;x.push(Array.from({length:3*F},(L,z)=>X+z%F))}const J=x.reduce((X,F)=>X+F.length,0),q=new Array(J);let B=0;for(let X=0;X<3;++X)for(let F=0;F<x.length;++F){const L=x[F],z=L.length/3;for(let K=X*z;K<(X+1)*z;++K)q[B++]=L[K]}let N=0;const U=h[M];for(let X=0;X<U.length;++X)if(U[X]==1){for(let F=0;F<3;++F)p[F][M][X]=q[F*J/3+N];++N}const ee=Ge(q)[0];u.push(ee+1-d[M].length)}return[new j("int64",p.flat(1/0),[3,e.dims[0],e.dims[1]]),new j("int64",u,[u.length,1])]}else if(n){const{data:d,dims:h}=__(n),p=BigInt64Array.from({length:3*d.length},(w,v)=>d[v%d.length]),m=Array.from({length:h[0]},(w,v)=>Ge(d.subarray(h[1]*v,h[1]*(v+1)))[0]+1n+BigInt(h[1]));return[new j("int64",p,[3,...h]),new j("int64",m,[m.length,1])]}else{const[d,h]=e.dims,p=BigInt64Array.from({length:3*d*h},(m,w)=>BigInt(Math.floor(w%h/d)));return[new j("int64",p,[3,...e.dims]),xp([d,1])]}}async encode_image({pixel_values:e,image_grid_thw:t}){return(await Me(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:t})).image_features}_merge_input_ids_with_image_features(e){return ns({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=mn([s,s,s],0)}return t}},lm=class extends im{image_grid_thw_name="image_grid_thw"},Zl=class extends P{},SP=class extends Zl{},PP=class extends Zl{},cm=class extends lm{},um=class extends cm{},FP=class extends um{},ec=class extends P{},IP=class extends ec{},LP=class extends ec{async _call(e){return new se(await super._call(e))}},tc=class extends P{},OP=class extends tc{},NP=class extends tc{async _call(e){return new dm(await super._call(e))}},dm=class extends as{},En=class extends P{},DP=class extends En{},zP=class extends En{async _call(e){return new Je(await super._call(e))}},BP=class extends En{async _call(e){return new se(await super._call(e))}},RP=class extends En{async _call(e){return new Qe(await super._call(e))}},$P=class extends En{async _call(e){return new ot(await super._call(e))}},An=class extends P{},GP=class extends An{},UP=class extends An{async _call(e){return new Je(await super._call(e))}},VP=class extends An{async _call(e){return new se(await super._call(e))}},jP=class extends An{async _call(e){return new Qe(await super._call(e))}},WP=class extends An{async _call(e){return new ot(await super._call(e))}},rc=class extends P{},qP=class extends rc{},HP=class extends rc{async _call(e){return new fm(await super._call(e))}},fm=class extends as{},hm=class extends He{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},pm=class extends P{},QP=class extends pm{async get_image_embeddings({pixel_values:e}){return await xr(this,{pixel_values:e})}async forward(e){!e.image_embeddings||!e.image_positional_embeddings?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_labels??=At(e.input_points.dims.slice(0,-1));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 Me(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new hm(await super._call(e))}},_m=class extends He{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}},mm=class extends P{},nc=class extends mm{async get_image_embeddings({pixel_values:e}){return await xr(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??=At(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 Me(n,s)}async _call(e){return new _m(await super._call(e))}},XP=class extends nc{},YP=class extends nc{},va=class extends P{},JP=class extends va{},KP=class extends va{},ZP=class extends va{},ya=class extends P{},eF=class extends ya{},tF=class extends ya{},rF=class extends ya{},sc=class extends P{},nF=class extends sc{},gm=class extends sc{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},sF=class extends Wr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},ac=class extends P{},aF=class extends ac{},oF=class extends ac{},ba=class extends P{main_input_name="input_values";forward_params=["input_values"]},iF=class extends ba{async encode(e){return await Me(this.sessions.encoder_model,e)}async decode(e){return await Me(this.sessions.decoder_model,e)}},wm=class extends ba{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},vm=class extends ba{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Ma=class extends P{},lF=class extends Ma{},cF=class extends Ma{},uF=class extends Ma{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 xr(this,o),u=i.dims[1]/this.config.reduction_factor,d=Math.floor(u*s),h=Math.floor(u*n),p=this.config.num_mel_bins;let m=[],w=null,v=null,b=0;for(;;){++b;const A=h_(!!v);let E;v?E=v.output_sequence_out:E=new j("float32",new Float32Array(p),[1,1,p]);let C={use_cache_branch:A,output_sequence:E,encoder_attention_mask:l,speaker_embeddings:t,encoder_hidden_states:i};this.addPastKeyValues(C,w),v=await Me(this.sessions.decoder_model_merged,C),w=this.getPastKeyValues(v,w);const{prob:O,spectrum:x}=v;if(m.push(x),b>=h&&(Array.from(O.data).filter(V=>V>=r).length>0||b>=d))break}const M=De(m),{waveform:k}=await Me(a.sessions.model,{spectrogram:M});return{spectrogram:M,waveform:k}}},dF=class extends P{main_input_name="spectrogram"},us=class extends P{},fF=class extends us{},hF=class extends us{async _call(e){return new Je(await super._call(e))}},pF=class extends us{async _call(e){return new se(await super._call(e))}},_F=class extends us{async _call(e){return new ot(await super._call(e))}},oc=class extends P{},mF=class extends oc{},gF=class extends oc{},ic=class extends P{},wF=class extends ic{},vF=class extends ic{},ym=class extends P{},yF=class extends ym{},bm=class extends P{},Mm=class extends bm{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:d}=await Me(this.sessions.text_encoder,{input_ids:e,attention_mask:t,style:r}),h=d.div(s).mul_(a),p=i*o,m=h.data,w=Int32Array.from(m,G=>Math.ceil(G/p)),v=Math.max(...w),b=e.dims[0],M=new BigInt64Array(b*v);for(let G=0;G<b;++G)M.fill(1n,G*v,G*v+w[G]);const k=new j("int64",M,[b,v]),A=l*o,E=A*v;let C=t1([b,A,v]);const O=C.data;for(let G=0;G<b;++G)if(w[G]!==v)for(let W=0;W<A;++W)O.fill(0,G*E+W*v+w[G],G*E+(W+1)*v);const x=at([b],n);for(let G=0;G<n;++G){const W=at([b],G);({denoised_latents:C}=await Me(this.sessions.latent_denoiser,{style:r,noisy_latents:C,latent_mask:k,encoder_outputs:u,attention_mask:t,timestep:W,num_inference_steps:x}))}const{waveform:V}=await Me(this.sessions.voice_decoder,{latents:C});return{waveform:V,durations:h}}},xa=class extends P{},bF=class extends xa{},MF=class extends xa{async _call(e){return new se(await super._call(e))}},xF=class extends xa{},lc=class extends P{},TF=class extends lc{},kF=class extends lc{},cc=class extends P{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]},EF=class extends cc{},AF=class extends cc{},uc=class extends P{},CF=class extends uc{},SF=class extends uc{async _call(e){return new xm(await super._call(e))}},xm=class extends Qi{},Tm=class extends P{},PF=class extends Tm{},km=class extends P{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},Em=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 g_({audio_token_id:this.config.ignore_index??this.config.audio_token_id,...e,audio_features:r})}},FF=class extends Em{},Ta=class extends P{},IF=class extends Ta{},LF=class extends Ta{async _call(e){return new jr(await super._call(e))}},OF=class extends Ta{async _call(e){return new se(await super._call(e))}},ds=class extends P{},NF=class extends ds{},DF=class extends ds{async _call(e){return new jr(await super._call(e))}},zF=class extends ds{async _call(e){return new se(await super._call(e))}},BF=class extends ds{async _call(e){return new Qe(await super._call(e))}},dc=class extends P{},RF=class extends dc{},$F=class extends dc{},GF=class extends P{main_input_name="pixel_values";forward_params=["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"]},fc=class extends P{},UF=class extends fc{},VF=class extends fc{async _call(e){return new se(await super._call(e))}},Am=class extends P{},jF=class extends Am{},hc=class extends P{},WF=class extends hc{},qF=class extends hc{async _call(e){return new se(await super._call(e))}},Cm=class extends P{},HF=class extends Cm{async _call(e){return new sE(await super._call(e))}},Sm=class extends P{},QF=class extends Sm{},Pm=class extends He{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}},Fm=class extends P{},XF=class extends Fm{async _call(e){return new Pm(await super._call(e))}},ka=class extends P{},YF=class extends ka{},JF=class extends ka{async _call(e){return new jr(await super._call(e))}},KF=class extends ka{async _call(e){return new se(await super._call(e))}},Im=class extends He{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},Cn=class extends P{},ZF=class extends Cn{},eI=class extends Cn{async _call(e){return new jr(await super._call(e))}},tI=class extends Cn{async _call(e){return new se(await super._call(e))}},rI=class extends Cn{async _call(e){return new Im(await super._call(e))}},nI=class extends Cn{async _call(e){return new Qe(await super._call(e))}},Lm=class extends P{},sI=class extends Lm{},aI=class extends d_{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},pc=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"]},oI=class extends pc{},Om=class extends pc{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,aI)}_retrieve_init_tokens(e){const t=[e.decoder_start_token_id];let r=e.language;const n=e.task;if(e.is_multilingual){r||(oe.warn("No language specified - defaulting to English (en)."),r="en");const a=`<|${X1(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&&(oe.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 Ho,r.push(new lE(t,a))),t.begin_suppress_tokens&&(r??=new Ho,r.push(new u_(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"&&oe.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&&oe.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&&(oe.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},(w,v)=>De(a.map(b=>b[v]),2)),i=mn(t.map(([w,v])=>{if(w>=o.length)throw new Error(`Layer index ${w} is out of bounds for cross attentions (length ${o.length}).`);return r?o[w].slice(null,v,null,[0,r]):o[w].slice(null,v)})).transpose(1,0,2,3),[l,u]=e1(i,-2,0,!0),d=i.clone();for(let w=0;w<d.dims[0];++w){const v=d[w];for(let b=0;b<v.dims[0];++b){const M=v[b],k=l[w][b][0].data,A=u[w][b][0].data;for(let E=0;E<M.dims[0];++E){let C=M[E].data;for(let O=0;O<C.length;++O)C[O]=(C[O]-A[O])/k[O];C.set(Nx(C,s))}}}const h=[vi(d,1)],p=e.sequences.dims,m=new j("float32",new Float32Array(p[0]*p[1]),p);for(let w=0;w<p[0];++w){const v=h[w].neg().squeeze_(0),[b,M]=zx(v.tolist()),k=Array.from({length:b.length-1},(C,O)=>b[O+1]-b[O]),A=Xt([1],k).map(C=>!!C),E=[];for(let C=0;C<A.length;++C)A[C]&&E.push(M[C]*n);m[w].data.set(E,1)}return m}},iI=class extends Om{},Sn=class extends P{},lI=class extends Sn{},cI=class extends Sn{async _call(e){return new Je(await super._call(e))}},uI=class extends Sn{async _call(e){return new se(await super._call(e))}},dI=class extends Sn{async _call(e){return new Qe(await super._call(e))}},fI=class extends Sn{async _call(e){return new ot(await super._call(e))}},Pn=class extends P{},hI=class extends Pn{},pI=class extends Pn{async _call(e){return new Je(await super._call(e))}},_I=class extends Pn{async _call(e){return new se(await super._call(e))}},mI=class extends Pn{async _call(e){return new Qe(await super._call(e))}},gI=class extends Pn{async _call(e){return new ot(await super._call(e))}},_c=class extends P{},wI=class extends _c{},vI=class extends _c{async _call(e){return new Nm(await super._call(e))}},Nm=class extends He{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},mc=class extends P{},yI=class extends mc{},bI=class extends mc{},MI=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"]]),xI=new Map([["t5","T5Model"],["longt5","LongT5Model"],["mt5","MT5Model"],["bart","BartModel"],["mbart","MBartModel"],["marian","MarianModel"],["whisper","WhisperModel"],["m2m_100","M2M100Model"],["blenderbot","BlenderbotModel"],["blenderbot-small","BlenderbotSmallModel"]]),TI=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),kI=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"]]),Dm=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"]]),zm=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),Bm=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),Rm=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"]]),$m=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"]]),Um=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"]]),EI=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"]]),jm=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"]]),qm=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"]]),Hm=new Map([["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"]]),AI=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),Qm=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"]]),Xm=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),Ym=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),an=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),Jm=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),Km=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),Zm=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),eg=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),tg=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),rg=new Map([["wavlm","WavLMForXVector"]]),ng=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),sg=new Map([["vitmatte","VitMatteForImageMatting"]]),CI=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),ag=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),og=new Map([["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),ig=new Map([["sapiens","SapiensForNormalEstimation"]]),lg=new Map([["vitpose","VitPoseForPoseEstimation"]]),cg=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),ug=[[MI,$.EncoderOnly],[xI,$.EncoderDecoder],[kI,$.DecoderOnlyWithoutHead],[TI,$.AutoEncoder],[Rm,$.EncoderOnly],[$m,$.EncoderOnly],[Gm,$.Seq2Seq],[Dm,$.Seq2Seq],[Um,$.DecoderOnly],[EI,$.MultiModality],[Vm,$.EncoderOnly],[jm,$.EncoderOnly],[Wm,$.Vision2Seq],[qm,$.ImageTextToText],[Hm,$.AudioTextToText],[Qm,$.EncoderOnly],[an,$.EncoderOnly],[Km,$.EncoderOnly],[Jm,$.EncoderOnly],[sg,$.EncoderOnly],[CI,$.EncoderOnly],[ag,$.EncoderOnly],[og,$.EncoderOnly],[ig,$.EncoderOnly],[lg,$.EncoderOnly],[Xm,$.EncoderOnly],[Ym,$.EncoderOnly],[Zm,$.MaskGeneration],[eg,$.EncoderOnly],[tg,$.EncoderOnly],[zm,$.Seq2Seq],[Bm,$.EncoderOnly],[rg,$.EncoderOnly],[ng,$.EncoderOnly],[cg,$.EncoderOnly]];for(const[e,t]of ug)for(const r of e.values()){Mr.set(r,t);const n=Pi[r];un.set(n,r),Si.set(r,n)}var SI=[["MusicgenForConditionalGeneration",em,$.Musicgen],["Phi3VForCausalLM",am,$.Phi3V],["CLIPTextModelWithProjection",x_,$.EncoderOnly],["SiglipTextModel",gm,$.EncoderOnly],["JinaCLIPTextModel",U_,$.EncoderOnly],["ClapTextModelWithProjection",b_,$.EncoderOnly],["ClapAudioModelWithProjection",M_,$.EncoderOnly],["DacEncoderModel",E_,$.EncoderOnly],["DacDecoderModel",A_,$.EncoderOnly],["MimiEncoderModel",J_,$.EncoderOnly],["MimiDecoderModel",K_,$.EncoderOnly],["SnacEncoderModel",wm,$.EncoderOnly],["SnacDecoderModel",vm,$.EncoderOnly],["Gemma3nForConditionalGeneration",z_,$.ImageAudioTextToText],["SupertonicForConditionalGeneration",Mm,$.Supertonic],["ChatterboxModel",v_,$.Chatterbox]];for(const[e,t,r]of SI)Mr.set(e,r),un.set(t,e),Si.set(e,t);var dg=new Map([["modnet",an],["birefnet",an],["isnet",an],["ben",an]]);for(const[e,t]of dg.entries())t.set(e,"PreTrainedModel"),Mr.set(e,$.EncoderOnly),Si.set(e,P);Mr.set("PreTrainedModel",$.EncoderOnly);un.set(P,"PreTrainedModel");var ke={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:Rm,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:$m,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:zm,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:Bm,MODEL_FOR_MASKED_LM_MAPPING_NAMES:Vm,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:jm,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:Qm,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:an,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:Jm,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:Km,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:Xm,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:Ym,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:Zm,MODEL_FOR_CTC_MAPPING_NAMES:eg,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:tg,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:rg,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:ng,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:AI,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:sg,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:ag,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:og,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:ig,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:lg,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:cg,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:qm,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:Hm,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:Gm,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:Dm,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:Um,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:Wm};ME(ke);var Ee=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:d=null,session_options:h={}}={}){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:d,session_options:h};if(p.config=await Ai.from_pretrained(e,p),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const m=p.config.model_type;for(const w of this.MODEL_CLASS_MAPPINGS){let v=w.get(m);if(!v){for(const b of w.values())if(b[0]===m){v=b;break}if(!v)continue}return await Pi[v].from_pretrained(e,p)}if(this.BASE_IF_FAIL)return dg.has(m)||oe.warn(`Unknown model class "${m}", attempting to construct from base class.`),await P.from_pretrained(e,p);throw Error(`Unsupported model type: ${m}`)}},Qn=class extends Ee{static MODEL_CLASS_MAPPINGS=ug.map(e=>e[0]);static BASE_IF_FAIL=!0},$f=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},PI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},Lo=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},FI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},II=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},LI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},OI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},NI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},DI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},zI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},BI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},Gf=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},Uf=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},Vf=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},RI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},$I=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]};(class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]});var GI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_CTC_MAPPING_NAMES]},UI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]};(class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]});(class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]});var VI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]};(class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]});var jI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},WI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]};(class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]});(class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]});var qI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]};(class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]});(class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]});async function Gt(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(t=>zt.read(t)))}async function Yn(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(r=>typeof r=="string"||r instanceof URL?sT(r,t):r instanceof Float64Array?new Float32Array(r):r))}function Xo(e,t){t&&(e=e.map(o=>o|0));const[r,n,s,a]=e;return{xmin:r,ymin:n,xmax:s,ymax:a}}var $e=class extends Ct{constructor({task:e,model:t,tokenizer:r=null,processor:n=null}){super(),this.task=e,this.model=t,this.tokenizer=r,this.processor=n}async dispose(){await this.model.dispose()}},HI=class extends $e{async _call(e,{top_k:t=1}={}){const r=this.tokenizer(e,{padding:!0,truncation:!0}),n=await this.model(r),{problem_type:s,id2label:a}=this.model.config,o=s==="multi_label_classification"?l=>l.sigmoid():l=>new j("float32",tt(l.data),l.dims),i=[];for(const l of n.logits){const u=o(l),d=await _n(u,t),h=d[0].tolist(),m=d[1].tolist().map((w,v)=>({label:a?a[w]:`LABEL_${w}`,score:h[v]}));t===1?i.push(...m):i.push(m)}return Array.isArray(e)||t===1?i:i[0]}},QI=class extends $e{async _call(e,{ignore_labels:t=["O"]}={}){const r=Array.isArray(e),n=this.tokenizer(r?e:[e],{padding:!0,truncation:!0}),a=(await this.model(n)).logits,o=this.model.config.id2label,i=[];for(let l=0;l<a.dims[0];++l){const u=n.input_ids[l],d=a[l],h=[];for(let p=0;p<d.dims[0];++p){const m=d[p],w=Ge(m.data)[1],v=o?o[w]:`LABEL_${w}`;if(t.includes(v))continue;const b=this.tokenizer.decode([u[p].item()],{skip_special_tokens:!0});if(b==="")continue;const M=tt(m.data);h.push({entity:v,score:M[w],index:p,word:b})}i.push(h)}return r?i:i[0]}},XI=class extends $e{async _call(e,t,{top_k:r=1}={}){const n=this.tokenizer(e,{text_pair:t,padding:!0,truncation:!0}),s=Array.isArray(e),{start_logits:a,end_logits:o}=await this.model(n),i=n.input_ids.tolist(),l=n.attention_mask.tolist(),{all_special_ids:u,sep_token_id:d}=this.tokenizer,h=[];for(let p=0;p<a.dims[0];++p){const m=i[p],w=m.findIndex(C=>C==d),v=a[p].tolist(),b=o[p].tolist();for(let C=1;C<v.length;++C)(l[p]==0||C<=w||u.findIndex(O=>O==m[C])!==-1)&&(v[C]=-1/0,b[C]=-1/0);const M=tt(v).map((C,O)=>[C,O]),k=tt(b).map((C,O)=>[C,O]);M[0][0]=0,k[0][0]=0;const A=fb(M,k).filter(C=>C[0][1]<=C[1][1]).map(C=>[C[0][1],C[1][1],C[0][0]*C[1][0]]).sort((C,O)=>O[2]-C[2]),E=[];for(let C=0;C<Math.min(A.length,r);++C){const[O,x,V]=A[C],G=m.slice(O,x+1),W=this.tokenizer.decode(G,{skip_special_tokens:!0});E.push({answer:W,score:V})}r===1?h.push(...E):h.push(E)}return s?h:h[0]}},YI=class extends $e{async _call(e,{top_k:t=5}={}){const{mask_token_id:r,mask_token:n}=this.tokenizer,s=this.tokenizer(e,{padding:!0,truncation:!0}),{logits:a}=await this.model(s),o=[],i=s.input_ids.tolist();for(let l=0;l<i.length;++l){const u=i[l],d=u.findIndex(v=>v==r);if(d===-1)throw Error(`Mask token (${n}) not found in text.`);const h=a[l][d],p=await _n(new j("float32",tt(h.data),h.dims),t),m=p[0].tolist(),w=p[1].tolist();o.push(w.map((v,b)=>{const M=u.slice();return M[d]=v,{score:m[b],token:Number(v),token_str:this.tokenizer.decode([v]),sequence:this.tokenizer.decode(M,{skip_special_tokens:!0})}}))}return Array.isArray(e)?o:o[0]}},gc=class extends $e{_key="generated_text";async _call(e,t={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(i=>this.model.config.prefix+i));const r=this.model.config.task_specific_params;r&&r[this.task]&&r[this.task].prefix&&(e=e.map(i=>r[this.task].prefix+i));const n=this.tokenizer,s={padding:!0,truncation:!0};let a;this.task==="translation"&&"_build_translation_inputs"in n?a=n._build_translation_inputs(e,s,t):a=n(e,s);const o=await this.model.generate({...a,...t});return n.batch_decode(o,{skip_special_tokens:!0}).map(i=>({[this._key]:i}))}},JI=class extends gc{_key="summary_text"},KI=class extends gc{_key="translation_text"};function jf(e){return Array.isArray(e)&&e.every(t=>"role"in t&&"content"in t)}var ZI=class extends $e{async _call(e,t={}){let r=!1,n=!1,s=t.add_special_tokens??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,a=t.tokenizer_encode_kwargs,o;if(typeof e=="string")o=e=[e];else if(Array.isArray(e)&&e.every(m=>typeof m=="string"))r=!0,o=e;else{if(jf(e))e=[e];else if(Array.isArray(e)&&e.every(jf))r=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");n=!0,o=e.map(m=>this.tokenizer.apply_chat_template(m,{tokenize:!1,add_generation_prompt:!0,...a})),s=!1,a=void 0}const i=n?!1:t.return_full_text??!0;this.tokenizer.padding_side="left";const l=this.tokenizer(o,{add_special_tokens:s,padding:!0,truncation:!0,...a}),u=await this.model.generate({...l,...t}),d=this.tokenizer.batch_decode(u,{skip_special_tokens:!0});let h;!i&&l.input_ids.dims.at(-1)>0&&(h=this.tokenizer.batch_decode(l.input_ids,{skip_special_tokens:!0}).map(m=>m.length));const p=Array.from({length:e.length},m=>[]);for(let m=0;m<d.length;++m){const w=Math.floor(m/u.dims[0]*e.length);h&&(d[m]=d[m].slice(h[w])),p[w].push({generated_text:n?[...e[w],{role:"assistant",content:d[m]}]:d[m]})}return!r&&p.length===1?p[0]:p}},eL=class extends $e{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([t,r])=>[t.toLowerCase(),r])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(oe.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(oe.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:r="This example is {}.",multi_label:n=!1}={}){const s=Array.isArray(e);s||(e=[e]),Array.isArray(t)||(t=[t]);const a=t.map(l=>r.replace("{}",l)),o=n||t.length===1,i=[];for(const l of e){const u=[];for(const p of a){const m=this.tokenizer(l,{text_pair:p,padding:!0,truncation:!0}),w=await this.model(m);o?u.push([w.logits.data[this.contradiction_id],w.logits.data[this.entailment_id]]):u.push(w.logits.data[this.entailment_id])}const h=(o?u.map(p=>tt(p)[1]):tt(u)).map((p,m)=>[p,m]).sort((p,m)=>m[0]-p[0]);i.push({sequence:l,labels:h.map(p=>t[p[1]]),scores:h.map(p=>p[0])})}return s?i:i[0]}},tL=class extends $e{async _call(e,{top_k:t=5}={}){const r=this.processor.feature_extractor.config.sampling_rate,n=await Yn(e,r),s=this.model.config.id2label,a=[];for(const o of n){const i=await this.processor(o),u=(await this.model(i)).logits[0],d=await _n(new j("float32",tt(u.data),u.dims),t),h=d[0].tolist(),m=d[1].tolist().map((w,v)=>({label:s?s[w]:`LABEL_${w}`,score:h[v]}));a.push(m)}return Array.isArray(e)?a:a[0]}},rL=class extends $e{async _call(e,t,{hypothesis_template:r="This is a sound of {}."}={}){const n=!Array.isArray(e);n&&(e=[e]);const s=t.map(u=>r.replace("{}",u)),a=this.tokenizer(s,{padding:!0,truncation:!0}),o=this.processor.feature_extractor.config.sampling_rate,i=await Yn(e,o),l=[];for(const u of i){const d=await this.processor(u),h=await this.model({...a,...d}),p=tt(h.logits_per_audio.data);l.push([...p].map((m,w)=>({score:m,label:t[w]})))}return n?l[0]:l}},nL=class extends $e{async _call(e,t={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(e,t);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(e,t);case"moonshine":return this._call_moonshine(e,t);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t){t.language&&oe.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&oe.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const r=!Array.isArray(e),n=r?[e]:e,s=this.processor.feature_extractor.config.sampling_rate,a=await Yn(n,s),o=[];for(const i of a){const l=await this.processor(i),d=(await this.model(l)).logits[0],h=[];for(const m of d)h.push(Ge(m.data)[1]);const p=this.tokenizer.decode(h,{skip_special_tokens:!0}).trim();o.push({text:p})}return r?o[0]:o}async _call_whisper(e,t){const r=t.return_timestamps??!1,n=t.chunk_length_s??0,s=t.force_full_sequences??!1;let a=t.stride_length_s??null;const o={...t};r==="word"&&(o.return_token_timestamps=!0,o.return_timestamps=!1);const i=!Array.isArray(e),l=i?[e]:e,u=this.processor.feature_extractor.config,d=u.chunk_length/this.model.config.max_source_positions,h=u.hop_length,p=u.sampling_rate,m=await Yn(l,p),w=[];for(const v of m){let b=[];if(n>0){if(a===null)a=n/6;else if(n<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const A=p*n,E=p*a,C=A-2*E;let O=0;for(;;){const x=O+A,V=v.subarray(O,x),G=await this.processor(V),W=O===0,J=x>=v.length;if(b.push({stride:[V.length,W?0:E,J?0:E],input_features:G.input_features,is_last:J}),J)break;O+=C}}else b=[{stride:[v.length,0,0],input_features:(await this.processor(v)).input_features,is_last:!0}];for(const A of b){o.num_frames=Math.floor(A.stride[0]/h);const E=await this.model.generate({inputs:A.input_features,...o});r==="word"?(A.tokens=E.sequences.tolist()[0],A.token_timestamps=E.token_timestamps.tolist()[0].map(C=>qn(C,2))):A.tokens=E[0].tolist(),A.stride=A.stride.map(C=>C/p)}const[M,k]=this.tokenizer._decode_asr(b,{time_precision:d,return_timestamps:r,force_full_sequences:s});w.push({text:M,...k})}return i?w[0]:w}async _call_moonshine(e,t){const r=!Array.isArray(e),n=r?[e]:e,s=this.processor.feature_extractor.config.sampling_rate,a=await Yn(n,s),o=[];for(const i of a){const l=await this.processor(i),u=Math.floor(i.length/s)*6,d=await this.model.generate({max_new_tokens:u,...t,...l}),h=this.processor.batch_decode(d,{skip_special_tokens:!0})[0];o.push({text:h})}return r?o[0]:o}},sL=class extends $e{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e),this.vocoder=e.vocoder??null}async _prepare_speaker_embeddings(e,t){if((typeof e=="string"||e instanceof URL)&&(e=new Float32Array(await(await ye.fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new j("float32",e,[e.length]);else if(!(e instanceof j))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(t>1){if(e.dims[0]===1)e=e.repeat(t,1);else if(e.dims[0]!==t)throw new Error(`Expected speaker embeddings batch size to be 1 or ${t}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,t,r,n=null){const s=t.data,[a,o]=t.dims,i=n?n.data:null,l=[];for(let u=0;u<a;++u){const d=i?Math.min(Math.ceil(i[u]),o):o,h=u*o;l.push(new pT(s.slice(h,h+d),r))}return Array.isArray(e)?l:l[0]}async _call(e,t){return this.processor?this._call_text_to_spectrogram(e,t):this.model.config.model_type==="supertonic"?this._call_supertonic(e,t):this._call_text_to_waveform(e)}async _call_supertonic(e,{speaker_embeddings:t,num_inference_steps:r,speed:n}){if(!t)throw new Error("Speaker embeddings must be provided for Supertonic models.");const{sampling_rate:s,style_dim:a}=this.model.config,o=this.tokenizer(e,{padding:!0,truncation:!0}),i=o.input_ids.dims[0];t=await this._prepare_speaker_embeddings(t,i),t=t.view(i,-1,a);const{waveform:l,durations:u}=await this.model.generate_speech({...o,style:t,num_inference_steps:r,speed:n});return this._postprocess_waveform(e,l,s,u)}async _call_text_to_waveform(e){const t=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:r}=await this.model(t),n=this.model.config.sampling_rate;return this._postprocess_waveform(e,r,n)}async _call_text_to_spectrogram(e,{speaker_embeddings:t}){this.vocoder||(oe.info("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await Qn.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"}));const{input_ids:r}=this.tokenizer(e,{padding:!0,truncation:!0}),n=r.dims[0];t=await this._prepare_speaker_embeddings(t,n),t=t.view(n,-1);const{waveform:s}=await this.model.generate_speech(r,t,{vocoder:this.vocoder}),a=this.processor.feature_extractor.config.sampling_rate;return this._postprocess_waveform(e,s,a)}},aL=class extends $e{async _call(e,t={}){const r=Array.isArray(e),n=await Gt(e),{pixel_values:s}=await this.processor(n),a=[];for(const o of s){o.dims=[1,...o.dims];const i=await this.model.generate({inputs:o,...t}),l=this.tokenizer.batch_decode(i,{skip_special_tokens:!0}).map(u=>({generated_text:u.trim()}));a.push(l)}return r?a:a[0]}},oL=class extends $e{async _call(e,{top_k:t=5}={}){const r=await Gt(e),{pixel_values:n}=await this.processor(r),s=await this.model({pixel_values:n}),{id2label:a}=this.model.config,o=[];for(const i of s.logits){const l=await _n(new j("float32",tt(i.data),i.dims),t),u=l[0].tolist(),h=l[1].tolist().map((p,m)=>({label:a?a[p]:`LABEL_${p}`,score:u[m]}));o.push(h)}return Array.isArray(e)?o:o[0]}},Wf={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},fg=class extends $e{async _call(e,{threshold:t=.5,mask_threshold:r=.5,overlap_mask_area_threshold:n=.8,label_ids_to_fuse:s=null,target_sizes:a=null,subtask:o=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const l=await Gt(e),u=l.map(M=>[M.height,M.width]),d=await this.processor(l),{inputNames:h,outputNames:p}=this.model.sessions.model;if(!h.includes("pixel_values")){if(h.length!==1)throw Error(`Expected a single input name, but got ${h.length} inputs: ${h}.`);const M=h[0];if(M in d)throw Error(`Input name ${M} already exists in the inputs.`);d[M]=d.pixel_values}const m=await this.model(d);let w=null;if(o!==null)w=Wf[o];else if(this.processor.image_processor){for(const[M,k]of Object.entries(Wf))if(k in this.processor.image_processor){w=this.processor.image_processor[k].bind(this.processor.image_processor),o=M;break}}const v=this.model.config.id2label,b=[];if(o)if(o==="panoptic"||o==="instance"){const M=w(m,t,r,n,s,a??u)[0],k=M.segmentation;for(const A of M.segments_info){const E=new Uint8ClampedArray(k.data.length);for(let O=0;O<k.data.length;++O)k.data[O]===A.id&&(E[O]=255);const C=new zt(E,k.dims[1],k.dims[0],1);b.push({score:A.score,label:v[A.label_id],mask:C})}}else if(o==="semantic"){const{segmentation:M,labels:k}=w(m,a??u)[0];for(const A of k){const E=new Uint8ClampedArray(M.data.length);for(let O=0;O<M.data.length;++O)M.data[O]===A&&(E[O]=255);const C=new zt(E,M.dims[1],M.dims[0],1);b.push({score:null,label:v[A],mask:C})}}else throw Error(`Subtask ${o} not supported.`);else{const k=m[p[0]];for(let A=0;A<u.length;++A){const E=u[A],C=k[A];C.data.some(x=>x<-1e-5||x>1+1e-5)&&C.sigmoid_();const O=await zt.fromTensor(C.mul_(255).to("uint8")).resize(E[1],E[0]);b.push({label:null,score:null,mask:O})}}return b}},iL=class extends fg{async _call(e,t={}){const r=await Gt(e),n=await super._call(e,t),s=r.map((a,o)=>{const i=a.clone();return i.putAlpha(n[o].mask),i});return Array.isArray(e)?s:s[0]}},lL=class extends $e{async _call(e,t,{hypothesis_template:r="This is a photo of {}"}={}){const n=Array.isArray(e),s=await Gt(e),a=t.map(h=>r.replace("{}",h)),o=this.tokenizer(a,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:i}=await this.processor(s),l=await this.model({...o,pixel_values:i}),u=this.model.config.model_type==="siglip"?h=>h.sigmoid().data:h=>tt(h.data),d=[];for(const h of l.logits_per_image){const m=[...u(h)].map((w,v)=>({score:w,label:t[v]}));m.sort((w,v)=>v.score-w.score),d.push(m)}return n?d:d[0]}},cL=class extends $e{async _call(e,{threshold:t=.9,percentage:r=!1}={}){const n=Array.isArray(e);if(n&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const s=await Gt(e),a=r?null:s.map(p=>[p.height,p.width]),{pixel_values:o,pixel_mask:i}=await this.processor(s),l=await this.model({pixel_values:o,pixel_mask:i}),u=this.processor.image_processor.post_process_object_detection(l,t,a),{id2label:d}=this.model.config,h=u.map(p=>p.boxes.map((m,w)=>({score:p.scores[w],label:d[p.classes[w]],box:Xo(m,!r)})));return n?h:h[0]}},uL=class extends $e{async _call(e,t,{threshold:r=.1,top_k:n=null,percentage:s=!1}={}){const a=Array.isArray(e),o=await Gt(e),i=this.tokenizer(t,{padding:!0,truncation:!0}),l=await this.processor(o),u=[];for(let d=0;d<o.length;++d){const h=o[d],p=s?null:[[h.height,h.width]],m=l.pixel_values[d].unsqueeze_(0),w=await this.model({...i,pixel_values:m});let v;if("post_process_grounded_object_detection"in this.processor){const b=this.processor.post_process_grounded_object_detection(w,i.input_ids,{box_threshold:r,text_threshold:r,target_sizes:p})[0];v=b.boxes.map((M,k)=>({score:b.scores[k],label:b.labels[k],box:Xo(M,!s)}))}else{const b=this.processor.image_processor.post_process_object_detection(w,r,p,!0)[0];v=b.boxes.map((M,k)=>({score:b.scores[k],label:t[b.classes[k]],box:Xo(M,!s)}))}v.sort((b,M)=>M.score-b.score),n!==null&&(v=v.slice(0,n)),u.push(v)}return a?u:u[0]}},dL=class extends $e{async _call(e,t,r={}){if(Array.isArray(e)){if(e.length!==1)throw Error("Document Question Answering pipeline currently only supports a batch size of 1.");e=e[0]}const n=(await Gt(e))[0],{pixel_values:s}=await this.processor(n),a=`<s_docvqa><s_question>${t}</s_question><s_answer>`,o=this.tokenizer(a,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,i=await this.model.generate({inputs:s,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:o,...r}),u=this.tokenizer.batch_decode(i)[0].match(/<s_answer>(.*?)<\/s_answer>/);let d=null;return u&&u.length>=2&&(d=u[1].trim()),[{answer:d}]}},fL=class extends $e{async _call(e){const t=await Gt(e),r=await this.processor(t),n=await this.model(r),s=[];for(const a of n.reconstruction){const o=a.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");s.push(zt.fromTensor(o))}return Array.isArray(e)?s:s[0]}},hL=class extends $e{async _call(e){const t=await Gt(e),r=await this.processor(t),{predicted_depth:n}=await this.model(r),s=[];for(let a=0;a<t.length;++a){const o=n[a],[i,l]=o.dims.slice(-2),[u,d]=t[a].size,h=(await yr(o.view(1,1,i,l),{size:[d,u],mode:"bilinear"})).view(d,u),p=h.min().item(),m=h.max().item(),w=h.sub(p).div_(m-p).mul_(255).to("uint8").unsqueeze(0),v=zt.fromTensor(w);s.push({predicted_depth:h,depth:v})}return Array.isArray(e)?s:s[0]}},pL=class extends $e{async _call(e,{pooling:t="none",normalize:r=!1,quantize:n=!1,precision:s="binary"}={}){const a=this.tokenizer(e,{padding:!0,truncation:!0}),o=await this.model(a);let i=o.last_hidden_state??o.logits??o.token_embeddings;switch(t){case"none":break;case"mean":i=Zx(i,a.attention_mask);break;case"first_token":case"cls":i=i.slice(null,0);break;case"last_token":case"eos":i=i.slice(null,-1);break;default:throw Error(`Pooling method '${t}' not supported.`)}return r&&(i=i.normalize(2,-1)),n&&(i=r1(i,s)),i}},_L=class extends $e{async _call(e,{pool:t=null}={}){const r=await Gt(e),{pixel_values:n}=await this.processor(r),s=await this.model({pixel_values:n});let a;if(t){if(!("pooler_output"in s))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");a=s.pooler_output}else a=s.last_hidden_state??s.logits??s.image_embeds;return a}},ta=Object.freeze({"text-classification":{tokenizer:ce,pipeline:HI,model:$f,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:ce,pipeline:QI,model:PI,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:ce,pipeline:XI,model:DI,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:ce,pipeline:YI,model:NI,default:{model:"onnx-community/ettin-encoder-32m-ONNX",dtype:"fp32"},type:"text"},summarization:{tokenizer:ce,pipeline:JI,model:Lo,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:ce,pipeline:KI,model:Lo,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:ce,pipeline:gc,model:Lo,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:ce,pipeline:ZI,model:OI,default:{model:"onnx-community/Qwen3-0.6B-ONNX",dtype:"q4"},type:"text"},"zero-shot-classification":{tokenizer:ce,pipeline:eL,model:$f,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:tL,model:UI,processor:ct,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:ce,pipeline:rL,model:Qn,processor:ct,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:ce,pipeline:nL,model:[FI,GI],processor:ct,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:ce,pipeline:sL,model:[LI,II],processor:[ct,null],default:{model:"onnx-community/Supertonic-TTS-ONNX",dtype:"fp32"},type:"text"},"image-to-text":{tokenizer:ce,pipeline:aL,model:zI,processor:ct,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:oL,model:BI,processor:ct,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:fg,model:[Gf,Uf,Vf],processor:ct,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:iL,model:[Gf,Uf,Vf],processor:ct,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:ce,pipeline:lL,model:Qn,processor:ct,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:cL,model:RI,processor:ct,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:ce,pipeline:uL,model:$I,processor:ct,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:ce,pipeline:dL,model:VI,processor:ct,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:fL,model:jI,processor:ct,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:hL,model:WI,processor:ct,default:{model:"onnx-community/depth-anything-v2-small"},type:"image"},"feature-extraction":{tokenizer:ce,pipeline:pL,model:Qn,default:{model:"onnx-community/all-MiniLM-L6-v2-ONNX",dtype:"fp32"},type:"text"},"image-feature-extraction":{processor:ct,pipeline:_L,model:[qI,Qn],default:{model:"onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX",dtype:"fp32"},type:"image"}}),hg=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function mL(e,{config:t=null,dtype:r=null,device:n=null,model_file_name:s=null}={}){t=await Ai.from_pretrained(e,{config:t});const a=["config.json"],o=t["transformers.js_config"]??{},i=o.use_external_data_format,l="onnx",u=n??o.device;let d=r??o.dtype,h;const p=t.architectures||[];let m=!1;for(const b of p){const M=Mr.get(b);if(M!==void 0){h=M,m=!0;break}}if(!m&&t.model_type){const b=Mr.get(t.model_type);b!==void 0&&(h=b,m=!0)}if(!m){const b=p.length>0?p.join(", "):"(none)";oe.warn(`[get_model_files] Architecture(s) not found in MODEL_TYPE_MAPPING: [${b}] for model type '${t.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${oa}`),h=$.EncoderOnly}const w=(b,M=null)=>{M=M??b;const k=mp(u,b),A=gp(d,b,k),E=Uo[A]??"",C=`${M}${E}.onnx`,O=`${l}/${C}`;a.push(O);const x=i_(i,C,b);for(const V of l_(C,x)){const G=`${l}/${V}`;a.push(G)}},v=s??"model";return h===$.DecoderOnly?(w("model",v),a.push("generation_config.json")):h===$.DecoderOnlyWithoutHead?w("model",v):h===$.Seq2Seq||h===$.Vision2Seq?(w("model","encoder_model"),w("decoder_model_merged"),a.push("generation_config.json")):h===$.MaskGeneration?(w("model","vision_encoder"),w("prompt_encoder_mask_decoder")):h===$.EncoderDecoder?(w("model","encoder_model"),w("decoder_model_merged")):h===$.ImageTextToText?(w("embed_tokens"),w("vision_encoder"),w("decoder_model_merged"),t.is_encoder_decoder&&w("model","encoder_model"),a.push("generation_config.json")):h===$.AudioTextToText?(w("embed_tokens"),w("audio_encoder"),w("decoder_model_merged"),a.push("generation_config.json")):h===$.ImageAudioTextToText?(w("embed_tokens"),w("audio_encoder"),w("vision_encoder"),w("decoder_model_merged"),a.push("generation_config.json")):h===$.Musicgen?(w("model","text_encoder"),w("decoder_model_merged"),w("encodec_decode"),a.push("generation_config.json")):h===$.MultiModality?(w("prepare_inputs_embeds"),w("model","language_model"),w("lm_head"),w("gen_head"),w("gen_img_embeds"),w("image_decode"),a.push("generation_config.json")):h===$.Phi3V?(w("prepare_inputs_embeds"),w("model"),w("vision_encoder"),a.push("generation_config.json")):h===$.Chatterbox?(w("embed_tokens"),w("speech_encoder"),w("model","language_model"),w("conditional_decoder"),a.push("generation_config.json")):h===$.AutoEncoder?(w("encoder_model"),w("decoder_model")):h===$.Supertonic?(w("text_encoder"),w("latent_denoiser"),w("voice_decoder")):w("model",v),a}async function gL(e){if(!e)throw new Error("modelId is required");return(await aa(e,Zn,{})).exists?[Zn]:[]}async function wL(e,{config:t=null,dtype:r=null,device:n=null,model_file_name:s=null,include_tokenizer:a=!0,include_processor:o=!0}={}){const i=await mL(e,{config:t,dtype:r,device:n,model_file_name:s});if(a){const l=await kp(e);i.push(...l)}if(o){const l=await gL(e);i.push(...l)}return i}function vL(e){const t=ta[e];return t?{tokenizer:!!t.tokenizer,processor:!!t.processor}:null}async function yL(e,t,r={}){e=hg[e]??e;const n=vL(e);if(!n)throw new Error(`Unsupported pipeline task: ${e}. Must be one of [${Object.keys(ta).join(", ")}]`);return wL(t,{...r,include_tokenizer:n.tokenizer,include_processor:n.processor})}async function bL(e,t=null,{progress_callback:r=null,config:n=null,cache_dir:s=null,local_files_only:a=!1,revision:o="main",device:i=null,dtype:l=null,subfolder:u="onnx",use_external_data_format:d=null,model_file_name:h=null,session_options:p={}}={}){e=hg[e]??e;const m=ta[e.split("_",1)[0]];if(!m)throw Error(`Unsupported pipeline: ${e}. Must be one of [${Object.keys(ta)}]`);t||(t=m.default.model,oe.info(`No model specified. Using default model: "${t}".`),!l&&m.default.dtype&&(l=m.default.dtype));let w={};if(r){const A=await yL(e,t,{device:i,dtype:l});(await Promise.all(A.map(async C=>aa(t,C)))).forEach((C,O)=>{C.exists&&(w[A[O]]={loaded:0,total:C.size??0})})}const v={progress_callback:r?A=>{if(A.status==="progress"){w[A.file]={loaded:A.loaded,total:A.total};const E=Object.values(w).reduce((x,V)=>x+V.loaded,0),C=Object.values(w).reduce((x,V)=>x+V.total,0),O=C>0?E/C*100:0;r({status:"progress_total",name:A.name,progress:O,loaded:E,total:C,files:structuredClone(w)})}r(A)}:void 0,config:n,cache_dir:s,local_files_only:a,revision:o,device:i,dtype:l,subfolder:u,use_external_data_format:d,model_file_name:h,session_options:p},b=new Map([["tokenizer",m.tokenizer],["model",m.model],["processor",m.processor]]),M=await ML(b,t,v);M.task=e,Dr(r,{status:"ready",task:e,model:t});const k=m.pipeline;return new k(M)}async function ML(e,t,r){const n=Object.create(null),s=[];for(const[a,o]of e.entries()){if(!o)continue;let i;Array.isArray(o)?i=new Promise(async(l,u)=>{let d;for(const h of o){if(h===null){l(null);return}try{l(await h.from_pretrained(t,r));return}catch(p){if(p.message?.includes("Unsupported model type"))d=p;else if(p.message?.includes("Could not locate file"))d=p;else{u(p);return}}}u(d)}):i=o.from_pretrained(t,r),n[a]=i,s.push(i)}await Promise.all(s);for(const[a,o]of Object.entries(n))n[a]=await o;return n}Ie.IS_PROCESS_AVAILABLE;const xL=16e3;self.postMessage({type:"loading",message:"Loading speech recognition model..."});const TL="webgpu",pg=await bL("automatic-speech-recognition","onnx-community/whisper-large-v3-turbo",{device:TL,dtype:{encoder_model:"fp16",decoder_model_merged:"q4"}}).catch(e=>{throw self.postMessage({type:"error",error:e.message||String(e)}),e});await pg(new Float32Array(xL));self.postMessage({type:"ready"});self.onmessage=async e=>{if(e.data.type==="transcribe")try{self.postMessage({type:"transcribing"});const{text:t}=await pg(e.data.audio),r=t.trim();r&&r!=="[BLANK_AUDIO]"?self.postMessage({type:"transcription",text:r}):self.postMessage({type:"transcription",text:""})}catch(t){self.postMessage({type:"error",error:t.message||String(t)})}};