otherwise-cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +193 -0
  2. package/bin/otherwise.js +5 -0
  3. package/frontend/404.html +84 -0
  4. package/frontend/assets/OpenDyslexic3-Bold-CDyRs55Y.ttf +0 -0
  5. package/frontend/assets/OpenDyslexic3-Regular-CIBXa4WE.ttf +0 -0
  6. package/frontend/assets/__vite-browser-external-BIHI7g3E.js +1 -0
  7. package/frontend/assets/conversational-worker-CeKiciGk.js +2929 -0
  8. package/frontend/assets/dictation-worker-D0aYfq8b.js +29 -0
  9. package/frontend/assets/gemini-color-CgSQmmva.png +0 -0
  10. package/frontend/assets/index-BLux5ps4.js +21 -0
  11. package/frontend/assets/index-Blh8_TEM.js +5272 -0
  12. package/frontend/assets/index-BpQ1PuKu.js +18 -0
  13. package/frontend/assets/index-Df737c8w.css +1 -0
  14. package/frontend/assets/index-xaYHL6wb.js +113 -0
  15. package/frontend/assets/ort-wasm-simd-threaded.asyncify-BynIiDiv.wasm +0 -0
  16. package/frontend/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm +0 -0
  17. package/frontend/assets/transformers-tULNc5V3.js +31 -0
  18. package/frontend/assets/tts-worker-DPJWqT7N.js +2899 -0
  19. package/frontend/assets/voice-mode-worker-GzvIE_uh.js +2927 -0
  20. package/frontend/assets/worker-2d5ABSLU.js +31 -0
  21. package/frontend/banner.png +0 -0
  22. package/frontend/favicon.svg +3 -0
  23. package/frontend/google55e5ec47ee14a5f8.html +1 -0
  24. package/frontend/index.html +234 -0
  25. package/frontend/manifest.json +17 -0
  26. package/frontend/pdf.worker.min.mjs +21 -0
  27. package/frontend/robots.txt +5 -0
  28. package/frontend/sitemap.xml +27 -0
  29. package/package.json +81 -0
  30. package/src/agent/index.js +1066 -0
  31. package/src/agent/location.js +51 -0
  32. package/src/agent/prompt.js +548 -0
  33. package/src/agent/tools.js +4372 -0
  34. package/src/browser/detect.js +68 -0
  35. package/src/browser/session.js +1109 -0
  36. package/src/config.js +137 -0
  37. package/src/email/client.js +503 -0
  38. package/src/index.js +557 -0
  39. package/src/inference/anthropic.js +113 -0
  40. package/src/inference/google.js +373 -0
  41. package/src/inference/index.js +81 -0
  42. package/src/inference/ollama.js +383 -0
  43. package/src/inference/openai.js +140 -0
  44. package/src/inference/openrouter.js +378 -0
  45. package/src/inference/xai.js +200 -0
  46. package/src/logBridge.js +9 -0
  47. package/src/models.js +146 -0
  48. package/src/remote/client.js +225 -0
  49. package/src/scheduler/cron.js +243 -0
  50. package/src/server.js +3876 -0
  51. package/src/storage/db.js +1135 -0
  52. package/src/storage/supabase.js +364 -0
  53. package/src/tunnel/cloudflare.js +241 -0
  54. package/src/ui/components/App.jsx +687 -0
  55. package/src/ui/components/BrowserSelect.jsx +111 -0
  56. package/src/ui/components/FilePicker.jsx +472 -0
  57. package/src/ui/components/Header.jsx +444 -0
  58. package/src/ui/components/HelpPanel.jsx +173 -0
  59. package/src/ui/components/HistoryPanel.jsx +158 -0
  60. package/src/ui/components/MessageList.jsx +235 -0
  61. package/src/ui/components/ModelSelector.jsx +304 -0
  62. package/src/ui/components/PromptInput.jsx +515 -0
  63. package/src/ui/components/StreamingResponse.jsx +134 -0
  64. package/src/ui/components/ThinkingIndicator.jsx +365 -0
  65. package/src/ui/components/ToolExecution.jsx +714 -0
  66. package/src/ui/components/index.js +82 -0
  67. package/src/ui/context/TerminalContext.jsx +150 -0
  68. package/src/ui/context/index.js +13 -0
  69. package/src/ui/hooks/index.js +16 -0
  70. package/src/ui/hooks/useChatState.js +675 -0
  71. package/src/ui/hooks/useCommands.js +280 -0
  72. package/src/ui/hooks/useFileAttachments.js +216 -0
  73. package/src/ui/hooks/useKeyboardShortcuts.js +173 -0
  74. package/src/ui/hooks/useNotifications.js +185 -0
  75. package/src/ui/hooks/useTerminalSize.js +151 -0
  76. package/src/ui/hooks/useWebSocket.js +273 -0
  77. package/src/ui/index.js +94 -0
  78. package/src/ui/ink-runner.js +22 -0
  79. package/src/ui/utils/formatters.js +424 -0
  80. package/src/ui/utils/index.js +6 -0
  81. package/src/ui/utils/markdown.js +166 -0
@@ -0,0 +1,31 @@
1
+ /*!
2
+ * ONNX Runtime Web v1.25.0-dev.20260228-6e72d31970
3
+ * Copyright (c) Microsoft Corporation. All rights reserved.
4
+ * Licensed under the MIT License.
5
+ */var ni=Object.defineProperty,My=Object.getOwnPropertyDescriptor,xy=Object.getOwnPropertyNames,Ty=Object.prototype.hasOwnProperty,ky=(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)ni(e,r,{get:t[r],enumerable:!0})},Ey=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of xy(t))!Ty.call(e,s)&&s!==r&&ni(e,s,{get:()=>t[s],enumerable:!(n=My(t,s))||n.enumerable});return e},Gs=e=>Ey(ni({},"__esModule",{value:!0}),e),zn,hr,Nr,Sd,Zh,ef=pe(()=>{zn=new Map,hr=[],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=hr.indexOf(e);s!==-1&&hr.splice(s,1);for(let a=0;a<hr.length;a++)if(zn.get(hr[a]).priority<=r){hr.splice(a,0,e);return}hr.push(e)}return}throw new TypeError("not a valid backend")},Sd=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}}},Zh=async e=>{let t=e.executionProviders||[],r=t.map(l=>typeof l=="string"?l:l.name),n=r.length===0?hr:r,s,a=[],o=new Set;for(let l of n){let c=await Sd(l);typeof c=="string"?a.push({name:l,err:c}):(s||(s=c),s===c&&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:c}of a)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=t.filter(l=>o.has(typeof l=="string"?l:l.name));return[s,new Proxy(e,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),Ay=pe(()=>{ef()}),tf,Cy=pe(()=>{tf="1.24.0-dev.20251116-b39e144322"}),lo,Ye,rf=pe(()=>{Cy(),lo="warning",Ye={wasm:{},webgl:{},webgpu:{},versions:{common:tf},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}`);lo=e}},get logLevel(){return lo}},Object.defineProperty(Ye,"logLevel",{enumerable:!0})}),Oe,Sy=pe(()=>{rf(),Oe=Ye}),nf,sf,Py=pe(()=>{nf=(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,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let 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++]-c[0])*l[0],k=(e.data[p++]-c[1])*l[1],A=(e.data[m++]-c[2])*l[2],E=w===-1?255:(e.data[w++]-c[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")},sf=(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,c,d;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?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])*c[0],n.data[w]=(e.data[k++]-d[1])*c[1],n.data[v]=(e.data[A++]-d[2])*c[2],n.data[b]=E===-1?255:(e.data[E++]-d[3])*c[3]}else throw new Error("Can not access image data");return n}}),ks,af,of,lf,cf,uf,Fy=pe(()=>{si(),ks=(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",c=r*n,d=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),h=4,p=0,m=1,w=2,v=3,b=0,M=c,k=c*2,A=-1;i==="RGB"&&(h=3,p=0,m=1,w=2,v=-1),l==="RGBA"?A=c*3:l==="RBG"?(b=0,k=c,M=c*2):l==="BGR"&&(k=0,M=c,b=c*2);for(let E=0;E<c;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])},af=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")},c=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=c(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=c(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=c(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,ks(o,i)}else throw new Error("Can not access image data")}else{if(a)return new Promise((d,h)=>{let p=l(),m=c(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(ks(v.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return ks(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},of=(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})},lf=(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})},cf=(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})},uf=(e,t,r)=>new vt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),Lr,jn,co,df,Iy=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"]]),co=!1,df=()=>{if(!co){co=!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)}}}),hf,ff,Ly=pe(()=>{si(),hf=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},ff=(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,si=pe(()=>{Py(),Fy(),Iy(),Ly(),vt=class{constructor(e,t,r){df();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=hf(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 af(e,t)}static fromTexture(e,t){return of(e,t)}static fromGpuBuffer(e,t){return lf(e,t)}static fromMLTensor(e,t){return cf(e,t)}static fromPinnedBuffer(e,t,r){return uf(e,t,r)}toDataURL(e){return nf(this,e)}toImageData(e){return sf(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 ff(this,e)}}}),Ot,pf=pe(()=>{si(),Ot=vt}),Vs,uo,Rr,$r,wr,vr,_f=pe(()=>{rf(),Vs=(e,t)=>{(typeof Ye.trace>"u"?!Ye.wasm.trace:!Ye.trace)||console.timeStamp(`${e}::ORT::${t}`)},uo=(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}`),Vs("CPU",a);return}r[s].includes("TRACE_FUNC")&&(n=!0)}},Rr=e=>{(typeof Ye.trace>"u"?!Ye.wasm.trace:!Ye.trace)||uo("BEGIN",e)},$r=e=>{(typeof Ye.trace>"u"?!Ye.wasm.trace:!Ye.trace)||uo("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}`)}}),mf,Oy=pe(()=>{ef(),pf(),_f(),mf=class gf{constructor(t){this.handler=t}async run(t,r,n){Rr(),wr("InferenceSession.run");let s={},a={};if(typeof t!="object"||t===null||t instanceof Ot||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 Ot)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 c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);s[c]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,d=Object.getOwnPropertyNames(r);for(let h of this.outputNames)if(d.indexOf(h)!==-1){let p=r[h];(p===null||p instanceof Ot)&&(c=!0,o=!1,s[h]=p)}if(c){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 c of this.inputNames)if(typeof t[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(o)for(let c of this.outputNames)s[c]=null;let i=await this.handler.run(t,s,a),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let d=i[c];d instanceof Ot?l[c]=d:l[c]=new Ot(d.type,d.data,d.dims)}return vr("InferenceSession.run"),$r(),l}async release(){return this.handler.dispose()}static async create(t,r,n,s){Rr(),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 Zh(o),c=await i.createInferenceSessionHandler(a,l);return vr("InferenceSession.create"),$r(),new gf(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),ai,Ny=pe(()=>{Oy(),ai=mf}),Dy=pe(()=>{}),zy=pe(()=>{}),By=pe(()=>{}),Ry=pe(()=>{}),wf={};es(wf,{InferenceSession:()=>ai,TRACE:()=>Vs,TRACE_EVENT_BEGIN:()=>wr,TRACE_EVENT_END:()=>vr,TRACE_FUNC_BEGIN:()=>Rr,TRACE_FUNC_END:()=>$r,Tensor:()=>Ot,env:()=>Oe,registerBackend:()=>Nr});var Gr=pe(()=>{Ay(),Sy(),Ny(),pf(),Dy(),zy(),_f(),By(),Ry()}),oi=pe(()=>{}),vf={};es(vf,{default:()=>yf});var ho,fo,yf,$y=pe(()=>{Nf(),Vr(),ii(),ho="ort-wasm-proxy-worker",fo=globalThis.self?.name===ho,fo&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":li(r.wasm).then(()=>{fi(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;pi(s,n).then(()=>{postMessage({type:t})},a=>{postMessage({type:t,err:a})});break}case"copy-from":{let{buffer:n}=r,s=Ws(n);postMessage({type:t,out:s});break}case"create":{let{model:n,options:s}=r;_i(n,s).then(a=>{postMessage({type:t,out:a})},a=>{postMessage({type:t,err:a})});break}case"release":mi(r),postMessage({type:t});break;case"run":{let{sessionId:n,inputIndices:s,inputs:a,outputIndices:o,options:i}=r;gi(n,s,a,o,new Array(o.length).fill(null),i).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:l},vi([...a,...l]))},l=>{postMessage({type:t,err:l})});break}case"end-profiling":wi(r),postMessage({type:t});break;default:}}catch(n){postMessage({type:t,err:n})}}),yf=fo?null:e=>new Worker(e??gt,{type:"module",name:ho})}),bf={};es(bf,{default:()=>Mf});async function Pd(e={}){var t=e,r=!!globalThis.window,n=!!globalThis.WorkerGlobalScope,s=n&&self.name?.startsWith("em-pthread");t.mountExternalData=(u,f)=>{u.startsWith("./")&&(u=u.substring(2)),(t.Uc||(t.Uc=new Map)).set(u,f)},t.unmountExternalData=()=>{delete t.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,Be:!0}).buffer.constructor;let a=()=>{let u=f=>(..._)=>{let g=jt;return _=f(..._),jt!=g?new Promise((y,T)=>{Va={resolve:y,reject:T}}):_};(()=>{for(let f of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])t[f]=u(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=(u,f)=>{throw f},c=import.meta.url,d="";if(r||n){try{d=new URL(".",c).href}catch{}n&&(i=u=>{var f=new XMLHttpRequest;return f.open("GET",u,!1),f.responseType="arraybuffer",f.send(null),new Uint8Array(f.response)}),o=async u=>{if(O(u))return new Promise((_,g)=>{var y=new XMLHttpRequest;y.open("GET",u,!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(u,{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=u=>u.startsWith("file://");function x(){ur.buffer!=G.buffer&&K()}if(s){let u=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)u(T);self.onmessage=u};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(),Ts()}else if(g==="run"){(function(y){var T=(x(),N)[y+52>>>2>>>0];y=(x(),N)[y+56>>>2>>>0],Ru(T,T-y),te(T)})(_.Nc),eo(_.Nc,0,0,1,0,0),Ec(),Ra(_.Nc),U||(bu(),U=!0);try{kg(_.he,_.Wc)}catch(y){if(y!="unwind")throw y}}else _.target!=="setimmediate"&&(g==="checkMailbox"?U&&ms():g&&(E(`worker: received unknown command ${g}`),E(_)))}catch(y){throw Ou(),y}};var U=!1;self.onunhandledrejection=f=>{throw f.reason||f},self.onmessage=u}var G,W,J,q,B,N,V,ee,X,F,L,z=!1;function K(){var u=ur.buffer;t.HEAP8=G=new Int8Array(u),J=new Int16Array(u),t.HEAPU8=W=new Uint8Array(u),q=new Uint16Array(u),t.HEAP32=B=new Int32Array(u),t.HEAPU32=N=new Uint32Array(u),V=new Float32Array(u),ee=new Float64Array(u),X=new BigInt64Array(u),F=new BigUint64Array(u)}function le(){z=!0,s?b():nr._b()}function Te(u){throw E(u="Aborted("+u+")"),C=!0,u=new WebAssembly.RuntimeError(u+". Build with -sASSERTIONS for more info."),v?.(u),u}function Pe(){return{a:{f:Eg,J:Ag,k:Cg,p:Sg,l:Pg,ta:Fg,b:Ig,ca:Lg,Ka:Ic,s:Og,da:Dc,_a:zc,Ga:Bc,Ia:Rc,$a:$c,Ya:Gc,Ra:Vc,Xa:Uc,pa:jc,Ha:Wc,Yb:qc,Za:Hc,Fa:Qc,eb:Ng,Da:Dg,Tb:zg,Rb:Rg,Ca:Gg,M:Vg,H:Ug,Sb:jg,ka:Jg,Ub:Kg,Ua:Zg,Wb:tw,La:rw,Pb:nw,la:sw,Ta:Ra,bb:aw,U:cw,n:pw,c:za,sb:_w,w:mw,L:gw,z:ww,j:vw,o:ru,tb:yw,G:bw,T:Mw,g:xw,u:Tw,m:kw,i:Ew,Oa:Aw,Pa:Cw,Qa:Sw,Ma:ou,Na:iu,Qb:lu,fb:Fw,db:Lw,Y:Ow,rb:Nw,ma:Dw,cb:Iw,gb:zw,ab:Bw,Xb:Rw,N:Pw,hb:$w,X:Gw,Vb:Vw,ob:Jw,C:Kw,sa:Zw,ra:ev,qb:tv,W:rv,v:nv,nb:sv,mb:av,lb:ov,pb:iv,kb:lv,jb:cv,ib:uv,Va:pu,Wa:_u,Ja:dt,ea:mu,oa:gu,Sa:wu,na:vu,Db:yy,xa:hy,Eb:vy,ya:dy,F:ty,e:Vv,r:$v,x:Rv,D:Kv,Ib:ly,ba:oy,B:jv,za:cy,$:fy,ha:iy,Fb:gy,Gb:my,Ba:ry,Aa:ay,Jb:ny,wa:wy,aa:uy,d:Uv,A:Wv,q:Gv,Cb:by,t:Hv,y:Zv,I:qv,E:Qv,K:ey,S:py,ja:Jv,_:_y,Kb:Yv,Lb:Xv,P:sy,h:hv,a:ur,Ob:cr,Hb:fv,ia:pv,O:_v,qa:mv,Mb:gv,Q:wv,zb:vv,Ab:yv,ua:bv,fa:Mv,R:xv,Ea:Tv,va:kv,Z:Ev,xb:Av,Zb:Cv,V:Sv,Bb:Pv,ub:Fv,vb:Lv,wb:Ov,ga:Nv,yb:Dv,Nb:zv}}}async function ut(){function u(g,y){var T=nr=g.exports;g={};for(let[S,I]of Object.entries(T))typeof I=="function"?(T=ow(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}(),Tc.push(nr.id),yu=(g=nr).$b,bu=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,Qa=t._OrtGetWebGpuDevice=g.Bc,Ms=g.Cc,It=t._free=g.Dc,Jr=t._malloc=g.Ec,Mu=t._wgpuBufferRelease=g.Fc,xu=t._wgpuCreateInstance=g.Gc,Tu=g.Hc,ku=g.Ic,Eu=g.Jc,Au=g.Kc,Cu=g.Lc,Su=g.Pc,Pu=g.Zc,Fu=g._c,Iu=g.$c,Xa=g.bd,Ya=g.cd,Ja=g.dd,Ka=g.ed,On=g.fd,Za=g.gd,Lu=g.hd,eo=g.kd,Ou=g.ld,Nu=g.md,Du=g.nd,to=g.od,zu=g.pd,Bu=g.qd,ro=g.rd,de=g.sd,Nn=g.td,Ru=g.ud,te=g.vd,xs=g.wd,re=g.xd,$u=g.yd,no=g.zd,Gu=g.Ad,Vu=g.Bd,Uu=g.Cd,so=g.Dd,ju=g.Ed,Wu=g.Fd,qu=g.Gd,Hu=g.Hd,Qu=g.Id,Xu=g.Jd,Yu=g.Kd,Ju=g.Ld,Ku=g.Md,Zu=g.Nd,ed=g.Od,td=g.Pd,rd=g.Qd,nd=g.Rd,sd=g.Td,ad=g.Ud,od=g.Vd,id=g.Wd,ld=g.Yd,cd=g.Zd,ud=g._d,dd=g.$d,hd=g.ae,fd=g.be,pd=g.pe,_d=g.qe,md=g.re,gd=g.se,wd=g.te,vd=g.ue,yd=g.ve,bd=g.we,Md=g.xe,xd=g.ye,Td=g.ze,kd=g.Xe,Ed=g.Ye,Ad=g.Ze,Cd=g._e,p=y,nr}var f,_=Pe();return t.instantiateWasm?new Promise(g=>{t.instantiateWasm(_,(y,T)=>{g(u(y,T))})}):s?u(new WebAssembly.Instance(p,Pe()),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)}(_),u(f.instance,f.module))}class Ve{name="ExitStatus";constructor(f){this.message=`Program terminated with exit(${f})`,this.status=f}}var ze=u=>{u.terminate(),u.onmessage=()=>{}},Ue=[],be=0,fe=null,je=u=>{We.length==0&&(Cc(),Ac(We[0]));var f=We.pop();if(!f)return 6;Fn.push(f),Er[u.Nc]=f,f.Nc=u.Nc;var _={Oc:"run",he:u.ge,Wc:u.Wc,Nc:u.Nc};return f.postMessage(_,u.Yc),0},_e=0,ye=(u,f,..._)=>{var g,y=16*_.length,T=re(),S=xs(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 u=Nu(u,0,y,S,f),te(T),u};function cr(u){if(s)return ye(0,1,u);if(m=u,!(0<_e)){for(var f of Fn)ze(f);for(f of We)ze(f);We=[],Fn=[],Er={},C=!0}l(0,new Ve(u))}function kr(u){if(s)return ye(1,0,u);dt(u)}var dt=u=>{if(m=u,s)throw kr(u),"unwind";cr(u)},We=[],Fn=[],Tc=[],Er={},kc=u=>{var f=u.Nc;delete Er[f],We.push(u),Fn.splice(Fn.indexOf(u),1),u.Nc=0,Du(f)};function Ec(){Tc.forEach(u=>u())}var Ac=u=>new Promise(f=>{u.onmessage=y=>{var T=y.data;if(y=T.Oc,T.Vc&&T.Vc!=Ms()){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"?ms():y==="spawnThread"?je(T):y==="cleanupThread"?lt(()=>{kc(Er[T.ie])}):y==="loaded"?(u.loaded=!0,f(u)):T.target==="setimmediate"?u.postMessage(T):y==="uncaughtException"?u.onerror(T.error):y==="callHandler"?t[T.ce](...T.args):y&&E(`worker sent an unknown command ${y}`)},u.onerror=y=>{throw E(`worker sent an error! ${y.filename}:${y.lineno}: ${y.message}`),y};var _,g=[];for(_ of[])t.propertyIsEnumerable(_)&&g.push(_);u.postMessage({Oc:"load",de:g,je:ur,ke:p})});function Cc(){var u=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(u)}var ur,kg=(u,f)=>{_e=0,u=so(u,f),0<_e?m=u:to(u)},ps=[],_s=0,it=u=>-9007199254740992>u||9007199254740992<u?NaN:Number(u);function Eg(u){var f=new La(u>>>=0);return(x(),G)[f.Qc+12>>>0]==0&&(Sc(f,!0),_s--),Pc(f,!1),ps.push(f),Vu(u)}var Hr=0,Ag=()=>{de(0,0);var u=ps.pop();$u(u.Xc),Hr=0};function Sc(u,f){f=f?1:0,(x(),G)[u.Qc+12>>>0]=f}function Pc(u,f){f=f?1:0,(x(),G)[u.Qc+13>>>0]=f}class La{constructor(f){this.Xc=f,this.Qc=f-24}}var Oa=u=>{var f=Hr;if(!f)return Nn(0),0;var _=new La(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 u){if(y===0||y===g)break;if(Gu(y,g,_.Qc+16))return Nn(y),f}return Nn(g),f};function Cg(){return Oa([])}function Sg(u){return Oa([u>>>0])}function Pg(u,f,_,g){return Oa([u>>>0,f>>>0,_>>>0,g>>>0])}var Fg=()=>{var u=ps.pop();u||Te("no exception to throw");var f=u.Xc;throw(x(),G)[u.Qc+13>>>0]==0&&(ps.push(u),Pc(u,!0),Sc(u,!1),_s++),no(f),Hr=f};function Ig(u,f,_){var g=new La(u>>>=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]=_,no(u),_s++,Hr=u}var Lg=()=>_s;function Fc(u,f,_,g){return s?ye(2,1,u,f,_,g):Ic(u,f,_,g)}function Ic(u,f,_,g){if(u>>>=0,f>>>=0,_>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var y=[];return s&&y.length===0?Fc(u,f,_,g):(u={ge:_,Nc:u,Wc:g,Yc:y},s?(u.Oc="spawnThread",postMessage(u,y),0):je(u))}function Og(u){throw Hr||=u>>>0,Hr}var Lc=globalThis.TextDecoder&&new TextDecoder,Oc=(u,f,_,g)=>{if(_=f+_,g)return _;for(;u[f]&&!(f>=_);)++f;return f},Nc=(u,f=0,_,g)=>{if(16<(_=Oc(u,f>>>=0,_,g))-f&&u.buffer&&Lc)return Lc.decode(u.buffer instanceof ArrayBuffer?u.subarray(f,_):u.slice(f,_));for(g="";f<_;){var y=u[f++];if(128&y){var T=63&u[f++];if((224&y)==192)g+=String.fromCharCode((31&y)<<6|T);else{var S=63&u[f++];65536>(y=(240&y)==224?(15&y)<<12|T<<6|S:(7&y)<<18|T<<12|S<<6|63&u[f++])?g+=String.fromCharCode(y):(y-=65536,g+=String.fromCharCode(55296|y>>10,56320|1023&y))}}else g+=String.fromCharCode(y)}return g},Qr=(u,f,_)=>(u>>>=0)?Nc((x(),W),u,f,_):"";function Dc(u,f,_){return s?ye(3,1,u,f,_):0}function zc(u,f){if(s)return ye(4,1,u,f)}function Bc(u,f){if(s)return ye(5,1,u,f)}function Rc(u,f,_){if(s)return ye(6,1,u,f,_)}function $c(u,f,_){return s?ye(7,1,u,f,_):0}function Gc(u,f){if(s)return ye(8,1,u,f)}function Vc(u,f,_){if(s)return ye(9,1,u,f,_)}function Uc(u,f,_,g){if(s)return ye(10,1,u,f,_,g)}function jc(u,f,_,g){if(s)return ye(11,1,u,f,_,g)}function Wc(u,f,_,g){if(s)return ye(12,1,u,f,_,g)}function qc(u){if(s)return ye(13,1,u)}function Hc(u,f){if(s)return ye(14,1,u,f)}function Qc(u,f,_){if(s)return ye(15,1,u,f,_)}var Ng=()=>Te(""),Ut=u=>{u>>>=0;for(var f="";;){var _=(x(),W)[u++>>>0];if(!_)return f;f+=String.fromCharCode(_)}},Na={},Da={},Xr=class extends Error{constructor(u){super(u),this.name="BindingError"}};function Kt(u,f,_={}){return function(g,y,T={}){var S=y.name;if(!g)throw new Xr(`type "${S}" must have a positive integer typeid pointer`);if(Da.hasOwnProperty(g)){if(T.ee)return;throw new Xr(`Cannot register type '${S}' twice`)}Da[g]=y,Na.hasOwnProperty(g)&&(y=Na[g],delete Na[g],y.forEach(I=>I()))}(u,f,_)}var Xc=(u,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}): ${u}`)}};function Dg(u,f,_,g,y){u>>>=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(u,{name:f,Mc:T,Sc:(S,I)=>(typeof I=="number"&&(I=BigInt(I)),I),Rc:Xc(f,_,!g),Tc:null})}function zg(u,f,_,g){Kt(u>>>=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 Yc=[],Ar=[0,1,,1,null,1,!0,1,!1,1];function za(u){9<(u>>>=0)&&--Ar[u+1]==0&&(Ar[u]=void 0,Yc.push(u))}var Mt=u=>{if(!u)throw new Xr(`Cannot use deleted val. handle = ${u}`);return Ar[u]},Ft=u=>{switch(u){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let f=Yc.pop()||Ar.length;return Ar[f]=u,Ar[f+1]=1,f}};function Ba(u){return this.Mc((x(),N)[u>>>2>>>0])}var Bg={name:"emscripten::val",Mc:u=>{var f=Mt(u);return za(u),f},Sc:(u,f)=>Ft(f),Rc:Ba,Tc:null};function Rg(u){return Kt(u>>>0,Bg)}var $g=(u,f)=>{switch(f){case 4:return function(_){return this.Mc((x(),V)[_>>>2>>>0])};case 8:return function(_){return this.Mc((x(),ee)[_>>>3>>>0])};default:throw new TypeError(`invalid float width (${f}): ${u}`)}};function Gg(u,f,_){_>>>=0,Kt(u>>>=0,{name:f=Ut(f>>>0),Mc:g=>g,Sc:(g,y)=>y,Rc:$g(f,_),Tc:null})}function Vg(u,f,_,g,y){u>>>=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(u,{name:f,Mc:T,Sc:(I,R)=>R,Rc:Xc(f,_,g!==0),Tc:null})}function Ug(u,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(u>>>=0,{name:_=Ut(_>>>0),Mc:g,Rc:g},{ee:!0})}var Zt=(u,f,_)=>{var g=(x(),W);if(f>>>=0,0<_){var y=f;_=f+_-1;for(var T=0;T<u.length;++T){var S=u.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,u=f-y}else u=0;return u},er=u=>{for(var f=0,_=0;_<u.length;++_){var g=u.charCodeAt(_);127>=g?f++:2047>=g?f+=2:55296<=g&&57343>=g?(f+=4,++_):f+=3}return f};function jg(u,f){Kt(u>>>=0,{name:f=Ut(f>>>0),Mc(_){var g=(x(),N)[_>>>2>>>0];return g=Qr(_+4,g,!0),It(_),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 Xr("Cannot pass non-string to std::string");var T=y?er(g):g.length,S=Jr(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(It,S),S},Rc:Ba,Tc(_){It(_)}})}var Jc=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,Wg=(u,f,_)=>{if(u>>>=1,16<(f=Oc((x(),q),u,f/2,_))-u&&Jc)return Jc.decode((x(),q).slice(u,f));for(_="";u<f;++u){var g=(x(),q)[u>>>0];_+=String.fromCharCode(g)}return _},qg=(u,f,_)=>{if(_??=2147483647,2>_)return 0;var g=f;_=(_-=2)<2*u.length?_/2:u.length;for(var y=0;y<_;++y){var T=u.charCodeAt(y);(x(),J)[f>>>1>>>0]=T,f+=2}return(x(),J)[f>>>1>>>0]=0,f-g},Hg=u=>2*u.length,Qg=(u,f,_)=>{var g="";u>>>=2;for(var y=0;!(y>=f/4);y++){var T=(x(),N)[u+y>>>0];if(!T&&!_)break;g+=String.fromCodePoint(T)}return g},Xg=(u,f,_)=>{if(f>>>=0,_??=2147483647,4>_)return 0;var g=f;_=g+_-4;for(var y=0;y<u.length;++y){var T=u.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},Yg=u=>{for(var f=0,_=0;_<u.length;++_)65535<u.codePointAt(_)&&_++,f+=4;return f};function Jg(u,f,_){if(u>>>=0,f>>>=0,_=Ut(_>>>=0),f===2)var g=Wg,y=qg,T=Hg;else g=Qg,y=Xg,T=Yg;Kt(u,{name:_,Mc:S=>{var I=(x(),N)[S>>>2>>>0];return I=g(S+4,I*f,!0),It(S),I},Sc:(S,I)=>{if(typeof I!="string")throw new Xr(`Cannot pass non-string to C++ string type ${_}`);var R=T(I),H=Jr(4+R+f);return(x(),N)[H>>>2>>>0]=R/f,y(I,H+4,R+f),S!==null&&S.push(It,H),H},Rc:Ba,Tc(S){It(S)}})}function Kg(u,f){Kt(u>>>=0,{fe:!0,name:f=Ut(f>>>0),Mc:()=>{},Sc:()=>{}})}function Zg(u){eo(u>>>0,!n,1,!r,131072,!1),Ec()}var lt=u=>{if(!C)try{if(u(),!(0<_e))try{s?Ms()&&to(m):dt(m)}catch(f){f instanceof Ve||f=="unwind"||l(0,f)}}catch(f){f instanceof Ve||f=="unwind"||l(0,f)}},ew=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Ra(u){u>>>=0,ew||(Atomics.waitAsync((x(),B),u>>>2,u).value.then(ms),u+=128,Atomics.store((x(),B),u>>>2,1))}var ms=()=>lt(()=>{var u=Ms();u&&(Ra(u),Bu())});function tw(u,f){(u>>>=0)==f>>>0?setTimeout(ms):s?postMessage({Vc:u,Oc:"checkMailbox"}):(u=Er[u])&&u.postMessage({Oc:"checkMailbox"})}var $a=[];function rw(u,f,_,g,y){for(f>>>=0,y>>>=0,$a.length=0,_=y>>>3,g=y+g>>>3;_<g;){var T;T=(x(),X)[_++>>>0]?(x(),X)[_++>>>0]:(x(),ee)[_++>>>0],$a.push(T)}return(f?ao[f]:Bv[u])(...$a)}var nw=()=>{_e=0};function sw(u){u>>>=0,s?postMessage({Oc:"cleanupThread",ie:u}):kc(Er[u])}function aw(u){}var gs=u=>{try{u()}catch(f){Te(f)}};function ow(u){var f=(..._)=>{ws.push(u);try{return u(..._)}finally{C||(ws.pop(),jt&&dr===1&&ws.length===0&&(dr=0,_e+=1,gs(Ed),typeof Fibers<"u"&&Fibers.De()))}};return eu.set(u,f),f}var dr=0,jt=null,Kc=0,ws=[],Ga=new Map,Zc=new Map,eu=new Map,iw=0,Va=null,lw=[],tu=u=>function(f){if(!C){if(dr===0){var _=!1,g=!1;f((y=0)=>{if(!C&&(Kc=y,_=!0,g)){dr=2,gs(()=>Ad(jt)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),y=!1;try{var T=function(){var R=(x(),B)[jt+8>>>2>>>0];return R=Zc.get(R),R=eu.get(R),--_e,R()}()}catch(R){T=R,y=!0}var S=!1;if(!jt){var I=Va;I&&(Va=null,(y?I.reject:I.resolve)(T),S=!0)}if(y&&!S)throw T}}),g=!0,_||(dr=1,jt=function(){var y=Jr(65548),T=y+12;if((x(),N)[y>>>2>>>0]=T,(x(),N)[y+4>>>2>>>0]=T+65536,T=ws[0],!Ga.has(T)){var S=iw++;Ga.set(T,S),Zc.set(S,T)}return T=Ga.get(T),(x(),B)[y+8>>>2>>>0]=T,y}(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),gs(()=>kd(jt)))}else dr===2?(dr=0,gs(Cd),It(jt),jt=null,lw.forEach(lt)):Te(`invalid state: ${dr}`);return Kc}}(f=>{u().then(f)});function cw(u){return u>>>=0,tu(async()=>{var f=await Mt(u);return Ft(f)})}var Ua=[],uw=u=>{var f=Ua.length;return Ua.push(u),f},dw=(u,f)=>{for(var _=Array(u),g=0;g<u;++g){var y=g,T=(x(),N)[f+4*g>>>2>>>0],S=Da[T];if(S===void 0)throw u=`parameter ${g}`,T=yu(T),f=Ut(T),It(T),new Xr(`${u} has unknown type ${f}`);_[y]=S}return _},hw=(u,f,_)=>{var g=[];return u=u(g,_),g.length&&((x(),N)[f>>>2>>>0]=Ft(g)),u},fw={},vs=u=>{var f=fw[u];return f===void 0?Ut(u):f};function pw(u,f,_){var[g,...y]=dw(u,f>>>0);f=g.Sc.bind(g);var T=y.map(R=>R.Rc.bind(R));u--;var S={toValue:Mt};switch(u=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=vs,I="toValue(handle)[getStringOrSymbol(methodName)]"}return I+=`(${u})`,g.fe||(S.toReturnWire=f,S.emval_returnValue=hw,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}>`,uw(Object.defineProperty(_,"name",{value:I}))}function _w(u,f){return f>>>=0,(u=Mt(u>>>0))==Mt(f)}function mw(u){return(u>>>=0)?(u=vs(u),Ft(globalThis[u])):Ft(globalThis)}function gw(u){return u=vs(u>>>0),Ft(t[u])}function ww(u,f){return f>>>=0,u=Mt(u>>>0),f=Mt(f),Ft(u[f])}function vw(u){9<(u>>>=0)&&(Ar[u+1]+=1)}function ru(u,f,_,g,y){return Ua[u>>>0](f>>>0,_>>>0,g>>>0,y>>>0)}function yw(u,f,_,g,y){return ru(u>>>0,f>>>0,_>>>0,g>>>0,y>>>0)}function bw(){return Ft([])}function Mw(u){u=Mt(u>>>0);for(var f=Array(u.length),_=0;_<u.length;_++)f[_]=u[_];return Ft(f)}function xw(u){return Ft(vs(u>>>0))}function Tw(){return Ft({})}function kw(u){for(var f=Mt(u>>>=0);f.length;){var _=f.pop();f.pop()(_)}za(u)}function Ew(u,f,_){f>>>=0,_>>>=0,u=Mt(u>>>0),f=Mt(f),_=Mt(_),u[f]=_}function Aw(u,f){u=it(u),f>>>=0,u=new Date(1e3*u),(x(),B)[f>>>2>>>0]=u.getUTCSeconds(),(x(),B)[f+4>>>2>>>0]=u.getUTCMinutes(),(x(),B)[f+8>>>2>>>0]=u.getUTCHours(),(x(),B)[f+12>>>2>>>0]=u.getUTCDate(),(x(),B)[f+16>>>2>>>0]=u.getUTCMonth(),(x(),B)[f+20>>>2>>>0]=u.getUTCFullYear()-1900,(x(),B)[f+24>>>2>>>0]=u.getUTCDay(),u=(u.getTime()-Date.UTC(u.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(x(),B)[f+28>>>2>>>0]=u}var nu=u=>u%4==0&&(u%100!=0||u%400==0),su=[0,31,60,91,121,152,182,213,244,274,305,335],au=[0,31,59,90,120,151,181,212,243,273,304,334];function Cw(u,f){u=it(u),f>>>=0,u=new Date(1e3*u),(x(),B)[f>>>2>>>0]=u.getSeconds(),(x(),B)[f+4>>>2>>>0]=u.getMinutes(),(x(),B)[f+8>>>2>>>0]=u.getHours(),(x(),B)[f+12>>>2>>>0]=u.getDate(),(x(),B)[f+16>>>2>>>0]=u.getMonth(),(x(),B)[f+20>>>2>>>0]=u.getFullYear()-1900,(x(),B)[f+24>>>2>>>0]=u.getDay();var _=(nu(u.getFullYear())?su:au)[u.getMonth()]+u.getDate()-1|0;(x(),B)[f+28>>>2>>>0]=_,(x(),B)[f+36>>>2>>>0]=-60*u.getTimezoneOffset(),_=new Date(u.getFullYear(),6,1).getTimezoneOffset();var g=new Date(u.getFullYear(),0,1).getTimezoneOffset();u=0|(_!=g&&u.getTimezoneOffset()==Math.min(g,_)),(x(),B)[f+32>>>2>>>0]=u}function Sw(u){u>>>=0;var f=new Date((x(),B)[u+20>>>2>>>0]+1900,(x(),B)[u+16>>>2>>>0],(x(),B)[u+12>>>2>>>0],(x(),B)[u+8>>>2>>>0],(x(),B)[u+4>>>2>>>0],(x(),B)[u>>>2>>>0],0),_=(x(),B)[u+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)[u+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)[u+24>>>2>>>0]=f.getDay(),_=(nu(f.getFullYear())?su:au)[f.getMonth()]+f.getDate()-1|0,(x(),B)[u+28>>>2>>>0]=_,(x(),B)[u>>>2>>>0]=f.getSeconds(),(x(),B)[u+4>>>2>>>0]=f.getMinutes(),(x(),B)[u+8>>>2>>>0]=f.getHours(),(x(),B)[u+12>>>2>>>0]=f.getDate(),(x(),B)[u+16>>>2>>>0]=f.getMonth(),(x(),B)[u+20>>>2>>>0]=f.getYear(),u=f.getTime(),BigInt(isNaN(u)?-1:u/1e3)}function ou(u,f,_,g,y,T,S){return s?ye(16,1,u,f,_,g,y,T,S):-52}function iu(u,f,_,g,y,T){if(s)return ye(17,1,u,f,_,g,y,T)}var In={},Pw=()=>performance.timeOrigin+performance.now();function lu(u,f){if(s)return ye(18,1,u,f);if(In[u]&&(clearTimeout(In[u].id),delete In[u]),!f)return 0;var _=setTimeout(()=>{delete In[u],lt(()=>zu(u,performance.timeOrigin+performance.now()))},f);return In[u]={id:_,Ce:f},0}function Fw(u,f,_,g){u>>>=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)[u>>>2>>>0]=60*S,(x(),B)[f>>>2>>>0]=+(T!=y),u=(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(u,_,17),Zt(f,g,17)):(Zt(u,g,17),Zt(f,_,17))}var Iw=()=>Date.now();function Lw(u,f,_){return _>>>=0,0<=u&&3>=u?(u===0?u=Date.now():u=performance.timeOrigin+performance.now(),u=Math.round(1e6*u),(x(),X)[_>>>3>>>0]=BigInt(u),0):28}var ja=[],cu=(u,f)=>{ja.length=0;for(var _;_=(x(),W)[u++>>>0];){var g=_!=105;f+=(g&=_!=112)&&f%8?4:0,ja.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 ja};function Ow(u,f,_){return u>>>=0,f=cu(f>>>0,_>>>0),ao[u](...f)}function Nw(u,f,_){return u>>>=0,f=cu(f>>>0,_>>>0),ao[u](...f)}var Dw=()=>{};function zw(u,f){return E(Qr(u>>>0,f>>>0))}var Bw=()=>{throw _e+=1,"unwind"};function Rw(){return 4294901760}var $w=()=>1,Gw=()=>navigator.hardwareConcurrency;function Vw(u){u>>>=0;var f=(x(),W).length;if(u<=f||4294901760<u)return!1;for(var _=1;4>=_;_*=2){var g=f*(1+.2/_);g=Math.min(g,u+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(u,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 Wt=u=>{var f=er(u)+1,_=xs(f);return Zt(u,_,f),_},Wa=(u,f)=>{(x(),N)[u>>>2>>>0]=f;var _=(x(),N)[u>>>2>>>0];(x(),N)[u+4>>>2>>>0]=(f-_)/4294967296},Ln=u=>(x(),N)[u>>>2>>>0]+4294967296*(x(),B)[u+4>>>2>>>0],Ke=[],Uw=(u,f)=>{Ke[u>>>0]=f},tr=[],ys=[],Yr=(u,f)=>{ys[u]=new Promise(_=>f.finally(()=>_(u)))},Z=u=>{if(u)return Ke[u>>>0]},jw=(u,f)=>{for(u=(x(),N)[u>>>2>>>0];u;u=(x(),N)[u>>>2>>>0])f[(x(),B)[u+4>>>2>>>0]](u)},bs=(u,f,_)=>{(x(),N)[u>>>2>>>0]=f,(x(),N)[u+4>>>2>>>0]=_},uu=u=>{var f=(x(),N)[u>>>2>>>0];return u=(x(),N)[u+4>>>2>>>0],Qr(f,u)},rr=u=>{var f=(x(),N)[u>>>2>>>0];return u=(x(),N)[u+4>>>2>>>0],f?Qr(f,u):u===0?"":void 0},Ww=u=>{var f=rr(u+4),_=(_=(x(),N)[u+12>>>2>>>0])?Z(_):"auto";if(u+=16){var g=Z((x(),N)[u+4>>>2>>>0]),y=(x(),N)[u+16>>>2>>>0],T=(x(),N)[u+20>>>2>>>0];if(y){for(var S={},I=0;I<y;++I){var R=T+24*I;S[uu(R+4)]=(x(),ee)[R+16>>>3>>>0]}y=S}else y=void 0;u={module:g,constants:y,entryPoint:rr(u+8)}}else u=void 0;return{label:f,layout:_,compute:u}},du=(u,f)=>{function _(g,y){g=u[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),Wa(f+64,u.maxUniformBufferBindingSize),Wa(f+72,u.maxStorageBufferBindingSize),_("maxVertexBuffers",88),Wa(f+96,u.maxBufferSize),_("maxVertexAttributes",104),_("maxVertexBufferArrayStride",108),_("maxInterStageShaderVariables",112),_("maxColorAttachments",116),_("maxColorAttachmentBytesPerSample",120),_("maxComputeWorkgroupStorageSize",124),_("maxComputeInvocationsPerWorkgroup",128),_("maxComputeWorkgroupSizeX",132),_("maxComputeWorkgroupSizeY",136),_("maxComputeWorkgroupSizeZ",140),_("maxComputeWorkgroupsPerDimension",144),u.Ae!==void 0&&_("maxImmediateSize",148)},qw=[,"validation","out-of-memory","internal"],Hw=[,"compatibility","core"],hu={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",22:"texture-component-swizzle",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect"},Qw=[,"low-power","high-performance"],Xw=[,"occlusion","timestamp"],Yw={undefined:1,unknown:1,destroyed:2};function Jw(u,f,_,g,y,T){f=it(f),_=it(_),g>>>=0,y>>>=0,T>>>=0;var S=Z(u>>>0);if(u={},T){var I=(x(),N)[T+12>>>2>>>0];if(I){var R=(x(),N)[T+16>>>2>>>0];u.requiredFeatures=Array.from((x(),N).subarray(R>>>2>>>0,R+4*I>>>2>>>0),Q=>hu[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)},he=function(Ce,Xe){Xe=H+Xe;var Dn=(x(),N)[Xe>>>2>>>0],oo=(x(),N)[Xe+4>>>2>>>0];Dn==4294967295&&oo==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),he("maxUniformBufferBindingSize",64),he("maxStorageBufferBindingSize",72),Q("maxVertexBuffers",88),he("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),u.requiredLimits=me}(I=(x(),N)[T+24>>>2>>>0])&&(I={label:rr(I+4)},u.defaultQueue=I),u.label=rr(T+4)}_e+=1,Yr(f,S.requestDevice(u).then(Q=>{--_e,lt(()=>{Ke[y>>>0]=Q.queue,Ke[g>>>0]=Q,Yr(_,Q.lost.then(he=>{lt(()=>{Q.onuncapturederror=()=>{};var Ce=re(),Xe=Wt(he.message);Ya(_,Yw[he.reason],Xe),te(Ce)})})),Q.onuncapturederror=he=>{var Ce=5;he.error instanceof GPUValidationError?Ce=2:he.error instanceof GPUOutOfMemoryError?Ce=3:he.error instanceof GPUInternalError&&(Ce=4);var Xe=re();he=Wt(he.error.message),Lu(g,Ce,he),te(Xe)},"adapterInfo"in Q||(Q.adapterInfo=S.info),Za(f,1,g,0)})},Q=>{--_e,lt(()=>{var he=re(),Ce=Wt(Q.message);Za(f,3,g,Ce),_&&Ya(_,4,Ce),te(he)})}))}function Kw(u){var f=Z(u>>>=0),_=tr[u];if(_){for(var g=0;g<_.length;++g)_[g]();delete tr[u]}f.destroy()}function Zw(u,f,_){_>>>=0;var g=Z(u>>>=0);_==4294967295&&(_=void 0);try{var y=g.getMappedRange(f>>>0,_)}catch{return 0}var T=ro(16,y.byteLength);return(x(),W).set(new Uint8Array(y),T>>>0),tr[u].push(()=>It(T)),T}function ev(u,f,_){_>>>=0;var g=Z(u>>>=0);_==4294967295&&(_=void 0);try{var y=g.getMappedRange(f>>>0,_)}catch{return 0}var T=ro(16,y.byteLength);return(x(),W).fill(0,T,y.byteLength),tr[u].push(()=>{new Uint8Array(y).set((x(),W).subarray(T>>>0,T+y.byteLength>>>0)),It(T)}),T}function tv(u,f,_,g,y){u>>>=0,f=it(f),_=it(_),y>>>=0;var T=Z(u);tr[u]=[],y==4294967295&&(y=void 0),_e+=1,Yr(f,T.mapAsync(_,g>>>0,y).then(()=>{--_e,lt(()=>{Ja(f,1,0)})},S=>{--_e,lt(()=>{re();var I=Wt(S.message);Ja(f,S.name==="AbortError"?4:S.name==="OperationError"?3:0,I),delete tr[u]})}))}function rv(u){var f=Z(u>>>=0),_=tr[u];if(_){for(var g=0;g<_.length;++g)_[g]();delete tr[u],f.unmap()}}function nv(u){delete Ke[u>>>0]}function sv(u,f,_){u>>>=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},u=Z(u);try{var y=u.createBuffer(f)}catch{return!1}return Ke[_>>>0]=y,g&&(tr[_]=[]),!0}function av(u,f,_,g){u>>>=0,f=it(f),g>>>=0,_=Ww(_>>>0),u=Z(u),_e+=1,Yr(f,u.createComputePipelineAsync(_).then(y=>{--_e,lt(()=>{Ke[g>>>0]=y,Xa(f,1,g,0)})},y=>{--_e,lt(()=>{var T=re(),S=Wt(y.message);Xa(f,y.reason==="validation"?3:y.reason==="internal"?4:0,g,S),te(T)})}))}function ov(u,f,_){u>>>=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=uu(g+8)),u=Z(u).createShaderModule(f),Ke[_>>>0]=u}var iv=u=>{(u=Z(u)).onuncapturederror=null,u.destroy()};function lv(u,f){f=it(f),u=Z(u>>>0),_e+=1,Yr(f,u.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=_?Wt(_.message):0;Ka(f,1,g,T),te(y)})},_=>{--_e,lt(()=>{var g=re(),y=Wt(_.message);Ka(f,1,5,y),te(g)})}))}function cv(u,f,_,g){if(f=it(f),g>>>=0,_>>>=0){var y={featureLevel:Hw[(x(),B)[_+4>>>2>>>0]],powerPreference:Qw[(x(),B)[_+8>>>2>>>0]],forceFallbackAdapter:!!(x(),N)[_+12>>>2>>>0]};(u=(x(),N)[_>>>2>>>0])!==0&&(x(),y.Fe=!!(x(),N)[u+8>>>2>>>0])}"gpu"in navigator?(_e+=1,Yr(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=Wt("WebGPU not available on this browser (requestAdapter returned null)");On(f,3,g,I),te(S)}})},T=>{--_e,lt(()=>{var S=re(),I=Wt(T.message);On(f,4,g,I),te(S)})}))):(y=re(),u=Wt("WebGPU not available on this browser (navigator.gpu is not available)"),On(f,3,g,u),te(y))}function uv(u,f,_){return u>>>=0,f>>>=0,_>>>=0,tu(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(u+8*T);if(!(S in ys))return S;g[T]=ys[S]}return g=await Promise.race(g),delete ys[g],g})}var qa,Ha={},fu=()=>{if(!qa){var u,f={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(u in Ha)Ha[u]===void 0?delete f[u]:f[u]=Ha[u];var _=[];for(u in f)_.push(`${u}=${f[u]}`);qa=_}return qa};function pu(u,f){if(s)return ye(19,1,u,f);u>>>=0,f>>>=0;var _,g=0,y=0;for(_ of fu()){var T=f+g;(x(),N)[u+y>>>2>>>0]=T,g+=Zt(_,T,1/0)+1,y+=4}return 0}function _u(u,f){if(s)return ye(20,1,u,f);u>>>=0,f>>>=0;var _=fu();for(var g of((x(),N)[u>>>2>>>0]=_.length,u=0,_))u+=er(g)+1;return(x(),N)[f>>>2>>>0]=u,0}function mu(u){return s?ye(21,1,u):52}function gu(u,f,_,g){return s?ye(22,1,u,f,_,g):52}function wu(u,f,_,g){return s?ye(23,1,u,f,_,g):70}var dv=[null,[],[]];function vu(u,f,_,g){if(s)return ye(24,1,u,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=u,me=(x(),W)[S+R>>>0],Q=dv[H];me===0||me===10?((H===1?A:E)(Nc(Q)),Q.length=0):Q.push(me)}y+=I}return(x(),N)[g>>>2>>>0]=y,0}function hv(u){return u>>>0}function fv(u,f){return du(Z(u>>>0).limits,f>>>0),1}function pv(u,f){return Z(u>>>0).features.has(hu[f])}function _v(u){return BigInt(Z(u>>>0).size)}function mv(u){return BigInt(Z(u>>>0).usage)}function gv(u,f){if(u>>>=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(u),u=Cu(0),_=f.beginComputePass(_),Ke[u>>>0]=_,u}function wv(u,f,_,g,y,T){_=it(_),y=it(y),T=it(T),Z(u>>>0).copyBufferToBuffer(Z(f>>>0),_,Z(g>>>0),y,T)}function vv(u){var f=Z(u>>>0);return u=Eu(0),f=f.finish(),Ke[u>>>0]=f,u}function yv(u,f,_,g,y,T){T=it(T),Z(u>>>0).resolveQuerySet(Z(f>>>0),_,g,Z(y>>>0),T)}function bv(u,f,_,g){Z(u>>>0).dispatchWorkgroups(f,_,g)}function Mv(u,f,_){_=it(_),Z(u>>>0).dispatchWorkgroupsIndirect(Z(f>>>0),_)}function xv(u){Z(u>>>0).end()}function Tv(u,f,_,g,y){g>>>=0,y>>>=0,u=Z(u>>>0),_=Z(_>>>0),g==0?u.setBindGroup(f,_):u.setBindGroup(f,_,(x(),N),y>>>2,g)}function kv(u,f){Z(u>>>0).setPipeline(Z(f>>>0))}function Ev(u,f,_){Z(u>>>0).Ee(Z(f>>>0),_)}function Av(u,f){var _=Z(u>>>0);return u=ku(0),f=_.getBindGroupLayout(f),Ke[u>>>0]=f,u}function Cv(u,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 jw(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}}u>>>=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])},u=Z(u);var g=Tu(0);return Uw(g,u.createBindGroup(f)),g}function Sv(u,f){var _;return u>>>=0,(f>>>=0)&&(_={label:rr(f+4)}),f=Z(u),u=Au(0),_=f.createCommandEncoder(_),Ke[u>>>0]=_,u}function Pv(u,f){u>>>=0,f>>>=0,f={type:Xw[(x(),B)[f+12>>>2>>>0]],count:(x(),N)[f+16>>>2>>>0]};var _=Z(u);return u=Su(0),f=_.createQuerySet(f),Ke[u>>>0]=f,u}function Fv(u,f){u=Z(u>>>0).adapterInfo,f>>>=0,(x(),N)[f+52>>>2>>>0]=u.subgroupMinSize,(x(),N)[f+56>>>2>>>0]=u.subgroupMaxSize;var _=u.vendor+u.architecture+u.device+u.description,g=er(_)+1,y=Jr(g);return y&&Zt(_,y,g),_=y,g=er(u.vendor),bs(f+4,_,g),_+=g,g=er(u.architecture),bs(f+12,_,g),_+=g,g=er(u.device),bs(f+20,_,g),bs(f+28,_+g,er(u.description)),(x(),B)[f+36>>>2>>>0]=2,u=u.isFallbackAdapter?3:4,(x(),B)[f+40>>>2>>>0]=u,(x(),N)[f+44>>>2>>>0]=0,(x(),N)[f+48>>>2>>>0]=0,1}var Iv={"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 Lv(u,f){f>>>=0;var _=Z(u>>>0);u=Jr(4*_.features.size);var g=0,y=0;for(let T of _.features)0<=(_=Iv[T])&&((x(),B)[u+g>>>2>>>0]=_,g+=4,y++);(x(),N)[f+4>>>2>>>0]=u,(x(),N)[f>>>2>>>0]=y}function Ov(u,f){return du(Z(u>>>0).limits,f>>>0),1}function Nv(u,f){Z(u>>>0).pushErrorScope(qw[f])}function Dv(u,f,_){f>>>=0,_>>>=0,u=Z(u>>>0),f=Array.from((x(),B).subarray(_>>>2>>>0,_+4*f>>>2>>>0),g=>Z(g)),u.submit(f)}function zv(u,f,_,g,y){_=it(_),g>>>=0,y>>>=0,u=Z(u>>>0),f=Z(f>>>0),g=(x(),W).subarray(g>>>0,g+y>>>0),u.writeBuffer(f,_,g,0,y)}s||function(){for(var u=t.numThreads-1;u--;)Cc();Ue.push(async()=>{var f=async function(){if(!s)return Promise.all(We.map(Ac))}();be++,await f,--be==0&&fe&&(f=fe,fe=null,f())})}(),s||(ur=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),K()),t.wasmBinary&&(h=t.wasmBinary),t.stackSave=()=>re(),t.stackRestore=u=>te(u),t.stackAlloc=u=>xs(u),t.setValue=function(u,f,_="i8"){switch(_.endsWith("*")&&(_="*"),_){case"i1":case"i8":(x(),G)[u>>>0]=f;break;case"i16":(x(),J)[u>>>1>>>0]=f;break;case"i32":(x(),B)[u>>>2>>>0]=f;break;case"i64":(x(),X)[u>>>3>>>0]=BigInt(f);break;case"float":(x(),V)[u>>>2>>>0]=f;break;case"double":(x(),ee)[u>>>3>>>0]=f;break;case"*":(x(),N)[u>>>2>>>0]=f;break;default:Te(`invalid type for setValue: ${_}`)}},t.getValue=function(u,f="i8"){switch(f.endsWith("*")&&(f="*"),f){case"i1":case"i8":return(x(),G)[u>>>0];case"i16":return(x(),J)[u>>>1>>>0];case"i32":return(x(),B)[u>>>2>>>0];case"i64":return(x(),X)[u>>>3>>>0];case"float":return(x(),V)[u>>>2>>>0];case"double":return(x(),ee)[u>>>3>>>0];case"*":return(x(),N)[u>>>2>>>0];default:Te(`invalid type for getValue: ${f}`)}},t.UTF8ToString=Qr,t.stringToUTF8=Zt,t.lengthBytesUTF8=er;var yu,bu,Qa,Ms,It,Jr,Mu,xu,Tu,ku,Eu,Au,Cu,Su,Pu,Fu,Iu,Xa,Ya,Ja,Ka,On,Za,Lu,eo,Ou,Nu,Du,to,zu,Bu,ro,de,Nn,Ru,te,xs,re,$u,no,Gu,Vu,Uu,so,ju,Wu,qu,Hu,Qu,Xu,Yu,Ju,Ku,Zu,ed,td,rd,nd,sd,ad,od,id,ld,cd,ud,dd,hd,fd,pd,_d,md,gd,wd,vd,yd,bd,Md,xd,Td,kd,Ed,Ad,Cd,nr,Bv=[cr,kr,Fc,Dc,zc,Bc,Rc,$c,Gc,Vc,Uc,jc,Wc,qc,Hc,Qc,ou,iu,lu,pu,_u,mu,gu,wu,vu],ao={922732:(u,f,_,g,y)=>{if(t===void 0||!t.Uc)return 1;if((u=Qr(Number(u>>>0))).startsWith("./")&&(u=u.substring(2)),!(u=t.Uc.get(u)))return 2;if(f=Number(f>>>0),_=Number(_>>>0),g=Number(g>>>0),f+_>u.byteLength)return 3;try{let T=u.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:(u,f,_)=>{t.Sd(u,(x(),W).subarray(f>>>0,f+_>>>0))},923620:()=>t.me(),923662:u=>{t.jd(u)},923699:()=>typeof wasmOffsetConverter<"u"};function Rv(u,f,_,g){var y=re();try{return Ju(u,f,_,g)}catch(T){if(te(y),T!==T+0)throw T;de(1,0)}}function $v(u,f,_){var g=re();try{return Qu(u,f,_)}catch(y){if(te(g),y!==y+0)throw y;de(1,0)}}function Gv(u,f,_){var g=re();try{Uu(u,f,_)}catch(y){if(te(g),y!==y+0)throw y;de(1,0)}}function Vv(u,f){var _=re();try{return so(u,f)}catch(g){if(te(_),g!==g+0)throw g;de(1,0)}}function Uv(u){var f=re();try{ju(u)}catch(_){if(te(f),_!==_+0)throw _;de(1,0)}}function jv(u,f,_,g,y,T,S){var I=re();try{return Hu(u,f,_,g,y,T,S)}catch(R){if(te(I),R!==R+0)throw R;de(1,0)}}function Wv(u,f){var _=re();try{Ku(u,f)}catch(g){if(te(_),g!==g+0)throw g;de(1,0)}}function qv(u,f,_,g,y,T){var S=re();try{Wu(u,f,_,g,y,T)}catch(I){if(te(S),I!==I+0)throw I;de(1,0)}}function Hv(u,f,_,g){var y=re();try{Yu(u,f,_,g)}catch(T){if(te(y),T!==T+0)throw T;de(1,0)}}function Qv(u,f,_,g,y,T,S){var I=re();try{ed(u,f,_,g,y,T,S)}catch(R){if(te(I),R!==R+0)throw R;de(1,0)}}function Xv(u,f,_,g,y,T,S){var I=re();try{td(u,f,_,g,y,T,S)}catch(R){if(te(I),R!==R+0)throw R;de(1,0)}}function Yv(u,f,_,g,y,T,S,I){var R=re();try{ud(u,f,_,g,y,T,S,I)}catch(H){if(te(R),H!==H+0)throw H;de(1,0)}}function Jv(u,f,_,g,y,T,S,I,R,H,me,Q){var he=re();try{rd(u,f,_,g,y,T,S,I,R,H,me,Q)}catch(Ce){if(te(he),Ce!==Ce+0)throw Ce;de(1,0)}}function Kv(u,f,_,g,y){var T=re();try{return Zu(u,f,_,g,y)}catch(S){if(te(T),S!==S+0)throw S;de(1,0)}}function Zv(u,f,_,g,y){var T=re();try{qu(u,f,_,g,y)}catch(S){if(te(T),S!==S+0)throw S;de(1,0)}}function ey(u,f,_,g,y,T,S,I){var R=re();try{Xu(u,f,_,g,y,T,S,I)}catch(H){if(te(R),H!==H+0)throw H;de(1,0)}}function ty(u){var f=re();try{return dd(u)}catch(_){if(te(f),_!==_+0)throw _;de(1,0)}}function ry(u,f,_){var g=re();try{return hd(u,f,_)}catch(y){if(te(g),y!==y+0)throw y;de(1,0)}}function ny(u,f){var _=re();try{return Td(u,f)}catch(g){if(te(_),g!==g+0)throw g;return de(1,0),0n}}function sy(u,f,_,g,y){var T=re();try{fd(u,f,_,g,y)}catch(S){if(te(T),S!==S+0)throw S;de(1,0)}}function ay(u){var f=re();try{return nd(u)}catch(_){if(te(f),_!==_+0)throw _;return de(1,0),0n}}function oy(u,f,_,g,y,T){var S=re();try{return ld(u,f,_,g,y,T)}catch(I){if(te(S),I!==I+0)throw I;de(1,0)}}function iy(u,f,_,g,y,T){var S=re();try{return pd(u,f,_,g,y,T)}catch(I){if(te(S),I!==I+0)throw I;de(1,0)}}function ly(u,f,_,g,y,T){var S=re();try{return _d(u,f,_,g,y,T)}catch(I){if(te(S),I!==I+0)throw I;de(1,0)}}function cy(u,f,_,g,y,T,S,I){var R=re();try{return cd(u,f,_,g,y,T,S,I)}catch(H){if(te(R),H!==H+0)throw H;de(1,0)}}function uy(u,f,_,g,y){var T=re();try{return md(u,f,_,g,y)}catch(S){if(te(T),S!==S+0)throw S;return de(1,0),0n}}function dy(u,f,_,g){var y=re();try{return gd(u,f,_,g)}catch(T){if(te(y),T!==T+0)throw T;de(1,0)}}function hy(u,f,_,g){var y=re();try{return wd(u,f,_,g)}catch(T){if(te(y),T!==T+0)throw T;de(1,0)}}function fy(u,f,_,g,y,T,S,I,R,H,me,Q){var he=re();try{return vd(u,f,_,g,y,T,S,I,R,H,me,Q)}catch(Ce){if(te(he),Ce!==Ce+0)throw Ce;de(1,0)}}function py(u,f,_,g,y,T,S,I,R,H,me){var Q=re();try{yd(u,f,_,g,y,T,S,I,R,H,me)}catch(he){if(te(Q),he!==he+0)throw he;de(1,0)}}function _y(u,f,_,g,y,T,S,I,R,H,me,Q,he,Ce,Xe,Dn){var oo=re();try{bd(u,f,_,g,y,T,S,I,R,H,me,Q,he,Ce,Xe,Dn)}catch(io){if(te(oo),io!==io+0)throw io;de(1,0)}}function my(u,f,_,g){var y=re();try{return Md(u,f,_,g)}catch(T){if(te(y),T!==T+0)throw T;de(1,0)}}function gy(u,f,_,g,y){var T=re();try{return xd(u,f,_,g,y)}catch(S){if(te(T),S!==S+0)throw S;de(1,0)}}function wy(u,f,_){var g=re();try{return ad(u,f,_)}catch(y){if(te(g),y!==y+0)throw y;return de(1,0),0n}}function vy(u,f,_){var g=re();try{return sd(u,f,_)}catch(y){if(te(g),y!==y+0)throw y;de(1,0)}}function yy(u,f,_){var g=re();try{return od(u,f,_)}catch(y){if(te(g),y!==y+0)throw y;de(1,0)}}function by(u,f,_,g){var y=re();try{id(u,f,_,g)}catch(T){if(te(y),T!==T+0)throw T;de(1,0)}}function Ts(){if(0<be)fe=Ts;else if(s)w?.(t),le();else{for(var u=Ue;0<u.length;)u.shift()(t);0<be?fe=Ts:(t.calledRun=!0,C||(le(),w?.(t)))}}return s||(nr=await ut(),Ts()),t.PTR_SIZE=4,t.webgpuInit=u=>{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 he=Iu(Q);return Q=Fu(Q,he),Ke[he>>>0]=me.queue,Ke[Q>>>0]=me,Q})(I,R=xu(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=Qa(R);T.set(I,H),R===0&&u(_??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=Pu(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 he=me.createBuffer({size:Q,usage:9});try{let Ce=me.createCommandEncoder();return Ce.copyBufferToBuffer(I,0,he,0,Q),me.queue.submit([Ce.finish()]),await he.mapAsync(GPUMapMode.READ),he.getMappedRange().slice(0,R)}finally{he.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 he=Qa(g);_=Z(he)}let Ce=(he=_.createBuffer({mappedAtCreation:!0,size:R,usage:6})).getMappedRange();new Uint8Array(Ce).set(new Uint8Array(H,me,Q)),he.unmap(),(H=_.createCommandEncoder()).copyBufferToBuffer(he,0,I,0,R),_.queue.submit([H.finish()]),he.destroy()}},t.webnnInit=u=>{let f=u[0];[t.me,t.jd,t.webnnEnsureTensor,t.Sd,t.webnnDownloadTensor,t.le,t.webnnEnableTraceEvent]=u.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((u,f)=>{w=u,v=f})}var Mf,Fd,Gy=pe(()=>{Mf=Pd,Fd=globalThis.self?.name?.startsWith("em-pthread"),Fd&&Pd()}),po,Go,Id,gt,xf,Es,Ld,Od,_o,Nd,mo,Tf,go,kf,ii=pe(()=>{oi(),po=typeof location>"u"?void 0:location.origin,Go=import.meta.url>"file:"&&import.meta.url<"file;",Id=()=>{{if(Go){let e=URL;return new URL(new e("ort.webgpu.bundle.min.mjs",import.meta.url).href,po).href}return import.meta.url}},gt=Id(),xf=()=>{if(gt&&!gt.startsWith("blob:"))return gt.substring(0,gt.lastIndexOf("/")+1)},Es=(e,t)=>{try{let r=t??gt;return(r?new URL(e,r):new URL(e)).origin===po}catch{return!1}},Ld=(e,t)=>{let r=t??gt;try{return(r?new URL(e,r):new URL(e)).href}catch{return}},Od=(e,t)=>`${t??"./"}${e}`,_o=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Nd=async e=>(await import(e)).default,mo=($y(),Gs(vf)).default,Tf=async()=>{if(!gt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Es(gt))return[void 0,mo()];let e=await _o(gt);return[e,mo(e)]},go=(Gy(),Gs(bf)).default,kf=async(e,t,r,n)=>{let s=go&&!(e||t);if(s)if(gt)s=Es(gt)||n&&!r;else if(n&&!r)s=!0;else throw new Error("cannot determine the script source URL.");if(s)return[void 0,go];{let a="ort-wasm-simd-threaded.asyncify.mjs",o=e??Ld(a,t),i=r&&o&&!Es(o,t),l=i?await _o(o):o??Od(a,t);return[i?l:void 0,await Nd(l)]}}}),wo,As,Bn,vo,Dd,zd,Bd,li,Ae,Vr=pe(()=>{ii(),As=!1,Bn=!1,vo=!1,Dd=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},zd=()=>{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}},Bd=()=>{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}},li=async e=>{if(As)return Promise.resolve();if(Bn)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(vo)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(!Bd())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!zd())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let n=Dd();r>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let s=e.wasmPaths,a=typeof s=="string"?s:void 0,o=s?.mjs,i=o?.href??o,l=s?.wasm,c=l?.href??l,d=e.wasmBinary,[h,p]=await kf(i,a,r>1,!!d||!!c),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(c||a)M.locateFile=k=>c??a+k;else if(i&&i.indexOf("blob:")!==0)M.locateFile=k=>new URL(k,i).href;else if(h){let k=xf();k&&(M.locateFile=A=>k+A)}p(M).then(k=>{Bn=!1,As=!0,wo=k,v(),h&&URL.revokeObjectURL(h)},k=>{Bn=!1,vo=!0,b(k)})})),await Promise.race(w),m)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Ae=()=>{if(As&&wo)return wo;throw new Error("WebAssembly is not initialized yet.")}}),wt,Us,xe,ci=pe(()=>{Vr(),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},Us=(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")Us(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)}}}),Ef,Vy=pe(()=>{Vr(),ci(),Ef=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&&Us(e.extra,"",new WeakSet,(o,i)=>{let l=wt(o,n),c=wt(i,n);t._OrtAddRunConfigEntry(r,l,c)!==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}}}),Rd,$d,Gd,Cs,fr,Vd,Af,Uy=pe(()=>{Vr(),ci(),Rd=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},$d=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Gd=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)},Cs=(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}.`)},fr=(e,t,r,n)=>{let s=wt(t,n),a=wt(r,n);e.push([s,a])},Vd=async(e,t,r)=>{let n=t.executionProviders;for(let s of n){let a=typeof s=="string"?s:s.name,o=[];switch(a){case"webnn":if(a="WEBNN",typeof s!="string"){let h=s?.deviceType;h&&Cs(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&&fr(o,"enableGraphCapture","1",r),typeof m.preferredLayout=="string"&&fr(o,"preferredLayout",m.preferredLayout,r),m.forceCpuNodeNames){let v=Array.isArray(m.forceCpuNodeNames)?m.forceCpuNodeNames:[m.forceCpuNodeNames];fr(o,"forceCpuNodeNames",v.join(`
8
+ `),r)}m.validationMode&&fr(o,"validationMode",m.validationMode,r)}let p=Ae().webgpuRegisterDevice(h);if(p){let[m,w,v]=p;fr(o,"deviceId",m.toString(),r),fr(o,"webgpuInstance",w.toString(),r),fr(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,c=0,d=0;if(l>0){c=Ae()._malloc(l*Ae().PTR_SIZE),r.push(c),d=Ae()._malloc(l*Ae().PTR_SIZE),r.push(d);for(let h=0;h<l;h++)Ae().setValue(c+h*Ae().PTR_SIZE,o[h][0],"*"),Ae().setValue(d+h*Ae().PTR_SIZE,o[h][1],"*")}await Ae()._OrtAppendExecutionProvider(e,i,c,d,l)!==0&&xe(`Can't append execution provider: ${a}.`)}},Af=async e=>{let t=Ae(),r=0,n=[],s=e||{};Gd(s);try{let a=Rd(s.graphOptimizationLevel??"all"),o=$d(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 c=s.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);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,c,d),r===0&&xe("Can't create session options."),s.executionProviders&&await Vd(r,s,n),s.enableGraphCapture!==void 0){if(typeof s.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${s.enableGraphCapture}`);Cs(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&&Us(s.extra,"",new WeakSet,(h,p)=>{Cs(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,zs,nn,Jn,js,ui,di,Vo,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}`)}},zs=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},nn=(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}`)}},js=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},ui=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",di=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Vo=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),hi,Cf=pe(()=>{oi(),hi=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 c=l.byteLength;new Uint8Array(a,o,c).set(l),o+=c}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Sf,jy=pe(()=>{dn(),Sf=(e,t)=>new(Jn(t))(e)}),Ud,jd,Wd,qd,Pf,Hd,nt,Ff=pe(()=>{dn(),Ud=["V","I","W","E","F"],jd=(e,t)=>{console.log(`[${Ud[e]},${new Date().toISOString()}]${t}`)},Pf=(e,t)=>{Wd=e,qd=t},Hd=(e,t)=>{let r=js(e),n=js(Wd);r>=n&&jd(r,typeof t=="function"?t():t)},nt=(...e)=>{qd&&Hd(...e)}}),yo,Uo,bo,Qd,Mo,Xd,xo,To,ko,Yd,If,Wy=pe(()=>{dn(),Ff(),yo=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Uo=(e,t)=>{if(t==="int32")return e;let r=yo.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'`)}},bo=(e,t)=>{if(t==="int32")return e;if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=e.byteLength/4,n=new Int32Array(e.buffer,e.byteOffset,r);switch(t){case"int64":{let s=BigInt64Array.from(n,BigInt);return new Uint8Array(s.buffer)}case"uint64":{if(n.some(a=>a<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let s=BigUint64Array.from(n,BigInt);return new Uint8Array(s.buffer)}case"int8":{if(n.some(a=>a<-128||a>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let s=Int8Array.from(n,Number);return new Uint8Array(s.buffer)}case"uint8":{if(n.some(s=>s<0||s>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(n,Number)}case"uint32":{if(n.some(a=>a<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let s=Uint32Array.from(n,Number);return new Uint8Array(s.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},Qd=1,Mo=()=>Qd++,Xd=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),xo=(e,t)=>{let r=yo.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((n,s)=>n*s)*r/8):0},To=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:r,tensor:n,dataType:s,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=r,this.mlTensor=n,this.dataType=s,this.tensorShape=a,this.fallbackDataType=o}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return xo(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=bo(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}},ko=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,r,n){let s=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!a?.input.dataTypes.includes(t)){if(o=Xd.get(t),!o||a?.input.dataTypes.includes(o))throw new Error(`WebNN backend does not support data type: ${t}`);nt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(s,t,r))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==xo(t,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,r,i,!0,!0,o),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")t=Uo(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else nt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?bo(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}else return t.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Yd=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=Mo();return this.tensorTrackersById.set(e,new ko(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=Mo(),o=new To({sessionId:e,context:s,tensor:t,dataType:r,shape:n});return this.tensorTrackersById.set(a,new ko(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,r,n,s,a,o){let i=this.getMLContext(e);for(let[c,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(c,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 To({sessionId:e,context:i,tensor:l,dataType:t,shape:r,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},If=(...e)=>new Yd(...e)}),Lf={};es(Lf,{WebNNBackend:()=>Of});var Rn,Jd,Of,qy=pe(()=>{dn(),Vr(),jy(),Wy(),Ff(),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"]]),Jd=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),n=Object.keys(t).sort();return r.length===n.length&&r.every((s,a)=>s===n[a]&&e[s]===t[s])},Of=class{constructor(e){this.tensorManager=If(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,Pf(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){nt("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){nt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let r of t)nt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let r=this.mlContextCache.findIndex(n=>n.gpuDevice===e);if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:n}),n}}else if(e===void 0){let r=this.mlContextCache.findIndex(n=>n.options===void 0&&n.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:n}),n}}let t=this.mlContextCache.findIndex(r=>Jd(r.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let r=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:r}),r}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let r=this.sessionIdsByMLContext.get(t);r||(r=new Set,this.sessionIdsByMLContext.set(t,r)),r.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(t);if(r.delete(e),r.size===0){this.sessionIdsByMLContext.delete(t);let n=this.mlContextCache.findIndex(s=>s.mlContext===t);n!==-1&&this.mlContextCache.splice(n,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){nt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,n,s){let a=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 Sf(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 c=l.slice(t,t+r).buffer,d;switch(s.dataType){case"float32":d=new Float32Array(c);break;case"float16":d=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":d=new Int32Array(c);break;case"uint32":d=new Uint32Array(c);break;case"int64":if(o){let h=Uo(new Uint8Array(c),"int64");d=new Int32Array(h.buffer),s.dataType="int32"}else d=new BigInt64Array(c);break;case"uint64":d=new BigUint64Array(c);break;case"int8":d=new Int8Array(c);break;case"int4":case"uint4":case"uint8":d=new Uint8Array(c);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(){}}}),Kd,fi,pi,pr,Zd,Eo,Ws,_i,mi,Ao,gi,wi,vi,Nf=pe(()=>{Gr(),Vy(),Uy(),dn(),Vr(),ci(),Cf(),Kd=(e,t)=>{Ae()._OrtInit(e,t)!==0&&xe("Can't initialize onnxruntime.")},fi=async e=>{Kd(e.wasm.numThreads,js(e.logLevel))},pi=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(qy(),Gs(Lf)).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,Zd=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)}},Eo=(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 c=r.HEAPU32[s/4+1],d=[];for(let h=0;h<c;h++){let p=Number(r.getValue(s+8+h*a,"*"));d.push(p!==0?r.UTF8ToString(p):Number(r.getValue(s+8+(h+c)*a,"*")))}return[i,l,d]}finally{r.stackRestore(n),s!==0&&r._OrtFree(s)}},Ws=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]},_i=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]=Ws(e);let a=0,o=0,i=0,l=[],c=[],d=[];try{if([o,l]=await Af(t),t?.externalData&&s.mountExternalData){let E=[];for(let C of t.externalData){let O=typeof C=="string"?C:C.path;E.push(hi(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,U=C?.deviceType,G=C?.powerPreference;O?s.currentContext=O:x?s.currentContext=await s.webnnCreateMLContext(x):s.currentContext=await s.webnnCreateMLContext({deviceType:U,powerPreference:G})}else s.currentContext=await s.webnnCreateMLContext();break}a=await s._OrtCreateSession(r,n,o),s.webgpuOnCreateSession?.(a),a===0&&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]=Zd(a),m=!!t?.enableGraphCapture,w=[],v=[],b=[],M=[],k=[];for(let E=0;E<h;E++){let[C,O,x]=Eo(a,E);C===0&&xe("Can't get an input name."),c.push(C);let U=s.UTF8ToString(C);w.push(U),b.push(O===0?{name:U,isTensor:!1}:{name:U,isTensor:!0,type:zs(O),shape:x})}for(let E=0;E<p;E++){let[C,O,x]=Eo(a,E+h);C===0&&xe("Can't get an output name."),d.push(C);let U=s.UTF8ToString(C);v.push(U),M.push(O===0?{name:U,isTensor:!1}:{name:U,isTensor:!0,type:zs(O),shape:x});{if(m&&t?.preferredOutputLocation===void 0){k.push("gpu-buffer");continue}let G=typeof t?.preferredOutputLocation=="string"?t.preferredOutputLocation:t?.preferredOutputLocation?.[U]??"cpu",W=s.webnnIsGraphOutput;if(G==="cpu"&&W&&W(a,U)){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=>Vo(E))}),pr.set(a,[a,c,d,A,m,!1]),[a,w,v,b,M]}catch(h){throw c.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?.()}},mi=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)},Ao=async(e,t,r,n,s,a,o=!1)=>{if(!e){t.push(0);return}let i=Ae(),l=i.PTR_SIZE,c=e[0],d=e[1],h=e[3],p=h,m,w;if(c==="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=nn(Or(c),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=nn(Or(c),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(c),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(c!=="string"&&k&&A){let E=i.UTF8ToString(s);if(k(n,E)||A(n,E)){let C=Or(c);w=nn(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 U=await O(n,C,d);x(U,new Uint8Array(M.buffer,M.byteOffset,M.byteLength)),m=U}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(c),m,w,b,d.length,Vo(p));M===0&&xe(`Can't create tensor for input/output. session=${n}, index=${a}.`),t.push(M)}finally{i.stackRestore(v)}},gi=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 c=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(),U=o.stackAlloc(v*i),G=o.stackAlloc(v*i),W=o.stackAlloc(b*i),J=o.stackAlloc(b*i);try{[M,k]=Ef(a),wr("wasm prepareInputOutputTensor");for(let V=0;V<v;V++)await Ao(r[V],A,C,e,d[t[V]],t[V],m);for(let V=0;V<b;V++)await Ao(s[V],E,C,e,h[n[V]],v+n[V],m);vr("wasm prepareInputOutputTensor");for(let V=0;V<v;V++)o.setValue(U+V*i,A[V],"*"),o.setValue(G+V*i,d[t[V]],"*");for(let V=0;V<b;V++)o.setValue(W+V*i,E[V],"*"),o.setValue(J+V*i,h[n[V]],"*");if(p&&!w){let{handle:V,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(V,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(V,h[L],E[F],0)!==0&&xe(`Can't bind pre-allocated output[${F}] for session=${e}.`)):o._OrtBindOutput(V,h[L],0,X[L])!==0&&xe(`Can't bind output[${F}] to ${ee[F]} for session=${e}.`)}vr("wasm bindInputsOutputs"),pr.set(e,[c,d,h,p,m,!0])}o.jsepOnRunStart?.(c),o.webnnOnRunStart?.(c);let q;p?q=await o._OrtRunWithBinding(c,p.handle,b,W,M):q=await o._OrtRun(c,G,U,v,J,b,W,M),q!==0&&xe("failed to call OrtRun().");let B=[],N=[];wr("wasm ProcessOutputTensor");for(let V=0;V<b;V++){let ee=Number(o.getValue(W+V*i,"*"));if(ee===E[V]||O.includes(E[V])){B.push(s[V]),ee!==E[V]&&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 ${V}.`);let le=i===4?"i32":"i64",Te=Number(o.getValue(F,le));K=o.getValue(F+i,"*");let Pe=o.getValue(F+i*2,"*"),ut=Number(o.getValue(F+i*3,le)),Ve=[];for(let be=0;be<ut;be++)Ve.push(Number(o.getValue(Pe+be*i,le)));o._OrtFree(Pe)!==0&&xe("Can't free memory for tensor dims.");let ze=Ve.reduce((be,fe)=>be*fe,1);z=zs(Te);let Ue=p?.outputPreferredLocations[n[V]];if(z==="string"){if(Ue==="gpu-buffer"||Ue==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let be=[];for(let fe=0;fe<ze;fe++){let je=o.getValue(K+fe*i,"*"),_e=o.getValue(K+(fe+1)*i,"*"),ye=fe===ze-1?void 0:_e-je;be.push(o.UTF8ToString(je,ye))}B.push([z,Ve,be,"cpu"])}else if(Ue==="gpu-buffer"&&ze>0){let be=o.webgpuGetBuffer;if(!be)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let fe=be(K),je=nn(Te,ze);if(je===void 0||!ui(z))throw new Error(`Unsupported data type: ${z}`);L=!0;{o.webgpuRegisterBuffer(fe,e,K);let _e=o.webgpuCreateDownloader(fe,je,e);B.push([z,Ve,{gpuBuffer:fe,download:async()=>{let ye=await _e();return new(Jn(z))(ye)},dispose:()=>{o._OrtReleaseTensor(ee)!==0&&xe("Can't release tensor.")}},"gpu-buffer"])}}else if(Ue==="ml-tensor"&&ze>0){let be=o.webnnEnsureTensor,fe=o.webnnIsGraphInputOutputTypeSupported;if(!be||!fe)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(nn(Te,ze)===void 0||!di(z))throw new Error(`Unsupported data type: ${z}`);if(!fe(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,Ve,!1);L=!0,B.push([z,Ve,{mlTensor:je,download:o.webnnCreateMLTensorDownloader(K,z),dispose:()=>{o.webnnReleaseTensorId(K),o._OrtReleaseTensor(ee)}},"ml-tensor"])}else if(Ue==="ml-tensor-cpu-output"&&ze>0){let be=o.webnnCreateMLTensorDownloader(K,z)(),fe=B.length;L=!0,N.push((async()=>{let je=[fe,await be];return o.webnnReleaseTensorId(K),o._OrtReleaseTensor(ee),je})()),B.push([z,Ve,[],"cpu"])}else{let be=Jn(z),fe=new be(ze);new Uint8Array(fe.buffer,fe.byteOffset,fe.byteLength).set(o.HEAPU8.subarray(K,K+fe.byteLength)),B.push([z,Ve,fe,"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,[c,d,h,p,m,!1]));for(let[V,ee]of await Promise.all(N))B[V][2]=ee;return vr("wasm ProcessOutputTensor"),B}finally{o.webnnOnRunEnd?.(c),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))}},wi=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)},vi=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,xt,Kr,$n,Gn,Ss,Co,Ps,Cr,Sr,eh,Df,zf,Bf,Rf,$f,Gf,Vf,Uf=pe(()=>{Gr(),Nf(),Vr(),ii(),_r=()=>!!Oe.wasm.proxy&&typeof document<"u",Kr=!1,$n=!1,Gn=!1,Ps=new Map,Cr=(e,t)=>{let r=Ps.get(e);r?r.push(t):Ps.set(e,[t])},Sr=()=>{if(Kr||!$n||Gn||!xt)throw new Error("worker not ready")},eh=e=>{switch(e.data.type){case"init-wasm":Kr=!1,e.data.err?(Gn=!0,Co[1](e.data.err)):($n=!0,Co[0]()),Ss&&(URL.revokeObjectURL(Ss),Ss=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Ps.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Df=async()=>{if(!$n){if(Kr)throw new Error("multiple calls to 'initWasm()' detected.");if(Gn)throw new Error("previous call to 'initWasm()' failed.");if(Kr=!0,_r())return new Promise((e,t)=>{xt?.terminate(),Tf().then(([r,n])=>{try{xt=n,xt.onerror=a=>t(a),xt.onmessage=eh,Co=[e,t];let s={type:"init-wasm",in:Oe};!s.in.wasm.wasmPaths&&(r||Go)&&(s.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.asyncify-BynIiDiv.wasm",import.meta.url).href}),xt.postMessage(s),Ss=r}catch(s){t(s)}},t)});try{await li(Oe.wasm),await fi(Oe),$n=!0}catch(e){throw Gn=!0,e}finally{Kr=!1}}},zf=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}};xt.postMessage(n)});await pi(Oe,e)},Bf=async e=>_r()?(Sr(),new Promise((t,r)=>{Cr("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};xt.postMessage(n,[e.buffer])})):Ws(e),Rf=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),xt.postMessage(s,a)})}else return _i(e,t)},$f=async e=>{if(_r())return Sr(),new Promise((t,r)=>{Cr("release",[t,r]);let n={type:"release",in:e};xt.postMessage(n)});mi(e)},Gf=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,c={type:"run",in:{sessionId:e,inputIndices:t,inputs:l,outputIndices:n,options:a}};xt.postMessage(c,vi(l))})}else return gi(e,t,r,n,s,a)},Vf=async e=>{if(_r())return Sr(),new Promise((t,r)=>{Cr("end-profiling",[t,r]);let n={type:"end-profiling",in:e};xt.postMessage(n)});wi(e)}}),So,th,jf,Hy=pe(()=>{Gr(),Uf(),dn(),oi(),Cf(),So=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},th=e=>{switch(e[3]){case"cpu":return new Ot(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!ui(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:s}=e[2];return Ot.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:s})}case"ml-tensor":{let t=e[0];if(!di(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:s}=e[2];return Ot.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:s})}default:throw new Error(`invalid data location: ${e[3]}`)}},jf=class{async fetchModelAndCopyToWasmMemory(e){return Bf(await hi(e))}async loadModel(e,t){Rr();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Rf(r,t),$r()}async dispose(){return $f(this.sessionId)}async run(e,t,r){Rr();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)=>So(h,()=>`input "${this.inputNames[s[p]]}"`)),l=a.map((h,p)=>h?So(h,()=>`output "${this.outputNames[o[p]]}"`):null),c=await Gf(this.sessionId,s,i,o,l,r),d={};for(let h=0;h<c.length;h++)d[this.outputNames[o[h]]]=a[h]??th(c[h]);return $r(),d}startProfiling(){}endProfiling(){Vf(this.sessionId)}}}),Wf={};es(Wf,{OnnxruntimeWebAssemblyBackend:()=>Wo,initializeFlags:()=>jo,wasmBackend:()=>qf});var jo,Wo,qf,Qy=pe(()=>{Gr(),Uf(),Hy(),jo=()=>{(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"?ky("node:os").cpus().length:navigator.hardwareConcurrency;Oe.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Wo=class{async init(e){jo(),await Df(),await zf(e)}async createInferenceSessionHandler(e,t){let r=new jf;return await r.loadModel(e,t),r}},qf=new Wo});Gr();Gr();Gr();var Xy="1.25.0-dev.20260228-6e72d31970",Yy=wf;{let e=(Qy(),Gs(Wf)).wasmBackend;Nr("webgpu",e,5),Nr("webnn",e,5),Nr("cpu",e,10),Nr("wasm",e,10)}Object.defineProperty(Oe.versions,"web",{value:Xy,enumerable:!0});const Jy=Object.freeze(Object.defineProperty({__proto__:null,get InferenceSession(){return ai},get TRACE(){return Vs},get TRACE_EVENT_BEGIN(){return wr},get TRACE_EVENT_END(){return vr},get TRACE_FUNC_BEGIN(){return Rr},get TRACE_FUNC_END(){return $r},get Tensor(){return Ot},default:Yy,get env(){return Oe},get registerBackend(){return Nr}},Symbol.toStringTag,{value:"Module"})),Ky=(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,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));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++]-c[0])*l[0],k=(e.data[p++]-c[1])*l[1],A=(e.data[m++]-c[2])*l[2],E=w===-1?255:(e.data[w++]-c[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")},Zy=(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 c,d;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?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])*c[0],n.data[w]=(e.data[k++]-d[1])*c[1],n.data[v]=(e.data[A++]-d[2])*c[2],n.data[b]=E===-1?255:(e.data[E++]-d[3])*c[3]}else throw new Error("Can not access image data");return n},Po=(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",c=r*n,d=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3);let h=4,p=0,m=1,w=2,v=3,b=0,M=c,k=c*2,A=-1;i==="RGB"&&(h=3,p=0,m=1,w=2,v=-1),l==="RGBA"?A=c*3:l==="RBG"?(b=0,k=c,M=c*2):l==="BGR"&&(k=0,M=c,b=c*2);for(let C=0;C<c;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 At("float32",d,[1,4,r,n]):new At("float32",d,[1,3,r,n])},eb=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")},c=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=c(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=c(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=c(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,Po(o,i)}else throw new Error("Can not access image data")}else{if(a)return new Promise((d,h)=>{const p=l(),m=c(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(Po(v.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return Po(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},tb=(e,t)=>{const{width:r,height:n,download:s,dispose:a}=t,o=[1,n,r,4];return new At({location:"texture",type:"float32",texture:e,dims:o,download:s,dispose:a})},rb=(e,t)=>{const{dataType:r,dims:n,download:s,dispose:a}=t;return new At({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},nb=(e,t)=>{const{dataType:r,dims:n,download:s,dispose:a}=t;return new At({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:s,dispose:a})},sb=(e,t,r)=>new At({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]}),an=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Bs=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let rh=!1;const ab=()=>{if(!rh){rh=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,n=typeof r<"u"&&r.from;e&&(an.set("int64",BigInt64Array),Bs.set(BigInt64Array,"int64")),t&&(an.set("uint64",BigUint64Array),Bs.set(BigUint64Array,"uint64")),n?(an.set("float16",r),Bs.set(r,"float16")):an.set("float16",Uint16Array)}},ob=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},ib=(e,t)=>{switch(e.location){case"cpu":return new At(e.type,e.data,t);case"cpu-pinned":return new At({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new At({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new At({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new At({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let At=class{constructor(t,r,n){ab();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=an.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 c=an.get(t);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t==="float16"&&c===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${c.name} as data.`);t==="uint64"||t==="int64"?i=c.from(r,BigInt):i=c.from(r)}else if(r instanceof c)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&&c!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${s} tensor's data must be type of ${c}`)}else if(l=r,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const c=typeof t[0];if(c==="string")s="string",i=t;else if(c==="boolean")s="bool",i=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(t instanceof Uint8ClampedArray)s="uint8",i=Uint8Array.from(t);else{const c=Bs.get(t.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);s=c,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=ob(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 eb(t,r)}static fromTexture(t,r){return tb(t,r)}static fromGpuBuffer(t,r){return rb(t,r)}static fromMLTensor(t,r){return nb(t,r)}static fromPinnedBuffer(t,r,n){return sb(t,r,n)}toDataURL(t){return Ky(this,t)}toImageData(t){return Zy(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 ib(this,t)}};const lb=At;var Fo={},cb=Object.defineProperty,hn=(e,t)=>{for(var r in t)cb(e,r,{get:t[r],enumerable:!0})},Et={},Xt={},ub={},db="4.0.0-next.5",ln=!Zf(Et),Hf=!Zf(Xt),qs=typeof self<"u"&&"caches"in self,hb=typeof globalThis.Deno<"u",Qf=hb&&qs&&!ln,Xf=typeof process<"u",Yf=Xf&&process?.release?.name==="node"&&!Qf,Jf=typeof window<"u"&&typeof window.document<"u",Kf=typeof self<"u"&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),fb=Yf||typeof navigator<"u"&&"gpu"in navigator,pb=typeof navigator<"u"&&"ml"in navigator,_b=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",mb=()=>{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},gb=mb(),Se=Object.freeze({IS_BROWSER_ENV:Jf,IS_WEBWORKER_ENV:Kf,IS_WEB_CACHE_AVAILABLE:qs,IS_WEBGPU_AVAILABLE:fb,IS_WEBNN_AVAILABLE:pb,IS_SAFARI:gb,IS_PROCESS_AVAILABLE:Xf,IS_NODE_ENV:Yf,IS_FS_AVAILABLE:ln,IS_PATH_AVAILABLE:Hf,IS_CRYPTO_AVAILABLE:_b}),yi=ln&&Hf,Hs="./";if(yi){const e=Object(import.meta).url;e?Hs=Xt.dirname(Xt.dirname(ub.fileURLToPath(e))):typeof __dirname<"u"&&(Hs=Xt.dirname(__dirname))}var wb=yi?Xt.join(Hs,"/.cache/"):null,nh="/models/",vb=yi?Xt.join(Hs,nh):nh,yb=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,Nt=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),sh=Nt.WARNING,ve={version:db,backends:{onnx:{}},get logLevel(){return sh},set logLevel(e){sh=e,ve.backends.onnx?.setLogLevel?.(e)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(Jf||Kf||Qf),localModelPath:vb,useFS:ln,useBrowserCache:qs,useFSCache:ln,cacheDir:wb,useCustomCache:!1,customCache:null,useWasmCache:qs||ln,cacheKey:"transformers-cache",fetch:yb};function Zf(e){return Object.keys(e).length===0}function Dr(e,t){e&&e(t)}function bb(e){return Number.isInteger(e)||typeof e=="bigint"}function ah(e){return e==null||e===-1}function oh(e){const t=[];let r=e;for(;Array.isArray(r);)t.push(r.length),r=r[0];return t}function Dt(...e){return Array.prototype.concat.apply([],e)}function Mb(...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 ft(e,t){return Object.assign({},...t.map(r=>{if(e[r]!==void 0)return{[r]:e[r]}}))}function xb(e,t){let r=0;for(const n of e)n===t&&++r;return r}var oe={error(...e){ve.logLevel<=Nt.ERROR&&console.error(...e)},warn(...e){ve.logLevel<=Nt.WARNING&&console.warn(...e)},info(...e){ve.logLevel<=Nt.INFO&&console.log(...e)},debug(...e){ve.logLevel<=Nt.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},Tb=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){const t=Object.create(null);for(const r of e){let n=t;for(let s=0;s<r.length;++s){const a=r[s];n=n[a]??=Object.create(null)}n.end=r}return t}split(e){const t=[],r=e.length;let n=0,s=0;for(;s<r;){let a=this.trie,o=null,i=s;for(;i<r&&(a=a[e[i]]);)a.end&&(o=a.end),++i;o?(s>n&&t.push(e.slice(n,s)),t.push(o),s+=o.length,n=s):++s}return n<r&&t.push(e.slice(n)),t}},ih=Tb,kb=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}},Eb=kb,ep=(()=>{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]]))})(),Ab=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[r,t])),Cb=Ab(ep),lh=".,!?…。,、।۔،",Sb=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],["(?>\\p{Nd}{510})","(?:\\p{Nd}{510})"],["\\p{Nd}{3}+","(?:\\p{Nd}{3})+"],["\\G",""],[` ?[^(\\s|[${lh}])]+`,` ?[^\\s${lh}]+`]]),Xs="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",bi=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"),sa=(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 Sb)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=Pb(e.String);return new RegExp(t?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",e),null},Pb=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Fb=(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},Ib=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,Lb=e=>Number.isInteger(e)||typeof e=="bigint",Ob=e=>{let t=0;for(const r of e)++t;return t},Nb=e=>tp(e.toLowerCase()),zt=(...e)=>Array.prototype.concat.apply([],e),Mi=e=>new Map(Object.entries(e)),Db=(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},tp=e=>e.replace(/\p{M}/gu,""),ch=(e,t,r=[])=>{if(!e||Array.isArray(e)||typeof e!="object")return`${t} must be a valid object`;for(const n of r)if(!(n in e))return`${t} must contain a "${n}" property`;return null},zb=e=>e.match(/\S+/g)||[],Bb=class{constructor(){const e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},ts=Bb,Rb=class extends ts{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},or=Rb,$b=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);Ib(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}},Gb=$b,Vb=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}},Ub=Vb,jb=class extends or{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(t=>rp(t))}normalize(e){return this.normalizers.reduce((t,r)=>r?r.normalize(t):t,e)}},Wb=jb,qb=class extends or{normalize(e){const t=sa(this.config.pattern??{});return t===null?e:e.replaceAll(t,this.config.content??"")}},Hb=qb,Qb=class extends or{constructor(){super(...arguments),this.form="NFC"}normalize(e){return e=e.normalize(this.form),e}},aa=Qb,Xb=class extends aa{constructor(){super(...arguments),this.form="NFC"}},Yb=Xb,Jb=class extends aa{constructor(){super(...arguments),this.form="NFD"}},Kb=Jb,Zb=class extends aa{constructor(){super(...arguments),this.form="NFKC"}},e0=Zb,t0=class extends aa{constructor(){super(...arguments),this.form="NFKD"}},r0=t0,n0=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}},s0=n0,a0=class extends or{normalize(e){return tp(e)}},o0=a0,i0=class extends or{normalize(e){return e.toLowerCase()}},l0=i0,c0=class extends or{normalize(e){return e=this.config.prepend+e,e}},u0=c0;function d0(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new Gb(e);case"Precompiled":return new Ub(e);case"Sequence":return new Wb(e);case"Replace":return new Hb(e);case"NFC":return new Yb(e);case"NFD":return new Kb(e);case"NFKC":return new e0(e);case"NFKD":return new r0(e);case"Strip":return new s0(e);case"StripAccents":return new o0(e);case"Lowercase":return new l0(e);case"Prepend":return new u0(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}var rp=d0,h0=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)}},Rt=h0,f0=class extends Rt{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=ep,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(""))}},p0=f0,_0=class extends Rt{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},m0=_0,g0=class extends Rt{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]}},w0=g0,v0=class extends Rt{constructor(e){super(),this.config=e,this.pattern=sa(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):Db(e,this.pattern)}},y0=v0,b0=class extends Rt{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${Xs}]+|[${Xs}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},M0=b0,x0=class extends Rt{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)||[]}},T0=x0,k0=class extends Rt{constructor(){super(),this.pattern=new RegExp(`[^\\s${Xs}]+|[${Xs}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},E0=k0,A0=class extends Rt{constructor(e){super(),this.config=e,this.pattern=sa(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??"")]}},C0=A0,S0=class extends Rt{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(t=>np(t))}pre_tokenize_text(e,t){return this.tokenizers.reduce((r,n)=>n?n.pre_tokenize(r,t):r,[e])}},P0=S0,F0=class extends Rt{pre_tokenize_text(e){return zb(e)}},I0=F0,L0=class extends Rt{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}},O0=L0;function N0(e){if(e===null)return null;switch(e.type){case"BertPreTokenizer":return new E0;case"Sequence":return new P0(e);case"Whitespace":return new m0;case"WhitespaceSplit":return new I0;case"Metaspace":return new w0(e);case"ByteLevel":return new p0(e);case"Split":return new y0(e);case"Punctuation":return new M0(e);case"Digits":return new T0(e);case"Replace":return new C0(e);case"FixedLength":return new O0(e);default:throw new Error(`Unknown PreTokenizer type: ${e.type}`)}}var np=N0,D0=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=Fb(t,this.tokens_to_ids,this.unk_token_id)),t}},oa=D0,z0=class extends oa{constructor(e){super(e),this.max_input_chars_per_word=100,this.tokens_to_ids=Mi(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 c=n.slice(a,i).join("");if(a>0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){l=c;break}--i}if(l===null){s=!0;break}o.push(l),a=i}s?t.push(this.unk_token):t.push(...o)}return t}},uh=z0,dh=class sp{constructor(t,r){this.is_leaf=t,this.children=r}static default(){return new sp(!1,new Map)}},B0=class{constructor(){this.root=dh.default()}extend(e){for(const t of e)this.push(t)}push(e){let t=this.root;for(const r of e){let n=t.children.get(r);n===void 0&&(n=dh.default(),t.children.set(r,n)),t=n}t.is_leaf=!0}*common_prefix_search(e){let t=this.root;if(t===void 0)return;let r="";for(const n of e){if(r+=n,t=t.children.get(n),t===void 0)return;t.is_leaf&&(yield r)}}},R0=B0,Io=class ap{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 ap(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},$0=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 Io(this.bos_token_id??0,0,0,0,0),s=new Io(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 Io(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 c of this.end_nodes[t]){const d=c.backtrace_score+o.score;(l===null||d>i)&&(l=c.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)}},G0=$0;function V0(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 U0=class extends oa{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=V0(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new R0,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),c=this.scores[l],d=Ob(i);e.insert(n,d,c,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 G0(e,this.bos_token_id,this.eos_token_id);return this.populate_nodes(t),t.tokens()}encode(e){const t=[];for(const r of e){const n=this.tokenize(r);t.push(...n)}return t}},hh=U0,j0=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}},W0=j0,q0=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()}},H0=q0,Q0=class extends oa{constructor(e){super(e),this.tokens_to_ids=Mi(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 H0(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 W0((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 c={...i.prev};i.prev.deleted=!0,i.prev=c,c.prev?c.prev.next=c:a=c}const l={token:i.token+i.next.token,bias:i.bias,prev:i.prev,next:i.next.next};l.prev?(l.prev.next=l,this.add_node(s,l.prev)):a=l,l.next&&(l.next.prev=l,this.add_node(s,l))}for(let i=a;i!==null;i=i.next)n.push(i.token)}else n=r;if(this.continuing_subword_suffix)for(let s=0;s<n.length-1;++s)n[s]+=this.continuing_subword_suffix;return e.length<this.max_length_to_cache&&this.cache.put(e,n),n}add_node(e,t){const r=this.bpe_ranks.get(JSON.stringify([t.token,t.next.token]));r!==void 0&&(t.score=r+t.bias,e.push(t))}encode(e){const t=[];for(const r of e){if(this.ignore_merges&&this.tokens_to_ids.has(r)){t.push(r);continue}const n=this.bpe(r);for(const s of n)if(this.tokens_to_ids.has(s))t.push(s);else if(this.byte_fallback){const a=Array.from(this.text_encoder.encode(s)).map(o=>`<0x${o.toString(16).toUpperCase().padStart(2,"0")}>`);a.every(o=>this.tokens_to_ids.has(o))?t.push(...a):t.push(this.unk_token)}else t.push(this.unk_token)}return t}},fh=Q0,X0=class extends oa{constructor(e,t){super(e);const r=e.vocab;this.tokens_to_ids=Mi(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}},Y0=X0;function J0(e,t){switch(e.type){case"WordPiece":return new uh(e);case"Unigram":return new hh(e,t.eos_token);case"BPE":return new fh(e);default:if(e.vocab)return Array.isArray(e.vocab)?new hh(e,t.eos_token):Object.hasOwn(e,"continuing_subword_prefix")&&Object.hasOwn(e,"unk_token")?Object.hasOwn(e,"merges")?new fh(e):new uh(e):new Y0(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 K0=J0,Z0=class extends ts{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},rs=Z0,eM=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=zt(s,e),a=zt(a,new Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id==="B"&&(s=zt(s,t),a=zt(a,new Array(t.length).fill(o.Sequence.type_id))));return{tokens:s,token_type_ids:a}}},tM=eM,rM=class extends rs{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},nM=rM,sM=class extends rs{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,r=!0){r&&(e=zt([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=zt(e,s,t,a),n=zt(n,new Array(t.length+s.length+a.length).fill(1))}return{tokens:e,token_type_ids:n}}},aM=sM,oM=class extends rs{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,r=!0){r&&(e=zt([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=zt(e,s,t,a),n=zt(n,new Array(t.length+s.length+a.length).fill(1))}return{tokens:e,token_type_ids:n}}},iM=oM,lM=class extends rs{constructor(e){super(e),this.processors=(e.processors??[]).map(t=>op(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}},cM=lM;function uM(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new tM(e);case"ByteLevel":return new nM(e);case"BertProcessing":return new aM(e);case"RobertaProcessing":return new iM(e);case"Sequence":return new cM(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}var op=uM,dM=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("")}},$t=dM,hM=class extends $t{constructor(e){super(e),this.byte_decoder=Cb,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}},fM=hM,pM=class extends $t{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=bi(t)),t})}},_M=pM,mM=class extends $t{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}},gM=mM,wM=class extends $t{constructor(e){super(e),this.suffix=e.suffix??""}decode_chain(e){return e.map((t,r)=>t.replaceAll(this.suffix,r===e.length-1?"":" "))}},vM=wM,yM=class extends $t{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=bi(n).replaceAll(this.word_delimiter_token," ").trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}},bM=yM,MM=class extends $t{constructor(e){super(e),this.decoders=(e.decoders??[]).map(t=>ip(t))}decode_chain(e){return this.decoders.reduce((t,r)=>r.decode_chain(t),e)}},xM=MM,TM=class extends $t{decode_chain(e){const t=sa(this.config.pattern),r=this.config.content??"";return t===null?e:e.map(n=>n.replaceAll(t,r))}},kM=TM,EM=class extends $t{decode_chain(e){return[e.join("")]}},AM=EM,CM=class extends $t{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)})}},SM=CM,PM=class extends $t{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}},FM=PM;function IM(e){if(e===null)return null;switch(e.type){case"ByteLevel":return new fM(e);case"WordPiece":return new _M(e);case"Metaspace":return new gM(e);case"BPEDecoder":return new vM(e);case"CTC":return new bM(e);case"Sequence":return new xM(e);case"Replace":return new kM(e);case"Fuse":return new AM(e);case"Strip":return new SM(e);case"ByteFallback":return new FM(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}var ip=IM,LM=class{constructor(e,t){const r=ch(e,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);const n=ch(t,"Config");if(n)throw new Error(n);this.tokenizer=e,this.config=t,this.normalizer=rp(this.tokenizer.normalizer),this.pre_tokenizer=np(this.tokenizer.pre_tokenizer),this.model=K0(this.tokenizer.model,this.config),this.post_processor=op(this.tokenizer.post_processor),this.decoder=ip(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 Eb(o);if(this.added_tokens.push(i),this.model.tokens_to_ids.set(i.content,i.id),this.model.vocab[i.id]=i.content,i.special&&(this.special_tokens.push(i.content),this.all_special_ids.push(i.id)),this.added_tokens_map.set(i.content,i),i.normalized&&this.normalizer!==null){const l=this.normalizer(i.content);a.push(l),this.added_tokens_map.set(l,i)}else s.push(i.content)}(this.config.additional_special_tokens??[]).forEach(o=>{this.special_tokens.includes(o)||this.special_tokens.push(o)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new ih(s),this.splitter_normalized=new ih(a),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:n=null}={}){const{tokens:s,token_type_ids:a}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}),o=s.map(l=>this.added_tokens_map.get(l)?.id??this.model.tokens_to_ids.get(l)??this.model.unk_token_id),i={ids:o,tokens:s,attention_mask:new Array(o.length).fill(1)};return n&&a&&(i.token_type_ids=a),i}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!Lb(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=bi(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=Nb(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:zt(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}},OM=LM,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"}),Tt=class{constructor(e,t){this.value=e,this.type=t}};function ph(e){return/\w/.test(e)}function Vn(e){return/[0-9]/.test(e)}function _h(e){return/\s/.test(e)}var NM=[["{%",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]],DM=new Map([["n",`
10
+ `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function zM(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 BM(e,t={}){const r=[],n=zM(e,t);let s=0,a=0;const o=c=>{let d="";for(;c(n[s]);){if(n[s]==="\\"){if(++s,s>=n.length)throw new SyntaxError("Unexpected end of input");const h=n[s++],p=DM.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 c=r.at(-1);c&&c.type===D.Text&&(c.value=c.value.trimEnd(),c.value===""&&r.pop())},l=()=>{for(;s<n.length&&_h(n[s]);)++s};e:for(;s<n.length;){const c=r.at(-1)?.type;if(c===void 0||c===D.CloseStatement||c===D.CloseExpression||c===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 Tt(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 Tt(p,D.Comment)),s+=2,m&&l();continue}if(n.slice(s,s+3)==="{%-"){i(),r.push(new Tt("{%",D.OpenStatement)),s+=3;continue}if(n.slice(s,s+3)==="{{-"){i(),r.push(new Tt("{{",D.OpenExpression)),a=0,s+=3;continue}if(o(_h),n.slice(s,s+3)==="-%}"){r.push(new Tt("%}",D.CloseStatement)),s+=3,l();continue}if(n.slice(s,s+3)==="-}}"){r.push(new Tt("}}",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(Vn);r.push(new Tt(`${d}${p}`,p.length>0?D.NumericLiteral:D.UnaryOperator));continue}}}for(const[h,p]of NM){if(h==="}}"&&a>0)continue;if(n.slice(s,s+h.length)===h){r.push(new Tt(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 Tt(h,D.StringLiteral)),++s;continue}if(Vn(d)){let h=o(Vn);if(n[s]==="."&&Vn(n[s+1])){++s;const p=o(Vn);h=`${h}.${p}`}r.push(new Tt(h,D.NumericLiteral));continue}if(ph(d)){const h=o(ph);r.push(new Tt(h,D.Identifier));continue}throw new SyntaxError(`Unexpected character: ${d}`)}return r}var Gt=class{type="Statement"},RM=class extends Gt{constructor(e){super(),this.body=e}type="Program"},$M=class extends Gt{constructor(e,t,r){super(),this.test=e,this.body=t,this.alternate=r}type="If"},GM=class extends Gt{constructor(e,t,r,n){super(),this.loopvar=e,this.iterable=t,this.body=r,this.defaultBlock=n}type="For"},VM=class extends Gt{type="Break"},UM=class extends Gt{type="Continue"},jM=class extends Gt{constructor(e,t,r){super(),this.assignee=e,this.value=t,this.body=r}type="Set"},WM=class extends Gt{constructor(e,t,r){super(),this.name=e,this.args=t,this.body=r}type="Macro"},qM=class extends Gt{constructor(e){super(),this.value=e}type="Comment"},bt=class extends Gt{type="Expression"},HM=class extends bt{constructor(e,t,r){super(),this.object=e,this.property=t,this.computed=r}type="MemberExpression"},mh=class extends bt{constructor(e,t){super(),this.callee=e,this.args=t}type="CallExpression"},Zr=class extends bt{constructor(e){super(),this.value=e}type="Identifier"},fn=class extends bt{constructor(e){super(),this.value=e}type="Literal"},QM=class extends fn{type="IntegerLiteral"},XM=class extends fn{type="FloatLiteral"},gh=class extends fn{type="StringLiteral"},YM=class extends fn{type="ArrayLiteral"},wh=class extends fn{type="TupleLiteral"},JM=class extends fn{type="ObjectLiteral"},Un=class extends bt{constructor(e,t,r){super(),this.operator=e,this.left=t,this.right=r}type="BinaryExpression"},KM=class extends bt{constructor(e,t){super(),this.operand=e,this.filter=t}type="FilterExpression"},ZM=class extends Gt{constructor(e,t){super(),this.filter=e,this.body=t}type="FilterStatement"},ex=class extends bt{constructor(e,t){super(),this.lhs=e,this.test=t}type="SelectExpression"},tx=class extends bt{constructor(e,t,r){super(),this.operand=e,this.negate=t,this.test=r}type="TestExpression"},rx=class extends bt{constructor(e,t){super(),this.operator=e,this.argument=t}type="UnaryExpression"},nx=class extends bt{constructor(e=void 0,t=void 0,r=void 0){super(),this.start=e,this.stop=t,this.step=r}type="SliceExpression"},sx=class extends bt{constructor(e,t){super(),this.key=e,this.value=t}type="KeywordArgumentExpression"},ax=class extends bt{constructor(e){super(),this.argument=e}type="SpreadExpression"},ox=class extends Gt{constructor(e,t,r){super(),this.call=e,this.callerArgs=t,this.body=r}type="CallStatement"},ix=class extends bt{constructor(e,t,r){super(),this.condition=e,this.trueExpr=t,this.falseExpr=r}type="Ternary"};function lx(e){const t=new RM([]);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 qM(e[r++].value);case D.Text:return c();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 c(){return new gh(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 Pe=new mh(K,le);L=new ox(Pe,z,Te);break}case"break":++r,n(D.CloseStatement,"Expected closing statement token"),L=new VM;break;case"continue":++r,n(D.CloseStatement,"Expected closing statement token"),L=new UM;break;case"filter":{++r;let z=X();z instanceof Zr&&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 ZM(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 jM(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 $M(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 WM(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 wh(z):z[0]}function b(){const F=v(!0);if(!(F instanceof Zr||F instanceof wh))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 GM(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 ix(L,F,z)}else return new ex(F,L)}return F}function A(){let F=E();for(;l("or");){const L=e[r];++r;const z=E();F=new Un(L,F,z)}return F}function E(){let F=C();for(;l("and");){const L=e[r];++r;const z=C();F=new Un(L,F,z)}return F}function C(){let F;for(;l("not");){const L=e[r];++r;const z=C();F=new rx(L,z)}return F??O()}function O(){let F=x();for(;;){let L;if(l("not","in"))L=new Tt("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 Un(L,F,z)}return F}function x(){let F=N();for(;o(D.AdditiveBinaryOperator);){const L=e[r];++r;const z=N();F=new Un(L,F,z)}return F}function U(){const F=B(X());return o(D.OpenParen)?G(F):F}function G(F){let L=new mh(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 ax(z)}else if(L=M(),o(D.Equals)){if(++r,!(L instanceof Zr))throw new SyntaxError("Expected identifier for keyword argument");const z=M();L=new sx(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 nx(...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 HM(F,z,K)}return F}function N(){let F=V();for(;o(D.MultiplicativeBinaryOperator);){const L=e[r++],z=V();F=new Un(L,F,z)}return F}function V(){let F=ee();for(;l("is");){++r;const L=l("not");L&&++r;const z=X();if(!(z instanceof Zr))throw new SyntaxError("Expected identifier for the test");F=new tx(F,L,z)}return F}function ee(){let F=U();for(;o(D.Pipe);){++r;let L=X();if(!(L instanceof Zr))throw new SyntaxError("Expected identifier for the filter");o(D.OpenParen)&&(L=G(L)),F=new KM(F,L)}return F}function X(){const F=e[r++];switch(F.type){case D.NumericLiteral:{const L=F.value;return L.includes(".")?new XM(Number(L)):new QM(Number(L))}case D.StringLiteral:{let L=F.value;for(;o(D.StringLiteral);)L+=e[r++].value;return new gh(L)}case D.Identifier:return new Zr(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 YM(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 JM(L)}default:throw new SyntaxError(`Unexpected token: ${F.type}`)}}for(;r<e.length;)t.body.push(a());return t}function cx(e,t,r=1){if(t===void 0&&(t=e,e=0),r===0)throw new Error("range() step must not be zero");const n=[];if(r>0)for(let s=e;s<t;s+=r)n.push(s);else for(let s=e;s>t;s+=r)n.push(s);return n}function vh(e,t,r,n=1){const s=Math.sign(n);s>=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),r=(r??=e.length)<0?Math.max(e.length+r,0):Math.min(r,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),r=(r??=-1)<-1?Math.max(e.length+r,-1):Math.min(r,e.length-1));const a=[];for(let o=t;s*o<s*r;o+=n)a.push(e[o]);return a}function ux(e){return e.replace(/\b\w/g,t=>t.toUpperCase())}function dx(e){return hx(new Date,e)}function hx(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 fx(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function px(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(fx(t),"gu");return e.replaceAll(a,o=>s>0?(--s,r):o)}var yh=class extends Error{},bh=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 Ie(()=>new Y(this.value.toUpperCase()))],["lower",new Ie(()=>new Y(this.value.toLowerCase()))],["strip",new Ie(()=>new Y(this.value.trim()))],["title",new Ie(()=>new Y(ux(this.value)))],["capitalize",new Ie(()=>new Y(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new ie(this.value.length)],["rstrip",new Ie(()=>new Y(this.value.trimEnd()))],["lstrip",new Ie(()=>new Y(this.value.trimStart()))],["startswith",new Ie(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 Ie(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 Ie(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 Ie(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(px(this.value,t.value,r.value,n.value))})]])},ne=class extends Yt{type="BooleanValue"},_x=/[\x7f-\uffff]/g;function Mh(e){return e.replace(_x,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,c;switch(o?[l,c]=o:s?(l=",",c=": "):(l=", ",c=": "),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=Mh(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=Mh(M));const k=`${M}${c}${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 Ie(([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 Ie(()=>this.items())],["keys",new Ie(()=>this.keys())],["values",new Ie(()=>this.values())],["dictsort",new Ie(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 c=s.value==="key"?0:1,d=i.value[c],h=l.value[c],p=qo(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)}},xh=class extends ge{type="TupleValue"},Ie=class extends Yt{type="FunctionValue"},Ne=class extends Yt{type="NullValue"},Fe=class extends Yt{type="UndefinedValue"},Fr=class{constructor(e){this.parent=e}variables=new Map([["namespace",new Ie(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 Ie],["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,Rs(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 Fe}catch{return new Fe}}};function mx(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",cx),e.set("strftime_now",dx),e.set("True",!0),e.set("False",!1),e.set("None",null)}function Th(e,t){const r=t.split(".");let n=e;for(const s of r)if(n instanceof rt)n=n.value.get(s)??new Fe;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 Fe}else return new Fe;return n}function qo(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 Fe&&t instanceof Fe)return 0;if(e instanceof Fe||t instanceof Fe)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 gx=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 Fe||n instanceof Fe){if(n instanceof Fe&&["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)=>qo(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 Ie)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 Ie?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 c=a.get("separators")??new Ne;let d=null;if(c instanceof ge||c instanceof xh){if(c.value.length!==2)throw new Error("separators must be a tuple of two strings");const[h,p]=c.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(!(c 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(c=>c.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 Fe||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 c=a.at(2)??o.get("attribute")??new Ne;if(!(c instanceof Y||c instanceof ie||c instanceof Ne))throw new Error("attribute must be a string, integer, or null");const d=h=>{if(c instanceof Ne)return h;const p=c instanceof ie?String(c.value):c.value;return Th(h,p)};return new ge(e.value.slice().sort((h,p)=>{const m=d(h),w=d(p),v=qo(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 c;if(i){const h=r.tests.get(i.value);if(!h)throw new Error(`Unknown test: ${i.value}`);c=h}else c=(...h)=>h[0].__bool__().value;const d=e.value.filter(h=>{const p=h.value.get(o.value),m=p?c(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(c=>{if(!(c instanceof rt))throw new Error("items in map must be an object");const d=Th(c,o.value);return d instanceof Fe?i??new Fe: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),c=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||!c.value&&m.length===0?m:h+m);return new Y(p.join(`
16
+ `))}case"replace":{const a=e.builtins.get("replace");if(!(a instanceof Ie))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 Ie){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 Fe}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 Fe))throw new Error("Slice start must be numeric or undefined");if(!(s instanceof ie||s instanceof Fe))throw new Error("Slice stop must be numeric or undefined");if(!(a instanceof ie||a instanceof Fe))throw new Error("Slice step must be numeric or undefined");return e instanceof ge?new ge(vh(e.value,n.value,s.value,a.value)):new Y(vh(Array.from(e.value),n.value,s.value,a.value).join(""))}evaluateMemberExpression(e,t){const r=this.evaluate(e.object,t);let n;if(e.computed){if(e.property.type==="SliceExpression")return this.evaluateSliceExpression(r,e.property,t);n=this.evaluate(e.property,t)}else n=new Y(e.property.value);let s;if(r instanceof rt){if(!(n instanceof Y))throw new Error(`Cannot access property with non-string: got ${n.type}`);s=r.value.get(n.value)??r.builtins.get(n.value)}else if(r instanceof 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 Fe}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 c=e.iterable;s=this.evaluate(c.lhs,r),n=c.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 c=0;c<s.value.length;++c){const d=new Fr(r),h=s.value[c];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 c=0;c<a.length;++c){const d=new Map([["index",new ie(c+1)],["index0",new ie(c)],["revindex",new ie(a.length-c)],["revindex0",new ie(a.length-c-1)],["first",new ne(c===0)],["last",new ne(c===a.length-1)],["length",new ie(a.length)],["previtem",c>0?a[c-1]:new Fe],["nextitem",c<a.length-1?a[c+1]:new Fe]]);r.setVariable("loop",new rt(d)),o[c](r);try{const h=this.evaluateBlock(e.body,r);i+=h.value}catch(h){if(h instanceof bh)continue;if(h instanceof yh)break;throw h}l=!1}if(l){const c=this.evaluateBlock(e.defaultBlock,r);i+=c.value}return new Y(i)}evaluateMacro(e,t){return t.setVariable(e.name.value,new Ie((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 c=i;if(!l)throw new Error(`Missing positional argument: ${c.value}`);s.setVariable(c.value,l)}else if(i.type==="KeywordArgumentExpression"){const c=i,d=l??a?.value.get(c.key.value)??this.evaluate(c.value,s);s.setVariable(c.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 Ie((i,l)=>{const c=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}`);c.setVariable(h.value,i[d]??new Fe)}return this.evaluateBlock(e.body,c)}),[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 Fe;switch(e.type){case"Program":return this.evalProgram(e,t);case"Set":return this.evaluateSet(e,t);case"If":return this.evaluateIf(e,t);case"For":return this.evaluateFor(e,t);case"Macro":return this.evaluateMacro(e,t);case"CallStatement":return this.evaluateCallStatement(e,t);case"Break":throw new yh;case"Continue":throw new bh;case"IntegerLiteral":return new 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 xh(e.value.map(r=>this.evaluate(r,t)));case"ObjectLiteral":{const r=new Map;for(const[n,s]of e.value){const a=this.evaluate(n,t);if(!(a instanceof Y))throw new Error(`Object keys must be strings: got ${a.type}`);r.set(a.value,this.evaluate(s,t))}return new rt(r)}case"Identifier":return this.evaluateIdentifier(e,t);case"CallExpression":return this.evaluateCallExpression(e,t);case"MemberExpression":return this.evaluateMemberExpression(e,t);case"UnaryExpression":return this.evaluateUnaryExpression(e,t);case"BinaryExpression":return this.evaluateBinaryExpression(e,t);case"FilterExpression":return this.evaluateFilterExpression(e,t);case"FilterStatement":return this.evaluateFilterStatement(e,t);case"TestExpression":return this.evaluateTestExpression(e,t);case"SelectExpression":return this.evaluateSelectExpression(e,t);case"Ternary":return this.evaluateTernaryExpression(e,t);case"Comment":return new Ne;default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};function Rs(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 Fe;case"object":return e===null?new Ne:Array.isArray(e)?new ge(e.map(Rs)):new rt(new Map(Object.entries(e).map(([t,r])=>[t,Rs(r)])));case"function":return new Ie((t,r)=>{const n=e(...t.map(s=>s.value))??null;return Rs(n)});default:throw new Error(`Cannot convert to runtime value: ${e}`)}}var qe=`
17
+ `,wx="{%- ",vx=" -%}";function yx(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 bx(e,t=" "){const r=typeof t=="number"?" ".repeat(t):t;return Bt(e.body,0,r).replace(/\n$/,"")}function et(...e){return wx+e.join(" ")+vx}function Bt(e,t,r){return e.map(n=>Mx(n,t,r)).join(qe)}function Mx(e,t,r){const n=r.repeat(t);switch(e.type){case"Program":return Bt(e.body,t,r);case"If":return xx(e,t,r);case"For":return Tx(e,t,r);case"Set":return kx(e,t,r);case"Macro":return Ex(e,t,r);case"Break":return n+et("break");case"Continue":return n+et("continue");case"CallStatement":return Ax(e,t,r);case"FilterStatement":return Cx(e,t,r);case"Comment":return n+"{# "+e.value+" #}";default:return n+"{{- "+we(e)+" -}}"}}function xx(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+Bt(s[0].body,t+1,r);for(let i=1;i<s.length;++i)o+=qe+n+et("elif",we(s[i].test))+qe+Bt(s[i].body,t+1,r);return a&&a.alternate.length>0&&(o+=qe+n+et("else")+qe+Bt(a.alternate,t+1,r)),o+=qe+n+et("endif"),o}function Tx(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+Bt(e.body,t+1,r);return e.defaultBlock.length>0&&(a+=qe+n+et("else")+qe+Bt(e.defaultBlock,t+1,r)),a+=qe+n+et("endfor"),a}function kx(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+Bt(e.body,t+1,r)+qe+n+et("endset")}function Ex(e,t,r){const n=r.repeat(t),s=e.args.map(we).join(", ");return n+et("macro",`${e.name.value}(${s})`)+qe+Bt(e.body,t+1,r)+qe+n+et("endmacro")}function Ax(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+=Bt(e.body,t+1,r)+qe,o+=n+et("endcall"),o}function Cx(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+=Bt(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=yx(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 Sx=class{parsed;constructor(e){const t=BM(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=lx(t)}render(e){const t=new Fr;if(mx(t),e)for(const[s,a]of Object.entries(e))t.set(s,a);return new gx(t).run(this.parsed).value}format(e){return bx(this.parsed,e?.indent||" ")}},St=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")}},Px={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"},Ys=class lp{constructor(t){if(this.filePath=t,this.headers=new Headers,this.exists=Et.existsSync(t),this.exists){this.status=200,this.statusText="OK";let r=Et.statSync(t);this.headers.set("content-length",r.size.toString()),this.updateContentType();const n=Et.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",Px[t]??"application/octet-stream")}clone(){let t=new lp(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 Et.promises.readFile(this.filePath)).buffer}async blob(){const t=await Et.promises.readFile(this.filePath);return new Blob([t],{type:this.headers.get("content-type")})}async text(){return await Et.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},cp=class{constructor(e){this.path=e}async match(e){let t=Xt.join(this.path,e),r=new Ys(t);if(r.exists)return r}async put(e,t,r=void 0){let n=Xt.join(this.path,e);try{const s=t.headers.get("Content-Length"),a=parseInt(s??"0");let o=0;await Et.promises.mkdir(Xt.dirname(n),{recursive:!0});const i=Et.createWriteStream(n),l=t.body.getReader();for(;;){const{done:c,value:d}=await l.read();if(c)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 Et.promises.unlink(n)}catch{}throw s}}async delete(e){let t=Xt.join(this.path,e);try{return await Et.promises.unlink(t),!0}catch{return!1}}},Fx={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"},kh=100,Ix=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Fs(...e){return e=e.map((t,r)=>(r&&(t=t.replace(new RegExp("^/"),"")),r!==e.length-1&&(t=t.replace(new RegExp("/$"),"")),t)),e.join("/")}function 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 Lx(e){return!(!Ix.test(e)||e.includes("..")||e.includes("--")||e.endsWith(".git")||e.endsWith(".ipynb"))}function Ox(e,t,r){if(!r)return null;const n=Fx[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${n}: "${t}".`)}async function Nx(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:c,value:d}=await i.read();if(c)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 ns(e=null){let t=null;if(ve.useCustomCache){if(!ve.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!ve.customCache.match||!ve.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=ve.customCache}if(!t&&ve.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{t=await caches.open(ve.cacheKey)}catch(r){oe.warn("An error occurred while opening the browser cache:",r)}}if(!t&&ve.useFSCache){if(!Se.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");t=new cp(e??ve.cacheDir)}return t}async function Dx(e,...t){for(let r of t)try{let n=await e.match(r);if(n)return n}catch{continue}}async function zx(e){if(!pn(e,["http:","https:"]))return null;const t=up(e);return t.set("Range","bytes=0-0"),ve.fetch(e,{method:"GET",headers:t})}async function ss(e,t,r={}){const n=await ns(r?.cache_dir),{localPath:s,remoteURL:a,proposedCacheKey:o,validModelId:i}=ia(e,t,r,n),l=await la(n,s,o);if(l!==void 0&&typeof l!="string"){const c=l.headers.get("content-length"),d=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:d||void 0,fromCache:!0}}if(ve.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(ve.allowRemoteModels&&!r.local_files_only&&i)try{const c=await zx(a);if(c&&c.status>=200&&c.status<300){let d;const h=c.headers.get("content-type");if(c.status===206){const p=c.headers.get("content-range");if(p){const m=p.match(/bytes \d+-\d+\/(\d+)/);m&&(d=parseInt(m[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(d===void 0){const p=c.headers.get("content-length");d=p?parseInt(p,10):void 0}return{exists:!0,size:d,contentType:h||void 0,fromCache:!1}}}catch(c){oe.warn(`Unable to fetch file metadata for "${a}": ${c}`)}return{exists:!1,fromCache:!1}}async function Kn(e){return ve.useFS&&!pn(e,["http:","https:","blob:"])?new Ys(e instanceof URL?e.protocol==="file:"?e.pathname:e.toString():e):ve.fetch(e,{headers:up(e)})}function up(e){const t=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(t){const n=!!Fo?.TESTING_REMOTELY,s=ve.version;if(r.set("User-Agent",`transformers.js/${s}; is_ci/${n};`),pn(e,["http:","https:"],["huggingface.co","hf.co"])){const o=Fo?.HF_TOKEN??Fo?.HF_ACCESS_TOKEN;o&&r.set("Authorization",`Bearer ${o}`)}}return r}function ia(e,t,r={},n=null){const s=r.revision??"main",a=Fs(e,t),o=Lx(e),i=o?Fs(ve.localModelPath,a):a,l=Fs(ve.remoteHost,ve.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(s)),t),c=n instanceof cp?s==="main"?a:Fs(e,s,t):l;return{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:o}}async function la(e,t,r){if(e)return await Dx(e,t,r)}async function Bx(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 Rx(e,t,r=!0,n={},s=!1,a=null){const{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:d}=ia(e,t,n,a);let h,p=!1,m;m=await la(a,i,c);const w=m!==void 0;if(!w){if(ve.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(!ve.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||!ve.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 Ox(m.status,l,r);h=c}p=a&&typeof Response<"u"&&m instanceof Response&&m.status===200}Dr(n.progress_callback,{status:"download",name:e,file:t});let v;if(!(Se.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 ss(e,t,n);E.size&&(k=E.size)}catch{}M=await Nx(m,E=>{Dr(n.progress_callback,{status:"progress",name:e,file:t,...E})},k)}v=M}if(p&&h&&typeof m!="string"&&await Bx(e,t,a,h,m,v,n),Dr(n.progress_callback,{status:"done",name:e,file:t}),v){if(!Se.IS_NODE_ENV&&s)throw new Error("Cannot return path in a browser environment.");return v}if(m instanceof Ys)return m.filePath;const b=await a?.match(h);if(b instanceof Ys)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 Js(e,t,r=!0,n={},s=!1){if(!ve.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(!ve.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 ns(n?.cache_dir);return await Rx(e,t,r,n,s,a)}async function dp(e,t,r=!0,n={}){const s=await Js(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 dp(e,t,r,n);return s===null?{}:JSON.parse(s)}function $x(e,[t,r,n],[s,a],o="bilinear",i=!1){const l=a/n,c=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)/c-.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,U=(1-O)*(1-x),G=O*(1-x),W=(1-O)*x,J=O*x,q=A*n,B=C*n,N=q+k,V=q+E,ee=B+k,X=B+E;for(let F=0;F<t;++F){const L=F*h;d[F*p+v]=U*e[L+N]+G*e[L+V]+W*e[L+ee]+J*e[L+X]}}return d}function Gx(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 c=t.length-1,d=i;c>=0;--c)l+=d%t[c]*a[c],d=Math.floor(d/t[c]);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 Vx(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 Ux(e,t){let r=0;for(let n=0;n<e.length;++n)r+=e[n]*t[n];return r}function DL(e,t){const r=Ux(e,t),n=Eh(e),s=Eh(t);return r/(n*s)}function Eh(e){return Math.sqrt(e.reduce((t,r)=>t+r*r,0))}function Ho(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let n=1;n<e.length;++n)e[n]<t&&(t=e[n],r=n);return[t,r]}function 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 hp(e){return e>0&&(e&e-1)===0}var fp=class{constructor(e){if(this.size=e|0,this.size<=1||!hp(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 c=this._bitrev;if(o===4)for(i=0,l=0;i<n;i+=o,++l){const h=c[l];this._singleTransform2(t,e,i,h,a)}else for(i=0,l=0;i<n;i+=o,++l){const h=c[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],U=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,V=d[2*w],ee=r*d[2*w+1],X=x*V-U*ee,F=x*ee+U*V,L=d[3*w],z=r*d[3*w+1],K=G*L-W*z,le=G*z+W*L,Te=A+X,Pe=E+F,ut=A-X,Ve=E-F,ze=B+K,Ue=N+le,be=r*(B-K),fe=r*(N-le);e[v]=Te+ze,e[v+1]=Pe+Ue,e[b]=ut+fe,e[b+1]=Ve-be,e[M]=Te-ze,e[M+1]=Pe-Ue,e[k]=ut-fe,e[k+1]=Ve+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],c=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=c+m,k=l-p,A=c-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 c=this._bitrev;if(o===4)for(i=0,l=0;i<n;i+=o,++l){const p=c[l];this._singleRealTransform2(t,e,i,p>>>1,a>>>1)}else for(i=0,l=0;i<n;i+=o,++l){const p=c[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],U=e[k+1],G=e[A],W=e[A+1],J=e[E],q=e[E+1],B=C,N=O,V=d[b],ee=r*d[b+1],X=x*V-U*ee,F=x*ee+U*V,L=d[2*b],z=r*d[2*b+1],K=G*L-W*z,le=G*z+W*L,Te=d[3*b],Pe=r*d[3*b+1],ut=J*Te-q*Pe,Ve=J*Pe+q*Te,ze=B+K,Ue=N+le,be=B-K,fe=N-le,je=X+ut,_e=F+Ve,ye=r*(X-ut),cr=r*(F-Ve);if(e[M]=ze+je,e[M+1]=Ue+_e,e[k]=be+cr,e[k+1]=fe-ye,v===0){e[A]=ze-je,e[A+1]=Ue-_e;continue}if(v===w)continue;const kr=i+m-v,dt=i+p-v;e[kr]=be-r*cr,e[kr+1]=-fe-r*ye,e[dt]=ze-r*je,e[dt+1]=-Ue+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],c=e[n+s],d=e[n+o],h=e[n+i],p=l+d,m=l-d,w=c+h,v=a*(c-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}},jx=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 c=0;c<r>>1;++c){const d=(c+1-e)**2/2,h=Math.sqrt(i**2+l**2)**d,p=d*Math.atan2(l,i),m=2*c;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 fp(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,c=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+c],p=o[d+c+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)}},Wx=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=hp(e),this.isPowerOfTwo?(this.fft=new fp(e),this.outputBufferSize=2*e):(this.fft=new jx(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,t){this.fft.realTransform(e,t)}transform(e,t){this.fft.transform(e,t)}};function qx(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 Hx(e){const t=Math.round(e);return Math.abs(e)%1===.5?t%2===0?t:t-1:t}function Qx(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=[],c=[];for(;o>0||i>0;)switch(l.push(o-1),c.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(),c.reverse(),[l,c]}var Xx=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 c=0;const d=(l&32768)<<16,h=(l&31744)>>10;let p=l&1023;if(h===31)c=d|2139095040|p<<13;else if(h===0)if(p===0)c=d;else{let m=113;for(;!(p&1024);)p<<=1,--m;p&=-1025,c=d|m<<23|p<<13}else c=d|h+112<<23|p<<13;o[0]=c,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}}(),pp={};hn(pp,{default:()=>Yx});var Yx={};async function _p(e){const t=e.split("/").pop();let r;try{if(r=await ns(),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 ve.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 Jx(e){const t=await _p(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 Kx(e){const t=await _p(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 Ah(e){return pn(e,["blob:"])}function Ch(e){let t;if(typeof location<"u"&&location.href)t=location.href;else if(typeof import.meta<"u"&&import.meta.url)t=import.meta.url;else return e;return new URL(e,t).href}var Zx=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}});function mp(e){return e<=Nt.DEBUG?0:e<=Nt.INFO?2:e<=Nt.WARNING||e<=Nt.ERROR?3:4}var e1={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},kt=[],Qo,cn,Sh=Symbol.for("onnxruntime");if(Sh in globalThis)cn=globalThis[Sh];else if(Se.IS_NODE_ENV){switch(cn=pp,process.platform){case"win32":kt.push("dml");break;case"linux":process.arch==="x64"&&kt.push("cuda");break;case"darwin":kt.push("coreml");break}kt.push("webgpu"),kt.push("cpu"),Qo=["cpu"]}else cn=Jy,Se.IS_WEBNN_AVAILABLE&&kt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),Se.IS_WEBGPU_AVAILABLE&&kt.push("webgpu"),kt.push("wasm"),Qo=["wasm"];var t1=cn.InferenceSession;function r1(e=null){if(!e)return Qo;switch(e){case"auto":return kt;case"gpu":return kt.filter(t=>["webgpu","cuda","dml","webnn-gpu"].includes(t))}if(kt.includes(e))return[Zx[e]??e];throw new Error(`Unsupported device: "${e}". Should be one of: ${kt.join(", ")}.`)}var gp=Se.IS_BROWSER_ENV||Se.IS_WEBWORKER_ENV,Ph=Promise.resolve(),en=null;async function n1(){return en||(ve.useWasmCache&&typeof Ze?.wasm?.wasmPaths=="object"&&Ze?.wasm?.wasmPaths?.wasm&&Ze?.wasm?.wasmPaths?.mjs?(en=(async()=>{const t=Ze.wasm.wasmPaths;await Promise.all([t.wasm&&!Ah(t.wasm)?(async()=>{try{const r=await Jx(Ch(t.wasm));r&&(Ze.wasm.wasmBinary=r)}catch(r){oe.warn("Failed to pre-load WASM binary:",r)}})():Promise.resolve(),t.mjs&&!Ah(t.mjs)?(async()=>{try{const r=await Kx(Ch(t.mjs));r&&(Ze.wasm.wasmPaths.mjs=r)}catch(r){oe.warn("Failed to pre-load WASM factory:",r)}})():Promise.resolve()])})(),en):(en=Promise.resolve(),en))}async function wp(e,t,r){await n1();const n=mp(ve.logLevel??Nt.WARNING),s=()=>t1.create(e,{logSeverityLevel:n,...t}),a=await(gp?Ph=Ph.then(s):s());return a.config=r,a}var Fh=Promise.resolve();async function vp(e,t){const r=()=>e.run(t);return await(gp?Fh=Fh.then(r):r())}function yp(e){return e instanceof cn.Tensor}var Ze=cn?.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=Se.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 xi(){return Ze?.wasm?.proxy}function bp(e){const t=mp(e);Ze.logLevel=e1[t]}bp(ve.logLevel??Nt.WARNING);ve.backends.onnx={...Ze,setLogLevel:bp};var mr=async(e,t,r)=>{const n=await wp(new Uint8Array(e),t);return async s=>{const a=xi(),o=Object.fromEntries(Object.entries(s).map(([l,c])=>[l,(a?c.clone():c).ort_tensor])),i=await vp(n,o);return Array.isArray(r)?r.map(l=>new j(i[l])):new j(i[r])}},Br=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}},s1=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"}),Lo=Se.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 (${Lo}).`),Lo):Lo}var a1=function(){let e;return async function(){if(e===void 0)if(!Se.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"}),Ih=st.fp32,Lh=Object.freeze({[s1.wasm]:st.q8}),Xo=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 xp(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=Lh[r]??Ih}else a&&st.hasOwnProperty(a)?i=a:i=Lh[r]??Ih;return o&&s&&s(`dtype not specified for "${t}". Using the default dtype (${i}) for this device (${r}).`),i}var Ks=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}),Tp=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(Se.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[kp(this._random_fn,t)]}};function kp(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 qt=new Tp,ca=Object.freeze({Random:Tp,seed:qt.seed.bind(qt),random:qt.random.bind(qt),gauss:qt.gauss.bind(qt),shuffle:qt.shuffle.bind(qt),choices:qt.choices.bind(qt)}),o1=e=>kp(ca.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 yp(t[0])?this.ort_tensor=t[0]:this.ort_tensor=new lb(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=Qt(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 i1(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=Qt(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:Qt(p,this.dims[d],d,!1),m=m===null?this.dims[d]:Qt(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 c=!0;for(let d=1;d<s.length;++d)if(n[d][0]!==0||n[d][1]!==this.dims[d]){c=!1;break}if(c){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 l1(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=(c,d)=>c+d**t;if(r===null){const c=s.reduce(a,0)**(1/t);return new Be(this.type,[c],[])}const[o,i,l]=Xn(a,this,r,n);if(t!==1)for(let c=0;c<i.length;++c)i[c]=i[c]**(1/t);return new Be(o,i,l)}normalize_(t=2,r=1){r=Qt(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,c=o,d=1;l>=0;--l){const h=this.dims[l];if(l!==r){const p=c%h;i+=p*d,d*=this.dims[l]}c=Math.floor(c/h)}s[o]/=a[i]}return this}normalize(t=2,r=1){return this.clone().normalize_(t,r)}stride(){return Oo(this.dims)}squeeze(t=null){return new Be(this.type,this.data,Oh(this.dims,t))}squeeze_(t=null){return this.dims=Oh(this.dims,t),this}unsqueeze(t){return new Be(this.type,this.data,Nh(this.dims,t))}unsqueeze_(t){return this.dims=Nh(this.dims,t),this}flatten_(t=0,r=-1){r=(r+this.dims.length)%this.dims.length;let n=this.dims.slice(0,t),s=this.dims.slice(t,r+1),a=this.dims.slice(r+1);return this.dims=[...n,s.reduce((o,i)=>o*i,1),...a],this}flatten(t=0,r=-1){return this.clone().flatten_(t,r)}view(...t){let r=-1;for(let s=0;s<t.length;++s)if(t[s]===-1){if(r!==-1)throw new Error("Only one dimension can be inferred");r=s}const n=this.data;if(r!==-1){const s=t.reduce((a,o,i)=>i!==r?a*o:a,1);t[r]=n.length/s}return new 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 Ti(this,t,r)}min(t=null,r=!1){if(t===null){const o=Ho(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=Ho(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=Oo(n),c=Oo(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/c[m]);h=h%c[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(!Ks.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,Xx(this.data),this.dims);return new Be(t,Ks[t].from(this.data,r),this.dims)}};function i1(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 l1(e,t){const[r,n]=Gx(e.data,e.dims,t);return new j(e.type,r,n)}function Ep(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=$x(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 Br.nearest_interpolate_4d;else if(r==="bilinear")s=await Br.bilinear_interpolate_4d;else if(r==="bicubic")s=await Br.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 c1(e,t){return await(await Br.matmul)({a:e,b:t})}async function zL(e,t){return await(await Br.rfft)({x:e,a:t})}async function _n(e,t){const r=await Br.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 Is=e=>new j("int64",e,[e.length]);async function Ap(e,t,r,n,s){return await(await Br.slice)({x:e,s:Is(t),e:Is(r),a:Is(n),t:Is(s??new Array(n.length).fill(1))})}function u1(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 c=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[c++]=M}}return new j(e.type,a,s)}function BL(e,t,{eps:r=1e-5}={}){if(e.dims.length!==2)throw new Error("`layer_norm` currently only supports 2D input.");const[n,s]=e.dims;if(t.length!==1&&t[0]!==s)throw new Error("`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.");const[a,o]=Cp(e,1,0,!0),i=a.data,l=o.data,c=e.data,d=new c.constructor(c.length);for(let h=0;h<n;++h){const p=h*s;for(let m=0;m<s;++m){const w=p+m;d[w]=(c[w]-l[h])/(i[h]+r)}}return new j(e.type,d,e.dims)}function Oh(e,t){return e=e.slice(),t===null?e=e.filter(r=>r!==1):typeof t=="number"?e[t]===1&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((r,n)=>r!==1||!t.includes(n))),e}function Nh(e,t){return t=Qt(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function Qt(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=Qt(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:c}=e[i];for(let d=0;d<l.length;++d){let h=0;for(let p=c.length-1,m=d,w=1;p>=0;--p){const v=c[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+=c[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=Qt(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 c=0;c<a.length;++c){let d=0;for(let h=o.length-1,p=c,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[c],c,d)}return n||i.splice(r,1),[t.type,l,i]}function Cp(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=Qt(t,a.length);const o=Ti(e,t,n),i=o.data,[l,c,d]=Xn((p,m,w,v)=>p+(m-i[v])**2,e,t,n);for(let p=0;p<c.length;++p)c[p]=Math.sqrt(c[p]/(a[t]-r));return[new j(l,c,d),o]}function Ti(e,t=null,r=!1){const n=e.dims,s=e.data;if(t===null){const l=s.reduce((c,d)=>c+d,0);return new j(e.type,[l/s.length],[])}t=Qt(t,n.length);const[a,o,i]=Xn((l,c)=>l+c,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 Oo(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 ki(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 ki(e,t,r,n)}function Yo(e,t){return at(e.dims,t)}function Ct(e){return ki(e,1n,"int64",BigInt64Array)}function Sp(e){return Ct(e.dims)}function Pp(e){return ki(e,0n,"int64",BigInt64Array)}function Fp(e){return Pp(e.dims)}function RL(e){const t=e.reduce((r,n)=>r*n,1);return new j("float32",Float32Array.from({length:t},()=>ca.random()),e)}function d1(e){const t=e.reduce((r,n)=>r*n,1);return new j("float32",Float32Array.from({length:t},()=>ca.gauss()),e)}function h1(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,c=Math.floor(i/8),d=i%8;o[c]|=l<<7-d,r&&d===0&&(o[c]-=128)}return new j(n,o,[e.dims[0],e.dims[1]/8])}async function Ei(e){if(!e)throw new Error("modelId is required for get_tokenizer_files");return(await ss(e,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function Ip(e,t){const r=await Ei(e);return await Promise.all(r.map(n=>ir(e,n,!0,t)))}function Lp(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 f1=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function p1(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"?Dt(e[s],i):Dt(i,e[s])}}function _1(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 m1(e){const t=[];for(const r of e.get_added_tokens_decoder().values())r.special&&t.push(r);return t}var ae=class extends St{return_token_type_ids=!1;padding_side="right";constructor(e,t){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=t,this._tokenizer=new OM(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=m1(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 Ip(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 c;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");c=e.map((h,p)=>this._encode_plus(h,{text_pair:t[p],add_special_tokens:r,return_token_type_ids:i}))}else c=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).");c=[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(c.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<c.length;++h)c[h].input_ids.length!==a&&(c[h].input_ids.length>a?s&&_1(c[h],a):n&&p1(c[h],a,p=>p==="input_ids"?this.pad_token_id:0,this.padding_side));const d={};if(o){if(!(n&&s)&&c.some(p=>{for(const m of Object.keys(p))if(p[m].length!==c[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=[c.length,c[0].input_ids.length];for(const p of Object.keys(c[0]))d[p]=new j("int64",BigInt64Array.from(c.flatMap(m=>m[p]).map(BigInt)),h)}else{for(const h of Object.keys(c[0]))d[h]=c.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=Lp(e)),!Array.isArray(e)||e.length===0||!bb(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:c=!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 Sx(n),this._compiled_template_cache.set(n,m));const w=Object.create(null);for(const b of f1){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:c,...h});return d?b:b.input_ids}return v}};function Ai(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 Op={};hn(Op,{AlbertTokenizer:()=>g1,AutoTokenizer:()=>ce,BartTokenizer:()=>w1,BertTokenizer:()=>v1,BlenderbotSmallTokenizer:()=>y1,BlenderbotTokenizer:()=>b1,BloomTokenizer:()=>M1,CLIPTokenizer:()=>T1,CamembertTokenizer:()=>x1,CodeGenTokenizer:()=>E1,CodeLlamaTokenizer:()=>k1,CohereTokenizer:()=>A1,ConvBertTokenizer:()=>C1,DebertaTokenizer:()=>P1,DebertaV2Tokenizer:()=>S1,DistilBertTokenizer:()=>F1,ElectraTokenizer:()=>I1,EsmTokenizer:()=>L1,FalconTokenizer:()=>O1,GPT2Tokenizer:()=>z1,GPTNeoXTokenizer:()=>D1,GemmaTokenizer:()=>N1,HerbertTokenizer:()=>B1,LlamaTokenizer:()=>R1,M2M100Tokenizer:()=>$1,MBart50Tokenizer:()=>V1,MBartTokenizer:()=>Np,MPNetTokenizer:()=>W1,MarianTokenizer:()=>G1,MgpstrTokenizer:()=>U1,MobileBertTokenizer:()=>j1,NllbTokenizer:()=>q1,NougatTokenizer:()=>H1,PreTrainedTokenizer:()=>ae,Qwen2Tokenizer:()=>Q1,RoFormerTokenizer:()=>Y1,RobertaTokenizer:()=>X1,SiglipTokenizer:()=>J1,SpeechT5Tokenizer:()=>K1,SqueezeBertTokenizer:()=>Z1,T5Tokenizer:()=>eT,TokenizersBackend:()=>ae,VitsTokenizer:()=>rT,Wav2Vec2CTCTokenizer:()=>nT,WhisperTokenizer:()=>iT,XLMRobertaTokenizer:()=>lT,XLMTokenizer:()=>cT});var g1=class extends ae{return_token_type_ids=!0},w1=class extends ae{},v1=class extends ae{return_token_type_ids=!0},y1=class extends ae{},b1=class extends ae{},M1=class extends ae{},x1=class extends ae{},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{return_token_type_ids=!0},P1=class extends ae{return_token_type_ids=!0},F1=class extends ae{},I1=class extends ae{return_token_type_ids=!0},L1=class extends ae{},O1=class extends ae{},N1=class extends ae{},D1=class extends ae{},z1=class extends ae{},B1=class extends ae{return_token_type_ids=!0},R1=class extends ae{padding_side="left"},$1=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 Ai(this,e,t,r)}},G1=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)}`),Dt([n],super._encode_text(s))}}},Np=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 Ai(this,e,t,r)}},V1=class extends Np{},U1=class extends ae{},j1=class extends ae{return_token_type_ids=!0},W1=class extends ae{},q1=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 Ai(this,e,t,r)}},H1=class extends ae{},Q1=class extends ae{},X1=class extends ae{},Y1=class extends ae{return_token_type_ids=!0},J1=class extends ae{},K1=class extends ae{},Z1=class extends ae{return_token_type_ids=!0},eT=class extends ae{},tT=class extends $t{decode_chain(e){let t="";for(let r=1;r<e.length;r+=2)t+=e[r];return[t]}},rT=class extends ae{constructor(e,t){super(e,t),this._tokenizer.decoder=new tT({type:"VitsDecoder"})}},nT=class extends ae{},Dp=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],$s=new Map(Dp),sT=new Map([...Dp.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 aT(e){e=e.toLowerCase();let t=sT.get(e);if(t===void 0){const r=e.match(/^<\|([a-z]{2})\|>$/);if(r&&(e=r[1]),$s.has(e))t=e;else{const s=e.length===2?$s.keys():$s.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(s))}`)}}return t}var oT="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Dh=new RegExp(`^[${oT}]+$`,"gu"),iT=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 c=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 U=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 V=O.length-1;V>=0;--V){const ee=Number(O[V]);if(ee>=h){if(U!==null&&(ee-h)*n<M)break;U=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]),V=$s.get(N.slice(2,-2));if(V!==void 0){if(a!==null&&V!==a&&!t){w.push(W);const ee=this.findLongestCommonSequence(w)[0],X=this.decode(ee);c.text=X,l.push(c),w=[],W=[],c=i()}a=c.language=V}}else if(B>=h&&B<=m){const N=(B-h)*n+d,V=qn(N,2);if(U!==null&&B>=U)b=!0;else if(b||w.length>0&&B<G)b=!1;else if(c.timestamp[0]===null)c.timestamp[0]=V;else if(V!==c.timestamp[0]){c.timestamp[1]=V,w.push(W),o&&v.push(J);const[ee,X]=this.findLongestCommonSequence(w,v),F=this.decode(ee);c.text=F,o&&(c.words=this.collateWordTimestamps(ee,X,a)),l.push(c),w=[],W=[],v=[],J=[],c=i()}}else if(W.push(B),o){let N=qn(x[q]+d,2),V;if(q+1<x.length){V=qn(x[q+1]+d,2);const ee=this.decode([B]);Dh.test(ee)&&(V=qn(Math.min(N+n,V),2))}else V=null;J.push([N,V])}}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)&&(c=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);c.text=x,o&&(c.words=this.collateWordTimestamps(C,O,a)),l.push(c)}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 c=e[l];let d=0,h=[n,n,0,0];const p=c.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),U=Math.min(p,A),G=c.slice(x,U);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,U])}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=c.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=Lp(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 c=0;c<e.length;++c){const d=e[c];o.push(d),i.push(c);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],c=r[i],d=n[i],h=c[0]>=this._tokenizer.token_to_id("<|endoftext|>"),p=l.startsWith(" "),m=l.trim(),w=Dh.test(m);if(h||p||w||s.length===0)s.push(l),a.push(c),o.push(d);else{const v=s.length-1;s[v]+=l,a[v].push(...c),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,c=a.length-1;for(;l>=0;)a[l].startsWith(" ")&&n.includes(a[l].trim())?(a[c]=a[l]+a[c],o[c]=Dt(o[l],o[c]),i[c]=Dt(i[l],i[c]),a[l]="",o[l]=[],i[l]=[]):c=l,--l;for(l=0,c=1;c<a.length;)!a[l].endsWith(" ")&&s.includes(a[c])?(a[l]+=a[c],o[l]=Dt(o[l],o[c]),i[l]=Dt(i[l],i[c]),a[c]="",o[c]=[],i[c]=[]):l=c,++c;return[a.filter(d=>d),o.filter(d=>d.length>0),i.filter(d=>d.length>0)]}},lT=class extends ae{},cT=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 Ip(e,{progress_callback:t,config:r,cache_dir:n,local_files_only:s,revision:a}),l=i.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let c=Op[l];return c||(oe.warn(`Unknown tokenizer class "${l}", attempting to construct from base class.`),c=ae),new c(o,i)}},ua="https://github.com/huggingface/transformers.js/issues/new/choose",Ci="preprocessor_config.json",Zn=Ci,uT="processor_config.json",dT="chat_template.jinja",Le=class extends St{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,uT,!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?dp(e,dT,!0,t):null]);return new this(r,n,s)}},Jo={};hn(Jo,{ChatterboxProcessor:()=>BT,Florence2Processor:()=>Fk,Gemma3nProcessor:()=>Ik,GroundingDinoProcessor:()=>Ok,Idefics3Processor:()=>Gh,JinaCLIPProcessor:()=>Rk,LlavaProcessor:()=>$k,MgpstrProcessor:()=>Gk,MoonshineProcessor:()=>Vk,OwlViTProcessor:()=>Uk,PaliGemmaProcessor:()=>Wk,Phi3VProcessor:()=>Hk,PixtralProcessor:()=>Qk,Processor:()=>Le,PyAnnoteProcessor:()=>Xk,Qwen2VLProcessor:()=>l_,Qwen2_5_VLProcessor:()=>c_,Qwen3VLProcessor:()=>Yk,Sam2Processor:()=>d_,Sam2VideoProcessor:()=>Jk,SamProcessor:()=>u_,SmolVLMProcessor:()=>Gh,SpeechT5Processor:()=>Kk,UltravoxProcessor:()=>Zk,VLChatProcessor:()=>Bk,VoxtralProcessor:()=>nE,Wav2Vec2Processor:()=>sE,Wav2Vec2ProcessorWithLM:()=>aE,WhisperProcessor:()=>oE});var pt=class extends St{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){const r=await ir(e,Ci,!0,t);return new this(r)}};function Pt(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw new Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var Si={};hn(Si,{ASTFeatureExtractor:()=>kT,ChatterboxFeatureExtractor:()=>ET,ClapFeatureExtractor:()=>AT,DacFeatureExtractor:()=>Gp,EncodecFeatureExtractor:()=>$p,FeatureExtractor:()=>pt,Gemma3nAudioFeatureExtractor:()=>CT,MoonshineFeatureExtractor:()=>ST,ParakeetFeatureExtractor:()=>FT,PyAnnoteFeatureExtractor:()=>Vp,SeamlessM4TFeatureExtractor:()=>IT,SnacFeatureExtractor:()=>LT,SpeechT5FeatureExtractor:()=>OT,Wav2Vec2FeatureExtractor:()=>NT,WeSpeakerFeatureExtractor:()=>DT,WhisperFeatureExtractor:()=>zT});var hT=()=>{},fT=hT;async function zp(e,t){if(Se.IS_BROWSER_ENV){if(Se.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(Se.IS_FS_AVAILABLE)t.stream(),Et.createWriteStream(e),await fT();else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function pT(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 c=0;c<s.length;++c)a[c]=o*(i[c]+l[c])/2}else a=s.getChannelData(0);return a}function Bp(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 zh(e){return Bp(e,.5)}function _T(e){return Bp(e,.54)}var mT={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 No(e,t="htk"){const r=mT[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 gT={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 wT(e,t="htk"){const r=gT[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 vT(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 c=-i[l]/r[l],d=i[l+2]/r[l+1];a[l][o]=Math.max(0,Math.min(c,d))}}return a}function Bh(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=No(r,o),c=No(n,o),d=Bh(l,c,t+2);let h=wT(d,o),p;if(i){const w=s/((e-1)*2);p=No(Float64Array.from({length:e},(v,b)=>b*w),o),h=d}else p=Bh(0,Math.floor(s/2),e);const m=vT(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 yT(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 Rp(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 bT(e,t=1,r=1e-5,n=null){return Rp(e,20,t,r,n)}function MT(e,t=1,r=1e-10,n=null){return Rp(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:c=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=yT(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 U=Math.floor(1+Math.floor((e.length-r)/n));k!==null&&U<k&&(U=k);const G=l?Math.floor(s/2)+1:s;let W=U,J=U;A!==null&&(A>U?E&&(J=A):J=W=A);const q=new Wx(s),B=new Float64Array(s),N=new Float64Array(q.outputBufferSize),V=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 Pe=0;Pe<K;++Pe)le+=B[Pe];const Te=le/K;for(let Pe=0;Pe<K;++Pe)B[Pe]-=Te}if(c!==null){for(let le=K-1;le>=1;--le)B[le]-=c*B[le-1];B[0]*=1-c}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;V[le*J+L]=N[Te]**2+N[Te+1]**2}}if(a!==null&&a!==2){const L=a/2;for(let z=0;z<V.length;++z)V[z]**=L}const ee=h.length;let X=await c1(new j("float32",h.flat(),[ee,G]),new j("float32",V,[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)bT(F,w,v,b);else if(a===2)MT(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 jr(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=zh(a);break;case"hamming":o=_T(a);break;case"povey":o=zh(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 xT(e,t){const r=e.reduce((a,o)=>a+o.length,0),n=new ArrayBuffer(44),s=new DataView(n);return Ls(s,0,"RIFF"),s.setUint32(4,36+r*4,!0),Ls(s,8,"WAVE"),Ls(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),Ls(s,36,"data"),s.setUint32(40,r*4,!0),new Blob([n,...e.map(a=>a.buffer)],{type:"audio/wav"})}function Ls(e,t,r){for(let n=0;n<r.length;++n)e.setUint8(t+n,r.charCodeAt(n))}var TT=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]),xT(e,this.sampling_rate)}async save(e){return zp(e,this.toBlob())}},kT=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=jr(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){Pt(e,"ASTFeatureExtractor");const t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){const r=this.std*2,n=t.data;for(let s=0;s<n.length;++s)n[s]=(n[s]-this.mean)/r}return{input_values:t.unsqueeze_(0)}}},$p=class extends pt{async _call(e){Pt(e,"EncodecFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=this.config.feature_size;if(e.length%t!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${t}).`);const r=[1,t,e.length/t];return{input_values:new j("float32",e,r)}}},ET=class extends pt{async _call(e){Pt(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,e.length];return{input_values:new j("float32",e,t)}}},AT=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=jr(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(ca.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 Pt(e,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(e,t??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}},Gp=class extends $p{},CT=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=jr(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(Pt(e,"Gemma3nAudioFeatureExtractor"),r&&e.length>t&&(e=e.slice(0,t)),n&&e.length%s!==0){const i=s-e.length%s,l=new Float64Array(e.length+i);l.set(e),this.config.padding_value!==0&&l.fill(this.config.padding_value,e.length),e=l}const a=await this._extract_fbank_features(e,this.config.max_length),o=at([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:o}}},ST=class extends pt{async _call(e){Pt(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,e.length];return{input_values:new j("float32",e,t)}}},PT=1e-5,FT=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=jr(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){Pt(e,"ParakeetFeatureExtractor");const t=await this._extract_fbank_features(e),r=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),n=t.data;n.fill(0,r*t.dims[1]);const[s,a]=t.dims,o=new Float64Array(a),i=new Float64Array(a);for(let 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)+PT);for(let v=0;v<r;++v){const b=v*a+d;n[b]=(n[b]-h)*w}}const c=new BigInt64Array(s);return c.fill(1n,0,r),{input_features:t.unsqueeze_(0),attention_mask:new j("int64",c,[1,s])}}},Vp=class extends pt{async _call(e){Pt(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]),[c,d]=Ge(l),[h,p]=[i,i+1];d!==o?(o=d,a.push({id:d,start:h,end:p,score:c})):(a.at(-1).end=p,a.at(-1).score+=c)}n.push(a.map(({id:i,start:l,end:c,score:d})=>({id:i,start:l*r,end:c*r,confidence:d/(c-l)})))}return n}},IT=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=jr(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}={}){Pt(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,c=this.config.stride;if(i%c!==0)throw new Error(`The number of frames (${i}) must be a multiple of the stride (${c}).`);const h=a.view(1,Math.floor(i/c),l*c),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+=c,++M)w[M]=v[b]}else w.fill(1n);p.attention_mask=new j("int64",w,[1,m])}return p}},LT=class extends Gp{},OT=class extends pt{},NT=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){Pt(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));const r=[1,t.length];return{input_values:new j("float32",t,r),attention_mask:new j("int64",new BigInt64Array(t.length).fill(1n),r)}}},DT=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=jr(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){Pt(e,"WeSpeakerFeatureExtractor");const t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const r=t.mean(1).data,n=t.data,[s,a,o]=t.dims;for(let i=0;i<s;++i){const l=i*a*o,c=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[c+p]}}}return{input_features:t}}},zT=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=jr(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}={}){Pt(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,Ci,!0,t),n=r.feature_extractor_type,s=Si[n];if(!s)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${ua}.`);return new s(r)}},BT=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}}},Ko={},Ir,Up,gr,Lt=Se.IS_BROWSER_ENV||Se.IS_WEBWORKER_ENV;if(Lt)Ir=(e,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(e,t)},gr=self.createImageBitmap,Up=self.ImageData;else if(Ko)gr=async e=>{const r=(await e.metadata()).channels,{data:n,info:s}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),a=new yt(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 RT={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},$T=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),yt=class Ht{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 Ht)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(!Lt)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 Ht(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(Lt){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=Ko(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 Ht(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=RT[n]??n;const a=ah(t),o=ah(r);if(a&&o)return this;if(a?t=r/this.height*this.width:o&&(r=t/this.width*this.height),Lt){const i=this.channels,l=this.toCanvas(),c=Ir(t,r).getContext("2d");return c.drawImage(l,0,0,t,r),new Ht(c.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(Lt){const a=this.channels,o=this.toCanvas(),i=this.width+t+r,l=this.height+n+s,c=Ir(i,l).getContext("2d");return c.drawImage(o,0,0,this.width,this.height,t,n,this.width,this.height),new Ht(c.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(Lt){const i=this.channels,l=this.toCanvas(),c=Ir(a,o).getContext("2d");return c.drawImage(l,t,r,a,o,0,0,a,o),new Ht(c.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(Lt){const a=this.channels,o=this.toCanvas(),i=Ir(t,r).getContext("2d");let l=0,c=0,d=0,h=0;return n>=0?l=n:d=-n,s>=0?c=s:h=-s,i.drawImage(o,l,c,t,r,d,h,t,r),new Ht(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],c=0;n<0?(l[0]=Math.floor(-n),l[1]=t-this.width-l[0]):c=Math.floor(n),a=a.extend({top:o[0],bottom:o[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:t,height:r})}return await gr(a)}}async toBlob(t="image/png",r=1){if(!Lt)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(!Lt)throw new Error("toCanvas() is only supported in browser environments.");const t=this.clone().rgba(),r=Ir(t.width,t.height),n=new Up(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 c=s*l;for(let d=0;d<s;++d)i[d][l]=t[c+d]}return i.map(l=>new Ht(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 Ht(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(Lt){if(Se.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const r=t.split(".").pop().toLowerCase(),n=$T.get(r)??"image/png",s=await this.toBlob(n);return zp(t,s)}else if(Se.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(Lt)throw new Error("toSharp() is only supported in server-side environments.");return Ko(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},$L=yt.read.bind(yt);function Rh(e,t,r=0,n=null){const s=e/t;let a=Hx(s)*t;return n!==null&&a>n&&(a=Math.floor(s)*t),a<r&&(a=Math.ceil(s)*t),a}function Do([e,t],r){return[Math.max(Math.floor(e/r),1)*r,Math.max(Math.floor(t/r),1)*r]}function jp([e,t,r,n]){return[e-r/2,t-n/2,e+r/2,t+n/2]}function da(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 c=[];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=jp(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])}}c.push(p)}return c}function Wp(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=Ep(i,o,"bilinear",!1));const[l,c]=o??i.dims.slice(-2),d=new j("int32",new Int32Array(l*c),[l,c]),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 GT(e,t,r,n){const s=[],a=[],o=[];for(let i=0;i<e.dims[0];++i){const l=e[i],c=t[i],d=Ge(l.data)[1];if(d===n)continue;const p=tt(l.data)[d];p>r&&(s.push(c),a.push(p),o.push(d))}return[s,a,o]}function VT(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 c=o>0&&i>0;return c&&(c=o/i>s),[c,a]}function UT(e,t,r,n,s,a=null,o=null){const[i,l]=o??e[0].dims,c=new j("int32",new Int32Array(i*l),[i,l]),d=[];if(o!==null)for(let v=0;v<e.length;++v)e[v]=Ep(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=c.data;for(let v=0;v<r.length;++v){const b=r[v],[M,k]=VT(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[c,d]}function qp(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[c,d,h]=o.dims;if(h-=1,a!==null&&a.length!==c)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<c;++m){let w=a!==null?a[m]:null,v=o[m],b=l[m],[M,k,A]=GT(v,b,t,h);if(A.length===0){let[O,x]=w??b.dims.slice(-2),U=new j("int32",new Int32Array(O*x).fill(-1),[O,x]);p.push({segmentation:U,segments_info:[]});continue}let[E,C]=UT(M,k,A,r,n,s,w);p.push({segmentation:E,segments_info:C})}return p}function Hp(e,t=.5,r=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}var ue=class extends St{constructor(e){super(),this.image_mean=e.image_mean??e.mean,this.image_std=e.image_std??e.std,this.resample=e.resample??2,this.do_rescale=e.do_rescale??!0,this.rescale_factor=e.rescale_factor??1/255,this.do_normalize=e.do_normalize,this.do_thumbnail=e.do_thumbnail,this.size=e.size??e.image_size,this.do_resize=e.do_resize??this.size!==void 0,this.size_divisibility=e.size_divisibility??e.size_divisor,this.do_center_crop=e.do_center_crop,this.crop_size=e.crop_size,this.do_convert_rgb=e.do_convert_rgb??!0,this.do_crop_margin=e.do_crop_margin,this.pad_size=e.pad_size,this.do_pad=e.do_pad,this.min_pixels=e.min_pixels,this.max_pixels=e.max_pixels,this.do_pad&&!this.pad_size&&this.size&&this.size.width!==void 0&&this.size.height!==void 0&&(this.pad_size=this.size),this.do_flip_channel_order=e.do_flip_channel_order??!1,this.config=e}async thumbnail(e,t,r=2){const n=e.height,s=e.width,a=t.height,o=t.width;let i=Math.min(n,a),l=Math.min(s,o);return i===n&&l===s?e:(n>s?l=Math.floor(s*i/n):s>n&&(i=Math.floor(n*l/s)),await e.resize(l,i,{resample:r}))}async crop_margin(e,t=200){const r=e.clone().grayscale(),n=Ho(r.data)[0],a=Ge(r.data)[0]-n;if(a===0)return e;const o=t/255;let i=r.width,l=r.height,c=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),c=Math.max(c,w),d=Math.max(d,p))}return e=await e.crop([i,l,c,d]),e}pad_image(e,t,r,{mode:n="constant",center:s=!1,constant_values:a=0}={}){const[o,i,l]=t;let c,d;if(typeof r=="number"?(c=r,d=r):r==="square"?c=d=Math.max(o,i):(c=r.width,d=r.height),c!==i||d!==o){const h=new Float32Array(c*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((c-i)/2),Math.floor((d-o)/2)]:[0,0];for(let w=0;w<o;++w){const v=(w+m)*c,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*c,k=Qs(b,w)*i;for(let A=0;A<c;++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,c,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,c=a===void 0?1:Math.min(a/i,a/l);let d=Math.floor(Number((i*c).toFixed(2))),h=Math.floor(Number((l*c).toFixed(2)));return this.size_divisibility!==void 0&&([d,h]=Do([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,c=o/r;Math.abs(1-c)<Math.abs(1-l)?l=c:c=l,i=Rh(l*n,this.config.ensure_multiple_of),o=Rh(c*r,this.config.ensure_multiple_of)}return[o,i]}else{if(this.size_divisibility!==void 0)return Do([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 c=Float32Array.from(e.data),d=[e.height,e.width,e.channels];if(this.do_rescale&&this.rescale(c),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<c.length;w+=e.channels)for(let v=0;v<e.channels;++v)c[w+v]=(c[w+v]-p[v])/m[v]}if(r??this.do_pad){if(this.pad_size)[c,d]=this.pad_image(c,[e.height,e.width,e.channels],this.pad_size);else if(this.size_divisibility){const[p,m]=Do([d[1],d[0]],this.size_divisibility);[c,d]=this.pad_image(c,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<c.length;p+=3){const m=c[p];c[p]=c[p+2],c[p+2]=m}}const h=new j("float32",c,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)}},Zs={};hn(Zs,{BeitFeatureExtractor:()=>jT,BitImageProcessor:()=>WT,CLIPFeatureExtractor:()=>HT,CLIPImageProcessor:()=>Qp,ChineseCLIPFeatureExtractor:()=>qT,ConvNextFeatureExtractor:()=>QT,ConvNextImageProcessor:()=>Xp,DINOv3ViTImageProcessor:()=>JT,DPTFeatureExtractor:()=>ZT,DPTImageProcessor:()=>Kp,DeiTFeatureExtractor:()=>XT,DeiTImageProcessor:()=>Yp,DetrFeatureExtractor:()=>YT,DetrImageProcessor:()=>Jp,DonutFeatureExtractor:()=>KT,DonutImageProcessor:()=>Pi,EfficientNetImageProcessor:()=>ek,GLPNFeatureExtractor:()=>tk,GroundingDinoImageProcessor:()=>rk,Idefics3ImageProcessor:()=>$h,ImageFeatureExtractor:()=>ue,ImageProcessor:()=>ue,JinaCLIPImageProcessor:()=>sk,LlavaOnevisionImageProcessor:()=>ak,Mask2FormerImageProcessor:()=>ik,MaskFormerFeatureExtractor:()=>ok,MaskFormerImageProcessor:()=>Fi,MobileNetV1FeatureExtractor:()=>lk,MobileNetV1ImageProcessor:()=>Zp,MobileNetV2FeatureExtractor:()=>ck,MobileNetV2ImageProcessor:()=>e_,MobileNetV3FeatureExtractor:()=>uk,MobileNetV3ImageProcessor:()=>t_,MobileNetV4FeatureExtractor:()=>dk,MobileNetV4ImageProcessor:()=>r_,MobileViTFeatureExtractor:()=>hk,MobileViTImageProcessor:()=>n_,NougatImageProcessor:()=>fk,OwlViTFeatureExtractor:()=>pk,OwlViTImageProcessor:()=>Ii,Owlv2ImageProcessor:()=>_k,Phi3VImageProcessor:()=>gk,PixtralImageProcessor:()=>wk,PvtImageProcessor:()=>vk,Qwen2VLImageProcessor:()=>bk,RTDetrImageProcessor:()=>Mk,Sam2ImageProcessor:()=>Ro,Sam3ImageProcessor:()=>Ro,SamImageProcessor:()=>Ro,SapiensFeatureExtractor:()=>xk,SapiensImageProcessor:()=>s_,SegformerFeatureExtractor:()=>Tk,SegformerImageProcessor:()=>a_,SiglipImageProcessor:()=>kk,SmolVLMImageProcessor:()=>$h,Swin2SRImageProcessor:()=>Ek,VLMImageProcessor:()=>nk,ViTFeatureExtractor:()=>Ak,ViTImageProcessor:()=>o_,VitMatteImageProcessor:()=>Ck,VitPoseImageProcessor:()=>Sk,YolosFeatureExtractor:()=>Pk,YolosImageProcessor:()=>i_});var jT=class extends ue{},WT=class extends ue{},qT=class extends ue{},Qp=class extends ue{},HT=class extends Qp{},Xp=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}},QT=class extends Xp{},Yp=class extends ue{},XT=class extends Yp{},Jp=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 da(...e)}post_process_panoptic_segmentation(...e){return qp(...e)}post_process_instance_segmentation(...e){return Hp(...e)}},YT=class extends Jp{},JT=class extends ue{},Pi=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 c=i.map((d,h)=>-d/l[h]);return super.pad_image(e,t,r,{center:!0,constant_values:c,...n})}},KT=class extends Pi{},Kp=class extends ue{},ZT=class extends Kp{},ek=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))}},tk=class extends ue{},rk=class extends ue{async _call(e){const t=await super._call(e),r=t.pixel_values.dims,n=Ct([r[0],r[2],r[3]]);return{...t,pixel_mask:n}}},$h=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 U=this.get_resize_for_vision_encoder(O.pixel_values,k),G=await yr(O.pixel_values,{size:[U.height,U.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 c=s.length,[d,h,p,m]=s[0].dims;let w,v;if(c===1)w=s[0].unsqueeze_(0),v=at([c,d,p,m],!0);else{const b=Math.max(...s.map(A=>A.dims.at(0)));v=at([c,b,p,m],!0);const M=v.data,k=b*p*m;for(let A=0;A<c;++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 c=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-c,k=a):(b=m*c,k=(m+1)*c),w===l-1?(v=o-d,M=o):(v=w*d,M=(w+1)*d);const C=await Ap(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}}},nk=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})}},sk=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})}},ak=class extends ue{},Fi=class extends ue{post_process_panoptic_segmentation(...e){return qp(...e)}post_process_instance_segmentation(...e){return Hp(...e)}},ok=class extends Fi{},ik=class extends Fi{},Zp=class extends ue{},lk=class extends Zp{},e_=class extends ue{},ck=class extends e_{},t_=class extends ue{},uk=class extends t_{},r_=class extends ue{},dk=class extends r_{},n_=class extends ue{},hk=class extends n_{},fk=class extends Pi{},Ii=class extends ue{post_process_object_detection(...e){return da(...e)}},pk=class extends Ii{},_k=class extends Ii{},mt=336,mk=[2,3],{ceil:zo,floor:tn,sqrt:Bo}=Math,gk=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 tn((tn(t/mt)*tn(e/mt)+1)*r+1+(tn(t/mt)+1)*Bo(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*zo(s/mt),i=mt*zo(a/mt),l=[1,1,1].map((c,d)=>(c-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||Bo(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=Bo(t),M=tn(m/b),k=tn(p/b);for(let E=0;E<b;++E)for(let C=0;C<b;++C){let O,x,U,G;E===b-1?(x=p-k,G=p):(x=E*k,G=(E+1)*k),C===b-1?(O=m-M,U=m):(O=C*M,U=(C+1)*M);const q=await Ap(h,[x,O],[G,U],mk);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*zo(p/mt))),c=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:c,num_img_tokens:d}}},wk=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:c}=this.config;if(!c)throw new Error("config must contain 'spatial_merge_size'");const d=l*c,h=Math.floor((o-1)/d)+1,p=Math.floor((i-1)/d)+1;return[h*d,p*d]}},vk=class extends ue{};function yk(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 bk=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 yk(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 c=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(c,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(c*h*p,d*o*l*l),w=new j("int64",[c,h,p],[1,3]);return{pixel_values:m,image_grid_thw:w,original_sizes:n,reshaped_input_sizes:s}}},Mk=class extends ue{post_process_object_detection(...e){return da(...e)}},Ro=class extends ue{reshape_input_points(e,t,r,n=!1){e=structuredClone(e);let s=oh(e);if(s.length===3)n||(s=[1,...s]),e=[e];else if(s.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;a<e.length;++a){const[o,i]=t[a],[l,c]=r[a],d=[c/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=oh(e);if(r.length===2)r=[1,...r],e=[e];else if(r.length!==3)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");if(r.some((n,s)=>n!==t.dims[s]))throw Error(`The first ${r.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new 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 c=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:c}),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}={}){}},s_=class extends ue{post_process_semantic_segmentation(...e){return Wp(...e)}},xk=class extends s_{},a_=class extends ue{post_process_semantic_segmentation(...e){return Wp(...e)}},Tk=class extends a_{},kk=class extends ue{},Ek=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})}},o_=class extends ue{},Ak=class extends o_{},Ck=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)}}},Sk=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 c=0;c<s;++c){const d=n[c],h=t[c],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,U=-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,U=Math.max(U,N),C+=(B+.5)*N,O+=J*N}}if(r!=null&&U<r)continue;const W=[k*C/x,A*O/x];v.push(W),M.push(E),b.push(U)}p.push({bbox:w,scores:b,labels:M,keypoints:v})}l.push(p)}return l}},i_=class extends ue{post_process_object_detection(...e){return da(...e)}},Pk=class extends i_{},_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=Zs[n?.replace(/Fast$/,"")];return s||(n!==void 0&&oe.warn(`Image processor type '${n}' not found, assuming base ImageProcessor. Please report this at ${ua}.`),s=ue),new s(r)}},Fk=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[c,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}}},Ik=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:c,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=c;const p=c.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 Lk(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 Ok=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),c=a.sigmoid(),d=c.max(-1).tolist(),h=o.tolist().map(m=>m.map(w=>jp(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=c[m][A];b.push(E),k.push(C);const x=Lk(O.gt(n),t[m]);M.push(x)}p.push({scores:b,boxes:k,labels:this.batch_decode(M)})}return p}};function Nk(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 Dk(e,t,r,n){return`${t}${n}`+r.repeat(e)+`${t}`}function zk(e,t,r,n,s,a){return e===0&&t===0?Dk(r,n,s,a):Nk(r,e,t,n,s,a)}var Gh=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(xb(h,this.image_token));const w=p.map((M,k)=>zk(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}}},Bk=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=>yt.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,c,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=Dt(h,[c],b,[d],M);const k=new Array(this.num_image_tokens).fill(!0);p=Dt(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}},Rk=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}}},$k=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:c}=this.config,d=Math.floor(a/l)*Math.floor(o/l)+c;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}}},Vh={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]},Gk=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(!Vh.hasOwnProperty(t))throw new Error(`Format ${t} is not supported.`);const[r,n]=Vh[t],s=this[r].bind(this),[a,o]=e.dims,i=[],l=[],c=e.tolist();for(let h=0;h<a;++h){const p=c[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"),c=[],d=[];for(let h=0;h<n.length;++h){const[p,m]=Ge([s[h],o[h],l[h]]);c.push([n[h],a[h],i[h]][m]),d.push(p)}return{generated_text:c,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}},Vk=class extends Le{static tokenizer_class=ce;static feature_extractor_class=lr;async _call(e){return await this.feature_extractor(e)}},Uk=class extends Le{static tokenizer_class=ce;static image_processor_class=_t},rn="<image>";function jk(e,t,r,n,s){return`${n.repeat(r*s)}${t}${e}
28
+ `}var Wk=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(rn))?a=t.map(l=>{const c=l.replaceAll(rn,rn.repeat(s)),d=c.lastIndexOf(rn),h=d===-1?0:d+rn.length;return c.slice(0,h)+n+c.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=>jk(l,n,s,rn,e.length)));const o=this.tokenizer(a,r);return{...await this.image_processor(e,r),...o}}},Uh="<|image|>",qk=/<\|image_\d+\|>/g,Hk=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(qk).join(Uh.repeat(i[h])));a=this.tokenizer(l,{padding:r,truncation:n});const c=this.tokenizer._tokenizer.token_to_id(Uh);a.input_ids.map_(d=>d==c?-d:d)}else a=this.tokenizer(e);return{...a,...o}}},Qk=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:c,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+c,A=M.repeat(m-1)+k;t[v]=t[v].replace(i,A)}}const s=t?this.tokenizer(t,r):{};return{...n,...s}}},Xk=class extends Le{static feature_extractor_class=Vp;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}},l_=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(c=>{for(;c.includes("<|image_pad|>");){const d=Number(l[i++].reduce((h,p)=>h*p,1n));c=c.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(d/o)))}return c.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(e),...n}}},c_=class extends l_{},Yk=class extends c_{},u_=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)}},d_=class extends u_{},Jk=class extends d_{},Kk=class extends Le{static tokenizer_class=ce;static feature_extractor_class=lr;async _call(e){return await this.feature_extractor(e)}},Zk=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 c=this.config.audio_placeholder;if(!e.includes(c))throw new Error(`The input text does not contain the image token ${c}.`);e=e.replaceAll(c,c.repeat(l))}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...n}}},Os="[AUDIO]",eE="[BEGIN_AUDIO]",tE=375;function rE(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 nE=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(Os))throw new Error(`The input text does not contain the audio token ${Os}.`);Array.isArray(t)||(t=[t]);const a=e.split(Os),o=a.length-1;if(o!==t.length)throw new Error(`The number of audio inputs (${t.length}) does not match the number of audio tokens in the text (${o}).`);const i=this.feature_extractor.config.n_samples,l=t.map(m=>rE(m,i)),c=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<c.length;++m){p+=eE;for(let w=0;w<c[m];++w)p+=Os.repeat(tE);p+=a[m+1]}e=p}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...n}}},sE=class extends Le{static tokenizer_class=ce;static feature_extractor_class=lr;async _call(e){return await this.feature_extractor(e)}},aE=class extends Le{static tokenizer_class=ce;static feature_extractor_class=lr;async _call(e){return await this.feature_extractor(e)}},oE=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=Zs[n.replace(/Fast$/,"")];if(!l)throw new Error(`Unknown image_processor_type: '${n}'.`);o.image_processor=new l(r)}if(s){const l=Zs[s];if(l)o.image_processor=new l(r);else{const c=Si[s];if(!c)throw new Error(`Unknown feature_extractor_type: '${s}'.`);o.feature_extractor=new c(r)}}const i={};return new Le(i,o,null)}};async function iE(e,t){return await ir(e,"config.json",!0,t)}function sn(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=sn(e.text_config);break;case"moondream1":r=sn(e.phi_config);break;case"musicgen":r=sn(e.decoder);break;case"multi_modality":r=sn(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=sn(e.decoder),a="num_decoder_layers"in s,o=ft(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,...ft(e,["model_type","multi_query","is_encoder_decoder"])};for(const s in t)n[s]=e[t[s]];return n}function h_(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:c}=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,c];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:c,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=c/i,k=t?.batch_size??1,A=(b??v*c)+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:c,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??c/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 lE(e,t)}function lE(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 c=0;c<s.num_decoder_layers;++c)n[`${t}.${c}.encoder.key`]=i,n[`${t}.${c}.encoder.value`]=i,n[`${t}.${c}.decoder.key`]=l,n[`${t}.${c}.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 c=0;c<o;++c)n[`${t}.${c}.key`]=l,n[`${t}.${c}.value`]=l}else if(s.multi_query){const l=[r*a,0,2*i];for(let c=0;c<o;++c)n[`${t}.${c}.key_value`]=l}else if(s.model_type==="bloom"){const l=[r*a,i,0],c=[r*a,0,i];for(let d=0;d<o;++d)n[`${t}.${d}.key`]=l,n[`${t}.${d}.value`]=c}else if(s.model_type==="openelm")for(let l=0;l<o;++l){const c=[r,a[l],0,i];n[`${t}.${l}.key`]=c,n[`${t}.${l}.value`]=c}else{const l=[r,a,0,i];for(let c=0;c<o;++c)n[`${t}.${c}.key`]=l,n[`${t}.${c}.value`]=l}}return n}var cE=class Zo{model_type=null;is_encoder_decoder=!1;max_position_embeddings;"transformers.js_config";constructor(t){Object.assign(this,t),this.normalized_config=sn(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 Zo)&&(n=new Zo(n));const i=n??await iE(t,{progress_callback:r,config:n,cache_dir:s,local_files_only:a,revision:o});return new this(i)}},Li=class{static async from_pretrained(...e){return cE.from_pretrained(...e)}};function f_(e,t,r){return e?typeof e=="object"&&e!==null?e.hasOwnProperty(t)?+e[t]:e.hasOwnProperty(r)?+e[r]:0:+e:0}function p_(e,t){const r=[];for(let n=0;n<t;++n)r.push(`${e}_data${n===0?"":"_"+n}`);return r}async function uE(e,t,r,n){const s=`${t}${n}.onnx`,a=`${r.subfolder??""}/${s}`;return await Js(e,a,!0,r,Se.IS_NODE_ENV)}async function dE(e,t,r,n,s,a={}){const o=`${t}${r}.onnx`,i=Se.IS_NODE_ENV;let l=[];const c=f_(s,o,t);if(c>0){if(c>kh)throw new Error(`The number of external data chunks (${c}) exceeds the maximum allowed value (${kh}).`);const d=p_(o,c);for(const h of d){const p=`${n.subfolder??""}/${h}`;l.push(new Promise(async(m,w)=>{const v=await Js(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 Js(e,d.data,!0,n);return{...d,data:h}}return d}));return Promise.all(l)}async function hE(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=r1(a),i=s.device_config??{};i.hasOwnProperty(a)&&(s={...s,...i[a]});const l=xp(r.dtype??s.dtype,t,a,{configDtype:s.dtype,warn:A=>oe.info(A)});if(Xo.hasOwnProperty(l)){if(a==="webgpu"&&!Se.IS_NODE_ENV&&l===st.fp16&&!await a1())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 c=s.kv_cache_dtype,d=c?typeof c=="string"?c:c[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=Xo[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=uE(e,t,r,h),v=r.use_external_data_format??s.use_external_data_format,b=await dE(e,t,h,r,v,p);if(b.length>0&&!Se.IS_NODE_ENV&&(p.externalData=b),n&&a==="webgpu"&&c!==!1){const A=h_(r.config,{prefix:"present"});if(Object.keys(A).length>0&&!xi()){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 ht(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 hE(e,t[s],r,s===n),l=await wp(a,o,i);return[s,l]})))}function __(e){for(let t in e)yp(e[t])?e[t]=new j(e[t]):typeof e[t]=="object"&&__(e[t]);return e}async function Me(e,t){const r=fE(e,t);try{const n=Object.fromEntries(Object.entries(r).map(([a,o])=>{const i=o.ort_tensor;return Se.IS_NODE_ENV&&typeof Float16Array<"u"&&i.cpuData instanceof Float16Array&&(i.cpuData=new Uint16Array(i.cpuData.buffer)),[a,i]})),s=await vp(e,n);return __(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 fE(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]=xi()?i.clone():i}if(n.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${n.join(", ")}.`);const s=Object.keys(t).length,a=e.inputNames.length;if(s>a){let o=Object.keys(t).filter(i=>!e.inputNames.includes(i));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}},Wr=class extends He{constructor({logits:e}){super(),this.logits=e}},pE=class extends He{constructor({alphas:e}){super(),this.alphas=e}},Jt=class extends St{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},Oi=class extends St{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},ei=class extends St{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()}},_E=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}},mE=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}},m_=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}},gE=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=Vx(n),l=Math.log(i.subarray(this.timestamp_begin).map(Math.exp).reduce((d,h)=>d+h)),c=Ge(i.subarray(0,this.timestamp_begin))[0];l>c&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},wE=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}},vE=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}},yE=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}},bE=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}},ME=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}},xE=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}},TE=class extends Oi{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}},GL=class extends Oi{constructor(e,{filter_value:t=-1/0,min_tokens_to_keep:r=1}={}){if(super(),e<0||e>1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${e}`);if(!Number.isInteger(r)||r<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${r}`);this.top_p=e,this.filter_value=t,this.min_tokens_to_keep=r}},VL=class extends Oi{constructor(e,{filter_value:t=-1/0,min_tokens_to_keep:r=1}={}){if(super(),!Number.isInteger(e)||e<0)throw new Error(`\`top_k\` must be a positive integer, but is ${e}`);this.top_k=Math.max(e,r),this.filter_value=t}},g_=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,ft(e,Object.getOwnPropertyNames(this)))}},ha=class extends St{_call(e,t){throw Error("StoppingCriteria needs to be subclassed")}},kE=class w_ extends St{constructor(){super(),this.criteria=[]}push(t){this.criteria.push(t)}extend(t){t instanceof w_?t=t.criteria:t instanceof ha&&(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()}},EE=class extends ha{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)}},AE=class extends ha{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)})}},UL=class extends ha{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(e,t){return new Array(e.length).fill(this.interrupted)}},fa=class extends St{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 o1(e)}static getSampler(e){if(e.do_sample)return new SE(e);if(e.num_beams>1)return new PE(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 CE(e)}},CE=class extends fa{async sample(e){const t=Ge(e.data)[1];return[[BigInt(t),0]]}},SE=class extends fa{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])]})}},PE=class extends fa{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 FE(e){Hn=e}function ti(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 v_(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},jh={[$.DecoderOnly]:{can_generate:!0,forward:ar,prepare_inputs:ea},[$.DecoderOnlyWithoutHead]:{can_generate:!1,forward:ar,prepare_inputs:ea},[$.Seq2Seq]:{can_generate:!0,forward:Ns,prepare_inputs:ta},[$.Vision2Seq]:{can_generate:!0,forward:Ns,prepare_inputs:ta},[$.Musicgen]:{can_generate:!0,forward:Ns},[$.EncoderDecoder]:{can_generate:!1,forward:Ns},[$.ImageTextToText]:{can_generate:!0,forward:OE,prepare_inputs:Ds},[$.AudioTextToText]:{can_generate:!0,forward:LE,prepare_inputs:Ds},[$.Phi3V]:{can_generate:!0,prepare_inputs:Ds},[$.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:Ds},[$.MultiModality]:{can_generate:!0},[$.AutoEncoder]:{can_generate:!1,forward:IE},[$.Chatterbox]:{can_generate:!0,forward:xr},default:{can_generate:!1,forward:xr}},Mr=new Map,Ni=new Map,un=new Map,P=class extends St{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=jh[s]??jh.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:c=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:c,use_external_data_format:d,session_options:h},m=un.get(this),w=Mr.get(m);r=p.config=await Li.from_pretrained(e,p);let v;if(w===$.DecoderOnly)v=await Promise.all([ht(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([ht(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([ht(e,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},p)]);else if(w===$.EncoderDecoder)v=await Promise.all([ht(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([ht(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([ht(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([ht(e,b,p),sr(e,{generation_config:"generation_config.json"},p)])}else if(w===$.Musicgen)v=await Promise.all([ht(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([ht(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([ht(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([ht(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([ht(e,{encoder_model:"encoder_model",decoder_model:"decoder_model"},p)]);else if(w===$.Supertonic)v=await Promise.all([ht(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 ${ua}.`)}v=await Promise.all([ht(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 ei;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&n.push(new vE(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&n.push(new wE(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&n.push(new ME(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&n.push(new yE(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 bE(t,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&n.push(new _E(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&n.push(new mE(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 m_(e.begin_suppress_tokens,s))}return e.guidance_scale!==null&&e.guidance_scale>1&&n.push(new xE(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 TE(e.temperature)),r!==null&&n.extend(r),n}_prepare_generation_config(e,t,r=g_){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,ft(t,Object.getOwnPropertyNames(s))),s}_get_stopping_criteria(e,t=null){const r=new kE;return e.max_length!==null&&r.push(new EE(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&r.push(new AE(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,Ct([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=ft(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,c=await this._prepare_inputs_embeds(t);t={...l,...ft(c,["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,Yo(s,0)],0),"attention_mask"in t&&(t.attention_mask=De([t.attention_mask,Fp(t.attention_mask)],0));else if(t.decoder_input_ids){const a=ti(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=ti(o)}return r.decoder_attention_mask=Sp(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 c=this.config.is_encoder_decoder;c&&("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;c?{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=fa.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,ft(k,this._return_dict_in_generate_keys));const x=k.logits.slice(null,-1,null).to("float32"),U=p(M,x),G=[];for(let J=0;J<U.dims.at(0);++J){const q=U[J],B=await v(q);for(const[N,V]of B){const ee=BigInt(N);b[J]+=V,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:c})}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"?Ks.float16:Ks.float32,o=h_(this.config,{batch_size:n});for(const i in o){const l=o[i].reduce((c,d)=>c*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 Ns(e,t){let{encoder_outputs:r,input_ids:n,decoder_input_ids:s,...a}=t;if(!r){const o=ft(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=ft(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=Fp(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=Ct([s[0],s[2],s[3]])}return await Me(r,n)}async function IE(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=v_(!!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=NE(a,s,i)}e.addPastKeyValues(a,s);const o=ft(a,n.inputNames);return await Me(n,o)}async function y_(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:c=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(c&&m&&a.dims[1]===1){const v=a.dims[1],b=Object.values(c)[0].dims.at(-2);o=De([Ct([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:c,attention_mask:o,position_ids:i,generation_config:d,logits_processor:h},!0)}async function LE(e,t){return await y_(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 OE(e,t){return await y_(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 b_(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 c=0;c<n;++c){const d=i+c;s[d]===0n?a[d]=BigInt(1):(a[d]=l,l+=s[d])}}return{data:a,dims:e.dims}}function NE(e,t=null,r=0){const{input_ids:n,inputs_embeds:s,attention_mask:a}=e,{data:o,dims:i}=b_(a,r);let l=new j("int64",o,i);if(t){const c=-(n??s).dims.at(1);l=l.slice(null,[c,null])}return l}function ea(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=Ct([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 ta(e,t,r,n){return r.past_key_values&&(t=t.map(s=>[s.at(-1)])),{...r,decoder_input_ids:ti(t)}}function Ds(e,...t){return e.config.is_encoder_decoder?ta(e,...t):ea(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(c=>c.reduce((d,h,p)=>(h==e&&d.push(p),d),[])),o=a.reduce((c,d)=>c+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 c=0;c<a.length;++c){const d=a[c],h=t[c];for(let p=0;p<d.length;++p)h[d[p]].data.set(r[l++].data)}return{inputs_embeds:t,attention_mask:s}}function as({image_token_id:e,inputs_embeds:t,image_features:r,input_ids:n,attention_mask:s}){return M_({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:n,attention_mask:s})}function x_({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 Di={};hn(Di,{ASTForAudioClassification:()=>HE,ASTModel:()=>qE,ASTPreTrainedModel:()=>$i,AfmoeForCausalLM:()=>UE,AfmoeModel:()=>VE,AfmoePreTrainedModel:()=>Bi,AlbertForMaskedLM:()=>RE,AlbertForQuestionAnswering:()=>BE,AlbertForSequenceClassification:()=>zE,AlbertModel:()=>DE,AlbertPreTrainedModel:()=>os,ApertusForCausalLM:()=>GE,ApertusModel:()=>$E,ApertusPreTrainedModel:()=>zi,ArceeForCausalLM:()=>WE,ArceeModel:()=>jE,ArceePreTrainedModel:()=>Ri,BartForConditionalGeneration:()=>XE,BartForSequenceClassification:()=>YE,BartModel:()=>QE,BartPretrainedModel:()=>pa,BeitForImageClassification:()=>KE,BeitModel:()=>JE,BeitPreTrainedModel:()=>Gi,BertForMaskedLM:()=>e2,BertForQuestionAnswering:()=>n2,BertForSequenceClassification:()=>t2,BertForTokenClassification:()=>r2,BertModel:()=>ZE,BertPreTrainedModel:()=>gn,BlenderbotForConditionalGeneration:()=>a2,BlenderbotModel:()=>s2,BlenderbotPreTrainedModel:()=>Vi,BlenderbotSmallForConditionalGeneration:()=>i2,BlenderbotSmallModel:()=>o2,BlenderbotSmallPreTrainedModel:()=>Ui,BloomForCausalLM:()=>c2,BloomModel:()=>l2,BloomPreTrainedModel:()=>ji,CLIPModel:()=>w2,CLIPPreTrainedModel:()=>qr,CLIPSegForImageSegmentation:()=>x2,CLIPSegModel:()=>M2,CLIPSegPreTrainedModel:()=>Wi,CLIPTextModel:()=>v2,CLIPTextModelWithProjection:()=>S_,CLIPVisionModel:()=>y2,CLIPVisionModelWithProjection:()=>b2,CamembertForMaskedLM:()=>d2,CamembertForQuestionAnswering:()=>p2,CamembertForSequenceClassification:()=>h2,CamembertForTokenClassification:()=>f2,CamembertModel:()=>u2,CamembertPreTrainedModel:()=>wn,ChatterboxModel:()=>k_,ChatterboxPreTrainedModel:()=>T_,ChineseCLIPModel:()=>m2,ChineseCLIPPreTrainedModel:()=>E_,ClapAudioModelWithProjection:()=>C_,ClapModel:()=>g2,ClapPreTrainedModel:()=>_a,ClapTextModelWithProjection:()=>A_,CodeGenForCausalLM:()=>k2,CodeGenModel:()=>T2,CodeGenPreTrainedModel:()=>qi,Cohere2ForCausalLM:()=>S2,Cohere2Model:()=>C2,Cohere2PreTrainedModel:()=>Qi,CohereForCausalLM:()=>A2,CohereModel:()=>E2,CoherePreTrainedModel:()=>Hi,ConvBertForMaskedLM:()=>F2,ConvBertForQuestionAnswering:()=>O2,ConvBertForSequenceClassification:()=>I2,ConvBertForTokenClassification:()=>L2,ConvBertModel:()=>P2,ConvBertPreTrainedModel:()=>vn,ConvNextForImageClassification:()=>D2,ConvNextModel:()=>N2,ConvNextPreTrainedModel:()=>Xi,ConvNextV2ForImageClassification:()=>B2,ConvNextV2Model:()=>z2,ConvNextV2PreTrainedModel:()=>Yi,DFineForObjectDetection:()=>V2,DFineModel:()=>G2,DFinePreTrainedModel:()=>Ki,DINOv3ConvNextModel:()=>hA,DINOv3ConvNextPreTrainedModel:()=>B_,DINOv3ViTModel:()=>fA,DINOv3ViTPreTrainedModel:()=>R_,DPTForDepthEstimation:()=>bA,DPTModel:()=>yA,DPTPreTrainedModel:()=>nl,DacDecoderModel:()=>L_,DacDecoderOutput:()=>F_,DacEncoderModel:()=>I_,DacEncoderOutput:()=>P_,DacModel:()=>U2,DacPreTrainedModel:()=>ma,DebertaForMaskedLM:()=>W2,DebertaForQuestionAnswering:()=>Q2,DebertaForSequenceClassification:()=>q2,DebertaForTokenClassification:()=>H2,DebertaModel:()=>j2,DebertaPreTrainedModel:()=>yn,DebertaV2ForMaskedLM:()=>Y2,DebertaV2ForQuestionAnswering:()=>Z2,DebertaV2ForSequenceClassification:()=>J2,DebertaV2ForTokenClassification:()=>K2,DebertaV2Model:()=>X2,DebertaV2PreTrainedModel:()=>bn,DecisionTransformerModel:()=>eA,DecisionTransformerPreTrainedModel:()=>O_,DeiTForImageClassification:()=>rA,DeiTModel:()=>tA,DeiTPreTrainedModel:()=>Zi,DepthAnythingForDepthEstimation:()=>nA,DepthAnythingPreTrainedModel:()=>N_,DepthProForDepthEstimation:()=>sA,DepthProPreTrainedModel:()=>D_,DetrForObjectDetection:()=>oA,DetrForSegmentation:()=>iA,DetrModel:()=>aA,DetrObjectDetectionOutput:()=>el,DetrPreTrainedModel:()=>ga,DetrSegmentationOutput:()=>z_,Dinov2ForImageClassification:()=>cA,Dinov2Model:()=>lA,Dinov2PreTrainedModel:()=>tl,Dinov2WithRegistersForImageClassification:()=>dA,Dinov2WithRegistersModel:()=>uA,Dinov2WithRegistersPreTrainedModel:()=>rl,DistilBertForMaskedLM:()=>wA,DistilBertForQuestionAnswering:()=>gA,DistilBertForSequenceClassification:()=>_A,DistilBertForTokenClassification:()=>mA,DistilBertModel:()=>pA,DistilBertPreTrainedModel:()=>Mn,DonutSwinModel:()=>vA,DonutSwinPreTrainedModel:()=>$_,EdgeTamModel:()=>sF,EfficientNetForImageClassification:()=>xA,EfficientNetModel:()=>MA,EfficientNetPreTrainedModel:()=>sl,ElectraForMaskedLM:()=>kA,ElectraForQuestionAnswering:()=>CA,ElectraForSequenceClassification:()=>EA,ElectraForTokenClassification:()=>AA,ElectraModel:()=>TA,ElectraPreTrainedModel:()=>xn,Ernie4_5ForCausalLM:()=>PA,Ernie4_5Model:()=>SA,Ernie4_5PretrainedModel:()=>al,EsmForMaskedLM:()=>IA,EsmForSequenceClassification:()=>LA,EsmForTokenClassification:()=>OA,EsmModel:()=>FA,EsmPreTrainedModel:()=>ls,ExaoneForCausalLM:()=>DA,ExaoneModel:()=>NA,ExaonePreTrainedModel:()=>ol,FalconForCausalLM:()=>BA,FalconH1ForCausalLM:()=>$A,FalconH1Model:()=>RA,FalconH1PreTrainedModel:()=>ll,FalconModel:()=>zA,FalconPreTrainedModel:()=>il,FastViTForImageClassification:()=>VA,FastViTModel:()=>GA,FastViTPreTrainedModel:()=>cl,Florence2ForConditionalGeneration:()=>UA,Florence2PreTrainedModel:()=>G_,GLPNForDepthEstimation:()=>ZA,GLPNModel:()=>KA,GLPNPreTrainedModel:()=>pl,GPT2LMHeadModel:()=>cC,GPT2Model:()=>lC,GPT2PreTrainedModel:()=>vl,GPTBigCodeForCausalLM:()=>tC,GPTBigCodeModel:()=>eC,GPTBigCodePreTrainedModel:()=>_l,GPTJForCausalLM:()=>dC,GPTJModel:()=>uC,GPTJPreTrainedModel:()=>yl,GPTNeoForCausalLM:()=>nC,GPTNeoModel:()=>rC,GPTNeoPreTrainedModel:()=>ml,GPTNeoXForCausalLM:()=>aC,GPTNeoXModel:()=>sC,GPTNeoXPreTrainedModel:()=>gl,Gemma2ForCausalLM:()=>HA,Gemma2Model:()=>qA,Gemma2PreTrainedModel:()=>dl,Gemma3ForCausalLM:()=>XA,Gemma3Model:()=>QA,Gemma3PreTrainedModel:()=>hl,Gemma3nForConditionalGeneration:()=>U_,Gemma3nPreTrainedModel:()=>V_,GemmaForCausalLM:()=>WA,GemmaModel:()=>jA,GemmaPreTrainedModel:()=>ul,GlmForCausalLM:()=>JA,GlmModel:()=>YA,GlmPreTrainedModel:()=>fl,GptOssForCausalLM:()=>iC,GptOssModel:()=>oC,GptOssPreTrainedModel:()=>wl,GraniteForCausalLM:()=>fC,GraniteModel:()=>hC,GraniteMoeHybridForCausalLM:()=>_C,GraniteMoeHybridModel:()=>pC,GraniteMoeHybridPreTrainedModel:()=>Ml,GranitePreTrainedModel:()=>bl,GroundingDinoForObjectDetection:()=>mC,GroundingDinoPreTrainedModel:()=>j_,GroupViTModel:()=>gC,GroupViTPreTrainedModel:()=>W_,HeliumForCausalLM:()=>vC,HeliumModel:()=>wC,HeliumPreTrainedModel:()=>xl,HieraForImageClassification:()=>bC,HieraModel:()=>yC,HieraPreTrainedModel:()=>Tl,HubertForCTC:()=>CC,HubertForSequenceClassification:()=>SC,HubertModel:()=>AC,HubertPreTrainedModel:()=>EC,HunYuanDenseV1ForCausalLM:()=>FC,HunYuanDenseV1Model:()=>PC,HunYuanDenseV1PreTrainedModel:()=>kl,IJepaForImageClassification:()=>OC,IJepaModel:()=>LC,IJepaPreTrainedModel:()=>El,Idefics3ForConditionalGeneration:()=>H_,Idefics3PreTrainedModel:()=>q_,JAISLMHeadModel:()=>DC,JAISModel:()=>NC,JAISPreTrainedModel:()=>Al,JinaCLIPModel:()=>zC,JinaCLIPPreTrainedModel:()=>wa,JinaCLIPTextModel:()=>Q_,JinaCLIPVisionModel:()=>BC,Lfm2ForCausalLM:()=>$C,Lfm2Model:()=>RC,Lfm2MoeForCausalLM:()=>VC,Lfm2MoeModel:()=>GC,Lfm2MoePreTrainedModel:()=>Sl,Lfm2PreTrainedModel:()=>Cl,LiteWhisperForConditionalGeneration:()=>mI,Llama4ForCausalLM:()=>WC,Llama4PreTrainedModel:()=>X_,LlamaForCausalLM:()=>jC,LlamaModel:()=>UC,LlamaPreTrainedModel:()=>Pl,LlavaForConditionalGeneration:()=>ra,LlavaOnevisionForConditionalGeneration:()=>ra,LlavaPreTrainedModel:()=>Y_,LlavaQwen2ForCausalLM:()=>HC,LongT5ForConditionalGeneration:()=>XC,LongT5Model:()=>QC,LongT5PreTrainedModel:()=>Fl,M2M100ForConditionalGeneration:()=>JC,M2M100Model:()=>YC,M2M100PreTrainedModel:()=>Il,MBartForCausalLM:()=>aS,MBartForConditionalGeneration:()=>nS,MBartForSequenceClassification:()=>sS,MBartModel:()=>rS,MBartPreTrainedModel:()=>cs,MPNetForMaskedLM:()=>US,MPNetForQuestionAnswering:()=>qS,MPNetForSequenceClassification:()=>jS,MPNetForTokenClassification:()=>WS,MPNetModel:()=>VS,MPNetPreTrainedModel:()=>Tn,MT5ForConditionalGeneration:()=>YS,MT5Model:()=>XS,MT5PreTrainedModel:()=>Vl,MarianMTModel:()=>ZC,MarianModel:()=>KC,MarianPreTrainedModel:()=>Ll,MaskFormerForInstanceSegmentation:()=>tS,MaskFormerModel:()=>eS,MaskFormerPreTrainedModel:()=>Ol,Metric3DForDepthEstimation:()=>oS,Metric3DPreTrainedModel:()=>J_,Metric3Dv2ForDepthEstimation:()=>iS,Metric3Dv2PreTrainedModel:()=>K_,MgpstrForSceneTextRecognition:()=>lS,MgpstrModelOutput:()=>Z_,MgpstrPreTrainedModel:()=>em,MimiDecoderModel:()=>sm,MimiDecoderOutput:()=>rm,MimiEncoderModel:()=>nm,MimiEncoderOutput:()=>tm,MimiModel:()=>cS,MimiPreTrainedModel:()=>va,MistralForCausalLM:()=>dS,MistralModel:()=>uS,MistralPreTrainedModel:()=>Nl,MobileBertForMaskedLM:()=>fS,MobileBertForQuestionAnswering:()=>_S,MobileBertForSequenceClassification:()=>pS,MobileBertModel:()=>hS,MobileBertPreTrainedModel:()=>us,MobileLLMForCausalLM:()=>gS,MobileLLMModel:()=>mS,MobileLLMPreTrainedModel:()=>Dl,MobileNetV1ForImageClassification:()=>vS,MobileNetV1ForSemanticSegmentation:()=>yS,MobileNetV1Model:()=>wS,MobileNetV1PreTrainedModel:()=>ya,MobileNetV2ForImageClassification:()=>MS,MobileNetV2ForSemanticSegmentation:()=>xS,MobileNetV2Model:()=>bS,MobileNetV2PreTrainedModel:()=>ba,MobileNetV3ForImageClassification:()=>kS,MobileNetV3ForSemanticSegmentation:()=>ES,MobileNetV3Model:()=>TS,MobileNetV3PreTrainedModel:()=>Ma,MobileNetV4ForImageClassification:()=>CS,MobileNetV4ForSemanticSegmentation:()=>SS,MobileNetV4Model:()=>AS,MobileNetV4PreTrainedModel:()=>xa,MobileViTForImageClassification:()=>FS,MobileViTModel:()=>PS,MobileViTPreTrainedModel:()=>zl,MobileViTV2ForImageClassification:()=>LS,MobileViTV2Model:()=>IS,MobileViTV2PreTrainedModel:()=>Bl,ModernBertDecoderForCausalLM:()=>RS,ModernBertDecoderModel:()=>BS,ModernBertDecoderPreTrainedModel:()=>Rl,ModernBertForMaskedLM:()=>NS,ModernBertForSequenceClassification:()=>DS,ModernBertForTokenClassification:()=>zS,ModernBertModel:()=>OS,ModernBertPreTrainedModel:()=>ds,Moondream1ForConditionalGeneration:()=>qC,MoonshineForConditionalGeneration:()=>GS,MoonshineModel:()=>$S,MoonshinePreTrainedModel:()=>$l,MptForCausalLM:()=>QS,MptModel:()=>HS,MptPreTrainedModel:()=>Gl,MultiModalityCausalLM:()=>JS,MultiModalityPreTrainedModel:()=>am,MusicgenForCausalLM:()=>ZS,MusicgenForConditionalGeneration:()=>om,MusicgenModel:()=>KS,MusicgenPreTrainedModel:()=>Ul,NanoChatForCausalLM:()=>tP,NanoChatModel:()=>eP,NanoChatPreTrainedModel:()=>jl,NeoBertForMaskedLM:()=>nP,NeoBertForQuestionAnswering:()=>oP,NeoBertForSequenceClassification:()=>sP,NeoBertForTokenClassification:()=>aP,NeoBertModel:()=>rP,NeoBertPreTrainedModel:()=>kn,NomicBertModel:()=>iP,NomicBertPreTrainedModel:()=>im,OPTForCausalLM:()=>gP,OPTModel:()=>mP,OPTPreTrainedModel:()=>Xl,Olmo2ForCausalLM:()=>dP,Olmo2Model:()=>uP,Olmo2PreTrainedModel:()=>ql,Olmo3ForCausalLM:()=>fP,Olmo3Model:()=>hP,Olmo3PreTrainedModel:()=>Hl,OlmoForCausalLM:()=>cP,OlmoModel:()=>lP,OlmoPreTrainedModel:()=>Wl,OpenELMForCausalLM:()=>_P,OpenELMModel:()=>pP,OpenELMPreTrainedModel:()=>Ql,OwlViTForObjectDetection:()=>bP,OwlViTModel:()=>yP,OwlViTPreTrainedModel:()=>Jl,Owlv2ForObjectDetection:()=>vP,Owlv2Model:()=>wP,Owlv2PreTrainedModel:()=>Yl,PaliGemmaForConditionalGeneration:()=>MP,PaliGemmaPreTrainedModel:()=>lm,ParakeetForCTC:()=>xP,ParakeetPreTrainedModel:()=>cm,PatchTSMixerForPrediction:()=>kP,PatchTSMixerModel:()=>TP,PatchTSMixerPreTrainedModel:()=>Kl,PatchTSTForPrediction:()=>AP,PatchTSTModel:()=>EP,PatchTSTPreTrainedModel:()=>Zl,Phi3ForCausalLM:()=>FP,Phi3Model:()=>PP,Phi3PreTrainedModel:()=>tc,Phi3VForCausalLM:()=>dm,Phi3VPreTrainedModel:()=>um,PhiForCausalLM:()=>SP,PhiModel:()=>CP,PhiPreTrainedModel:()=>ec,PreTrainedModel:()=>P,PvtForImageClassification:()=>LP,PvtModel:()=>IP,PvtPreTrainedModel:()=>rc,PyAnnoteForAudioFrameClassification:()=>NP,PyAnnoteModel:()=>OP,PyAnnotePreTrainedModel:()=>nc,Qwen2ForCausalLM:()=>zP,Qwen2Model:()=>DP,Qwen2PreTrainedModel:()=>sc,Qwen2VLForConditionalGeneration:()=>fm,Qwen2VLPreTrainedModel:()=>hm,Qwen2_5_VLForConditionalGeneration:()=>pm,Qwen3ForCausalLM:()=>RP,Qwen3Model:()=>BP,Qwen3PreTrainedModel:()=>ac,Qwen3VLForConditionalGeneration:()=>_m,Qwen3_5ForConditionalGeneration:()=>mm,Qwen3_5MoeForConditionalGeneration:()=>$P,RFDetrForObjectDetection:()=>jP,RFDetrModel:()=>UP,RFDetrObjectDetectionOutput:()=>gm,RFDetrPreTrainedModel:()=>ic,RTDetrForObjectDetection:()=>$2,RTDetrModel:()=>R2,RTDetrObjectDetectionOutput:()=>is,RTDetrPreTrainedModel:()=>Ji,RTDetrV2ForObjectDetection:()=>rF,RTDetrV2Model:()=>tF,RTDetrV2ObjectDetectionOutput:()=>wm,RTDetrV2PreTrainedModel:()=>lc,ResNetForImageClassification:()=>VP,ResNetModel:()=>GP,ResNetPreTrainedModel:()=>oc,RoFormerForMaskedLM:()=>JP,RoFormerForQuestionAnswering:()=>eF,RoFormerForSequenceClassification:()=>KP,RoFormerForTokenClassification:()=>ZP,RoFormerModel:()=>YP,RoFormerPreTrainedModel:()=>An,RobertaForMaskedLM:()=>qP,RobertaForQuestionAnswering:()=>XP,RobertaForSequenceClassification:()=>HP,RobertaForTokenClassification:()=>QP,RobertaModel:()=>WP,RobertaPreTrainedModel:()=>En,Sam2ImageSegmentationOutput:()=>bm,Sam2Model:()=>cc,Sam2PreTrainedModel:()=>Mm,Sam3TrackerModel:()=>aF,SamImageSegmentationOutput:()=>vm,SamModel:()=>nF,SamPreTrainedModel:()=>ym,SapiensForDepthEstimation:()=>iF,SapiensForNormalEstimation:()=>lF,SapiensForSemanticSegmentation:()=>oF,SapiensPreTrainedModel:()=>Ta,SegformerForImageClassification:()=>uF,SegformerForSemanticSegmentation:()=>dF,SegformerModel:()=>cF,SegformerPreTrainedModel:()=>ka,SiglipModel:()=>hF,SiglipPreTrainedModel:()=>uc,SiglipTextModel:()=>xm,SiglipVisionModel:()=>fF,SmolLM3ForCausalLM:()=>_F,SmolLM3Model:()=>pF,SmolLM3PreTrainedModel:()=>dc,SmolVLMForConditionalGeneration:()=>IC,SnacDecoderModel:()=>km,SnacEncoderModel:()=>Tm,SnacModel:()=>mF,SnacPreTrainedModel:()=>Ea,SpeechT5ForSpeechToText:()=>wF,SpeechT5ForTextToSpeech:()=>vF,SpeechT5HifiGan:()=>yF,SpeechT5Model:()=>gF,SpeechT5PreTrainedModel:()=>Aa,SqueezeBertForMaskedLM:()=>MF,SqueezeBertForQuestionAnswering:()=>TF,SqueezeBertForSequenceClassification:()=>xF,SqueezeBertModel:()=>bF,SqueezeBertPreTrainedModel:()=>hs,StableLmForCausalLM:()=>EF,StableLmModel:()=>kF,StableLmPreTrainedModel:()=>hc,Starcoder2ForCausalLM:()=>CF,Starcoder2Model:()=>AF,Starcoder2PreTrainedModel:()=>fc,StyleTextToSpeech2Model:()=>SF,StyleTextToSpeech2PreTrainedModel:()=>Em,SupertonicForConditionalGeneration:()=>Cm,SupertonicPreTrainedModel:()=>Am,Swin2SRForImageSuperResolution:()=>OF,Swin2SRModel:()=>LF,Swin2SRPreTrainedModel:()=>pc,SwinForImageClassification:()=>FF,SwinForSemanticSegmentation:()=>IF,SwinModel:()=>PF,SwinPreTrainedModel:()=>Ca,T5ForConditionalGeneration:()=>DF,T5Model:()=>NF,T5PreTrainedModel:()=>_c,TableTransformerForObjectDetection:()=>BF,TableTransformerModel:()=>zF,TableTransformerObjectDetectionOutput:()=>Sm,TableTransformerPreTrainedModel:()=>mc,TrOCRForCausalLM:()=>RF,TrOCRPreTrainedModel:()=>Pm,UltravoxModel:()=>Im,UltravoxPreTrainedModel:()=>Fm,UniSpeechForCTC:()=>VF,UniSpeechForSequenceClassification:()=>UF,UniSpeechModel:()=>GF,UniSpeechPreTrainedModel:()=>Sa,UniSpeechSatForAudioFrameClassification:()=>HF,UniSpeechSatForCTC:()=>WF,UniSpeechSatForSequenceClassification:()=>qF,UniSpeechSatModel:()=>jF,UniSpeechSatPreTrainedModel:()=>fs,VaultGemmaForCausalLM:()=>XF,VaultGemmaModel:()=>QF,VaultGemmaPreTrainedModel:()=>gc,ViTForImageClassification:()=>KF,ViTMAEModel:()=>ZF,ViTMAEPreTrainedModel:()=>Lm,ViTMSNForImageClassification:()=>tI,ViTMSNModel:()=>eI,ViTMSNPreTrainedModel:()=>vc,ViTModel:()=>JF,ViTPreTrainedModel:()=>wc,VisionEncoderDecoderModel:()=>YF,VitMatteForImageMatting:()=>rI,VitMattePreTrainedModel:()=>Om,VitPoseForPoseEstimation:()=>nI,VitPosePreTrainedModel:()=>Nm,VitsModel:()=>sI,VitsModelOutput:()=>Dm,VitsPreTrainedModel:()=>zm,VoxtralForConditionalGeneration:()=>$F,Wav2Vec2BertForCTC:()=>oI,Wav2Vec2BertForSequenceClassification:()=>iI,Wav2Vec2BertModel:()=>aI,Wav2Vec2BertPreTrainedModel:()=>Pa,Wav2Vec2ForAudioFrameClassification:()=>kC,Wav2Vec2ForCTC:()=>xC,Wav2Vec2ForSequenceClassification:()=>TC,Wav2Vec2Model:()=>MC,Wav2Vec2PreTrainedModel:()=>Tr,WavLMForAudioFrameClassification:()=>hI,WavLMForCTC:()=>cI,WavLMForSequenceClassification:()=>uI,WavLMForXVector:()=>dI,WavLMModel:()=>lI,WavLMPreTrainedModel:()=>Cn,WeSpeakerResNetModel:()=>fI,WeSpeakerResNetPreTrainedModel:()=>Rm,WhisperForConditionalGeneration:()=>$m,WhisperModel:()=>_I,WhisperPreTrainedModel:()=>yc,XLMForQuestionAnswering:()=>bI,XLMForSequenceClassification:()=>vI,XLMForTokenClassification:()=>yI,XLMModel:()=>gI,XLMPreTrainedModel:()=>Sn,XLMRobertaForMaskedLM:()=>xI,XLMRobertaForQuestionAnswering:()=>EI,XLMRobertaForSequenceClassification:()=>TI,XLMRobertaForTokenClassification:()=>kI,XLMRobertaModel:()=>MI,XLMRobertaPreTrainedModel:()=>Pn,XLMWithLMHeadModel:()=>wI,XVectorOutput:()=>Bm,YolosForObjectDetection:()=>CI,YolosModel:()=>AI,YolosObjectDetectionOutput:()=>Gm,YolosPreTrainedModel:()=>bc,YoutuForCausalLM:()=>PI,YoutuModel:()=>SI,YoutuPreTrainedModel:()=>Mc});var os=class extends P{},DE=class extends os{},zE=class extends os{async _call(e){return new se(await super._call(e))}},BE=class extends os{async _call(e){return new ot(await super._call(e))}},RE=class extends os{async _call(e){return new Je(await super._call(e))}},zi=class extends P{},$E=class extends zi{},GE=class extends zi{},Bi=class extends P{},VE=class extends Bi{},UE=class extends Bi{},Ri=class extends P{},jE=class extends Ri{},WE=class extends Ri{},$i=class extends P{},qE=class extends $i{},HE=class extends $i{},pa=class extends P{},QE=class extends pa{},XE=class extends pa{},YE=class extends pa{async _call(e){return new se(await super._call(e))}},Gi=class extends P{},JE=class extends Gi{},KE=class extends Gi{async _call(e){return new se(await super._call(e))}},gn=class extends P{},ZE=class extends gn{},e2=class extends gn{async _call(e){return new Je(await super._call(e))}},t2=class extends gn{async _call(e){return new se(await super._call(e))}},r2=class extends gn{async _call(e){return new Qe(await super._call(e))}},n2=class extends gn{async _call(e){return new ot(await super._call(e))}},Vi=class extends P{},s2=class extends Vi{},a2=class extends Vi{},Ui=class extends P{},o2=class extends Ui{},i2=class extends Ui{},ji=class extends P{},l2=class extends ji{},c2=class extends ji{},wn=class extends P{},u2=class extends wn{},d2=class extends wn{async _call(e){return new Je(await super._call(e))}},h2=class extends wn{async _call(e){return new se(await super._call(e))}},f2=class extends wn{async _call(e){return new Qe(await super._call(e))}},p2=class extends wn{async _call(e){return new ot(await super._call(e))}},_2=4299n,Wh=6561n,T_=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"]},k_=class extends T_{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:c=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),c&&d&&h&&p&&(w={audio_features:c,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=Ct([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=Ct([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==Wh)-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>=Wh?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),ea(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],_2),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}},E_=class extends P{},m2=class extends E_{},_a=class extends P{},g2=class extends _a{},A_=class extends _a{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},C_=class extends _a{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"audio_model"})}},qr=class extends P{},w2=class extends qr{},v2=class extends qr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},S_=class extends qr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},y2=class extends qr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},b2=class extends qr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Wi=class extends P{},M2=class extends Wi{},x2=class extends Wi{},qi=class extends P{},T2=class extends qi{},k2=class extends qi{},Hi=class extends P{},E2=class extends Hi{},A2=class extends Hi{},Qi=class extends P{},C2=class extends Qi{},S2=class extends Qi{},vn=class extends P{},P2=class extends vn{},F2=class extends vn{async _call(e){return new Je(await super._call(e))}},I2=class extends vn{async _call(e){return new se(await super._call(e))}},L2=class extends vn{async _call(e){return new Qe(await super._call(e))}},O2=class extends vn{async _call(e){return new ot(await super._call(e))}},Xi=class extends P{},N2=class extends Xi{},D2=class extends Xi{async _call(e){return new se(await super._call(e))}},Yi=class extends P{},z2=class extends Yi{},B2=class extends Yi{async _call(e){return new se(await super._call(e))}},Ji=class extends P{},R2=class extends Ji{},$2=class extends Ji{async _call(e){return new is(await super._call(e))}},is=class extends He{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Ki=class extends P{},G2=class extends Ki{},V2=class extends Ki{async _call(e){return new is(await super._call(e))}},P_=class extends He{constructor({audio_codes:e}){super(),this.audio_codes=e}},F_=class extends He{constructor({audio_values:e}){super(),this.audio_values=e}},ma=class extends P{main_input_name="input_values";forward_params=["input_values"]},U2=class extends ma{async encode(e){return new P_(await Me(this.sessions.encoder_model,e))}async decode(e){return new F_(await Me(this.sessions.decoder_model,e))}},I_=class extends ma{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},L_=class extends ma{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{},j2=class extends yn{},W2=class extends yn{async _call(e){return new Je(await super._call(e))}},q2=class extends yn{async _call(e){return new se(await super._call(e))}},H2=class extends yn{async _call(e){return new Qe(await super._call(e))}},Q2=class extends yn{async _call(e){return new ot(await super._call(e))}},bn=class extends P{},X2=class extends bn{},Y2=class extends bn{async _call(e){return new Je(await super._call(e))}},J2=class extends bn{async _call(e){return new se(await super._call(e))}},K2=class extends bn{async _call(e){return new Qe(await super._call(e))}},Z2=class extends bn{async _call(e){return new ot(await super._call(e))}},O_=class extends P{},eA=class extends O_{},Zi=class extends P{},tA=class extends Zi{},rA=class extends Zi{async _call(e){return new se(await super._call(e))}},N_=class extends P{},nA=class extends N_{},D_=class extends P{},sA=class extends D_{},ga=class extends P{},aA=class extends ga{},oA=class extends ga{async _call(e){return new el(await super._call(e))}},iA=class extends ga{async _call(e){return new z_(await super._call(e))}},el=class extends He{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},z_=class extends He{constructor({logits:e,pred_boxes:t,pred_masks:r}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=r}},tl=class extends P{},lA=class extends tl{},cA=class extends tl{async _call(e){return new se(await super._call(e))}},rl=class extends P{},uA=class extends rl{},dA=class extends rl{async _call(e){return new se(await super._call(e))}},B_=class extends P{},hA=class extends B_{},R_=class extends P{},fA=class extends R_{},Mn=class extends P{},pA=class extends Mn{},_A=class extends Mn{async _call(e){return new se(await super._call(e))}},mA=class extends Mn{async _call(e){return new Qe(await super._call(e))}},gA=class extends Mn{async _call(e){return new ot(await super._call(e))}},wA=class extends Mn{async _call(e){return new Je(await super._call(e))}},$_=class extends P{},vA=class extends $_{},nl=class extends P{},yA=class extends nl{},bA=class extends nl{},sl=class extends P{},MA=class extends sl{},xA=class extends sl{async _call(e){return new se(await super._call(e))}},xn=class extends P{},TA=class extends xn{},kA=class extends xn{async _call(e){return new Je(await super._call(e))}},EA=class extends xn{async _call(e){return new se(await super._call(e))}},AA=class extends xn{async _call(e){return new Qe(await super._call(e))}},CA=class extends xn{async _call(e){return new ot(await super._call(e))}},al=class extends P{},SA=class extends al{},PA=class extends al{},ls=class extends P{},FA=class extends ls{},IA=class extends ls{async _call(e){return new Je(await super._call(e))}},LA=class extends ls{async _call(e){return new se(await super._call(e))}},OA=class extends ls{async _call(e){return new Qe(await super._call(e))}},ol=class extends P{},NA=class extends ol{},DA=class extends ol{},il=class extends P{},zA=class extends il{},BA=class extends il{},ll=class extends P{},RA=class extends ll{},$A=class extends ll{},cl=class extends P{},GA=class extends cl{},VA=class extends cl{async _call(e){return new se(await super._call(e))}},G_=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"},UA=class extends G_{_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([Ct(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)}},ul=class extends P{},jA=class extends ul{},WA=class extends ul{},dl=class extends P{},qA=class extends dl{},HA=class extends dl{},hl=class extends P{},QA=class extends hl{},XA=class extends hl{},V_=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"]},U_=class extends V_{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:c=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:c,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 as({image_token_id:this.config.image_token_id,...e,image_features:r})}_merge_input_ids_with_audio_features(e){const t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return x_({audio_token_id:this.config.audio_token_id,...e,audio_features:r})}},fl=class extends P{},YA=class extends fl{},JA=class extends fl{},pl=class extends P{},KA=class extends pl{},ZA=class extends pl{},_l=class extends P{},eC=class extends _l{},tC=class extends _l{},ml=class extends P{},rC=class extends ml{},nC=class extends ml{},gl=class extends P{},sC=class extends gl{},aC=class extends gl{},wl=class extends P{},oC=class extends wl{},iC=class extends wl{},vl=class extends P{},lC=class extends vl{},cC=class extends vl{},yl=class extends P{},uC=class extends yl{},dC=class extends yl{},bl=class extends P{},hC=class extends bl{},fC=class extends bl{},Ml=class extends P{},pC=class extends Ml{},_C=class extends Ml{},j_=class extends P{},mC=class extends j_{},W_=class extends P{},gC=class extends W_{},xl=class extends P{},wC=class extends xl{},vC=class extends xl{},Tl=class extends P{},yC=class extends Tl{},bC=class extends Tl{async _call(e){return new se(await super._call(e))}},Tr=class extends P{},MC=class extends Tr{},xC=class extends Tr{async _call(e){return new Wr(await super._call(e))}},TC=class extends Tr{async _call(e){return new se(await super._call(e))}},kC=class extends Tr{async _call(e){return new Qe(await super._call(e))}},EC=class extends P{},AC=class extends Tr{},CC=class extends Tr{async _call(e){return new Wr(await super._call(e))}},SC=class extends Tr{async _call(e){return new se(await super._call(e))}},kl=class extends P{},PC=class extends kl{},FC=class extends kl{},q_=class extends P{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]},H_=class extends q_{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 as({image_token_id:this.config.image_token_id,...e,image_features:r})}},IC=class extends H_{},El=class extends P{},LC=class extends El{},OC=class extends El{async _call(e){return new se(await super._call(e))}},Al=class extends P{},NC=class extends Al{},DC=class extends Al{},wa=class extends P{},zC=class extends wa{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=Ct([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}},Q_=class extends wa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},BC=class extends wa{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Cl=class extends P{},RC=class extends Cl{},$C=class extends Cl{},Sl=class extends P{},GC=class extends Sl{},VC=class extends Sl{},Pl=class extends P{},UC=class extends Pl{},jC=class extends Pl{},X_=class extends P{},WC=class extends X_{},Y_=class extends P{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},ra=class extends Y_{_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return as({image_token_id:this.config.image_token_index,...e,image_features:r})}},qC=class extends ra{},HC=class extends ra{},Fl=class extends P{},QC=class extends Fl{},XC=class extends Fl{},Il=class extends P{},YC=class extends Il{},JC=class extends Il{},Ll=class extends P{},KC=class extends Ll{},ZC=class extends Ll{},Ol=class extends P{},eS=class extends Ol{},tS=class extends Ol{},cs=class extends P{},rS=class extends cs{},nS=class extends cs{},sS=class extends cs{async _call(e){return new se(await super._call(e))}},aS=class extends cs{},J_=class extends P{},oS=class extends J_{},K_=class extends P{},iS=class extends K_{},Z_=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]}},em=class extends P{},lS=class extends em{async _call(e){return new Z_(await super._call(e))}},tm=class extends He{constructor({audio_codes:e}){super(),this.audio_codes=e}},rm=class extends He{constructor({audio_values:e}){super(),this.audio_values=e}},va=class extends P{main_input_name="input_values";forward_params=["input_values"]},cS=class extends va{async encode(e){return new tm(await Me(this.sessions.encoder_model,e))}async decode(e){return new rm(await Me(this.sessions.decoder_model,e))}},nm=class extends va{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},sm=class extends va{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Nl=class extends P{},uS=class extends Nl{},dS=class extends Nl{},us=class extends P{},hS=class extends us{},fS=class extends us{async _call(e){return new Je(await super._call(e))}},pS=class extends us{async _call(e){return new se(await super._call(e))}},_S=class extends us{async _call(e){return new ot(await super._call(e))}},Dl=class extends P{},mS=class extends Dl{},gS=class extends Dl{},ya=class extends P{},wS=class extends ya{},vS=class extends ya{async _call(e){return new se(await super._call(e))}},yS=class extends ya{},ba=class extends P{},bS=class extends ba{},MS=class extends ba{async _call(e){return new se(await super._call(e))}},xS=class extends ba{},Ma=class extends P{},TS=class extends Ma{},kS=class extends Ma{async _call(e){return new se(await super._call(e))}},ES=class extends Ma{},xa=class extends P{},AS=class extends xa{},CS=class extends xa{async _call(e){return new se(await super._call(e))}},SS=class extends xa{},zl=class extends P{},PS=class extends zl{},FS=class extends zl{async _call(e){return new se(await super._call(e))}},Bl=class extends P{},IS=class extends Bl{},LS=class extends Bl{async _call(e){return new se(await super._call(e))}},ds=class extends P{},OS=class extends ds{},NS=class extends ds{async _call(e){return new Je(await super._call(e))}},DS=class extends ds{async _call(e){return new se(await super._call(e))}},zS=class extends ds{async _call(e){return new Qe(await super._call(e))}},Rl=class extends P{},BS=class extends Rl{},RS=class extends Rl{},$l=class extends P{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},$S=class extends $l{},GS=class extends $l{},Tn=class extends P{},VS=class extends Tn{},US=class extends Tn{async _call(e){return new Je(await super._call(e))}},jS=class extends Tn{async _call(e){return new se(await super._call(e))}},WS=class extends Tn{async _call(e){return new Qe(await super._call(e))}},qS=class extends Tn{async _call(e){return new ot(await super._call(e))}},Gl=class extends P{},HS=class extends Gl{},QS=class extends Gl{},Vl=class extends P{},XS=class extends Vl{},YS=class extends Vl{},am=class extends P{},JS=class extends am{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=ft(e,i.inputNames);r=await Me(i,l)}else{const i=this.sessions.gen_img_embeds,l=ft({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,ft(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,Yo(t.input_ids,BigInt(r.pad_token_id))],0),t.attention_mask=De([t.attention_mask,Yo(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 c=yt.fromTensor(l);i.push(c)}return i}},Ul=class extends P{},KS=class extends Ul{},ZS=class extends Ul{},om=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 c=l%r,d=Math.floor(l/r)%n,h=c-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)),ta(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}},jl=class extends P{},eP=class extends jl{},tP=class extends jl{},kn=class extends P{},rP=class extends kn{},nP=class extends kn{async _call(e){return new Je(await super._call(e))}},sP=class extends kn{async _call(e){return new se(await super._call(e))}},aP=class extends kn{async _call(e){return new Qe(await super._call(e))}},oP=class extends kn{async _call(e){return new ot(await super._call(e))}},im=class extends P{},iP=class extends im{},Wl=class extends P{},lP=class extends Wl{},cP=class extends Wl{},ql=class extends P{},uP=class extends ql{},dP=class extends ql{},Hl=class extends P{},hP=class extends Hl{},fP=class extends Hl{},Ql=class extends P{},pP=class extends Ql{},_P=class extends Ql{},Xl=class extends P{},mP=class extends Xl{},gP=class extends Xl{},Yl=class extends P{},wP=class extends Yl{},vP=class extends Yl{},Jl=class extends P{},yP=class extends Jl{},bP=class extends Jl{},lm=class extends P{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},MP=class extends lm{_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return as({image_token_id:this.config.image_token_index,...e,image_features:r})}},cm=class extends P{},xP=class extends cm{async _call(e){return new Wr(await super._call(e))}},Kl=class extends P{},TP=class extends Kl{},kP=class extends Kl{},Zl=class extends P{},EP=class extends Zl{},AP=class extends Zl{},ec=class extends P{},CP=class extends ec{},SP=class extends ec{},tc=class extends P{},PP=class extends tc{},FP=class extends tc{},um=class extends P{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},dm=class extends um{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,...c}){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)}},rc=class extends P{},IP=class extends rc{},LP=class extends rc{async _call(e){return new se(await super._call(e))}},nc=class extends P{},OP=class extends nc{},NP=class extends nc{async _call(e){return new Qe(await super._call(e))}},sc=class extends P{},DP=class extends sc{},zP=class extends sc{},hm=class extends P{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},fm=class extends hm{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,c=[];if(t||r){let d=e.tolist();n||(n=Sp(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=[],U=0,G=C,W=O;for(let X=0;X<E.length;++X){const F=k.findIndex((dt,We)=>We>U&&dt==a),L=k.findIndex((dt,We)=>We>U&&dt==o),z=G>0&&F!==-1?F:k.length+1,K=W>0&&L!==-1?L:k.length+1;let le,Te,Pe,ut;z<K?([Te,Pe,ut]=m[v],++v,--G,le=z):([Te,Pe,ut]=w[b],++b,--W,le=K);const[Ve,ze,Ue]=[Number(Te),Math.floor(Number(Pe)/l),Math.floor(Number(ut)/l)],be=le-U,fe=x.length>0?Ge(x.at(-1))[0]+1:0;x.push(Array.from({length:3*be},(dt,We)=>fe+We%be));const je=be+fe,_e=Ve*ze*Ue,ye=Array.from({length:_e},(dt,We)=>je+Math.floor(We/(ze*Ue))),cr=Array.from({length:_e},(dt,We)=>je+Math.floor(We/Ue)%ze),kr=Array.from({length:_e},(dt,We)=>je+We%Ue);x.push([ye,cr,kr].flat()),U=le+_e}if(U<k.length){const X=x.length>0?Ge(x.at(-1))[0]+1:0,F=k.length-U;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 V=h[M];for(let X=0;X<V.length;++X)if(V[X]==1){for(let F=0;F<3;++F)p[F][M][X]=q[F*J/3+N];++N}const ee=Ge(q)[0];c.push(ee+1-d[M].length)}return[new j("int64",p.flat(1/0),[3,e.dims[0],e.dims[1]]),new j("int64",c,[c.length,1])]}else if(n){const{data:d,dims:h}=b_(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]),Pp([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 as({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,t,r){if(t.attention_mask&&!t.position_ids)if(!t.past_key_values)[t.position_ids,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);else{t.pixel_values=null;const n=BigInt(Object.values(t.past_key_values)[0].dims.at(-2)),s=t.rope_deltas.map(a=>n+a);t.position_ids=mn([s,s,s],0)}return t}},pm=class extends fm{image_grid_thw_name="image_grid_thw"},ac=class extends P{},BP=class extends ac{},RP=class extends ac{},_m=class extends pm{},mm=class extends _m{},$P=class extends mm{},oc=class extends P{},GP=class extends oc{},VP=class extends oc{async _call(e){return new se(await super._call(e))}},ic=class extends P{},UP=class extends ic{},jP=class extends ic{async _call(e){return new gm(await super._call(e))}},gm=class extends is{},En=class extends P{},WP=class extends En{},qP=class extends En{async _call(e){return new Je(await super._call(e))}},HP=class extends En{async _call(e){return new se(await super._call(e))}},QP=class extends En{async _call(e){return new Qe(await super._call(e))}},XP=class extends En{async _call(e){return new ot(await super._call(e))}},An=class extends P{},YP=class extends An{},JP=class extends An{async _call(e){return new Je(await super._call(e))}},KP=class extends An{async _call(e){return new se(await super._call(e))}},ZP=class extends An{async _call(e){return new Qe(await super._call(e))}},eF=class extends An{async _call(e){return new ot(await super._call(e))}},lc=class extends P{},tF=class extends lc{},rF=class extends lc{async _call(e){return new wm(await super._call(e))}},wm=class extends is{},vm=class extends He{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},ym=class extends P{},nF=class extends ym{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??=Ct(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 vm(await super._call(e))}},bm=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{},cc=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??=Ct(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=ft(e,n.inputNames);return await Me(n,s)}async _call(e){return new bm(await super._call(e))}},sF=class extends cc{},aF=class extends cc{},Ta=class extends P{},oF=class extends Ta{},iF=class extends Ta{},lF=class extends Ta{},ka=class extends P{},cF=class extends ka{},uF=class extends ka{},dF=class extends ka{},uc=class extends P{},hF=class extends uc{},xm=class extends uc{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},fF=class extends qr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},dc=class extends P{},pF=class extends dc{},_F=class extends dc{},Ea=class extends P{main_input_name="input_values";forward_params=["input_values"]},mF=class extends Ea{async encode(e){return await Me(this.sessions.encoder_model,e)}async decode(e){return await Me(this.sessions.decoder_model,e)}},Tm=class extends Ea{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},km=class extends Ea{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Aa=class extends P{},gF=class extends Aa{},wF=class extends Aa{},vF=class extends Aa{async generate_speech(e,t,{threshold:r=.5,minlenratio:n=0,maxlenratio:s=20,vocoder:a=null}={}){const o={input_ids:e},{encoder_outputs:i,encoder_attention_mask:l}=await xr(this,o),c=i.dims[1]/this.config.reduction_factor,d=Math.floor(c*s),h=Math.floor(c*n),p=this.config.num_mel_bins;let m=[],w=null,v=null,b=0;for(;;){++b;const A=v_(!!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(U=>U>=r).length>0||b>=d))break}const M=De(m),{waveform:k}=await Me(a.sessions.model,{spectrogram:M});return{spectrogram:M,waveform:k}}},yF=class extends P{main_input_name="spectrogram"},hs=class extends P{},bF=class extends hs{},MF=class extends hs{async _call(e){return new Je(await super._call(e))}},xF=class extends hs{async _call(e){return new se(await super._call(e))}},TF=class extends hs{async _call(e){return new ot(await super._call(e))}},hc=class extends P{},kF=class extends hc{},EF=class extends hc{},fc=class extends P{},AF=class extends fc{},CF=class extends fc{},Em=class extends P{},SF=class extends Em{},Am=class extends P{},Cm=class extends Am{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:c,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=d1([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:c,attention_mask:t,timestep:W,num_inference_steps:x}))}const{waveform:U}=await Me(this.sessions.voice_decoder,{latents:C});return{waveform:U,durations:h}}},Ca=class extends P{},PF=class extends Ca{},FF=class extends Ca{async _call(e){return new se(await super._call(e))}},IF=class extends Ca{},pc=class extends P{},LF=class extends pc{},OF=class extends pc{},_c=class extends P{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]},NF=class extends _c{},DF=class extends _c{},mc=class extends P{},zF=class extends mc{},BF=class extends mc{async _call(e){return new Sm(await super._call(e))}},Sm=class extends el{},Pm=class extends P{},RF=class extends Pm{},Fm=class extends P{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},Im=class extends Fm{_merge_input_ids_with_audio_features(e){const t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return x_({audio_token_id:this.config.ignore_index??this.config.audio_token_id,...e,audio_features:r})}},$F=class extends Im{},Sa=class extends P{},GF=class extends Sa{},VF=class extends Sa{async _call(e){return new Wr(await super._call(e))}},UF=class extends Sa{async _call(e){return new se(await super._call(e))}},fs=class extends P{},jF=class extends fs{},WF=class extends fs{async _call(e){return new Wr(await super._call(e))}},qF=class extends fs{async _call(e){return new se(await super._call(e))}},HF=class extends fs{async _call(e){return new Qe(await super._call(e))}},gc=class extends P{},QF=class extends gc{},XF=class extends gc{},YF=class extends P{main_input_name="pixel_values";forward_params=["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"]},wc=class extends P{},JF=class extends wc{},KF=class extends wc{async _call(e){return new se(await super._call(e))}},Lm=class extends P{},ZF=class extends Lm{},vc=class extends P{},eI=class extends vc{},tI=class extends vc{async _call(e){return new se(await super._call(e))}},Om=class extends P{},rI=class extends Om{async _call(e){return new pE(await super._call(e))}},Nm=class extends P{},nI=class extends Nm{},Dm=class extends He{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}},zm=class extends P{},sI=class extends zm{async _call(e){return new Dm(await super._call(e))}},Pa=class extends P{},aI=class extends Pa{},oI=class extends Pa{async _call(e){return new Wr(await super._call(e))}},iI=class extends Pa{async _call(e){return new se(await super._call(e))}},Bm=class extends He{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},Cn=class extends P{},lI=class extends Cn{},cI=class extends Cn{async _call(e){return new Wr(await super._call(e))}},uI=class extends Cn{async _call(e){return new se(await super._call(e))}},dI=class extends Cn{async _call(e){return new Bm(await super._call(e))}},hI=class extends Cn{async _call(e){return new Qe(await super._call(e))}},Rm=class extends P{},fI=class extends Rm{},pI=class extends g_{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},yc=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"]},_I=class extends yc{},$m=class extends yc{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,pI)}_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=`<|${aT(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 ei,r.push(new gE(t,a))),t.begin_suppress_tokens&&(r??=new ei,r.push(new m_(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,c]=Cp(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=c[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(qx(C,s))}}}const h=[Ti(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]=Qx(v.tolist()),k=Array.from({length:b.length-1},(C,O)=>b[O+1]-b[O]),A=Dt([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}},mI=class extends $m{},Sn=class extends P{},gI=class extends Sn{},wI=class extends Sn{async _call(e){return new Je(await super._call(e))}},vI=class extends Sn{async _call(e){return new se(await super._call(e))}},yI=class extends Sn{async _call(e){return new Qe(await super._call(e))}},bI=class extends Sn{async _call(e){return new ot(await super._call(e))}},Pn=class extends P{},MI=class extends Pn{},xI=class extends Pn{async _call(e){return new Je(await super._call(e))}},TI=class extends Pn{async _call(e){return new se(await super._call(e))}},kI=class extends Pn{async _call(e){return new Qe(await super._call(e))}},EI=class extends Pn{async _call(e){return new ot(await super._call(e))}},bc=class extends P{},AI=class extends bc{},CI=class extends bc{async _call(e){return new Gm(await super._call(e))}},Gm=class extends He{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Mc=class extends P{},SI=class extends Mc{},PI=class extends Mc{},FI=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"]]),II=new Map([["t5","T5Model"],["longt5","LongT5Model"],["mt5","MT5Model"],["bart","BartModel"],["mbart","MBartModel"],["marian","MarianModel"],["whisper","WhisperModel"],["m2m_100","M2M100Model"],["blenderbot","BlenderbotModel"],["blenderbot-small","BlenderbotSmallModel"]]),LI=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),OI=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"]]),Vm=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"]]),Um=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),jm=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),Wm=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"]]),qm=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"]]),Hm=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),Qm=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"]]),NI=new Map([["multi_modality","MultiModalityCausalLM"]]),Xm=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"]]),Ym=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"]]),Jm=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),Km=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"]]),Zm=new Map([["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"]]),DI=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),eg=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"]]),tg=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),rg=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),on=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),ng=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),sg=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),ag=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),og=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),ig=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),lg=new Map([["wavlm","WavLMForXVector"]]),cg=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),ug=new Map([["vitmatte","VitMatteForImageMatting"]]),zI=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),dg=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),hg=new Map([["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),fg=new Map([["sapiens","SapiensForNormalEstimation"]]),pg=new Map([["vitpose","VitPoseForPoseEstimation"]]),_g=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),mg=[[FI,$.EncoderOnly],[II,$.EncoderDecoder],[OI,$.DecoderOnlyWithoutHead],[LI,$.AutoEncoder],[Wm,$.EncoderOnly],[qm,$.EncoderOnly],[Hm,$.Seq2Seq],[Vm,$.Seq2Seq],[Qm,$.DecoderOnly],[NI,$.MultiModality],[Xm,$.EncoderOnly],[Ym,$.EncoderOnly],[Jm,$.Vision2Seq],[Km,$.ImageTextToText],[Zm,$.AudioTextToText],[eg,$.EncoderOnly],[on,$.EncoderOnly],[sg,$.EncoderOnly],[ng,$.EncoderOnly],[ug,$.EncoderOnly],[zI,$.EncoderOnly],[dg,$.EncoderOnly],[hg,$.EncoderOnly],[fg,$.EncoderOnly],[pg,$.EncoderOnly],[tg,$.EncoderOnly],[rg,$.EncoderOnly],[ag,$.MaskGeneration],[og,$.EncoderOnly],[ig,$.EncoderOnly],[Um,$.Seq2Seq],[jm,$.EncoderOnly],[lg,$.EncoderOnly],[cg,$.EncoderOnly],[_g,$.EncoderOnly]];for(const[e,t]of mg)for(const r of e.values()){Mr.set(r,t);const n=Di[r];un.set(n,r),Ni.set(r,n)}var BI=[["MusicgenForConditionalGeneration",om,$.Musicgen],["Phi3VForCausalLM",dm,$.Phi3V],["CLIPTextModelWithProjection",S_,$.EncoderOnly],["SiglipTextModel",xm,$.EncoderOnly],["JinaCLIPTextModel",Q_,$.EncoderOnly],["ClapTextModelWithProjection",A_,$.EncoderOnly],["ClapAudioModelWithProjection",C_,$.EncoderOnly],["DacEncoderModel",I_,$.EncoderOnly],["DacDecoderModel",L_,$.EncoderOnly],["MimiEncoderModel",nm,$.EncoderOnly],["MimiDecoderModel",sm,$.EncoderOnly],["SnacEncoderModel",Tm,$.EncoderOnly],["SnacDecoderModel",km,$.EncoderOnly],["Gemma3nForConditionalGeneration",U_,$.ImageAudioTextToText],["SupertonicForConditionalGeneration",Cm,$.Supertonic],["ChatterboxModel",k_,$.Chatterbox]];for(const[e,t,r]of BI)Mr.set(e,r),un.set(t,e),Ni.set(e,t);var gg=new Map([["modnet",on],["birefnet",on],["isnet",on],["ben",on]]);for(const[e,t]of gg.entries())t.set(e,"PreTrainedModel"),Mr.set(e,$.EncoderOnly),Ni.set(e,P);Mr.set("PreTrainedModel",$.EncoderOnly);un.set(P,"PreTrainedModel");var ke={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:Wm,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:qm,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:Um,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:jm,MODEL_FOR_MASKED_LM_MAPPING_NAMES:Xm,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:Ym,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:eg,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:on,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:ng,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:sg,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:tg,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:rg,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:ag,MODEL_FOR_CTC_MAPPING_NAMES:og,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:ig,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:lg,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:cg,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:DI,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:ug,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:dg,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:hg,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:fg,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:pg,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:_g,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:Km,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:Zm,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:Hm,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:Vm,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:Qm,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:Jm};FE(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:c=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:c,use_external_data_format:d,session_options:h};if(p.config=await Li.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 Di[v].from_pretrained(e,p)}if(this.BASE_IF_FAIL)return gg.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=mg.map(e=>e[0]);static BASE_IF_FAIL=!0},qh=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},RI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},$o=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},$I=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},GI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},VI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},UI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},jI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},WI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},qI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},HI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},Hh=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},Qh=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},Xh=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},QI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},XI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]},jL=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]},YI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_CTC_MAPPING_NAMES]},JI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]},WL=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]},qL=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]},KI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]},HL=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]},ZI=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},eL=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]},QL=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]},XL=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]},tL=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]},YL=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]},JL=class extends Ee{static MODEL_CLASS_MAPPINGS=[ke.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function Vt(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(t=>yt.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?pT(r,t):r instanceof Float64Array?new Float32Array(r):r))}function ri(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 St{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()}},rL=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 c=o(l),d=await _n(c,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]}},nL=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 c=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([c[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]}},sL=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:c,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||c.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=Mb(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,U]=A[C],G=m.slice(O,x+1),W=this.tokenizer.decode(G,{skip_special_tokens:!0});E.push({answer:W,score:U})}r===1?h.push(...E):h.push(E)}return s?h:h[0]}},aL=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 c=i[l],d=c.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=c.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]}},xc=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}))}},oL=class extends xc{_key="summary_text"},iL=class extends xc{_key="translation_text"};function Yh(e){return Array.isArray(e)&&e.every(t=>"role"in t&&"content"in t)}var lL=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(Yh(e))e=[e];else if(Array.isArray(e)&&e.every(Yh))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}),c=await this.model.generate({...l,...t}),d=this.tokenizer.batch_decode(c,{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/c.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}},cL=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 c=[];for(const p of a){const m=this.tokenizer(l,{text_pair:p,padding:!0,truncation:!0}),w=await this.model(m);o?c.push([w.logits.data[this.contradiction_id],w.logits.data[this.entailment_id]]):c.push(w.logits.data[this.entailment_id])}const h=(o?c.map(p=>tt(p)[1]):tt(c)).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]}},uL=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),c=(await this.model(i)).logits[0],d=await _n(new j("float32",tt(c.data),c.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]}},dL=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(c=>r.replace("{}",c)),a=this.tokenizer(s,{padding:!0,truncation:!0}),o=this.processor.feature_extractor.config.sampling_rate,i=await Yn(e,o),l=[];for(const c of i){const d=await this.processor(c),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}},hL=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,c=this.processor.feature_extractor.config,d=c.chunk_length/this.model.config.max_source_positions,h=c.hop_length,p=c.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,U=v.subarray(O,x),G=await this.processor(U),W=O===0,J=x>=v.length;if(b.push({stride:[U.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),c=Math.floor(i.length/s)*6,d=await this.model.generate({max_new_tokens:c,...t,...l}),h=this.processor.batch_decode(d,{skip_special_tokens:!0})[0];o.push({text:h})}return r?o[0]:o}},fL=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 ve.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 c=0;c<a;++c){const d=i?Math.min(Math.ceil(i[c]),o):o,h=c*o;l.push(new TT(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:c}=await this.model.generate_speech({...o,style:t,num_inference_steps:r,speed:n});return this._postprocess_waveform(e,l,s,c)}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)}},pL=class extends $e{async _call(e,t={}){const r=Array.isArray(e),n=await Vt(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(c=>({generated_text:c.trim()}));a.push(l)}return r?a:a[0]}},_L=class extends $e{async _call(e,{top_k:t=5}={}){const r=await Vt(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),c=l[0].tolist(),h=l[1].tolist().map((p,m)=>({label:a?a[p]:`LABEL_${p}`,score:c[m]}));o.push(h)}return Array.isArray(e)?o:o[0]}},Jh={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},wg=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 Vt(e),c=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=Jh[o];else if(this.processor.image_processor){for(const[M,k]of Object.entries(Jh))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??c)[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 yt(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??c)[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 yt(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<c.length;++A){const E=c[A],C=k[A];C.data.some(x=>x<-1e-5||x>1+1e-5)&&C.sigmoid_();const O=await yt.fromTensor(C.mul_(255).to("uint8")).resize(E[1],E[0]);b.push({label:null,score:null,mask:O})}}return b}},mL=class extends wg{async _call(e,t={}){const r=await Vt(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]}},gL=class extends $e{async _call(e,t,{hypothesis_template:r="This is a photo of {}"}={}){const n=Array.isArray(e),s=await Vt(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}),c=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=[...c(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]}},wL=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 Vt(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}),c=this.processor.image_processor.post_process_object_detection(l,t,a),{id2label:d}=this.model.config,h=c.map(p=>p.boxes.map((m,w)=>({score:p.scores[w],label:d[p.classes[w]],box:ri(m,!r)})));return n?h:h[0]}},vL=class extends $e{async _call(e,t,{threshold:r=.1,top_k:n=null,percentage:s=!1}={}){const a=Array.isArray(e),o=await Vt(e),i=this.tokenizer(t,{padding:!0,truncation:!0}),l=await this.processor(o),c=[];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:ri(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:ri(M,!s)}))}v.sort((b,M)=>M.score-b.score),n!==null&&(v=v.slice(0,n)),c.push(v)}return a?c:c[0]}},yL=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 Vt(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}),c=this.tokenizer.batch_decode(i)[0].match(/<s_answer>(.*?)<\/s_answer>/);let d=null;return c&&c.length>=2&&(d=c[1].trim()),[{answer:d}]}},bL=class extends $e{async _call(e){const t=await Vt(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(yt.fromTensor(o))}return Array.isArray(e)?s:s[0]}},ML=class extends $e{async _call(e){const t=await Vt(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),[c,d]=t[a].size,h=(await yr(o.view(1,1,i,l),{size:[d,c],mode:"bilinear"})).view(d,c),p=h.min().item(),m=h.max().item(),w=h.sub(p).div_(m-p).mul_(255).to("uint8").unsqueeze(0),v=yt.fromTensor(w);s.push({predicted_depth:h,depth:v})}return Array.isArray(e)?s:s[0]}},xL=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=u1(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=h1(i,s)),i}},TL=class extends $e{async _call(e,{pool:t=null}={}){const r=await Vt(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}},na=Object.freeze({"text-classification":{tokenizer:ce,pipeline:rL,model:qh,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:ce,pipeline:nL,model:RI,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:ce,pipeline:sL,model:WI,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:ce,pipeline:aL,model:jI,default:{model:"onnx-community/ettin-encoder-32m-ONNX",dtype:"fp32"},type:"text"},summarization:{tokenizer:ce,pipeline:oL,model:$o,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:ce,pipeline:iL,model:$o,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:ce,pipeline:xc,model:$o,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:ce,pipeline:lL,model:UI,default:{model:"onnx-community/Qwen3-0.6B-ONNX",dtype:"q4"},type:"text"},"zero-shot-classification":{tokenizer:ce,pipeline:cL,model:qh,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:uL,model:JI,processor:ct,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:ce,pipeline:dL,model:Qn,processor:ct,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:ce,pipeline:hL,model:[$I,YI],processor:ct,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:ce,pipeline:fL,model:[VI,GI],processor:[ct,null],default:{model:"onnx-community/Supertonic-TTS-ONNX",dtype:"fp32"},type:"text"},"image-to-text":{tokenizer:ce,pipeline:pL,model:qI,processor:ct,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:_L,model:HI,processor:ct,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:wg,model:[Hh,Qh,Xh],processor:ct,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:mL,model:[Hh,Qh,Xh],processor:ct,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:ce,pipeline:gL,model:Qn,processor:ct,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:wL,model:QI,processor:ct,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:ce,pipeline:vL,model:XI,processor:ct,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:ce,pipeline:yL,model:KI,processor:ct,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:bL,model:ZI,processor:ct,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:ML,model:eL,processor:ct,default:{model:"onnx-community/depth-anything-v2-small"},type:"image"},"feature-extraction":{tokenizer:ce,pipeline:xL,model:Qn,default:{model:"onnx-community/all-MiniLM-L6-v2-ONNX",dtype:"fp32"},type:"text"},"image-feature-extraction":{processor:ct,pipeline:TL,model:[tL,Qn],default:{model:"onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX",dtype:"fp32"},type:"image"}}),vg=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function yg(e,{config:t=null,dtype:r=null,device:n=null,model_file_name:s=null}={}){t=await Li.from_pretrained(e,{config:t});const a=["config.json"],o=t["transformers.js_config"]??{},i=o.use_external_data_format,l="onnx",c=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: ${ua}`),h=$.EncoderOnly}const w=(b,M=null)=>{M=M??b;const k=Mp(c,b),A=xp(d,b,k),E=Xo[A]??"",C=`${M}${E}.onnx`,O=`${l}/${C}`;a.push(O);const x=f_(i,C,b);for(const U of p_(C,x)){const G=`${l}/${U}`;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 bg(e){if(!e)throw new Error("modelId is required");return(await ss(e,Zn,{})).exists?[Zn]:[]}async function Fa(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 yg(e,{config:t,dtype:r,device:n,model_file_name:s});if(a){const l=await Ei(e);i.push(...l)}if(o){const l=await bg(e);i.push(...l)}return i}function kL(e){const t=na[e];return t?{tokenizer:!!t.tokenizer,processor:!!t.processor}:null}async function Ia(e,t,r={}){e=vg[e]??e;const n=kL(e);if(!n)throw new Error(`Unsupported pipeline task: ${e}. Must be one of [${Object.keys(na).join(", ")}]`);return Fa(t,{...r,include_tokenizer:n.tokenizer,include_processor:n.processor})}async function KL(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:c="onnx",use_external_data_format:d=null,model_file_name:h=null,session_options:p={}}={}){e=vg[e]??e;const m=na[e.split("_",1)[0]];if(!m)throw Error(`Unsupported pipeline: ${e}. Must be one of [${Object.keys(na)}]`);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 Ia(e,t,{device:i,dtype:l});(await Promise.all(A.map(async C=>ss(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,U)=>x+U.loaded,0),C=Object.values(w).reduce((x,U)=>x+U.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:c,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 EL(b,t,v);M.task=e,Dr(r,{status:"ready",task:e,model:t});const k=m.pipeline;return new k(M)}async function EL(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,c)=>{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{c(p);return}}}c(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}var AL=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,CL=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},Kh=Se.IS_PROCESS_AVAILABLE?e=>process.stdout.write(e):e=>console.log(e),SL=class extends CL{constructor(e,{skip_prompt:t=!1,callback_function:r=null,token_callback_function:n=null,skip_special_tokens:s=!0,decode_kwargs:a={},...o}={}){super(),this.tokenizer=e,this.skip_prompt=t,this.callback_function=r??Kh,this.token_callback_function=n,this.decode_kwargs={skip_special_tokens:s,...a,...o},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0,this.special_ids=new Set(this.tokenizer.all_special_ids.map(BigInt))}put(e){if(e.length>1)throw Error("TextStreamer only supports batch size of 1");const t=this.next_tokens_are_prompt;if(t&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;const r=e[0];if(this.token_callback_function?.(r),r.length===1&&this.special_ids.has(r[0])){if(this.decode_kwargs.skip_special_tokens)return;if(this.token_cache.length>0){const i=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len);this.on_finalized_text(i,!1),this.token_cache=[],this.print_len=0}const a=this.tokenizer.decode(r,this.decode_kwargs);this.on_finalized_text(a,!1);return}this.token_cache=Dt(this.token_cache,r);const n=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let s;t||n.endsWith(`
30
+ `)?(s=n.slice(this.print_len),this.token_cache=[],this.print_len=0):n.length>0&&AL(n.charCodeAt(n.length-1))?(s=n.slice(this.print_len),this.print_len+=s.length):(s=n.slice(this.print_len,n.lastIndexOf(" ")+1),this.print_len+=s.length),this.on_finalized_text(s,!1)}end(){let e;this.token_cache.length>0?(e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):e="",this.next_tokens_are_prompt=!0,this.on_finalized_text(e,!0)}on_finalized_text(e,t){e.length>0&&this.callback_function?.(e),t&&this.callback_function===Kh&&Se.IS_PROCESS_AVAILABLE&&this.callback_function?.(`
31
+ `)}},ZL=class extends SL{constructor(e,{skip_prompt:t=!1,callback_function:r=null,token_callback_function:n=null,on_chunk_start:s=null,on_chunk_end:a=null,on_finalize:o=null,time_precision:i=.02,skip_special_tokens:l=!0,decode_kwargs:c={}}={}){super(e,{skip_prompt:t,skip_special_tokens:l,callback_function:r,token_callback_function:n,decode_kwargs:c}),this.timestamp_begin=e.timestamp_begin,this.on_chunk_start=s,this.on_chunk_end=a,this.on_finalize=o,this.time_precision=i,this.waiting_for_timestamp=!1}put(e){if(e.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const t=e[0];if(t.length===1){const r=Number(t[0])-this.timestamp_begin;if(r>=0){const n=r*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(n):this.on_chunk_start?.(n),this.waiting_for_timestamp=!this.waiting_for_timestamp,this.token_callback_function?.(t);return}}return super.put(e)}end(){super.end(),this.on_finalize?.()}},Mg=class{constructor(e,t){this.image=e,this.timestamp=t}},PL=class{constructor(e,t){e.length>0&&e[0]instanceof yt&&(e=e.map((r,n)=>new Mg(r,(n+1)/(e.length+1)*t))),this.frames=e,this.duration=t}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}};async function eO(e,{num_frames:t=null,fps:r=null}={}){if(!Se.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(t==null&&r==null)throw new Error("Either num_frames or fps must be provided.");const n=[],s=document.createElement("video");if(s.crossOrigin="anonymous",s.muted=!0,typeof e=="string")s.src=e;else if(e instanceof Blob)s.src=URL.createObjectURL(e);else if(e instanceof HTMLVideoElement)s.src=e.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(h=>s.onloadedmetadata=h),s.seekable.start(0)===s.seekable.end(0)){const p=await(await ve.fetch(s.src)).blob();s.src=URL.createObjectURL(p),await new Promise(m=>s.onloadedmetadata=m)}const a=s.duration;let o,i;t!=null?(o=t,i=t===1?0:a/(t-1)):(i=1/r,o=Math.floor(a/i));let l=[];for(let h=0;h<o;++h)l.push(t===1?a/2:h*i);const c=document.createElement("canvas");c.width=s.videoWidth,c.height=s.videoHeight;const d=c.getContext("2d",{willReadFrequently:!0});for(const h of l){s.currentTime=h,await new Promise(v=>{s.onseeked=v}),d.drawImage(s,0,0,c.width,c.height);const p=d.getImageData(0,0,c.width,c.height),m=new yt(p.data,c.width,c.height,4),w=new Mg(m,h);n.push(w)}return s.remove(),new PL(n,a)}async function xg(e,t,r={}){const n=await ns(r?.cache_dir);if(!n)return{allCached:!1,files:t.map(o=>({file:o,cached:!1}))};const s=await Promise.all(t.map(async a=>{const{localPath:o,proposedCacheKey:i}=ia(e,a,r,n),l=await la(n,o,i);return{file:a,cached:!!l}}));return{allCached:s.every(a=>a.cached),files:s}}async function FL(e,t={}){if(!e)throw new Error("modelId is required");const r=await Fa(e,t);return await xg(e,r,t)}async function IL(e,t,r={}){if(!e)throw new Error("task is required");if(!t)throw new Error("modelId is required");const n=await Ia(e,t,r);return await xg(t,n,r)}async function Tg(e,t,r={}){const n=await ns(r?.cache_dir);if(!n)return{filesDeleted:0,filesCached:0,files:t.map(a=>({file:a,deleted:!1,wasCached:!1}))};if(!n.delete)throw new Error("Cache does not support delete operation");const s=await Promise.all(t.map(async a=>{const{localPath:o,proposedCacheKey:i}=ia(e,a,r,n),c=!!await la(n,o,i);let d=!1;if(c){const h=await n.delete(i),p=!h&&i!==o?await n.delete(o):!1;d=h||p}return{file:a,deleted:d,wasCached:c}}));return{filesDeleted:s.filter(a=>a.deleted).length,filesCached:s.filter(a=>a.wasCached).length,files:s}}async function LL(e,t={}){if(!e)throw new Error("modelId is required");const r=await Fa(e,t);return await Tg(e,r,t)}async function OL(e,t,r={}){if(!e)throw new Error("task is required");if(!t)throw new Error("modelId is required");const n=await Ia(e,t,r);return await Tg(t,n,r)}var tO=class{static async get_files(e,t={}){return Fa(e,t)}static async get_pipeline_files(e,t,r={}){return Ia(e,t,r)}static async get_model_files(e,t={}){return yg(e,t)}static async get_tokenizer_files(e){return Ei(e)}static async get_processor_files(e){return bg(e)}static async is_cached(e,t={}){return FL(e,t)}static async is_pipeline_cached(e,t,r={}){return IL(e,t,r)}static async get_file_metadata(e,t,r={}){return ss(e,t,r)}static async clear_cache(e,t={}){return LL(e,t)}static async clear_pipeline_cache(e,t,r={}){return OL(e,t,r)}};export{kT as ASTFeatureExtractor,HE as ASTForAudioClassification,qE as ASTModel,$i as ASTPreTrainedModel,UE as AfmoeForCausalLM,VE as AfmoeModel,Bi as AfmoePreTrainedModel,RE as AlbertForMaskedLM,BE as AlbertForQuestionAnswering,zE as AlbertForSequenceClassification,DE as AlbertModel,os as AlbertPreTrainedModel,g1 as AlbertTokenizer,GE as ApertusForCausalLM,$E as ApertusModel,zi as ApertusPreTrainedModel,WE as ArceeForCausalLM,jE as ArceeModel,Ri as ArceePreTrainedModel,uL as AudioClassificationPipeline,Li as AutoConfig,lr as AutoFeatureExtractor,_t as AutoImageProcessor,Qn as AutoModel,JI as AutoModelForAudioClassification,qL as AutoModelForAudioFrameClassification,JL as AutoModelForAudioTextToText,YI as AutoModelForCTC,UI as AutoModelForCausalLM,eL as AutoModelForDepthEstimation,KI as AutoModelForDocumentQuestionAnswering,HI as AutoModelForImageClassification,tL as AutoModelForImageFeatureExtraction,HL as AutoModelForImageMatting,Hh as AutoModelForImageSegmentation,YL as AutoModelForImageTextToText,ZI as AutoModelForImageToImage,jL as AutoModelForMaskGeneration,jI as AutoModelForMaskedLM,QL as AutoModelForNormalEstimation,QI as AutoModelForObjectDetection,XL as AutoModelForPoseEstimation,WI as AutoModelForQuestionAnswering,Qh as AutoModelForSemanticSegmentation,$o as AutoModelForSeq2SeqLM,qh as AutoModelForSequenceClassification,$I as AutoModelForSpeechSeq2Seq,GI as AutoModelForTextToSpectrogram,VI as AutoModelForTextToWaveform,RI as AutoModelForTokenClassification,Xh as AutoModelForUniversalSegmentation,qI as AutoModelForVision2Seq,WL as AutoModelForXVector,XI as AutoModelForZeroShotObjectDetection,ct as AutoProcessor,ce as AutoTokenizer,hL as AutomaticSpeechRecognitionPipeline,mL as BackgroundRemovalPipeline,XE as BartForConditionalGeneration,YE as BartForSequenceClassification,QE as BartModel,pa as BartPretrainedModel,w1 as BartTokenizer,CL as BaseStreamer,jT as BeitFeatureExtractor,KE as BeitForImageClassification,JE as BeitModel,Gi as BeitPreTrainedModel,e2 as BertForMaskedLM,n2 as BertForQuestionAnswering,t2 as BertForSequenceClassification,r2 as BertForTokenClassification,ZE as BertModel,gn as BertPreTrainedModel,v1 as BertTokenizer,WT as BitImageProcessor,a2 as BlenderbotForConditionalGeneration,s2 as BlenderbotModel,Vi as BlenderbotPreTrainedModel,i2 as BlenderbotSmallForConditionalGeneration,o2 as BlenderbotSmallModel,Ui as BlenderbotSmallPreTrainedModel,y1 as BlenderbotSmallTokenizer,b1 as BlenderbotTokenizer,c2 as BloomForCausalLM,l2 as BloomModel,ji as BloomPreTrainedModel,M1 as BloomTokenizer,HT as CLIPFeatureExtractor,Qp as CLIPImageProcessor,w2 as CLIPModel,qr as CLIPPreTrainedModel,x2 as CLIPSegForImageSegmentation,M2 as CLIPSegModel,Wi as CLIPSegPreTrainedModel,v2 as CLIPTextModel,S_ as CLIPTextModelWithProjection,T1 as CLIPTokenizer,y2 as CLIPVisionModel,b2 as CLIPVisionModelWithProjection,d2 as CamembertForMaskedLM,p2 as CamembertForQuestionAnswering,h2 as CamembertForSequenceClassification,f2 as CamembertForTokenClassification,u2 as CamembertModel,wn as CamembertPreTrainedModel,x1 as CamembertTokenizer,ET as ChatterboxFeatureExtractor,k_ as ChatterboxModel,T_ as ChatterboxPreTrainedModel,BT as ChatterboxProcessor,qT as ChineseCLIPFeatureExtractor,m2 as ChineseCLIPModel,E_ as ChineseCLIPPreTrainedModel,C_ as ClapAudioModelWithProjection,AT as ClapFeatureExtractor,g2 as ClapModel,_a as ClapPreTrainedModel,A_ as ClapTextModelWithProjection,xE as ClassifierFreeGuidanceLogitsProcessor,k2 as CodeGenForCausalLM,T2 as CodeGenModel,qi as CodeGenPreTrainedModel,E1 as CodeGenTokenizer,k1 as CodeLlamaTokenizer,S2 as Cohere2ForCausalLM,C2 as Cohere2Model,Qi as Cohere2PreTrainedModel,A2 as CohereForCausalLM,E2 as CohereModel,Hi as CoherePreTrainedModel,A1 as CohereTokenizer,F2 as ConvBertForMaskedLM,O2 as ConvBertForQuestionAnswering,I2 as ConvBertForSequenceClassification,L2 as ConvBertForTokenClassification,P2 as ConvBertModel,vn as ConvBertPreTrainedModel,C1 as ConvBertTokenizer,QT as ConvNextFeatureExtractor,D2 as ConvNextForImageClassification,Xp as ConvNextImageProcessor,N2 as ConvNextModel,Xi as ConvNextPreTrainedModel,B2 as ConvNextV2ForImageClassification,z2 as ConvNextV2Model,Yi as ConvNextV2PreTrainedModel,V2 as DFineForObjectDetection,G2 as DFineModel,Ki as DFinePreTrainedModel,hA as DINOv3ConvNextModel,B_ as DINOv3ConvNextPreTrainedModel,JT as DINOv3ViTImageProcessor,fA as DINOv3ViTModel,R_ as DINOv3ViTPreTrainedModel,ZT as DPTFeatureExtractor,bA as DPTForDepthEstimation,Kp as DPTImageProcessor,yA as DPTModel,nl as DPTPreTrainedModel,L_ as DacDecoderModel,F_ as DacDecoderOutput,I_ as DacEncoderModel,P_ as DacEncoderOutput,Gp as DacFeatureExtractor,U2 as DacModel,ma as DacPreTrainedModel,W2 as DebertaForMaskedLM,Q2 as DebertaForQuestionAnswering,q2 as DebertaForSequenceClassification,H2 as DebertaForTokenClassification,j2 as DebertaModel,yn as DebertaPreTrainedModel,P1 as DebertaTokenizer,Y2 as DebertaV2ForMaskedLM,Z2 as DebertaV2ForQuestionAnswering,J2 as DebertaV2ForSequenceClassification,K2 as DebertaV2ForTokenClassification,X2 as DebertaV2Model,bn as DebertaV2PreTrainedModel,S1 as DebertaV2Tokenizer,eA as DecisionTransformerModel,O_ as DecisionTransformerPreTrainedModel,XT as DeiTFeatureExtractor,rA as DeiTForImageClassification,Yp as DeiTImageProcessor,tA as DeiTModel,Zi as DeiTPreTrainedModel,nA as DepthAnythingForDepthEstimation,N_ as DepthAnythingPreTrainedModel,ML as DepthEstimationPipeline,sA as DepthProForDepthEstimation,D_ as DepthProPreTrainedModel,YT as DetrFeatureExtractor,oA as DetrForObjectDetection,iA as DetrForSegmentation,Jp as DetrImageProcessor,aA as DetrModel,el as DetrObjectDetectionOutput,ga as DetrPreTrainedModel,z_ as DetrSegmentationOutput,cA as Dinov2ForImageClassification,lA as Dinov2Model,tl as Dinov2PreTrainedModel,dA as Dinov2WithRegistersForImageClassification,uA as Dinov2WithRegistersModel,rl as Dinov2WithRegistersPreTrainedModel,wA as DistilBertForMaskedLM,gA as DistilBertForQuestionAnswering,_A as DistilBertForSequenceClassification,mA as DistilBertForTokenClassification,pA as DistilBertModel,Mn as DistilBertPreTrainedModel,F1 as DistilBertTokenizer,yL as DocumentQuestionAnsweringPipeline,KT as DonutFeatureExtractor,Pi as DonutImageProcessor,vA as DonutSwinModel,$_ as DonutSwinPreTrainedModel,sF as EdgeTamModel,xA as EfficientNetForImageClassification,ek as EfficientNetImageProcessor,MA as EfficientNetModel,sl as EfficientNetPreTrainedModel,kA as ElectraForMaskedLM,CA as ElectraForQuestionAnswering,EA as ElectraForSequenceClassification,AA as ElectraForTokenClassification,TA as ElectraModel,xn as ElectraPreTrainedModel,I1 as ElectraTokenizer,$p as EncodecFeatureExtractor,AE as EosTokenCriteria,PA as Ernie4_5ForCausalLM,SA as Ernie4_5Model,al as Ernie4_5PretrainedModel,IA as EsmForMaskedLM,LA as EsmForSequenceClassification,OA as EsmForTokenClassification,FA as EsmModel,ls as EsmPreTrainedModel,L1 as EsmTokenizer,DA as ExaoneForCausalLM,NA as ExaoneModel,ol as ExaonePreTrainedModel,BA as FalconForCausalLM,$A as FalconH1ForCausalLM,RA as FalconH1Model,ll as FalconH1PreTrainedModel,zA as FalconModel,il as FalconPreTrainedModel,O1 as FalconTokenizer,VA as FastViTForImageClassification,GA as FastViTModel,cl as FastViTPreTrainedModel,xL as FeatureExtractionPipeline,pt as FeatureExtractor,aL as FillMaskPipeline,UA as Florence2ForConditionalGeneration,G_ as Florence2PreTrainedModel,Fk as Florence2Processor,_E as ForcedBOSTokenLogitsProcessor,mE as ForcedEOSTokenLogitsProcessor,tk as GLPNFeatureExtractor,ZA as GLPNForDepthEstimation,KA as GLPNModel,pl as GLPNPreTrainedModel,cC as GPT2LMHeadModel,lC as GPT2Model,vl as GPT2PreTrainedModel,z1 as GPT2Tokenizer,tC as GPTBigCodeForCausalLM,eC as GPTBigCodeModel,_l as GPTBigCodePreTrainedModel,dC as GPTJForCausalLM,uC as GPTJModel,yl as GPTJPreTrainedModel,nC as GPTNeoForCausalLM,rC as GPTNeoModel,ml as GPTNeoPreTrainedModel,aC as GPTNeoXForCausalLM,sC as GPTNeoXModel,gl as GPTNeoXPreTrainedModel,D1 as GPTNeoXTokenizer,HA as Gemma2ForCausalLM,qA as Gemma2Model,dl as Gemma2PreTrainedModel,XA as Gemma3ForCausalLM,QA as Gemma3Model,hl as Gemma3PreTrainedModel,CT as Gemma3nAudioFeatureExtractor,U_ as Gemma3nForConditionalGeneration,V_ as Gemma3nPreTrainedModel,Ik as Gemma3nProcessor,WA as GemmaForCausalLM,jA as GemmaModel,ul as GemmaPreTrainedModel,N1 as GemmaTokenizer,JA as GlmForCausalLM,YA as GlmModel,fl as GlmPreTrainedModel,iC as GptOssForCausalLM,oC as GptOssModel,wl as GptOssPreTrainedModel,fC as GraniteForCausalLM,hC as GraniteModel,_C as GraniteMoeHybridForCausalLM,pC as GraniteMoeHybridModel,Ml as GraniteMoeHybridPreTrainedModel,bl as GranitePreTrainedModel,mC as GroundingDinoForObjectDetection,rk as GroundingDinoImageProcessor,j_ as GroundingDinoPreTrainedModel,Ok as GroundingDinoProcessor,gC as GroupViTModel,W_ as GroupViTPreTrainedModel,vC as HeliumForCausalLM,wC as HeliumModel,xl as HeliumPreTrainedModel,B1 as HerbertTokenizer,bC as HieraForImageClassification,yC as HieraModel,Tl as HieraPreTrainedModel,CC as HubertForCTC,SC as HubertForSequenceClassification,AC as HubertModel,EC as HubertPreTrainedModel,FC as HunYuanDenseV1ForCausalLM,PC as HunYuanDenseV1Model,kl as HunYuanDenseV1PreTrainedModel,OC as IJepaForImageClassification,LC as IJepaModel,El as IJepaPreTrainedModel,H_ as Idefics3ForConditionalGeneration,$h as Idefics3ImageProcessor,q_ as Idefics3PreTrainedModel,Gh as Idefics3Processor,_L as ImageClassificationPipeline,TL as ImageFeatureExtractionPipeline,ue as ImageFeatureExtractor,ue as ImageProcessor,wg as ImageSegmentationPipeline,bL as ImageToImagePipeline,pL as ImageToTextPipeline,UL as InterruptableStoppingCriteria,DC as JAISLMHeadModel,NC as JAISModel,Al as JAISPreTrainedModel,sk as JinaCLIPImageProcessor,zC as JinaCLIPModel,wa as JinaCLIPPreTrainedModel,Rk as JinaCLIPProcessor,Q_ as JinaCLIPTextModel,BC as JinaCLIPVisionModel,$C as Lfm2ForCausalLM,RC as Lfm2Model,VC as Lfm2MoeForCausalLM,GC as Lfm2MoeModel,Sl as Lfm2MoePreTrainedModel,Cl as Lfm2PreTrainedModel,mI as LiteWhisperForConditionalGeneration,WC as Llama4ForCausalLM,X_ as Llama4PreTrainedModel,jC as LlamaForCausalLM,UC as LlamaModel,Pl as LlamaPreTrainedModel,R1 as LlamaTokenizer,ra as LlavaForConditionalGeneration,ra as LlavaOnevisionForConditionalGeneration,ak as LlavaOnevisionImageProcessor,Y_ as LlavaPreTrainedModel,$k as LlavaProcessor,HC as LlavaQwen2ForCausalLM,Nt as LogLevel,Jt as LogitsProcessor,ei as LogitsProcessorList,Oi as LogitsWarper,XC as LongT5ForConditionalGeneration,QC as LongT5Model,Fl as LongT5PreTrainedModel,JC as M2M100ForConditionalGeneration,YC as M2M100Model,Il as M2M100PreTrainedModel,$1 as M2M100Tokenizer,V1 as MBart50Tokenizer,aS as MBartForCausalLM,nS as MBartForConditionalGeneration,sS as MBartForSequenceClassification,rS as MBartModel,cs as MBartPreTrainedModel,Np as MBartTokenizer,US as MPNetForMaskedLM,qS as MPNetForQuestionAnswering,jS as MPNetForSequenceClassification,WS as MPNetForTokenClassification,VS as MPNetModel,Tn as MPNetPreTrainedModel,W1 as MPNetTokenizer,YS as MT5ForConditionalGeneration,XS as MT5Model,Vl as MT5PreTrainedModel,ZC as MarianMTModel,KC as MarianModel,Ll as MarianPreTrainedModel,G1 as MarianTokenizer,ik as Mask2FormerImageProcessor,ok as MaskFormerFeatureExtractor,tS as MaskFormerForInstanceSegmentation,Fi as MaskFormerImageProcessor,eS as MaskFormerModel,Ol as MaskFormerPreTrainedModel,EE as MaxLengthCriteria,oS as Metric3DForDepthEstimation,J_ as Metric3DPreTrainedModel,iS as Metric3Dv2ForDepthEstimation,K_ as Metric3Dv2PreTrainedModel,lS as MgpstrForSceneTextRecognition,Z_ as MgpstrModelOutput,em as MgpstrPreTrainedModel,Gk as MgpstrProcessor,U1 as MgpstrTokenizer,sm as MimiDecoderModel,rm as MimiDecoderOutput,nm as MimiEncoderModel,tm as MimiEncoderOutput,cS as MimiModel,va as MimiPreTrainedModel,yE as MinLengthLogitsProcessor,bE as MinNewTokensLengthLogitsProcessor,dS as MistralForCausalLM,uS as MistralModel,Nl as MistralPreTrainedModel,fS as MobileBertForMaskedLM,_S as MobileBertForQuestionAnswering,pS as MobileBertForSequenceClassification,hS as MobileBertModel,us as MobileBertPreTrainedModel,j1 as MobileBertTokenizer,gS as MobileLLMForCausalLM,mS as MobileLLMModel,Dl as MobileLLMPreTrainedModel,lk as MobileNetV1FeatureExtractor,vS as MobileNetV1ForImageClassification,yS as MobileNetV1ForSemanticSegmentation,Zp as MobileNetV1ImageProcessor,wS as MobileNetV1Model,ya as MobileNetV1PreTrainedModel,ck as MobileNetV2FeatureExtractor,MS as MobileNetV2ForImageClassification,xS as MobileNetV2ForSemanticSegmentation,e_ as MobileNetV2ImageProcessor,bS as MobileNetV2Model,ba as MobileNetV2PreTrainedModel,uk as MobileNetV3FeatureExtractor,kS as MobileNetV3ForImageClassification,ES as MobileNetV3ForSemanticSegmentation,t_ as MobileNetV3ImageProcessor,TS as MobileNetV3Model,Ma as MobileNetV3PreTrainedModel,dk as MobileNetV4FeatureExtractor,CS as MobileNetV4ForImageClassification,SS as MobileNetV4ForSemanticSegmentation,r_ as MobileNetV4ImageProcessor,AS as MobileNetV4Model,xa as MobileNetV4PreTrainedModel,hk as MobileViTFeatureExtractor,FS as MobileViTForImageClassification,n_ as MobileViTImageProcessor,PS as MobileViTModel,zl as MobileViTPreTrainedModel,LS as MobileViTV2ForImageClassification,IS as MobileViTV2Model,Bl as MobileViTV2PreTrainedModel,tO as ModelRegistry,RS as ModernBertDecoderForCausalLM,BS as ModernBertDecoderModel,Rl as ModernBertDecoderPreTrainedModel,NS as ModernBertForMaskedLM,DS as ModernBertForSequenceClassification,zS as ModernBertForTokenClassification,OS as ModernBertModel,ds as ModernBertPreTrainedModel,qC as Moondream1ForConditionalGeneration,ST as MoonshineFeatureExtractor,GS as MoonshineForConditionalGeneration,$S as MoonshineModel,$l as MoonshinePreTrainedModel,Vk as MoonshineProcessor,QS as MptForCausalLM,HS as MptModel,Gl as MptPreTrainedModel,JS as MultiModalityCausalLM,am as MultiModalityPreTrainedModel,ZS as MusicgenForCausalLM,om as MusicgenForConditionalGeneration,KS as MusicgenModel,Ul as MusicgenPreTrainedModel,tP as NanoChatForCausalLM,eP as NanoChatModel,jl as NanoChatPreTrainedModel,nP as NeoBertForMaskedLM,oP as NeoBertForQuestionAnswering,sP as NeoBertForSequenceClassification,aP as NeoBertForTokenClassification,rP as NeoBertModel,kn as NeoBertPreTrainedModel,q1 as NllbTokenizer,ME as NoBadWordsLogitsProcessor,wE as NoRepeatNGramLogitsProcessor,iP as NomicBertModel,im as NomicBertPreTrainedModel,fk as NougatImageProcessor,H1 as NougatTokenizer,gP as OPTForCausalLM,mP as OPTModel,Xl as OPTPreTrainedModel,wL as ObjectDetectionPipeline,dP as Olmo2ForCausalLM,uP as Olmo2Model,ql as Olmo2PreTrainedModel,fP as Olmo3ForCausalLM,hP as Olmo3Model,Hl as Olmo3PreTrainedModel,cP as OlmoForCausalLM,lP as OlmoModel,Wl as OlmoPreTrainedModel,_P as OpenELMForCausalLM,pP as OpenELMModel,Ql as OpenELMPreTrainedModel,pk as OwlViTFeatureExtractor,bP as OwlViTForObjectDetection,Ii as OwlViTImageProcessor,yP as OwlViTModel,Jl as OwlViTPreTrainedModel,Uk as OwlViTProcessor,vP as Owlv2ForObjectDetection,_k as Owlv2ImageProcessor,wP as Owlv2Model,Yl as Owlv2PreTrainedModel,MP as PaliGemmaForConditionalGeneration,lm as PaliGemmaPreTrainedModel,Wk as PaliGemmaProcessor,FT as ParakeetFeatureExtractor,xP as ParakeetForCTC,cm as ParakeetPreTrainedModel,kP as PatchTSMixerForPrediction,TP as PatchTSMixerModel,Kl as PatchTSMixerPreTrainedModel,AP as PatchTSTForPrediction,EP as PatchTSTModel,Zl as PatchTSTPreTrainedModel,FP as Phi3ForCausalLM,PP as Phi3Model,tc as Phi3PreTrainedModel,dm as Phi3VForCausalLM,gk as Phi3VImageProcessor,um as Phi3VPreTrainedModel,Hk as Phi3VProcessor,SP as PhiForCausalLM,CP as PhiModel,ec as PhiPreTrainedModel,wk as PixtralImageProcessor,Qk as PixtralProcessor,P as PreTrainedModel,ae as PreTrainedTokenizer,cE as PretrainedConfig,Le as Processor,LP as PvtForImageClassification,vk as PvtImageProcessor,IP as PvtModel,rc as PvtPreTrainedModel,Vp as PyAnnoteFeatureExtractor,NP as PyAnnoteForAudioFrameClassification,OP as PyAnnoteModel,nc as PyAnnotePreTrainedModel,Xk as PyAnnoteProcessor,sL as QuestionAnsweringPipeline,zP as Qwen2ForCausalLM,DP as Qwen2Model,sc as Qwen2PreTrainedModel,Q1 as Qwen2Tokenizer,fm as Qwen2VLForConditionalGeneration,bk as Qwen2VLImageProcessor,hm as Qwen2VLPreTrainedModel,l_ as Qwen2VLProcessor,pm as Qwen2_5_VLForConditionalGeneration,c_ as Qwen2_5_VLProcessor,RP as Qwen3ForCausalLM,BP as Qwen3Model,ac as Qwen3PreTrainedModel,_m as Qwen3VLForConditionalGeneration,Yk as Qwen3VLProcessor,mm as Qwen3_5ForConditionalGeneration,$P as Qwen3_5MoeForConditionalGeneration,jP as RFDetrForObjectDetection,UP as RFDetrModel,gm as RFDetrObjectDetectionOutput,ic as RFDetrPreTrainedModel,$2 as RTDetrForObjectDetection,Mk as RTDetrImageProcessor,R2 as RTDetrModel,is as RTDetrObjectDetectionOutput,Ji as RTDetrPreTrainedModel,rF as RTDetrV2ForObjectDetection,tF as RTDetrV2Model,wm as RTDetrV2ObjectDetectionOutput,lc as RTDetrV2PreTrainedModel,TT as RawAudio,yt as RawImage,PL as RawVideo,Mg as RawVideoFrame,vE as RepetitionPenaltyLogitsProcessor,VP as ResNetForImageClassification,GP as ResNetModel,oc as ResNetPreTrainedModel,JP as RoFormerForMaskedLM,eF as RoFormerForQuestionAnswering,KP as RoFormerForSequenceClassification,ZP as RoFormerForTokenClassification,YP as RoFormerModel,An as RoFormerPreTrainedModel,Y1 as RoFormerTokenizer,qP as RobertaForMaskedLM,XP as RobertaForQuestionAnswering,HP as RobertaForSequenceClassification,QP as RobertaForTokenClassification,WP as RobertaModel,En as RobertaPreTrainedModel,X1 as RobertaTokenizer,Ro as Sam2ImageProcessor,bm as Sam2ImageSegmentationOutput,cc as Sam2Model,Mm as Sam2PreTrainedModel,d_ as Sam2Processor,Jk as Sam2VideoProcessor,Ro as Sam3ImageProcessor,aF as Sam3TrackerModel,Ro as SamImageProcessor,vm as SamImageSegmentationOutput,nF as SamModel,ym as SamPreTrainedModel,u_ as SamProcessor,xk as SapiensFeatureExtractor,iF as SapiensForDepthEstimation,lF as SapiensForNormalEstimation,oF as SapiensForSemanticSegmentation,s_ as SapiensImageProcessor,Ta as SapiensPreTrainedModel,IT as SeamlessM4TFeatureExtractor,Tk as SegformerFeatureExtractor,uF as SegformerForImageClassification,dF as SegformerForSemanticSegmentation,a_ as SegformerImageProcessor,cF as SegformerModel,ka as SegformerPreTrainedModel,kk as SiglipImageProcessor,hF as SiglipModel,uc as SiglipPreTrainedModel,xm as SiglipTextModel,J1 as SiglipTokenizer,fF as SiglipVisionModel,_F as SmolLM3ForCausalLM,pF as SmolLM3Model,dc as SmolLM3PreTrainedModel,IC as SmolVLMForConditionalGeneration,$h as SmolVLMImageProcessor,Gh as SmolVLMProcessor,km as SnacDecoderModel,Tm as SnacEncoderModel,LT as SnacFeatureExtractor,mF as SnacModel,Ea as SnacPreTrainedModel,OT as SpeechT5FeatureExtractor,wF as SpeechT5ForSpeechToText,vF as SpeechT5ForTextToSpeech,yF as SpeechT5HifiGan,gF as SpeechT5Model,Aa as SpeechT5PreTrainedModel,Kk as SpeechT5Processor,K1 as SpeechT5Tokenizer,MF as SqueezeBertForMaskedLM,TF as SqueezeBertForQuestionAnswering,xF as SqueezeBertForSequenceClassification,bF as SqueezeBertModel,hs as SqueezeBertPreTrainedModel,Z1 as SqueezeBertTokenizer,EF as StableLmForCausalLM,kF as StableLmModel,hc as StableLmPreTrainedModel,CF as Starcoder2ForCausalLM,AF as Starcoder2Model,fc as Starcoder2PreTrainedModel,ha as StoppingCriteria,kE as StoppingCriteriaList,SF as StyleTextToSpeech2Model,Em as StyleTextToSpeech2PreTrainedModel,oL as SummarizationPipeline,Cm as SupertonicForConditionalGeneration,Am as SupertonicPreTrainedModel,m_ as SuppressTokensAtBeginLogitsProcessor,OF as Swin2SRForImageSuperResolution,Ek as Swin2SRImageProcessor,LF as Swin2SRModel,pc as Swin2SRPreTrainedModel,FF as SwinForImageClassification,IF as SwinForSemanticSegmentation,PF as SwinModel,Ca as SwinPreTrainedModel,DF as T5ForConditionalGeneration,NF as T5Model,_c as T5PreTrainedModel,eT as T5Tokenizer,BF as TableTransformerForObjectDetection,zF as TableTransformerModel,Sm as TableTransformerObjectDetectionOutput,mc as TableTransformerPreTrainedModel,TE as TemperatureLogitsWarper,j as Tensor,xc as Text2TextGenerationPipeline,rL as TextClassificationPipeline,lL as TextGenerationPipeline,SL as TextStreamer,fL as TextToAudioPipeline,nL as TokenClassificationPipeline,ae as TokenizersBackend,VL as TopKLogitsWarper,GL as TopPLogitsWarper,RF as TrOCRForCausalLM,Pm as TrOCRPreTrainedModel,iL as TranslationPipeline,Im as UltravoxModel,Fm as UltravoxPreTrainedModel,Zk as UltravoxProcessor,VF as UniSpeechForCTC,UF as UniSpeechForSequenceClassification,GF as UniSpeechModel,Sa as UniSpeechPreTrainedModel,HF as UniSpeechSatForAudioFrameClassification,WF as UniSpeechSatForCTC,qF as UniSpeechSatForSequenceClassification,jF as UniSpeechSatModel,fs as UniSpeechSatPreTrainedModel,Bk as VLChatProcessor,nk as VLMImageProcessor,XF as VaultGemmaForCausalLM,QF as VaultGemmaModel,gc as VaultGemmaPreTrainedModel,Ak as ViTFeatureExtractor,KF as ViTForImageClassification,o_ as ViTImageProcessor,ZF as ViTMAEModel,Lm as ViTMAEPreTrainedModel,tI as ViTMSNForImageClassification,eI as ViTMSNModel,vc as ViTMSNPreTrainedModel,JF as ViTModel,wc as ViTPreTrainedModel,YF as VisionEncoderDecoderModel,rI as VitMatteForImageMatting,Ck as VitMatteImageProcessor,Om as VitMattePreTrainedModel,nI as VitPoseForPoseEstimation,Sk as VitPoseImageProcessor,Nm as VitPosePreTrainedModel,sI as VitsModel,Dm as VitsModelOutput,zm as VitsPreTrainedModel,rT as VitsTokenizer,$F as VoxtralForConditionalGeneration,nE as VoxtralProcessor,oI as Wav2Vec2BertForCTC,iI as Wav2Vec2BertForSequenceClassification,aI as Wav2Vec2BertModel,Pa as Wav2Vec2BertPreTrainedModel,nT as Wav2Vec2CTCTokenizer,NT as Wav2Vec2FeatureExtractor,kC as Wav2Vec2ForAudioFrameClassification,xC as Wav2Vec2ForCTC,TC as Wav2Vec2ForSequenceClassification,MC as Wav2Vec2Model,Tr as Wav2Vec2PreTrainedModel,sE as Wav2Vec2Processor,aE as Wav2Vec2ProcessorWithLM,hI as WavLMForAudioFrameClassification,cI as WavLMForCTC,uI as WavLMForSequenceClassification,dI as WavLMForXVector,lI as WavLMModel,Cn as WavLMPreTrainedModel,DT as WeSpeakerFeatureExtractor,fI as WeSpeakerResNetModel,Rm as WeSpeakerResNetPreTrainedModel,zT as WhisperFeatureExtractor,$m as WhisperForConditionalGeneration,_I as WhisperModel,yc as WhisperPreTrainedModel,oE as WhisperProcessor,ZL as WhisperTextStreamer,gE as WhisperTimeStampLogitsProcessor,iT as WhisperTokenizer,bI as XLMForQuestionAnswering,vI as XLMForSequenceClassification,yI as XLMForTokenClassification,gI as XLMModel,Sn as XLMPreTrainedModel,xI as XLMRobertaForMaskedLM,EI as XLMRobertaForQuestionAnswering,TI as XLMRobertaForSequenceClassification,kI as XLMRobertaForTokenClassification,MI as XLMRobertaModel,Pn as XLMRobertaPreTrainedModel,lT as XLMRobertaTokenizer,cT as XLMTokenizer,wI as XLMWithLMHeadModel,Bm as XVectorOutput,Pk as YolosFeatureExtractor,CI as YolosForObjectDetection,i_ as YolosImageProcessor,AI as YolosModel,Gm as YolosObjectDetectionOutput,bc as YolosPreTrainedModel,PI as YoutuForCausalLM,SI as YoutuModel,Mc as YoutuPreTrainedModel,dL as ZeroShotAudioClassificationPipeline,cL as ZeroShotClassificationPipeline,gL as ZeroShotImageClassificationPipeline,vL as ZeroShotObjectDetectionPipeline,De as cat,DL as cos_sim,Ux as dot,ve as env,at as full,Yo as full_like,Ep as interpolate,yr as interpolate_4d,BL as layer_norm,$L as load_image,eO as load_video,Vx as log_softmax,c1 as matmul,Ti as mean,u1 as mean_pooling,Ct as ones,Sp as ones_like,l1 as permute,KL as pipeline,h1 as quantize_embeddings,RL as rand,d1 as randn,ca as random,pT as read_audio,zL as rfft,Ap as slice,tt as softmax,mn as stack,Cp as std_mean,_n as topk,Pp as zeros,Fp as zeros_like};