var M1=Object.defineProperty;var S1=(J)=>J;function L1(J,Q){this[J]=S1.bind(null,Q)}var C1=(J,Q)=>{for(var X in Q)M1(J,X,{get:Q[X],enumerable:!0,configurable:!0,set:L1.bind(Q,X)})};var $4=((J)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(J,{get:(Q,X)=>(typeof require<"u"?require:Q)[X]}):J)(function(J){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+J+'" is not supported')});var s4={};C1(s4,{registerBackend:()=>x5,env:()=>b0,default:()=>t1,Tensor:()=>I6,TRACE_FUNC_END:()=>h5,TRACE_FUNC_BEGIN:()=>k5,TRACE_EVENT_END:()=>M5,TRACE_EVENT_BEGIN:()=>D5,TRACE:()=>k9,InferenceSession:()=>b4});/*! * ONNX Runtime Web v1.27.0 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var{defineProperty:k4,getOwnPropertyDescriptor:R1,getOwnPropertyNames:A1}=Object,P1=Object.prototype.hasOwnProperty,E1=((J)=>$4)(function(J){return $4.apply(this,arguments)}),N0=(J,Q)=>()=>(J&&(Q=J(J=0)),Q),d8=(J,Q)=>{for(var X in Q)k4(J,X,{get:Q[X],enumerable:!0})},w1=(J,Q,X,K)=>{if(Q&&typeof Q=="object"||typeof Q=="function")for(let Z of A1(Q))!P1.call(J,Z)&&Z!==X&&k4(J,Z,{get:()=>Q[Z],enumerable:!(K=R1(Q,Z))||K.enumerable});return J},x9=(J)=>w1(k4({},"__esModule",{value:!0}),J),f8,j5,x5,HH,yH,xH=N0(()=>{f8=new Map,j5=[],x5=(J,Q,X)=>{if(Q&&typeof Q.init=="function"&&typeof Q.createInferenceSessionHandler=="function"){let K=f8.get(J);if(K===void 0)f8.set(J,{backend:Q,priority:X});else{if(K.priority>X)return;if(K.priority===X&&K.backend!==Q)throw Error(`cannot register backend "${J}" using priority ${X}`)}if(X>=0){let Z=j5.indexOf(J);Z!==-1&&j5.splice(Z,1);for(let H=0;H{let Q=f8.get(J);if(!Q)return"backend not found.";if(Q.initialized)return Q.backend;if(Q.aborted)return Q.error;{let X=!!Q.initPromise;try{return X||(Q.initPromise=Q.backend.init(J)),await Q.initPromise,Q.initialized=!0,Q.backend}catch(K){return X||(Q.error=`${K}`,Q.aborted=!0),Q.error}finally{delete Q.initPromise}}},yH=async(J)=>{let Q=J.executionProviders||[],X=Q.map((V)=>typeof V=="string"?V:V.name),K=X.length===0?j5:X,Z,H=[],Y=new Set;for(let V of K){let W=await HH(V);typeof W=="string"?H.push({name:V,err:W}):(Z||(Z=W),Z===W&&Y.add(V))}if(!Z)throw Error(`no available backend found. ERR: ${H.map((V)=>`[${V.name}] ${V.err}`).join(", ")}`);for(let{name:V,err:W}of H)X.includes(V)&&console.warn(`removing requested execution provider "${V}" from session options because it is not available: ${W}`);let $=Q.filter((V)=>Y.has(typeof V=="string"?V:V.name));return[Z,new Proxy(J,{get:(V,W)=>W==="executionProviders"?$:Reflect.get(V,W)})]}}),T1=N0(()=>{xH()}),kH,I1=N0(()=>{kH="1.27.0"}),V4,s0,hH=N0(()=>{I1(),V4="warning",s0={wasm:{},webgl:{},webgpu:{},versions:{common:kH},set logLevel(J){if(J!==void 0){if(typeof J!="string"||["verbose","info","warning","error","fatal"].indexOf(J)===-1)throw Error(`Unsupported logging level: ${J}`);V4=J}},get logLevel(){return V4}},Object.defineProperty(s0,"logLevel",{enumerable:!0})}),b0,v1=N0(()=>{hH(),b0=s0}),bH,fH,y1=N0(()=>{bH=(J,Q)=>{let X=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);X.width=J.dims[3],X.height=J.dims[2];let K=X.getContext("2d");if(K!=null){let Z,H;Q?.tensorLayout!==void 0&&Q.tensorLayout==="NHWC"?(Z=J.dims[2],H=J.dims[3]):(Z=J.dims[3],H=J.dims[2]);let Y=Q?.format!==void 0?Q.format:"RGB",$=Q?.norm,V,W;$===void 0||$.mean===void 0?V=[255,255,255,255]:typeof $.mean=="number"?V=[$.mean,$.mean,$.mean,$.mean]:(V=[$.mean[0],$.mean[1],$.mean[2],0],$.mean[3]!==void 0&&(V[3]=$.mean[3])),$===void 0||$.bias===void 0?W=[0,0,0,0]:typeof $.bias=="number"?W=[$.bias,$.bias,$.bias,$.bias]:(W=[$.bias[0],$.bias[1],$.bias[2],0],$.bias[3]!==void 0&&(W[3]=$.bias[3]));let q=H*Z,F=0,N=q,j=q*2,B=-1;Y==="RGBA"?(F=0,N=q,j=q*2,B=q*3):Y==="RGB"?(F=0,N=q,j=q*2):Y==="RBG"&&(F=0,j=q,N=q*2);for(let D=0;D{let X=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),K;if(X!=null){let Z,H,Y;Q?.tensorLayout!==void 0&&Q.tensorLayout==="NHWC"?(Z=J.dims[2],H=J.dims[1],Y=J.dims[3]):(Z=J.dims[3],H=J.dims[2],Y=J.dims[1]);let $=Q!==void 0&&Q.format!==void 0?Q.format:"RGB",V=Q?.norm,W,q;V===void 0||V.mean===void 0?W=[255,255,255,255]:typeof V.mean=="number"?W=[V.mean,V.mean,V.mean,V.mean]:(W=[V.mean[0],V.mean[1],V.mean[2],255],V.mean[3]!==void 0&&(W[3]=V.mean[3])),V===void 0||V.bias===void 0?q=[0,0,0,0]:typeof V.bias=="number"?q=[V.bias,V.bias,V.bias,V.bias]:(q=[V.bias[0],V.bias[1],V.bias[2],0],V.bias[3]!==void 0&&(q[3]=V.bias[3]));let F=H*Z;if(Q!==void 0&&(Q.format!==void 0&&Y===4&&Q.format!=="RGBA"||Y===3&&Q.format!=="RGB"&&Q.format!=="BGR"))throw Error("Tensor format doesn't match input tensor dims");let N=4,j=0,B=1,D=2,L=3,M=0,R=F,E=F*2,P=-1;$==="RGBA"?(M=0,R=F,E=F*2,P=F*3):$==="RGB"?(M=0,R=F,E=F*2):$==="RBG"&&(M=0,E=F,R=F*2),K=X.createImageData(Z,H);for(let w=0;w{h4(),E9=(J,Q)=>{if(J===void 0)throw Error("Image buffer must be defined");if(Q.height===void 0||Q.width===void 0)throw Error("Image height and width must be defined");if(Q.tensorLayout==="NHWC")throw Error("NHWC Tensor layout is not supported yet");let{height:X,width:K}=Q,Z=Q.norm??{mean:255,bias:0},H,Y;typeof Z.mean=="number"?H=[Z.mean,Z.mean,Z.mean,Z.mean]:H=[Z.mean[0],Z.mean[1],Z.mean[2],Z.mean[3]??255],typeof Z.bias=="number"?Y=[Z.bias,Z.bias,Z.bias,Z.bias]:Y=[Z.bias[0],Z.bias[1],Z.bias[2],Z.bias[3]??0];let $=Q.format!==void 0?Q.format:"RGBA",V=Q.tensorFormat!==void 0&&Q.tensorFormat!==void 0?Q.tensorFormat:"RGB",W=X*K,q=V==="RGBA"?new Float32Array(W*4):new Float32Array(W*3),F=4,N=0,j=1,B=2,D=3,L=0,M=W,R=W*2,E=-1;$==="RGB"&&(F=3,N=0,j=1,B=2,D=-1),V==="RGBA"?E=W*3:V==="RBG"?(L=0,R=W,M=W*2):V==="BGR"&&(R=0,M=W,L=W*2);for(let P=0;P{let X=typeof HTMLImageElement<"u"&&J instanceof HTMLImageElement,K=typeof ImageData<"u"&&J instanceof ImageData,Z=typeof ImageBitmap<"u"&&J instanceof ImageBitmap,H=typeof J=="string",Y,$=Q??{},V=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw Error("Canvas is not supported")},W=(q)=>typeof HTMLCanvasElement<"u"&&q instanceof HTMLCanvasElement||q instanceof OffscreenCanvas?q.getContext("2d"):null;if(X){let q=V();q.width=J.width,q.height=J.height;let F=W(q);if(F!=null){let{height:N,width:j}=J;if(Q!==void 0&&Q.resizedHeight!==void 0&&Q.resizedWidth!==void 0&&(N=Q.resizedHeight,j=Q.resizedWidth),Q!==void 0){if($=Q,Q.tensorFormat!==void 0)throw Error("Image input config format must be RGBA for HTMLImageElement");$.tensorFormat="RGBA",$.height=N,$.width=j}else $.tensorFormat="RGBA",$.height=N,$.width=j;F.drawImage(J,0,0),Y=F.getImageData(0,0,j,N).data}else throw Error("Can not access image data")}else if(K){let q,F;if(Q!==void 0&&Q.resizedWidth!==void 0&&Q.resizedHeight!==void 0?(q=Q.resizedHeight,F=Q.resizedWidth):(q=J.height,F=J.width),Q!==void 0&&($=Q),$.format="RGBA",$.height=q,$.width=F,Q!==void 0){let N=V();N.width=F,N.height=q;let j=W(N);if(j!=null)j.putImageData(J,0,0),Y=j.getImageData(0,0,F,q).data;else throw Error("Can not access image data")}else Y=J.data}else if(Z){if(Q===void 0)throw Error("Please provide image config with format for Imagebitmap");let q=V();q.width=J.width,q.height=J.height;let F=W(q);if(F!=null){let{height:N,width:j}=J;return F.drawImage(J,0,0,j,N),Y=F.getImageData(0,0,j,N).data,$.height=N,$.width=j,E9(Y,$)}else throw Error("Can not access image data")}else{if(H)return new Promise((q,F)=>{let N=V(),j=W(N);if(!J||!j)return F();let B=new Image;B.crossOrigin="Anonymous",B.src=J,B.onload=()=>{N.width=B.width,N.height=B.height,j.drawImage(B,0,0,N.width,N.height);let D=j.getImageData(0,0,N.width,N.height);$.height=N.height,$.width=N.width,q(E9(D.data,$))}});throw Error("Input data provided is not supported - aborted tensor creation")}if(Y!==void 0)return E9(Y,$);throw Error("Input data provided is not supported - aborted tensor creation")},gH=(J,Q)=>{let{width:X,height:K,download:Z,dispose:H}=Q;return new D6({location:"texture",type:"float32",texture:J,dims:[1,K,X,4],download:Z,dispose:H})},cH=(J,Q)=>{let{dataType:X,dims:K,download:Z,dispose:H}=Q;return new D6({location:"gpu-buffer",type:X??"float32",gpuBuffer:J,dims:K,download:Z,dispose:H})},lH=(J,Q)=>{let{dataType:X,dims:K,download:Z,dispose:H}=Q;return new D6({location:"ml-tensor",type:X??"float32",mlTensor:J,dims:K,download:Z,dispose:H})},uH=(J,Q,X)=>new D6({location:"cpu-pinned",type:J,data:Q,dims:X??[Q.length]})}),v5,u8,W4,mH,k1=N0(()=>{v5=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),u8=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),W4=!1,mH=()=>{if(!W4){W4=!0;let J=typeof BigInt64Array<"u"&&BigInt64Array.from,Q=typeof BigUint64Array<"u"&&BigUint64Array.from,X=globalThis.Float16Array,K=typeof X<"u"&&X.from;J&&(v5.set("int64",BigInt64Array),u8.set(BigInt64Array,"int64")),Q&&(v5.set("uint64",BigUint64Array),u8.set(BigUint64Array,"uint64")),K?(v5.set("float16",X),u8.set(X,"float16")):v5.set("float16",Uint16Array)}}}),dH,pH,h1=N0(()=>{h4(),dH=(J)=>{let Q=1;for(let X=0;X{switch(J.location){case"cpu":return new D6(J.type,J.data,Q);case"cpu-pinned":return new D6({location:"cpu-pinned",data:J.data,type:J.type,dims:Q});case"texture":return new D6({location:"texture",texture:J.texture,type:J.type,dims:Q});case"gpu-buffer":return new D6({location:"gpu-buffer",gpuBuffer:J.gpuBuffer,type:J.type,dims:Q});case"ml-tensor":return new D6({location:"ml-tensor",mlTensor:J.mlTensor,type:J.type,dims:Q});default:throw Error(`tensorReshape: tensor location ${J.location} is not supported`)}}}),D6,h4=N0(()=>{y1(),x1(),k1(),h1(),D6=class{constructor(J,Q,X){mH();let K,Z;if(typeof J=="object"&&"location"in J)switch(this.dataLocation=J.location,K=J.type,Z=J.dims,J.location){case"cpu-pinned":{let Y=v5.get(K);if(!Y)throw TypeError(`unsupported type "${K}" to create tensor from pinned buffer`);if(!(J.data instanceof Y))throw TypeError(`buffer should be of type ${Y.name}`);this.cpuData=J.data;break}case"texture":{if(K!=="float32")throw TypeError(`unsupported type "${K}" to create tensor from texture`);this.gpuTextureData=J.texture,this.downloader=J.download,this.disposer=J.dispose;break}case"gpu-buffer":{if(K!=="float32"&&K!=="float16"&&K!=="int32"&&K!=="int64"&&K!=="uint32"&&K!=="uint8"&&K!=="bool"&&K!=="uint4"&&K!=="int4")throw TypeError(`unsupported type "${K}" to create tensor from gpu buffer`);this.gpuBufferData=J.gpuBuffer,this.downloader=J.download,this.disposer=J.dispose;break}case"ml-tensor":{if(K!=="float32"&&K!=="float16"&&K!=="int32"&&K!=="int64"&&K!=="uint32"&&K!=="uint64"&&K!=="int8"&&K!=="uint8"&&K!=="bool"&&K!=="uint4"&&K!=="int4")throw TypeError(`unsupported type "${K}" to create tensor from MLTensor`);this.mlTensorData=J.mlTensor,this.downloader=J.download,this.disposer=J.dispose;break}default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let Y,$;if(typeof J=="string")if(K=J,$=X,J==="string"){if(!Array.isArray(Q))throw TypeError("A string tensor's data must be a string array.");Y=Q}else{let V=v5.get(J);if(V===void 0)throw TypeError(`Unsupported tensor type: ${J}.`);if(Array.isArray(Q)){if(J==="float16"&&V===Uint16Array||J==="uint4"||J==="int4")throw TypeError(`Creating a ${J} tensor from number array is not supported. Please use ${V.name} as data.`);J==="uint64"||J==="int64"?Y=V.from(Q,BigInt):Y=V.from(Q)}else if(Q instanceof V)Y=Q;else if(Q instanceof Uint8ClampedArray)if(J==="uint8")Y=Uint8Array.from(Q);else throw TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(J==="float16"&&Q instanceof Uint16Array&&V!==Uint16Array)Y=new globalThis.Float16Array(Q.buffer,Q.byteOffset,Q.length);else throw TypeError(`A ${K} tensor's data must be type of ${V}`)}else if($=Q,Array.isArray(J)){if(J.length===0)throw TypeError("Tensor type cannot be inferred from an empty array.");let V=typeof J[0];if(V==="string")K="string",Y=J;else if(V==="boolean")K="bool",Y=Uint8Array.from(J);else throw TypeError(`Invalid element type of data array: ${V}.`)}else if(J instanceof Uint8ClampedArray)K="uint8",Y=Uint8Array.from(J);else{let V=u8.get(J.constructor);if(V===void 0)throw TypeError(`Unsupported type for tensor data: ${J.constructor}.`);K=V,Y=J}if($===void 0)$=[Y.length];else if(!Array.isArray($))throw TypeError("A tensor's dims must be a number array");Z=$,this.cpuData=Y,this.dataLocation="cpu"}let H=dH(Z);if(this.cpuData&&H!==this.cpuData.length&&!((K==="uint4"||K==="int4")&&Math.ceil(H/2)===this.cpuData.length))throw Error(`Tensor's size(${H}) does not match data length(${this.cpuData.length}).`);this.type=K,this.dims=Z,this.size=H}static async fromImage(J,Q){return _H(J,Q)}static fromTexture(J,Q){return gH(J,Q)}static fromGpuBuffer(J,Q){return cH(J,Q)}static fromMLTensor(J,Q){return lH(J,Q)}static fromPinnedBuffer(J,Q,X){return uH(J,Q,X)}toDataURL(J){return bH(this,J)}toImageData(J){return fH(this,J)}get data(){if(this.ensureValid(),!this.cpuData)throw 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 Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(J){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 Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let Q=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=Q,J&&this.disposer&&(this.disposer(),this.disposer=void 0),Q}finally{this.isDownloading=!1}}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw 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 Error("The tensor is disposed.")}reshape(J){if(this.ensureValid(),this.downloader||this.disposer)throw Error("Cannot reshape a tensor that owns GPU resource.");return pH(this,J)}}}),I6,iH=N0(()=>{h4(),I6=D6}),k9,G4,k5,h5,D5,M5,rH=N0(()=>{hH(),k9=(J,Q)=>{(typeof s0.trace>"u"?!s0.wasm.trace:!s0.trace)||console.timeStamp(`${J}::ORT::${Q}`)},G4=(J,Q)=>{let X=Error().stack?.split(/\r\n|\r|\n/g)||[],K=!1;for(let Z=0;Z{(typeof s0.trace>"u"?!s0.wasm.trace:!s0.trace)||G4("BEGIN",J)},h5=(J)=>{(typeof s0.trace>"u"?!s0.wasm.trace:!s0.trace)||G4("END",J)},D5=(J)=>{(typeof s0.trace>"u"?!s0.wasm.trace:!s0.trace)||console.time(`ORT::${J}`)},M5=(J)=>{(typeof s0.trace>"u"?!s0.wasm.trace:!s0.trace)||console.timeEnd(`ORT::${J}`)}}),aH,b1=N0(()=>{xH(),iH(),rH(),aH=class J{constructor(Q){this.handler=Q}async run(Q,X,K){k5(),D5("InferenceSession.run");let Z={},H={};if(typeof Q!="object"||Q===null||Q instanceof I6||Array.isArray(Q))throw TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let Y=!0;if(typeof X=="object"){if(X===null)throw TypeError("Unexpected argument[1]: cannot be null.");if(X instanceof I6)throw TypeError("'fetches' cannot be a Tensor");if(Array.isArray(X)){if(X.length===0)throw TypeError("'fetches' cannot be an empty array.");Y=!1;for(let W of X){if(typeof W!="string")throw TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(W)===-1)throw RangeError(`'fetches' contains invalid output name: ${W}.`);Z[W]=null}if(typeof K=="object"&&K!==null)H=K;else if(typeof K<"u")throw TypeError("'options' must be an object.")}else{let W=!1,q=Object.getOwnPropertyNames(X);for(let F of this.outputNames)if(q.indexOf(F)!==-1){let N=X[F];(N===null||N instanceof I6)&&(W=!0,Y=!1,Z[F]=N)}if(W){if(typeof K=="object"&&K!==null)H=K;else if(typeof K<"u")throw TypeError("'options' must be an object.")}else H=X}}else if(typeof X<"u")throw TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let W of this.inputNames)if(typeof Q[W]>"u")throw Error(`input '${W}' is missing in 'feeds'.`);if(Y)for(let W of this.outputNames)Z[W]=null;let $=await this.handler.run(Q,Z,H),V={};for(let W in $)if(Object.hasOwnProperty.call($,W)){let q=$[W];q instanceof I6?V[W]=q:V[W]=new I6(q.type,q.data,q.dims)}return M5("InferenceSession.run"),h5(),V}async release(){return this.handler.dispose()}static async create(Q,X,K,Z){k5(),D5("InferenceSession.create");let H,Y={};if(typeof Q=="string"){if(H=Q,typeof X=="object"&&X!==null)Y=X;else if(typeof X<"u")throw TypeError("'options' must be an object.")}else if(Q instanceof Uint8Array){if(H=Q,typeof X=="object"&&X!==null)Y=X;else if(typeof X<"u")throw TypeError("'options' must be an object.")}else if(Q instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&Q instanceof SharedArrayBuffer){let q=Q,F=0,N=Q.byteLength;if(typeof X=="object"&&X!==null)Y=X;else if(typeof X=="number"){if(F=X,!Number.isSafeInteger(F))throw RangeError("'byteOffset' must be an integer.");if(F<0||F>=q.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${q.byteLength}).`);if(N=Q.byteLength-F,typeof K=="number"){if(N=K,!Number.isSafeInteger(N))throw RangeError("'byteLength' must be an integer.");if(N<=0||F+N>q.byteLength)throw RangeError(`'byteLength' is out of range (0, ${q.byteLength-F}].`);if(typeof Z=="object"&&Z!==null)Y=Z;else if(typeof Z<"u")throw TypeError("'options' must be an object.")}else if(typeof K<"u")throw TypeError("'byteLength' must be a number.")}else if(typeof X<"u")throw TypeError("'options' must be an object.");H=new Uint8Array(q,F,N)}else throw TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[$,V]=await yH(Y),W=await $.createInferenceSessionHandler(H,V);return M5("InferenceSession.create"),h5(),new J(W)}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}}}),b4,f1=N0(()=>{b1(),b4=aH}),_1=N0(()=>{}),g1=N0(()=>{}),c1=N0(()=>{}),l1=N0(()=>{}),oH={};d8(oH,{InferenceSession:()=>b4,TRACE:()=>k9,TRACE_EVENT_BEGIN:()=>D5,TRACE_EVENT_END:()=>M5,TRACE_FUNC_BEGIN:()=>k5,TRACE_FUNC_END:()=>h5,Tensor:()=>I6,env:()=>b0,registerBackend:()=>x5});var b5=N0(()=>{T1(),v1(),f1(),iH(),_1(),g1(),rH(),c1(),l1()}),f4=N0(()=>{}),nH={};d8(nH,{default:()=>sH});var q4,F4,sH,u1=N0(()=>{FY(),f5(),_4(),q4="ort-wasm-proxy-worker",F4=globalThis.self?.name===q4,F4&&(self.onmessage=(J)=>{let{type:Q,in:X}=J.data;try{switch(Q){case"init-wasm":g4(X.wasm).then(()=>{d4(X).then(()=>{postMessage({type:Q})},(K)=>{postMessage({type:Q,err:K})})},(K)=>{postMessage({type:Q,err:K})});break;case"init-ep":{let{epName:K,env:Z}=X;p4(Z,K).then(()=>{postMessage({type:Q})},(H)=>{postMessage({type:Q,err:H})});break}case"copy-from":{let{buffer:K}=X,Z=f9(K);postMessage({type:Q,out:Z});break}case"create":{let{model:K,options:Z}=X;i4(K,Z).then((H)=>{postMessage({type:Q,out:H})},(H)=>{postMessage({type:Q,err:H})});break}case"release":r4(X),postMessage({type:Q});break;case"run":{let{sessionId:K,inputIndices:Z,inputs:H,outputIndices:Y,options:$}=X;a4(K,Z,H,Y,Array(Y.length).fill(null),$).then((V)=>{V.some((W)=>W[3]!=="cpu")?postMessage({type:Q,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:Q,out:V},n4([...H,...V]))},(V)=>{postMessage({type:Q,err:V})});break}case"end-profiling":o4(X),postMessage({type:Q});break;default:}}catch(K){postMessage({type:Q,err:K})}}),sH=F4?null:(J)=>new Worker(J??O6,{type:"module",name:q4})}),tH={};d8(tH,{default:()=>eH});async function YH(J={}){var Q=J,X=!!globalThis.window,K=!!globalThis.WorkerGlobalScope,Z=K&&self.name?.startsWith("em-pthread");Q.mountExternalData=(G,U)=>{G.startsWith("./")&&(G=G.substring(2)),(Q.Vc||(Q.Vc=new Map)).set(G,U)},Q.unmountExternalData=()=>{delete Q.Vc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let H=()=>{let G=(U)=>(...z)=>{let O=m6;return z=U(...z),m6!=O?new Promise((S,A)=>{m7={resolve:S,reject:A}}):z};(()=>{for(let U of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])Q[U]=G(Q[U])})(),typeof jsepRunAsync<"u"&&(Q._OrtRun=jsepRunAsync(Q._OrtRun),Q._OrtRunWithBinding=jsepRunAsync(Q._OrtRunWithBinding)),H=void 0};Q.asyncInit=()=>{H?.()};var Y,$,V=(G,U)=>{throw U},W=import.meta.url,q="";if(X||K){try{q=new URL(".",W).href}catch{}K&&($=(G)=>{var U=new XMLHttpRequest;return U.open("GET",G,!1),U.responseType="arraybuffer",U.send(null),new Uint8Array(U.response)}),Y=async(G)=>{if(k(G))return new Promise((z,O)=>{var S=new XMLHttpRequest;S.open("GET",G,!0),S.responseType="arraybuffer",S.onload=()=>{S.status==200||S.status==0&&S.response?z(S.response):O(S.status)},S.onerror=O,S.send(null)});var U=await fetch(G,{credentials:"same-origin"});if(U.ok)return U.arrayBuffer();throw Error(U.status+" : "+U.url)}}var F,N,j,B,D,L,M=console.log.bind(console),R=console.error.bind(console),E=M,P=R,w=!1,k=(G)=>G.startsWith("file://");function C(){U5.buffer!=d.buffer&&q0()}if(Z){let G=function(U){try{var z=U.data,O=z.Pc;if(O==="load"){let S=[];self.onmessage=(A)=>S.push(A),L=()=>{postMessage({Pc:"loaded"});for(let A of S)G(A);self.onmessage=G};for(let A of z.ee)Q[A]&&!Q[A].proxy||(Q[A]=(...I)=>{postMessage({Pc:"callHandler",de:A,args:I})},A=="print"&&(E=Q[A]),A=="printErr"&&(P=Q[A]));U5=z.ke,q0(),N=z.le,y0(),P9()}else if(O==="run"){(function(S){var A=(C(),v)[S+52>>>2>>>0];S=(C(),v)[S+56>>>2>>>0],jZ(A,A-S),X0(A)})(z.Oc),Q4(z.Oc,0,0,1,0,0),XK(),c7(z.Oc),g||(sK(),g=!0);try{Dq(z.ie,z.Xc)}catch(S){if(S!="unwind")throw S}}else z.target!=="setimmediate"&&(O==="checkMailbox"?g&&B9():O&&(P(`worker: received unknown command ${O}`),P(z)))}catch(S){throw GZ(),S}};var c=G,g=!1;self.onunhandledrejection=(U)=>{throw U.reason||U},self.onmessage=G}var d,r,i,p,f,v,o,Q0,x,h,_,a=!1;function q0(){var G=U5.buffer;Q.HEAP8=d=new Int8Array(G),i=new Int16Array(G),Q.HEAPU8=r=new Uint8Array(G),p=new Uint16Array(G),Q.HEAP32=f=new Int32Array(G),Q.HEAPU32=v=new Uint32Array(G),o=new Float32Array(G),Q0=new Float64Array(G),x=new BigInt64Array(G),h=new BigUint64Array(G)}function v0(){a=!0,Z?L():Z5.$b()}function J0(G){throw P(G="Aborted("+G+")"),w=!0,G=new WebAssembly.RuntimeError(G+". Build with -sASSERTIONS for more info."),D?.(G),G}function q6(){return{a:{f:Mq,J:Sq,k:Lq,p:Cq,l:Rq,sa:Aq,b:Pq,ca:Eq,Ja:VK,q:wq,da:FK,Za:UK,Fa:NK,Ha:jK,_a:zK,Xa:OK,Qa:BK,Wa:DK,oa:MK,Ga:SK,Yb:LK,Ya:CK,Zb:RK,db:Tq,Da:vq,Tb:yq,Rb:kq,Ca:bq,M:fq,I:_q,Sb:gq,ja:iq,Ub:rq,Ta:aq,Wb:nq,Ka:sq,Pb:tq,ka:eq,Sa:c7,ab:J2,U:Z2,n:W2,c:_7,rb:G2,w:q2,L:F2,z:U2,j:N2,o:yK,sb:j2,G:z2,T:O2,h:B2,u:D2,m:M2,i:S2,Na:L2,Oa:C2,Pa:R2,La:bK,Ma:fK,Qb:_K,eb:P2,cb:T2,Y:I2,qb:v2,la:y2,bb:E2,fb:x2,$a:k2,Xb:h2,N:A2,gb:b2,X:f2,Vb:_2,nb:r2,C:a2,ra:o2,qa:n2,pb:s2,W:t2,v:e2,mb:JF,lb:QF,kb:XF,ob:KF,jb:ZF,ib:HF,hb:YF,Ua:dK,Va:pK,Ia:k7,V:iK,na:rK,Ra:aK,ma:oK,Cb:O1,xa:q1,Db:z1,ya:G1,F:eF,e:gF,s:fF,x:bF,B:oF,Fb:$1,ba:Y1,D:uF,za:V1,$:F1,ga:H1,Gb:Z1,Hb:K1,Ba:J1,Aa:X1,Ib:Q1,wa:j1,aa:W1,d:_F,A:lF,r:cF,Bb:B1,t:dF,y:sF,H:mF,E:pF,K:tF,R:U1,ia:aF,_:N1,Kb:rF,Lb:iF,Jb:nF,g:VF,a:U5,Ob:p5,Eb:WF,ha:GF,O:qF,pa:FF,Mb:UF,ta:NF,Q:jF,yb:zF,zb:OF,ua:BF,ea:DF,P:MF,Ea:SF,va:LF,Z:CF,wb:RF,_b:AF,S:PF,Ab:EF,tb:wF,ub:IF,vb:vF,fa:yF,xb:xF,Nb:kF}}}async function y0(){function G(O,S){var A=Z5=O.exports;O={};for(let[I,y]of Object.entries(A))typeof y=="function"?(A=Q2(y),O[I]=A):O[I]=y;return Z5=O,Z5=function(){var I=Z5,y=(n)=>(D0)=>n(D0)>>>0,l=(n)=>()=>n()>>>0;return(I=Object.assign({},I)).ac=y(I.ac),I.Dc=l(I.Dc),I.Fc=y(I.Fc),I.sd=((n)=>(D0,L0)=>n(D0,L0)>>>0)(I.sd),I.xd=y(I.xd),I.yd=l(I.yd),I.Cd=y(I.Cd),I}(),JK.push(Z5.jd),nK=(O=Z5).ac,sK=O.bc,Q._OrtInit=O.cc,Q._OrtGetLastError=O.dc,Q._OrtCreateSessionOptions=O.ec,Q._OrtAppendExecutionProvider=O.fc,Q._OrtAddFreeDimensionOverride=O.gc,Q._OrtAddSessionConfigEntry=O.hc,Q._OrtReleaseSessionOptions=O.ic,Q._OrtCreateSession=O.jc,Q._OrtReleaseSession=O.kc,Q._OrtGetInputOutputCount=O.lc,Q._OrtGetInputOutputMetadata=O.mc,Q._OrtFree=O.nc,Q._OrtCreateTensor=O.oc,Q._OrtGetTensorData=O.pc,Q._OrtReleaseTensor=O.qc,Q._OrtCreateRunOptions=O.rc,Q._OrtAddRunConfigEntry=O.sc,Q._OrtReleaseRunOptions=O.tc,Q._OrtCreateBinding=O.uc,Q._OrtBindInput=O.vc,Q._OrtBindOutput=O.wc,Q._OrtClearBoundOutputs=O.xc,Q._OrtReleaseBinding=O.yc,Q._OrtRunWithBinding=O.zc,Q._OrtRun=O.Ac,Q._OrtEndProfiling=O.Bc,o7=Q._OrtGetWebGpuDevice=O.Cc,R9=O.Dc,T6=Q._free=O.Ec,n5=Q._malloc=O.Fc,tK=Q._wgpuBufferRelease=O.Gc,eK=Q._wgpuCreateInstance=O.Hc,JZ=O.Ic,QZ=O.Jc,XZ=O.Kc,KZ=O.Lc,ZZ=O.Mc,HZ=O.Qc,YZ=O._c,$Z=O.$c,VZ=O.ad,n7=O.cd,s7=O.dd,t7=O.ed,e7=O.fd,h8=O.gd,J4=O.hd,WZ=O.id,Q4=O.ld,GZ=O.md,qZ=O.nd,FZ=O.od,X4=O.pd,UZ=O.qd,NZ=O.rd,K4=O.sd,F0=O.td,b8=O.ud,jZ=O.vd,X0=O.wd,A9=O.xd,K0=O.yd,zZ=O.zd,Z4=O.Ad,OZ=O.Bd,BZ=O.Cd,DZ=O.Dd,H4=O.Ed,MZ=O.Fd,SZ=O.Gd,LZ=O.Hd,CZ=O.Id,RZ=O.Jd,AZ=O.Kd,PZ=O.Ld,EZ=O.Md,wZ=O.Nd,TZ=O.Od,IZ=O.Pd,vZ=O.Qd,yZ=O.Rd,xZ=O.Sd,kZ=O.Ud,hZ=O.Vd,bZ=O.Wd,fZ=O.Xd,_Z=O.Zd,gZ=O._d,cZ=O.$d,lZ=O.ae,uZ=O.be,mZ=O.ce,dZ=O.qe,pZ=O.re,iZ=O.se,rZ=O.te,aZ=O.ue,oZ=O.ve,nZ=O.we,sZ=O.xe,tZ=O.ye,eZ=O.ze,JH=O.Ae,QH=O.$e,XH=O.af,KH=O.bf,ZH=O.cf,N=S,Z5}var U,z=q6();return Q.instantiateWasm?new Promise((O)=>{Q.instantiateWasm(z,(S,A)=>{O(G(S,A))})}):Z?G(new WebAssembly.Instance(N,q6()),N):(_??=Q.locateFile?Q.locateFile?Q.locateFile("ort-wasm-simd-threaded.asyncify.wasm",q):q+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href,U=await async function(O){var S=_;if(!F&&!k(S))try{var A=fetch(S,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(A,O)}catch(I){P(`wasm streaming compile failed: ${I}`),P("falling back to ArrayBuffer instantiation")}return async function(I,y){try{var l=await async function(n){if(!F)try{var D0=await Y(n);return new Uint8Array(D0)}catch{}if(n==_&&F)n=new Uint8Array(F);else{if(!$)throw"both async and sync fetching of the wasm failed";n=$(n)}return n}(I);return await WebAssembly.instantiate(l,y)}catch(n){P(`failed to asynchronously prepare wasm: ${n}`),J0(n)}}(S,O)}(z),G(U.instance,U.module))}class l0{name="ExitStatus";constructor(G){this.message=`Program terminated with exit(${G})`,this.status=G}}var F6=(G)=>{G.terminate(),G.onmessage=()=>{}},T0=[],B0=0,d0=null,l6=(G)=>{F5.length==0&&(ZK(),KK(F5[0]));var U=F5.pop();if(!U)return 6;y8.push(U),P5[G.Oc]=U,U.Oc=G.Oc;var z={Pc:"run",ie:G.he,Xc:G.Xc,Oc:G.Oc};return U.postMessage(z,G.Zc),0},M0=0,w0=(G,U,...z)=>{var O,S=16*z.length,A=K0(),I=A9(S),y=I>>>3;for(O of z)typeof O=="bigint"?((C(),x)[y++>>>0]=1n,(C(),x)[y++>>>0]=O):((C(),x)[y++>>>0]=0n,(C(),Q0)[y++>>>0]=O);return G=qZ(G,0,S,I,U),X0(A),G};function p5(G){if(Z)return w0(0,1,G);if(j=G,!(0{if(j=G,Z)throw v8(G),"unwind";p5(G)},F5=[],y8=[],JK=[],P5={},QK=(G)=>{var U=G.Oc;delete P5[U],F5.push(G),y8.splice(y8.indexOf(G),1),G.Oc=0,FZ(U)};function XK(){JK.forEach((G)=>G())}var KK=(G)=>new Promise((U)=>{G.onmessage=(S)=>{var A=S.data;if(S=A.Pc,A.Wc&&A.Wc!=R9()){var I=P5[A.Wc];I?I.postMessage(A,A.Zc):P(`Internal error! Worker sent a message "${S}" to target pthread ${A.Wc}, but that thread no longer exists!`)}else S==="checkMailbox"?B9():S==="spawnThread"?l6(A):S==="cleanupThread"?U6(()=>{QK(P5[A.je])}):S==="loaded"?(G.loaded=!0,U(G)):A.target==="setimmediate"?G.postMessage(A):S==="uncaughtException"?G.onerror(A.error):S==="callHandler"?Q[A.de](...A.args):S&&P(`worker sent an unknown command ${S}`)},G.onerror=(S)=>{throw P(`worker sent an error! ${S.filename}:${S.lineno}: ${S.message}`),S};var z,O=[];for(z of[])Q.propertyIsEnumerable(z)&&O.push(z);G.postMessage({Pc:"load",ee:O,ke:U5,le:N})});function ZK(){var G=new Worker((()=>{let U=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new U("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});F5.push(G)}var U5,Dq=(G,U)=>{M0=0,G=H4(G,U),0-9007199254740992>G||9007199254740992>>=0);return(C(),d)[U.Rc+12>>>0]==0&&(HK(U,!0),z9--),YK(U,!1),j9.push(U),BZ(G)}var i5=0,Sq=()=>{F0(0,0);var G=j9.pop();zZ(G.Yc),i5=0};function HK(G,U){U=U?1:0,(C(),d)[G.Rc+12>>>0]=U}function YK(G,U){U=U?1:0,(C(),d)[G.Rc+13>>>0]=U}class O9{constructor(G){this.Yc=G,this.Rc=G-24}}var h7=(G)=>{var U=i5;if(!U)return b8(0),0;var z=new O9(U);(C(),v)[z.Rc+16>>>2>>>0]=U;var O=(C(),v)[z.Rc+4>>>2>>>0];if(!O)return b8(0),U;for(var S of G){if(S===0||S===O)break;if(OZ(S,O,z.Rc+16))return b8(S),U}return b8(O),U};function Lq(){return h7([])}function Cq(G){return h7([G>>>0])}function Rq(G,U,z,O){return h7([G>>>0,U>>>0,z>>>0,O>>>0])}var Aq=()=>{var G=j9.pop();G||J0("no exception to throw");var U=G.Yc;throw(C(),d)[G.Rc+13>>>0]==0&&(j9.push(G),YK(G,!0),HK(G,!1),z9++),Z4(U),i5=U};function Pq(G,U,z){var O=new O9(G>>>=0);throw U>>>=0,z>>>=0,(C(),v)[O.Rc+16>>>2>>>0]=0,(C(),v)[O.Rc+4>>>2>>>0]=U,(C(),v)[O.Rc+8>>>2>>>0]=z,Z4(G),z9++,i5=G}var Eq=()=>z9;function $K(G,U,z,O){return Z?w0(2,1,G,U,z,O):VK(G,U,z,O)}function VK(G,U,z,O){if(G>>>=0,U>>>=0,z>>>=0,O>>>=0,!globalThis.SharedArrayBuffer)return 6;var S=[];return Z&&S.length===0?$K(G,U,z,O):(G={he:z,Oc:G,Xc:O,Zc:S},Z?(G.Pc="spawnThread",postMessage(G,S),0):l6(G))}function wq(G){throw i5||=G>>>0,i5}var WK=globalThis.TextDecoder&&new TextDecoder,GK=(G,U,z,O)=>{if(z=U+z,O)return z;for(;G[U]&&!(U>=z);)++U;return U},qK=(G,U=0,z,O)=>{if(16<(z=GK(G,U>>>=0,z,O))-U&&G.buffer&&WK)return WK.decode(G.buffer instanceof ArrayBuffer?G.subarray(U,z):G.slice(U,z));for(O="";U(S=(240&S)==224?(15&S)<<12|A<<6|I:(7&S)<<18|A<<12|I<<6|63&G[U++])?O+=String.fromCharCode(S):(S-=65536,O+=String.fromCharCode(55296|S>>10,56320|1023&S))}}else O+=String.fromCharCode(S)}return O},r5=(G,U,z)=>(G>>>=0)?qK((C(),r),G,U,z):"";function FK(G,U,z){return Z?w0(3,1,G,U,z):0}function UK(G,U){if(Z)return w0(4,1,G,U)}function NK(G,U){if(Z)return w0(5,1,G,U)}function jK(G,U,z){if(Z)return w0(6,1,G,U,z)}function zK(G,U,z){return Z?w0(7,1,G,U,z):0}function OK(G,U){if(Z)return w0(8,1,G,U)}function BK(G,U,z){if(Z)return w0(9,1,G,U,z)}function DK(G,U,z,O){if(Z)return w0(10,1,G,U,z,O)}function MK(G,U,z,O){if(Z)return w0(11,1,G,U,z,O)}function SK(G,U,z,O){if(Z)return w0(12,1,G,U,z,O)}function LK(G){if(Z)return w0(13,1,G)}function CK(G,U){if(Z)return w0(14,1,G,U)}function RK(G,U,z){if(Z)return w0(15,1,G,U,z)}var Tq=()=>J0(""),u6=(G)=>{G>>>=0;for(var U="";;){var z=(C(),r)[G++>>>0];if(!z)return U;U+=String.fromCharCode(z)}},b7={},f7={},Iq={},a5=class extends Error{constructor(G){super(G),this.name="BindingError"}};function e6(G,U,z={}){return function(O,S,A={}){var I=S.name;if(!O)throw new a5(`type "${I}" must have a positive integer typeid pointer`);if(f7.hasOwnProperty(O)){if(A.fe)return;throw new a5(`Cannot register type '${I}' twice`)}f7[O]=S,delete Iq[O],b7.hasOwnProperty(O)&&(S=b7[O],delete b7[O],S.forEach((y)=>y()))}(G,U,z)}var AK=(G,U,z)=>{switch(U){case 1:return z?(O)=>(C(),d)[O>>>0]:(O)=>(C(),r)[O>>>0];case 2:return z?(O)=>(C(),i)[O>>>1>>>0]:(O)=>(C(),p)[O>>>1>>>0];case 4:return z?(O)=>(C(),f)[O>>>2>>>0]:(O)=>(C(),v)[O>>>2>>>0];case 8:return z?(O)=>(C(),x)[O>>>3>>>0]:(O)=>(C(),h)[O>>>3>>>0];default:throw TypeError(`invalid integer width (${U}): ${G}`)}};function vq(G,U,z,O,S){G>>>=0,z>>>=0,U=u6(U>>>0);let A=(I)=>I;if(O=O===0n){let I=8*z;A=(y)=>BigInt.asUintN(I,y),S=A(S)}e6(G,{name:U,Nc:A,Tc:(I,y)=>(typeof y=="number"&&(y=BigInt(y)),y),Sc:AK(U,z,!O),Uc:null})}function yq(G,U,z,O){e6(G>>>=0,{name:U=u6(U>>>0),Nc:function(S){return!!S},Tc:function(S,A){return A?z:O},Sc:function(S){return this.Nc((C(),r)[S>>>0])},Uc:null})}var PK=[],E5=[0,1,,1,null,1,!0,1,!1,1];function _7(G){9<(G>>>=0)&&--E5[G+1]===0&&(E5[G]=void 0,PK.push(G))}var C6=(G)=>{if(!G)throw new a5(`Cannot use deleted val. handle = ${G}`);return E5[G]},w6=(G)=>{switch(G){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let U=PK.pop()||E5.length;return E5[U]=G,E5[U+1]=1,U}};function g7(G){return this.Nc((C(),v)[G>>>2>>>0])}var xq={name:"emscripten::val",Nc:(G)=>{var U=C6(G);return _7(G),U},Tc:(G,U)=>w6(U),Sc:g7,Uc:null};function kq(G){return e6(G>>>0,xq)}var hq=(G,U)=>{switch(U){case 4:return function(z){return this.Nc((C(),o)[z>>>2>>>0])};case 8:return function(z){return this.Nc((C(),Q0)[z>>>3>>>0])};default:throw TypeError(`invalid float width (${U}): ${G}`)}};function bq(G,U,z){z>>>=0,e6(G>>>=0,{name:U=u6(U>>>0),Nc:(O)=>O,Tc:(O,S)=>S,Sc:hq(U,z),Uc:null})}function fq(G,U,z,O,S){G>>>=0,z>>>=0,U=u6(U>>>0);let A=(y)=>y;if(O===0){var I=32-8*z;A=(y)=>y<>>I,S=A(S)}e6(G,{name:U,Nc:A,Tc:(y,l)=>l,Sc:AK(U,z,O!==0),Uc:null})}function _q(G,U,z){function O(A){var I=(C(),v)[A>>>2>>>0];return A=(C(),v)[A+4>>>2>>>0],new S((C(),d).buffer,A,I)}var S=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][U];e6(G>>>=0,{name:z=u6(z>>>0),Nc:O,Sc:O},{fe:!0})}var J5=(G,U,z)=>{var O=(C(),r);if(U>>>=0,0=I){if(U>=z)break;O[U++>>>0]=I}else if(2047>=I){if(U+1>=z)break;O[U++>>>0]=192|I>>6,O[U++>>>0]=128|63&I}else if(65535>=I){if(U+2>=z)break;O[U++>>>0]=224|I>>12,O[U++>>>0]=128|I>>6&63,O[U++>>>0]=128|63&I}else{if(U+3>=z)break;O[U++>>>0]=240|I>>18,O[U++>>>0]=128|I>>12&63,O[U++>>>0]=128|I>>6&63,O[U++>>>0]=128|63&I,A++}}O[U>>>0]=0,G=U-S}else G=0;return G},Q5=(G)=>{for(var U=0,z=0;z=O?U++:2047>=O?U+=2:55296<=O&&57343>=O?(U+=4,++z):U+=3}return U};function gq(G,U){e6(G>>>=0,{name:U=u6(U>>>0),Nc(z){var O=(C(),v)[z>>>2>>>0];return O=r5(z+4,O,!0),T6(z),O},Tc(z,O){O instanceof ArrayBuffer&&(O=new Uint8Array(O));var S=typeof O=="string";if(!(S||ArrayBuffer.isView(O)&&O.BYTES_PER_ELEMENT==1))throw new a5("Cannot pass non-string to std::string");var A=S?Q5(O):O.length,I=n5(4+A+1),y=I+4;return(C(),v)[I>>>2>>>0]=A,S?J5(O,y,A+1):(C(),r).set(O,y>>>0),z!==null&&z.push(T6,I),I},Sc:g7,Uc(z){T6(z)}})}var EK=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,cq=(G,U,z)=>{if(G>>>=1,16<(U=GK((C(),p),G,U/2,z))-G&&EK)return EK.decode((C(),p).slice(G,U));for(z="";G>>0];z+=String.fromCharCode(O)}return z},lq=(G,U,z)=>{if(z??=2147483647,2>z)return 0;var O=U;z=(z-=2)<2*G.length?z/2:G.length;for(var S=0;S>>1>>>0]=A,U+=2}return(C(),i)[U>>>1>>>0]=0,U-O},uq=(G)=>2*G.length,mq=(G,U,z)=>{var O="";G>>>=2;for(var S=0;!(S>=U/4);S++){var A=(C(),v)[G+S>>>0];if(!A&&!z)break;O+=String.fromCodePoint(A)}return O},dq=(G,U,z)=>{if(U>>>=0,z??=2147483647,4>z)return 0;var O=U;z=O+z-4;for(var S=0;S>>2>>>0]=A,(U+=4)+4>z)break}return(C(),f)[U>>>2>>>0]=0,U-O},pq=(G)=>{for(var U=0,z=0;z>>=0,U>>>=0,z=u6(z>>>=0),U===2)var O=cq,S=lq,A=uq;else O=mq,S=dq,A=pq;e6(G,{name:z,Nc:(I)=>{var y=(C(),v)[I>>>2>>>0];return y=O(I+4,y*U,!0),T6(I),y},Tc:(I,y)=>{if(typeof y!="string")throw new a5(`Cannot pass non-string to C++ string type ${z}`);var l=A(y),n=n5(4+l+U);return(C(),v)[n>>>2>>>0]=l/U,S(y,n+4,l+U),I!==null&&I.push(T6,n),n},Sc:g7,Uc(I){T6(I)}})}function rq(G,U){e6(G>>>=0,{ge:!0,name:U=u6(U>>>0),Nc:()=>{},Tc:()=>{}})}function aq(G){Q4(G>>>0,!K,1,!X,131072,!1),XK()}var U6=(G)=>{if(!w)try{if(G(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function c7(G){G>>>=0,oq||(Atomics.waitAsync((C(),f),G>>>2,G).value.then(B9),G+=128,Atomics.store((C(),f),G>>>2,1))}var B9=()=>U6(()=>{var G=R9();G&&(c7(G),NZ())});function nq(G,U){(G>>>=0)==U>>>0?setTimeout(B9):Z?postMessage({Wc:G,Pc:"checkMailbox"}):(G=P5[G])&&G.postMessage({Pc:"checkMailbox"})}var l7=[];function sq(G,U,z,O,S){for(U>>>=0,S>>>=0,l7.length=0,z=S>>>3,O=S+O>>>3;z>>0]?(C(),x)[z++>>>0]:(C(),Q0)[z++>>>0],l7.push(A)}return(U?Y4[U]:hF[G])(...l7)}var tq=()=>{M0=0};function eq(G){G>>>=0,Z?postMessage({Pc:"cleanupThread",je:G}):QK(P5[G])}function J2(G){}var D9=(G)=>{try{G()}catch(U){J0(U)}};function Q2(G){var U=(...z)=>{M9.push(G);try{return G(...z)}finally{w||(M9.pop(),m6&&N5===1&&M9.length===0&&(N5=0,M0+=1,D9(XH),typeof Fibers<"u"&&Fibers.De()))}};return IK.set(G,U),U}var N5=0,m6=null,wK=0,M9=[],u7=new Map,TK=new Map,IK=new Map,X2=0,m7=null,K2=[],vK=(G)=>function(U){if(!w){if(N5===0){var z=!1,O=!1;U((S=0)=>{if(!w&&(wK=S,z=!0,O)){N5=2,D9(()=>KH(m6)),typeof MainLoop<"u"&&MainLoop.Yd&&MainLoop.resume(),S=!1;try{var A=function(){var l=(C(),f)[m6+8>>>2>>>0];return l=TK.get(l),l=IK.get(l),--M0,l()}()}catch(l){A=l,S=!0}var I=!1;if(!m6){var y=m7;y&&(m7=null,(S?y.reject:y.resolve)(A),I=!0)}if(S&&!I)throw A}}),O=!0,z||(N5=1,m6=function(){var S=n5(65548),A=S+12;if((C(),v)[S>>>2>>>0]=A,(C(),v)[S+4>>>2>>>0]=A+65536,A=M9[0],!u7.has(A)){var I=X2++;u7.set(A,I),TK.set(I,A)}return A=u7.get(A),(C(),f)[S+8>>>2>>>0]=A,S}(),typeof MainLoop<"u"&&MainLoop.Yd&&MainLoop.pause(),D9(()=>QH(m6)))}else N5===2?(N5=0,D9(ZH),T6(m6),m6=null,K2.forEach(U6)):J0(`invalid state: ${N5}`);return wK}}((U)=>{G().then(U)});function Z2(G){return G>>>=0,vK(async()=>{var U=await C6(G);return w6(U)})}var d7=[],H2=(G)=>{var U=d7.length;return d7.push(G),U},Y2=(G,U)=>{for(var z=Array(G),O=0;O>>2>>>0],I=f7[A];if(I===void 0)throw G=`parameter ${O}`,A=nK(A),U=u6(A),T6(A),new a5(`${G} has unknown type ${U}`);z[S]=I}return z},$2=(G,U,z)=>{var O=[];return G=G(O,z),O.length&&((C(),v)[U>>>2>>>0]=w6(O)),G},V2={},S9=(G)=>{var U=V2[G];return U===void 0?u6(G):U};function W2(G,U,z){var[O,...S]=Y2(G,U>>>0);U=O.Tc.bind(O);var A=S.map((l)=>l.Sc.bind(l));G--;var I={toValue:C6};switch(G=A.map((l,n)=>{var D0=`argFromPtr${n}`;return I[D0]=l,`${D0}(args${n?"+"+8*n:""})`}),z){case 0:var y="toValue(handle)";break;case 2:y="new (toValue(handle))";break;case 3:y="";break;case 1:I.getStringOrSymbol=S9,y="toValue(handle)[getStringOrSymbol(methodName)]"}return y+=`(${G})`,O.ge||(I.toReturnWire=U,I.emval_returnValue=$2,y=`return emval_returnValue(toReturnWire, destructorsRef, ${y})`),y=`return function (handle, methodName, destructorsRef, args) { ${y} }`,z=Function(Object.keys(I),y)(...Object.values(I)),y=`methodCaller<(${S.map((l)=>l.name)}) => ${O.name}>`,H2(Object.defineProperty(z,"name",{value:y}))}function G2(G,U){return U>>>=0,(G=C6(G>>>0))==C6(U)}function q2(G){return(G>>>=0)?(G=S9(G),w6(globalThis[G])):w6(globalThis)}function F2(G){return G=S9(G>>>0),w6(Q[G])}function U2(G,U){return U>>>=0,G=C6(G>>>0),U=C6(U),w6(G[U])}function N2(G){9<(G>>>=0)&&(E5[G+1]+=1)}function yK(G,U,z,O,S){return d7[G>>>0](U>>>0,z>>>0,O>>>0,S>>>0)}function j2(G,U,z,O,S){return yK(G>>>0,U>>>0,z>>>0,O>>>0,S>>>0)}function z2(){return w6([])}function O2(G){G=C6(G>>>0);for(var U=Array(G.length),z=0;z>>0))}function D2(){return w6({})}function M2(G){for(var U=C6(G>>>=0);U.length;){var z=U.pop();U.pop()(z)}_7(G)}function S2(G,U,z){U>>>=0,z>>>=0,G=C6(G>>>0),U=C6(U),z=C6(z),G[U]=z}function L2(G,U){G=J6(G),U>>>=0,G=new Date(1000*G),(C(),f)[U>>>2>>>0]=G.getUTCSeconds(),(C(),f)[U+4>>>2>>>0]=G.getUTCMinutes(),(C(),f)[U+8>>>2>>>0]=G.getUTCHours(),(C(),f)[U+12>>>2>>>0]=G.getUTCDate(),(C(),f)[U+16>>>2>>>0]=G.getUTCMonth(),(C(),f)[U+20>>>2>>>0]=G.getUTCFullYear()-1900,(C(),f)[U+24>>>2>>>0]=G.getUTCDay(),G=(G.getTime()-Date.UTC(G.getUTCFullYear(),0,1,0,0,0,0))/86400000|0,(C(),f)[U+28>>>2>>>0]=G}var xK=(G)=>G%4==0&&(G%100!=0||G%400==0),kK=[0,31,60,91,121,152,182,213,244,274,305,335],hK=[0,31,59,90,120,151,181,212,243,273,304,334];function C2(G,U){G=J6(G),U>>>=0,G=new Date(1000*G),(C(),f)[U>>>2>>>0]=G.getSeconds(),(C(),f)[U+4>>>2>>>0]=G.getMinutes(),(C(),f)[U+8>>>2>>>0]=G.getHours(),(C(),f)[U+12>>>2>>>0]=G.getDate(),(C(),f)[U+16>>>2>>>0]=G.getMonth(),(C(),f)[U+20>>>2>>>0]=G.getFullYear()-1900,(C(),f)[U+24>>>2>>>0]=G.getDay();var z=(xK(G.getFullYear())?kK:hK)[G.getMonth()]+G.getDate()-1|0;(C(),f)[U+28>>>2>>>0]=z,(C(),f)[U+36>>>2>>>0]=-60*G.getTimezoneOffset(),z=new Date(G.getFullYear(),6,1).getTimezoneOffset();var O=new Date(G.getFullYear(),0,1).getTimezoneOffset();G=0|(z!=O&&G.getTimezoneOffset()==Math.min(O,z)),(C(),f)[U+32>>>2>>>0]=G}function R2(G){G>>>=0;var U=new Date((C(),f)[G+20>>>2>>>0]+1900,(C(),f)[G+16>>>2>>>0],(C(),f)[G+12>>>2>>>0],(C(),f)[G+8>>>2>>>0],(C(),f)[G+4>>>2>>>0],(C(),f)[G>>>2>>>0],0),z=(C(),f)[G+32>>>2>>>0],O=U.getTimezoneOffset(),S=new Date(U.getFullYear(),6,1).getTimezoneOffset(),A=new Date(U.getFullYear(),0,1).getTimezoneOffset(),I=Math.min(A,S);return 0>z?(C(),f)[G+32>>>2>>>0]=+(S!=A&&I==O):0>>2>>>0]=U.getDay(),z=(xK(U.getFullYear())?kK:hK)[U.getMonth()]+U.getDate()-1|0,(C(),f)[G+28>>>2>>>0]=z,(C(),f)[G>>>2>>>0]=U.getSeconds(),(C(),f)[G+4>>>2>>>0]=U.getMinutes(),(C(),f)[G+8>>>2>>>0]=U.getHours(),(C(),f)[G+12>>>2>>>0]=U.getDate(),(C(),f)[G+16>>>2>>>0]=U.getMonth(),(C(),f)[G+20>>>2>>>0]=U.getYear(),G=U.getTime(),BigInt(isNaN(G)?-1:G/1000)}function bK(G,U,z,O,S,A,I){return Z?w0(16,1,G,U,z,O,S,A,I):-52}function fK(G,U,z,O,S,A){if(Z)return w0(17,1,G,U,z,O,S,A)}var x8={},A2=()=>performance.timeOrigin+performance.now();function _K(G,U){if(Z)return w0(18,1,G,U);if(x8[G]&&(clearTimeout(x8[G].id),delete x8[G]),!U)return 0;var z=setTimeout(()=>{delete x8[G],U6(()=>UZ(G,performance.timeOrigin+performance.now()))},U);return x8[G]={id:z,Ce:U},0}function P2(G,U,z,O){G>>>=0,U>>>=0,z>>>=0,O>>>=0;var S=new Date().getFullYear(),A=new Date(S,0,1).getTimezoneOffset();S=new Date(S,6,1).getTimezoneOffset();var I=Math.max(A,S);(C(),v)[G>>>2>>>0]=60*I,(C(),f)[U>>>2>>>0]=+(A!=S),G=(U=(y)=>{var l=Math.abs(y);return`UTC${0<=y?"-":"+"}${String(Math.floor(l/60)).padStart(2,"0")}${String(l%60).padStart(2,"0")}`})(A),U=U(S),SDate.now(),w2=1;function T2(G,U,z){if(z>>>=0,!(0<=G&&3>=G))return 28;if(G===0)G=Date.now();else{if(!w2)return 52;G=performance.timeOrigin+performance.now()}return G=Math.round(1e6*G),(C(),x)[z>>>3>>>0]=BigInt(G),0}var p7=[],gK=(G,U)=>{p7.length=0;for(var z;z=(C(),r)[G++>>>0];){var O=z!=105;U+=(O&=z!=112)&&U%8?4:0,p7.push(z==112?(C(),v)[U>>>2>>>0]:z==106?(C(),x)[U>>>3>>>0]:z==105?(C(),f)[U>>>2>>>0]:(C(),Q0)[U>>>3>>>0]),U+=O?8:4}return p7};function I2(G,U,z){return G>>>=0,U=gK(U>>>0,z>>>0),Y4[G](...U)}function v2(G,U,z){return G>>>=0,U=gK(U>>>0,z>>>0),Y4[G](...U)}var y2=()=>{};function x2(G,U){return P(r5(G>>>0,U>>>0))}var k2=()=>{throw M0+=1,"unwind"};function h2(){return 4294901760}var b2=()=>1,f2=()=>navigator.hardwareConcurrency;function _2(G){G>>>=0;var U=(C(),r).length;if(G<=U||4294901760=z;z*=2){var O=U*(1+0.2/z);O=Math.min(O,G+100663296);J:{O=(Math.min(4294901760,65536*Math.ceil(Math.max(G,O)/65536))-U5.buffer.byteLength+65535)/65536|0;try{U5.grow(O),q0();var S=1;break J}catch{}S=void 0}if(S)return!0}return!1}var d6=(G)=>{var U=Q5(G)+1,z=A9(U);return J5(G,z,U),z},i7=(G,U)=>{(C(),v)[G>>>2>>>0]=U;var z=(C(),v)[G>>>2>>>0];(C(),v)[G+4>>>2>>>0]=(U-z)/4294967296},k8=(G)=>(C(),v)[G>>>2>>>0]+4294967296*(C(),f)[G+4>>>2>>>0],Q6=[],g2=(G,U)=>{Q6[G>>>0]=U},X5=[],L9=[],o5=(G,U)=>{L9[G]=new Promise((z)=>U.finally(()=>z(G)))},t=(G)=>{if(G)return Q6[G>>>0]},c2=(G,U)=>{for(G=(C(),v)[G>>>2>>>0];G;G=(C(),v)[G>>>2>>>0])U[(C(),f)[G+4>>>2>>>0]](G)},C9=(G,U,z)=>{(C(),v)[G>>>2>>>0]=U,(C(),v)[G+4>>>2>>>0]=z},cK=(G)=>{var U=(C(),v)[G>>>2>>>0];return G=(C(),v)[G+4>>>2>>>0],r5(U,G)},K5=(G)=>{var U=(C(),v)[G>>>2>>>0];return G=(C(),v)[G+4>>>2>>>0],U?r5(U,G):G===0?"":void 0},l2=(G)=>{var U=K5(G+4),z=(z=(C(),v)[G+12>>>2>>>0])?t(z):"auto";if(G+=16){var O=t((C(),v)[G+4>>>2>>>0]),S=(C(),v)[G+16>>>2>>>0],A=(C(),v)[G+20>>>2>>>0];if(S){for(var I={},y=0;y>>3>>>0]}S=I}else S=void 0;G={module:O,constants:S,entryPoint:K5(G+8)}}else G=void 0;return{label:U,layout:z,compute:G}},lK=(G,U)=>{function z(O,S){O=G[O],(C(),v)[U+S>>>2>>>0]=O}z("maxTextureDimension1D",4),z("maxTextureDimension2D",8),z("maxTextureDimension3D",12),z("maxTextureArrayLayers",16),z("maxBindGroups",20),z("maxBindGroupsPlusVertexBuffers",24),z("maxBindingsPerBindGroup",28),z("maxDynamicUniformBuffersPerPipelineLayout",32),z("maxDynamicStorageBuffersPerPipelineLayout",36),z("maxSampledTexturesPerShaderStage",40),z("maxSamplersPerShaderStage",44),z("maxStorageBuffersPerShaderStage",48),z("maxStorageTexturesPerShaderStage",52),z("maxUniformBuffersPerShaderStage",56),z("minUniformBufferOffsetAlignment",80),z("minStorageBufferOffsetAlignment",84),i7(U+64,G.maxUniformBufferBindingSize),i7(U+72,G.maxStorageBufferBindingSize),z("maxVertexBuffers",88),i7(U+96,G.maxBufferSize),z("maxVertexAttributes",104),z("maxVertexBufferArrayStride",108),z("maxInterStageShaderVariables",112),z("maxColorAttachments",116),z("maxColorAttachmentBytesPerSample",120),z("maxComputeWorkgroupStorageSize",124),z("maxComputeInvocationsPerWorkgroup",128),z("maxComputeWorkgroupSizeX",132),z("maxComputeWorkgroupSizeY",136),z("maxComputeWorkgroupSizeZ",140),z("maxComputeWorkgroupsPerDimension",144),G.Be!==void 0&&z("maxImmediateSize",148)},u2=[,"validation","out-of-memory","internal"],m2=[,"compatibility","core"],uK={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"},d2=[,"low-power","high-performance"],p2=[,"occlusion","timestamp"],i2={undefined:1,unknown:1,destroyed:2};function r2(G,U,z,O,S,A){U=J6(U),z=J6(z),O>>>=0,S>>>=0,A>>>=0;var I=t(G>>>0);if(G={},A){var y=(C(),v)[A+12>>>2>>>0];if(y){var l=(C(),v)[A+16>>>2>>>0];G.requiredFeatures=Array.from((C(),v).subarray(l>>>2>>>0,l+4*y>>>2>>>0),(e)=>uK[e])}var n=(C(),v)[A+20>>>2>>>0];if(n){let e=function(N6,n0,w5=!1){n0=n+n0,(n0=(C(),v)[n0>>>2>>>0])==4294967295||w5&&n0==0||(I0[N6]=n0)},o0=function(N6,n0){n0=n+n0;var w5=(C(),v)[n0>>>2>>>0],D1=(C(),v)[n0+4>>>2>>>0];w5==4294967295&&D1==4294967295||(I0[N6]=k8(n0))};var D0=e,L0=o0,I0={};e("maxTextureDimension1D",4),e("maxTextureDimension2D",8),e("maxTextureDimension3D",12),e("maxTextureArrayLayers",16),e("maxBindGroups",20),e("maxBindGroupsPlusVertexBuffers",24),e("maxDynamicUniformBuffersPerPipelineLayout",32),e("maxDynamicStorageBuffersPerPipelineLayout",36),e("maxSampledTexturesPerShaderStage",40),e("maxSamplersPerShaderStage",44),e("maxStorageBuffersPerShaderStage",48),e("maxStorageTexturesPerShaderStage",52),e("maxUniformBuffersPerShaderStage",56),e("minUniformBufferOffsetAlignment",80),e("minStorageBufferOffsetAlignment",84),o0("maxUniformBufferBindingSize",64),o0("maxStorageBufferBindingSize",72),e("maxVertexBuffers",88),o0("maxBufferSize",96),e("maxVertexAttributes",104),e("maxVertexBufferArrayStride",108),e("maxInterStageShaderVariables",112),e("maxColorAttachments",116),e("maxColorAttachmentBytesPerSample",120),e("maxComputeWorkgroupStorageSize",124),e("maxComputeInvocationsPerWorkgroup",128),e("maxComputeWorkgroupSizeX",132),e("maxComputeWorkgroupSizeY",136),e("maxComputeWorkgroupSizeZ",140),e("maxComputeWorkgroupsPerDimension",144),e("maxImmediateSize",148,!0),G.requiredLimits=I0}(y=(C(),v)[A+24>>>2>>>0])&&(y={label:K5(y+4)},G.defaultQueue=y),G.label=K5(A+4)}M0+=1,o5(U,I.requestDevice(G).then((e)=>{--M0,U6(()=>{Q6[S>>>0]=e.queue,Q6[O>>>0]=e,M0+=1,o5(z,e.lost.then((o0)=>{U6(()=>{e.onuncapturederror=()=>{};var N6=K0(),n0=d6(o0.message);s7(z,i2[o0.reason],n0),X0(N6)}),--M0})),e.onuncapturederror=(o0)=>{var N6=5;o0.error instanceof GPUValidationError?N6=2:o0.error instanceof GPUOutOfMemoryError?N6=3:o0.error instanceof GPUInternalError&&(N6=4);var n0=K0();o0=d6(o0.error.message),WZ(O,N6,o0),X0(n0)},"adapterInfo"in e||(e.adapterInfo=I.info),J4(U,1,O,0)})},(e)=>{--M0,U6(()=>{var o0=K0(),N6=d6(e.message);J4(U,3,O,N6),z&&s7(z,4,N6),X0(o0)})}))}function a2(G){var U=t(G>>>=0),z=X5[G];if(z){for(var O=0;O>>=0;var O=t(G>>>=0);z==4294967295&&(z=void 0);try{var S=O.getMappedRange(U>>>0,z)}catch{return 0}var A=K4(16,S.byteLength);return(C(),r).set(new Uint8Array(S),A>>>0),X5[G].push(()=>T6(A)),A}function n2(G,U,z){z>>>=0;var O=t(G>>>=0);z==4294967295&&(z=void 0);try{var S=O.getMappedRange(U>>>0,z)}catch{return 0}var A=K4(16,S.byteLength);return(C(),r).fill(0,A,S.byteLength),X5[G].push(()=>{new Uint8Array(S).set((C(),r).subarray(A>>>0,A+S.byteLength>>>0)),T6(A)}),A}function s2(G,U,z,O,S){G>>>=0,U=J6(U),z=J6(z),S>>>=0;var A=t(G);X5[G]=[],S==4294967295&&(S=void 0),M0+=1,o5(U,A.mapAsync(z,O>>>0,S).then(()=>{--M0,U6(()=>{t7(U,1,0)})},(I)=>{--M0,U6(()=>{K0();var y=d6(I.message);t7(U,I.name==="AbortError"?4:I.name==="OperationError"?3:0,y),delete X5[G]})}))}function t2(G){var U=t(G>>>=0),z=X5[G];if(z){for(var O=0;O>>0]}function JF(G,U,z){G>>>=0,U>>>=0,z>>>=0;var O=!!(C(),v)[U+32>>>2>>>0];U={label:K5(U+4),usage:(C(),v)[U+16>>>2>>>0],size:k8(U+24),mappedAtCreation:O},G=t(G);try{var S=G.createBuffer(U)}catch{return!1}return Q6[z>>>0]=S,O&&(X5[z]=[]),!0}function QF(G,U,z,O){G>>>=0,U=J6(U),O>>>=0,z=l2(z>>>0),G=t(G),M0+=1,o5(U,G.createComputePipelineAsync(z).then((S)=>{--M0,U6(()=>{Q6[O>>>0]=S,n7(U,1,O,0)})},(S)=>{--M0,U6(()=>{var A=K0(),I=d6(S.message);n7(U,S.reason==="validation"?3:S.reason==="internal"?4:0,O,I),X0(A)})}))}function XF(G,U,z){G>>>=0,U>>>=0,z>>>=0;var O=(C(),v)[U>>>2>>>0],S=(C(),f)[O+4>>>2>>>0];U={label:K5(U+4),code:""},S===2&&(U.code=cK(O+8)),G=t(G).createShaderModule(U),Q6[z>>>0]=G}var KF=(G)=>{(G=t(G)).onuncapturederror=null,G.destroy()};function ZF(G,U){U=J6(U),G=t(G>>>0),M0+=1,o5(U,G.popErrorScope().then((z)=>{--M0,U6(()=>{var O=5;z?z instanceof GPUValidationError?O=2:z instanceof GPUOutOfMemoryError?O=3:z instanceof GPUInternalError&&(O=4):O=1;var S=K0(),A=z?d6(z.message):0;e7(U,1,O,A),X0(S)})},(z)=>{--M0,U6(()=>{var O=K0(),S=d6(z.message);e7(U,1,5,S),X0(O)})}))}function HF(G,U,z,O){if(U=J6(U),O>>>=0,z>>>=0){var S={featureLevel:m2[(C(),f)[z+4>>>2>>>0]],powerPreference:d2[(C(),f)[z+8>>>2>>>0]],forceFallbackAdapter:!!(C(),v)[z+12>>>2>>>0]};(G=(C(),v)[z>>>2>>>0])!==0&&(C(),S.Fe=!!(C(),v)[G+8>>>2>>>0])}"gpu"in navigator?(M0+=1,o5(U,navigator.gpu.requestAdapter(S).then((A)=>{--M0,U6(()=>{if(A)Q6[O>>>0]=A,h8(U,1,O,0);else{var I=K0(),y=d6("WebGPU not available on this browser (requestAdapter returned null)");h8(U,3,O,y),X0(I)}})},(A)=>{--M0,U6(()=>{var I=K0(),y=d6(A.message);h8(U,4,O,y),X0(I)})}))):(S=K0(),G=d6("WebGPU not available on this browser (navigator.gpu is not available)"),h8(U,3,O,G),X0(S))}function YF(G,U,z){return G>>>=0,U>>>=0,z>>>=0,vK(async()=>{var O=[];if(z){var S=(C(),f)[z>>>2>>>0];O.length=U+1,O[U]=new Promise((y)=>setTimeout(y,S,0))}else O.length=U;for(var A=0;A{if(!r7){var G,U={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(G in a7)a7[G]===void 0?delete U[G]:U[G]=a7[G];var z=[];for(G in U)z.push(`${G}=${U[G]}`);r7=z}return r7};function dK(G,U){if(Z)return w0(19,1,G,U);G>>>=0,U>>>=0;var z,O=0,S=0;for(z of mK()){var A=U+O;(C(),v)[G+S>>>2>>>0]=A,O+=J5(z,A,1/0)+1,S+=4}return 0}function pK(G,U){if(Z)return w0(20,1,G,U);G>>>=0,U>>>=0;var z=mK();for(var O of((C(),v)[G>>>2>>>0]=z.length,G=0,z))G+=Q5(O)+1;return(C(),v)[U>>>2>>>0]=G,0}function iK(G){return Z?w0(21,1,G):52}function rK(G,U,z,O){return Z?w0(22,1,G,U,z,O):52}function aK(G,U,z,O){return Z?w0(23,1,G,U,z,O):70}var $F=[null,[],[]];function oK(G,U,z,O){if(Z)return w0(24,1,G,U,z,O);U>>>=0,z>>>=0,O>>>=0;for(var S=0,A=0;A>>2>>>0],y=(C(),v)[U+4>>>2>>>0];U+=8;for(var l=0;l>>0],L0=$F[n];D0===0||D0===10?((n===1?E:P)(qK(L0)),L0.length=0):L0.push(D0)}S+=y}return(C(),v)[O>>>2>>>0]=S,0}function VF(G){return G>>>0}function WF(G,U){return lK(t(G>>>0).limits,U>>>0),1}function GF(G,U){return t(G>>>0).features.has(uK[U])}function qF(G){return BigInt(t(G>>>0).size)}function FF(G){return BigInt(t(G>>>0).usage)}function UF(G,U){if(G>>>=0,U>>>=0){var z=K5(U+4);z={label:z,timestampWrites:U=(U=(C(),v)[U+12>>>2>>>0])!==0?{querySet:t((C(),v)[U+4>>>2>>>0]),beginningOfPassWriteIndex:(C(),v)[U+8>>>2>>>0],endOfPassWriteIndex:(C(),v)[U+12>>>2>>>0]}:void 0}}return U=t(G),G=ZZ(0),z=U.beginComputePass(z),Q6[G>>>0]=z,G}function NF(G,U,z,O){z=J6(z),(O=J6(O))==-1&&(O=void 0),(G=t(G>>>0)).clearBuffer(t(U>>>0),z,O)}function jF(G,U,z,O,S,A){z=J6(z),S=J6(S),A=J6(A),t(G>>>0).copyBufferToBuffer(t(U>>>0),z,t(O>>>0),S,A)}function zF(G){var U=t(G>>>0);return G=XZ(0),U=U.finish(),Q6[G>>>0]=U,G}function OF(G,U,z,O,S,A){A=J6(A),t(G>>>0).resolveQuerySet(t(U>>>0),z,O,t(S>>>0),A)}function BF(G,U,z,O){t(G>>>0).dispatchWorkgroups(U,z,O)}function DF(G,U,z){z=J6(z),t(G>>>0).dispatchWorkgroupsIndirect(t(U>>>0),z)}function MF(G){t(G>>>0).end()}function SF(G,U,z,O,S){O>>>=0,S>>>=0,G=t(G>>>0),z=t(z>>>0),O==0?G.setBindGroup(U,z):G.setBindGroup(U,z,(C(),v),S>>>2,O)}function LF(G,U){t(G>>>0).setPipeline(t(U>>>0))}function CF(G,U,z){t(G>>>0).Ee(t(U>>>0),z)}function RF(G,U){var z=t(G>>>0);return G=QZ(0),U=z.getBindGroupLayout(U),Q6[G>>>0]=U,G}function AF(G,U){function z(S){var A=(C(),v)[S+8>>>2>>>0],I=(C(),v)[S+32>>>2>>>0],y=(C(),v)[S+36>>>2>>>0],l=0;return c2(S,{327681:(n)=>{l=(C(),v)[n+8>>>2>>>0]}}),A?((I=k8(S+24))==-1&&(I=void 0),A={buffer:t(A),offset:k8(S+16),size:I}):A=t(I||y||l),{binding:(C(),v)[S+4>>>2>>>0],resource:A}}G>>>=0,U={label:K5((U>>>=0)+4),layout:t((C(),v)[U+12>>>2>>>0]),entries:function(S,A){for(var I=[],y=0;y>>2>>>0],(C(),v)[U+20>>>2>>>0])},G=t(G);var O=JZ(0);return g2(O,G.createBindGroup(U)),O}function PF(G,U){var z;return G>>>=0,(U>>>=0)&&(z={label:K5(U+4)}),U=t(G),G=KZ(0),z=U.createCommandEncoder(z),Q6[G>>>0]=z,G}function EF(G,U){G>>>=0,U>>>=0,U={type:p2[(C(),f)[U+12>>>2>>>0]],count:(C(),v)[U+16>>>2>>>0]};var z=t(G);return G=HZ(0),U=z.createQuerySet(U),Q6[G>>>0]=U,G}function wF(G,U){G=t(G>>>0).adapterInfo,U>>>=0,(C(),v)[U+52>>>2>>>0]=G.subgroupMinSize,(C(),v)[U+56>>>2>>>0]=G.subgroupMaxSize;var z=G.vendor+G.architecture+G.device+G.description,O=Q5(z)+1,S=n5(O);return S&&J5(z,S,O),z=S,O=Q5(G.vendor),C9(U+4,z,O),z+=O,O=Q5(G.architecture),C9(U+12,z,O),z+=O,O=Q5(G.device),C9(U+20,z,O),C9(U+28,z+O,Q5(G.description)),(C(),f)[U+36>>>2>>>0]=2,G=G.isFallbackAdapter?3:4,(C(),f)[U+40>>>2>>>0]=G,(C(),v)[U+44>>>2>>>0]=0,(C(),v)[U+48>>>2>>>0]=0,1}var TF={"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 IF(G,U){U>>>=0;var z=t(G>>>0);G=n5(4*z.features.size);var O=0,S=0;for(let A of z.features)0<=(z=TF[A])&&((C(),f)[G+O>>>2>>>0]=z,O+=4,S++);(C(),v)[U+4>>>2>>>0]=G,(C(),v)[U>>>2>>>0]=S}function vF(G,U){return lK(t(G>>>0).limits,U>>>0),1}function yF(G,U){t(G>>>0).pushErrorScope(u2[U])}function xF(G,U,z){U>>>=0,z>>>=0,G=t(G>>>0),U=Array.from((C(),f).subarray(z>>>2>>>0,z+4*U>>>2>>>0),(O)=>t(O)),G.submit(U)}function kF(G,U,z,O,S){z=J6(z),O>>>=0,S>>>=0,G=t(G>>>0),U=t(U>>>0),O=(C(),r).subarray(O>>>0,O+S>>>0),G.writeBuffer(U,z,O,0,S)}Z||function(){for(var G=Q.numThreads-1;G--;)ZK();T0.push(async()=>{var U=async function(){if(!Z)return Promise.all(F5.map(KK))}();B0++,await U,--B0==0&&d0&&(U=d0,d0=null,U())})}(),Z||(U5=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),q0()),Q.wasmBinary&&(F=Q.wasmBinary),Q.stackSave=()=>K0(),Q.stackRestore=(G)=>X0(G),Q.stackAlloc=(G)=>A9(G),Q.setValue=function(G,U,z="i8"){switch(z.endsWith("*")&&(z="*"),z){case"i1":case"i8":(C(),d)[G>>>0]=U;break;case"i16":(C(),i)[G>>>1>>>0]=U;break;case"i32":(C(),f)[G>>>2>>>0]=U;break;case"i64":(C(),x)[G>>>3>>>0]=BigInt(U);break;case"float":(C(),o)[G>>>2>>>0]=U;break;case"double":(C(),Q0)[G>>>3>>>0]=U;break;case"*":(C(),v)[G>>>2>>>0]=U;break;default:J0(`invalid type for setValue: ${z}`)}},Q.getValue=function(G,U="i8"){switch(U.endsWith("*")&&(U="*"),U){case"i1":case"i8":return(C(),d)[G>>>0];case"i16":return(C(),i)[G>>>1>>>0];case"i32":return(C(),f)[G>>>2>>>0];case"i64":return(C(),x)[G>>>3>>>0];case"float":return(C(),o)[G>>>2>>>0];case"double":return(C(),Q0)[G>>>3>>>0];case"*":return(C(),v)[G>>>2>>>0];default:J0(`invalid type for getValue: ${U}`)}},Q.UTF8ToString=r5,Q.stringToUTF8=J5,Q.lengthBytesUTF8=Q5;var nK,sK,o7,R9,T6,n5,tK,eK,JZ,QZ,XZ,KZ,ZZ,HZ,YZ,$Z,VZ,n7,s7,t7,e7,h8,J4,WZ,Q4,GZ,qZ,FZ,X4,UZ,NZ,K4,F0,b8,jZ,X0,A9,K0,zZ,Z4,OZ,BZ,DZ,H4,MZ,SZ,LZ,CZ,RZ,AZ,PZ,EZ,wZ,TZ,IZ,vZ,yZ,xZ,kZ,hZ,bZ,fZ,_Z,gZ,cZ,lZ,uZ,mZ,dZ,pZ,iZ,rZ,aZ,oZ,nZ,sZ,tZ,eZ,JH,QH,XH,KH,ZH,Z5,hF=[p5,v8,$K,FK,UK,NK,jK,zK,OK,BK,DK,MK,SK,LK,CK,RK,bK,fK,_K,dK,pK,iK,rK,aK,oK],Y4={1028716:(G,U,z,O,S)=>{if(Q===void 0||!Q.Vc)return 1;if((G=r5(Number(G>>>0))).startsWith("./")&&(G=G.substring(2)),!(G=Q.Vc.get(G)))return 2;if(U=Number(U>>>0),z=Number(z>>>0),O=Number(O>>>0),U+z>G.byteLength)return 3;try{let A=G.subarray(U,U+z);switch(S){case 0:(C(),r).set(A,O>>>0);break;case 1:Q.bd?Q.bd(O,A):Q.pe(O,A);break;default:return 4}return 0}catch{return 4}},1029540:(G,U,z)=>{Q.Td(G,(C(),r).subarray(U>>>0,U+z>>>0))},1029604:()=>Q.ne(),1029646:(G)=>{Q.kd(G)},1029683:()=>typeof wasmOffsetConverter<"u"};function bF(G,U,z,O){var S=K0();try{return EZ(G,U,z,O)}catch(A){if(X0(S),A!==A+0)throw A;F0(1,0)}}function fF(G,U,z){var O=K0();try{return RZ(G,U,z)}catch(S){if(X0(O),S!==S+0)throw S;F0(1,0)}}function _F(G){var U=K0();try{MZ(G)}catch(z){if(X0(U),z!==z+0)throw z;F0(1,0)}}function gF(G,U){var z=K0();try{return H4(G,U)}catch(O){if(X0(z),O!==O+0)throw O;F0(1,0)}}function cF(G,U,z){var O=K0();try{DZ(G,U,z)}catch(S){if(X0(O),S!==S+0)throw S;F0(1,0)}}function lF(G,U){var z=K0();try{wZ(G,U)}catch(O){if(X0(z),O!==O+0)throw O;F0(1,0)}}function uF(G,U,z,O,S,A,I){var y=K0();try{return CZ(G,U,z,O,S,A,I)}catch(l){if(X0(y),l!==l+0)throw l;F0(1,0)}}function mF(G,U,z,O,S,A){var I=K0();try{SZ(G,U,z,O,S,A)}catch(y){if(X0(I),y!==y+0)throw y;F0(1,0)}}function dF(G,U,z,O){var S=K0();try{PZ(G,U,z,O)}catch(A){if(X0(S),A!==A+0)throw A;F0(1,0)}}function pF(G,U,z,O,S,A,I){var y=K0();try{IZ(G,U,z,O,S,A,I)}catch(l){if(X0(y),l!==l+0)throw l;F0(1,0)}}function iF(G,U,z,O,S,A,I){var y=K0();try{vZ(G,U,z,O,S,A,I)}catch(l){if(X0(y),l!==l+0)throw l;F0(1,0)}}function rF(G,U,z,O,S,A,I,y){var l=K0();try{cZ(G,U,z,O,S,A,I,y)}catch(n){if(X0(l),n!==n+0)throw n;F0(1,0)}}function aF(G,U,z,O,S,A,I,y,l,n,D0,L0){var I0=K0();try{yZ(G,U,z,O,S,A,I,y,l,n,D0,L0)}catch(e){if(X0(I0),e!==e+0)throw e;F0(1,0)}}function oF(G,U,z,O,S){var A=K0();try{return TZ(G,U,z,O,S)}catch(I){if(X0(A),I!==I+0)throw I;F0(1,0)}}function nF(G,U,z,O,S,A){var I=K0();try{lZ(G,U,z,O,S,A)}catch(y){if(X0(I),y!==y+0)throw y;F0(1,0)}}function sF(G,U,z,O,S){var A=K0();try{LZ(G,U,z,O,S)}catch(I){if(X0(A),I!==I+0)throw I;F0(1,0)}}function tF(G,U,z,O,S,A,I,y){var l=K0();try{AZ(G,U,z,O,S,A,I,y)}catch(n){if(X0(l),n!==n+0)throw n;F0(1,0)}}function eF(G){var U=K0();try{return uZ(G)}catch(z){if(X0(U),z!==z+0)throw z;F0(1,0)}}function J1(G,U,z){var O=K0();try{return mZ(G,U,z)}catch(S){if(X0(O),S!==S+0)throw S;F0(1,0)}}function Q1(G,U){var z=K0();try{return JH(G,U)}catch(O){if(X0(z),O!==O+0)throw O;return F0(1,0),0n}}function X1(G){var U=K0();try{return xZ(G)}catch(z){if(X0(U),z!==z+0)throw z;return F0(1,0),0n}}function K1(G,U,z,O){var S=K0();try{return dZ(G,U,z,O)}catch(A){if(X0(S),A!==A+0)throw A;F0(1,0)}}function Z1(G,U,z,O,S){var A=K0();try{return pZ(G,U,z,O,S)}catch(I){if(X0(A),I!==I+0)throw I;F0(1,0)}}function H1(G,U,z,O,S,A){var I=K0();try{return iZ(G,U,z,O,S,A)}catch(y){if(X0(I),y!==y+0)throw y;F0(1,0)}}function Y1(G,U,z,O,S,A){var I=K0();try{return _Z(G,U,z,O,S,A)}catch(y){if(X0(I),y!==y+0)throw y;F0(1,0)}}function $1(G,U,z,O,S,A){var I=K0();try{return rZ(G,U,z,O,S,A)}catch(y){if(X0(I),y!==y+0)throw y;F0(1,0)}}function V1(G,U,z,O,S,A,I,y){var l=K0();try{return gZ(G,U,z,O,S,A,I,y)}catch(n){if(X0(l),n!==n+0)throw n;F0(1,0)}}function W1(G,U,z,O,S){var A=K0();try{return aZ(G,U,z,O,S)}catch(I){if(X0(A),I!==I+0)throw I;return F0(1,0),0n}}function G1(G,U,z,O){var S=K0();try{return oZ(G,U,z,O)}catch(A){if(X0(S),A!==A+0)throw A;F0(1,0)}}function q1(G,U,z,O){var S=K0();try{return nZ(G,U,z,O)}catch(A){if(X0(S),A!==A+0)throw A;F0(1,0)}}function F1(G,U,z,O,S,A,I,y,l,n,D0,L0){var I0=K0();try{return sZ(G,U,z,O,S,A,I,y,l,n,D0,L0)}catch(e){if(X0(I0),e!==e+0)throw e;F0(1,0)}}function U1(G,U,z,O,S,A,I,y,l,n,D0){var L0=K0();try{tZ(G,U,z,O,S,A,I,y,l,n,D0)}catch(I0){if(X0(L0),I0!==I0+0)throw I0;F0(1,0)}}function N1(G,U,z,O,S,A,I,y,l,n,D0,L0,I0,e,o0,N6){var n0=K0();try{eZ(G,U,z,O,S,A,I,y,l,n,D0,L0,I0,e,o0,N6)}catch(w5){if(X0(n0),w5!==w5+0)throw w5;F0(1,0)}}function j1(G,U,z){var O=K0();try{return hZ(G,U,z)}catch(S){if(X0(O),S!==S+0)throw S;return F0(1,0),0n}}function z1(G,U,z){var O=K0();try{return kZ(G,U,z)}catch(S){if(X0(O),S!==S+0)throw S;F0(1,0)}}function O1(G,U,z){var O=K0();try{return bZ(G,U,z)}catch(S){if(X0(O),S!==S+0)throw S;F0(1,0)}}function B1(G,U,z,O){var S=K0();try{fZ(G,U,z,O)}catch(A){if(X0(S),A!==A+0)throw A;F0(1,0)}}function P9(){if(0{let U=new WeakMap,z,O,S=1;Q.webgpuRegisterDevice=(y)=>{if(O!==void 0)throw Error("another WebGPU EP inference session is being created.");if(y){var l=U.get(y);if(!l){let n=((D0,L0=0)=>{var I0=VZ(L0);return L0=$Z(L0,I0),Q6[I0>>>0]=D0.queue,Q6[L0>>>0]=D0,L0})(y,l=eK(0));l=[S++,l,n],U.set(y,l)}return z=y,O=l[0],l}z=void 0,O=0};let A=new Map;Q.webgpuOnCreateSession=(y)=>{if(O!==void 0){var l=O;if(O=void 0,y){let n=o7(l);A.set(y,n),l===0&&G(z??t(n))}z=void 0}},Q.webgpuOnReleaseSession=(y)=>{A.delete(y)};let I=Symbol("gpuBufferMetadata");Q.webgpuRegisterBuffer=(y,l,n)=>{if(n)return y[I]=[n,NaN],n;if(n=y[I])return n[1]++,n[0];if((l=A.get(l))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return l=((D0,L0=0)=>(D0.mapState==="unmapped"||J0(),L0=YZ(L0),Q6[L0>>>0]=D0,L0))(y,l),y[I]=[l,1],l},Q.webgpuUnregisterBuffer=(y)=>{let l=y[I];if(!l)throw Error("Buffer is not registered");l[1]--,l[1]===0&&(tK(l[0]),delete y[I])},Q.webgpuGetBuffer=(y)=>t(y),Q.webgpuCreateDownloader=(y,l,n)=>{if((n=A.get(n))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let D0=t(n),L0=16*Math.ceil(Number(l)/16);return async()=>{let I0=D0.createBuffer({size:L0,usage:9});try{let e=D0.createCommandEncoder();return e.copyBufferToBuffer(y,0,I0,0,L0),D0.queue.submit([e.finish()]),await I0.mapAsync(GPUMapMode.READ),I0.getMappedRange().slice(0,l)}finally{I0.destroy()}}},Q.bd=(y,l)=>{var n=l.buffer;let{byteOffset:D0,byteLength:L0}=l;if(l=16*Math.ceil(Number(L0)/16),y=t(y),!z){var I0=o7(O);z=t(I0)}let e=(I0=z.createBuffer({mappedAtCreation:!0,size:l,usage:6})).getMappedRange();new Uint8Array(e).set(new Uint8Array(n,D0,L0)),I0.unmap(),(n=z.createCommandEncoder()).copyBufferToBuffer(I0,0,y,0,l),z.queue.submit([n.finish()]),I0.destroy()}},Q.webnnInit=(G)=>{let U=G[0];[Q.ne,Q.kd,Q.webnnEnsureTensor,Q.Td,Q.webnnDownloadTensor,Q.me,Q.webnnEnableTraceEvent]=G.slice(1),Q.webnnReleaseTensorId=Q.kd,Q.webnnUploadTensor=Q.Td,Q.webnnRegisterMLContext=Q.me,Q.webnnOnRunStart=(z)=>U.onRunStart(z),Q.webnnOnRunEnd=U.onRunEnd.bind(U),Q.webnnOnReleaseSession=(z)=>{U.onReleaseSession(z)},Q.webnnCreateMLTensorDownloader=(z,O)=>U.createMLTensorDownloader(z,O),Q.webnnRegisterMLTensor=(z,O,S,A)=>U.registerMLTensor(z,O,S,A),Q.webnnCreateMLContext=(z)=>U.createMLContext(z),Q.webnnRegisterMLConstant=(z,O,S,A,I,y)=>U.registerMLConstant(z,O,S,A,I,Q.Vc,y),Q.webnnRegisterGraphInput=U.registerGraphInput.bind(U),Q.webnnIsGraphInput=U.isGraphInput.bind(U),Q.webnnRegisterGraphOutput=U.registerGraphOutput.bind(U),Q.webnnIsGraphOutput=U.isGraphOutput.bind(U),Q.webnnCreateTemporaryTensor=U.createTemporaryTensor.bind(U),Q.webnnIsGraphInputOutputTypeSupported=U.isGraphInputOutputTypeSupported.bind(U)},a?Q:new Promise((G,U)=>{B=G,D=U})}var eH,$H,m1=N0(()=>{eH=YH,$H=globalThis.self?.name?.startsWith("em-pthread"),$H&&YH()}),U4,T4,VH,O6,JY,w9,WH,GH,N4,qH,j4,QY,z4,XY,_4=N0(()=>{f4(),U4=typeof location>"u"?void 0:location.origin,T4=import.meta.url>"file:"&&import.meta.url<"file;",VH=()=>{if(T4)return new URL(new URL("ort.webgpu.bundle.min.mjs",import.meta.url).href,U4).href;return import.meta.url},O6=VH(),JY=()=>{if(O6&&!O6.startsWith("blob:"))return O6.substring(0,O6.lastIndexOf("/")+1)},w9=(J,Q)=>{try{let X=Q??O6;return(X?new URL(J,X):new URL(J)).origin===U4}catch{return!1}},WH=(J,Q)=>{let X=Q??O6;try{return(X?new URL(J,X):new URL(J)).href}catch{return}},GH=(J,Q)=>`${Q??"./"}${J}`,N4=async(J)=>{let Q=await(await fetch(J,{credentials:"same-origin"})).blob();return URL.createObjectURL(Q)},qH=async(J)=>(await import(J)).default,j4=(u1(),x9(nH)).default,QY=async()=>{if(!O6)throw Error("Failed to load proxy worker: cannot determine the script source URL.");if(w9(O6))return[void 0,j4()];let J=await N4(O6);return[J,j4(J)]},z4=(m1(),x9(tH)).default,XY=async(J,Q,X,K)=>{let Z=z4&&!(J||Q);if(Z)if(O6)Z=w9(O6)||K&&!X;else if(K&&!X)Z=!0;else throw Error("cannot determine the script source URL.");if(Z)return[void 0,z4];{let H="ort-wasm-simd-threaded.asyncify.mjs",Y=J??WH(H,Q),$=X&&Y&&!w9(Y,Q),V=$?await N4(Y):Y??GH(H,Q);return[$?V:void 0,await qH(V)]}}}),O4,T9,_8,B4,FH,UH,NH,g4,E0,f5=N0(()=>{_4(),T9=!1,_8=!1,B4=!1,FH=()=>{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}},UH=()=>{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}},NH=()=>{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}},g4=async(J)=>{if(T9)return Promise.resolve();if(_8)throw Error("multiple calls to 'initializeWebAssembly()' detected.");if(B4)throw Error("previous call to 'initializeWebAssembly()' failed.");_8=!0;let{initTimeout:Q,numThreads:X}=J;if(J.simd!==!1){if(J.simd==="relaxed"){if(!NH())throw Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!UH())throw Error("WebAssembly SIMD is not supported in the current environment.")}let K=FH();X>1&&!K&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+X+", 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."),J.numThreads=X=1);let Z=J.wasmPaths,H=typeof Z=="string"?Z:void 0,Y=Z?.mjs,$=Y?.href??Y,V=Z?.wasm,W=V?.href??V,q=J.wasmBinary,[F,N]=await XY($,H,X>1,!!q||!!W),j=!1,B=[];if(Q>0&&B.push(new Promise((D)=>{setTimeout(()=>{j=!0,D()},Q)})),B.push(new Promise((D,L)=>{let M={numThreads:X};if(q)M.wasmBinary=q,M.locateFile=(R)=>R;else if(W||H)M.locateFile=(R)=>W??H+R;else if($&&$.indexOf("blob:")!==0)M.locateFile=(R)=>new URL(R,$).href;else if(F){let R=JY();R&&(M.locateFile=(E)=>R+E)}N(M).then((R)=>{_8=!1,T9=!0,O4=R,D(),F&&URL.revokeObjectURL(F)},(R)=>{_8=!1,B4=!0,L(R)})})),await Promise.race(B),j)throw Error(`WebAssembly backend initializing failed due to timeout: ${Q}ms`)},E0=()=>{if(T9&&O4)return O4;throw Error("WebAssembly is not initialized yet.")}}),B6,h9,S0,c4=N0(()=>{f5(),B6=(J,Q)=>{let X=E0(),K=X.lengthBytesUTF8(J)+1,Z=X._malloc(K);return X.stringToUTF8(J,Z,K),Q.push(Z),Z},h9=(J,Q,X,K)=>{if(typeof J=="object"&&J!==null){if(X.has(J))throw Error("Circular reference in options");X.add(J)}Object.entries(J).forEach(([Z,H])=>{let Y=Q?Q+Z:Z;if(typeof H=="object")h9(H,Y+".",X,K);else if(typeof H=="string"||typeof H=="number")K(Y,H.toString());else if(typeof H=="boolean")K(Y,H?"1":"0");else throw Error(`Can't handle extra config type: ${typeof H}`)})},S0=(J)=>{let Q=E0(),X=Q.stackSave();try{let K=Q.PTR_SIZE,Z=Q.stackAlloc(2*K);Q._OrtGetLastError(Z,Z+K);let H=Number(Q.getValue(Z,K===4?"i32":"i64")),Y=Q.getValue(Z+K,"*"),$=Y?Q.UTF8ToString(Y):"";throw Error(`${J} ERROR_CODE: ${H}, ERROR_MESSAGE: ${$}`)}finally{Q.stackRestore(X)}}}),KY,d1=N0(()=>{f5(),c4(),KY=(J)=>{let Q=E0(),X=0,K=[],Z=J||{};try{if(J?.logSeverityLevel===void 0)Z.logSeverityLevel=2;else if(typeof J.logSeverityLevel!="number"||!Number.isInteger(J.logSeverityLevel)||J.logSeverityLevel<0||J.logSeverityLevel>4)throw Error(`log severity level is not valid: ${J.logSeverityLevel}`);if(J?.logVerbosityLevel===void 0)Z.logVerbosityLevel=0;else if(typeof J.logVerbosityLevel!="number"||!Number.isInteger(J.logVerbosityLevel))throw Error(`log verbosity level is not valid: ${J.logVerbosityLevel}`);J?.terminate===void 0&&(Z.terminate=!1);let H=0;return J?.tag!==void 0&&(H=B6(J.tag,K)),X=Q._OrtCreateRunOptions(Z.logSeverityLevel,Z.logVerbosityLevel,!!Z.terminate,H),X===0&&S0("Can't create run options."),J?.extra!==void 0&&h9(J.extra,"",new WeakSet,(Y,$)=>{let V=B6(Y,K),W=B6($,K);Q._OrtAddRunConfigEntry(X,V,W)!==0&&S0(`Can't set a run config entry: ${Y} - ${$}.`)}),[X,K]}catch(H){throw X!==0&&Q._OrtReleaseRunOptions(X),K.forEach((Y)=>Q._free(Y)),H}}}),jH,zH,OH,s5,z5,BH,ZY,p1=N0(()=>{f5(),c4(),jH=(J)=>{switch(J){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw Error(`unsupported graph optimization level: ${J}`)}},zH=(J)=>{switch(J){case"sequential":return 0;case"parallel":return 1;default:throw Error(`unsupported execution mode: ${J}`)}},OH=(J)=>{J.extra||(J.extra={}),J.extra.session||(J.extra.session={});let Q=J.extra.session;Q.use_ort_model_bytes_directly||(Q.use_ort_model_bytes_directly="1"),J.executionProviders&&J.executionProviders.some((X)=>(typeof X=="string"?X:X.name)==="webgpu")&&(J.enableMemPattern=!1)},s5=(J,Q,X,K)=>{let Z=B6(Q,K),H=B6(X,K);E0()._OrtAddSessionConfigEntry(J,Z,H)!==0&&S0(`Can't set a session config entry: ${Q} - ${X}.`)},z5=(J,Q,X,K)=>{let Z=B6(Q,K),H=B6(X,K);J.push([Z,H])},BH=async(J,Q,X)=>{let K=Q.executionProviders;for(let Z of K){let H=typeof Z=="string"?Z:Z.name,Y=[];switch(H){case"webnn":if(H="WEBNN",s5(J,"session.disable_quant_qdq","1",X),s5(J,"session.disable_qdq_constant_folding","1",X),typeof Z!="string"){let F=Z?.deviceType;F&&s5(J,"deviceType",F,X)}break;case"webgpu":{H="WebGPU";let F;if(typeof Z!="string"){let j=Z;if(j.device)if(typeof GPUDevice<"u"&&j.device instanceof GPUDevice)F=j.device;else throw Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:B}=Q;if(typeof B=="boolean"&&B&&z5(Y,"enableGraphCapture","1",X),typeof j.preferredLayout=="string"&&z5(Y,"preferredLayout",j.preferredLayout,X),j.forceCpuNodeNames){let D=Array.isArray(j.forceCpuNodeNames)?j.forceCpuNodeNames:[j.forceCpuNodeNames];z5(Y,"forceCpuNodeNames",D.join(` `),X)}j.validationMode&&z5(Y,"validationMode",j.validationMode,X)}let N=E0().webgpuRegisterDevice(F);if(N){let[j,B,D]=N;z5(Y,"deviceId",j.toString(),X),z5(Y,"webgpuInstance",B.toString(),X),z5(Y,"webgpuDevice",D.toString(),X)}}break;case"wasm":case"cpu":continue;default:throw Error(`not supported execution provider: ${H}`)}let $=B6(H,X),V=Y.length,W=0,q=0;if(V>0){W=E0()._malloc(V*E0().PTR_SIZE),X.push(W),q=E0()._malloc(V*E0().PTR_SIZE),X.push(q);for(let F=0;F{let Q=E0(),X=0,K=[],Z=J||{};OH(Z);try{let H=jH(Z.graphOptimizationLevel??"all"),Y=zH(Z.executionMode??"sequential"),$=typeof Z.logId=="string"?B6(Z.logId,K):0,V=Z.logSeverityLevel??2;if(!Number.isInteger(V)||V<0||V>4)throw Error(`log severity level is not valid: ${V}`);let W=Z.logVerbosityLevel??0;if(!Number.isInteger(W)||W<0||W>4)throw Error(`log verbosity level is not valid: ${W}`);let q=typeof Z.optimizedModelFilePath=="string"?B6(Z.optimizedModelFilePath,K):0;if(X=Q._OrtCreateSessionOptions(H,!!Z.enableCpuMemArena,!!Z.enableMemPattern,Y,!!Z.enableProfiling,0,$,V,W,q),X===0&&S0("Can't create session options."),Z.executionProviders&&await BH(X,Z,K),Z.enableGraphCapture!==void 0){if(typeof Z.enableGraphCapture!="boolean")throw Error(`enableGraphCapture must be a boolean value: ${Z.enableGraphCapture}`);s5(X,"enableGraphCapture",Z.enableGraphCapture.toString(),K)}if(Z.freeDimensionOverrides)for(let[F,N]of Object.entries(Z.freeDimensionOverrides)){if(typeof F!="string")throw Error(`free dimension override name must be a string: ${F}`);if(typeof N!="number"||!Number.isInteger(N)||N<0)throw Error(`free dimension override value must be a non-negative integer: ${N}`);let j=B6(F,K);Q._OrtAddFreeDimensionOverride(X,j,N)!==0&&S0(`Can't set a free dimension override: ${F} - ${N}.`)}return Z.extra!==void 0&&h9(Z.extra,"",new WeakSet,(F,N)=>{s5(X,F,N,K)}),[X,K]}catch(H){throw X!==0&&Q._OrtReleaseSessionOptions(X)!==0&&S0("Can't release session options."),K.forEach((Y)=>Q._free(Y)),H}}}),y5,y9,e5,m8,b9,l4,u4,I4,J8=N0(()=>{y5=(J)=>{switch(J){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 Error(`unsupported data type: ${J}`)}},y9=(J)=>{switch(J){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 Error(`unsupported data type: ${J}`)}},e5=(J,Q)=>{let X=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,0.5,0.5][J],K=typeof Q=="number"?Q:Q.reduce((Z,H)=>Z*H,1);return X>0?Math.ceil(K*X):void 0},m8=(J)=>{switch(J){case"float16":return typeof Float16Array<"u"?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 Error(`unsupported type: ${J}`)}},b9=(J)=>{switch(J){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw Error(`unsupported logging level: ${J}`)}},l4=(J)=>J==="float32"||J==="float16"||J==="int32"||J==="int64"||J==="uint32"||J==="uint8"||J==="bool"||J==="uint4"||J==="int4",u4=(J)=>J==="float32"||J==="float16"||J==="int32"||J==="int64"||J==="uint32"||J==="uint64"||J==="int8"||J==="uint8"||J==="bool"||J==="uint4"||J==="int4",I4=(J)=>{switch(J){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 Error(`unsupported data location: ${J}`)}}}),m4,HY=N0(()=>{f4(),m4=async(J)=>{if(typeof J=="string"){let Q=await fetch(J);if(!Q.ok)throw Error(`failed to load external data file: ${J}`);let X=Q.headers.get("Content-Length"),K=X?parseInt(X,10):0;if(K<1073741824)return new Uint8Array(await Q.arrayBuffer());{if(!Q.body)throw Error(`failed to load external data file: ${J}, no response body.`);let Z=Q.body.getReader(),H;try{H=new ArrayBuffer(K)}catch($){if($ instanceof RangeError){let V=Math.ceil(K/65536);H=new WebAssembly.Memory({initial:V,maximum:V}).buffer}else throw $}let Y=0;for(;;){let{done:$,value:V}=await Z.read();if($)break;let W=V.byteLength;new Uint8Array(H,Y,W).set(V),Y+=W}return new Uint8Array(H,0,K)}}else return J instanceof Blob?new Uint8Array(await J.arrayBuffer()):J instanceof Uint8Array?J:new Uint8Array(J)}}),YY,i1=N0(()=>{J8(),YY=(J,Q)=>new(m8(Q))(J)}),DH,MH,SH,LH,$Y,CH,H6,VY=N0(()=>{J8(),DH=["V","I","W","E","F"],MH=(J,Q)=>{console.log(`[${DH[J]},${new Date().toISOString()}]${Q}`)},$Y=(J,Q)=>{SH=J,LH=Q},CH=(J,Q)=>{let X=b9(J),K=b9(SH);X>=K&&MH(X,typeof Q=="function"?Q():Q)},H6=(...J)=>{LH&&CH(...J)}}),D4,v4,M4,RH,S4,AH,L4,C4,R4,PH,WY,r1=N0(()=>{J8(),VY(),D4=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),v4=(J,Q)=>{if(Q==="int32")return J;let X=D4.get(Q);if(!X)throw Error(`WebNN backend does not support data type: ${Q}`);let K=X/8;if(J.byteLength%K!==0)throw Error(`Invalid Uint8Array length - must be a multiple of ${K}.`);let Z=J.byteLength/K,H=new(m8(Q))(J.buffer,J.byteOffset,Z);switch(Q){case"int64":case"uint64":{let Y=new Int32Array(Z);for(let $=0;$2147483647n||V<-2147483648n)throw Error("Can not convert int64 data to int32 - value out of range.");Y[$]=Number(V)}return new Uint8Array(Y.buffer)}case"int8":case"uint8":case"uint32":{if(Q==="uint32"&&H.some(($)=>$>2147483647))throw Error("Can not convert uint32 data to int32 - value out of range.");let Y=Int32Array.from(H,Number);return new Uint8Array(Y.buffer)}default:throw Error(`Unsupported data conversion from ${Q} to 'int32'`)}},M4=(J,Q)=>{if(Q==="int32")return J;if(J.byteLength%4!==0)throw Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let X=J.byteLength/4,K=new Int32Array(J.buffer,J.byteOffset,X);switch(Q){case"int64":{let Z=BigInt64Array.from(K,BigInt);return new Uint8Array(Z.buffer)}case"uint64":{if(K.some((H)=>H<0))throw Error("Can not convert int32 data to uin64 - negative value found.");let Z=BigUint64Array.from(K,BigInt);return new Uint8Array(Z.buffer)}case"int8":{if(K.some((H)=>H<-128||H>127))throw Error("Can not convert int32 data to int8 - value out of range.");let Z=Int8Array.from(K,Number);return new Uint8Array(Z.buffer)}case"uint8":{if(K.some((Z)=>Z<0||Z>255))throw Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(K,Number)}case"uint32":{if(K.some((H)=>H<0))throw Error("Can not convert int32 data to uint32 - negative value found.");let Z=Uint32Array.from(K,Number);return new Uint8Array(Z.buffer)}default:throw Error(`Unsupported data conversion from 'int32' to ${Q}`)}},RH=1,S4=()=>RH++,AH=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),L4=(J,Q)=>{let X=D4.get(J);if(!X)throw Error(`WebNN backend does not support data type: ${J}`);return Q.length>0?Math.ceil(Q.reduce((K,Z)=>K*Z)*X/8):0},C4=class{constructor(J){this.isDataConverted=!1;let{sessionId:Q,context:X,tensor:K,dataType:Z,shape:H,fallbackDataType:Y}=J;this.sessionId=Q,this.mlContext=X,this.mlTensor=K,this.dataType=Z,this.tensorShape=H,this.fallbackDataType=Y}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return L4(this.dataType,this.tensorShape)}destroy(){H6("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(J){this.mlContext.writeTensor(this.mlTensor,J)}async read(J){if(this.fallbackDataType){let Q=await this.mlContext.readTensor(this.mlTensor),X=M4(new Uint8Array(Q),this.dataType);if(J){(J instanceof ArrayBuffer?new Uint8Array(J):new Uint8Array(J.buffer,J.byteOffset,J.byteLength)).set(X);return}else return new Uint8Array(X).buffer}else return J?this.mlContext.readTensor(this.mlTensor,J):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(J,Q,X){return this.mlContext===J&&this.dataType===Q&&this.tensorShape.length===X.length&&this.tensorShape.every((K,Z)=>K===X[Z])}setIsDataConverted(J){this.isDataConverted=J}},R4=class{constructor(J,Q){this.tensorManager=J,this.wrapper=Q}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(J,Q,X,K){let Z=this.tensorManager.getMLContext(J),H=this.tensorManager.getMLOpSupportLimits(J),Y;if(!H?.input.dataTypes.includes(Q)){if(Y=AH.get(Q),!Y||H?.input.dataTypes.includes(Y))throw Error(`WebNN backend does not support data type: ${Q}`);H6("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${Q} to ${Y}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(Z,Q,X))return this.wrapper.tensor;if(K){if(this.wrapper.byteLength!==L4(Q,X))throw Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let $=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(J,Q,X,$,!0,!0,Y),K&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(J){let Q=J;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")Q=v4(J,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(J.byteLength===this.wrapper.byteLength){this.wrapper.write(Q);return}else H6("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(Q):this.activeUpload=new Uint8Array(Q)}async download(J){if(this.activeUpload){let Q=this.wrapper?.isDataConverted?M4(this.activeUpload,this.wrapper?.type):this.activeUpload;if(J){J instanceof ArrayBuffer?new Uint8Array(J).set(Q):new Uint8Array(J.buffer,J.byteOffset,J.byteLength).set(Q);return}else return Q.buffer}if(!this.wrapper)throw Error("Tensor has not been created.");return J?this.wrapper.read(J):this.wrapper.read()}},PH=class{constructor(J){this.backend=J,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(J){let Q=this.backend.getMLContext(J);if(!Q)throw Error("MLContext not found for session.");return Q}getMLOpSupportLimits(J){return this.backend.getMLOpSupportLimits(J)}reserveTensorId(){let J=S4();return this.tensorTrackersById.set(J,new R4(this)),J}releaseTensorId(J){let Q=this.tensorTrackersById.get(J);Q&&(this.tensorTrackersById.delete(J),Q.tensorWrapper&&this.releaseTensor(Q.tensorWrapper))}async ensureTensor(J,Q,X,K,Z){H6("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${Q}, dataType: ${X}, shape: ${K}, copyOld: ${Z}}`);let H=this.tensorTrackersById.get(Q);if(!H)throw Error("Tensor not found.");return H.ensureTensor(J,X,K,Z)}upload(J,Q){let X=this.tensorTrackersById.get(J);if(!X)throw Error("Tensor not found.");X.upload(Q)}async download(J,Q){H6("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${J}, dstBuffer: ${Q?.byteLength}}`);let X=this.tensorTrackersById.get(J);if(!X)throw Error("Tensor not found.");return X.download(Q)}releaseTensorsForSession(J){for(let Q of this.freeTensors)Q.sessionId===J&&Q.destroy();this.freeTensors=this.freeTensors.filter((Q)=>Q.sessionId!==J)}registerTensor(J,Q,X,K){let Z=this.getMLContext(J),H=S4(),Y=new C4({sessionId:J,context:Z,tensor:Q,dataType:X,shape:K});return this.tensorTrackersById.set(H,new R4(this,Y)),this.externalTensors.add(Y),H}async getCachedTensor(J,Q,X,K,Z,H,Y){let $=this.getMLContext(J);for(let[W,q]of this.freeTensors.entries())if(q.canReuseTensor($,Q,X)){H6("verbose",()=>`[WebNN] Reusing tensor {dataType: ${Q}, ${Y?`fallbackDataType: ${Y},`:""} shape: ${X}`);let F=this.freeTensors.splice(W,1)[0];return F.sessionId=J,F}H6("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${Q}, ${Y?`fallbackDataType: ${Y},`:""} shape: ${X}}`);let V=await $.createTensor({dataType:Y??Q,shape:X,dimensions:X,usage:K,writable:Z,readable:H});return new C4({sessionId:J,context:$,tensor:V,dataType:Q,shape:X,fallbackDataType:Y})}releaseTensor(J){this.externalTensors.has(J)&&this.externalTensors.delete(J),this.freeTensors.push(J)}},WY=(...J)=>new PH(...J)}),GY={};d8(GY,{WebNNBackend:()=>qY});var g8,EH,qY,a1=N0(()=>{J8(),f5(),i1(),r1(),VY(),g8=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),EH=(J,Q)=>{if(J===Q)return!0;if(J===void 0||Q===void 0)return!1;let X=Object.keys(J).sort(),K=Object.keys(Q).sort();return X.length===K.length&&X.every((Z,H)=>Z===K[H]&&J[Z]===Q[Z])},qY=class{constructor(J){this.tensorManager=WY(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,$Y(J.logLevel,!!J.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw Error("No active session");return this.activeSessionId}onRunStart(J){H6("verbose",()=>`[WebNN] onRunStart {sessionId: ${J}}`),this.activeSessionId=J}onRunEnd(J){H6("verbose",()=>`[WebNN] onRunEnd {sessionId: ${J}}`);let Q=this.temporarySessionTensorIds.get(J);if(Q){for(let X of Q)H6("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${X}}`),this.tensorManager.releaseTensorId(X);this.temporarySessionTensorIds.delete(J),this.activeSessionId=void 0}}async createMLContext(J){if(J instanceof GPUDevice){let X=this.mlContextCache.findIndex((K)=>K.gpuDevice===J);if(X!==-1)return this.mlContextCache[X].mlContext;{let K=await navigator.ml.createContext(J);return this.mlContextCache.push({gpuDevice:J,mlContext:K}),K}}else if(J===void 0){let X=this.mlContextCache.findIndex((K)=>K.options===void 0&&K.gpuDevice===void 0);if(X!==-1)return this.mlContextCache[X].mlContext;{let K=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:K}),K}}let Q=this.mlContextCache.findIndex((X)=>EH(X.options,J));if(Q!==-1)return this.mlContextCache[Q].mlContext;{let X=await navigator.ml.createContext(J);return this.mlContextCache.push({options:J,mlContext:X}),X}}registerMLContext(J,Q){this.mlContextBySessionId.set(J,Q);let X=this.sessionIdsByMLContext.get(Q);X||(X=new Set,this.sessionIdsByMLContext.set(Q,X)),X.add(J),this.mlOpSupportLimitsBySessionId.has(J)||this.mlOpSupportLimitsBySessionId.set(J,Q.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(J,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(J,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(J){this.sessionGraphInputs.delete(J),this.sessionGraphOutputs.delete(J);let Q=this.mlContextBySessionId.get(J);if(!Q)return;this.tensorManager.releaseTensorsForSession(J),this.mlContextBySessionId.delete(J),this.mlOpSupportLimitsBySessionId.delete(J);let X=this.sessionIdsByMLContext.get(Q);if(X.delete(J),X.size===0){this.sessionIdsByMLContext.delete(Q);let K=this.mlContextCache.findIndex((Z)=>Z.mlContext===Q);K!==-1&&this.mlContextCache.splice(K,1)}}getMLContext(J){return this.mlContextBySessionId.get(J)}getMLOpSupportLimits(J){return this.mlOpSupportLimitsBySessionId.get(J)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(J){H6("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${J}}`),this.tensorManager.releaseTensorId(J)}async ensureTensor(J,Q,X,K,Z){let H=g8.get(X);if(!H)throw Error(`Unsupported ONNX data type: ${X}`);return this.tensorManager.ensureTensor(J??this.currentSessionId,Q,H,K,Z)}async createTemporaryTensor(J,Q,X){H6("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${Q}, shape: ${X}}`);let K=g8.get(Q);if(!K)throw Error(`Unsupported ONNX data type: ${Q}`);let Z=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(J,Z,K,X,!1);let H=this.temporarySessionTensorIds.get(J);return H?H.push(Z):this.temporarySessionTensorIds.set(J,[Z]),Z}uploadTensor(J,Q){if(!E0().shouldTransferToMLTensor)throw Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");H6("verbose",()=>`[WebNN] uploadTensor {tensorId: ${J}, data: ${Q.byteLength}}`),this.tensorManager.upload(J,Q)}async downloadTensor(J,Q){return this.tensorManager.download(J,Q)}createMLTensorDownloader(J,Q){return async()=>{let X=await this.tensorManager.download(J);return YY(X,Q)}}registerMLTensor(J,Q,X,K){let Z=g8.get(X);if(!Z)throw Error(`Unsupported ONNX data type: ${X}`);let H=this.tensorManager.registerTensor(J,Q,Z,K);return H6("verbose",()=>`[WebNN] registerMLTensor {tensor: ${Q}, dataType: ${Z}, dimensions: ${K}} -> {tensorId: ${H}}`),H}registerMLConstant(J,Q,X,K,Z,H,Y=!1){if(!H)throw Error("External mounted files are not available.");let $=J;J.startsWith("./")&&($=J.substring(2));let V=H.get($);if(!V)throw Error(`File with name ${$} not found in preloaded files.`);if(Q+X>V.byteLength)throw Error("Out of bounds: data offset and length exceed the external file data size.");let W=V.slice(Q,Q+X).buffer,q;switch(Z.dataType){case"float32":q=new Float32Array(W);break;case"float16":q=typeof Float16Array<"u"?new Float16Array(W):new Uint16Array(W);break;case"int32":q=new Int32Array(W);break;case"uint32":q=new Uint32Array(W);break;case"int64":if(Y){let F=v4(new Uint8Array(W),"int64");q=new Int32Array(F.buffer),Z.dataType="int32"}else q=new BigInt64Array(W);break;case"uint64":q=new BigUint64Array(W);break;case"int8":q=new Int8Array(W);break;case"int4":case"uint4":case"uint8":q=new Uint8Array(W);break;default:throw Error(`Unsupported data type: ${Z.dataType} in creating WebNN Constant from external data.`)}return H6("verbose",()=>`[WebNN] registerMLConstant {dataType: ${Z.dataType}, shape: ${Z.shape}}} ${Y?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),K.constant(Z,q)}registerGraphInput(J){this.temporaryGraphInputs.push(J)}registerGraphOutput(J){this.temporaryGraphOutputs.push(J)}isGraphInput(J,Q){let X=this.sessionGraphInputs.get(J);return X?X.includes(Q):!1}isGraphOutput(J,Q){let X=this.sessionGraphOutputs.get(J);return X?X.includes(Q):!1}isGraphInputOutputTypeSupported(J,Q,X=!0){let K=g8.get(y5(Q)),Z=this.mlOpSupportLimitsBySessionId.get(J);return typeof K>"u"?!1:X?!!Z?.input.dataTypes.includes(K):!!Z?.output.dataTypes.includes(K)}flush(){}}}),wH,d4,p4,O5,TH,A4,f9,i4,r4,P4,a4,o4,n4,FY=N0(()=>{b5(),d1(),p1(),J8(),f5(),c4(),HY(),wH=(J,Q)=>{E0()._OrtInit(J,Q)!==0&&S0("Can't initialize onnxruntime.")},d4=async(J)=>{wH(J.wasm.numThreads,b9(J.logLevel))},p4=async(J,Q)=>{E0().asyncInit?.();let X=J.webgpu.adapter;if(Q==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw Error("WebGPU is not supported in current environment");if(X){if(typeof X.limits!="object"||typeof X.features!="object"||typeof X.requestDevice!="function")throw Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let K=J.webgpu.powerPreference;if(K!==void 0&&K!=="low-power"&&K!=="high-performance")throw Error(`Invalid powerPreference setting: "${K}"`);let Z=J.webgpu.forceFallbackAdapter;if(Z!==void 0&&typeof Z!="boolean")throw Error(`Invalid forceFallbackAdapter setting: "${Z}"`);if(X=await navigator.gpu.requestAdapter({powerPreference:K,forceFallbackAdapter:Z}),!X)throw Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(Q==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw Error("WebNN is not supported in current environment");if(Q==="webgpu"&&E0().webgpuInit((K)=>{J.webgpu.device=K}),Q==="webnn"){let K=new(a1(),x9(GY)).WebNNBackend(J);E0().webnnInit([K,()=>K.reserveTensorId(),(Z)=>K.releaseTensorId(Z),async(Z,H,Y,$,V)=>K.ensureTensor(Z,H,Y,$,V),(Z,H)=>{K.uploadTensor(Z,H)},async(Z,H)=>K.downloadTensor(Z,H),(Z,H)=>K.registerMLContext(Z,H),!!J.trace])}},O5=new Map,TH=(J)=>{let Q=E0(),X=Q.stackSave();try{let K=Q.PTR_SIZE,Z=Q.stackAlloc(2*K);Q._OrtGetInputOutputCount(J,Z,Z+K)!==0&&S0("Can't get session input/output count.");let H=K===4?"i32":"i64";return[Number(Q.getValue(Z,H)),Number(Q.getValue(Z+K,H))]}finally{Q.stackRestore(X)}},A4=(J,Q)=>{let X=E0(),K=X.stackSave(),Z=0;try{let H=X.PTR_SIZE,Y=X.stackAlloc(2*H);X._OrtGetInputOutputMetadata(J,Q,Y,Y+H)!==0&&S0("Can't get session input/output metadata.");let $=Number(X.getValue(Y,"*"));Z=Number(X.getValue(Y+H,"*"));let V=X.HEAP32[Z/4];if(V===0)return[$,0];let W=X.HEAPU32[Z/4+1],q=[];for(let F=0;F{let Q=E0(),X=Q._malloc(J.byteLength);if(X===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${J.byteLength}.`);return Q.HEAPU8.set(J,X),[X,J.byteLength]},i4=async(J,Q)=>{let X,K,Z=E0();Array.isArray(J)?[X,K]=J:J.buffer===Z.HEAPU8.buffer?[X,K]=[J.byteOffset,J.byteLength]:[X,K]=f9(J);let H=0,Y=0,$=0,V=[],W=[],q=[];try{if([Y,V]=await ZY(Q),Q?.externalData&&Z.mountExternalData){let P=[];for(let w of Q.externalData){let k=typeof w=="string"?w:w.path;P.push(m4(typeof w=="string"?w:w.data).then((C)=>{Z.mountExternalData(k,C)}))}await Promise.all(P)}for(let P of Q?.executionProviders??[])if((typeof P=="string"?P:P.name)==="webnn"){if(Z.shouldTransferToMLTensor=!1,typeof P!="string"){let w=P,k=w?.context,C=w?.gpuDevice,c=w?.deviceType,g=w?.powerPreference;k?Z.currentContext=k:C?Z.currentContext=await Z.webnnCreateMLContext(C):Z.currentContext=await Z.webnnCreateMLContext({deviceType:c,powerPreference:g})}else Z.currentContext=await Z.webnnCreateMLContext();break}H=await Z._OrtCreateSession(X,K,Y),Z.webgpuOnCreateSession?.(H),H===0&&S0("Can't create a session."),Z.jsepOnCreateSession?.(),Z.currentContext&&(Z.webnnRegisterMLContext(H,Z.currentContext),Z.currentContext=void 0,Z.shouldTransferToMLTensor=!0);let[F,N]=TH(H),j=!!Q?.enableGraphCapture,B=[],D=[],L=[],M=[],R=[];for(let P=0;PP==="gpu-buffer"||P==="ml-tensor"||P==="ml-tensor-cpu-output")&&($=Z._OrtCreateBinding(H),$===0&&S0("Can't create IO binding."),E={handle:$,outputPreferredLocations:R,outputPreferredLocationsEncoded:R.map((P)=>P==="ml-tensor-cpu-output"?"ml-tensor":P).map((P)=>I4(P))}),O5.set(H,[H,W,q,E,j,!1]),[H,B,D,L,M]}catch(F){throw W.forEach((N)=>Z._OrtFree(N)),q.forEach((N)=>Z._OrtFree(N)),$!==0&&Z._OrtReleaseBinding($)!==0&&S0("Can't release IO binding."),H!==0&&Z._OrtReleaseSession(H)!==0&&S0("Can't release session."),F}finally{Z._free(X),Y!==0&&Z._OrtReleaseSessionOptions(Y)!==0&&S0("Can't release session options."),V.forEach((F)=>Z._free(F)),Z.unmountExternalData?.()}},r4=(J)=>{let Q=E0(),X=O5.get(J);if(!X)throw Error(`cannot release session. invalid session id: ${J}`);let[K,Z,H,Y,$]=X;Y&&($&&Q._OrtClearBoundOutputs(Y.handle)!==0&&S0("Can't clear bound outputs."),Q._OrtReleaseBinding(Y.handle)!==0&&S0("Can't release IO binding.")),Q.jsepOnReleaseSession?.(J),Q.webnnOnReleaseSession?.(J),Q.webgpuOnReleaseSession?.(J),Z.forEach((V)=>Q._OrtFree(V)),H.forEach((V)=>Q._OrtFree(V)),Q._OrtReleaseSession(K)!==0&&S0("Can't release session."),O5.delete(J)},P4=async(J,Q,X,K,Z,H,Y=!1)=>{if(!J){Q.push(0);return}let $=E0(),V=$.PTR_SIZE,W=J[0],q=J[1],F=J[3],N=F,j,B;if(W==="string"&&(F==="gpu-buffer"||F==="ml-tensor"))throw Error("String tensor is not supported on GPU.");if(Y&&F!=="gpu-buffer")throw Error(`External buffer must be provided for input/output index ${H} when enableGraphCapture is true.`);if(F==="gpu-buffer"){let M=J[2].gpuBuffer;B=e5(y5(W),q);{let R=$.webgpuRegisterBuffer;if(!R)throw Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');j=R(M,K)}}else if(F==="ml-tensor"){let M=J[2].mlTensor;B=e5(y5(W),q);let R=$.webnnRegisterMLTensor;if(!R)throw Error('Tensor location "ml-tensor" is not supported without using WebNN.');j=R(K,M,y5(W),q)}else{let M=J[2];if(Array.isArray(M)){B=V*M.length,j=$._malloc(B),X.push(j);for(let R=0;R$.setValue(L+E*V,R,V===4?"i32":"i64"));let M=$._OrtCreateTensor(y5(W),j,B,L,q.length,I4(N));M===0&&S0(`Can't create tensor for input/output. session=${K}, index=${H}.`),Q.push(M)}finally{$.stackRestore(D)}},a4=async(J,Q,X,K,Z,H)=>{let Y=E0(),$=Y.PTR_SIZE,V=O5.get(J);if(!V)throw Error(`cannot run inference. invalid session id: ${J}`);let W=V[0],q=V[1],F=V[2],N=V[3],j=V[4],B=V[5],D=Q.length,L=K.length,M=0,R=[],E=[],P=[],w=[],k=[],C=Y.stackSave(),c=Y.stackAlloc(D*$),g=Y.stackAlloc(D*$),d=Y.stackAlloc(L*$),r=Y.stackAlloc(L*$);try{[M,R]=KY(H),D5("wasm prepareInputOutputTensor");for(let v=0;vT0*B0,1);_=y9(v0);let F6=N?.outputPreferredLocations[K[v]];if(_==="string"){if(F6==="gpu-buffer"||F6==="ml-tensor")throw Error("String tensor is not supported on GPU.");let T0=[];for(let B0=0;B00){let T0=Y.webgpuGetBuffer;if(!T0)throw Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let B0=T0(a),d0=e5(v0,l0);if(d0===void 0||!l4(_))throw Error(`Unsupported data type: ${_}`);h=!0;{Y.webgpuRegisterBuffer(B0,J,a);let l6=Y.webgpuCreateDownloader(B0,d0,J);p.push([_,y0,{gpuBuffer:B0,download:async()=>{let M0=await l6();return new(m8(_))(M0)},dispose:()=>{Y._OrtReleaseTensor(o)!==0&&S0("Can't release tensor.")}},"gpu-buffer"])}}else if(F6==="ml-tensor"&&l0>0){let{webnnEnsureTensor:T0,webnnIsGraphInputOutputTypeSupported:B0}=Y;if(!T0||!B0)throw Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(e5(v0,l0)===void 0||!u4(_))throw Error(`Unsupported data type: ${_}`);if(!B0(J,_,!1))throw Error(`preferredLocation "ml-tensor" for ${_} output is not supported by current WebNN Context.`);let d0=await T0(J,a,v0,y0,!1);h=!0,p.push([_,y0,{mlTensor:d0,download:Y.webnnCreateMLTensorDownloader(a,_),dispose:()=>{Y.webnnReleaseTensorId(a),Y._OrtReleaseTensor(o)}},"ml-tensor"])}else if(F6==="ml-tensor-cpu-output"&&l0>0){let T0=Y.webnnCreateMLTensorDownloader(a,_)(),B0=p.length;h=!0,f.push((async()=>{let d0=[B0,await T0];return Y.webnnReleaseTensorId(a),Y._OrtReleaseTensor(o),d0})()),p.push([_,y0,[],"cpu"])}else{let T0=m8(_),B0=new T0(l0);new Uint8Array(B0.buffer,B0.byteOffset,B0.byteLength).set(Y.HEAPU8.subarray(a,a+B0.byteLength)),p.push([_,y0,B0,"cpu"])}}finally{Y.stackRestore(Q0),_==="string"&&a&&Y._free(a),h||Y._OrtReleaseTensor(o)}}N&&!j&&(Y._OrtClearBoundOutputs(N.handle)!==0&&S0("Can't clear bound outputs."),O5.set(J,[W,q,F,N,j,!1]));for(let[v,o]of await Promise.all(f))p[v][2]=o;return M5("wasm ProcessOutputTensor"),p}finally{Y.webnnOnRunEnd?.(W),Y.stackRestore(C),X.forEach((i)=>{i&&i[3]==="gpu-buffer"&&Y.webgpuUnregisterBuffer(i[2].gpuBuffer)}),Z.forEach((i)=>{i&&i[3]==="gpu-buffer"&&Y.webgpuUnregisterBuffer(i[2].gpuBuffer)}),E.forEach((i)=>Y._OrtReleaseTensor(i)),P.forEach((i)=>Y._OrtReleaseTensor(i)),w.forEach((i)=>Y._free(i)),M!==0&&Y._OrtReleaseRunOptions(M),R.forEach((i)=>Y._free(i))}},o4=(J)=>{let Q=E0(),X=O5.get(J);if(!X)throw Error("invalid session id");let K=X[0],Z=Q._OrtEndProfiling(K);Z===0&&S0("Can't get an profile file name."),Q._OrtFree(Z)},n4=(J)=>{let Q=[];for(let X of J){let K=X[2];!Array.isArray(K)&&"buffer"in K&&Q.push(K.buffer)}return Q}}),B5,R6,t5,c8,l8,I9,E4,v9,T5,I5,IH,UY,NY,jY,zY,OY,BY,DY,MY=N0(()=>{b5(),FY(),f5(),_4(),B5=()=>!!b0.wasm.proxy&&typeof document<"u",t5=!1,c8=!1,l8=!1,v9=new Map,T5=(J,Q)=>{let X=v9.get(J);X?X.push(Q):v9.set(J,[Q])},I5=()=>{if(t5||!c8||l8||!R6)throw Error("worker not ready")},IH=(J)=>{switch(J.data.type){case"init-wasm":t5=!1,J.data.err?(l8=!0,E4[1](J.data.err)):(c8=!0,E4[0]()),I9&&(URL.revokeObjectURL(I9),I9=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let Q=v9.get(J.data.type);J.data.err?Q.shift()[1](J.data.err):Q.shift()[0](J.data.out);break}default:}},UY=async()=>{if(!c8){if(t5)throw Error("multiple calls to 'initWasm()' detected.");if(l8)throw Error("previous call to 'initWasm()' failed.");if(t5=!0,B5())return new Promise((J,Q)=>{R6?.terminate(),QY().then(([X,K])=>{try{R6=K,R6.onerror=(H)=>Q(H),R6.onmessage=IH,E4=[J,Q];let Z={type:"init-wasm",in:b0};!Z.in.wasm.wasmPaths&&(X||T4)&&(Z.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href}),R6.postMessage(Z),I9=X}catch(Z){Q(Z)}},Q)});try{await g4(b0.wasm),await d4(b0),c8=!0}catch(J){throw l8=!0,J}finally{t5=!1}}},NY=async(J)=>{if(B5())return I5(),new Promise((Q,X)=>{T5("init-ep",[Q,X]);let K={type:"init-ep",in:{epName:J,env:b0}};R6.postMessage(K)});await p4(b0,J)},jY=async(J)=>B5()?(I5(),new Promise((Q,X)=>{T5("copy-from",[Q,X]);let K={type:"copy-from",in:{buffer:J}};R6.postMessage(K,[J.buffer])})):f9(J),zY=async(J,Q)=>{if(B5()){if(Q?.preferredOutputLocation)throw Error('session option "preferredOutputLocation" is not supported for proxy.');return I5(),new Promise((X,K)=>{T5("create",[X,K]);let Z={type:"create",in:{model:J,options:{...Q}}},H=[];J instanceof Uint8Array&&H.push(J.buffer),R6.postMessage(Z,H)})}else return i4(J,Q)},OY=async(J)=>{if(B5())return I5(),new Promise((Q,X)=>{T5("release",[Q,X]);let K={type:"release",in:J};R6.postMessage(K)});r4(J)},BY=async(J,Q,X,K,Z,H)=>{if(B5()){if(X.some((Y)=>Y[3]!=="cpu"))throw Error("input tensor on GPU is not supported for proxy.");if(Z.some((Y)=>Y))throw Error("pre-allocated output tensor is not supported for proxy.");return I5(),new Promise((Y,$)=>{T5("run",[Y,$]);let V=X,W={type:"run",in:{sessionId:J,inputIndices:Q,inputs:V,outputIndices:K,options:H}};R6.postMessage(W,n4(V))})}else return a4(J,Q,X,K,Z,H)},DY=async(J)=>{if(B5())return I5(),new Promise((Q,X)=>{T5("end-profiling",[Q,X]);let K={type:"end-profiling",in:J};R6.postMessage(K)});o4(J)}}),w4,vH,SY,o1=N0(()=>{b5(),MY(),J8(),f4(),HY(),w4=(J,Q)=>{switch(J.location){case"cpu":return[J.type,J.dims,J.data,"cpu"];case"gpu-buffer":return[J.type,J.dims,{gpuBuffer:J.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[J.type,J.dims,{mlTensor:J.mlTensor},"ml-tensor"];default:throw Error(`invalid data location: ${J.location} for ${Q()}`)}},vH=(J)=>{switch(J[3]){case"cpu":return new I6(J[0],J[2],J[1]);case"gpu-buffer":{let Q=J[0];if(!l4(Q))throw Error(`not supported data type: ${Q} for deserializing GPU tensor`);let{gpuBuffer:X,download:K,dispose:Z}=J[2];return I6.fromGpuBuffer(X,{dataType:Q,dims:J[1],download:K,dispose:Z})}case"ml-tensor":{let Q=J[0];if(!u4(Q))throw Error(`not supported data type: ${Q} for deserializing MLTensor tensor`);let{mlTensor:X,download:K,dispose:Z}=J[2];return I6.fromMLTensor(X,{dataType:Q,dims:J[1],download:K,dispose:Z})}default:throw Error(`invalid data location: ${J[3]}`)}},SY=class{async fetchModelAndCopyToWasmMemory(J){return jY(await m4(J))}async loadModel(J,Q){k5();let X;typeof J=="string"?X=await this.fetchModelAndCopyToWasmMemory(J):X=J,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await zY(X,Q),h5()}async dispose(){return OY(this.sessionId)}async run(J,Q,X){k5();let K=[],Z=[];Object.entries(J).forEach((F)=>{let N=F[0],j=F[1],B=this.inputNames.indexOf(N);if(B===-1)throw Error(`invalid input '${N}'`);K.push(j),Z.push(B)});let H=[],Y=[];Object.entries(Q).forEach((F)=>{let N=F[0],j=F[1],B=this.outputNames.indexOf(N);if(B===-1)throw Error(`invalid output '${N}'`);H.push(j),Y.push(B)});let $=K.map((F,N)=>w4(F,()=>`input "${this.inputNames[Z[N]]}"`)),V=H.map((F,N)=>F?w4(F,()=>`output "${this.outputNames[Y[N]]}"`):null),W=await BY(this.sessionId,Z,$,Y,V,X),q={};for(let F=0;Fx4,initializeFlags:()=>y4,wasmBackend:()=>CY});var y4,x4,CY,n1=N0(()=>{b5(),MY(),o1(),y4=()=>{(typeof b0.wasm.initTimeout!="number"||b0.wasm.initTimeout<0)&&(b0.wasm.initTimeout=0);let J=b0.wasm.simd;if(typeof J!="boolean"&&J!==void 0&&J!=="fixed"&&J!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${J}". Reset it to \`false\` and ignore SIMD feature checking.`),b0.wasm.simd=!1),typeof b0.wasm.proxy!="boolean"&&(b0.wasm.proxy=!1),typeof b0.wasm.trace!="boolean"&&(b0.wasm.trace=!1),typeof b0.wasm.numThreads!="number"||!Number.isInteger(b0.wasm.numThreads)||b0.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)b0.wasm.numThreads=1;else{let Q=typeof navigator>"u"?E1("node:os").cpus().length:navigator.hardwareConcurrency;b0.wasm.numThreads=Math.min(4,Math.ceil((Q||1)/2))}},x4=class{async init(J){y4(),await UY(),await NY(J)}async createInferenceSessionHandler(J,Q){let X=new SY;return await X.loadModel(J,Q),X}},CY=new x4});b5();b5();b5();var s1="1.27.0",t1=oH;{let J=(n1(),x9(LY)).wasmBackend;x5("webgpu",J,5),x5("webnn",J,5),x5("cpu",J,10),x5("wasm",J,10)}Object.defineProperty(b0.versions,"web",{value:s1,enumerable:!0});var RY="1.24.3";var AY="warning",t4={wasm:{},webgl:{},webgpu:{},versions:{common:RY},set logLevel(J){if(J===void 0)return;if(typeof J!=="string"||["verbose","info","warning","error","fatal"].indexOf(J)===-1)throw Error(`Unsupported logging level: ${J}`);AY=J},get logLevel(){return AY}};Object.defineProperty(t4,"logLevel",{enumerable:!0});var PY=(J,Q)=>{let X=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);X.width=J.dims[3],X.height=J.dims[2];let K=X.getContext("2d");if(K!=null){let Z,H;if(Q?.tensorLayout!==void 0&&Q.tensorLayout==="NHWC")Z=J.dims[2],H=J.dims[3];else Z=J.dims[3],H=J.dims[2];let Y=Q?.format!==void 0?Q.format:"RGB",$=Q?.norm,V,W;if($===void 0||$.mean===void 0)V=[255,255,255,255];else if(typeof $.mean==="number")V=[$.mean,$.mean,$.mean,$.mean];else if(V=[$.mean[0],$.mean[1],$.mean[2],0],$.mean[3]!==void 0)V[3]=$.mean[3];if($===void 0||$.bias===void 0)W=[0,0,0,0];else if(typeof $.bias==="number")W=[$.bias,$.bias,$.bias,$.bias];else if(W=[$.bias[0],$.bias[1],$.bias[2],0],$.bias[3]!==void 0)W[3]=$.bias[3];let q=H*Z,F=0,N=q,j=q*2,B=-1;if(Y==="RGBA")F=0,N=q,j=q*2,B=q*3;else if(Y==="RGB")F=0,N=q,j=q*2;else if(Y==="RBG")F=0,j=q,N=q*2;for(let D=0;D{let X=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),K;if(X!=null){let Z,H,Y;if(Q?.tensorLayout!==void 0&&Q.tensorLayout==="NHWC")Z=J.dims[2],H=J.dims[1],Y=J.dims[3];else Z=J.dims[3],H=J.dims[2],Y=J.dims[1];let $=Q!==void 0?Q.format!==void 0?Q.format:"RGB":"RGB",V=Q?.norm,W,q;if(V===void 0||V.mean===void 0)W=[255,255,255,255];else if(typeof V.mean==="number")W=[V.mean,V.mean,V.mean,V.mean];else if(W=[V.mean[0],V.mean[1],V.mean[2],255],V.mean[3]!==void 0)W[3]=V.mean[3];if(V===void 0||V.bias===void 0)q=[0,0,0,0];else if(typeof V.bias==="number")q=[V.bias,V.bias,V.bias,V.bias];else if(q=[V.bias[0],V.bias[1],V.bias[2],0],V.bias[3]!==void 0)q[3]=V.bias[3];let F=H*Z;if(Q!==void 0){if(Q.format!==void 0&&Y===4&&Q.format!=="RGBA"||Y===3&&Q.format!=="RGB"&&Q.format!=="BGR")throw Error("Tensor format doesn't match input tensor dims")}let N=4,j=0,B=1,D=2,L=3,M=0,R=F,E=F*2,P=-1;if($==="RGBA")M=0,R=F,E=F*2,P=F*3;else if($==="RGB")M=0,R=F,E=F*2;else if($==="RBG")M=0,E=F,R=F*2;K=X.createImageData(Z,H);for(let w=0;w{if(J===void 0)throw Error("Image buffer must be defined");if(Q.height===void 0||Q.width===void 0)throw Error("Image height and width must be defined");if(Q.tensorLayout==="NHWC")throw Error("NHWC Tensor layout is not supported yet");let{height:X,width:K}=Q,Z=Q.norm??{mean:255,bias:0},H,Y;if(typeof Z.mean==="number")H=[Z.mean,Z.mean,Z.mean,Z.mean];else H=[Z.mean[0],Z.mean[1],Z.mean[2],Z.mean[3]??255];if(typeof Z.bias==="number")Y=[Z.bias,Z.bias,Z.bias,Z.bias];else Y=[Z.bias[0],Z.bias[1],Z.bias[2],Z.bias[3]??0];let $=Q.format!==void 0?Q.format:"RGBA",V=Q.tensorFormat!==void 0?Q.tensorFormat!==void 0?Q.tensorFormat:"RGB":"RGB",W=X*K,q=V==="RGBA"?new Float32Array(W*4):new Float32Array(W*3),F=4,N=0,j=1,B=2,D=3,L=0,M=W,R=W*2,E=-1;if($==="RGB")F=3,N=0,j=1,B=2,D=-1;if(V==="RGBA")E=W*3;else if(V==="RBG")L=0,R=W,M=W*2;else if(V==="BGR")R=0,M=W,L=W*2;for(let w=0;w{let X=typeof HTMLImageElement<"u"&&J instanceof HTMLImageElement,K=typeof ImageData<"u"&&J instanceof ImageData,Z=typeof ImageBitmap<"u"&&J instanceof ImageBitmap,H=typeof J==="string",Y,$=Q??{},V=()=>{if(typeof document<"u")return document.createElement("canvas");else if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);else throw Error("Canvas is not supported")},W=(q)=>{if(typeof HTMLCanvasElement<"u"&&q instanceof HTMLCanvasElement)return q.getContext("2d");else if(q instanceof OffscreenCanvas)return q.getContext("2d");else return null};if(X){let q=V();q.width=J.width,q.height=J.height;let F=W(q);if(F!=null){let{height:N,width:j}=J;if(Q!==void 0&&Q.resizedHeight!==void 0&&Q.resizedWidth!==void 0)N=Q.resizedHeight,j=Q.resizedWidth;if(Q!==void 0){if($=Q,Q.tensorFormat!==void 0)throw Error("Image input config format must be RGBA for HTMLImageElement");else $.tensorFormat="RGBA";$.height=N,$.width=j}else $.tensorFormat="RGBA",$.height=N,$.width=j;F.drawImage(J,0,0),Y=F.getImageData(0,0,j,N).data}else throw Error("Can not access image data")}else if(K){let q,F;if(Q!==void 0&&Q.resizedWidth!==void 0&&Q.resizedHeight!==void 0)q=Q.resizedHeight,F=Q.resizedWidth;else q=J.height,F=J.width;if(Q!==void 0)$=Q;if($.format="RGBA",$.height=q,$.width=F,Q!==void 0){let N=V();N.width=F,N.height=q;let j=W(N);if(j!=null)j.putImageData(J,0,0),Y=j.getImageData(0,0,F,q).data;else throw Error("Can not access image data")}else Y=J.data}else if(Z){if(Q===void 0)throw Error("Please provide image config with format for Imagebitmap");let q=V();q.width=J.width,q.height=J.height;let F=W(q);if(F!=null){let{height:N,width:j}=J;return F.drawImage(J,0,0,j,N),Y=F.getImageData(0,0,j,N).data,$.height=N,$.width=j,e4(Y,$)}else throw Error("Can not access image data")}else if(H)return new Promise((q,F)=>{let N=V(),j=W(N);if(!J||!j)return F();let B=new Image;B.crossOrigin="Anonymous",B.src=J,B.onload=()=>{N.width=B.width,N.height=B.height,j.drawImage(B,0,0,N.width,N.height);let D=j.getImageData(0,0,N.width,N.height);$.height=N.height,$.width=N.width,q(e4(D.data,$))}});else throw Error("Input data provided is not supported - aborted tensor creation");if(Y!==void 0)return e4(Y,$);else throw Error("Input data provided is not supported - aborted tensor creation")},TY=(J,Q)=>{let{width:X,height:K,download:Z,dispose:H}=Q;return new Y6({location:"texture",type:"float32",texture:J,dims:[1,K,X,4],download:Z,dispose:H})},IY=(J,Q)=>{let{dataType:X,dims:K,download:Z,dispose:H}=Q;return new Y6({location:"gpu-buffer",type:X??"float32",gpuBuffer:J,dims:K,download:Z,dispose:H})},vY=(J,Q)=>{let{dataType:X,dims:K,download:Z,dispose:H}=Q;return new Y6({location:"ml-tensor",type:X??"float32",mlTensor:J,dims:K,download:Z,dispose:H})},yY=(J,Q,X)=>new Y6({location:"cpu-pinned",type:J,data:Q,dims:X??[Q.length]});var _5=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),p8=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),xY=!1,kY=()=>{if(!xY){xY=!0;let J=typeof BigInt64Array<"u"&&BigInt64Array.from,Q=typeof BigUint64Array<"u"&&BigUint64Array.from,X=globalThis.Float16Array,K=typeof X<"u"&&X.from;if(J)_5.set("int64",BigInt64Array),p8.set(BigInt64Array,"int64");if(Q)_5.set("uint64",BigUint64Array),p8.set(BigUint64Array,"uint64");if(K)_5.set("float16",X),p8.set(X,"float16");else _5.set("float16",Uint16Array)}};var hY=(J)=>{let Q=1;for(let X=0;X{switch(J.location){case"cpu":return new Y6(J.type,J.data,Q);case"cpu-pinned":return new Y6({location:"cpu-pinned",data:J.data,type:J.type,dims:Q});case"texture":return new Y6({location:"texture",texture:J.texture,type:J.type,dims:Q});case"gpu-buffer":return new Y6({location:"gpu-buffer",gpuBuffer:J.gpuBuffer,type:J.type,dims:Q});case"ml-tensor":return new Y6({location:"ml-tensor",mlTensor:J.mlTensor,type:J.type,dims:Q});default:throw Error(`tensorReshape: tensor location ${J.location} is not supported`)}};class Y6{constructor(J,Q,X){kY();let K,Z;if(typeof J==="object"&&"location"in J)switch(this.dataLocation=J.location,K=J.type,Z=J.dims,J.location){case"cpu-pinned":{let Y=_5.get(K);if(!Y)throw TypeError(`unsupported type "${K}" to create tensor from pinned buffer`);if(!(J.data instanceof Y))throw TypeError(`buffer should be of type ${Y.name}`);this.cpuData=J.data;break}case"texture":{if(K!=="float32")throw TypeError(`unsupported type "${K}" to create tensor from texture`);this.gpuTextureData=J.texture,this.downloader=J.download,this.disposer=J.dispose;break}case"gpu-buffer":{if(K!=="float32"&&K!=="float16"&&K!=="int32"&&K!=="int64"&&K!=="uint32"&&K!=="uint8"&&K!=="bool"&&K!=="uint4"&&K!=="int4")throw TypeError(`unsupported type "${K}" to create tensor from gpu buffer`);this.gpuBufferData=J.gpuBuffer,this.downloader=J.download,this.disposer=J.dispose;break}case"ml-tensor":{if(K!=="float32"&&K!=="float16"&&K!=="int32"&&K!=="int64"&&K!=="uint32"&&K!=="uint64"&&K!=="int8"&&K!=="uint8"&&K!=="bool"&&K!=="uint4"&&K!=="int4")throw TypeError(`unsupported type "${K}" to create tensor from MLTensor`);this.mlTensorData=J.mlTensor,this.downloader=J.download,this.disposer=J.dispose;break}default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let Y,$;if(typeof J==="string")if(K=J,$=X,J==="string"){if(!Array.isArray(Q))throw TypeError("A string tensor's data must be a string array.");Y=Q}else{let V=_5.get(J);if(V===void 0)throw TypeError(`Unsupported tensor type: ${J}.`);if(Array.isArray(Q))if(J==="float16"&&V===Uint16Array||J==="uint4"||J==="int4")throw TypeError(`Creating a ${J} tensor from number array is not supported. Please use ${V.name} as data.`);else if(J==="uint64"||J==="int64")Y=V.from(Q,BigInt);else Y=V.from(Q);else if(Q instanceof V)Y=Q;else if(Q instanceof Uint8ClampedArray)if(J==="uint8")Y=Uint8Array.from(Q);else throw TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(J==="float16"&&Q instanceof Uint16Array&&V!==Uint16Array)Y=new globalThis.Float16Array(Q.buffer,Q.byteOffset,Q.length);else throw TypeError(`A ${K} tensor's data must be type of ${V}`)}else if($=Q,Array.isArray(J)){if(J.length===0)throw TypeError("Tensor type cannot be inferred from an empty array.");let V=typeof J[0];if(V==="string")K="string",Y=J;else if(V==="boolean")K="bool",Y=Uint8Array.from(J);else throw TypeError(`Invalid element type of data array: ${V}.`)}else if(J instanceof Uint8ClampedArray)K="uint8",Y=Uint8Array.from(J);else{let V=p8.get(J.constructor);if(V===void 0)throw TypeError(`Unsupported type for tensor data: ${J.constructor}.`);K=V,Y=J}if($===void 0)$=[Y.length];else if(!Array.isArray($))throw TypeError("A tensor's dims must be a number array");Z=$,this.cpuData=Y,this.dataLocation="cpu"}let H=hY(Z);if(this.cpuData&&H!==this.cpuData.length)if((K==="uint4"||K==="int4")&&Math.ceil(H/2)===this.cpuData.length);else throw Error(`Tensor's size(${H}) does not match data length(${this.cpuData.length}).`);this.type=K,this.dims=Z,this.size=H}static async fromImage(J,Q){return wY(J,Q)}static fromTexture(J,Q){return TY(J,Q)}static fromGpuBuffer(J,Q){return IY(J,Q)}static fromMLTensor(J,Q){return vY(J,Q)}static fromPinnedBuffer(J,Q,X){return yY(J,Q,X)}toDataURL(J){return PY(this,J)}toImageData(J){return EY(this,J)}get data(){if(this.ensureValid(),!this.cpuData)throw 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 Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(J){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 Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let Q=await this.downloader();if(this.downloader=void 0,this.dataLocation="cpu",this.cpuData=Q,J&&this.disposer)this.disposer(),this.disposer=void 0;return Q}finally{this.isDownloading=!1}}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error("The current tensor is being downloaded.");if(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 Error("The tensor is disposed.")}reshape(J){if(this.ensureValid(),this.downloader||this.disposer)throw Error("Cannot reshape a tensor that owns GPU resource.");return bY(this,J)}}var JJ=Y6;var __dirname="/home/rakuni/pi/node_modules/@huggingface/transformers/dist",e1=Object.defineProperty,U8=(J,Q)=>{for(var X in Q)e1(J,X,{get:Q[X],enumerable:!0})},S6={},r6={},JU={},QU="4.2.0",RJ=typeof self<"u",W8=!l$(S6),_$=!l$(r6),a9=RJ&&"caches"in self,XU=typeof globalThis.Deno<"u",XI=typeof globalThis.Bun<"u",Z7=XU&&a9&&!W8,g$=typeof process<"u",c$=g$&&process?.release?.name==="node"&&!Z7,AJ=typeof window<"u"&&typeof window.document<"u",PJ=RJ&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),KU=AJ||PJ||Z7,ZU=c$||typeof navigator<"u"&&"gpu"in navigator,HU=typeof navigator<"u"&&"ml"in navigator,YU=typeof crypto<"u"&&typeof crypto.getRandomValues==="function",$U=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id==="string",VU=typeof ServiceWorkerGlobalScope<"u"&&RJ&&self instanceof ServiceWorkerGlobalScope,WU=()=>{if(typeof navigator>"u")return!1;let J=navigator.userAgent,X=(navigator.vendor||"").indexOf("Apple")>-1,K=!J.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!J.includes("Chrome")&&!J.includes("Android");return X&&K},GU=WU(),U0=Object.freeze({IS_BROWSER_ENV:AJ,IS_WEBWORKER_ENV:PJ,IS_WEB_ENV:KU,IS_SERVICE_WORKER_ENV:VU,IS_DENO_WEB_RUNTIME:Z7,IS_WEB_CACHE_AVAILABLE:a9,IS_WEBGPU_AVAILABLE:ZU,IS_WEBNN_AVAILABLE:HU,IS_SAFARI:GU,IS_PROCESS_AVAILABLE:g$,IS_NODE_ENV:c$,IS_FS_AVAILABLE:W8,IS_PATH_AVAILABLE:_$,IS_CRYPTO_AVAILABLE:YU,IS_CHROME_AVAILABLE:$U}),EJ=W8&&_$,o9="./";if(EJ){let J=Object(import.meta).url;if(J)o9=r6.dirname(r6.dirname(JU.fileURLToPath(J)));else if(typeof __dirname<"u")o9=r6.dirname(__dirname)}var qU=EJ?r6.join(o9,"/.cache/"):null,fY="/models/",FU=EJ?r6.join(o9,fY):fY,UU=typeof globalThis.fetch==="function"?globalThis.fetch.bind(globalThis):void 0,v6=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),_Y=v6.WARNING,G0={version:QU,backends:{onnx:{}},get logLevel(){return _Y},set logLevel(J){_Y=J,G0.backends.onnx?.setLogLevel?.(J)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(AJ||PJ||Z7),localModelPath:FU,useFS:W8,useBrowserCache:a9,useFSCache:W8,cacheDir:qU,useCustomCache:!1,customCache:null,useWasmCache:a9||W8,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:UU};function l$(J){return Object.keys(J).length===0}var z6=class{constructor(){let J=function(...Q){return J._call(...Q)};return Object.setPrototypeOf(J,new.target.prototype)}_call(...J){throw Error("Must implement _call method in subclass")}};function C5(J,Q){if(J)J(Q)}var FJ=class extends z6{constructor(J,Q){super();this.callback=J,this.files_loading=Q}_call(J){if(J.status==="progress"){this.files_loading[J.file]={loaded:J.loaded,total:J.total};let Q=Object.values(this.files_loading).reduce((Z,H)=>Z+H.loaded,0),X=Object.values(this.files_loading).reduce((Z,H)=>Z+H.total,0),K=X>0?Q/X*100:0;this.callback({status:"progress_total",name:J.name,progress:K,loaded:Q,total:X,files:structuredClone(this.files_loading)})}this.callback(J)}};function NU(J){return Number.isInteger(J)||typeof J==="bigint"}function gY(J){return J===null||J===void 0||J===-1}function cY(J){let Q=[],X=J;while(Array.isArray(X))Q.push(X.length),X=X[0];return Q}function a6(...J){return Array.prototype.concat.apply([],J)}function jU(...J){return J.reduce((Q,X)=>Q.flatMap((K)=>X.map((Z)=>[K,Z])))}function n9(J,Q){return Math.abs((J+Q)%(2*Q)-Q)}function e0(J,Q){return Object.assign({},...Q.map((X)=>{if(J[X]!==void 0)return{[X]:J[X]}}))}function zU(J,Q){let X=0;for(let K of J)if(K===Q)++X;return X}var $0={error(...J){if(G0.logLevel<=v6.ERROR)console.error(...J)},warn(...J){if(G0.logLevel<=v6.WARNING)console.warn(...J)},info(...J){if(G0.logLevel<=v6.INFO)console.log(...J)},debug(...J){if(G0.logLevel<=v6.DEBUG)console.log(...J)},log(...J){this.info(...J)}},OU=class{constructor(J){this.trie=this._build_trie(J)}_build_trie(J){let Q=Object.create(null);for(let X of J){let K=Q;for(let Z=0;ZK)Q.push(J.slice(K,Z));Q.push(Y),Z+=Y.length,K=Z}else++Z}if(K{let J=[...Array.from({length:94},(Z,H)=>H+33),...Array.from({length:"¬".charCodeAt(0)-"¡".charCodeAt(0)+1},(Z,H)=>H+"¡".charCodeAt(0)),...Array.from({length:"ÿ".charCodeAt(0)-"®".charCodeAt(0)+1},(Z,H)=>H+"®".charCodeAt(0))],Q=J.slice(),X=0;for(let Z=0;Z<256;++Z)if(!J.includes(Z))J.push(Z),Q.push(256+X),X+=1;let K=Q.map((Z)=>String.fromCharCode(Z));return Object.fromEntries(J.map((Z,H)=>[Z,K[H]]))})(),MU=(J)=>Object.fromEntries(Object.entries(J).map(([Q,X])=>[X,Q])),SU=MU(u$),uY=".,!?…。,、।۔،",LU=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|[${uY}])]+`,` ?[^\\s${uY}]+`]]),s9="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",wJ=(J)=>J.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"),H7=(J,Q=!0)=>{if(J.Regex!==void 0){let X=J.Regex.replace(/\\([#&~])/g,"$1");X=X.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(let[K,Z]of LU)X=X.replaceAll(K,Z);try{return new RegExp(X,"gu")}catch(K){if(!(K instanceof SyntaxError)||!K.message.toLowerCase().includes("invalid property name"))throw K;let Z=!1,H=X.replace(/(\\[pP])\{([^}=]+)\}/g,(Y,$,V)=>{try{return new RegExp(`\\p{${V}}`,"u"),`${$}{${V}}`}catch{return Z=!0,`${$}{Script=${V}}`}});if(!Z)throw K;try{return new RegExp(H,"gu")}catch(Y){throw K}}}else if(J.String!==void 0){let X=CU(J.String);return new RegExp(Q?X:`(${X})`,"gu")}else return console.warn("Unknown pattern type:",J),null},CU=(J)=>J.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),RU=(J,Q,X)=>{let K=[],Z=0;while(ZJ>=19968&&J<=40959||J>=13312&&J<=19903||J>=131072&&J<=173791||J>=173824&&J<=177983||J>=177984&&J<=178207||J>=178208&&J<=183983||J>=63744&&J<=64255||J>=194560&&J<=195103,PU=(J)=>Number.isInteger(J)||typeof J==="bigint",EU=(J)=>{let Q=0;for(let X of J)++Q;return Q},wU=(J)=>m$(J.toLowerCase()),y6=(...J)=>Array.prototype.concat.apply([],J),TJ=(J)=>new Map(Object.entries(J)),TU=(J,Q)=>{let X=[],K=0;for(let Z of J.matchAll(Q)){let H=Z[0];if(K0)X.push(H);K=Z.index+H.length}if(KJ.replace(/\p{M}/gu,""),mY=(J,Q,X=[])=>{if(!J||Array.isArray(J)||typeof J!=="object")return`${Q} must be a valid object`;for(let K of X)if(!(K in J))return`${Q} must contain a "${K}" property`;return null},IU=(J)=>J.match(/\S+/g)||[],vU=class{constructor(){let J=function(...Q){return J._call(...Q)};return Object.setPrototypeOf(J,new.target.prototype)}},K9=vU,yU=class extends K9{constructor(J){super();this.config=J}_call(J){return this.normalize(J)}},G5=yU,xU=class extends G5{tokenize_chinese_chars(J){let Q=[];for(let X=0;XX.normalize("NFKC")).join("~");else J=J.normalize("NFKC");return J}},bU=hU,fU=class extends G5{constructor(J){super(J);this.normalizers=(J.normalizers??[]).map((Q)=>d$(Q))}normalize(J){return this.normalizers.reduce((Q,X)=>{return X?X.normalize(Q):Q},J)}},_U=fU,gU=class extends G5{normalize(J){let Q=H7(this.config.pattern??{});return Q===null?J:J.replaceAll(Q,this.config.content??"")}},cU=gU,lU=class extends G5{constructor(){super(...arguments);this.form="NFC"}normalize(J){return J=J.normalize(this.form),J}},Y7=lU,uU=class extends Y7{constructor(){super(...arguments);this.form="NFC"}},mU=uU,dU=class extends Y7{constructor(){super(...arguments);this.form="NFD"}},pU=dU,iU=class extends Y7{constructor(){super(...arguments);this.form="NFKC"}},rU=iU,aU=class extends Y7{constructor(){super(...arguments);this.form="NFKD"}},oU=aU,nU=class extends G5{normalize(J){if(this.config.strip_left&&this.config.strip_right)J=J.trim();else{if(this.config.strip_left)J=J.trimStart();if(this.config.strip_right)J=J.trimEnd()}return J}},sU=nU,tU=class extends G5{normalize(J){return m$(J)}},eU=tU,J3=class extends G5{normalize(J){return J.toLowerCase()}},Q3=J3,X3=class extends G5{normalize(J){return J=this.config.prepend+J,J}},K3=X3;function Z3(J){if(J===null)return null;switch(J.type){case"BertNormalizer":return new kU(J);case"Precompiled":return new bU(J);case"Sequence":return new _U(J);case"Replace":return new cU(J);case"NFC":return new mU(J);case"NFD":return new pU(J);case"NFKC":return new rU(J);case"NFKD":return new oU(J);case"Strip":return new sU(J);case"StripAccents":return new eU(J);case"Lowercase":return new Q3(J);case"Prepend":return new K3(J);default:throw Error(`Unknown Normalizer type: ${J.type}`)}}var d$=Z3,H3=class extends K9{pre_tokenize(J,Q){return(Array.isArray(J)?J.map((X)=>this.pre_tokenize_text(X,Q)):this.pre_tokenize_text(J,Q)).flat()}_call(J,Q){return this.pre_tokenize(J,Q)}},b6=H3,Y3=class extends b6{constructor(J){super();this.config=J,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=u$,this.text_encoder=new TextEncoder}pre_tokenize_text(J,Q){if(this.add_prefix_space&&!J.startsWith(" "))J=" "+J;return(this.use_regex?J.match(this.pattern)||[]:[J]).map((K)=>Array.from(this.text_encoder.encode(K),(Z)=>this.byte_encoder[Z]).join(""))}},$3=Y3,V3=class extends b6{pre_tokenize_text(J,Q){return J.match(/\w+|[^\w\s]+/g)||[]}},W3=V3,G3=class extends b6{constructor(J){super();this.replacement=J.replacement??"▁",this.str_rep=J.str_rep||this.replacement,this.prepend_scheme=J.prepend_scheme??"always"}pre_tokenize_text(J,Q){let{section_index:X=void 0}=Q??{},K=J.replaceAll(" ",this.str_rep);if(!K.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&X===0))K=this.str_rep+K;return[K]}},q3=G3,F3=class extends b6{constructor(J){super();this.config=J,this.pattern=H7(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(J){if(this.pattern===null)return[];if(this.config.invert)return J.match(this.pattern)||[];else if(this.config.behavior?.toLowerCase()==="removed")return J.split(this.pattern).filter((Q)=>Q);else return TU(J,this.pattern)}},U3=F3,N3=class extends b6{constructor(J){super();this.config=J,this.pattern=new RegExp(`[^${s9}]+|[${s9}]+`,"gu")}pre_tokenize_text(J){return J.match(this.pattern)||[]}},j3=N3,z3=class extends b6{constructor(J){super();this.config=J;let Q=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(Q,"gu")}pre_tokenize_text(J){return J.match(this.pattern)||[]}},O3=z3,B3=class extends b6{constructor(){super();this.pattern=new RegExp(`[^\\s${s9}]+|[${s9}]`,"gu")}pre_tokenize_text(J,Q){return J.trim().match(this.pattern)||[]}},D3=B3,M3=class extends b6{constructor(J){super();this.config=J,this.pattern=H7(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(J){if(this.pattern===null)return[J];return[J.replaceAll(this.pattern,this.config.content??"")]}},S3=M3,L3=class extends b6{constructor(J){super();this.tokenizers=(J.pretokenizers??[]).map((Q)=>p$(Q))}pre_tokenize_text(J,Q){return this.tokenizers.reduce((X,K)=>{return K?K.pre_tokenize(X,Q):X},[J])}},C3=L3,R3=class extends b6{pre_tokenize_text(J){return IU(J)}},A3=R3,P3=class extends b6{constructor(J){super();this.config=J,this._length=J.length}pre_tokenize_text(J){let Q=[];for(let X=0;Xthis.max_input_chars_per_word){Q.push(this.unk_token);continue}let Z=!1,H=0,Y=[];while(H0)W=this.config.continuing_subword_prefix+W;if(this.tokens_to_ids.has(W)){V=W;break}--$}if(V===null){Z=!0;break}Y.push(V),H=$}if(Z)Q.push(this.unk_token);else Q.push(...Y)}return Q}},dY=I3,pY=class J{constructor(Q,X){this.is_leaf=Q,this.children=X}static default(){return new J(!1,new Map)}},v3=class{constructor(){this.root=pY.default()}extend(J){for(let Q of J)this.push(Q)}push(J){let Q=this.root;for(let X of J){let K=Q.children.get(X);if(K===void 0)K=pY.default(),Q.children.set(X,K);Q=K}Q.is_leaf=!0}*common_prefix_search(J){let Q=this.root;if(Q===void 0)return;let X="";for(let K of J){if(X+=K,Q=Q.children.get(K),Q===void 0)return;if(Q.is_leaf)yield X}}},y3=v3,QJ=class J{constructor(Q,X,K,Z,H){this.token_id=Q,this.node_id=X,this.pos=K,this.length=Z,this.score=H,this.prev=null,this.backtrace_score=0}clone(){let Q=new J(this.token_id,this.node_id,this.pos,this.length,this.score);return Q.prev=this.prev,Q.backtrace_score=this.backtrace_score,Q}},x3=class{constructor(J,Q,X){this.chars=Array.from(J),this.len=this.chars.length,this.bos_token_id=Q,this.eos_token_id=X,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let K=new QJ(this.bos_token_id??0,0,0,0,0),Z=new QJ(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(K.clone()),this.nodes.push(Z.clone()),this.begin_nodes[this.len].push(Z),this.end_nodes[0].push(K)}insert(J,Q,X,K){let Z=this.nodes.length,H=new QJ(K,Z,J,Q,X);this.begin_nodes[J].push(H),this.end_nodes[J+Q].push(H),this.nodes.push(H)}viterbi(){let J=this.len,Q=0;while(Q<=J){if(this.begin_nodes[Q].length==0)return[];for(let Y of this.begin_nodes[Q]){Y.prev=null;let $=0,V=null;for(let W of this.end_nodes[Q]){let q=W.backtrace_score+Y.score;if(V===null||q>$)V=W.clone(),$=q}if(V!==null)Y.prev=V,Y.backtrace_score=$;else return[]}++Q}let X=[],Z=this.begin_nodes[J][0].prev;if(Z===null)return[];let H=Z.clone();while(H.prev!==null)X.push(H.clone()),H=H.clone().prev.clone();return X.reverse(),X}piece(J){return this.chars.slice(J.pos,J.pos+J.length).join("")}tokens(){return this.viterbi().map((Q)=>this.piece(Q))}token_ids(){return this.viterbi().map((Q)=>Q.token_id)}},k3=x3;function h3(J){if(J.length===0)throw Error("Array must not be empty");let Q=J[0],X=0;for(let K=1;K[K,Z])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=Q,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=h3(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new y3,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(J){let Q=J.chars,X=1,K=0;while(KX>K,Q=1/0){this._heap=[],this._comparator=J,this._max_size=Q}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...J){return this.extend(J)}extend(J){for(let Q of J)if(this.size0)this._swap(0,Q);return this._heap.pop(),this._sift_down(),J}replace(J){let Q=this.peek();return this._heap[0]=J,this._sift_down(),Q}_parent(J){return(J+1>>>1)-1}_left(J){return(J<<1)+1}_right(J){return J+1<<1}_greater(J,Q){return this._comparator(this._heap[J],this._heap[Q])}_swap(J,Q){let X=this._heap[J];this._heap[J]=this._heap[Q],this._heap[Q]=X}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(J){while(J>0&&this._greater(J,this._parent(J)))this._swap(J,this._parent(J)),J=this._parent(J)}_sift_down(){let J=0;while(this._left(J)this.capacity)this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},c3=g3,l3=class extends $7{constructor(J){super(J);this.tokens_to_ids=TJ(J.vocab),this.unk_token_id=this.tokens_to_ids.get(J.unk_token),this.unk_token=J.unk_token,this.vocab=Array(this.tokens_to_ids.size);for(let[X,K]of this.tokens_to_ids)this.vocab[K]=X;let Q=Array.isArray(J.merges[0]);if(this.merges=Q?J.merges:J.merges.map((X)=>X.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((X,K)=>[JSON.stringify(X),K])),this.end_of_word_suffix=J.end_of_word_suffix,this.continuing_subword_suffix=J.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 c3(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(J){if(J.length===0)return[];let Q=this.cache.get(J);if(Q!==void 0)return Q;let X=Array.from(J);if(this.end_of_word_suffix)X[X.length-1]+=this.end_of_word_suffix;let K=[];if(X.length>1){let Z=new _3(($,V)=>$.score`<0x${Y.toString(16).toUpperCase().padStart(2,"0")}>`);if(H.every((Y)=>this.tokens_to_ids.has(Y)))Q.push(...H);else if(this.unk_token!=null)Q.push(this.unk_token)}else if(this.unk_token!=null)Q.push(this.unk_token)}return Q}},rY=l3,u3=class extends $7{constructor(J,Q){super(J);let X=J.vocab;this.tokens_to_ids=TJ(Q.target_lang?X[Q.target_lang]:X),this.bos_token=Q.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=Q.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=Q.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=Q.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=Array(this.tokens_to_ids.size);for(let[K,Z]of this.tokens_to_ids)this.vocab[Z]=K}encode(J){return J}},m3=u3;function d3(J,Q){switch(J.type){case"WordPiece":return new dY(J);case"Unigram":return new iY(J,Q.eos_token);case"BPE":return new rY(J);default:if(J.vocab)if(Array.isArray(J.vocab))return new iY(J,Q.eos_token);else if(Object.hasOwn(J,"continuing_subword_prefix")&&Object.hasOwn(J,"unk_token"))if(Object.hasOwn(J,"merges"))return new rY(J);else return new dY(J);else return new m3(J,{target_lang:Q.target_lang,bos_token:Q.bos_token,eos_token:Q.eos_token,pad_token:Q.pad_token,unk_token:Q.unk_token});throw Error(`Unknown TokenizerModel type: ${J?.type}`)}}var p3=d3,i3=class extends K9{constructor(J){super();this.config=J}_call(J,...Q){return this.post_process(J,...Q)}},Z9=i3,r3=class extends Z9{post_process(J,Q=null,X=!0){let K=Q===null?this.config.single:this.config.pair,Z=[],H=[];for(let Y of K)if("SpecialToken"in Y){if(X)Z.push(Y.SpecialToken.id),H.push(Y.SpecialToken.type_id)}else if("Sequence"in Y){if(Y.Sequence.id==="A")Z=y6(Z,J),H=y6(H,Array(J.length).fill(Y.Sequence.type_id));else if(Y.Sequence.id==="B")Z=y6(Z,Q),H=y6(H,Array(Q.length).fill(Y.Sequence.type_id))}return{tokens:Z,token_type_ids:H}}},a3=r3,o3=class extends Z9{post_process(J,Q=null){return{tokens:J,tokens_pair:Q}}},n3=o3,s3=class extends Z9{constructor(J){super(J);this.sep=J.sep,this.cls=J.cls}post_process(J,Q=null,X=!0){if(X)J=y6([this.cls[0]],J,[this.sep[0]]);let K=Array(J.length).fill(0);if(Q){let Z=[],H=X?[this.sep[0]]:[];J=y6(J,Z,Q,H),K=y6(K,Array(Q.length+Z.length+H.length).fill(1))}return{tokens:J,token_type_ids:K}}},t3=s3,e3=class extends Z9{constructor(J){super(J);this.sep=J.sep,this.cls=J.cls}post_process(J,Q,X=!0){if(X)J=y6([this.cls[0]],J,[this.sep[0]]);let K=Array(J.length).fill(0);if(Q){let Z=X?[this.sep[0]]:[],H=X?[this.sep[0]]:[];J=y6(J,Z,Q,H),K=y6(K,Array(Q.length+Z.length+H.length).fill(1))}return{tokens:J,token_type_ids:K}}},JN=e3,QN=class extends Z9{constructor(J){super(J);this.processors=(J.processors??[]).map((Q)=>i$(Q))}post_process(J,Q=null,X=!0){let K={tokens:J,tokens_pair:Q};for(let Z of this.processors)K=Z.post_process(K.tokens,K.tokens_pair,X);return K}},XN=QN;function KN(J){if(J===null)return null;switch(J.type){case"TemplateProcessing":return new a3(J);case"ByteLevel":return new n3(J);case"BertProcessing":return new t3(J);case"RobertaProcessing":return new JN(J);case"Sequence":return new XN(J);default:throw Error(`Unknown PostProcessor type: ${J.type}`)}}var i$=KN,ZN=class extends K9{constructor(J){super();this.config=J,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in J?J.trim_offsets:!1}_call(J){return this.decode(J)}decode(J){return this.decode_chain(J).join("")}},f6=ZN,HN=class extends f6{constructor(J){super(J);this.byte_decoder=SU,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(J){let Q=J.join(""),X=new Uint8Array([...Q].map((K)=>this.byte_decoder[K]));return this.text_decoder.decode(X)}decode_chain(J){let Q=[],X=[];for(let K of J)if(this.added_tokens.find((Z)=>Z.content===K)!==void 0){if(X.length>0)Q.push(this.convert_tokens_to_string(X)),X=[];Q.push(K)}else X.push(K);if(X.length>0)Q.push(this.convert_tokens_to_string(X));return Q}},YN=HN,$N=class extends f6{constructor(J){super(J);this.cleanup=J.cleanup}decode_chain(J){return J.map((Q,X)=>{if(X!==0){let K=this.config.prefix;if(K&&Q.startsWith(K))Q=Q.replace(K,"");else Q=" "+Q}if(this.cleanup)Q=wJ(Q);return Q})}},VN=$N,WN=class extends f6{constructor(J){super(J);this.replacement=J.replacement??"▁"}decode_chain(J){let Q=[];for(let X=0;X{return Q.replaceAll(this.suffix,X===J.length-1?"":" ")})}},FN=qN,UN=class extends f6{constructor(J){super(J);this.pad_token=J.pad_token??"",this.word_delimiter_token=J.word_delimiter_token??"",this.cleanup=J.cleanup}convert_tokens_to_string(J){if(J.length===0)return"";let Q=[J[0]];for(let Z=1;ZZ!==this.pad_token).join("");if(this.cleanup)K=wJ(K).replaceAll(this.word_delimiter_token," ").trim();return K}decode_chain(J){return[this.convert_tokens_to_string(J)]}},NN=UN,jN=class extends f6{constructor(J){super(J);this.decoders=(J.decoders??[]).map((Q)=>r$(Q))}decode_chain(J){return this.decoders.reduce((Q,X)=>{return X.decode_chain(Q)},J)}},zN=jN,ON=class extends f6{decode_chain(J){let Q=H7(this.config.pattern),X=this.config.content??"";return Q===null?J:J.map((K)=>K.replaceAll(Q,X))}},BN=ON,DN=class extends f6{decode_chain(J){return[J.join("")]}},MN=DN,SN=class extends f6{constructor(J){super(J);this.content=J.content??"",this.start=J.start??0,this.stop=J.stop??0}decode_chain(J){return J.map((Q)=>{let X=0;for(let Z=0;Z")){let H=parseInt(K.slice(3,5),16);if(!isNaN(H))Z=H}if(Z!==null)X.push(Z);else{if(X.length>0){let H=this.text_decoder.decode(Uint8Array.from(X));Q.push(H),X=[]}Q.push(K)}}if(X.length>0){let K=this.text_decoder.decode(Uint8Array.from(X));Q.push(K),X=[]}return Q}},RN=CN;function AN(J){if(J===null)return null;switch(J.type){case"ByteLevel":return new YN(J);case"WordPiece":return new VN(J);case"Metaspace":return new GN(J);case"BPEDecoder":return new FN(J);case"CTC":return new NN(J);case"Sequence":return new zN(J);case"Replace":return new BN(J);case"Fuse":return new MN(J);case"Strip":return new LN(J);case"ByteFallback":return new RN(J);default:throw Error(`Unknown Decoder type: ${J.type}`)}}var r$=AN,PN=class{constructor(J,Q){let X=mY(J,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(X)throw Error(X);let K=mY(Q,"Config");if(K)throw Error(K);this.tokenizer=J,this.config=Q,this.normalizer=d$(this.tokenizer.normalizer),this.pre_tokenizer=p$(this.tokenizer.pre_tokenizer),this.model=p3(this.tokenizer.model,this.config),this.post_processor=i$(this.tokenizer.post_processor),this.decoder=r$(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let Z=[],H=[];this.added_tokens_map=new Map;for(let Y of this.tokenizer.added_tokens){let $=new DU(Y);if(this.added_tokens.push($),this.model.tokens_to_ids.set($.content,$.id),this.model.vocab[$.id]=$.content,$.special)this.special_tokens.push($.content),this.all_special_ids.push($.id);if(this.added_tokens_map.set($.content,$),$.normalized&&this.normalizer!==null){let V=this.normalizer($.content);H.push(V),this.added_tokens_map.set(V,$)}else Z.push($.content)}if((this.config.additional_special_tokens??[]).forEach((Y)=>{if(!this.special_tokens.includes(Y))this.special_tokens.push(Y)}),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 lY(Z),this.splitter_normalized=new lY(H),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(J,{text_pair:Q=null,add_special_tokens:X=!0,return_token_type_ids:K=null}={}){let{tokens:Z,token_type_ids:H}=this.tokenize_helper(J,{text_pair:Q,add_special_tokens:X}),Y=Z.map((V)=>this.added_tokens_map.get(V)?.id??this.model.tokens_to_ids.get(V)??this.model.unk_token_id),$={ids:Y,tokens:Z,attention_mask:Array(Y.length).fill(1)};if(K&&H)$.token_type_ids=H;return $}decode(J,Q={}){if(!Array.isArray(J)||J.length===0||!PU(J[0]))throw Error("token_ids must be a non-empty array of integers.");let X=J.map((Z)=>this.model.vocab[Number(Z)]??this.model.unk_token);if(Q.skip_special_tokens)X=X.filter((Z)=>!this.special_tokens.includes(Z));let K=this.decoder?this.decoder(X):X.join(" ");if(this.decoder&&this.decoder.end_of_word_suffix){if(K=K.replaceAll(this.decoder.end_of_word_suffix," "),Q.skip_special_tokens)K=K.trim()}if(Q.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)K=wJ(K);return K}tokenize(J,{text_pair:Q=null,add_special_tokens:X=!1}={}){return this.tokenize_helper(J,{text_pair:Q,add_special_tokens:X}).tokens}encode_text(J){if(J===null)return null;let Q=this.splitter_unnormalized.split(J);return Q.forEach((X,K)=>{let Z=this.added_tokens_map.get(X);if(Z){if(Z.lstrip&&K>0)Q[K-1]=Q[K-1].trimEnd();if(Z.rstrip&&K{if(X.length===0)return[];if(this.added_tokens_map.has(X))return[X];if(this.remove_space===!0)X=X.trim().split(/\s+/).join(" ");if(this.do_lowercase_and_remove_accent)X=wU(X);if(this.normalizer!==null)X=this.normalizer(X);if(X.length===0)return[];let Z=this.splitter_normalized.split(X);return Z.forEach((H,Y)=>{let $=this.added_tokens_map.get(H);if($){if($.lstrip&&Y>0)Z[Y-1]=Z[Y-1].trimEnd();if($.rstrip&&Y{if(H.length===0)return[];if(this.added_tokens_map.has(H))return[H];let Y=this.pre_tokenizer!==null?this.pre_tokenizer(H,{section_index:K}):[H];return this.model(Y)})})}tokenize_helper(J,{text_pair:Q=null,add_special_tokens:X=!0}){let K=this.encode_text(J),Z=this.encode_text(Q||null);return this.post_processor?this.post_processor(K,Z,X):{tokens:y6(K??[],Z??[])}}token_to_id(J){return this.model.tokens_to_ids.get(J)}id_to_token(J){return this.model.vocab[J]}get_added_tokens_decoder(){let J=new Map;for(let Q of this.added_tokens)J.set(Q.id,Q);return J}get_vocab(J=!0){let Q=new Map;for(let X=0;X=",b.ComparisonBinaryOperator],["==",b.ComparisonBinaryOperator],["!=",b.ComparisonBinaryOperator],["<",b.ComparisonBinaryOperator],[">",b.ComparisonBinaryOperator],["+",b.AdditiveBinaryOperator],["-",b.AdditiveBinaryOperator],["~",b.AdditiveBinaryOperator],["*",b.MultiplicativeBinaryOperator],["/",b.MultiplicativeBinaryOperator],["%",b.MultiplicativeBinaryOperator],["=",b.Equals]],TN=new Map([["n",` `],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function IN(J,Q={}){if(J.endsWith(` `))J=J.slice(0,-1);if(Q.lstrip_blocks)J=J.replace(/^[ \t]*({[#%-])/gm,"$1");if(Q.trim_blocks)J=J.replace(/([#%-]})\n/g,"$1");return J.replace(/{%\s*(end)?generation\s*%}/gs,"")}function vN(J,Q={}){let X=[],K=IN(J,Q),Z=0,H=0,Y=(W)=>{let q="";while(W(K[Z])){if(K[Z]==="\\"){if(++Z,Z>=K.length)throw SyntaxError("Unexpected end of input");let F=K[Z++],N=TN.get(F);if(N===void 0)throw SyntaxError(`Unexpected escaped character: ${F}`);q+=N;continue}if(q+=K[Z++],Z>=K.length)throw SyntaxError("Unexpected end of input")}return q},$=()=>{let W=X.at(-1);if(W&&W.type===b.Text){if(W.value=W.value.trimEnd(),W.value==="")X.pop()}},V=()=>{while(Z0){X.push(new A6(F,b.Text));continue}}if(K[Z]==="{"&&K[Z+1]==="#"){Z+=2;let F=K[Z]==="-";if(F)++Z;let N="";while(K[Z]!=="#"||K[Z+1]!=="}"){if(Z+2>=K.length)throw SyntaxError("Missing end of comment tag");N+=K[Z++]}let j=N.endsWith("-");if(j)N=N.slice(0,-1);if(F)$();if(X.push(new A6(N,b.Comment)),Z+=2,j)V();continue}if(K.slice(Z,Z+3)==="{%-"){$(),X.push(new A6("{%",b.OpenStatement)),Z+=3;continue}if(K.slice(Z,Z+3)==="{{-"){$(),X.push(new A6("{{",b.OpenExpression)),H=0,Z+=3;continue}if(Y(oY),K.slice(Z,Z+3)==="-%}"){X.push(new A6("%}",b.CloseStatement)),Z+=3,V();continue}if(K.slice(Z,Z+3)==="-}}"){X.push(new A6("}}",b.CloseExpression)),Z+=3,V();continue}let q=K[Z];if(q==="-"||q==="+"){let F=X.at(-1)?.type;if(F===b.Text||F===void 0)throw SyntaxError(`Unexpected character: ${q}`);switch(F){case b.Identifier:case b.NumericLiteral:case b.StringLiteral:case b.CloseParen:case b.CloseSquareBracket:break;default:{++Z;let N=Y(i8);X.push(new A6(`${q}${N}`,N.length>0?b.NumericLiteral:b.UnaryOperator));continue}}}for(let[F,N]of wN){if(F==="}}"&&H>0)continue;if(K.slice(Z,Z+F.length)===F){if(X.push(new A6(F,N)),N===b.OpenExpression)H=0;else if(N===b.OpenCurlyBracket)++H;else if(N===b.CloseCurlyBracket)--H;Z+=F.length;continue J}}if(q==="'"||q==='"'){++Z;let F=Y((N)=>N!==q);X.push(new A6(F,b.StringLiteral)),++Z;continue}if(i8(q)){let F=Y(i8);if(K[Z]==="."&&i8(K[Z+1])){++Z;let N=Y(i8);F=`${F}.${N}`}X.push(new A6(F,b.NumericLiteral));continue}if(aY(q)){let F=Y(aY);X.push(new A6(F,b.Identifier));continue}throw SyntaxError(`Unexpected character: ${q}`)}return X}var _6=class{type="Statement"},yN=class extends _6{constructor(J){super();this.body=J}type="Program"},xN=class extends _6{constructor(J,Q,X){super();this.test=J,this.body=Q,this.alternate=X}type="If"},kN=class extends _6{constructor(J,Q,X,K){super();this.loopvar=J,this.iterable=Q,this.body=X,this.defaultBlock=K}type="For"},hN=class extends _6{type="Break"},bN=class extends _6{type="Continue"},fN=class extends _6{constructor(J,Q,X){super();this.assignee=J,this.value=Q,this.body=X}type="Set"},_N=class extends _6{constructor(J,Q,X){super();this.name=J,this.args=Q,this.body=X}type="Macro"},gN=class extends _6{constructor(J){super();this.value=J}type="Comment"},L6=class extends _6{type="Expression"},cN=class extends L6{constructor(J,Q,X){super();this.object=J,this.property=Q,this.computed=X}type="MemberExpression"},nY=class extends L6{constructor(J,Q){super();this.callee=J,this.args=Q}type="CallExpression"},Q8=class extends L6{constructor(J){super();this.value=J}type="Identifier"},N8=class extends L6{constructor(J){super();this.value=J}type="Literal"},lN=class extends N8{type="IntegerLiteral"},uN=class extends N8{type="FloatLiteral"},sY=class extends N8{type="StringLiteral"},mN=class extends N8{type="ArrayLiteral"},tY=class extends N8{type="TupleLiteral"},dN=class extends N8{type="ObjectLiteral"},r8=class extends L6{constructor(J,Q,X){super();this.operator=J,this.left=Q,this.right=X}type="BinaryExpression"},pN=class extends L6{constructor(J,Q){super();this.operand=J,this.filter=Q}type="FilterExpression"},iN=class extends _6{constructor(J,Q){super();this.filter=J,this.body=Q}type="FilterStatement"},rN=class extends L6{constructor(J,Q){super();this.lhs=J,this.test=Q}type="SelectExpression"},aN=class extends L6{constructor(J,Q,X){super();this.operand=J,this.negate=Q,this.test=X}type="TestExpression"},oN=class extends L6{constructor(J,Q){super();this.operator=J,this.argument=Q}type="UnaryExpression"},nN=class extends L6{constructor(J=void 0,Q=void 0,X=void 0){super();this.start=J,this.stop=Q,this.step=X}type="SliceExpression"},sN=class extends L6{constructor(J,Q){super();this.key=J,this.value=Q}type="KeywordArgumentExpression"},tN=class extends L6{constructor(J){super();this.argument=J}type="SpreadExpression"},eN=class extends _6{constructor(J,Q,X){super();this.call=J,this.callerArgs=Q,this.body=X}type="CallStatement"},Jj=class extends L6{constructor(J,Q,X){super();this.condition=J,this.trueExpr=Q,this.falseExpr=X}type="Ternary"};function Qj(J){let Q=new yN([]),X=0;function K(x,h){let _=J[X++];if(!_||_.type!==x)throw Error(`Parser Error: ${h}. ${_.type} !== ${x}.`);return _}function Z(x){if(!V(x))throw SyntaxError(`Expected ${x}`);++X}function H(){switch(J[X].type){case b.Comment:return new gN(J[X++].value);case b.Text:return W();case b.OpenStatement:return q();case b.OpenExpression:return F();default:throw SyntaxError(`Unexpected token type: ${J[X].type}`)}}function Y(...x){return X+x.length<=J.length&&x.every((h,_)=>h===J[X+_].type)}function $(...x){return J[X]?.type===b.OpenStatement&&J[X+1]?.type===b.Identifier&&x.includes(J[X+1]?.value)}function V(...x){return X+x.length<=J.length&&x.every((h,_)=>J[X+_].type==="Identifier"&&h===J[X+_].value)}function W(){return new sY(K(b.Text,"Expected text token").value)}function q(){if(K(b.OpenStatement,"Expected opening statement token"),J[X].type!==b.Identifier)throw SyntaxError(`Unknown statement, got ${J[X].type}`);let x=J[X].value,h;switch(x){case"set":++X,h=N();break;case"if":++X,h=j(),K(b.OpenStatement,"Expected {% token"),Z("endif"),K(b.CloseStatement,"Expected %} token");break;case"macro":++X,h=B(),K(b.OpenStatement,"Expected {% token"),Z("endmacro"),K(b.CloseStatement,"Expected %} token");break;case"for":++X,h=L(),K(b.OpenStatement,"Expected {% token"),Z("endfor"),K(b.CloseStatement,"Expected %} token");break;case"call":{++X;let _=null;if(Y(b.OpenParen))_=d();let a=Q0();if(a.type!=="Identifier")throw SyntaxError("Expected identifier following call statement");let q0=d();K(b.CloseStatement,"Expected closing statement token");let v0=[];while(!$("endcall"))v0.push(H());K(b.OpenStatement,"Expected '{%'"),Z("endcall"),K(b.CloseStatement,"Expected closing statement token");let J0=new nY(a,q0);h=new eN(J0,_,v0);break}case"break":++X,K(b.CloseStatement,"Expected closing statement token"),h=new hN;break;case"continue":++X,K(b.CloseStatement,"Expected closing statement token"),h=new bN;break;case"filter":{++X;let _=Q0();if(_ instanceof Q8&&Y(b.OpenParen))_=g(_);K(b.CloseStatement,"Expected closing statement token");let a=[];while(!$("endfilter"))a.push(H());K(b.OpenStatement,"Expected '{%'"),Z("endfilter"),K(b.CloseStatement,"Expected '%}'"),h=new iN(_,a);break}default:throw SyntaxError(`Unknown statement type: ${x}`)}return h}function F(){K(b.OpenExpression,"Expected opening expression token");let x=M();return K(b.CloseExpression,"Expected closing expression token"),x}function N(){let x=D(),h=null,_=[];if(Y(b.Equals))++X,h=D();else{K(b.CloseStatement,"Expected %} token");while(!$("endset"))_.push(H());K(b.OpenStatement,"Expected {% token"),Z("endset")}return K(b.CloseStatement,"Expected closing statement token"),new fN(x,h,_)}function j(){let x=M();K(b.CloseStatement,"Expected closing statement token");let h=[],_=[];while(!$("elif","else","endif"))h.push(H());if($("elif")){++X,++X;let a=j();_.push(a)}else if($("else")){++X,++X,K(b.CloseStatement,"Expected closing statement token");while(!$("endif"))_.push(H())}return new xN(x,h,_)}function B(){let x=Q0();if(x.type!=="Identifier")throw SyntaxError("Expected identifier following macro statement");let h=d();K(b.CloseStatement,"Expected closing statement token");let _=[];while(!$("endmacro"))_.push(H());return new _N(x,h,_)}function D(x=!1){let h=x?Q0:M,_=[h()],a=Y(b.Comma);while(a)if(++X,_.push(h()),!Y(b.Comma))break;return a?new tY(_):_[0]}function L(){let x=D(!0);if(!(x instanceof Q8||x instanceof tY))throw SyntaxError(`Expected identifier/tuple for the loop variable, got ${x.type} instead`);if(!V("in"))throw SyntaxError("Expected `in` keyword following loop variable");++X;let h=M();K(b.CloseStatement,"Expected closing statement token");let _=[];while(!$("endfor","else"))_.push(H());let a=[];if($("else")){++X,++X,K(b.CloseStatement,"Expected closing statement token");while(!$("endfor"))a.push(H())}return new kN(x,h,_,a)}function M(){return R()}function R(){let x=E();if(V("if")){++X;let h=E();if(V("else")){++X;let _=R();return new Jj(h,x,_)}else return new rN(x,h)}return x}function E(){let x=P();while(V("or")){let h=J[X];++X;let _=P();x=new r8(h,x,_)}return x}function P(){let x=w();while(V("and")){let h=J[X];++X;let _=w();x=new r8(h,x,_)}return x}function w(){let x;while(V("not")){let h=J[X];++X;let _=w();x=new oN(h,_)}return x??k()}function k(){let x=C();while(!0){let h;if(V("not","in"))h=new A6("not in",b.Identifier),X+=2;else if(V("in"))h=J[X++];else if(Y(b.ComparisonBinaryOperator))h=J[X++];else break;let _=C();x=new r8(h,x,_)}return x}function C(){let x=f();while(Y(b.AdditiveBinaryOperator)){let h=J[X];++X;let _=f();x=new r8(h,x,_)}return x}function c(){let x=p(Q0());if(Y(b.OpenParen))return g(x);return x}function g(x){let h=new nY(x,d());if(h=p(h),Y(b.OpenParen))h=g(h);return h}function d(){K(b.OpenParen,"Expected opening parenthesis for arguments list");let x=r();return K(b.CloseParen,"Expected closing parenthesis for arguments list"),x}function r(){let x=[];while(!Y(b.CloseParen)){let h;if(J[X].type===b.MultiplicativeBinaryOperator&&J[X].value==="*"){++X;let _=M();h=new tN(_)}else if(h=M(),Y(b.Equals)){if(++X,!(h instanceof Q8))throw SyntaxError("Expected identifier for keyword argument");let _=M();h=new sN(h,_)}if(x.push(h),Y(b.Comma))++X}return x}function i(){let x=[],h=!1;while(!Y(b.CloseSquareBracket))if(Y(b.Colon))x.push(void 0),++X,h=!0;else if(x.push(M()),Y(b.Colon))++X,h=!0;if(x.length===0)throw SyntaxError("Expected at least one argument for member/slice expression");if(h){if(x.length>3)throw SyntaxError("Expected 0-3 arguments for slice expression");return new nN(...x)}return x[0]}function p(x){while(Y(b.Dot)||Y(b.OpenSquareBracket)){let h=J[X];++X;let _,a=h.type===b.OpenSquareBracket;if(a)_=i(),K(b.CloseSquareBracket,"Expected closing square bracket");else if(_=Q0(),_.type!=="Identifier")throw SyntaxError("Expected identifier following dot operator");x=new cN(x,_,a)}return x}function f(){let x=v();while(Y(b.MultiplicativeBinaryOperator)){let h=J[X++],_=v();x=new r8(h,x,_)}return x}function v(){let x=o();while(V("is")){++X;let h=V("not");if(h)++X;let _=Q0();if(!(_ instanceof Q8))throw SyntaxError("Expected identifier for the test");x=new aN(x,h,_)}return x}function o(){let x=c();while(Y(b.Pipe)){++X;let h=Q0();if(!(h instanceof Q8))throw SyntaxError("Expected identifier for the filter");if(Y(b.OpenParen))h=g(h);x=new pN(x,h)}return x}function Q0(){let x=J[X++];switch(x.type){case b.NumericLiteral:{let h=x.value;return h.includes(".")?new uN(Number(h)):new lN(Number(h))}case b.StringLiteral:{let h=x.value;while(Y(b.StringLiteral))h+=J[X++].value;return new sY(h)}case b.Identifier:return new Q8(x.value);case b.OpenParen:{let h=D();return K(b.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),h}case b.OpenSquareBracket:{let h=[];while(!Y(b.CloseSquareBracket))if(h.push(M()),Y(b.Comma))++X;return++X,new mN(h)}case b.OpenCurlyBracket:{let h=new Map;while(!Y(b.CloseCurlyBracket)){let _=M();K(b.Colon,"Expected colon between key and value in object literal");let a=M();if(h.set(_,a),Y(b.Comma))++X}return++X,new dN(h)}default:throw SyntaxError(`Unexpected token: ${x.type}`)}}while(X0)for(let Z=J;ZQ;Z+=X)K.push(Z);return K}function eY(J,Q,X,K=1){let Z=Math.sign(K);if(Z>=0)Q=(Q??=0)<0?Math.max(J.length+Q,0):Math.min(Q,J.length),X=(X??=J.length)<0?Math.max(J.length+X,0):Math.min(X,J.length);else Q=(Q??=J.length-1)<0?Math.max(J.length+Q,-1):Math.min(Q,J.length-1),X=(X??=-1)<-1?Math.max(J.length+X,-1):Math.min(X,J.length-1);let H=[];for(let Y=Q;Z*YQ.toUpperCase())}function Zj(J){return Hj(new Date,J)}function Hj(J,Q){let X=new Intl.DateTimeFormat(void 0,{month:"long"}),K=new Intl.DateTimeFormat(void 0,{month:"short"}),Z=(H)=>H<10?"0"+H:H.toString();return Q.replace(/%[YmdbBHM%]/g,(H)=>{switch(H){case"%Y":return J.getFullYear().toString();case"%m":return Z(J.getMonth()+1);case"%d":return Z(J.getDate());case"%b":return K.format(J);case"%B":return X.format(J);case"%H":return Z(J.getHours());case"%M":return Z(J.getMinutes());case"%%":return"%";default:return H}})}function Yj(J){return J.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $j(J,Q,X,K){if(K===0)return J;let Z=K==null||K<0?1/0:K,H=Q.length===0?new RegExp("(?=)","gu"):new RegExp(Yj(Q),"gu");return J.replaceAll(H,(Y)=>{if(Z>0)return--Z,X;return Y})}var J$=class extends Error{},Q$=class extends Error{},n6=class{type="RuntimeValue";value;builtins=new Map;constructor(J=void 0){this.value=J}__bool__(){return new H0(!!this.value)}toString(){return String(this.value)}},W0=class extends n6{type="IntegerValue"},_0=class extends n6{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},s=class extends n6{type="StringValue";builtins=new Map([["upper",new k0(()=>{return new s(this.value.toUpperCase())})],["lower",new k0(()=>{return new s(this.value.toLowerCase())})],["strip",new k0(()=>{return new s(this.value.trim())})],["title",new k0(()=>{return new s(Kj(this.value))})],["capitalize",new k0(()=>{return new s(this.value.charAt(0).toUpperCase()+this.value.slice(1))})],["length",new W0(this.value.length)],["rstrip",new k0(()=>{return new s(this.value.trimEnd())})],["lstrip",new k0(()=>{return new s(this.value.trimStart())})],["startswith",new k0((J)=>{if(J.length===0)throw Error("startswith() requires at least one argument");let Q=J[0];if(Q instanceof s)return new H0(this.value.startsWith(Q.value));else if(Q instanceof j0){for(let X of Q.value){if(!(X instanceof s))throw Error("startswith() tuple elements must be strings");if(this.value.startsWith(X.value))return new H0(!0)}return new H0(!1)}throw Error("startswith() argument must be a string or tuple of strings")})],["endswith",new k0((J)=>{if(J.length===0)throw Error("endswith() requires at least one argument");let Q=J[0];if(Q instanceof s)return new H0(this.value.endsWith(Q.value));else if(Q instanceof j0){for(let X of Q.value){if(!(X instanceof s))throw Error("endswith() tuple elements must be strings");if(this.value.endsWith(X.value))return new H0(!0)}return new H0(!1)}throw Error("endswith() argument must be a string or tuple of strings")})],["split",new k0((J)=>{let Q=J[0]??new f0;if(!(Q instanceof s||Q instanceof f0))throw Error("sep argument must be a string or null");let X=J[1]??new W0(-1);if(!(X instanceof W0))throw Error("maxsplit argument must be a number");let K=[];if(Q instanceof f0){let Z=this.value.trimStart();for(let{0:H,index:Y}of Z.matchAll(/\S+/g)){if(X.value!==-1&&K.length>=X.value&&Y!==void 0){K.push(H+Z.slice(Y+H.length));break}K.push(H)}}else{if(Q.value==="")throw Error("empty separator");if(K=this.value.split(Q.value),X.value!==-1&&K.length>X.value)K.push(K.splice(X.value).join(Q.value))}return new j0(K.map((Z)=>new s(Z)))})],["replace",new k0((J)=>{if(J.length<2)throw Error("replace() requires at least two arguments");let Q=J[0],X=J[1];if(!(Q instanceof s&&X instanceof s))throw Error("replace() arguments must be strings");let K;if(J.length>2)if(J[2].type==="KeywordArgumentsValue")K=J[2].value.get("count")??new f0;else K=J[2];else K=new f0;if(!(K instanceof W0||K instanceof f0))throw Error("replace() count argument must be a number or null");return new s($j(this.value,Q.value,X.value,K.value))})]])},H0=class extends n6{type="BooleanValue"},Vj=/[\x7f-\uffff]/g;function X$(J){return J.replace(Vj,(Q)=>"\\u"+Q.charCodeAt(0).toString(16).padStart(4,"0"))}function u5(J,Q={},X=0,K=!0){let{indent:Z=null,ensureAscii:H=!1,separators:Y=null,sortKeys:$=!1}=Q,V,W;if(Y)[V,W]=Y;else if(Z)V=",",W=": ";else V=", ",W=": ";switch(J.type){case"NullValue":return"null";case"UndefinedValue":return K?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(J.value);case"StringValue":{let q=JSON.stringify(J.value);if(H)q=X$(q);return q}case"ArrayValue":case"ObjectValue":{let q=Z?" ".repeat(Z):"",F=` `+q.repeat(X),N=F+q;if(J.type==="ArrayValue"){let j=J.value.map((B)=>u5(B,Q,X+1,K));return Z?`[${N}${j.join(`${V}${N}`)}${F}]`:`[${j.join(V)}]`}else{let j=Array.from(J.value.entries());if($)j=j.sort(([D],[L])=>D.localeCompare(L));let B=j.map(([D,L])=>{let M=JSON.stringify(D);if(H)M=X$(M);let R=`${M}${W}${u5(L,Q,X+1,K)}`;return Z?`${N}${R}`:R});return Z?`{${B.join(V)}${F}}`:`{${B.join(V)}}`}}default:throw Error(`Cannot convert to JSON: ${J.type}`)}}var t0=class extends n6{type="ObjectValue";__bool__(){return new H0(this.value.size>0)}builtins=new Map([["get",new k0(([J,Q])=>{if(!(J instanceof s))throw Error(`Object key must be a string: got ${J.type}`);return this.value.get(J.value)??Q??new f0})],["items",new k0(()=>this.items())],["keys",new k0(()=>this.keys())],["values",new k0(()=>this.values())],["dictsort",new k0((J)=>{let Q=new Map,X=J.filter(($)=>{if($ instanceof a8)return Q=$.value,!1;return!0}),K=X.at(0)??Q.get("case_sensitive")??new H0(!1);if(!(K instanceof H0))throw Error("case_sensitive must be a boolean");let Z=X.at(1)??Q.get("by")??new s("key");if(!(Z instanceof s))throw Error("by must be a string");if(!["key","value"].includes(Z.value))throw Error("by must be either 'key' or 'value'");let H=X.at(2)??Q.get("reverse")??new H0(!1);if(!(H instanceof H0))throw Error("reverse must be a boolean");let Y=Array.from(this.value.entries()).map(([$,V])=>new j0([new s($),V])).sort(($,V)=>{let W=Z.value==="key"?0:1,q=$.value[W],F=V.value[W],N=UJ(q,F,K.value);return H.value?-N:N});return new j0(Y)})]]);items(){return new j0(Array.from(this.value.entries()).map(([J,Q])=>new j0([new s(J),Q])))}keys(){return new j0(Array.from(this.value.keys()).map((J)=>new s(J)))}values(){return new j0(Array.from(this.value.values()))}toString(){return u5(this,{},0,!1)}},a8=class extends t0{type="KeywordArgumentsValue"},j0=class extends n6{type="ArrayValue";builtins=new Map([["length",new W0(this.value.length)]]);__bool__(){return new H0(this.value.length>0)}toString(){return u5(this,{},0,!1)}},K$=class extends j0{type="TupleValue"},k0=class extends n6{type="FunctionValue"},f0=class extends n6{type="NullValue"},x0=class extends n6{type="UndefinedValue"},c5=class{constructor(J){this.parent=J}variables=new Map([["namespace",new k0((J)=>{if(J.length===0)return new t0(new Map);if(J.length!==1||!(J[0]instanceof t0))throw Error("`namespace` expects either zero arguments or a single object argument");return J[0]})]]);tests=new Map([["boolean",(J)=>J.type==="BooleanValue"],["callable",(J)=>J instanceof k0],["odd",(J)=>{if(!(J instanceof W0))throw Error(`cannot odd on ${J.type}`);return J.value%2!==0}],["even",(J)=>{if(!(J instanceof W0))throw Error(`cannot even on ${J.type}`);return J.value%2===0}],["false",(J)=>J.type==="BooleanValue"&&!J.value],["true",(J)=>J.type==="BooleanValue"&&J.value],["none",(J)=>J.type==="NullValue"],["string",(J)=>J.type==="StringValue"],["number",(J)=>J instanceof W0||J instanceof _0],["integer",(J)=>J instanceof W0],["iterable",(J)=>J.type==="ArrayValue"||J.type==="StringValue"],["mapping",(J)=>J instanceof t0],["sequence",(J)=>J instanceof j0||J instanceof t0||J instanceof s],["lower",(J)=>{let Q=J.value;return J.type==="StringValue"&&Q===Q.toLowerCase()}],["upper",(J)=>{let Q=J.value;return J.type==="StringValue"&&Q===Q.toUpperCase()}],["none",(J)=>J.type==="NullValue"],["defined",(J)=>J.type!=="UndefinedValue"],["undefined",(J)=>J.type==="UndefinedValue"],["equalto",(J,Q)=>J.value===Q.value],["eq",(J,Q)=>J.value===Q.value]]);set(J,Q){return this.declareVariable(J,i9(Q))}declareVariable(J,Q){if(this.variables.has(J))throw SyntaxError(`Variable already declared: ${J}`);return this.variables.set(J,Q),Q}setVariable(J,Q){return this.variables.set(J,Q),Q}resolve(J){if(this.variables.has(J))return this;if(this.parent)return this.parent.resolve(J);throw Error(`Unknown variable: ${J}`)}lookupVariable(J){try{return this.resolve(J).variables.get(J)??new x0}catch{return new x0}}};function Wj(J){J.set("false",!1),J.set("true",!0),J.set("none",null),J.set("raise_exception",(Q)=>{throw Error(Q)}),J.set("range",Xj),J.set("strftime_now",Zj),J.set("True",!0),J.set("False",!1),J.set("None",null)}function Z$(J,Q){let X=Q.split("."),K=J;for(let Z of X)if(K instanceof t0)K=K.value.get(Z)??new x0;else if(K instanceof j0){let H=parseInt(Z,10);if(!isNaN(H)&&H>=0&&HH instanceof W0||H instanceof _0||H instanceof H0,Z=(H)=>{if(H instanceof H0)return H.value?1:0;return H.value};if(K(J)&&K(Q)){let H=Z(J),Y=Z(Q);return HY?1:0}if(J.type!==Q.type)throw Error(`Cannot compare different types: ${J.type} and ${Q.type}`);switch(J.type){case"StringValue":{let H=J.value,Y=Q.value;if(!X)H=H.toLowerCase(),Y=Y.toLowerCase();return HY?1:0}default:throw Error(`Cannot compare type: ${J.type}`)}}var Gj=class{global;constructor(J){this.global=J??new c5}run(J){return this.evaluate(J,this.global)}evaluateBinaryExpression(J,Q){let X=this.evaluate(J.left,Q);switch(J.operator.value){case"and":return X.__bool__().value?this.evaluate(J.right,Q):X;case"or":return X.__bool__().value?X:this.evaluate(J.right,Q)}let K=this.evaluate(J.right,Q);switch(J.operator.value){case"==":return new H0(X.value==K.value);case"!=":return new H0(X.value!=K.value)}if(X instanceof x0||K instanceof x0){if(K instanceof x0&&["in","not in"].includes(J.operator.value))return new H0(J.operator.value==="not in");throw Error(`Cannot perform operation ${J.operator.value} on undefined values`)}else if(X instanceof f0||K instanceof f0)throw Error("Cannot perform operation on null values");else if(J.operator.value==="~")return new s(X.value.toString()+K.value.toString());else if((X instanceof W0||X instanceof _0)&&(K instanceof W0||K instanceof _0)){let Z=X.value,H=K.value;switch(J.operator.value){case"+":case"-":case"*":{let Y=J.operator.value==="+"?Z+H:J.operator.value==="-"?Z-H:Z*H;return X instanceof _0||K instanceof _0?new _0(Y):new W0(Y)}case"/":return new _0(Z/H);case"%":{let Y=Z%H;return X instanceof _0||K instanceof _0?new _0(Y):new W0(Y)}case"<":return new H0(Z":return new H0(Z>H);case">=":return new H0(Z>=H);case"<=":return new H0(Z<=H)}}else if(X instanceof j0&&K instanceof j0)switch(J.operator.value){case"+":return new j0(X.value.concat(K.value))}else if(K instanceof j0){let Z=K.value.find((H)=>H.value===X.value)!==void 0;switch(J.operator.value){case"in":return new H0(Z);case"not in":return new H0(!Z)}}if(X instanceof s||K instanceof s)switch(J.operator.value){case"+":return new s(X.value.toString()+K.value.toString())}if(X instanceof s&&K instanceof s)switch(J.operator.value){case"in":return new H0(K.value.includes(X.value));case"not in":return new H0(!K.value.includes(X.value))}if(X instanceof s&&K instanceof t0)switch(J.operator.value){case"in":return new H0(K.value.has(X.value));case"not in":return new H0(!K.value.has(X.value))}throw SyntaxError(`Unknown operator "${J.operator.value}" between ${X.type} and ${K.type}`)}evaluateArguments(J,Q){let X=[],K=new Map;for(let Z of J)if(Z.type==="SpreadExpression"){let H=Z,Y=this.evaluate(H.argument,Q);if(!(Y instanceof j0))throw Error(`Cannot unpack non-iterable type: ${Y.type}`);for(let $ of Y.value)X.push($)}else if(Z.type==="KeywordArgumentExpression"){let H=Z;K.set(H.key.value,this.evaluate(H.value,Q))}else{if(K.size>0)throw Error("Positional arguments must come before keyword arguments");X.push(this.evaluate(Z,Q))}return[X,K]}applyFilter(J,Q,X){if(Q.type==="Identifier"){let K=Q;if(K.value==="safe")return J;if(K.value==="tojson")return new s(u5(J,{}));if(J instanceof j0)switch(K.value){case"list":return J;case"first":return J.value[0];case"last":return J.value[J.value.length-1];case"length":return new W0(J.value.length);case"reverse":return new j0(J.value.slice().reverse());case"sort":return new j0(J.value.slice().sort((Z,H)=>UJ(Z,H,!1)));case"join":return new s(J.value.map((Z)=>Z.value).join(""));case"string":return new s(u5(J,{},0,!1));case"unique":{let Z=new Set,H=[];for(let Y of J.value)if(!Z.has(Y.value))Z.add(Y.value),H.push(Y);return new j0(H)}default:throw Error(`Unknown ArrayValue filter: ${K.value}`)}else if(J instanceof s)switch(K.value){case"length":case"upper":case"lower":case"title":case"capitalize":{let Z=J.builtins.get(K.value);if(Z instanceof k0)return Z.value([],X);else if(Z instanceof W0)return Z;else throw Error(`Unknown StringValue filter: ${K.value}`)}case"trim":return new s(J.value.trim());case"indent":return new s(J.value.split(` `).map((Z,H)=>H===0||Z.length===0?Z:" "+Z).join(` `));case"join":case"string":return J;case"int":{let Z=parseInt(J.value,10);return new W0(isNaN(Z)?0:Z)}case"float":{let Z=parseFloat(J.value);return new _0(isNaN(Z)?0:Z)}default:throw Error(`Unknown StringValue filter: ${K.value}`)}else if(J instanceof W0||J instanceof _0)switch(K.value){case"abs":return J instanceof W0?new W0(Math.abs(J.value)):new _0(Math.abs(J.value));case"int":return new W0(Math.floor(J.value));case"float":return new _0(J.value);case"string":return new s(J.toString());default:throw Error(`Unknown NumericValue filter: ${K.value}`)}else if(J instanceof t0)switch(K.value){case"items":return new j0(Array.from(J.value.entries()).map(([Z,H])=>new j0([new s(Z),H])));case"length":return new W0(J.value.size);default:{let Z=J.builtins.get(K.value);if(Z){if(Z instanceof k0)return Z.value([],X);return Z}throw Error(`Unknown ObjectValue filter: ${K.value}`)}}else if(J instanceof H0)switch(K.value){case"bool":return new H0(J.value);case"int":return new W0(J.value?1:0);case"float":return new _0(J.value?1:0);case"string":return new s(J.value?"true":"false");default:throw Error(`Unknown BooleanValue filter: ${K.value}`)}throw Error(`Cannot apply filter "${K.value}" to type: ${J.type}`)}else if(Q.type==="CallExpression"){let K=Q;if(K.callee.type!=="Identifier")throw Error(`Unknown filter: ${K.callee.type}`);let Z=K.callee.value;if(Z==="tojson"){let[,H]=this.evaluateArguments(K.args,X),Y=H.get("indent")??new f0;if(!(Y instanceof W0||Y instanceof f0))throw Error("If set, indent must be a number");let $=H.get("ensure_ascii")??new H0(!1);if(!($ instanceof H0))throw Error("If set, ensure_ascii must be a boolean");let V=H.get("sort_keys")??new H0(!1);if(!(V instanceof H0))throw Error("If set, sort_keys must be a boolean");let W=H.get("separators")??new f0,q=null;if(W instanceof j0||W instanceof K$){if(W.value.length!==2)throw Error("separators must be a tuple of two strings");let[F,N]=W.value;if(!(F instanceof s)||!(N instanceof s))throw Error("separators must be a tuple of two strings");q=[F.value,N.value]}else if(!(W instanceof f0))throw Error("If set, separators must be a tuple of two strings");return new s(u5(J,{indent:Y.value,ensureAscii:$.value,sortKeys:V.value,separators:q}))}else if(Z==="join"){let H;if(J instanceof s)H=Array.from(J.value);else if(J instanceof j0)H=J.value.map((W)=>W.value);else throw Error(`Cannot apply filter "${Z}" to type: ${J.type}`);let[Y,$]=this.evaluateArguments(K.args,X),V=Y.at(0)??$.get("separator")??new s("");if(!(V instanceof s))throw Error("separator must be a string");return new s(H.join(V.value))}else if(Z==="int"||Z==="float"){let[H,Y]=this.evaluateArguments(K.args,X),$=H.at(0)??Y.get("default")??(Z==="int"?new W0(0):new _0(0));if(J instanceof s){let V=Z==="int"?parseInt(J.value,10):parseFloat(J.value);return isNaN(V)?$:Z==="int"?new W0(V):new _0(V)}else if(J instanceof W0||J instanceof _0)return J;else if(J instanceof H0)return Z==="int"?new W0(J.value?1:0):new _0(J.value?1:0);else throw Error(`Cannot apply filter "${Z}" to type: ${J.type}`)}else if(Z==="default"){let[H,Y]=this.evaluateArguments(K.args,X),$=H[0]??new s(""),V=H[1]??Y.get("boolean")??new H0(!1);if(!(V instanceof H0))throw Error("`default` filter flag must be a boolean");if(J instanceof x0||V.value&&!J.__bool__().value)return $;return J}if(J instanceof j0){switch(Z){case"sort":{let[H,Y]=this.evaluateArguments(K.args,X),$=H.at(0)??Y.get("reverse")??new H0(!1);if(!($ instanceof H0))throw Error("reverse must be a boolean");let V=H.at(1)??Y.get("case_sensitive")??new H0(!1);if(!(V instanceof H0))throw Error("case_sensitive must be a boolean");let W=H.at(2)??Y.get("attribute")??new f0;if(!(W instanceof s||W instanceof W0||W instanceof f0))throw Error("attribute must be a string, integer, or null");let q=(F)=>{if(W instanceof f0)return F;let N=W instanceof W0?String(W.value):W.value;return Z$(F,N)};return new j0(J.value.slice().sort((F,N)=>{let j=q(F),B=q(N),D=UJ(j,B,V.value);return $.value?-D:D}))}case"selectattr":case"rejectattr":{let H=Z==="selectattr";if(J.value.some((F)=>!(F instanceof t0)))throw Error(`\`${Z}\` can only be applied to array of objects`);if(K.args.some((F)=>F.type!=="StringLiteral"))throw Error(`arguments of \`${Z}\` must be strings`);let[Y,$,V]=K.args.map((F)=>this.evaluate(F,X)),W;if($){let F=X.tests.get($.value);if(!F)throw Error(`Unknown test: ${$.value}`);W=F}else W=(...F)=>F[0].__bool__().value;let q=J.value.filter((F)=>{let N=F.value.get(Y.value),j=N?W(N,V):!1;return H?j:!j});return new j0(q)}case"map":{let[,H]=this.evaluateArguments(K.args,X);if(H.has("attribute")){let Y=H.get("attribute");if(!(Y instanceof s))throw Error("attribute must be a string");let $=H.get("default"),V=J.value.map((W)=>{if(!(W instanceof t0))throw Error("items in map must be an object");let q=Z$(W,Y.value);return q instanceof x0?$??new x0:q});return new j0(V)}else throw Error("`map` expressions without `attribute` set are not currently supported.")}}throw Error(`Unknown ArrayValue filter: ${Z}`)}else if(J instanceof s){switch(Z){case"indent":{let[H,Y]=this.evaluateArguments(K.args,X),$=H.at(0)??Y.get("width")??new W0(4);if(!($ instanceof W0))throw Error("width must be a number");let V=H.at(1)??Y.get("first")??new H0(!1),W=H.at(2)??Y.get("blank")??new H0(!1),q=J.value.split(` `),F=" ".repeat($.value),N=q.map((j,B)=>!V.value&&B===0||!W.value&&j.length===0?j:F+j);return new s(N.join(` `))}case"replace":{let H=J.builtins.get("replace");if(!(H instanceof k0))throw Error("replace filter not available");let[Y,$]=this.evaluateArguments(K.args,X);return H.value([...Y,new a8($)],X)}}throw Error(`Unknown StringValue filter: ${Z}`)}else if(J instanceof t0){let H=J.builtins.get(Z);if(H&&H instanceof k0){let[Y,$]=this.evaluateArguments(K.args,X);if($.size>0)Y.push(new a8($));return H.value(Y,X)}throw Error(`Unknown ObjectValue filter: ${Z}`)}else throw Error(`Cannot apply filter "${Z}" to type: ${J.type}`)}throw Error(`Unknown filter: ${Q.type}`)}evaluateFilterExpression(J,Q){let X=this.evaluate(J.operand,Q);return this.applyFilter(X,J.filter,Q)}evaluateTestExpression(J,Q){let X=this.evaluate(J.operand,Q),K=Q.tests.get(J.test.value);if(!K)throw Error(`Unknown test: ${J.test.value}`);let Z=K(X);return new H0(J.negate?!Z:Z)}evaluateSelectExpression(J,Q){if(!this.evaluate(J.test,Q).__bool__().value)return new x0;return this.evaluate(J.lhs,Q)}evaluateUnaryExpression(J,Q){let X=this.evaluate(J.argument,Q);switch(J.operator.value){case"not":return new H0(!X.value);default:throw SyntaxError(`Unknown operator: ${J.operator.value}`)}}evaluateTernaryExpression(J,Q){return this.evaluate(J.condition,Q).__bool__().value?this.evaluate(J.trueExpr,Q):this.evaluate(J.falseExpr,Q)}evalProgram(J,Q){return this.evaluateBlock(J.body,Q)}evaluateBlock(J,Q){let X="";for(let K of J){let Z=this.evaluate(K,Q);if(Z.type!=="NullValue"&&Z.type!=="UndefinedValue")X+=Z.toString()}return new s(X)}evaluateIdentifier(J,Q){return Q.lookupVariable(J.value)}evaluateCallExpression(J,Q){let[X,K]=this.evaluateArguments(J.args,Q);if(K.size>0)X.push(new a8(K));let Z=this.evaluate(J.callee,Q);if(Z.type!=="FunctionValue")throw Error(`Cannot call something that is not a function: got ${Z.type}`);return Z.value(X,Q)}evaluateSliceExpression(J,Q,X){if(!(J instanceof j0||J instanceof s))throw Error("Slice object must be an array or string");let K=this.evaluate(Q.start,X),Z=this.evaluate(Q.stop,X),H=this.evaluate(Q.step,X);if(!(K instanceof W0||K instanceof x0))throw Error("Slice start must be numeric or undefined");if(!(Z instanceof W0||Z instanceof x0))throw Error("Slice stop must be numeric or undefined");if(!(H instanceof W0||H instanceof x0))throw Error("Slice step must be numeric or undefined");if(J instanceof j0)return new j0(eY(J.value,K.value,Z.value,H.value));else return new s(eY(Array.from(J.value),K.value,Z.value,H.value).join(""))}evaluateMemberExpression(J,Q){let X=this.evaluate(J.object,Q),K;if(J.computed)if(J.property.type==="SliceExpression")return this.evaluateSliceExpression(X,J.property,Q);else K=this.evaluate(J.property,Q);else K=new s(J.property.value);let Z;if(X instanceof t0){if(!(K instanceof s))throw Error(`Cannot access property with non-string: got ${K.type}`);Z=X.value.get(K.value)??X.builtins.get(K.value)}else if(X instanceof j0||X instanceof s)if(K instanceof W0){if(Z=X.value.at(K.value),X instanceof s)Z=new s(X.value.at(K.value))}else if(K instanceof s)Z=X.builtins.get(K.value);else throw Error(`Cannot access property with non-string/non-number: got ${K.type}`);else{if(!(K instanceof s))throw Error(`Cannot access property with non-string: got ${K.type}`);Z=X.builtins.get(K.value)}return Z instanceof n6?Z:new x0}evaluateSet(J,Q){let X=J.value?this.evaluate(J.value,Q):this.evaluateBlock(J.body,Q);if(J.assignee.type==="Identifier"){let K=J.assignee.value;Q.setVariable(K,X)}else if(J.assignee.type==="TupleLiteral"){let K=J.assignee;if(!(X instanceof j0))throw Error(`Cannot unpack non-iterable type in set: ${X.type}`);let Z=X.value;if(Z.length!==K.value.length)throw Error(`Too ${K.value.length>Z.length?"few":"many"} items to unpack in set`);for(let H=0;Hj.setVariable(J.loopvar.value,F);else if(J.loopvar.type==="TupleLiteral"){let j=J.loopvar;if(F.type!=="ArrayValue")throw Error(`Cannot unpack non-iterable type: ${F.type}`);let B=F;if(j.value.length!==B.value.length)throw Error(`Too ${j.value.length>B.value.length?"few":"many"} items to unpack`);N=(D)=>{for(let L=0;L0?H[W-1]:new x0],["nextitem",W{let Z=new c5(K);X=X.slice();let H;if(X.at(-1)?.type==="KeywordArgumentsValue")H=X.pop();for(let Y=0;Y{let W=new c5(V);if(J.callerArgs)for(let q=0;qthis.evaluate(X,Q)));case"TupleLiteral":return new K$(J.value.map((X)=>this.evaluate(X,Q)));case"ObjectLiteral":{let X=new Map;for(let[K,Z]of J.value){let H=this.evaluate(K,Q);if(!(H instanceof s))throw Error(`Object keys must be strings: got ${H.type}`);X.set(H.value,this.evaluate(Z,Q))}return new t0(X)}case"Identifier":return this.evaluateIdentifier(J,Q);case"CallExpression":return this.evaluateCallExpression(J,Q);case"MemberExpression":return this.evaluateMemberExpression(J,Q);case"UnaryExpression":return this.evaluateUnaryExpression(J,Q);case"BinaryExpression":return this.evaluateBinaryExpression(J,Q);case"FilterExpression":return this.evaluateFilterExpression(J,Q);case"FilterStatement":return this.evaluateFilterStatement(J,Q);case"TestExpression":return this.evaluateTestExpression(J,Q);case"SelectExpression":return this.evaluateSelectExpression(J,Q);case"Ternary":return this.evaluateTernaryExpression(J,Q);case"Comment":return new f0;default:throw SyntaxError(`Unknown node type: ${J.type}`)}}};function i9(J){switch(typeof J){case"number":return Number.isInteger(J)?new W0(J):new _0(J);case"string":return new s(J);case"boolean":return new H0(J);case"undefined":return new x0;case"object":if(J===null)return new f0;else if(Array.isArray(J))return new j0(J.map(i9));else return new t0(new Map(Object.entries(J).map(([Q,X])=>[Q,i9(X)])));case"function":return new k0((Q,X)=>{let K=J(...Q.map((Z)=>Z.value))??null;return i9(K)});default:throw Error(`Cannot convert to runtime value: ${J}`)}}var i0=` `,qj="{%- ",Fj=" -%}";function Uj(J){switch(J.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":if(J.operator.value==="and")return 1;if(J.operator.value==="in"||J.operator.value==="not in")return 2;return 0}return 0}function Nj(J,Q="\t"){let X=typeof Q==="number"?" ".repeat(Q):Q;return x6(J.body,0,X).replace(/\n$/,"")}function X6(...J){return qj+J.join(" ")+Fj}function x6(J,Q,X){return J.map((K)=>jj(K,Q,X)).join(i0)}function jj(J,Q,X){let K=X.repeat(Q);switch(J.type){case"Program":return x6(J.body,Q,X);case"If":return zj(J,Q,X);case"For":return Oj(J,Q,X);case"Set":return Bj(J,Q,X);case"Macro":return Dj(J,Q,X);case"Break":return K+X6("break");case"Continue":return K+X6("continue");case"CallStatement":return Mj(J,Q,X);case"FilterStatement":return Sj(J,Q,X);case"Comment":return K+"{# "+J.value+" #}";default:return K+"{{- "+z0(J)+" -}}"}}function zj(J,Q,X){let K=X.repeat(Q),Z=[],H=J;while(H)if(Z.push({test:H.test,body:H.body}),H.alternate.length===1&&H.alternate[0].type==="If")H=H.alternate[0];else break;let Y=K+X6("if",z0(Z[0].test))+i0+x6(Z[0].body,Q+1,X);for(let $=1;$0)Y+=i0+K+X6("else")+i0+x6(H.alternate,Q+1,X);return Y+=i0+K+X6("endif"),Y}function Oj(J,Q,X){let K=X.repeat(Q),Z="";if(J.iterable.type==="SelectExpression"){let Y=J.iterable;Z=`${z0(Y.lhs)} if ${z0(Y.test)}`}else Z=z0(J.iterable);let H=K+X6("for",z0(J.loopvar),"in",Z)+i0+x6(J.body,Q+1,X);if(J.defaultBlock.length>0)H+=i0+K+X6("else")+i0+x6(J.defaultBlock,Q+1,X);return H+=i0+K+X6("endfor"),H}function Bj(J,Q,X){let K=X.repeat(Q),Z=z0(J.assignee),H=J.value?z0(J.value):"",Y=K+X6("set",`${Z}${J.value?" = "+H:""}`);if(J.body.length===0)return Y;return Y+i0+x6(J.body,Q+1,X)+i0+K+X6("endset")}function Dj(J,Q,X){let K=X.repeat(Q),Z=J.args.map(z0).join(", ");return K+X6("macro",`${J.name.value}(${Z})`)+i0+x6(J.body,Q+1,X)+i0+K+X6("endmacro")}function Mj(J,Q,X){let K=X.repeat(Q),Z=J.callerArgs&&J.callerArgs.length>0?`(${J.callerArgs.map(z0).join(", ")})`:"",H=z0(J.call),Y=K+X6(`call${Z}`,H)+i0;return Y+=x6(J.body,Q+1,X)+i0,Y+=K+X6("endcall"),Y}function Sj(J,Q,X){let K=X.repeat(Q),Z=J.filter.type==="Identifier"?J.filter.value:z0(J.filter),H=K+X6("filter",Z)+i0;return H+=x6(J.body,Q+1,X)+i0,H+=K+X6("endfilter"),H}function z0(J,Q=-1){switch(J.type){case"SpreadExpression":return`*${z0(J.argument)}`;case"Identifier":return J.value;case"IntegerLiteral":return`${J.value}`;case"FloatLiteral":return`${J.value}`;case"StringLiteral":return JSON.stringify(J.value);case"BinaryExpression":{let X=J,K=Uj(X),Z=z0(X.left,K),H=z0(X.right,K+1),Y=`${Z} ${X.operator.value} ${H}`;return K`${z0(K)}: ${z0(Z)}`).join(", ")}}`;case"SliceExpression":{let X=J,K=X.start?z0(X.start):"",Z=X.stop?z0(X.stop):"",H=X.step?`:${z0(X.step)}`:"";return`${K}:${Z}${H}`}case"KeywordArgumentExpression":{let X=J;return`${X.key.value}=${z0(X.value)}`}case"Ternary":{let X=J,K=`${z0(X.trueExpr)} if ${z0(X.condition,0)} else ${z0(X.falseExpr)}`;return Q>-1?`(${K})`:K}default:throw Error(`Unknown expression type: ${J.type}`)}}var Lj=class{parsed;constructor(J){let Q=vN(J,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Qj(Q)}render(J){let Q=new c5;if(Wj(Q),J)for(let[Z,H]of Object.entries(J))Q.set(Z,H);return new Gj(Q).run(this.parsed).value}format(J){return Nj(this.parsed,J?.indent||"\t")}},Cj={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"},t9=class J{constructor(Q){if(this.filePath=Q,this.headers=new Headers,this.exists=S6.existsSync(Q),this.exists){this.status=200,this.statusText="OK";let X=S6.statSync(Q);this.headers.set("content-length",X.size.toString()),this.updateContentType();let K=S6.createReadStream(Q);this.body=new ReadableStream({start(Z){K.on("data",(H)=>Z.enqueue(H)),K.on("end",()=>Z.close()),K.on("error",(H)=>Z.error(H))},cancel(){K.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let Q=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",Cj[Q]??"application/octet-stream")}clone(){let Q=new J(this.filePath);return Q.exists=this.exists,Q.status=this.status,Q.statusText=this.statusText,Q.headers=new Headers(this.headers),Q}async arrayBuffer(){return(await S6.promises.readFile(this.filePath)).buffer}async blob(){let Q=await S6.promises.readFile(this.filePath);return new Blob([Q],{type:this.headers.get("content-type")})}async text(){return await S6.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},V7=class{constructor(J){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(J)}seed(J){if(J===void 0||J===null)if(U0.IS_CRYPTO_AVAILABLE){let Y=new Uint32Array(1);crypto.getRandomValues(Y),J=Y[0]}else J=Date.now()>>>0;let Q=this._mt,X=(Y,$)=>Math.imul(Y,$)>>>0,K=[];for(let Y=J||0;Y>0;Y=Math.floor(Y/4294967296))K.push(Y&4294967295);if(!K.length)K.push(0);Q[0]=19650218;for(let Y=1;Y<624;++Y)Q[Y]=X(1812433253,Q[Y-1]^Q[Y-1]>>>30)+Y>>>0;let Z=1,H=0;for(let Y=Math.max(624,K.length);Y>0;--Y,++Z,++H){if(Z>=624)Q[0]=Q[623],Z=1;if(H>=K.length)H=0;Q[Z]=(Q[Z]^X(Q[Z-1]^Q[Z-1]>>>30,1664525))+K[H]+H>>>0}for(let Y=623;Y>0;--Y,++Z){if(Z>=624)Q[0]=Q[623],Z=1;Q[Z]=(Q[Z]^X(Q[Z-1]^Q[Z-1]>>>30,1566083941))-Z>>>0}Q[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let J=this._mt;if(this._idx>=624){for(let X=0;X<624;++X){let K=J[X]&2147483648|J[(X+1)%624]&2147483647;J[X]=(J[(X+397)%624]^K>>>1^(K&1?2567483615:0))>>>0}this._idx=0}let Q=J[this._idx++];return Q^=Q>>>11,Q^=Q<<7&2636928640,Q^=Q<<15&4022730752,Q^=Q>>>18,Q>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(J=0,Q=1){let X=this._gauss_next;if(this._gauss_next=null,X===null){let K=this.random()*2*Math.PI,Z=Math.sqrt(-2*Math.log(1-this.random()));X=Math.cos(K)*Z,this._gauss_next=Math.sin(K)*Z}return J+X*Q}shuffle(J){for(let Q=J.length-1;Q>0;--Q){let X=32-Math.clz32(Q+1),K=this._int32()>>>32-X;while(K>Q)K=this._int32()>>>32-X;let Z=J[Q];J[Q]=J[K],J[K]=Z}}choices(J,Q){return J[a$(this._random_fn,Q)]}};function a$(J,Q){let X=0;for(let Z=0;Za$(IJ.random,J),Aj=new V7,o$=class{constructor(J){this.path=J}async match(J){let Q=r6.join(this.path,J),X=new t9(Q);if(X.exists)return X;else return}async put(J,Q,X=void 0){let K=r6.join(this.path,J),Z=U0.IS_PROCESS_AVAILABLE?process.pid:Date.now(),H=Aj._int32().toString(36),Y=K+`.tmp.${Z}.${H}`;try{let $=Q.headers.get("Content-Length"),V=parseInt($??"0"),W=0;await S6.promises.mkdir(r6.dirname(K),{recursive:!0});let q=S6.createWriteStream(Y),F=Q.body.getReader();while(!0){let{done:N,value:j}=await F.read();if(N)break;await new Promise((D,L)=>{q.write(j,(M)=>{if(M){L(M);return}D()})}),W+=j.length;let B=V?W/V*100:0;X?.({progress:B,loaded:W,total:V})}await new Promise((N,j)=>{q.close((B)=>B?j(B):N())}),await S6.promises.rename(Y,K)}catch($){try{await S6.promises.unlink(Y)}catch{}throw $}}async delete(J){let Q=r6.join(this.path,J);try{return await S6.promises.unlink(Q),!0}catch(X){return!1}}},Pj={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"},H$=100,Ej=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function _9(...J){return J=J.map((Q,X)=>{if(X)Q=Q.replace(new RegExp("^/"),"");if(X!==J.length-1)Q=Q.replace(new RegExp("/$"),"");return Q}),J.join("/")}function j8(J,Q=null,X=null){let K;try{K=new URL(J)}catch(Z){return!1}if(Q&&!Q.includes(K.protocol))return!1;if(X&&!X.includes(K.hostname))return!1;return!0}function wj(J){if(!Ej.test(J))return!1;if(J.includes("..")||J.includes("--"))return!1;if(J.endsWith(".git")||J.endsWith(".ipynb"))return!1;return!0}function Tj(J,Q,X){if(!X)return null;let K=Pj[J]??`Error (${J}) occurred while trying to load file`;throw Error(`${K}: "${Q}".`)}async function Ij(J,Q,X){let K=J.headers.get("Content-Length"),Z=K?parseInt(K,10):X??0;if(K===null&&!X)$0.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let H=new Uint8Array(Z),Y=0,$=J.body.getReader();async function V(){let{done:W,value:q}=await $.read();if(W)return;let F=Y+q.length;if(F>Z){Z=F;let j=new Uint8Array(Z);j.set(H),H=j}H.set(q,Y),Y=F;let N=Y/Z*100;return Q({progress:N,loaded:Y,total:Z}),V()}return await V(),H}function Y$(J){return j8(J,["blob:"])}function $$(J){let Q;if(typeof location<"u"&&location.href)Q=location.href;else if(typeof import.meta<"u"&&import.meta.url)Q=import.meta.url;else return J;return new URL(J,Q).href}var n$="SHA-256",vj="experimental_transformers-hash-cache",V$=(J)=>({algorithm:n$,value:J}),W$=class{#Q=null;_getHashCache=()=>{return this.#Q??=caches.open(vj),this.#Q};static isAvailable=()=>typeof navigator<"u"&&("crossOriginStorage"in navigator);match=async(J)=>{let Q=await this._getFileHash(J);if(!Q)return;try{let[X]=await navigator.crossOriginStorage.requestFileHandles([V$(Q)]),K=await X.getFile();return new Response(K,{headers:{"Content-Length":String(K.size)}})}catch{return}};put=async(J,Q)=>{let X=await this._getFileHash(J);if(X){let K=await Q.blob();await this._storeBlobInCOS(K,X)}else this._processAndStore(J,Q.body)};_storeBlobInCOS=async(J,Q)=>{let[X]=await navigator.crossOriginStorage.requestFileHandles([V$(Q)],{create:!0}),K=await X.createWritable();await K.write(J),await K.close()};_processAndStore=async(J,Q)=>{try{let X=[];for await(let H of Q)X.push(H);let K=new Blob(X),Z=await this._getBlobHash(K);await this._storeBlobInCOS(K,Z);try{await(await this._getHashCache()).put(J,new Response(Z))}catch{}}catch{}};delete=async(J)=>{try{return await(await this._getHashCache()).delete(J)}catch{return!1}};_getFileHash=async(J)=>{try{let Q=await this._getHashCache(),X=await Q.match(J);if(X)return X.text();let K=await this._getLfsFileHash(J);if(K)return await Q.put(J,new Response(K)),K;return null}catch{return null}};_getLfsFileHash=async(J)=>{if(!J.includes("/resolve/"))return null;let Q=J.replace("/resolve/","/raw/");try{let K=(await fetch(Q).then((Z)=>Z.text())).match(/^oid sha256:([0-9a-f]+)$/m);return K?K[1]:null}catch{return null}};_getBlobHash=async(J)=>{let Q=await J.arrayBuffer(),X=await crypto.subtle.digest(n$,Q);return Array.from(new Uint8Array(X)).map((Z)=>Z.toString(16).padStart(2,"0")).join("")}};async function vJ(J=null){let Q=null;if(G0.useCustomCache){if(!G0.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!G0.customCache.match||!G0.customCache.put)throw 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");Q=G0.customCache}if(!Q&&G0.experimental_useCrossOriginStorage&&W$.isAvailable())Q=new W$;if(!Q&&G0.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{Q=await caches.open(G0.cacheKey)}catch(X){$0.warn("An error occurred while opening the browser cache:",X)}}if(!Q&&G0.useFSCache){if(!U0.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");Q=new o$(J??G0.cacheDir)}return Q}async function yj(J,...Q){for(let X of Q)try{let K=await J.match(X);if(K)return K}catch(K){continue}return}var xj=class{#Q;#J;constructor(J){this.#Q=J,this.#J=new Map}get(J){if(!this.#J.has(J))return;let Q=this.#J.get(J);return this.#J.delete(J),this.#J.set(J,Q),Q}put(J,Q){if(this.#J.has(J))this.#J.delete(J);if(this.#J.set(J,Q),this.#J.size>this.#Q)this.#J.delete(this.#J.keys().next().value)}delete(J){return this.#J.delete(J)}clear(){this.#J.clear()}},kj=100,XJ=new xj(kj);function s$(J,Q){let X=XJ.get(J);if(X!==void 0)return X;let K=Q().then((Z)=>Z,(Z)=>{return XJ.delete(J),Promise.reject(Z)});return XJ.put(J,K),K}async function hj(J){if(!j8(J,["http:","https:"]))return null;let Q=t$(J);return Q.set("Range","bytes=0-0"),G0.fetch(J,{method:"GET",headers:Q,cache:"no-store"})}function H9(J,Q,X={}){let K=JSON.stringify([J,Q,X?.revision,X?.cache_dir,X?.local_files_only]);return s$(K,()=>bj(J,Q,X))}async function bj(J,Q,X){let K=await vJ(X?.cache_dir),{localPath:Z,remoteURL:H,proposedCacheKey:Y,validModelId:$}=e$(J,Q,X,K),V=await JV(K,Z,Y);if(V!==void 0&&typeof V!=="string"){let W=V.headers.get("content-length"),q=V.headers.get("content-type");return{exists:!0,size:W?parseInt(W,10):void 0,contentType:q||void 0,fromCache:!0}}if(G0.allowLocalModels){if(!j8(Z,["http:","https:"]))try{let q=await e8(Z);if(typeof q!=="string"&&q.status!==404){let F=q.headers.get("content-length"),N=q.headers.get("content-type");return{exists:!0,size:F?parseInt(F,10):void 0,contentType:N||void 0,fromCache:!1}}}catch(q){}}if(G0.allowRemoteModels&&!X.local_files_only&&$)try{let W=await hj(H);if(W&&W.status>=200&&W.status<300){let q,F=W.headers.get("content-type");if(W.status===206){let N=W.headers.get("content-range");if(N){let j=N.match(/bytes \d+-\d+\/(\d+)/);if(j)q=parseInt(j[1],10)}}else if(W.status===200)try{await W.body?.cancel()}catch(N){}if(q===void 0){let N=W.headers.get("content-length");q=N?parseInt(N,10):void 0}return{exists:!0,size:q,contentType:F||void 0,fromCache:!1}}}catch(W){$0.warn(`Unable to fetch file metadata for "${H}": ${W}`)}return{exists:!1,fromCache:!1}}async function e8(J){if(G0.useFS&&!j8(J,["http:","https:","blob:"]))return new t9(J instanceof URL?J.protocol==="file:"?J.pathname:J.toString():J);else return G0.fetch(J,{headers:t$(J)})}function t$(J){let Q=typeof process<"u"&&process?.release?.name==="node",X=new Headers;if(Q){let K=!!process.env?.TESTING_REMOTELY,Z=G0.version;if(X.set("User-Agent",`transformers.js/${Z}; is_ci/${K};`),j8(J,["http:","https:"],["huggingface.co","hf.co"])){let Y=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;if(Y)X.set("Authorization",`Bearer ${Y}`)}}return X}function e$(J,Q,X={},K=null){let Z=X.revision??"main",H=_9(J,Q),Y=wj(J),$=Y?_9(G0.localModelPath,H):H,V=_9(G0.remoteHost,G0.remotePathTemplate.replaceAll("{model}",J).replaceAll("{revision}",encodeURIComponent(Z)),Q),W=K instanceof o$?Z==="main"?H:_9(J,Z,Q):V;return{requestURL:H,localPath:$,remoteURL:V,proposedCacheKey:W,validModelId:Y}}async function JV(J,Q,X){if(!J)return;return await yj(J,Q,X)}async function fj(J,Q,X,K,Z,H,Y={}){if(await X.match(K)!==void 0)return;if(!H){let $=Y.progress_callback?(V)=>C5(Y.progress_callback,{status:"progress",name:J,file:Q,...V}):void 0;await X.put(K,Z,$)}else if(typeof Z!=="string"){let $=new Headers(Z.headers);$.set("content-length",H.byteLength.toString()),await X.put(K,new Response(H,{headers:$})).catch((V)=>{$0.warn(`Unable to add response to browser cache: ${V}.`)})}}async function _j(J,Q,X=!0,K={},Z=!1,H=null){let{requestURL:Y,localPath:$,remoteURL:V,proposedCacheKey:W,validModelId:q}=e$(J,Q,K,H),F,N=!1,j;j=await JV(H,$,W);let B=j!==void 0;if(B)F=W;else{if(G0.allowLocalModels){if(!j8(Y,["http:","https:"]))try{j=await e8($),F=$}catch(R){$0.warn(`Unable to load from local path "${$}": "${R}"`)}else if(K.local_files_only)throw Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${Y}.`);else if(!G0.allowRemoteModels)throw Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${Y}.`)}if(j===void 0||typeof j!=="string"&&j.status===404){if(K.local_files_only||!G0.allowRemoteModels)if(X)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${$}".`);else return null;if(!q)throw Error(`Local file missing at "${$}" and download aborted due to invalid model ID "${J}".`);if(j=await e8(V),j.status!==200)return Tj(j.status,V,X);F=W}N=H&&typeof Response<"u"&&j instanceof Response&&j.status===200}C5(K.progress_callback,{status:"download",name:J,file:Q});let D;if(U0.IS_NODE_ENV&&Z);else{let M;if(typeof j!=="string")if(!K.progress_callback)M=new Uint8Array(await j.arrayBuffer());else if(B&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))M=new Uint8Array(await j.arrayBuffer()),C5(K.progress_callback,{status:"progress",name:J,file:Q,progress:100,loaded:M.length,total:M.length});else{let R,E=j.headers.get("content-length");if(E)R=parseInt(E,10);else try{let P=await H9(J,Q,K);if(P.size)R=P.size}catch(P){}M=await Ij(j,(P)=>{C5(K.progress_callback,{status:"progress",name:J,file:Q,...P})},R)}D=M}if(N&&F&&typeof j!=="string")await fj(J,Q,H,F,j,D,K);if(U0.IS_NODE_ENV&&Z&&K.progress_callback&&typeof j!=="string"){let M=parseInt(j.headers.get("content-length"),10)||0;C5(K.progress_callback,{status:"progress",name:J,file:Q,progress:100,loaded:M,total:M})}if(C5(K.progress_callback,{status:"done",name:J,file:Q}),D){if(!U0.IS_NODE_ENV&&Z)throw Error("Cannot return path in a browser environment.");return D}if(j instanceof t9)return j.filePath;let L=await H?.match(F);if(L instanceof t9)return L.filePath;else if(L instanceof Response)return new Uint8Array(await L.arrayBuffer());else if(typeof L==="string")return L;throw Error("Unable to get model file path or buffer.")}var g9=new Map;async function e9(J,Q,X=!0,K={},Z=!1){if(!G0.allowLocalModels){if(K.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`).");else if(!G0.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}C5(K.progress_callback,{status:"initiate",name:J,file:Q});let H=`${J}::${Q}`,Y=g9.get(H);if(!Y){let $=await vJ(K?.cache_dir);Y=_j(J,Q,X,K,Z,$).then((V)=>{return g9.delete(H),V},(V)=>{throw g9.delete(H),V}),g9.set(H,Y)}return await Y}async function yJ(J,Q,X=!0,K={}){let Z=await e9(J,Q,X,K,!1);if(Z===null)return null;return new TextDecoder("utf-8").decode(Z)}async function s6(J,Q,X=!0,K={}){let Z=await yJ(J,Q,X,K);if(Z===null)return{};return JSON.parse(Z)}function gj(J,[Q,X,K],[Z,H],Y="bilinear",$=!1){let V=H/K,W=Z/X,q=new J.constructor(Z*H*Q),F=X*K,N=Z*H;for(let j=0;j=0;--$)Z[$]=V,K[$]=Q[X[$]],V*=K[$];let H=X.map(($,V)=>Z[X.indexOf(V)]),Y=new J.constructor(J.length);for(let $=0;$=0;--W)V+=q%Q[W]*H[W],q=Math.floor(q/Q[W]);Y[V]=J[$]}return[Y,K]}function K6(J){let Q=c0(J)[0],X=J.map((H)=>Math.exp(H-Q)),K=X.reduce((H,Y)=>H+Y,0);return X.map((H)=>H/K)}function lj(J){let Q=c0(J)[0],X=0;for(let H=0;HH-Q-K)}function NJ(J){if(J.length===0)throw Error("Array must not be empty");let Q=J[0],X=0;for(let K=1;KQ)Q=J[K],X=K;return[Q,X]}function QV(J){return J>0&&(J&J-1)===0}var XV=class{constructor(J){if(this.size=J|0,this.size<=1||!QV(this.size))throw Error("FFT size must be a power of two larger than 1");this._csize=J<<1,this.table=new Float64Array(this.size*2);for(let X=0;XX;X<<=1)++Q;this._width=Q%2===0?Q-1:Q,this._bitrev=new Int32Array(1<>>K&3)<>>1);for(let K=0;K>>1]=J[K];return X}toComplexArray(J,Q){let X=Q||this.createComplexArray();for(let K=0;K>>1],X[K+1]=0;return X}transform(J,Q){if(J===Q)throw Error("Input and output buffers must be different");this._transform4(J,Q,1)}realTransform(J,Q){if(J===Q)throw Error("Input and output buffers must be different");this._realTransform4(J,Q,1)}inverseTransform(J,Q){if(J===Q)throw Error("Input and output buffers must be different");this._transform4(J,Q,-1);for(let X=0;X>=2;H>=2;H>>=2){Y=K/H<<1;let F=Y>>>2;for($=0;$>>1,H>>>1)}else for($=0,V=0;$>>1,H>>>1,X)}let q=this.table;for(H>>=2;H>=2;H>>=2){Y=K/H<<1;let N=Y>>>1,j=N>>>1,B=j>>>1;for($=0;$>>1;for(let N=2;N>1;++W){let q=(W+1-J)**2/2,F=Math.sqrt($**2+V**2)**q,N=q*Math.atan2(V,$),j=2*W;Z[j]=F*Math.cos(N),Z[j+1]=F*Math.sin(N),H[j]=Z[j],H[j+1]=-Z[j+1]}this._slicedChirpBuffer=Z.subarray(Q,X),this._f=new XV(K>>1),this._f.transform(this._chirpBuffer,H)}_transform(J,Q,X){let K=this._buffer1,Z=this._buffer2,H=this._outBuffer1,Y=this._outBuffer2,$=this._chirpBuffer,V=this._slicedChirpBuffer,W=this._a;if(X)for(let q=0;q>1,j=Q[N];K[q]=j*V[q],K[F]=j*V[F]}else for(let q=0;q=J.length)V=2*(J.length-1)-V;K[Y++]=J[V]}K.sort(),X[H]=K[Z]}return X}function o8(J,Q){let X=Math.pow(10,Q);return Math.round(J*X)/X}function pj(J){let Q=Math.round(J);return Math.abs(J)%1===0.5?Q%2===0?Q:Q-1:Q}function ij(J){let Q=J.length,X=J[0].length,K=[Q+1,X+1],Z=Array.from({length:K[0]},()=>Array(K[1]).fill(1/0));Z[0][0]=0;let H=Array.from({length:K[0]},()=>Array(K[1]).fill(-1));for(let q=1;q0||$>0)switch(V.push(Y-1),W.push($-1),H[Y][$]){case 0:--Y,--$;break;case 1:--Y;break;case 2:--$;break;default:throw Error(`Internal error in dynamic time warping. Unexpected trace[${Y}, ${$}]. Please file a bug report.`)}return V.reverse(),W.reverse(),[V,W]}var rj=function(){let J=null;return function(Q){if(!J){J=new Float32Array(65536);let H=new ArrayBuffer(4),Y=new Uint32Array(H),$=new Float32Array(H);for(let V=0;V>10,N=V&1023;if(F===31)W=q|2139095040|N<<13;else if(F===0)if(N===0)W=q;else{let j=113;while((N&1024)===0)N<<=1,--j;N&=-1025,W=q|j<<23|N<<13}else W=q|F+112<<23|N<<13;Y[0]=W,J[V]=$[0]}}let X=Q.length,K=J,Z=new Float32Array(X);for(let H=0;Haj});var aj={};async function ZV(J){let Q=J.split("/").pop(),X;try{if(X=await vJ(),X){let Z=await X.match(J);if(Z)return Z}}catch(Z){$0.warn(`Failed to load ${Q} from cache:`,Z)}let K=await G0.fetch(J);if(!K.ok)throw Error(`Failed to fetch ${Q}: ${K.status} ${K.statusText}`);if(X)try{await X.put(J,K.clone())}catch(Z){$0.warn(`Failed to cache ${Q}:`,Z)}return K}async function oj(J){let Q=await ZV(J);if(!Q||typeof Q==="string")return null;try{return await Q.arrayBuffer()}catch(X){return $0.warn("Failed to read WASM binary:",X),null}}async function nj(J){if(U0.IS_SERVICE_WORKER_ENV||U0.IS_CHROME_AVAILABLE)return J;let Q=await ZV(J);if(!Q||typeof Q==="string")return null;try{let X=await Q.text();X=X.replaceAll("globalThis.process?.versions?.node","false");let K=new Blob([X],{type:"text/javascript"});return URL.createObjectURL(K)}catch(X){return $0.warn("Failed to read WASM factory:",X),null}}var sj=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 HV(J){if(J<=v6.DEBUG)return 0;else if(J<=v6.INFO)return 2;else if(J<=v6.WARNING)return 3;else if(J<=v6.ERROR)return 3;else return 4}var tj={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},P6=[],jJ,G8,G$=Symbol.for("onnxruntime");if(G$ in globalThis)G8=globalThis[G$];else if(U0.IS_NODE_ENV){switch(G8=KV,process.platform){case"win32":P6.push("dml");break;case"linux":if(process.arch==="x64")P6.push("cuda");break;case"darwin":P6.push("coreml");break}P6.push("webgpu"),P6.push("cpu"),jJ=["cpu"]}else{if(G8=s4,U0.IS_WEBNN_AVAILABLE)P6.push("webnn-npu","webnn-gpu","webnn-cpu","webnn");if(U0.IS_WEBGPU_AVAILABLE)P6.push("webgpu");P6.push("wasm"),jJ=["wasm"]}var ej=G8.InferenceSession;function Jz(J=null){if(!J)return jJ;switch(J){case"auto":return P6;case"gpu":return P6.filter((Q)=>["webgpu","cuda","dml","webnn-gpu"].includes(Q))}if(P6.includes(J))return[sj[J]??J];throw Error(`Unsupported device: "${J}". Should be one of: ${P6.join(", ")}.`)}var q$=Promise.resolve(),X8=null;async function Qz(){if(X8)return X8;if(!(G0.useWasmCache&&typeof p0?.wasm?.wasmPaths==="object"&&p0?.wasm?.wasmPaths?.wasm&&p0?.wasm?.wasmPaths?.mjs)){if(U0.IS_DENO_WEB_RUNTIME)throw Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return X8=Promise.resolve(),X8}return X8=(async()=>{let Q=p0.wasm.wasmPaths,X=!1;if(await Promise.all([Q.wasm&&!Y$(Q.wasm)?(async()=>{try{let K=await oj($$(Q.wasm));if(K)p0.wasm.wasmBinary=K,X=!0}catch(K){$0.warn("Failed to pre-load WASM binary:",K)}})():Promise.resolve(),Q.mjs&&!Y$(Q.mjs)?(async()=>{try{let K=await nj($$(Q.mjs));if(K)p0.wasm.wasmPaths.mjs=K}catch(K){$0.warn("Failed to pre-load WASM factory:",K)}})():Promise.resolve()]),!X)p0.wasm.wasmPaths.mjs=Q.mjs})(),X8}async function YV(J,Q,X){await Qz();let K=HV(G0.logLevel??v6.WARNING),Z=()=>ej.create(J,{logSeverityLevel:K,...Q}),H=await(U0.IS_WEB_ENV?q$=q$.then(Z):Z());return H.config=X,H}var F$=Promise.resolve();async function $V(J,Q){let X=()=>J.run(Q);return U0.IS_WEB_ENV?F$=F$.then(X):X()}function VV(J){return J instanceof G8.Tensor}var p0=G8?.env;function xJ(){return p0?.wasm?.proxy}if(p0){let J=function(Q){let X=HV(Q);p0.logLevel=tj[X]};if(p0.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&p0.versions?.web&&!p0.wasm.wasmPaths){let Q=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${p0.versions.web}/dist/`;p0.wasm.wasmPaths=U0.IS_SAFARI?{mjs:`${Q}ort-wasm-simd-threaded.mjs`,wasm:`${Q}ort-wasm-simd-threaded.wasm`}:{mjs:`${Q}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${Q}ort-wasm-simd-threaded.asyncify.wasm`}}p0.wasm.proxy=!1}if(p0.webgpu)p0.webgpu.powerPreference="high-performance";J(G0.logLevel??v6.WARNING),G0.backends.onnx={...p0,setLogLevel:J}}var S5=async(J,Q,X)=>{let K=await YV(new Uint8Array(J),Q);return async(Z)=>{let H=xJ(),Y=Object.fromEntries(Object.entries(Z).map(([V,W])=>[V,(H?W.clone():W).ort_tensor])),$=await $V(K,Y);if(Array.isArray(X))return X.map((V)=>new u($[V]));else return new u($[X])}},q8=class{static session_options={};static get nearest_interpolate_4d(){if(!this._nearest_interpolate_4d)this._nearest_interpolate_4d=S5([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");return this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){if(!this._bilinear_interpolate_4d)this._bilinear_interpolate_4d=S5([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");return this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){if(!this._bicubic_interpolate_4d)this._bicubic_interpolate_4d=S5([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");return this._bicubic_interpolate_4d}static get matmul(){if(!this._matmul)this._matmul=S5([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");return this._matmul}static get stft(){if(!this._stft)this._stft=S5([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");return this._stft}static get rfft(){if(!this._rfft)this._rfft=S5([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");return this._rfft}static get top_k(){if(!this._top_k)this._top_k=S5([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"]);return this._top_k}static get slice(){if(!this._slice)this._slice=S5([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");return this._slice}},Xz=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"}),KJ=U0.IS_NODE_ENV?"cpu":"wasm";function WV(J,Q,{warn:X}={}){if(!J)return KJ;if(typeof J==="string")return J;if(J.hasOwnProperty(Q))return J[Q];if(X)X(`device not specified for "${Q}". Using the default device (${KJ}).`);return KJ}var Kz=function(){let J;return async function(){if(J===void 0)if(!U0.IS_WEBGPU_AVAILABLE)J=!1;else try{J=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch(Q){J=!1}return J}}(),u0=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16",q2:"q2",q2f16:"q2f16",q1:"q1",q1f16:"q1f16"}),U$=u0.fp32,N$=Object.freeze({[Xz.wasm]:u0.q8}),J7=Object.freeze({[u0.fp32]:"",[u0.fp16]:"_fp16",[u0.int8]:"_int8",[u0.uint8]:"_uint8",[u0.q8]:"_quantized",[u0.q4]:"_q4",[u0.q2]:"_q2",[u0.q1]:"_q1",[u0.q4f16]:"_q4f16",[u0.q2f16]:"_q2f16",[u0.q1f16]:"_q1f16",[u0.bnb4]:"_bnb4"});function GV(J,Q,X,{configDtype:K=null,warn:Z}={}){let H,Y=!1;if(J&&typeof J!=="string")if(J.hasOwnProperty(Q))H=J[Q];else H=null,Y=!0;else H=J;let $;if(H===u0.auto){if(K){let V=typeof K==="string"?K:K?.[Q];if(V&&V!==u0.auto&&u0.hasOwnProperty(V))return V}$=N$[X]??U$}else if(H&&u0.hasOwnProperty(H))$=H;else $=N$[X]??U$;if(Y&&Z)Z(`dtype not specified for "${Q}". Using the default dtype (${$}) for this device (${X}).`);return $}var J9=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}),u=class J{get dims(){return this.ort_tensor.dims}set dims(Q){this.ort_tensor.dims=Q}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(...Q){if(VV(Q[0]))this.ort_tensor=Q[0];else this.ort_tensor=new JJ(Q[0],Q[1],Q[2]);return new Proxy(this,{get:(X,K)=>{if(typeof K==="string"){let Z=Number(K);if(Number.isInteger(Z))return X._getitem(Z)}return X[K]},set:(X,K,Z)=>{return X[K]=Z}})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[Q,...X]=this.dims;if(X.length>0){let K=X.reduce((Z,H)=>Z*H);for(let Z=0;Z0){let Z=K.reduce((H,Y)=>H*Y);return this._subarray(Q,Z,K)}else return new J(this.type,[this.data[Q]],K)}indexOf(Q){let X=this.data;for(let K=0;Kj)throw Error(`Invalid slice: ${F}`);let B=[Math.max(N,0),Math.min(j,this.dims[q])];K.push(B),X.push(B[1]-B[0])}else throw Error(`Invalid slice: ${F}`)}let Z=K.map(([q,F])=>F-q),H=Z.reduce((q,F)=>q*F),Y=this.data,$=new Y.constructor(H),V=this.stride(),W=!0;for(let q=1;q=0;--N){let B=Z[N];F+=(j%B+K[N][0])*V[N],j=Math.floor(j/B)}$[q]=Y[F]}return new J(this.type,$,X)}permute(...Q){return Hz(this,Q)}transpose(...Q){return this.permute(...Q)}sum(Q=null,X=!1){return this.norm(1,Q,X)}norm(Q="fro",X=null,K=!1){if(Q==="fro")Q=2;else if(typeof Q==="string")throw Error(`Unsupported norm: ${Q}`);let Z=this.data,H=Z instanceof BigInt64Array||Z instanceof BigUint64Array;if(H&&Q!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let Y,$;if(H)Y=(F,N)=>F+N,$=0n;else Y=(F,N)=>F+N**Q,$=0;if(X===null){let F=Z.reduce(Y,$);if(Q!==1)F=F**(1/Q);return new J(this.type,[F],[])}let[V,W,q]=s8(Y,this,X,K);if(Q!==1)for(let F=0;F=0;--V){let F=this.dims[V];if(V!==X){let N=W%F;$+=N*q,q*=this.dims[V]}W=Math.floor(W/F)}Z[Y]/=H[$]}return this}normalize(Q=2,X=1){return this.clone().normalize_(Q,X)}stride(){return ZJ(this.dims)}squeeze(Q=null){return new J(this.type,this.data,j$(this.dims,Q))}squeeze_(Q=null){return this.dims=j$(this.dims,Q),this}unsqueeze(Q){return new J(this.type,this.data,z$(this.dims,Q))}unsqueeze_(Q){return this.dims=z$(this.dims,Q),this}flatten_(Q=0,X=-1){X=(X+this.dims.length)%this.dims.length;let K=this.dims.slice(0,Q),Z=this.dims.slice(Q,X+1),H=this.dims.slice(X+1);return this.dims=[...K,Z.reduce((Y,$)=>Y*$,1),...H],this}flatten(Q=0,X=-1){return this.clone().flatten_(Q,X)}view(...Q){let X=-1;for(let Z=0;Z{return $!==X?H*Y:H},1);Q[X]=K.length/Z}return new J(this.type,K,Q)}neg_(){let Q=this.data;for(let X=0;XQ?1:0;return new J("bool",X,this.dims)}lt(Q){let X=new Uint8Array(this.data.length),K=this.data;for(let Z=0;ZMath.min(Y,$),this,Q,X,1/0);return new J(K,Z,H)}max(Q=null,X=!1){if(Q===null){let Y=c0(this.data)[0];return new J(this.type,[Y],[])}let[K,Z,H]=s8((Y,$)=>Math.max(Y,$),this,Q,X,-1/0);return new J(K,Z,H)}argmin(Q=null,X=!1){if(Q!==null)throw Error("`dim !== null` not yet implemented.");let K=NJ(this.data)[1];return new J("int64",[BigInt(K)],[])}argmax(Q=null,X=!1){if(Q!==null)throw Error("`dim !== null` not yet implemented.");let K=c0(this.data)[1];return new J("int64",[BigInt(K)],[])}repeat(...Q){if(Q.lengthq===1)){if(Q.length===this.dims.length)return this.clone();let q=Q.length-this.dims.length,F=Array(q).fill(1).concat(this.dims);return new J(this.type,this.data.slice(),F)}let X=Q.length-this.dims.length,K=Array(X).fill(1).concat(this.dims),Z=K.map((q,F)=>q*Q[F]),H=Z.reduce((q,F)=>q*F,1),Y=this.data,$=new Y.constructor(H),V=ZJ(K),W=ZJ(Z);for(let q=0;qBigInt(Math.floor(H));else X=BigInt;else if(this.type==="float16"&&Q=="float32"&&this.data instanceof Uint16Array)return new J(Q,rj(this.data),this.dims);return new J(Q,J9[Q].from(this.data,X),this.dims)}};function Zz(J,Q){let X=J.length,K=Q.reduce((H,Y)=>H*Y);if(X!==K)throw Error(`cannot reshape array of size ${X} into shape (${Q})`);let Z=J;for(let H=Q.length-1;H>=0;H--)Z=Z.reduce((Y,$)=>{let V=Y[Y.length-1];if(V.lengthnew u("int64",J,[J.length]);async function FV(J,Q,X,K,Z){return await(await q8.slice)({x:J,s:c9(Q),e:c9(X),a:c9(K),t:c9(Z??Array(K.length).fill(1))})}function $z(J,Q){let X=J.data,K=Q.data,Z=[J.dims[0],J.dims[2]],H=new X.constructor(Z[0]*Z[1]),[Y,$,V]=J.dims,W=0;for(let q=0;qX!==1);else if(typeof Q==="number"){if(J[Q]===1)J.splice(Q,1)}else if(Array.isArray(Q))J=J.filter((X,K)=>{return X!==1||!Q.includes(K)});return J}function z$(J,Q){return Q=i6(Q,J.length+1),J=J.slice(),J.splice(Q,0,1),J}function i6(J,Q,X=null,K=!0){if(J<-Q||J>=Q)if(K)throw Error(`IndexError: index ${J} is out of bounds for dimension${X===null?"":" "+X} with size ${Q}`);else return J<-Q?0:Q;if(J<0)J=(J%Q+Q)%Q;return J}function h0(J,Q=0){Q=i6(Q,J[0].dims.length);let X=J[0].dims.slice();X[Q]=J.reduce((Y,$)=>Y+$.dims[Q],0);let K=X.reduce((Y,$)=>Y*$,1),Z=new J[0].data.constructor(K),H=J[0].type;if(Q===0){let Y=0;for(let $ of J){let V=$.data;Z.set(V,Y),Y+=V.length}}else{let Y=0;for(let $=0;$=0;--N){let D=W[N],L=j%D;if(N===Q)L+=Y;F+=L*B,B*=X[N],j=Math.floor(j/D)}Z[F]=V[q]}Y+=W[Q]}}return new u(H,Z,X)}function $5(J,Q=0){return h0(J.map((X)=>X.unsqueeze(Q)),Q)}function s8(J,Q,X,K=!1,Z=null){let{data:H,dims:Y}=Q;X=i6(X,Y.length);let $=Y.slice();$[X]=1;let V=new H.constructor(H.length/Y[X]);if(Z!==null)V.fill(Z);for(let W=0;W=0;--F){let B=Y[F];if(F!==X){let D=N%B;q+=D*j,j*=$[F]}N=Math.floor(N/B)}V[q]=J(V[q],H[W],W,q)}if(!K)$.splice(X,1);return[Q.type,V,$]}function Vz(J,Q=null,X=1,K=!1){let{data:Z,dims:H}=J;if(Q===null){let j=Z.reduce((M,R)=>M+R,0)/Z.length,B=Math.sqrt(Z.reduce((M,R)=>M+(R-j)**2,0)/(Z.length-X)),D=new u(J.type,[j],[]);return[new u(J.type,[B],[]),D]}Q=i6(Q,H.length);let Y=kJ(J,Q,K),$=Y.data,[V,W,q]=s8((N,j,B,D)=>N+(j-$[D])**2,J,Q,K);for(let N=0;NW+q,0);return new u(J.type,[V/Z.length],[])}Q=i6(Q,K.length);let[H,Y,$]=s8((V,W)=>V+W,J,Q,X);if(K[Q]!==1)for(let V=0;V=0;--X)Q[X]=K,K*=J[X];return Q}function hJ(J,Q,X,K){let Z=J.reduce((H,Y)=>H*Y,1);return new u(X,new K(Z).fill(Q),J)}function $6(J,Q){let X,K;if(typeof Q==="number")X="float32",K=Float32Array;else if(typeof Q==="bigint")X="int64",K=BigInt64Array;else if(typeof Q==="boolean")X="bool",K=Uint8Array;else throw Error(`Unsupported data type: ${typeof Q}`);return hJ(J,Q,X,K)}function zJ(J,Q){return $6(J.dims,Q)}function j6(J){return hJ(J,1n,"int64",BigInt64Array)}function UV(J){return j6(J.dims)}function NV(J){return hJ(J,0n,"int64",BigInt64Array)}function jV(J){return NV(J.dims)}function Wz(J){let Q=J.reduce((X,K)=>X*K,1);return new u("float32",Float32Array.from({length:Q},()=>IJ.gauss()),J)}function Gz(J,Q){if(J.dims.length!==2)throw Error("The tensor must have 2 dimensions");if(J.dims.at(-1)%8!==0)throw Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(Q))throw Error("The precision must be either 'binary' or 'ubinary'");let X=Q==="binary",K=X?"int8":"uint8",Z=X?Int8Array:Uint8Array,H=J.data,Y=new Z(H.length/8);for(let $=0;$0?1:0,W=Math.floor($/8),q=$%8;if(Y[W]|=V<<7-q,X&&q===0)Y[W]-=128}return new u(K,Y,[J.dims[0],J.dims[1]/8])}async function zV(J){if(!J)throw Error("modelId is required for get_tokenizer_files");if((await H9(J,"tokenizer_config.json",{})).exists)return["tokenizer.json","tokenizer_config.json"];return[]}async function OV(J,Q){let X=await zV(J);return await Promise.all(X.map((K)=>s6(J,K,!0,Q)))}function bJ(J){let Q=J.dims;switch(Q.length){case 1:return J.tolist();case 2:if(Q[0]!==1)throw Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return J.tolist()[0];default:throw Error(`Expected tensor to have 1-2 dimensions, got ${Q.length}.`)}}var qz=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Fz(J,Q,X,K){for(let Z of Object.keys(J)){let H=Q-J[Z].length,Y=X(Z),$=Array(H).fill(Y);J[Z]=K==="right"?a6(J[Z],$):a6($,J[Z])}}function Uz(J,Q){for(let X of Object.keys(J))J[X].length=Q}function g5(J,...Q){for(let X of Q){if(!Object.hasOwn(J,X))continue;let K=J[X];if(!K)continue;if(typeof K==="object")if(K.__type==="AddedToken")return K.content;else throw Error(`Unknown token: ${K}`);else return K}return null}function Nz(J){let Q=[];for(let X of J.get_added_tokens_decoder().values())if(X.special)Q.push(X);return Q}var Y0=class extends z6{return_token_type_ids=!1;padding_side="right";constructor(J,Q){super();if(this._tokenizerJSON=J,this._tokenizerConfig=Q,this._tokenizer=new EN(J,Q),this.config=Q,this.padding_side=Q.padding_side??this.padding_side,this.mask_token=g5(Q,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=g5(Q,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=g5(Q,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=g5(Q,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=g5(Q,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=g5(Q,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=Q.chat_template??null,Array.isArray(this.chat_template)){let K=Object.create(null);for(let{name:Z,template:H}of this.chat_template){if(typeof Z!=="string"||typeof H!=="string")throw Error('Chat template must be a list of objects with "name" and "template" properties');K[Z]=H}this.chat_template=K}this._compiled_template_cache=new Map;let X=Nz(this._tokenizer);this.all_special_ids=X.map((K)=>K.id),this.all_special_tokens=X.map((K)=>K.content)}static async from_pretrained(J,{progress_callback:Q=null,config:X=null,cache_dir:K=null,local_files_only:Z=!1,revision:H="main"}={}){let Y=await OV(J,{progress_callback:Q,config:X,cache_dir:K,local_files_only:Z,revision:H});return new this(...Y)}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(J){if(typeof J==="string")return this._tokenizer.token_to_id(J);else return J.map((Q)=>this._tokenizer.token_to_id(Q))}_call(J,Q={}){let{text_pair:X=null,add_special_tokens:K=!0,padding:Z=!1,return_token_type_ids:H=null}=Q,{truncation:Y=null,max_length:$=null}=Q,V=Q.return_tensor??!0,W=Array.isArray(J),q;if(W){if(J.length===0)throw Error("text array must be non-empty");if(X!==null){if(!Array.isArray(X))throw Error("text_pair must also be an array");else if(J.length!==X.length)throw Error("text and text_pair must have the same length");q=J.map((N,j)=>this._encode_plus(N,{text_pair:X[j],add_special_tokens:K,return_token_type_ids:H}))}else q=J.map((N)=>this._encode_plus(N,{add_special_tokens:K,return_token_type_ids:H}))}else{if(J===null||J===void 0)throw Error("text may not be null or undefined");if(Array.isArray(X))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");q=[this._encode_plus(J,{text_pair:X,add_special_tokens:K,return_token_type_ids:H})]}if($===null)$=this.model_max_length;else if(Y===null){if(Z===!0)$0.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),$=this.model_max_length;else if(Z===!1)$0.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."),Y=!0}if(Z===!0)$=Math.min(c0(q.map((N)=>N.input_ids.length))[0],$??1/0);if($=Math.min($,this.model_max_length??1/0),Z||Y){for(let N=0;N$){if(Y)Uz(q[N],$)}else if(Z)Fz(q[N],$,(j)=>j==="input_ids"?this.pad_token_id:0,this.padding_side)}let F={};if(V){if(!(Z&&Y)){if(q.some((j)=>{for(let B of Object.keys(j))if(j[B].length!==q[0][B]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.")}let N=[q.length,q[0].input_ids.length];for(let j of Object.keys(q[0]))F[j]=new u("int64",BigInt64Array.from(q.flatMap((B)=>B[j]).map(BigInt)),N)}else{for(let N of Object.keys(q[0]))F[N]=q.map((j)=>j[N]);if(!W)for(let N of Object.keys(F))F[N]=F[N][0]}return F}_encode_text(J){if(J===null)return null;return this._tokenizer.encode(J).tokens}_encode_plus(J,{text_pair:Q=null,add_special_tokens:X=!0,return_token_type_ids:K=null}={}){let{ids:Z,attention_mask:H,token_type_ids:Y}=this._tokenizer.encode(J,{text_pair:Q,add_special_tokens:X,return_token_type_ids:K??this.return_token_type_ids});return{input_ids:Z,attention_mask:H,...Y?{token_type_ids:Y}:{}}}tokenize(J,{pair:Q=null,add_special_tokens:X=!1}={}){return this._tokenizer.tokenize(J,{text_pair:Q,add_special_tokens:X})}encode(J,{text_pair:Q=null,add_special_tokens:X=!0,return_token_type_ids:K=null}={}){return this._tokenizer.encode(J,{text_pair:Q,add_special_tokens:X,return_token_type_ids:K}).ids}batch_decode(J,Q={}){if(J instanceof u)J=J.tolist();return J.map((X)=>this.decode(X,Q))}decode(J,Q={}){if(J instanceof u)J=bJ(J);if(!Array.isArray(J)||J.length===0||!NU(J[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(J,Q)}decode_single(J,{skip_special_tokens:Q=!1,clean_up_tokenization_spaces:X=null}){return this._tokenizer.decode(J,{skip_special_tokens:Q,clean_up_tokenization_spaces:X})}get_chat_template({chat_template:J=null,tools:Q=null}={}){if(this.chat_template&&typeof this.chat_template==="object"){let X=this.chat_template;if(J!==null&&Object.hasOwn(X,J))J=X[J];else if(J===null)if(Q!==null&&"tool_use"in X)J=X.tool_use;else if("default"in X)J=X.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(X).sort()}.`)}else if(J===null)if(this.chat_template)J=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 J}apply_chat_template(J,Q={}){let{tools:X=null,documents:K=null,chat_template:Z=null,add_generation_prompt:H=!1,tokenize:Y=!0,padding:$=!1,truncation:V=!1,max_length:W=null,return_tensor:q=!0,return_dict:F=!0,tokenizer_kwargs:N={},...j}=Q;if(Z=this.get_chat_template({chat_template:Z,tools:X}),typeof Z!=="string")throw Error(`chat_template must be a string, but got ${typeof Z}`);let B=this._compiled_template_cache.get(Z);if(B===void 0)B=new Lj(Z),this._compiled_template_cache.set(Z,B);let D=Object.create(null);for(let M of qz){let R=g5(this.config,M);if(R)D[M]=R}let L=B.render({messages:J,add_generation_prompt:H,tools:X,documents:K,...D,...j});if(Y){let M=this._call(L,{add_special_tokens:!1,padding:$,truncation:V,max_length:W,return_tensor:q,...N});return F?M:M.input_ids}return L}};function fJ(J,Q,X,K){if(!("language_codes"in J)||!Array.isArray(J.language_codes))throw Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in J)||!(J.languageRegex instanceof RegExp))throw Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in J)||typeof J.lang_to_token!=="function")throw Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let{src_lang:Z,tgt_lang:H}=K;if(!J.language_codes.includes(H))throw Error(`Target language code "${H}" is not valid. Must be one of: {${J.language_codes.join(", ")}}`);if(Z!==void 0){if(!J.language_codes.includes(Z))throw Error(`Source language code "${Z}" is not valid. Must be one of: {${J.language_codes.join(", ")}}`);for(let Y of J._tokenizer.post_processor.config.single)if("SpecialToken"in Y&&J.languageRegex.test(Y.SpecialToken.id)){Y.SpecialToken.id=J.lang_to_token(Z);break}}return K.forced_bos_token_id=J._tokenizer.token_to_id(J.lang_to_token(H)),J._call(Q,X)}var BV={};U8(BV,{AlbertTokenizer:()=>jz,AutoTokenizer:()=>C0,BartTokenizer:()=>zz,BertTokenizer:()=>Oz,BlenderbotSmallTokenizer:()=>Bz,BlenderbotTokenizer:()=>Dz,BloomTokenizer:()=>Mz,CLIPTokenizer:()=>Lz,CamembertTokenizer:()=>Sz,CodeGenTokenizer:()=>Rz,CodeLlamaTokenizer:()=>Cz,CohereAsrTokenizer:()=>Pz,CohereTokenizer:()=>Az,ConvBertTokenizer:()=>Ez,DebertaTokenizer:()=>Tz,DebertaV2Tokenizer:()=>wz,DistilBertTokenizer:()=>Iz,ElectraTokenizer:()=>vz,EsmTokenizer:()=>yz,FalconTokenizer:()=>xz,GPT2Tokenizer:()=>bz,GPTNeoXTokenizer:()=>hz,GemmaTokenizer:()=>kz,HerbertTokenizer:()=>fz,LlamaTokenizer:()=>_z,M2M100Tokenizer:()=>gz,MBart50Tokenizer:()=>lz,MBartTokenizer:()=>DV,MPNetTokenizer:()=>dz,MarianTokenizer:()=>cz,MgpstrTokenizer:()=>uz,MobileBertTokenizer:()=>mz,NllbTokenizer:()=>pz,NougatTokenizer:()=>iz,PreTrainedTokenizer:()=>Y0,Qwen2Tokenizer:()=>rz,RoFormerTokenizer:()=>oz,RobertaTokenizer:()=>az,SiglipTokenizer:()=>nz,SpeechT5Tokenizer:()=>sz,SqueezeBertTokenizer:()=>tz,T5Tokenizer:()=>ez,TokenizersBackend:()=>Y0,VitsTokenizer:()=>QO,Wav2Vec2CTCTokenizer:()=>XO,WhisperTokenizer:()=>$O,XLMRobertaTokenizer:()=>VO,XLMTokenizer:()=>WO});var jz=class extends Y0{return_token_type_ids=!0},zz=class extends Y0{},Oz=class extends Y0{return_token_type_ids=!0},Bz=class extends Y0{},Dz=class extends Y0{},Mz=class extends Y0{},Sz=class extends Y0{},Lz=class extends Y0{},Cz=class extends Y0{},Rz=class extends Y0{},Az=class extends Y0{},Pz=class extends Y0{},Ez=class extends Y0{return_token_type_ids=!0},wz=class extends Y0{return_token_type_ids=!0},Tz=class extends Y0{return_token_type_ids=!0},Iz=class extends Y0{},vz=class extends Y0{return_token_type_ids=!0},yz=class extends Y0{},xz=class extends Y0{},kz=class extends Y0{},hz=class extends Y0{},bz=class extends Y0{},fz=class extends Y0{return_token_type_ids=!0},_z=class extends Y0{padding_side="left"},gz=class extends Y0{constructor(J,Q){super(J,Q);this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter((X)=>this.languageRegex.test(X)).map((X)=>X.slice(2,-2)),this.lang_to_token=(X)=>`__${X}__`}_build_translation_inputs(J,Q,X){return fJ(this,J,Q,X)}},cz=class extends Y0{constructor(J,Q){super(J,Q);this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter((X)=>this.languageRegex.test(X)),$0.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(J){if(J===null)return null;let[Q,...X]=J.trim().split(this.languageRegex);if(X.length===0)return super._encode_text(Q);else if(X.length===2){let[K,Z]=X;if(!this.supported_language_codes.includes(K))$0.warn(`Unsupported language code "${K}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`);return a6([K],super._encode_text(Z))}}},DV=class extends Y0{constructor(J,Q){super(J,Q);this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter((X)=>this.languageRegex.test(X)).map((X)=>X),this.lang_to_token=(X)=>X}_build_translation_inputs(J,Q,X){return fJ(this,J,Q,X)}},lz=class extends DV{},uz=class extends Y0{},mz=class extends Y0{return_token_type_ids=!0},dz=class extends Y0{},pz=class extends Y0{constructor(J,Q){super(J,Q);this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter((X)=>this.languageRegex.test(X)),this.lang_to_token=(X)=>X}_build_translation_inputs(J,Q,X){return fJ(this,J,Q,X)}},iz=class extends Y0{},rz=class extends Y0{},az=class extends Y0{},oz=class extends Y0{return_token_type_ids=!0},nz=class extends Y0{},sz=class extends Y0{},tz=class extends Y0{return_token_type_ids=!0},ez=class extends Y0{},JO=class extends f6{decode_chain(J){let Q="";for(let X=1;X[Q,J]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function ZO(J){J=J.toLowerCase();let Q=KO.get(J);if(Q===void 0){let X=J.match(/^<\|([a-z]{2})\|>$/);if(X)J=X[1];if(r9.has(J))Q=J;else{let Z=J.length===2?r9.keys():r9.values();throw Error(`Language "${J}" is not supported. Must be one of: ${JSON.stringify(Array.from(Z))}`)}}return Q}var HO="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",O$=new RegExp(`^[${HO}]+$`,"gu"),YO=0.1,$O=class extends Y0{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(J,{return_timestamps:Q=!1,return_language:X=!1,time_precision:K=null,force_full_sequences:Z=!0}={}){if(K===null)throw Error("Must specify time_precision");let H=null,Y=Q==="word";function $(){return{language:H,timestamp:[null,null],text:""}}let V=[],W=$(),q=0,F=this.timestamp_begin,j=F+1500,B=[],D=[],L=!1,M=null,R=new Set(this.all_special_ids);for(let w of J){let k=w.tokens,C=Y?w.token_timestamps:null,c=null,g=F;if("stride"in w){let[i,p,f]=w.stride;if(q-=p,M=i-f,p)g=p/K+F;if(f)for(let v=k.length-1;v>=0;--v){let o=Number(k[v]);if(o>=F){if(c!==null&&(o-F)*K=F&&p<=j){let f=(p-F)*K+q,v=o8(f,2);if(c!==null&&p>=c)L=!0;else if(L||B.length>0&&p0&&W.timestamp[1]!==null){for(let h of W.words)if(h.timestamp[1]>W.timestamp[1]&&W.timestamp[1]>=h.timestamp[0])h.timestamp[1]=W.timestamp[1]}}V.push(W),B=[],d=[],D=[],r=[],W=$()}}else if(d.push(p),Y){let f=o8(C[i]+q,2),v;if(i+10){if(B.push(d),Y)D.push(r)}else if(B.every((i)=>i.length===0))W=$(),B=[],d=[],D=[],r=[]}if(B.length>0){if(Z&&Q)throw Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[w,k]=this.findLongestCommonSequence(B,D),C=this.decode(w);if(W.text=C,Y)W.words=this.collateWordTimestamps(w,k,H);V.push(W)}let E=Object.create(null),P=V.map((w)=>w.text).join("");if(Q||X){for(let w=0;w0,Y=H?[]:null,$=H?Q[0]:null;for(let V=1;Vp===g[f]&&$[P+f][0]-YO<=Q[V][C+f][0]).length;else d=k.filter((p,f)=>p===g[f]).length;let r=E/1e4,i=d/E+r;if(d>1&&i>q)q=i,F=[P,w,C,c]}let[j,B,D,L]=F,M=Math.floor((B+j)/2),R=Math.floor((L+D)/2);if(H&&q===0&&K>0){let E=$[K-1][0],P=Q[V].findIndex((w)=>w[0]>=E);R=P===-1?W.length:P}if(Z.push(...X.slice(0,M)),X=W.slice(R),K=X.length,H)Y.push(...$.slice(0,M)),$=Q[V].slice(R)}if(Z.push(...X),H)return Y.push(...$),[Z,Y];else return[Z,[]]}collateWordTimestamps(J,Q,X){let[K,Z,H]=this.combineTokensIntoWords(J,X),Y=[];for(let $=0;$=K){let Y=((H-K)*X).toFixed(2);Z.push(`<|${Y}|>`),Z.push([])}else Z[Z.length-1].push(H);return Z=Z.map((H)=>typeof H==="string"?H:super.decode(H,Q)),Z.join("")}splitTokensOnUnicode(J){let Q=this.decode(J,{decode_with_timestamps:!0}),X="�",K=[],Z=[],H=[],Y=[],$=[],V=0;for(let W=0;W=this._tokenizer.token_to_id("<|endoftext|>"),N=V.startsWith(" "),j=V.trim(),B=O$.test(j);if(F||N||B||Z.length===0)Z.push(V),H.push(W),Y.push(q);else{let D=Z.length-1;Z[D]+=V,H[D].push(...W),Y[D].push(...q)}}return[Z,H,Y]}mergePunctuations(J,Q,X,K,Z){let H=structuredClone(J),Y=structuredClone(Q),$=structuredClone(X),V=H.length-2,W=H.length-1;while(V>=0){if(H[V].startsWith(" ")&&K.includes(H[V].trim()))H[W]=H[V]+H[W],Y[W]=a6(Y[V],Y[W]),$[W]=a6($[V],$[W]),H[V]="",Y[V]=[],$[V]=[];else W=V;--V}V=0,W=1;while(Wq),Y.filter((q)=>q.length>0),$.filter((q)=>q.length>0)]}},VO=class extends Y0{},WO=class extends Y0{return_token_type_ids=!0;constructor(J,Q){super(J,Q);$0.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},C0=class{static async from_pretrained(J,{progress_callback:Q=null,config:X=null,cache_dir:K=null,local_files_only:Z=!1,revision:H="main"}={}){let[Y,$]=await OV(J,{progress_callback:Q,config:X,cache_dir:K,local_files_only:Z,revision:H}),V=$.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",W=BV[V];if(!W)$0.warn(`Unknown tokenizer class "${V}", attempting to construct from base class.`),W=Y0;return new W(Y,$)}},W7="https://github.com/huggingface/transformers.js/issues/new/choose",_J="preprocessor_config.json",Q9=_J,SV="processor_config.json",LV="chat_template.jinja",R0=class extends z6{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(J,Q,X){super();this.config=J,this.components=Q,this.chat_template=X}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(J,Q={}){if(!this.tokenizer)throw Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(J,{tokenize:!1,chat_template:this.chat_template??void 0,...Q})}batch_decode(...J){if(!this.tokenizer)throw Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...J)}decode(...J){if(!this.tokenizer)throw Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...J)}async _call(J,...Q){for(let X of[this.image_processor,this.feature_extractor,this.tokenizer])if(X)return X(J,...Q);throw Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(J,Q={}){let[X,K,Z]=await Promise.all([this.uses_processor_config?s6(J,SV,!0,Q):{},Promise.all(this.classes.filter((H)=>(H in this)).map(async(H)=>{let Y=await this[H].from_pretrained(J,Q);return[H.replace(/_class$/,""),Y]})).then(Object.fromEntries),this.uses_chat_template_file?yJ(J,LV,!0,Q):null]);return new this(X,K,Z)}},OJ={};U8(OJ,{ChatterboxProcessor:()=>cO,CohereAsrProcessor:()=>uO,Florence2Processor:()=>mB,Gemma3Processor:()=>dB,Gemma3nProcessor:()=>pB,Gemma4Processor:()=>iB,Glm46VProcessor:()=>rB,GraniteSpeechProcessor:()=>aB,GroundingDinoProcessor:()=>nB,Idefics3Processor:()=>R$,JinaCLIPProcessor:()=>QD,Lfm2VlProcessor:()=>XD,LlavaProcessor:()=>KD,MgpstrProcessor:()=>ZD,MoonshineProcessor:()=>HD,OwlViTProcessor:()=>YD,PaliGemmaProcessor:()=>VD,Phi3VProcessor:()=>GD,PixtralProcessor:()=>qD,Processor:()=>R0,PyAnnoteProcessor:()=>FD,Qwen2VLProcessor:()=>dJ,Qwen2_5_VLProcessor:()=>eV,Qwen3VLProcessor:()=>UD,Sam2Processor:()=>QW,Sam2VideoProcessor:()=>ND,SamProcessor:()=>JW,SmolVLMProcessor:()=>R$,SpeechT5Processor:()=>jD,UltravoxProcessor:()=>zD,VLChatProcessor:()=>JD,VoxtralProcessor:()=>MD,VoxtralRealtimeProcessor:()=>CD,Wav2Vec2Processor:()=>RD,Wav2Vec2ProcessorWithLM:()=>AD,WhisperProcessor:()=>PD});var V6=class extends z6{constructor(J){super();this.config=J}static async from_pretrained(J,Q={}){let X=await s6(J,_J,!0,Q);return new this(X)}};function Z6(J,Q){if(!(J instanceof Float32Array||J instanceof Float64Array))throw Error(`${Q} expects input to be a Float32Array or a Float64Array, but got ${J?.constructor?.name??typeof J} 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 gJ={};U8(gJ,{ASTFeatureExtractor:()=>PO,ChatterboxFeatureExtractor:()=>EO,ClapFeatureExtractor:()=>wO,CohereAsrFeatureExtractor:()=>IO,DacFeatureExtractor:()=>wV,EncodecFeatureExtractor:()=>PV,FeatureExtractor:()=>V6,Gemma3nAudioFeatureExtractor:()=>TV,Gemma4AudioFeatureExtractor:()=>IV,GraniteSpeechFeatureExtractor:()=>vO,MoonshineFeatureExtractor:()=>yO,ParakeetFeatureExtractor:()=>EV,PyAnnoteFeatureExtractor:()=>vV,SeamlessM4TFeatureExtractor:()=>xO,SnacFeatureExtractor:()=>kO,SpeechT5FeatureExtractor:()=>hO,VoxtralRealtimeFeatureExtractor:()=>_O,Wav2Vec2FeatureExtractor:()=>bO,WeSpeakerFeatureExtractor:()=>fO,WhisperFeatureExtractor:()=>gO});var GO=()=>{},qO={fromWeb:GO},FO=()=>{},UO=FO;async function CV(J,Q){if(U0.IS_BROWSER_ENV){if(U0.IS_WEBWORKER_ENV)throw Error("Unable to save a file from a Web Worker.");let X=URL.createObjectURL(Q),K=document.createElement("a");K.href=X,K.download=J,K.click(),K.remove(),URL.revokeObjectURL(X)}else if(U0.IS_FS_AVAILABLE){let X=Q.stream(),K=qO.fromWeb(X),Z=S6.createWriteStream(J);await UO(K,Z)}else throw Error("Unable to save because filesystem is disabled in this environment.")}async function NO(J,Q){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let X=await(await e8(J)).arrayBuffer(),K=new AudioContext({sampleRate:Q});if(typeof Q>"u")$0.warn(`No sampling rate provided, using default of ${K.sampleRate}Hz.`);let Z=await K.decodeAudioData(X),H;if(Z.numberOfChannels===2){let Y=Math.sqrt(2),$=Z.getChannelData(0),V=Z.getChannelData(1);H=new Float32Array($.length);for(let W=0;W2595*Math.log10(1+J/700),kaldi:(J)=>1127*Math.log(1+J/700),slaney:(J,Q=1000,X=15,K=27/Math.log(6.4))=>J>=Q?X+Math.log(J/Q)*K:3*J/200};function HJ(J,Q="htk"){let X=OO[Q];if(!X)throw Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof J==="number"?X(J):J.map((K)=>X(K))}var BO={htk:(J)=>700*(10**(J/2595)-1),kaldi:(J)=>700*(Math.exp(J/1127)-1),slaney:(J,Q=1000,X=15,K=Math.log(6.4)/27)=>J>=X?Q*Math.exp(K*(J-X)):200*J/3};function DO(J,Q="htk"){let X=BO[Q];if(!X)throw Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof J==="number"?X(J):J.map((K)=>X(K))}function MO(J,Q){let X=Float64Array.from({length:Q.length-1},(Y,$)=>Q[$+1]-Q[$]),K=Array.from({length:J.length},()=>Array(Q.length));for(let Y=0;YArray(J.length));for(let Y=0;YJ+K*H)}function o6(J,Q,X,K,Z,H=null,Y="htk",$=!1){if(H!==null&&H!=="slaney")throw Error('norm must be one of null or "slaney"');if(J<2)throw Error(`Require num_frequency_bins: ${J} >= 2`);if(X>K)throw Error(`Require min_frequency: ${X} <= max_frequency: ${K}`);let V=HJ(X,Y),W=HJ(K,Y),q=D$(V,W,Q+2),F=DO(q,Y),N;if($){let B=Z/((J-1)*2);N=HJ(Float64Array.from({length:J},(D,L)=>L*B),Y),F=q}else N=D$(0,Math.floor(Z/2),J);let j=MO(N,F);if(H!==null&&H==="slaney")for(let B=0;BZ)throw Error(`frame_length (${X}) may not be larger than fft_length (${Z})`);if(g!==X)throw Error(`Length of the window (${g}) must equal frame_length (${X})`);if(K<=0)throw Error("hop_length must be greater than zero");if(H===null&&F!==null)throw 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(!q)throw Error("`preemphasis_htk_flavor=false` is not currently supported.");if(Y){let a=Math.floor(X/2);switch($){case"reflect":{J=SO(J,a,a);break}case"constant":{let q0=new J.constructor(J.length+2*a);q0.set(J,a),J=q0;break}case"semicausal":{let q0=new J.constructor(J.length+a);q0.set(J,a),J=q0;break}default:throw Error(`pad_mode="${$}" not implemented yet.`)}}let d=Math.floor(1+Math.floor((J.length-X)/K));if(E!==null&&dd){if(w)p=P}else p=i=P;let f=new mj(Z),v=new Float64Array(Z),o=new Float64Array(f.outputBufferSize),Q0=new Float32Array(r*p);for(let a=0;a=1;--J0)v[J0]-=W*v[J0-1];v[0]*=1-W}for(let J0=0;J0Math.pow(W,0.85));break;default:throw Error(`Unknown window type ${Q}.`)}if(X)Y=Y.subarray(0,J);if(K===null||J===K)return Y;if(J>K)throw Error(`Length of the window (${J}) may not be larger than frame_length (${K})`);let $=new Float64Array(K),V=Z?Math.floor((K-J)/2):0;return $.set(Y,V),$}function RO(J,Q){let X=J.reduce((H,Y)=>H+Y.length,0),K=new ArrayBuffer(44),Z=new DataView(K);return l9(Z,0,"RIFF"),Z.setUint32(4,36+X*4,!0),l9(Z,8,"WAVE"),l9(Z,12,"fmt "),Z.setUint32(16,16,!0),Z.setUint16(20,3,!0),Z.setUint16(22,1,!0),Z.setUint32(24,Q,!0),Z.setUint32(28,Q*4,!0),Z.setUint16(32,4,!0),Z.setUint16(34,32,!0),l9(Z,36,"data"),Z.setUint32(40,X*4,!0),new Blob([K,...J.map((H)=>H.buffer)],{type:"audio/wav"})}function l9(J,Q,X){for(let K=0;KK+Z.length,0),Q=new Float32Array(J),X=0;for(let K of this.audio)Q.set(K,X),X+=K.length;return Q}else return this.audio}toBlob(){let J=this.audio;if(J instanceof Float32Array)J=[J];return RO(J,this.sampling_rate)}async save(J){return CV(J,this.toBlob())}},PO=class extends V6{constructor(J){super(J);let Q=this.config.sampling_rate,X=o6(257,this.config.num_mel_bins,20,Math.floor(Q/2),Q,null,"kaldi",!0);this.mel_filters=X,this.window=q5(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(J,Q){return t6(J,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:0.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:0.0000001192092955078125,remove_dc_offset:!0,max_num_frames:Q,transpose:!0})}async _call(J){Z6(J,"ASTFeatureExtractor");let Q=await this._extract_fbank_features(J,this.config.max_length);if(this.config.do_normalize){let X=this.std*2,K=Q.data;for(let Z=0;Z0)if(X==="rand_trunc"){H=!0;let $=Math.floor(IJ.random()*(Y+1));J=J.subarray($,$+Q),Z=await this._extract_fbank_features(J,this.mel_filters_slaney,this.config.nb_max_samples)}else throw Error(`Truncation strategy "${X}" not implemented`);else{if(Y<0){let $=new Float64Array(Q);if($.set(J),K==="repeat")for(let V=J.length;V=1;--K)J[K]-=Q*J[K-1];return await t6(J,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:0.00000005960464477539063})}async _call(J){Z6(J,"ParakeetFeatureExtractor");let Q=await this._extract_fbank_features(J),X=Math.floor((J.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),K=Q.data;K.fill(0,X*Q.dims[1]);let[Z,H]=Q.dims,Y=new Float64Array(H),$=new Float64Array(H);for(let q=0;q1?X-1:1;for(let q=0;q=W){$.push(J.slice(V,W));break}let q=Math.max(V,V+H-Y),F=Math.min(V+H,W),N;if(F<=q)N=V+H;else N=this._find_split_point_energy(J,q,F,K);N=Math.max(V+1,Math.min(N,W)),$.push(J.slice(V,N)),V=N}return $}_find_split_point_energy(J,Q,X,K){let Z=X-Q;if(Z<=K)return Math.floor((Q+X)/2);let H=1/0,Y=Q,$=Z-K;for(let V=0;V<=$;V+=K){let W=0;for(let q=0;qQ)J=J.slice(0,Q);if(K&&J.length%Z!==0){let $=Z-J.length%Z,V=new Float64Array(J.length+$);if(V.set(J),this.config.padding_value!==0)V.fill(this.config.padding_value,J.length);J=V}let H=await this._extract_fbank_features(J,this.config.max_length),Y=$6([1,H.dims[0]],!0);return{input_features:H.unsqueeze_(0),input_features_mask:Y}}},IV=class extends TV{async _extract_fbank_features(J,Q){let{frame_length:X,hop_length:K,fft_length:Z}=this.config,H=Math.floor(X/2),Y=Math.floor((J.length+H-(X+1))/K)+1;return t6(J,this.window,X,K,{fft_length:Z,center:!0,pad_mode:"semicausal",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,mel_floor_mode:"add",remove_dc_offset:!1,transpose:!0,max_num_frames:Y})}async _call(J,Q={}){Z6(J,"Gemma4AudioFeatureExtractor");let X=J.length,K=await super._call(J,Q),{input_features:Z}=K,[,H,Y]=Z.dims,{frame_length:$,hop_length:V}=this.config,W=Math.floor($/2),q=$+1,F=new Uint8Array(X+W+(Q.pad_to_multiple_of??128));F.fill(1,W,W+X);let N=new Uint8Array(H);for(let B=0;B({id:$,start:V*X,end:W*X,confidence:q/(W-V)})))}return K}},xO=class extends V6{constructor(J){super(J);let Q=this.config.sampling_rate,X=o6(257,this.config.num_mel_bins,20,Math.floor(Q/2),Q,null,"kaldi",!0);this.mel_filters=X,this.window=q5(400,"povey",{periodic:!1})}async _extract_fbank_features(J,Q){return J=J.map((X)=>X*32768),t6(J,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:0.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:0.0000001192092955078125,remove_dc_offset:!0,max_num_frames:Q,transpose:!0})}async _call(J,{padding:Q=!0,pad_to_multiple_of:X=2,do_normalize_per_mel_bins:K=!0,return_attention_mask:Z=!0}={}){Z6(J,"SeamlessM4TFeatureExtractor");let H=await this._extract_fbank_features(J,this.config.max_length);if(K){let[j,B]=H.dims,D=H.data;for(let L=0;L0){let M=new Float32Array(B*(j+L));M.set(D),M.fill(this.config.padding_value,D.length);let R=j+L;if(H=new u(H.type,M,[R,B]),Z)Y=new u("int64",new BigInt64Array(R),[1,R]),Y.data.fill(1n,0,j)}}let[$,V]=H.dims,W=this.config.stride;if($%W!==0)throw Error(`The number of frames (${$}) must be a multiple of the stride (${W}).`);let F=H.view(1,Math.floor($/W),V*W),N={input_features:F};if(Z){let j=F.dims[1],B=new BigInt64Array(j);if(Y){let D=Y.data;for(let L=1,M=0;L<$;L+=W,++M)B[M]=D[L]}else B.fill(1n);N.attention_mask=new u("int64",B,[1,j])}return N}},kO=class extends wV{},hO=class extends V6{},bO=class extends V6{_zero_mean_unit_var_norm(J){let X=J.reduce((Z,H)=>Z+H,0)/J.length,K=J.reduce((Z,H)=>Z+(H-X)**2,0)/J.length;return J.map((Z)=>(Z-X)/Math.sqrt(K+0.0000001))}async _call(J){if(Z6(J,"Wav2Vec2FeatureExtractor"),J instanceof Float64Array)J=new Float32Array(J);let Q=J;if(this.config.do_normalize)Q=this._zero_mean_unit_var_norm(Q);let X=[1,Q.length];return{input_values:new u("float32",Q,X),attention_mask:new u("int64",new BigInt64Array(Q.length).fill(1n),X)}}},fO=class extends V6{constructor(J){super(J);let Q=this.config.sampling_rate,X=o6(257,this.config.num_mel_bins,20,Math.floor(Q/2),Q,null,"kaldi",!0);this.mel_filters=X,this.window=q5(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(J){return J=J.map((Q)=>Q*32768),t6(J,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:0.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:0.0000001192092955078125,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(J){Z6(J,"WeSpeakerFeatureExtractor");let Q=(await this._extract_fbank_features(J)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let X=Q.mean(1).data,K=Q.data,[Z,H,Y]=Q.dims;for(let $=0;$K){if(J.length>this.config.n_samples)$0.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`.");X=J.slice(0,K)}else X=new Float32Array(K),X.set(J);return{input_features:(await this._extract_fbank_features(X)).unsqueeze_(0)}}},E6=class{static async from_pretrained(J,Q={}){let X=await s6(J,_J,!0,Q),K=X.feature_extractor_type,Z=gJ[K];if(!Z)throw Error(`Unknown feature_extractor_type: '${K}'. Please report this at ${W7}.`);return new Z(X)}},cO=class extends R0{static tokenizer_class=C0;static feature_extractor_class=E6;async _call(J,Q=null){let X=this.tokenizer(J),K=Q?await this.feature_extractor(Q):{};return{...X,...K}}},lO=new Set(["ja","zh"]),uO=class extends R0{static tokenizer_class=C0;static feature_extractor_class=E6;static uses_processor_config=!0;get_decoder_prompt_ids(J="en"){let Q=["▁","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${J}|>`,`<|${J}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(Q)}static join_chunks(J,Q="en"){let X=J.filter((H)=>H&&H.trim());if(X.length===0)return"";let K=lO.has(Q)?"":" ";return[X[0].trimEnd(),...X.slice(1).map((H)=>H.trim())].join(K)}async _call(J){return await this.feature_extractor(J)}},BJ={},l5,yV,L5;if(U0.IS_WEB_ENV)l5=(J,Q)=>{if(!self.OffscreenCanvas)throw Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(J,Q)},L5=self.createImageBitmap,yV=self.ImageData;else if(BJ)L5=async(J)=>{let X=(await J.metadata()).channels,{data:K,info:Z}=await J.rotate().raw().toBuffer({resolveWithObject:!0}),H=new h6(new Uint8ClampedArray(K),Z.width,Z.height,Z.channels);if(X!==void 0&&X!==Z.channels)H.convert(X);return H};else throw Error("Unable to load image processing library.");var mO={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},dO=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),h6=class J{constructor(Q,X,K,Z){this.data=Q,this.width=X,this.height=K,this.channels=Z}get size(){return[this.width,this.height]}static async read(Q){if(Q instanceof J)return Q;else if(typeof Q==="string"||Q instanceof URL)return await this.fromURL(Q);else if(Q instanceof Blob)return await this.fromBlob(Q);else if(typeof HTMLCanvasElement<"u"&&Q instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&Q instanceof OffscreenCanvas)return this.fromCanvas(Q);else throw Error(`Unsupported input type: ${typeof Q}`)}static fromCanvas(Q){if(!U0.IS_WEB_ENV)throw Error("fromCanvas() is only supported in browser environments.");let K=Q.getContext("2d").getImageData(0,0,Q.width,Q.height).data;return new J(K,Q.width,Q.height,4)}static async fromURL(Q){let X=await e8(Q);if(X.status!==200)throw Error(`Unable to read image from "${Q}" (${X.status} ${X.statusText})`);let K=await X.blob();return this.fromBlob(K)}static async fromBlob(Q){if(U0.IS_WEB_ENV){let X=await L5(Q),K=l5(X.width,X.height).getContext("2d");return K.drawImage(X,0,0),new this(K.getImageData(0,0,X.width,X.height).data,X.width,X.height,4)}else{let X=BJ(await Q.arrayBuffer());return await L5(X)}}static fromTensor(Q,X="CHW"){if(Q.dims.length!==3)throw Error(`Tensor should have 3 dimensions, but has ${Q.dims.length} dimensions.`);if(X==="CHW")Q=Q.transpose(1,2,0);else if(X==="HWC");else throw Error(`Unsupported channel format: ${X}`);if(!(Q.data instanceof Uint8ClampedArray||Q.data instanceof Uint8Array))throw Error(`Unsupported tensor type: ${Q.type}`);switch(Q.dims[2]){case 1:case 2:case 3:case 4:return new J(Q.data,Q.dims[1],Q.dims[0],Q.dims[2]);default:throw Error(`Unsupported number of channels: ${Q.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let Q=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let X=0,K=0;X=0)V=K;else q=-K;if(Z>=0)W=Z;else F=-Z;return $.drawImage(Y,V,W,Q,X,q,F,Q,X),new J($.getImageData(0,0,Q,X).data,Q,X,4).convert(H)}else{let H=this.toSharp();if(K>=0&&Z>=0)H=H.extract({left:Math.floor(K),top:Math.floor(Z),width:Q,height:X});else if(K<=0&&Z<=0){let Y=Math.floor(-Z),$=Math.floor(-K);H=H.extend({top:Y,left:$,right:Q-this.width-$,bottom:X-this.height-Y})}else{let Y=[0,0],$=0;if(Z<0)Y[0]=Math.floor(-Z),Y[1]=X-this.height-Y[0];else $=Math.floor(Z);let V=[0,0],W=0;if(K<0)V[0]=Math.floor(-K),V[1]=Q-this.width-V[0];else W=Math.floor(K);H=H.extend({top:Y[0],bottom:Y[1],left:V[0],right:V[1]}).extract({left:W,top:$,width:Q,height:X})}return await L5(H)}}async toBlob(Q="image/png",X=1){if(!U0.IS_WEB_ENV)throw Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:Q,quality:X})}toTensor(Q="CHW"){let X=new u("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(Q==="HWC");else if(Q==="CHW")X=X.permute(2,0,1);else throw Error(`Unsupported channel format: ${Q}`);return X}toCanvas(){if(!U0.IS_WEB_ENV)throw Error("toCanvas() is only supported in browser environments.");let Q=this.clone().rgba(),X=l5(Q.width,Q.height),K=new yV(Q.data,Q.width,Q.height);return X.getContext("2d").putImageData(K,0,0),X}split(){let{data:Q,width:X,height:K,channels:Z}=this,H=Q.constructor,Y=Q.length/Z,$=Array.from({length:Z},()=>new H(Y));for(let V=0;Vnew J(V,X,K,1))}_update(Q,X,K,Z=null){if(this.data=Q,this.width=X,this.height=K,Z!==null)this.channels=Z;return this}clone(){return new J(this.data.slice(),this.width,this.height,this.channels)}convert(Q){if(this.channels===Q)return this;switch(Q){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(Q){if(U0.IS_WEB_ENV){if(U0.IS_WEBWORKER_ENV)throw Error("Unable to save an image from a Web Worker.");let X=Q.split(".").pop().toLowerCase(),K=dO.get(X)??"image/png",Z=await this.toBlob(K);return CV(Q,Z)}else if(U0.IS_FS_AVAILABLE)await this.toSharp().toFile(Q);else throw Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(U0.IS_WEB_ENV)throw Error("toSharp() is only supported in server-side environments.");return BJ(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},ZI=h6.read.bind(h6);function M$(J,Q,X=0,K=null){let Z=J/Q,H=pj(Z)*Q;if(K!==null&&H>K)H=Math.floor(Z)*Q;if(HQ)M.push(E)}else{let E=c0(L.data)[1];if(E===V-1)continue;if(R=K6(L.data),R[E]w*F[(k+1)%2]);N.boxes.push(P),N.classes.push(E),N.scores.push(R[E])}}W.push(N)}return W}function kV(J,Q=null){let X=J.logits,K=X.dims[0];if(Q!==null&&Q.length!==K)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let Z=[];for(let H=0;HF[M])F[M]=L[M],N[M]=D}let j=Array($.dims[0]);for(let D=0;DD!==void 0);Z.push({segmentation:q,labels:B})}return Z}function pO(J,Q,X,K){let Z=[],H=[],Y=[];for(let $=0;$X)Z.push(W),H.push(N),Y.push(q)}return[Z,H,Y]}function iO(J,Q,X,K=0.5,Z=0.8){let H=[],Y=0,$=0,V=Q[X].data;for(let q=0;q=K)++$}let W=Y>0&&$>0;if(W)W=Y/$>Z;return[W,H]}function rO(J,Q,X,K,Z,H=null,Y=null){let[$,V]=Y??J[0].dims,W=new u("int32",new Int32Array($*V),[$,V]),q=[];if(Y!==null)for(let D=0;DN[R])F[R]=D,N[R]=M[R]}let j=0,B=W.data;for(let D=0;D200)throw Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(J,Q)/Math.min(J,Q)}`);let Y=Math.round(J/X)*X,$=Math.round(Q/X)*X;if(H*Y*$>Z){let V=Math.sqrt(H*J*Q/Z);Y=Math.max(X,Math.floor(J/V/X)*X),$=Math.max(X,Math.floor(Q/V/X)*X)}else if(H*Y*$Z)V=Math.floor(Z*$/K);else if(Z>K)$=Math.floor(K*V/Z);return await J.resize(V,$,{resample:X})}async crop_margin(J,Q=200){let X=J.clone().grayscale(),K=NJ(X.data)[0],H=c0(X.data)[0]-K;if(H===0)return J;let Y=Q/255,$=X.width,V=X.height,W=0,q=0,F=X.data;for(let N=0;Nthis.preprocess(Z)));return{pixel_values:$5(X.map((Z)=>Z.pixel_values),0),original_sizes:X.map((Z)=>Z.original_size),reshaped_input_sizes:X.map((Z)=>Z.reshaped_input_size)}}static async from_pretrained(J,Q={}){let X=await s6(J,Q9,!0,Q);return new this(X)}},Q7={};U8(Q7,{BeitFeatureExtractor:()=>aO,BitImageProcessor:()=>oO,CHMv2ImageProcessor:()=>sO,CLIPFeatureExtractor:()=>tO,CLIPImageProcessor:()=>fV,ChineseCLIPFeatureExtractor:()=>nO,ConvNextFeatureExtractor:()=>eO,ConvNextImageProcessor:()=>_V,DINOv3ViTImageProcessor:()=>XB,DPTFeatureExtractor:()=>ZB,DPTImageProcessor:()=>lV,DeiTFeatureExtractor:()=>JB,DeiTImageProcessor:()=>gV,DetrFeatureExtractor:()=>QB,DetrImageProcessor:()=>cV,DonutFeatureExtractor:()=>KB,DonutImageProcessor:()=>lJ,EfficientNetImageProcessor:()=>HB,GLPNFeatureExtractor:()=>GB,Gemma3ImageProcessor:()=>YB,Gemma4ImageProcessor:()=>uV,Glm46VImageProcessor:()=>WB,GroundingDinoImageProcessor:()=>qB,Idefics3ImageProcessor:()=>L$,ImageFeatureExtractor:()=>V0,ImageProcessor:()=>V0,JinaCLIPImageProcessor:()=>UB,Lfm2VlImageProcessor:()=>BB,LlavaOnevisionImageProcessor:()=>DB,Mask2FormerImageProcessor:()=>SB,MaskFormerFeatureExtractor:()=>MB,MaskFormerImageProcessor:()=>uJ,MobileNetV1FeatureExtractor:()=>LB,MobileNetV1ImageProcessor:()=>dV,MobileNetV2FeatureExtractor:()=>CB,MobileNetV2ImageProcessor:()=>pV,MobileNetV3FeatureExtractor:()=>RB,MobileNetV3ImageProcessor:()=>iV,MobileNetV4FeatureExtractor:()=>AB,MobileNetV4ImageProcessor:()=>rV,MobileViTFeatureExtractor:()=>PB,MobileViTImageProcessor:()=>aV,NougatImageProcessor:()=>EB,OwlViTFeatureExtractor:()=>wB,OwlViTImageProcessor:()=>mJ,Owlv2ImageProcessor:()=>TB,Phi3VImageProcessor:()=>vB,PixtralImageProcessor:()=>yB,PvtImageProcessor:()=>xB,Qwen2VLImageProcessor:()=>mV,RTDetrImageProcessor:()=>kB,Sam2ImageProcessor:()=>VJ,Sam3ImageProcessor:()=>VJ,SamImageProcessor:()=>VJ,SapiensFeatureExtractor:()=>hB,SapiensImageProcessor:()=>oV,SegformerFeatureExtractor:()=>bB,SegformerImageProcessor:()=>nV,SiglipImageProcessor:()=>fB,SmolVLMImageProcessor:()=>L$,Swin2SRImageProcessor:()=>_B,VLMImageProcessor:()=>FB,ViTFeatureExtractor:()=>gB,ViTImageProcessor:()=>sV,VitMatteImageProcessor:()=>cB,VitPoseImageProcessor:()=>lB,YolosFeatureExtractor:()=>uB,YolosImageProcessor:()=>tV});var aO=class extends V0{},oO=class extends V0{},nO=class extends V0{},sO=class extends V0{},fV=class extends V0{},tO=class extends fV{},_V=class extends V0{constructor(J){super(J);this.crop_pct=this.config.crop_pct??0.875}async resize(J){let Q=this.size?.shortest_edge;if(Q===void 0)throw Error("Size dictionary must contain 'shortest_edge' key.");if(Q<384){let X=Math.floor(Q/this.crop_pct),[K,Z]=this.get_resize_output_image_size(J,{shortest_edge:X});J=await J.resize(K,Z,{resample:this.resample}),J=await J.center_crop(Q,Q)}else J=await J.resize(Q,Q,{resample:this.resample});return J}},eO=class extends _V{},gV=class extends V0{},JB=class extends gV{},cV=class extends V0{async _call(J){let Q=await super._call(J),X=[Q.pixel_values.dims[0],64,64],K=$6(X,1n);return{...Q,pixel_mask:K}}post_process_object_detection(...J){return G7(...J)}post_process_panoptic_segmentation(...J){return hV(...J)}post_process_instance_segmentation(...J){return bV(...J)}},QB=class extends cV{},XB=class extends V0{},lJ=class extends V0{pad_image(J,Q,X,K={}){let[Z,H,Y]=Q,$=this.image_mean;if(!Array.isArray(this.image_mean))$=Array(Y).fill($);let V=this.image_std;if(!Array.isArray(V))V=Array(Y).fill($);let W=$.map((q,F)=>-q/V[F]);return super.pad_image(J,Q,X,{center:!0,constant_values:W,...K})}},KB=class extends lJ{},lV=class extends V0{},ZB=class extends lV{},HB=class extends V0{constructor(J){super(J);if(this.include_top=this.config.include_top??!0,this.include_top)this.image_std=this.image_std.map((Q)=>Q*Q)}},YB=class extends V0{};function $B(J,Q,X,K,Z){let H=K*X**2,Y=Math.sqrt(H/(J*Q)),$=Z*X,V=Math.floor(Y*J/$)*$,W=Math.floor(Y*Q/$)*$;if(V===0&&W===0)throw Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${$}.`);let q=Math.floor(K/Z**2)*$;if(V===0)V=$,W=Math.min(Math.floor(Q/J)*$,q);else if(W===0)W=$,V=Math.min(Math.floor(J/Q)*$,q);return[V,W]}function VB(J,Q,X,K,Z,H,Y){let $=Math.floor(Q/Z),V=Math.floor(X/Z),W=$*V,q=Z*Z*K,F=new Float32Array(H*q),N=0;for(let D=0;D<$;++D)for(let L=0;LH),0);let W=H.dims[0]/Y,q=H.dims[1],F=Math.floor(H.dims[2]/V),N=Math.floor(H.dims[3]/V),j=H.view(W,Y,q,Math.floor(F/$),$,V,Math.floor(N/$),$,V).permute(0,3,6,4,7,2,1,5,8).view(W*F*N,q*Y*V*V),B=new u("int64",[W,F,N],[1,3]);return{pixel_values:j,image_grid_thw:B,original_sizes:K,reshaped_input_sizes:Z}}},WB=class extends mV{get_resize_output_image_size(J,Q){let X=this.patch_size*this.merge_size,K=this.config.temporal_patch_size??2;return cJ(J.height,J.width,X,this.min_pixels,this.max_pixels,K)}},GB=class extends V0{},qB=class extends V0{async _call(J){let Q=await super._call(J),X=Q.pixel_values.dims,K=j6([X[0],X[2],X[3]]);return{...Q,pixel_mask:K}}},L$=class extends V0{constructor(J){super(J);this.do_image_splitting=J.do_image_splitting??!0,this.max_image_size=J.max_image_size}get_resize_for_vision_encoder(J,Q){let[X,K]=J.dims.slice(-2),Z=K/X;if(K>=X)K=Math.ceil(K/Q)*Q,X=Math.floor(K/Z),X=Math.ceil(X/Q)*Q;else X=Math.ceil(X/Q)*Q,K=Math.floor(X*Z),K=Math.ceil(K/Q)*Q;return{height:X,width:K}}async _call(J,{do_image_splitting:Q=null,return_row_col_info:X=!1}={}){let K;if(!Array.isArray(J))K=[[J]];else{if(J.length===0||!J[0])throw Error("No images provided.");if(!Array.isArray(J[0]))K=[J];else K=J}let Z=[],H=[],Y=[],$=[],V=[];for(let L of K){let M=await Promise.all(L.map((P)=>this.preprocess(P)));$.push(...M.map((P)=>P.original_size)),V.push(...M.map((P)=>P.reshaped_input_size)),M.forEach((P)=>P.pixel_values.unsqueeze_(0));let{longest_edge:R}=this.max_image_size,E;if(Q??this.do_image_splitting){let P=Array(M.length),w=Array(M.length);E=await Promise.all(M.map(async(k,C)=>{let c=this.get_resize_for_vision_encoder(k.pixel_values,R),g=await k6(k.pixel_values,{size:[c.height,c.width]}),{frames:d,num_splits_h:r,num_splits_w:i}=await this.split_image(g,this.max_image_size);return P[C]=r,w[C]=i,h0(d,0)})),H.push(P),Y.push(w)}else{let P=[R,R];E=await Promise.all(M.map((w)=>k6(w.pixel_values,{size:P}))),H.push(Array(M.length).fill(0)),Y.push(Array(M.length).fill(0))}Z.push(h0(E,0))}let W=Z.length,[q,F,N,j]=Z[0].dims,B,D;if(W===1)B=Z[0].unsqueeze_(0),D=$6([W,q,N,j],!0);else{let L=Math.max(...Z.map((E)=>E.dims.at(0)));D=$6([W,L,N,j],!0);let M=D.data,R=L*N*j;for(let E=0;EX||Y>K){$=Math.ceil(H/X),V=Math.ceil(Y/K);let W=Math.ceil(H/$),q=Math.ceil(Y/V);for(let j=0;j<$;++j)for(let B=0;BQ*this.rescale_factor)}pad_image(J,Q,X,K){return super.pad_image(J,Q,X,{constant_values:this.constant_values,center:!0,...K})}},UB=class extends V0{constructor(J){let{resize_mode:Q,fill_color:X,interpolation:K,size:Z,...H}=J,Y=Q==="squash"?{width:Z,height:Z}:Q==="shortest"?{shortest_edge:Z}:{longest_edge:Z},$=K==="bicubic"?3:2;super({...H,size:Y,resample:$,do_center_crop:!0,crop_size:Z,do_normalize:!0})}};function C$(J,Q){return Math.round(J/Q)*Q}function NB(J,Q,X,K,Z){let H=1/0,Y=[1,1],$=X*K;for(let V of Q){let W=Math.abs(J-V[0]/V[1]);if(W0.5*Z*Z*V[0]*V[1])Y=V}return Y}function jB(J,Q){let X=[],K=new Set;for(let Z=J;Z<=Q;++Z)for(let H=1;H<=Z;++H)for(let Y=1;Y<=Z;++Y){let $=H*Y;if($>=J&&$<=Q){let V=H<<16|Y;if(!K.has(V))K.add(V),X.push([H,Y])}}return X.sort((Z,H)=>Z[0]*Z[1]-H[0]*H[1])}function zB(J,Q){let[X,K,Z,H]=J.dims,Y=Math.floor(Z/Q),$=Math.floor(H/Q),V=Q*Q*K,W=J.data,q=new Float32Array(X*Y*$*V),F=Z*H;for(let N=0;Nthis.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(J,Q){let X=jB(this.min_tiles,this.max_tiles),[K,Z]=NB(Q/J,X,Q,J,this.tile_size);return{grid_width:K,grid_height:Z,target_width:this.tile_size*K,target_height:this.tile_size*Z}}async _call(J,{return_row_col_info:Q=null}={}){let X;if(!Array.isArray(J))X=[[J]];else if(!Array.isArray(J[0]))X=[J];else X=J;let K=[],Z=[],H=[],Y=[],$=[],V=[];for(let q of X){let F=await Promise.all(q.map((N)=>this.preprocess(N,{do_pad:!1})));for(let{pixel_values:N}of F){let[,j,B]=N.dims,D=N.unsqueeze_(0),L=this.encoder_patch_size*this.downsample_factor,M=L**2,[R,E]=cJ(Math.max(L,j),Math.max(L,B),L,this.min_image_tokens*M,this.max_image_tokens*M).map((g)=>Math.max(L,g)),P,w=1,k=1,C=this._is_image_too_large(j,B),c=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(C&&c){let{grid_width:g,grid_height:d,target_width:r,target_height:i}=this._get_grid_layout(j,B);w=d,k=g;let p=await k6(D,{size:[i,r]});P=[];for(let f=0;f(W-this.image_mean[q])/this.image_std[q]);return super.pad_image(J,Q,{width:$,height:Y},{center:!0,constant_values:V,...K})}async _call(J,{num_crops:Q=null}={}){if(this._num_crops=Q??=this.config.num_crops,Q<4||$J(Q)%1!==0)throw Error("num_crops must be a square number >= 4");if(!Array.isArray(J))J=[J];let X=J.length,K=await Promise.all(J.map((F)=>this.preprocess(F))),Z=K.map((F)=>F.original_size),H=K.map((F)=>F.reshaped_input_size),Y=[];for(let{pixel_values:F}of K){F.unsqueeze_(0);let[N,j]=F.dims.slice(-2),B=await k6(F,{size:[M6,M6],mode:"bicubic"});if(Q>0){let D=[],L=$J(Q),M=K8(j/L),R=K8(N/L);for(let P=0;PF.map((N)=>M6*YJ(N/M6))),W=new u("int64",V.flat(),[X,2]),q=V.map(([F,N])=>this.calc_num_image_tokens_from_image_size(N,F));return{pixel_values:$,original_sizes:Z,reshaped_input_sizes:H,image_sizes:W,num_img_tokens:q}}},yB=class extends V0{get_resize_output_image_size(J,Q){let{longest_edge:X}=Q;if(X===void 0)throw Error("size must contain 'longest_edge'");let[K,Z]=J.size,H=Math.max(K,Z)/X,Y=K,$=Z;if(H>1)Y=Math.floor(K/H),$=Math.floor(Z/H);let{patch_size:V,spatial_merge_size:W}=this.config;if(!W)throw Error("config must contain 'spatial_merge_size'");let q=V*W,F=Math.floor((Y-1)/q)+1,N=Math.floor(($-1)/q)+1;return[F*q,N*q]}},xB=class extends V0{},kB=class extends V0{post_process_object_detection(...J){return G7(...J)}},VJ=class extends V0{reshape_input_points(J,Q,X,K=!1){J=structuredClone(J);let Z=cY(J);if(Z.length===3){if(!K)Z=[1,...Z];J=[J]}else if(Z.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 H=0;HK!==Q.dims[Z]))throw Error(`The first ${X.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new u("int64",J.flat(1/0).map(BigInt),X)}async _call(J,{input_points:Q=null,input_labels:X=null,input_boxes:K=null}={}){let Z=await super._call(J);if(Q)Z.input_points=this.reshape_input_points(Q,Z.original_sizes,Z.reshaped_input_sizes);if(X){if(!Z.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");Z.input_labels=this.add_input_labels(X,Z.input_points)}if(K)Z.input_boxes=this.reshape_input_points(K,Z.original_sizes,Z.reshaped_input_sizes,!0);return Z}async post_process_masks(J,Q,X,{mask_threshold:K=0,binarize:Z=!0,pad_size:H=null}={}){let Y=[];H=H??this.pad_size??this.size;let $=[H.height,H.width];for(let V=0;VK)j[B]=1;F=new u("bool",j,F.dims)}Y.push(F)}return Y}generate_crop_boxes(J,Q,{crop_n_layers:X=0,overlap_ratio:K=0.3413333333333333,points_per_crop:Z=32,crop_n_points_downscale_factor:H=1}={}){}},oV=class extends V0{post_process_semantic_segmentation(...J){return kV(...J)}},hB=class extends oV{},nV=class extends V0{post_process_semantic_segmentation(...J){return kV(...J)}},bB=class extends nV{},fB=class extends V0{},_B=class extends V0{pad_image(J,Q,X,K={}){let[Z,H,Y]=Q;return super.pad_image(J,Q,{width:H+(X-H%X)%X,height:Z+(X-Z%X)%X},{mode:"symmetric",center:!1,constant_values:-1,...K})}},sV=class extends V0{},gB=class extends sV{},cB=class extends V0{async _call(J,Q){if(!Array.isArray(J))J=[J];if(!Array.isArray(Q))Q=[Q];let X=await Promise.all(J.map((H)=>this.preprocess(H))),K=await Promise.all(Q.map((H)=>this.preprocess(H,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:$5(X.map((H,Y)=>h0([H.pixel_values,K[Y].pixel_values],0)),0),original_sizes:X.map((H)=>H.original_size),reshaped_input_sizes:X.map((H)=>H.reshaped_input_size)}}},lB=class extends V0{post_process_pose_estimation(J,Q,{threshold:X=null}={}){let K=J.tolist(),[Z,H,Y,$]=J.dims,V=[];for(let W=0;W/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1000}construct_prompts(J){if(typeof J==="string")J=[J];let Q=[];for(let X of J)if(this.task_prompts_without_inputs.has(X))Q.push(this.task_prompts_without_inputs.get(X));else{for(let[K,Z]of this.task_prompts_with_input)if(X.includes(K)){Q.push(Z.replaceAll("{input}",X).replaceAll(K,""));break}if(Q.length!==J.length)Q.push(X)}return Q}post_process_generation(J,Q,X){let K=this.tasks_answer_post_processing_type.get(Q)??"pure_text";J=J.replaceAll("","").replaceAll("","");let Z;switch(K){case"pure_text":Z=J;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let H=K==="ocr"?"quad_boxes":"bboxes",Y=J.matchAll(this.regexes[H]),$=[],V=[];for(let[W,q,...F]of Y)$.push(q?q.trim():$.at(-1)??""),V.push(F.map((N,j)=>(Number(N)+0.5)/this.size_per_bin*X[j%2]));Z={labels:$,[H]:V};break;default:throw Error(`Task "${Q}" (of type "${K}") not yet implemented.`)}return{[Q]:Z}}async _call(J,Q=null,X={}){if(!J&&!Q)throw Error("Either text or images must be provided");let K=await this.image_processor(J,X),Z=Q?this.tokenizer(this.construct_prompts(Q),X):{};return{...K,...Z}}},dB=class extends R0{static tokenizer_class=C0;static image_processor_class=W6;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(J,Q,X){super(J,Q,X);this.image_seq_length=this.config.image_seq_length;let{boi_token:K,image_token:Z,eoi_token:H}=this.tokenizer.config;this.boi_token=K,this.image_token=Z,this.eoi_token=H;let Y=Z.repeat(this.image_seq_length);this.full_image_sequence=` ${K}${Y}${H} `}async _call(J,Q=null,X={}){if(typeof J==="string")J=[J];let K;if(Q)K=await this.image_processor(Q,X),J=J.map((H)=>H.replaceAll(this.boi_token,this.full_image_sequence));return{...this.tokenizer(J,X),...K}}},pB=class extends R0{static image_processor_class=W6;static feature_extractor_class=E6;static tokenizer_class=C0;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(J,Q,X){super(J,Q,X);this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:K,boa_token:Z,audio_token:H,eoa_token:Y,image_token_id:$,boi_token:V,image_token:W,eoi_token:q}=this.tokenizer.config;this.audio_token_id=K,this.boa_token=Z,this.audio_token=H;let F=H.repeat(this.audio_seq_length);this.full_audio_sequence=` ${Z}${F}${Y} `,this.image_token_id=$,this.boi_token=V,this.image_token=W;let N=W.repeat(this.image_seq_length);this.full_image_sequence=` ${V}${N}${q} `}async _call(J,Q=null,X=null,K={}){if(typeof J==="string")J=[J];let Z;if(X)Z=await this.feature_extractor(X,K),J=J.map(($)=>$.replaceAll(this.audio_token,this.full_audio_sequence));let H;if(Q)H=await this.image_processor(Q,K),J=J.map(($)=>$.replaceAll(this.image_token,this.full_image_sequence));return{...this.tokenizer(J,K),...H,...Z}}},iB=class extends R0{static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(J,Q,X){super(J,Q,X);this.audio_ms_per_token=this.config.audio_ms_per_token??40,this.audio_seq_length=this.config.audio_seq_length??750,this.image_seq_length=this.config.image_seq_length??280;let{audio_token:K,boa_token:Z,eoa_token:H,image_token:Y,boi_token:$,eoi_token:V}=this.tokenizer.config;this.audio_token=K,this.boa_token=Z,this.eoa_token=H,this.image_token=Y,this.boi_token=$,this.eoi_token=V}static async from_pretrained(J,Q={}){let[X,K,Z]=await Promise.all([s6(J,SV,!0,Q),C0.from_pretrained(J,Q),yJ(J,LV,!1,Q)]),H={tokenizer:K};if(X.image_processor)H.image_processor=new uV(X.image_processor);if(X.feature_extractor)H.feature_extractor=new IV(X.feature_extractor);return new this(X,H,Z)}_compute_audio_num_tokens(J,Q){let X=Math.round(Q*20/1000),K=Math.round(Q*10/1000),Z=Math.floor(X/2),H=Math.floor((J+Z-X-1)/K)+1;if(H<=0)return 0;for(let Y=0;Y<2;++Y)H=Math.floor((H-1)/2)+1;return Math.min(H,this.audio_seq_length)}async _call(J,Q=null,X=null,K={}){if(typeof J==="string")J=[J];let Z;if(Q){Z=await this.image_processor(Q,K);let Y=Z.num_soft_tokens_per_image,$=0;J=J.map((V)=>V.replaceAll(this.image_token,()=>` ${this.boi_token}${this.image_token.repeat(Y[$++])}${this.eoi_token} `))}let H;if(X){let Y=Array.isArray(X)?X:[X];H=await this.feature_extractor(Y[0],K);let $=this.feature_extractor.config.sampling_rate??16000,V=0;J=J.map((W)=>W.replaceAll(this.audio_token,()=>` ${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(Y[V++].length,$))}${this.eoa_token} `))}return{...this.tokenizer(J,K),...Z,...H}}},dJ=class extends R0{static image_processor_class=W6;static tokenizer_class=C0;static image_token="<|image_pad|>";async _call(J,Q=null,...X){if(!Array.isArray(J))J=[J];let K,Z;if(Q)K=await this.image_processor(Q),Z=K.image_grid_thw;if(Z){let Y=this.image_processor.config.merge_size**2,$=0,V=this.constructor.image_token,W=Z.tolist();J=J.map((q)=>{while(q.includes(V)){let F=Number(W[$++].reduce((N,j)=>N*j,1n));q=q.replace(V,"<|placeholder|>".repeat(Math.floor(F/Y)))}return q.replaceAll("<|placeholder|>",V)})}return{...this.tokenizer(J),...K}}},rB=class extends dJ{static image_token="<|image|>"},aB=class extends R0{static tokenizer_class=C0;static feature_extractor_class=E6;static uses_processor_config=!0;_get_num_audio_features(J){let{hop_length:Q}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:X,projector_downsample_rate:K}=this.feature_extractor.config,Z=Math.floor(X/K),H=Math.floor(J/Q)+1,Y=Math.floor(H/2);return Math.ceil(Y/X)*Z}async _call(J,Q=null,X={}){if(Array.isArray(J))throw Error("Batched inputs are not supported yet.");let K={};if(Q){let{input_features:H}=await this.feature_extractor(Q);K.input_features=H;let Y=this._get_num_audio_features(Q.length),$=new Uint8Array(Y).fill(1);K.input_features_mask=new u("bool",$,[1,Y]);let V=this.config.audio_token??"<|audio|>";if(!J.includes(V))throw Error(`The input text does not contain the audio token ${V}.`);J=J.replaceAll(V,V.repeat(Y))}return{...this.tokenizer(J,{add_special_tokens:!1,...X}),...K}}};function oB(J,Q){let K=J.dims.at(-1)-1,Z=J.tolist();Z.fill(!1,0,1),Z.fill(!1,K);let H=Q.tolist();return Z.map((Y,$)=>Y?$:null).filter((Y)=>Y!==null).map((Y)=>H[Y])}var nB=class extends R0{static tokenizer_class=C0;static image_processor_class=W6;async _call(J,Q,X={}){let K=J?await this.image_processor(J,X):{};return{...Q?this.tokenizer(Q,X):{},...K}}post_process_grounded_object_detection(J,Q,{box_threshold:X=0.25,text_threshold:K=0.25,target_sizes:Z=null}={}){let{logits:H,pred_boxes:Y}=J,$=H.dims[0];if(Z!==null&&Z.length!==$)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let V=H.dims.at(1),W=H.sigmoid(),q=W.max(-1).tolist(),F=Y.tolist().map((j)=>j.map((B)=>xV(B))),N=[];for(let j=0;j<$;++j){let B=Z!==null?Z[j]:null;if(B!==null)F[j]=F[j].map((E)=>E.map((P,w)=>P*B[(w+1)%2]));let D=q[j],L=[],M=[],R=[];for(let E=0;E`+Z.repeat(J);Y+=` `}return Y+=` ${K}${H}`+Z.repeat(J)+`${K}`,Y}function tB(J,Q,X,K){return`${Q}${K}`+X.repeat(J)+`${Q}`}function eB(J,Q,X,K,Z,H){if(J===0&&Q===0)return tB(X,K,Z,H);return sB(X,J,Q,K,Z,H)}var R$=class extends R0{static image_processor_class=W6;static tokenizer_class=C0;static uses_processor_config=!0;fake_image_token="";image_token="";global_img_token="";async _call(J,Q=null,X={}){X.return_row_col_info??=!0;let K;if(Q)K=await this.image_processor(Q,X);if(!Array.isArray(J))J=[J];let Z=K.rows??[Array(J.length).fill(0)],H=K.cols??[Array(J.length).fill(0)],Y=this.config.image_seq_len,$=[],V=[];for(let q=0;qeB(M,j[R],Y,this.fake_image_token,this.image_token,this.global_img_token)),D=F.split(this.image_token);if(D.length===0)throw Error("The image token should be present in the text.");let L=D[0];for(let M=0;MD.images).flatMap((D)=>D.images).map((D)=>h6.read(D)));else if(!Array.isArray(Q))Q=[Q];let K=this.tokenizer,Z=K.apply_chat_template(J,{tokenize:!1,add_generation_prompt:!0,chat_template:X}),H=(D)=>K.encode(D,{add_special_tokens:!1}),Y=Z.split(this.image_tag),$=Y.length-1;if(Q.length!==$)throw Error(`Number of images provided (${Q.length}) does not match number of "${this.image_tag}" image tags (${$})`);let[V,W,q]=K.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),F=H(Y[0]),N=Array(F.length).fill(!1);for(let D=1;D0){let D=await this.image_processor(Q);return D.pixel_values.unsqueeze_(0),{...B,...D}}return B}},QD=class extends R0{static tokenizer_class=C0;static image_processor_class=W6;async _call(J=null,Q=null,X={}){if(!J&&!Q)throw Error("Either text or images must be provided");let K=J?this.tokenizer(J,X):{},Z=Q?await this.image_processor(Q,X):{};return{...K,...Z}}},XD=class extends R0{static tokenizer_class=C0;static image_processor_class=W6;async _call(J,Q=null,X={}){let{image_rows:K,image_cols:Z,image_sizes:H,...Y}=await this.image_processor(J,{...X,return_row_col_info:!0});if(Q){let $=this.config.image_token??"",{tile_size:V=512,downsample_factor:W=2,encoder_patch_size:q=16,use_thumbnail:F=!0}=this.image_processor.config,N=(R)=>Math.ceil(Math.floor(R/q)/W),j=N(V)**2,B=this.config.image_start_token??"<|image_start|>",D=this.config.image_end_token??"<|image_end|>",L=this.config.image_thumbnail??"<|img_thumbnail|>";if(!Array.isArray(Q))Q=[Q];let M=0;Q=Q.map((R)=>{let E=R.split($);return E[0]+E.slice(1).map((P)=>{let w=M++,[k,C]=H[w],c=K[w],g=Z[w],d=N(k)*N(C),r=B;if(c>1||g>1){let i=$.repeat(j);for(let p=0;p`+i;if(F)r+=L+$.repeat(d)}else r+=$.repeat(d);return r+D+P}).join("")})}return{...Y,...Q?this.tokenizer(Q,X):{}}}},KD=class extends R0{static tokenizer_class=C0;static image_processor_class=W6;static uses_processor_config=!0;async _call(J,Q=null,X={}){let K=await this.image_processor(J,X);if(Q){let[H,Y]=K.pixel_values.dims.slice(-2),{image_token:$,patch_size:V,num_additional_image_tokens:W}=this.config,q=Math.floor(H/V)*Math.floor(Y/V)+W;if(Q=structuredClone(Q),!Array.isArray(Q))Q=[Q];for(let F=0;F0?B.reduce((L,M)=>L*M,1):0;V.push(j),$.push(D)}return[Z(V),$]}char_decode(J){return this.char_tokenizer.batch_decode(J).map((Q)=>Q.replaceAll(" ",""))}bpe_decode(J){return this.bpe_tokenizer.batch_decode(J)}wp_decode(J){return this.wp_tokenizer.batch_decode(J).map((Q)=>Q.replaceAll(" ",""))}batch_decode([J,Q,X]){let[K,Z]=this._decode_helper(J,"char"),[H,Y]=this._decode_helper(Q,"bpe"),[$,V]=this._decode_helper(X,"wp"),W=[],q=[];for(let F=0;F";function $D(J,Q,X,K,Z){return`${K.repeat(X*Z)}${Q}${J} `}var VD=class extends R0{static tokenizer_class=C0;static image_processor_class=W6;static uses_processor_config=!1;async _call(J,Q=null,X={}){if(!Q)$0.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),Q="";if(!Array.isArray(J))J=[J];if(!Array.isArray(Q))Q=[Q];let K=this.tokenizer.bos_token,Z=this.image_processor.config.image_seq_length,H;if(Q.some((V)=>V.includes(Z8)))H=Q.map((V)=>{let W=V.replaceAll(Z8,Z8.repeat(Z)),q=W.lastIndexOf(Z8),F=q===-1?0:q+Z8.length;return W.slice(0,F)+K+W.slice(F)+` `});else $0.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 `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),H=Q.map((V)=>$D(V,K,Z,Z8,J.length));let Y=this.tokenizer(H,X);return{...await this.image_processor(J,X),...Y}}},P$="<|image|>",WD=/<\|image_\d+\|>/g,GD=class extends R0{static image_processor_class=W6;static tokenizer_class=C0;async _call(J,Q=null,{padding:X=!0,truncation:K=!0,num_crops:Z=null}={}){if(!Array.isArray(J))J=[J];let H,Y;if(Q){Y=await this.image_processor(Q,{num_crops:Z});let{num_img_tokens:$}=Y,V=J.map((q,F)=>q.split(WD).join(P$.repeat($[F])));H=this.tokenizer(V,{padding:X,truncation:K});let W=this.tokenizer._tokenizer.token_to_id(P$);H.input_ids.map_((q)=>q==W?-q:q)}else H=this.tokenizer(J);return{...H,...Y}}},qD=class extends R0{static tokenizer_class=C0;static image_processor_class=W6;static uses_processor_config=!0;async _call(J,Q=null,X={}){let K=await this.image_processor(J,X);if(Q){let[H,Y]=K.pixel_values.dims.slice(-2),{image_token:$,image_break_token:V,image_end_token:W,patch_size:q,spatial_merge_size:F}=this.config,N=q*F,j=Math.floor(H/N),B=Math.floor(Y/N);if(Q=structuredClone(Q),!Array.isArray(Q))Q=[Q];for(let D=0;DDD(j,$)),W=V.map((j)=>j.length),q=V.flat(),F=(await Promise.all(q.map((j)=>this.feature_extractor(j,X)))).map((j)=>j.input_features);K.audio_values=F.length>1?h0(F,0):F[0];let N=H[0];for(let j=0;j0){if(W>H$)throw Error(`The number of external data chunks (${W}) exceeds the maximum allowed value (${H$}).`);let q=KW(Y,W);for(let F of q){let N=`${K.subfolder??""}/${F}`;V.push(new Promise(async(j,B)=>{let D=await e9(J,N,!0,K,$);j(D instanceof Uint8Array?{path:F,data:D}:F)}))}}else if(H.externalData!==void 0)V=H.externalData.map(async(q)=>{if(typeof q.data==="string"){let F=await e9(J,q.data,!0,K);return{...q,data:F}}return q});return Promise.all(V)}async function yD(J,Q,X,K=!1,Z=void 0){let H=X.config?.["transformers.js_config"]??{},Y=WV(X.device??H.device,Q,{warn:(R)=>$0.info(R)}),$=Jz(Y),V=H.device_config??{};if(V.hasOwnProperty(Y))H={...H,...V[Y]};let W=GV(X.dtype??H.dtype,Q,Y,{configDtype:H.dtype,warn:(R)=>$0.info(R)});if(!J7.hasOwnProperty(W))throw Error(`Invalid dtype: ${W}. Should be one of: ${Object.keys(u0).join(", ")}`);else if(Y==="webgpu"&&!U0.IS_NODE_ENV&&W===u0.fp16&&!await Kz())throw Error(`The device (${Y}) does not support fp16.`);let q=J7[W],F={...X.session_options};F.executionProviders??=$;let N=H.free_dimension_overrides;if(N)F.freeDimensionOverrides??=N;else if(Y.startsWith("webnn")&&!F.freeDimensionOverrides)$0.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"]["${Y}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let j=ID(J,Q,X,q),B=X.use_external_data_format??H.use_external_data_format,D=await vD(J,Q,q,X,B,F);if(D.length>0&&(!U0.IS_NODE_ENV||D.some((R)=>typeof R!=="string")))F.externalData=D;if(K&&Y==="webgpu"){let R=q7(X.config,{prefix:"present",session_name:Z});if(R.size>0&&!xJ()){let E={};for(let P of R)E[P]="gpu-buffer";F.preferredOutputLocation=E}}return{buffer_or_path:await j,session_options:F,session_config:{dtype:W,device:Y}}}async function xD(J,Q,X,K=void 0){return Object.fromEntries(await Promise.all(Object.keys(Q).map(async(Z)=>{let H=K?.[Z]??!1,{buffer_or_path:Y,session_options:$,session_config:V}=await yD(J,Q[Z],X,H,Z),W=await YV(Y,$,V);return[Z,W]})))}function ZW(J){for(let Q in J)if(VV(J[Q]))J[Q]=new u(J[Q]);else if(typeof J[Q]==="object")ZW(J[Q]);return J}async function O0(J,Q){let X=kD(J,Q);try{let K=Object.fromEntries(Object.entries(X).map(([H,Y])=>{let $=Y.ort_tensor;if(U0.IS_NODE_ENV){if(typeof Float16Array<"u"&&$.cpuData instanceof Float16Array)$.cpuData=new Uint16Array($.cpuData.buffer)}return[H,$]})),Z=await $V(J,K);return ZW(Z)}catch(K){let Z=Object.fromEntries(Object.entries(X).map(([H,Y])=>{let $={type:Y.type,dims:Y.dims,location:Y.location};if($.location!=="gpu-buffer")$.data=Y.data;return[H,$]}));throw $0.error(`An error occurred during model execution: "${K}".`),$0.error("Inputs given to model:",Z),K}}function kD(J,Q){let X=Object.create(null),K=[];for(let Y of J.inputNames){let $=Q[Y];if(!($ instanceof u)){K.push(Y);continue}X[Y]=xJ()?$.clone():$}if(K.length>0)throw Error(`An error occurred during model execution: "Missing the following inputs: ${K.join(", ")}.`);let Z=Object.keys(Q).length,H=J.inputNames.length;if(Z>H){let Y=Object.keys(Q).filter(($)=>!J.inputNames.includes($));$0.warn(`WARNING: Too many inputs were provided (${Z} > ${H}). The following inputs will be ignored: "${Y.join(", ")}".`)}return X}var r0=class{},Z0=class extends r0{constructor({logits:J,...Q}){super();this.logits=J;let X=Object.values(Q);if(X.length>0)this.attentions=X}},m0=class extends r0{constructor({logits:J}){super();this.logits=J}},a0=class extends r0{constructor({logits:J}){super();this.logits=J}},G6=class extends r0{constructor({start_logits:J,end_logits:Q}){super();this.start_logits=J,this.end_logits=Q}},m5=class extends r0{constructor({logits:J}){super();this.logits=J}},hD=class extends r0{constructor({alphas:J}){super();this.alphas=J}},g6=class extends z6{_call(J,Q){throw Error("`_call` should be implemented in a subclass")}},bD=class extends z6{_call(J,Q){throw Error("`_call` should be implemented in a subclass")}},MJ=class extends z6{constructor(){super();this.processors=[]}push(J){this.processors.push(J)}extend(J){this.processors.push(...J)}_call(J,Q){let X=Q;for(let K of this.processors)X=K(J,X);return X}[Symbol.iterator](){return this.processors.values()}},fD=class extends g6{constructor(J){super();this.bos_token_id=J}_call(J,Q){for(let X=0;X=1&&Z[Z.length-1]>=this.timestamp_begin,Y=Z.length<2||Z[Z.length-2]>=this.timestamp_begin;if(H)if(Y)K.subarray(this.timestamp_begin).fill(-1/0);else K.subarray(0,this.eos_token_id).fill(-1/0);if(J[X].length===this.begin_index&&this.max_initial_timestamp_index!==null){let q=this.timestamp_begin+this.max_initial_timestamp_index;K.subarray(q+1).fill(-1/0)}let $=lj(K),V=Math.log($.subarray(this.timestamp_begin).map(Math.exp).reduce((q,F)=>q+F)),W=c0($.subarray(0,this.timestamp_begin))[0];if(V>W)K.subarray(0,this.timestamp_begin).fill(-1/0)}return Q}},lD=class extends g6{constructor(J){super();this.no_repeat_ngram_size=J}getNgrams(J){let Q=J.length,X=[];for(let Z=0;Z1 to use the classifier free guidance processor, got guidance scale ${J}.`);this.guidance_scale=J}_call(J,Q){if(Q.dims[0]!==2*J.length)throw 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 ${Q.dims[0]} for the logits and ${J.length} for the input ids.`);let X=J.length,K=Q.slice([0,X],null),Z=Q.slice([X,Q.dims[0]],null);for(let H=0;HQ.length>=this.max_length)}},oD=class extends F7{constructor(J){super();if(!Array.isArray(J))J=[J];this.eos_token_id=J}_call(J,Q){return J.map((X)=>{let K=X.at(-1);return this.eos_token_id.some((Z)=>K==Z)})}};var U7=class extends z6{constructor(J){super();this.generation_config=J}async _call(J){return this.sample(J)}async sample(J){throw Error("sample should be implemented in subclasses.")}getLogits(J,Q){let X=J.dims.at(-1),K=J.data;if(Q===-1)K=K.slice(-X);else{let Z=Q*X;K=K.slice(Z,Z+X)}return K}randomSelect(J){return Rj(J)}static getSampler(J){if(J.do_sample)return new sD(J);else if(J.num_beams>1)return new tD(J);else{if(J.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${J.num_return_sequences}.`);return new nD(J)}}},nD=class extends U7{async sample(J){let Q=c0(J.data)[1];return[[BigInt(Q),0]]}},sD=class extends U7{async sample(J){let Q=J.dims.at(-1);if(this.generation_config.top_k>0)Q=Math.min(this.generation_config.top_k,Q);let[X,K]=await z8(J,Q),Z=K6(X.data);return Array.from({length:this.generation_config.num_beams},()=>{let H=this.randomSelect(Z);return[K.data[H],Math.log(Z[H])]})}},tD=class extends U7{async sample(J){let Q=J.dims.at(-1);if(this.generation_config.top_k>0)Q=Math.min(this.generation_config.top_k,Q);let[X,K]=await z8(J,Q),Z=K6(X.data);return Array.from({length:this.generation_config.num_beams},(H,Y)=>{return[K.data[Y],Math.log(Z[Y])]})}},eD=class{constructor(J){if(!J)return;for(let Q in J){if(Q in this)throw TypeError(`Key "${Q}" conflicts with an existing property on DynamicCache`);let X=J[Q];if(!(X instanceof u))throw TypeError(`Expected a Tensor for key "${Q}", got ${typeof X}`);this[Q]=X}}get_seq_length(){let J=this;if(Object.keys(J).length===0)return 0;for(let Q in J)if(Q.startsWith("past_key_values."))return J[Q].dims.at(-2);throw Error("Unable to determine sequence length from the cache.")}update(J){for(let Q in J){let X=this[Q],K=J[Q];if(X&&X!==K&&X.location==="gpu-buffer")X.dispose();this[Q]=K}}async dispose(){let J=[];for(let Q of Object.values(this))if(Q.location==="gpu-buffer")J.push(Q.dispose());await Promise.all(J)}},pJ=eD,m={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,VoxtralRealtime:16},H5={[m.DecoderOnly]:{sessions:(J,Q)=>({model:Q.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[m.DecoderOnlyWithoutHead]:{sessions:(J,Q)=>({model:Q.model_file_name??"model"})},[m.Seq2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[m.Vision2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[m.Musicgen]:{sessions:()=>({model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[m.EncoderDecoder]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[m.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[m.ImageTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(J,Q,X)=>{let K={...H5[m.ImageTextToText].text_only_sessions};if(!X)K.vision_encoder="vision_encoder";if(J.is_encoder_decoder)K.model="encoder_model";return K},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[m.AudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(J,Q,X)=>{let K={...H5[m.AudioTextToText].text_only_sessions};if(!X)K.audio_encoder="audio_encoder";return K},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[m.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(J,Q,X)=>{let K={...H5[m.ImageAudioTextToText].text_only_sessions};if(!X)K.audio_encoder="audio_encoder",K.vision_encoder="vision_encoder";return K},optional_configs:{generation_config:"generation_config.json"}},[m.Phi3V]:{sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[m.MultiModality]:{sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[m.AutoEncoder]:{sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[m.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[m.Chatterbox]:{sessions:()=>({embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[m.VoxtralRealtime]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(J,Q,X)=>{let K={...H5[m.VoxtralRealtime].text_only_sessions};if(!X)K.audio_encoder="audio_encoder";return K},cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:"generation_config.json"}},default:{sessions:(J,Q)=>({model:Q.model_file_name??"model"})}};function JM(J){return H5[J]?.text_only_sessions??null}function QM(J,Q,X={}){let K=H5[J]??H5.default;return{sessions:K.sessions(Q,X,X.textOnly??!1),cache_sessions:K.cache_sessions,optional_configs:K.optional_configs}}function VW(J,{warn:Q=!0}={}){let X=J.architectures||[];for(let K of X){let Z=Y5.get(K);if(Z!==void 0)return Z}if(J.model_type){let K=Y5.get(J.model_type);if(K!==void 0)return K;for(let Z of Object.values(Y8))if(Z.has(J.model_type)){let H=Y5.get(Z.get(J.model_type));if(H!==void 0)return H}}if(Q){let K=X.length>0?X.join(", "):"(none)";$0.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${K}] for model type '${J.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${W7}`)}return m.EncoderOnly}function WW(J,{config:Q=null,cache_dir:X=null,local_files_only:K=!1,revision:Z="main"}={}){if(Q!==null)return X9.from_pretrained(J,{config:Q,cache_dir:X,local_files_only:K,revision:Z});let H=JSON.stringify([J,X,K,Z]);return s$(H,()=>X9.from_pretrained(J,{config:Q,cache_dir:X,local_files_only:K,revision:Z}))}async function GW(J,{config:Q=null,dtype:X=null,device:K=null,model_file_name:Z=null}={}){Q=await WW(J,{config:Q});let H=["config.json"],Y=Q["transformers.js_config"]??{},$=Y.use_external_data_format,V="onnx",W=K??Y.device,q=X??Y.dtype,F=VW(Q),N=(D,L=null)=>{L=L??D;let M=WV(W,D),R=GV(q,D,M),E=J7[R]??"",P=`${L}${E}.onnx`,w=V?`${V}/${P}`:P;H.push(w);let k=XW($,P,D);for(let C of KW(P,k)){let c=V?`${V}/${C}`:C;H.push(c)}},{sessions:j,optional_configs:B}=QM(F,Q,{model_file_name:Z});for(let[D,L]of Object.entries(j))N(D,L);if(B)for(let D of Object.values(B))H.push(D);return H}var Y8=null;function XM(J){Y8=J}function SJ(J){if(J instanceof u)return J;if(J.length===0)throw Error("items must be non-empty");if(Array.isArray(J[0])){if(J.some((Q)=>Q.length!==J[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new u("int64",BigInt64Array.from(J.flat().map((Q)=>BigInt(Q))),[J.length,J[0].length])}else return new u("int64",BigInt64Array.from(J.map((Q)=>BigInt(Q))),[1,J.length])}function qW(J){return new u("bool",[J],[1])}var w$={[m.DecoderOnly]:{can_generate:!0,forward:V5,prepare_inputs:t8},[m.DecoderOnlyWithoutHead]:{can_generate:!1,forward:V5,prepare_inputs:t8},[m.Seq2Seq]:{can_generate:!0,forward:d9,prepare_inputs:X7},[m.Vision2Seq]:{can_generate:!0,forward:d9,prepare_inputs:X7},[m.Musicgen]:{can_generate:!0,forward:d9},[m.EncoderDecoder]:{can_generate:!1,forward:d9},[m.ImageTextToText]:{can_generate:!0,forward:YM,prepare_inputs:p9},[m.AudioTextToText]:{can_generate:!0,forward:HM,prepare_inputs:p9},[m.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:p9},[m.Phi3V]:{can_generate:!0,prepare_inputs:p9},[m.MultiModality]:{can_generate:!0},[m.AutoEncoder]:{can_generate:!1,forward:KM},[m.Chatterbox]:{can_generate:!0,forward:R5},[m.VoxtralRealtime]:{can_generate:!0,prepare_inputs:t8},default:{can_generate:!1,forward:R5}};function T$(J,Q){let X=Y5.get(J),K=!1,Z=Q?.architectures?.[0];if(Z&&Z!==J&&J?.endsWith("ForCausalLM")&&Z.endsWith("ForConditionalGeneration")){let $=Y5.get(Z);if($!==void 0)X=$,K=!0}let H=w$[X]??w$.default,Y=H5[X]??H5.default;return{typeConfig:{...H,...Y},textOnly:K,modelType:X}}var Y5=new Map,iJ=new Map,F8=new Map,T=class extends z6{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];_return_dict_in_generate_keys=null;constructor(J,Q,X){super();this.config=J,this.sessions=Q,this.configs=X;let K=F8.get(this.constructor),{typeConfig:Z}=T$(K,J);if(this.can_generate=Z.can_generate,this._forward=Z.forward,this._prepare_inputs_for_generation=Z.prepare_inputs,this.can_generate)this.forward_params.push("past_key_values");this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){let J=[];for(let Q of Object.values(this.sessions))J.push(Q.release?.());return await Promise.all(J)}static async from_pretrained(J,{progress_callback:Q=null,config:X=null,cache_dir:K=null,local_files_only:Z=!1,revision:H="main",model_file_name:Y=null,subfolder:$="onnx",device:V=null,dtype:W=null,use_external_data_format:q=null,session_options:F={}}={}){let N={progress_callback:Q,config:X,cache_dir:K,local_files_only:Z,revision:H,model_file_name:Y,subfolder:$,device:V,dtype:W,use_external_data_format:q,session_options:F},j=F8.get(this);X=N.config=await X9.from_pretrained(J,N);let{typeConfig:B,textOnly:D,modelType:L}=T$(j,X);if(L===void 0){let P=j??X?.model_type;if(P!=="custom")$0.warn(`Model type for '${P}' not found, assuming encoder-only architecture. Please report this at ${W7}.`)}if(Q&&!(Q instanceof FJ)){let P={};try{let w=await GW(J,{config:X,dtype:W,device:V,model_file_name:Y});(await Promise.all(w.map((C)=>H9(J,C,N)))).forEach((C,c)=>{if(C.exists){let g=w[c]==="config.json";P[w[c]]={loaded:g?C.size??0:0,total:C.size??0}}})}catch(w){$0.warn(`Unable to fetch model file metadata for total progress tracking: ${w}`)}if(Object.keys(P).length>0)N.progress_callback=new FJ(Q,P)}let M=B.sessions(X,N,D),R=[xD(J,M,N,B.cache_sessions)];if(B.optional_configs)R.push(VM(J,B.optional_configs,N));let E=await Promise.all(R);return new this(X,...E)}async _call(J){return await this.forward(J)}async forward(J){return await this._forward(this,J)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(J,Q,X=null){let K=new MJ;if(J.repetition_penalty!==null&&J.repetition_penalty!==1)K.push(new uD(J.repetition_penalty));if(J.no_repeat_ngram_size!==null&&J.no_repeat_ngram_size>0)K.push(new lD(J.no_repeat_ngram_size));if(J.bad_words_ids!==null)K.push(new pD(J.bad_words_ids,J.eos_token_id));if(J.min_length!==null&&J.eos_token_id!==null&&J.min_length>0)K.push(new mD(J.min_length,J.eos_token_id));if(J.min_new_tokens!==null&&J.eos_token_id!==null&&J.min_new_tokens>0)K.push(new dD(Q,J.min_new_tokens,J.eos_token_id));if(J.forced_bos_token_id!==null)K.push(new fD(J.forced_bos_token_id));if(J.forced_eos_token_id!==null)K.push(new _D(J.max_length,J.forced_eos_token_id));if(J.suppress_tokens!==null)K.push(new gD(J.suppress_tokens));if(J.begin_suppress_tokens!==null){let Z=Q>1||J.forced_bos_token_id===null?Q:Q+1;K.push(new HW(J.begin_suppress_tokens,Z))}if(J.guidance_scale!==null&&J.guidance_scale>1)K.push(new iD(J.guidance_scale));if(J.temperature===0&&J.do_sample)$0.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`."),J.do_sample=!1;if(J.do_sample){if(J.temperature!==null&&J.temperature!==1)K.push(new rD(J.temperature))}if(X!==null)K.extend(X);return K}_prepare_generation_config(J,Q,X=YW){let K={...this.config};for(let H of["decoder","generator","text_config"])if(H in K)Object.assign(K,K[H]);let Z=new X(K);if(Object.assign(Z,this.generation_config??{}),J)Object.assign(Z,J);if(Q)Object.assign(Z,e0(Q,Object.getOwnPropertyNames(Z)));return Z}_get_stopping_criteria(J,Q=null){let X=new $W;if(J.max_length!==null)X.push(new aD(J.max_length,this.config.max_position_embeddings??null));if(J.eos_token_id!==null)X.push(new oD(J.eos_token_id));if(Q)X.extend(Q);return X}_validate_model_class(){if(!this.can_generate){let J=[Y8.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,Y8.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,Y8.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,Y8.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),Q=F8.get(this.constructor),X=new Set,K=this.config.model_type;for(let H of J){let Y=H?.get(K);if(Y)X.add(Y)}let Z=`The current model class (${Q}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;if(X.size>0)Z+=` Please use the following class instead: ${[...X].join(", ")}`;throw Error(Z)}}prepare_inputs_for_generation(...J){if(!this._prepare_inputs_for_generation)throw Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...J)}_update_model_kwargs_for_generation({generated_input_ids:J,outputs:Q,model_inputs:X,is_encoder_decoder:K}){if(X.past_key_values=LJ(Q,X.past_key_values),X.input_ids=new u("int64",J.flat(),[J.length,1]),!K)X.attention_mask=h0([X.attention_mask,j6([X.attention_mask.dims[0],1])],1);else if("decoder_attention_mask"in X)X.decoder_attention_mask=h0([X.decoder_attention_mask,j6([X.decoder_attention_mask.dims[0],1])],1);return X.position_ids=null,X}_prepare_model_inputs({inputs:J,bos_token_id:Q,model_kwargs:X}){let K=e0(X,this.forward_params),Z=this.main_input_name;if(Z in K){if(J)throw Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else K[Z]=J;return{inputs_tensor:K[Z],model_inputs:K,model_input_name:Z}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:J,model_inputs:Q,model_input_name:X,generation_config:K}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!Q.inputs_embeds&&"_prepare_inputs_embeds"in this){let{input_ids:H,pixel_values:Y,attention_mask:$,...V}=Q,W=await this._prepare_inputs_embeds(Q);Q={...V,...e0(W,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Z}=await R5(this,Q);if(K.guidance_scale!==null&&K.guidance_scale>1){if(Z=h0([Z,zJ(Z,0)],0),"attention_mask"in Q)Q.attention_mask=h0([Q.attention_mask,jV(Q.attention_mask)],0)}else if(Q.decoder_input_ids){let H=SJ(Q.decoder_input_ids).dims[0];if(H!==Z.dims[0]){if(Z.dims[0]!==1)throw Error(`The encoder outputs have a different batch size (${Z.dims[0]}) than the decoder inputs (${H}).`);Z=h0(Array.from({length:H},()=>Z),0)}}return Q.encoder_outputs=Z,Q}_prepare_decoder_input_ids_for_generation({batch_size:J,model_input_name:Q,model_kwargs:X,decoder_start_token_id:K,bos_token_id:Z,generation_config:H}){let{decoder_input_ids:Y,...$}=X;if(!(Y instanceof u)){if(!Y)if(K??=Z,this.config.model_type==="musicgen")Y=Array.from({length:J*this.config.decoder.num_codebooks},()=>[K]);else if(Array.isArray(K)){if(K.length!==J)throw Error(`\`decoder_start_token_id\` expcted to have length ${J} but got ${K.length}`);Y=K}else Y=Array.from({length:J},()=>[K]);else if(!Array.isArray(Y[0]))Y=Array.from({length:J},()=>Y);Y=SJ(Y)}return $.decoder_attention_mask=UV(Y),{input_ids:Y,model_inputs:$}}async generate({inputs:J=null,generation_config:Q=null,logits_processor:X=null,stopping_criteria:K=null,streamer:Z=null,...H}){this._validate_model_class(),Q=this._prepare_generation_config(Q,H);let{inputs_tensor:Y,model_inputs:$,model_input_name:V}=this._prepare_model_inputs({inputs:J,model_kwargs:H}),W=this.config.is_encoder_decoder;if(!W);else if(!("encoder_outputs"in $))$=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Y,model_inputs:$,model_input_name:V,generation_config:Q});let q;if(W)({input_ids:q,model_inputs:$}=this._prepare_decoder_input_ids_for_generation({batch_size:$[V].dims.at(0),model_input_name:V,model_kwargs:$,decoder_start_token_id:Q.decoder_start_token_id,bos_token_id:Q.bos_token_id,generation_config:Q}));else q=$[V];let F=q.dims.at(-1);if(Q.max_new_tokens!==null)Q.max_length=F+Q.max_new_tokens;let N=this._get_logits_processor(Q,F,X),j=this._get_stopping_criteria(Q,K),B=$[V].dims.at(0),D=U7.getSampler(Q),L=Array(B).fill(0),M=q.tolist();if(Z)Z.put(M);let R,E={},P={};while(!0){if($=this.prepare_inputs_for_generation(M,$,Q),R=await this.forward($),Q.return_dict_in_generate){if(Q.output_attentions){let p=ZM(R);for(let f in p){if(!(f in E))E[f]=[];E[f].push(p[f])}}else if(this._return_dict_in_generate_keys)Object.assign(P,e0(R,this._return_dict_in_generate_keys))}let g=R.logits.slice(null,-1,null).to("float32"),d=N(M,g),r=[];for(let p=0;pp))break;$=this._update_model_kwargs_for_generation({generated_input_ids:r,outputs:R,model_inputs:$,is_encoder_decoder:W})}if(Z)Z.end();let w=new u("int64",M.flat(),[M.length,M[0].length]),k=LJ(R,$.past_key_values),C=new Set(Object.values(k));for(let g of Object.values(R))if(g.location==="gpu-buffer"&&!C.has(g))g.dispose();if(!(("past_key_values"in H)||Q.return_dict_in_generate))await k.dispose();if(Q.return_dict_in_generate)return{sequences:w,past_key_values:k,...E,...P};return w}async _encode_input(J,Q,X){if(!Object.hasOwn(this.sessions,J))throw Error(`Model does not have a ${J} session.`);let K=this.sessions[J];return(await O0(K,e0(Q,K.inputNames)))[X]}async encode_image(J){return this._encode_input("vision_encoder",J,"image_features")}async encode_text(J){return this._encode_input("embed_tokens",J,"inputs_embeds")}async encode_audio(J){return this._encode_input("audio_encoder",J,"audio_features")}};async function d9(J,Q){let{encoder_outputs:X,input_ids:K,decoder_input_ids:Z,decoder_attention_mask:H,...Y}=Q;if(!X){let $=e0(Q,J.sessions.model.inputNames);X=(await R5(J,$)).last_hidden_state}if(Y.input_ids=Z,Y.encoder_hidden_states=X,J.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask"))Y.encoder_attention_mask=Q.attention_mask;if(H&&!Y.attention_mask)Y.attention_mask=H;return await V5(J,Y,!0)}async function R5(J,Q){let X=J.sessions.model,K=e0(Q,X.inputNames);if(X.inputNames.includes("inputs_embeds")&&!K.inputs_embeds){if(!Q.input_ids)throw Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");K.inputs_embeds=await J.encode_text({input_ids:Q.input_ids})}if(X.inputNames.includes("token_type_ids")&&!K.token_type_ids){if(!K.input_ids)throw Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");K.token_type_ids=jV(K.input_ids)}if(X.inputNames.includes("pixel_mask")&&!K.pixel_mask){if(!K.pixel_values)throw Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");let Z=K.pixel_values.dims;K.pixel_mask=j6([Z[0],Z[2],Z[3]])}return await O0(X,K)}async function KM(J,Q){let X=await J.encode(Q);return await J.decode(X)}function LJ(J,Q){let X=Object.create(null);for(let K in J)if(K.startsWith("present")){let Z=K.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present_recurrent","past_recurrent").replace("present","past_key_values");if(K.includes("encoder")&&Q)X[Z]=Q[Z];else X[Z]=J[K]}if(Q)return Q.update(X),Q;return new pJ(X)}function ZM(J){let Q={};for(let X of["cross_attentions","encoder_attentions","decoder_attentions"])for(let K in J)if(K.startsWith(X)){if(!(X in Q))Q[X]=[];Q[X].push(J[K])}return Q}function FW(J,Q){return J.map((X)=>{if(typeof X==="number")return X;return Q[X]??0})}function rJ(J,Q,X){if(X&&Object.keys(X).length>0)return Object.assign(Q,X),X;let K=J.sessions.decoder_model_merged??J.sessions.model,Z=(Q[J.main_input_name]??Q.attention_mask)?.dims?.[0]??1,H=q7(J.config),Y=J.config?.normalized_config?.num_heads,$={batch_size:Z};if(typeof Y==="number")$["batch_size x num_heads"]=Z*Y;let V=Object.create(null);for(let W of K.inputMetadata){if(!H.has(W.name))continue;let q=FW(W.shape,$),F=q.reduce((B,D)=>B*D,1),N=J9[W.type],j=new u(W.type,new N(F),q);Q[W.name]=j,V[W.name]=j}if(X)return X.update(V),X;return new pJ(V)}async function V5(J,Q,X=!1){let K=J.sessions[X?"decoder_model_merged":"model"],{past_key_values:Z,...H}=Q;if(K.inputNames.includes("use_cache_branch"))H.use_cache_branch=qW(Z!=null&&Object.keys(Z).length>0);if(K.inputNames.includes("position_ids")&&H.attention_mask&&!H.position_ids){let $=["paligemma","gemma3_text","gemma3"].includes(J.config.model_type)?1:0;H.position_ids=$M(H,Z,$)}if(K.inputNames.includes("num_logits_to_keep")&&!H.num_logits_to_keep)H.num_logits_to_keep=new u("int64",[0n],[]);rJ(J,H,Z);let Y=e0(H,K.inputNames);return await O0(K,Y)}async function UW(J,{encode_function:Q,merge_function:X,modality_input_names:K,modality_output_name:Z,input_ids:H=null,attention_mask:Y=null,position_ids:$=null,inputs_embeds:V=null,past_key_values:W=null,generation_config:q=null,logits_processor:F=null,...N}){if(!V){V=await J.encode_text({input_ids:H,...N});let B=e0(N,K);if(Object.keys(B).length>0){if(H.dims[1]!==1){let D=await Q({...B,...N});({inputs_embeds:V,attention_mask:Y}=X({[Z]:D,inputs_embeds:V,input_ids:H,attention_mask:Y}))}else if(W&&H.dims[1]===1){let D=H.dims[1],L=W.get_seq_length();Y=h0([j6([H.dims[0],L]),Y.slice(null,[Y.dims[1]-D,Y.dims[1]])],1)}}}if(!$){if(["qwen2_vl","qwen2_vl_text","qwen2_5_vl","qwen2_5_vl_text","qwen3_vl","qwen3_vl_text","qwen3_vl_moe","qwen3_vl_moe_text","qwen3_5","qwen3_5_text","qwen3_5_moe","qwen3_5_moe_text","glm_ocr","glm_ocr_text"].includes(J.config.model_type)){let{image_grid_thw:B,video_grid_thw:D}=N;[$]=J.get_rope_index(H,B,D,Y)}}return await V5(J,{inputs_embeds:V,past_key_values:W,attention_mask:Y,position_ids:$,generation_config:q,logits_processor:F},!0)}async function HM(J,Q){return await UW(J,{...Q,modality_input_names:["audio_values","input_features"],modality_output_name:"audio_features",encode_function:J.encode_audio.bind(J),merge_function:J._merge_input_ids_with_audio_features.bind(J)})}async function YM(J,Q){return await UW(J,{...Q,modality_input_names:["pixel_values"],modality_output_name:"image_features",encode_function:J.encode_image.bind(J),merge_function:J._merge_input_ids_with_image_features.bind(J)})}function NW(J,Q=0){let[X,K]=J.dims,Z=J.data,H=new BigInt64Array(Z.length);for(let Y=0;YY.dims[1]);else if(Z[Z.at(-1)]);return{...X,decoder_input_ids:SJ(Q)}}function p9(J,...Q){if(J.config.is_encoder_decoder)return X7(J,...Q);else return t8(J,...Q)}function jW({modality_token_id:J,inputs_embeds:Q,modality_features:X,input_ids:K,attention_mask:Z}){let H=K.tolist().map((W)=>W.reduce((q,F,N)=>{if(F==J)q.push(N);return q},[])),Y=H.reduce((W,q)=>W+q.length,0),$=X.dims[0];if(Y!==$)throw Error(`Number of tokens and features do not match: tokens: ${Y}, features ${$}`);let V=0;for(let W=0;W{let Z=await s6(J,Q[K],!1,X);return[K,Z]})))}var oJ={};U8(oJ,{ASTForAudioClassification:()=>MM,ASTModel:()=>DM,ASTPreTrainedModel:()=>eJ,AfmoeForCausalLM:()=>zM,AfmoeModel:()=>jM,AfmoePreTrainedModel:()=>sJ,AlbertForMaskedLM:()=>FM,AlbertForQuestionAnswering:()=>qM,AlbertForSequenceClassification:()=>GM,AlbertModel:()=>WM,AlbertPreTrainedModel:()=>Y9,ApertusForCausalLM:()=>NM,ApertusModel:()=>UM,ApertusPreTrainedModel:()=>nJ,ArceeForCausalLM:()=>BM,ArceeModel:()=>OM,ArceePreTrainedModel:()=>tJ,BartForConditionalGeneration:()=>LM,BartForSequenceClassification:()=>CM,BartModel:()=>SM,BartPretrainedModel:()=>N7,BeitForImageClassification:()=>AM,BeitModel:()=>RM,BeitPreTrainedModel:()=>JQ,BertForMaskedLM:()=>EM,BertForQuestionAnswering:()=>IM,BertForSequenceClassification:()=>wM,BertForTokenClassification:()=>TM,BertModel:()=>PM,BertPreTrainedModel:()=>O8,BlenderbotForConditionalGeneration:()=>yM,BlenderbotModel:()=>vM,BlenderbotPreTrainedModel:()=>QQ,BlenderbotSmallForConditionalGeneration:()=>kM,BlenderbotSmallModel:()=>xM,BlenderbotSmallPreTrainedModel:()=>XQ,BloomForCausalLM:()=>bM,BloomModel:()=>hM,BloomPreTrainedModel:()=>KQ,CHMv2ForDepthEstimation:()=>dM,CHMv2PreTrainedModel:()=>MW,CLIPModel:()=>iM,CLIPPreTrainedModel:()=>d5,CLIPSegForImageSegmentation:()=>sM,CLIPSegModel:()=>nM,CLIPSegPreTrainedModel:()=>ZQ,CLIPTextModel:()=>rM,CLIPTextModelWithProjection:()=>CW,CLIPVisionModel:()=>aM,CLIPVisionModelWithProjection:()=>oM,CamembertForMaskedLM:()=>_M,CamembertForQuestionAnswering:()=>lM,CamembertForSequenceClassification:()=>gM,CamembertForTokenClassification:()=>cM,CamembertModel:()=>fM,CamembertPreTrainedModel:()=>B8,ChatterboxModel:()=>BW,ChatterboxPreTrainedModel:()=>OW,ChineseCLIPModel:()=>mM,ChineseCLIPPreTrainedModel:()=>DW,ClapAudioModelWithProjection:()=>LW,ClapModel:()=>pM,ClapPreTrainedModel:()=>j7,ClapTextModelWithProjection:()=>SW,CodeGenForCausalLM:()=>eM,CodeGenModel:()=>tM,CodeGenPreTrainedModel:()=>HQ,Cohere2ForCausalLM:()=>KS,Cohere2Model:()=>XS,Cohere2PreTrainedModel:()=>$Q,CohereAsrForConditionalGeneration:()=>HS,CohereAsrModel:()=>ZS,CohereAsrPreTrainedModel:()=>VQ,CohereForCausalLM:()=>QS,CohereModel:()=>JS,CoherePreTrainedModel:()=>YQ,ConvBertForMaskedLM:()=>$S,ConvBertForQuestionAnswering:()=>GS,ConvBertForSequenceClassification:()=>VS,ConvBertForTokenClassification:()=>WS,ConvBertModel:()=>YS,ConvBertPreTrainedModel:()=>D8,ConvNextForImageClassification:()=>FS,ConvNextModel:()=>qS,ConvNextPreTrainedModel:()=>WQ,ConvNextV2ForImageClassification:()=>NS,ConvNextV2Model:()=>US,ConvNextV2PreTrainedModel:()=>GQ,DFineForObjectDetection:()=>BS,DFineModel:()=>OS,DFinePreTrainedModel:()=>FQ,DINOv3ConvNextModel:()=>dS,DINOv3ConvNextPreTrainedModel:()=>yW,DINOv3ViTModel:()=>pS,DINOv3ViTPreTrainedModel:()=>xW,DPTForDepthEstimation:()=>eS,DPTModel:()=>tS,DPTPreTrainedModel:()=>BQ,DacDecoderModel:()=>EW,DacDecoderOutput:()=>AW,DacEncoderModel:()=>PW,DacEncoderOutput:()=>RW,DacModel:()=>DS,DacPreTrainedModel:()=>z7,DebertaForMaskedLM:()=>SS,DebertaForQuestionAnswering:()=>RS,DebertaForSequenceClassification:()=>LS,DebertaForTokenClassification:()=>CS,DebertaModel:()=>MS,DebertaPreTrainedModel:()=>M8,DebertaV2ForMaskedLM:()=>wS,DebertaV2ForQuestionAnswering:()=>vS,DebertaV2ForSequenceClassification:()=>TS,DebertaV2ForTokenClassification:()=>IS,DebertaV2Model:()=>ES,DebertaV2PreTrainedModel:()=>S8,DecisionTransformerModel:()=>yS,DecisionTransformerPreTrainedModel:()=>wW,DeepseekV3ForCausalLM:()=>PS,DeepseekV3Model:()=>AS,DeepseekV3PreTrainedModel:()=>UQ,DeiTForImageClassification:()=>kS,DeiTModel:()=>xS,DeiTPreTrainedModel:()=>NQ,DepthAnythingForDepthEstimation:()=>hS,DepthAnythingPreTrainedModel:()=>TW,DepthProForDepthEstimation:()=>bS,DepthProPreTrainedModel:()=>IW,DetrForObjectDetection:()=>_S,DetrForSegmentation:()=>gS,DetrModel:()=>fS,DetrObjectDetectionOutput:()=>jQ,DetrPreTrainedModel:()=>O7,DetrSegmentationOutput:()=>vW,Dinov2ForImageClassification:()=>lS,Dinov2Model:()=>cS,Dinov2PreTrainedModel:()=>zQ,Dinov2WithRegistersForImageClassification:()=>mS,Dinov2WithRegistersModel:()=>uS,Dinov2WithRegistersPreTrainedModel:()=>OQ,DistilBertForMaskedLM:()=>nS,DistilBertForQuestionAnswering:()=>oS,DistilBertForSequenceClassification:()=>rS,DistilBertForTokenClassification:()=>aS,DistilBertModel:()=>iS,DistilBertPreTrainedModel:()=>L8,DonutSwinModel:()=>sS,DonutSwinPreTrainedModel:()=>kW,EdgeTamModel:()=>GP,EfficientNetForImageClassification:()=>QL,EfficientNetModel:()=>JL,EfficientNetPreTrainedModel:()=>DQ,ElectraForMaskedLM:()=>KL,ElectraForQuestionAnswering:()=>YL,ElectraForSequenceClassification:()=>ZL,ElectraForTokenClassification:()=>HL,ElectraModel:()=>XL,ElectraPreTrainedModel:()=>C8,Ernie4_5ForCausalLM:()=>VL,Ernie4_5Model:()=>$L,Ernie4_5PretrainedModel:()=>MQ,EsmForMaskedLM:()=>GL,EsmForSequenceClassification:()=>qL,EsmForTokenClassification:()=>FL,EsmModel:()=>WL,EsmPreTrainedModel:()=>V9,EuroBertForMaskedLM:()=>NL,EuroBertForSequenceClassification:()=>jL,EuroBertForTokenClassification:()=>zL,EuroBertModel:()=>UL,EuroBertPreTrainedModel:()=>W9,ExaoneForCausalLM:()=>BL,ExaoneModel:()=>OL,ExaonePreTrainedModel:()=>SQ,FalconForCausalLM:()=>ML,FalconH1ForCausalLM:()=>LL,FalconH1Model:()=>SL,FalconH1PreTrainedModel:()=>CQ,FalconModel:()=>DL,FalconPreTrainedModel:()=>LQ,FastViTForImageClassification:()=>RL,FastViTModel:()=>CL,FastViTPreTrainedModel:()=>RQ,Florence2ForConditionalGeneration:()=>AL,Florence2PreTrainedModel:()=>hW,GLPNForDepthEstimation:()=>uL,GLPNModel:()=>lL,GLPNPreTrainedModel:()=>yQ,GPT2LMHeadModel:()=>tL,GPT2Model:()=>sL,GPT2PreTrainedModel:()=>fQ,GPTBigCodeForCausalLM:()=>dL,GPTBigCodeModel:()=>mL,GPTBigCodePreTrainedModel:()=>xQ,GPTJForCausalLM:()=>JC,GPTJModel:()=>eL,GPTJPreTrainedModel:()=>_Q,GPTNeoForCausalLM:()=>iL,GPTNeoModel:()=>pL,GPTNeoPreTrainedModel:()=>kQ,GPTNeoXForCausalLM:()=>aL,GPTNeoXModel:()=>rL,GPTNeoXPreTrainedModel:()=>hQ,Gemma2ForCausalLM:()=>TL,Gemma2Model:()=>wL,Gemma2PreTrainedModel:()=>PQ,Gemma3ForCausalLM:()=>xL,Gemma3ForConditionalGeneration:()=>_W,Gemma3Model:()=>yL,Gemma3PreTrainedModel:()=>fW,Gemma3nForCausalLM:()=>kL,Gemma3nForConditionalGeneration:()=>B7,Gemma3nPreTrainedModel:()=>gW,Gemma4ForCausalLM:()=>hL,Gemma4ForConditionalGeneration:()=>EQ,GemmaForCausalLM:()=>EL,GemmaModel:()=>PL,GemmaPreTrainedModel:()=>AQ,GlmForCausalLM:()=>fL,GlmModel:()=>bL,GlmMoeDsaForCausalLM:()=>gL,GlmMoeDsaModel:()=>_L,GlmMoeDsaPreTrainedModel:()=>TQ,GlmOcrForConditionalGeneration:()=>cL,GlmPreTrainedModel:()=>wQ,GptOssForCausalLM:()=>nL,GptOssModel:()=>oL,GptOssPreTrainedModel:()=>bQ,GraniteForCausalLM:()=>XC,GraniteModel:()=>QC,GraniteMoeHybridForCausalLM:()=>ZC,GraniteMoeHybridModel:()=>KC,GraniteMoeHybridPreTrainedModel:()=>cQ,GranitePreTrainedModel:()=>gQ,GraniteSpeechForConditionalGeneration:()=>HC,GroundingDinoForObjectDetection:()=>YC,GroundingDinoPreTrainedModel:()=>dW,GroupViTModel:()=>$C,GroupViTPreTrainedModel:()=>pW,HeliumForCausalLM:()=>WC,HeliumModel:()=>VC,HeliumPreTrainedModel:()=>uQ,HieraForImageClassification:()=>qC,HieraModel:()=>GC,HieraPreTrainedModel:()=>mQ,HubertForCTC:()=>BC,HubertForSequenceClassification:()=>DC,HubertModel:()=>OC,HubertPreTrainedModel:()=>zC,HunYuanDenseV1ForCausalLM:()=>SC,HunYuanDenseV1Model:()=>MC,HunYuanDenseV1PreTrainedModel:()=>dQ,IJepaForImageClassification:()=>CC,IJepaModel:()=>LC,IJepaPreTrainedModel:()=>pQ,Idefics3ForConditionalGeneration:()=>iW,JAISLMHeadModel:()=>AC,JAISModel:()=>RC,JAISPreTrainedModel:()=>iQ,JinaCLIPModel:()=>PC,JinaCLIPPreTrainedModel:()=>D7,JinaCLIPTextModel:()=>rW,JinaCLIPVisionModel:()=>EC,Lfm2ForCausalLM:()=>TC,Lfm2Model:()=>wC,Lfm2MoeForCausalLM:()=>yC,Lfm2MoeModel:()=>vC,Lfm2MoePreTrainedModel:()=>aQ,Lfm2PreTrainedModel:()=>rQ,Lfm2VlForConditionalGeneration:()=>xC,LightOnOcrForConditionalGeneration:()=>IC,LiteWhisperForConditionalGeneration:()=>vE,Llama4ForCausalLM:()=>bC,Llama4PreTrainedModel:()=>aW,LlamaForCausalLM:()=>hC,LlamaModel:()=>kC,LlamaPreTrainedModel:()=>oQ,LlavaForConditionalGeneration:()=>W5,LlavaOnevisionForConditionalGeneration:()=>W5,LlavaPreTrainedModel:()=>bW,LlavaQwen2ForCausalLM:()=>vL,LongT5ForConditionalGeneration:()=>_C,LongT5Model:()=>fC,LongT5PreTrainedModel:()=>nQ,M2M100ForConditionalGeneration:()=>cC,M2M100Model:()=>gC,M2M100PreTrainedModel:()=>sQ,MBartForCausalLM:()=>aC,MBartForConditionalGeneration:()=>iC,MBartForSequenceClassification:()=>rC,MBartModel:()=>pC,MBartPreTrainedModel:()=>G9,MPNetForMaskedLM:()=>kR,MPNetForQuestionAnswering:()=>fR,MPNetForSequenceClassification:()=>hR,MPNetForTokenClassification:()=>bR,MPNetModel:()=>xR,MPNetPreTrainedModel:()=>R8,MT5ForConditionalGeneration:()=>lR,MT5Model:()=>cR,MT5PreTrainedModel:()=>VX,MarianMTModel:()=>uC,MarianModel:()=>lC,MarianPreTrainedModel:()=>tQ,MaskFormerForInstanceSegmentation:()=>dC,MaskFormerModel:()=>mC,MaskFormerPreTrainedModel:()=>eQ,Metric3DForDepthEstimation:()=>oC,Metric3DPreTrainedModel:()=>oW,Metric3Dv2ForDepthEstimation:()=>nC,Metric3Dv2PreTrainedModel:()=>nW,MgpstrForSceneTextRecognition:()=>sC,MgpstrModelOutput:()=>sW,MgpstrPreTrainedModel:()=>tW,MimiDecoderModel:()=>XG,MimiDecoderOutput:()=>JG,MimiEncoderModel:()=>QG,MimiEncoderOutput:()=>eW,MimiModel:()=>tC,MimiPreTrainedModel:()=>M7,Mistral4ForCausalLM:()=>XR,Mistral4Model:()=>QR,Mistral4PreTrainedModel:()=>QX,MistralForCausalLM:()=>JR,MistralModel:()=>eC,MistralPreTrainedModel:()=>JX,MobileBertForMaskedLM:()=>ZR,MobileBertForQuestionAnswering:()=>YR,MobileBertForSequenceClassification:()=>HR,MobileBertModel:()=>KR,MobileBertPreTrainedModel:()=>q9,MobileLLMForCausalLM:()=>VR,MobileLLMModel:()=>$R,MobileLLMPreTrainedModel:()=>XX,MobileNetV1ForImageClassification:()=>GR,MobileNetV1ForSemanticSegmentation:()=>qR,MobileNetV1Model:()=>WR,MobileNetV1PreTrainedModel:()=>S7,MobileNetV2ForImageClassification:()=>UR,MobileNetV2ForSemanticSegmentation:()=>NR,MobileNetV2Model:()=>FR,MobileNetV2PreTrainedModel:()=>L7,MobileNetV3ForImageClassification:()=>zR,MobileNetV3ForSemanticSegmentation:()=>OR,MobileNetV3Model:()=>jR,MobileNetV3PreTrainedModel:()=>C7,MobileNetV4ForImageClassification:()=>DR,MobileNetV4ForSemanticSegmentation:()=>MR,MobileNetV4Model:()=>BR,MobileNetV4PreTrainedModel:()=>R7,MobileViTForImageClassification:()=>LR,MobileViTModel:()=>SR,MobileViTPreTrainedModel:()=>KX,MobileViTV2ForImageClassification:()=>RR,MobileViTV2Model:()=>CR,MobileViTV2PreTrainedModel:()=>ZX,ModernBertDecoderForCausalLM:()=>IR,ModernBertDecoderModel:()=>TR,ModernBertDecoderPreTrainedModel:()=>HX,ModernBertForMaskedLM:()=>PR,ModernBertForSequenceClassification:()=>ER,ModernBertForTokenClassification:()=>wR,ModernBertModel:()=>AR,ModernBertPreTrainedModel:()=>F9,Moondream1ForConditionalGeneration:()=>IL,MoonshineForConditionalGeneration:()=>yR,MoonshineModel:()=>vR,MoonshinePreTrainedModel:()=>YX,MptForCausalLM:()=>gR,MptModel:()=>_R,MptPreTrainedModel:()=>$X,MultiModalityCausalLM:()=>uR,MultiModalityPreTrainedModel:()=>KG,MusicgenForCausalLM:()=>dR,MusicgenForConditionalGeneration:()=>ZG,MusicgenModel:()=>mR,MusicgenPreTrainedModel:()=>WX,NanoChatForCausalLM:()=>iR,NanoChatModel:()=>pR,NanoChatPreTrainedModel:()=>GX,NemotronHForCausalLM:()=>aR,NemotronHModel:()=>rR,NemotronHPreTrainedModel:()=>qX,NeoBertForMaskedLM:()=>nR,NeoBertForQuestionAnswering:()=>eR,NeoBertForSequenceClassification:()=>sR,NeoBertForTokenClassification:()=>tR,NeoBertModel:()=>oR,NeoBertPreTrainedModel:()=>A8,NomicBertModel:()=>JA,NomicBertPreTrainedModel:()=>HG,OPTForCausalLM:()=>NA,OPTModel:()=>UA,OPTPreTrainedModel:()=>BX,Olmo2ForCausalLM:()=>ZA,Olmo2Model:()=>KA,Olmo2PreTrainedModel:()=>UX,Olmo3ForCausalLM:()=>YA,Olmo3Model:()=>HA,Olmo3PreTrainedModel:()=>NX,OlmoForCausalLM:()=>XA,OlmoHybridForCausalLM:()=>VA,OlmoHybridModel:()=>$A,OlmoHybridPreTrainedModel:()=>jX,OlmoModel:()=>QA,OlmoPreTrainedModel:()=>FX,OpenAIPrivacyFilterForTokenClassification:()=>GA,OpenAIPrivacyFilterModel:()=>WA,OpenAIPrivacyFilterPreTrainedModel:()=>zX,OpenELMForCausalLM:()=>FA,OpenELMModel:()=>qA,OpenELMPreTrainedModel:()=>OX,OwlViTForObjectDetection:()=>BA,OwlViTModel:()=>OA,OwlViTPreTrainedModel:()=>MX,Owlv2ForObjectDetection:()=>zA,Owlv2Model:()=>jA,Owlv2PreTrainedModel:()=>DX,PaliGemmaForConditionalGeneration:()=>DA,ParakeetForCTC:()=>MA,ParakeetPreTrainedModel:()=>YG,PatchTSMixerForPrediction:()=>LA,PatchTSMixerModel:()=>SA,PatchTSMixerPreTrainedModel:()=>SX,PatchTSTForPrediction:()=>RA,PatchTSTModel:()=>CA,PatchTSTPreTrainedModel:()=>LX,Phi3ForCausalLM:()=>wA,Phi3Model:()=>EA,Phi3PreTrainedModel:()=>RX,Phi3VForCausalLM:()=>VG,Phi3VPreTrainedModel:()=>$G,PhiForCausalLM:()=>PA,PhiModel:()=>AA,PhiPreTrainedModel:()=>CX,PreTrainedModel:()=>T,PvtForImageClassification:()=>IA,PvtModel:()=>TA,PvtPreTrainedModel:()=>AX,PyAnnoteForAudioFrameClassification:()=>yA,PyAnnoteModel:()=>vA,PyAnnotePreTrainedModel:()=>PX,Qwen2ForCausalLM:()=>kA,Qwen2Model:()=>xA,Qwen2MoeForCausalLM:()=>bA,Qwen2MoeModel:()=>hA,Qwen2MoePreTrainedModel:()=>wX,Qwen2PreTrainedModel:()=>EX,Qwen2VLForCausalLM:()=>lW,Qwen2VLForConditionalGeneration:()=>IQ,Qwen2VLPreTrainedModel:()=>cW,Qwen2_5_VLForCausalLM:()=>uW,Qwen2_5_VLForConditionalGeneration:()=>vQ,Qwen3ForCausalLM:()=>_A,Qwen3Model:()=>fA,Qwen3MoeForCausalLM:()=>cA,Qwen3MoeModel:()=>gA,Qwen3MoePreTrainedModel:()=>IX,Qwen3NextForCausalLM:()=>uA,Qwen3NextModel:()=>lA,Qwen3NextPreTrainedModel:()=>vX,Qwen3PreTrainedModel:()=>TX,Qwen3VLForCausalLM:()=>WG,Qwen3VLForConditionalGeneration:()=>yX,Qwen3VLMoeForCausalLM:()=>dA,Qwen3VLMoeForConditionalGeneration:()=>mA,Qwen3_5ForCausalLM:()=>GG,Qwen3_5ForConditionalGeneration:()=>xX,Qwen3_5MoeForCausalLM:()=>iA,Qwen3_5MoeForConditionalGeneration:()=>pA,RFDetrForObjectDetection:()=>nA,RFDetrModel:()=>oA,RFDetrObjectDetectionOutput:()=>qG,RFDetrPreTrainedModel:()=>hX,RTDetrForObjectDetection:()=>zS,RTDetrModel:()=>jS,RTDetrObjectDetectionOutput:()=>$9,RTDetrPreTrainedModel:()=>qQ,RTDetrV2ForObjectDetection:()=>VP,RTDetrV2Model:()=>$P,RTDetrV2ObjectDetectionOutput:()=>FG,RTDetrV2PreTrainedModel:()=>bX,ResNetForImageClassification:()=>aA,ResNetModel:()=>rA,ResNetPreTrainedModel:()=>kX,RoFormerForMaskedLM:()=>KP,RoFormerForQuestionAnswering:()=>YP,RoFormerForSequenceClassification:()=>ZP,RoFormerForTokenClassification:()=>HP,RoFormerModel:()=>XP,RoFormerPreTrainedModel:()=>E8,RobertaForMaskedLM:()=>tA,RobertaForQuestionAnswering:()=>QP,RobertaForSequenceClassification:()=>eA,RobertaForTokenClassification:()=>JP,RobertaModel:()=>sA,RobertaPreTrainedModel:()=>P8,Sam2ImageSegmentationOutput:()=>jG,Sam2Model:()=>fX,Sam2PreTrainedModel:()=>zG,Sam3TrackerModel:()=>qP,SamImageSegmentationOutput:()=>UG,SamModel:()=>WP,SamPreTrainedModel:()=>NG,SapiensForDepthEstimation:()=>UP,SapiensForNormalEstimation:()=>NP,SapiensForSemanticSegmentation:()=>FP,SapiensPreTrainedModel:()=>A7,SegformerForImageClassification:()=>zP,SegformerForSemanticSegmentation:()=>OP,SegformerModel:()=>jP,SegformerPreTrainedModel:()=>P7,SiglipModel:()=>BP,SiglipPreTrainedModel:()=>_X,SiglipTextModel:()=>OG,SiglipVisionModel:()=>DP,SmolLM3ForCausalLM:()=>SP,SmolLM3Model:()=>MP,SmolLM3PreTrainedModel:()=>gX,SmolVLMForConditionalGeneration:()=>LP,SnacDecoderModel:()=>DG,SnacEncoderModel:()=>BG,SnacModel:()=>CP,SnacPreTrainedModel:()=>E7,SolarOpenForCausalLM:()=>AP,SolarOpenModel:()=>RP,SolarOpenPreTrainedModel:()=>cX,SpeechT5ForSpeechToText:()=>EP,SpeechT5ForTextToSpeech:()=>wP,SpeechT5HifiGan:()=>TP,SpeechT5Model:()=>PP,SpeechT5PreTrainedModel:()=>w7,SqueezeBertForMaskedLM:()=>vP,SqueezeBertForQuestionAnswering:()=>xP,SqueezeBertForSequenceClassification:()=>yP,SqueezeBertModel:()=>IP,SqueezeBertPreTrainedModel:()=>U9,StableLmForCausalLM:()=>hP,StableLmModel:()=>kP,StableLmPreTrainedModel:()=>lX,Starcoder2ForCausalLM:()=>fP,Starcoder2Model:()=>bP,Starcoder2PreTrainedModel:()=>uX,StyleTextToSpeech2Model:()=>_P,StyleTextToSpeech2PreTrainedModel:()=>MG,SupertonicForConditionalGeneration:()=>LG,SupertonicPreTrainedModel:()=>SG,Swin2SRForImageSuperResolution:()=>mP,Swin2SRModel:()=>uP,Swin2SRPreTrainedModel:()=>mX,SwinForImageClassification:()=>cP,SwinForSemanticSegmentation:()=>lP,SwinModel:()=>gP,SwinPreTrainedModel:()=>T7,T5ForConditionalGeneration:()=>pP,T5Model:()=>dP,T5PreTrainedModel:()=>dX,TableTransformerForObjectDetection:()=>rP,TableTransformerModel:()=>iP,TableTransformerObjectDetectionOutput:()=>CG,TableTransformerPreTrainedModel:()=>pX,TrOCRForCausalLM:()=>aP,TrOCRPreTrainedModel:()=>RG,UltravoxModel:()=>lQ,UltravoxPreTrainedModel:()=>mW,UniSpeechForCTC:()=>nP,UniSpeechForSequenceClassification:()=>sP,UniSpeechModel:()=>oP,UniSpeechPreTrainedModel:()=>I7,UniSpeechSatForAudioFrameClassification:()=>QE,UniSpeechSatForCTC:()=>eP,UniSpeechSatForSequenceClassification:()=>JE,UniSpeechSatModel:()=>tP,UniSpeechSatPreTrainedModel:()=>N9,VaultGemmaForCausalLM:()=>KE,VaultGemmaModel:()=>XE,VaultGemmaPreTrainedModel:()=>iX,ViTForImageClassification:()=>YE,ViTMAEModel:()=>$E,ViTMAEPreTrainedModel:()=>AG,ViTMSNForImageClassification:()=>WE,ViTMSNModel:()=>VE,ViTMSNPreTrainedModel:()=>aX,ViTModel:()=>HE,ViTPreTrainedModel:()=>rX,VisionEncoderDecoderModel:()=>ZE,VitMatteForImageMatting:()=>GE,VitMattePreTrainedModel:()=>PG,VitPoseForPoseEstimation:()=>qE,VitPosePreTrainedModel:()=>EG,VitsModel:()=>FE,VitsModelOutput:()=>wG,VitsPreTrainedModel:()=>TG,VoxtralForConditionalGeneration:()=>UE,VoxtralRealtimeForConditionalGeneration:()=>vG,VoxtralRealtimePreTrainedModel:()=>IG,Wav2Vec2BertForCTC:()=>SE,Wav2Vec2BertForSequenceClassification:()=>LE,Wav2Vec2BertModel:()=>ME,Wav2Vec2BertPreTrainedModel:()=>v7,Wav2Vec2ForAudioFrameClassification:()=>jC,Wav2Vec2ForCTC:()=>UC,Wav2Vec2ForSequenceClassification:()=>NC,Wav2Vec2Model:()=>FC,Wav2Vec2PreTrainedModel:()=>A5,WavLMForAudioFrameClassification:()=>EE,WavLMForCTC:()=>RE,WavLMForSequenceClassification:()=>AE,WavLMForXVector:()=>PE,WavLMModel:()=>CE,WavLMPreTrainedModel:()=>w8,WeSpeakerResNetModel:()=>wE,WeSpeakerResNetPreTrainedModel:()=>xG,WhisperForConditionalGeneration:()=>kG,WhisperModel:()=>IE,WhisperPreTrainedModel:()=>oX,XLMForQuestionAnswering:()=>bE,XLMForSequenceClassification:()=>kE,XLMForTokenClassification:()=>hE,XLMModel:()=>yE,XLMPreTrainedModel:()=>T8,XLMRobertaForMaskedLM:()=>_E,XLMRobertaForQuestionAnswering:()=>lE,XLMRobertaForSequenceClassification:()=>gE,XLMRobertaForTokenClassification:()=>cE,XLMRobertaModel:()=>fE,XLMRobertaPreTrainedModel:()=>I8,XLMWithLMHeadModel:()=>xE,XVectorOutput:()=>yG,YolosForObjectDetection:()=>mE,YolosModel:()=>uE,YolosObjectDetectionOutput:()=>hG,YolosPreTrainedModel:()=>nX,YoutuForCausalLM:()=>pE,YoutuModel:()=>dE,YoutuPreTrainedModel:()=>sX});var Y9=class extends T{},WM=class extends Y9{},GM=class extends Y9{async _call(J){return new Z0(await super._call(J))}},qM=class extends Y9{async _call(J){return new G6(await super._call(J))}},FM=class extends Y9{async _call(J){return new a0(await super._call(J))}},nJ=class extends T{},UM=class extends nJ{},NM=class extends nJ{},sJ=class extends T{},jM=class extends sJ{},zM=class extends sJ{},tJ=class extends T{},OM=class extends tJ{},BM=class extends tJ{},eJ=class extends T{},DM=class extends eJ{},MM=class extends eJ{},N7=class extends T{},SM=class extends N7{},LM=class extends N7{},CM=class extends N7{async _call(J){return new Z0(await super._call(J))}},JQ=class extends T{},RM=class extends JQ{},AM=class extends JQ{async _call(J){return new Z0(await super._call(J))}},O8=class extends T{},PM=class extends O8{},EM=class extends O8{async _call(J){return new a0(await super._call(J))}},wM=class extends O8{async _call(J){return new Z0(await super._call(J))}},TM=class extends O8{async _call(J){return new m0(await super._call(J))}},IM=class extends O8{async _call(J){return new G6(await super._call(J))}},QQ=class extends T{},vM=class extends QQ{},yM=class extends QQ{},XQ=class extends T{},xM=class extends XQ{},kM=class extends XQ{},KQ=class extends T{},hM=class extends KQ{},bM=class extends KQ{},B8=class extends T{},fM=class extends B8{},_M=class extends B8{async _call(J){return new a0(await super._call(J))}},gM=class extends B8{async _call(J){return new Z0(await super._call(J))}},cM=class extends B8{async _call(J){return new m0(await super._call(J))}},lM=class extends B8{async _call(J){return new G6(await super._call(J))}},uM=4299n,I$=6561n,OW=class extends T{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"]},BW=class extends OW{async encode_speech(J){return O0(this.sessions.speech_encoder,{audio_values:J})}async forward({input_ids:J=null,attention_mask:Q=null,audio_values:X=null,exaggeration:K=null,position_ids:Z=null,inputs_embeds:H=null,past_key_values:Y=null,generation_config:$=null,logits_processor:V=null,audio_features:W=null,audio_tokens:q=null,speaker_embeddings:F=null,speaker_features:N=null,...j}){let B;if(!H){let L=this.sessions.embed_tokens.inputNames,M={input_ids:J};if(L.includes("exaggeration")){if(!(K instanceof u)){let R=J.dims[0];if(K==null)K=$6([R],0.5);else if(typeof K==="number")K=$6([R],K);else if(Array.isArray(K))K=new u("float32",K,[R]);else throw Error("Unsupported type for `exaggeration` input")}M.exaggeration=K}if(L.includes("position_ids"))M.position_ids=Z;if({inputs_embeds:H}=await O0(this.sessions.embed_tokens,M),W&&q&&F&&N)B={audio_features:W,audio_tokens:q,speaker_embeddings:F,speaker_features:N};if(B||X)B??=await this.encode_speech(X),H=h0([B.audio_features,H],1),Q=j6([H.dims[0],H.dims[1]]);else{let R=H.dims[1];if(!Y||R!==1)throw Error("Incorrect state encountered during generation.");let E=Y.get_seq_length();Q=j6([H.dims[0],E+R])}}return{...await V5(this,{inputs_embeds:H,past_key_values:Y,attention_mask:Q,generation_config:$,logits_processor:V},!1),...B}}prepare_inputs_for_generation(J,Q,X){if(!Q.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(Q.input_ids.dims[1]===1){let K=Array.from({length:J.length},(Z,H)=>J[H].length-J[H].findLastIndex((Y)=>Y==I$)-1);Q.position_ids=new u("int64",K,[J.length,1])}else{let Z=Q.input_ids.tolist().map((H)=>{let Y=0;return H.map(($)=>$>=I$?0:Y++)});Q.position_ids=new u("int64",Z.flat(),Q.input_ids.dims)}if(Q.input_ids.dims[1]===1)delete Q.audio_values,delete Q.audio_features,delete Q.audio_tokens,delete Q.speaker_embeddings,delete Q.speaker_features;return t8(this,J,Q,X)}async generate(J){let{sequences:Q,audio_tokens:X,speaker_embeddings:K,speaker_features:Z}=await super.generate({...J,return_dict_in_generate:!0}),H=Q.slice(null,[J.input_ids.dims[1],-1]),Y=$6([H.dims[0],3],uM),$=h0([X,H,Y],1),{waveform:V}=await O0(this.sessions.conditional_decoder,{speech_tokens:$,speaker_features:Z,speaker_embeddings:K});return V}},DW=class extends T{},mM=class extends DW{},MW=class extends T{},dM=class extends MW{},j7=class extends T{},pM=class extends j7{},SW=class extends j7{static async from_pretrained(J,Q={}){return super.from_pretrained(J,{...Q,model_file_name:Q.model_file_name??"text_model"})}},LW=class extends j7{static async from_pretrained(J,Q={}){return super.from_pretrained(J,{...Q,model_file_name:Q.model_file_name??"audio_model"})}},d5=class extends T{},iM=class extends d5{},rM=class extends d5{static async from_pretrained(J,Q={}){return super.from_pretrained(J,{...Q,model_file_name:Q.model_file_name??"text_model"})}},CW=class extends d5{static async from_pretrained(J,Q={}){return super.from_pretrained(J,{...Q,model_file_name:Q.model_file_name??"text_model"})}},aM=class extends d5{static async from_pretrained(J,Q={}){return super.from_pretrained(J,{...Q,model_file_name:Q.model_file_name??"vision_model"})}},oM=class extends d5{static async from_pretrained(J,Q={}){return super.from_pretrained(J,{...Q,model_file_name:Q.model_file_name??"vision_model"})}},ZQ=class extends T{},nM=class extends ZQ{},sM=class extends ZQ{},HQ=class extends T{},tM=class extends HQ{},eM=class extends HQ{},YQ=class extends T{},JS=class extends YQ{},QS=class extends YQ{},$Q=class extends T{},XS=class extends $Q{},KS=class extends $Q{},VQ=class extends T{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","decoder_input_ids","decoder_attention_mask","past_key_values"]},ZS=class extends VQ{},HS=class extends VQ{},D8=class extends T{},YS=class extends D8{},$S=class extends D8{async _call(J){return new a0(await super._call(J))}},VS=class extends D8{async _call(J){return new Z0(await super._call(J))}},WS=class extends D8{async _call(J){return new m0(await super._call(J))}},GS=class extends D8{async _call(J){return new G6(await super._call(J))}},WQ=class extends T{},qS=class extends WQ{},FS=class extends WQ{async _call(J){return new Z0(await super._call(J))}},GQ=class extends T{},US=class extends GQ{},NS=class extends GQ{async _call(J){return new Z0(await super._call(J))}},qQ=class extends T{},jS=class extends qQ{},zS=class extends qQ{async _call(J){return new $9(await super._call(J))}},$9=class extends r0{constructor({logits:J,pred_boxes:Q}){super();this.logits=J,this.pred_boxes=Q}},FQ=class extends T{},OS=class extends FQ{},BS=class extends FQ{async _call(J){return new $9(await super._call(J))}},RW=class extends r0{constructor({audio_codes:J}){super();this.audio_codes=J}},AW=class extends r0{constructor({audio_values:J}){super();this.audio_values=J}},z7=class extends T{main_input_name="input_values";forward_params=["input_values"]},DS=class extends z7{async encode(J){return new RW(await O0(this.sessions.encoder_model,J))}async decode(J){return new AW(await O0(this.sessions.decoder_model,J))}},PW=class extends z7{static async from_pretrained(J,Q={}){return super.from_pretrained(J,{...Q,model_file_name:Q.model_file_name??"encoder_model"})}},EW=class extends z7{static async from_pretrained(J,Q={}){return super.from_pretrained(J,{...Q,model_file_name:Q.model_file_name??"decoder_model"})}},M8=class extends T{},MS=class extends M8{},SS=class extends M8{async _call(J){return new a0(await super._call(J))}},LS=class extends M8{async _call(J){return new Z0(await super._call(J))}},CS=class extends M8{async _call(J){return new m0(await super._call(J))}},RS=class extends M8{async _call(J){return new G6(await super._call(J))}},UQ=class extends T{},AS=class extends UQ{},PS=class extends UQ{},S8=class extends T{},ES=class extends S8{},wS=class extends S8{async _call(J){return new a0(await super._call(J))}},TS=class extends S8{async _call(J){return new Z0(await super._call(J))}},IS=class extends S8{async _call(J){return new m0(await super._call(J))}},vS=class extends S8{async _call(J){return new G6(await super._call(J))}},wW=class extends T{},yS=class extends wW{},NQ=class extends T{},xS=class extends NQ{},kS=class extends NQ{async _call(J){return new Z0(await super._call(J))}},TW=class extends T{},hS=class extends TW{},IW=class extends T{},bS=class extends IW{},O7=class extends T{},fS=class extends O7{},_S=class extends O7{async _call(J){return new jQ(await super._call(J))}},gS=class extends O7{async _call(J){return new vW(await super._call(J))}},jQ=class extends r0{constructor({logits:J,pred_boxes:Q}){super();this.logits=J,this.pred_boxes=Q}},vW=class extends r0{constructor({logits:J,pred_boxes:Q,pred_masks:X}){super();this.logits=J,this.pred_boxes=Q,this.pred_masks=X}},zQ=class extends T{},cS=class extends zQ{},lS=class extends zQ{async _call(J){return new Z0(await super._call(J))}},OQ=class extends T{},uS=class extends OQ{},mS=class extends OQ{async _call(J){return new Z0(await super._call(J))}},yW=class extends T{},dS=class extends yW{},xW=class extends T{},pS=class extends xW{},L8=class extends T{},iS=class extends L8{},rS=class extends L8{async _call(J){return new Z0(await super._call(J))}},aS=class extends L8{async _call(J){return new m0(await super._call(J))}},oS=class extends L8{async _call(J){return new G6(await super._call(J))}},nS=class extends L8{async _call(J){return new a0(await super._call(J))}},kW=class extends T{},sS=class extends kW{},BQ=class extends T{},tS=class extends BQ{},eS=class extends BQ{},DQ=class extends T{},JL=class extends DQ{},QL=class extends DQ{async _call(J){return new Z0(await super._call(J))}},C8=class extends T{},XL=class extends C8{},KL=class extends C8{async _call(J){return new a0(await super._call(J))}},ZL=class extends C8{async _call(J){return new Z0(await super._call(J))}},HL=class extends C8{async _call(J){return new m0(await super._call(J))}},YL=class extends C8{async _call(J){return new G6(await super._call(J))}},MQ=class extends T{},$L=class extends MQ{},VL=class extends MQ{},V9=class extends T{},WL=class extends V9{},GL=class extends V9{async _call(J){return new a0(await super._call(J))}},qL=class extends V9{async _call(J){return new Z0(await super._call(J))}},FL=class extends V9{async _call(J){return new m0(await super._call(J))}},W9=class extends T{},UL=class extends W9{},NL=class extends W9{async _call(J){return new a0(await super._call(J))}},jL=class extends W9{async _call(J){return new Z0(await super._call(J))}},zL=class extends W9{async _call(J){return new m0(await super._call(J))}},SQ=class extends T{},OL=class extends SQ{},BL=class extends SQ{},LQ=class extends T{},DL=class extends LQ{},ML=class extends LQ{},CQ=class extends T{},SL=class extends CQ{},LL=class extends CQ{},RQ=class extends T{},CL=class extends RQ{},RL=class extends RQ{async _call(J){return new Z0(await super._call(J))}},hW=class extends T{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"},AL=class extends hW{_merge_input_ids_with_image_features({inputs_embeds:J,image_features:Q,input_ids:X,attention_mask:K}){return{inputs_embeds:h0([Q,J],1),attention_mask:h0([j6(Q.dims.slice(0,2)),K],1)}}async _prepare_inputs_embeds({input_ids:J,pixel_values:Q,inputs_embeds:X,attention_mask:K}){if(!J&&!Q)throw Error("Either `input_ids` or `pixel_values` should be provided.");let Z,H;if(J)Z=await this.encode_text({input_ids:J});if(Q)H=await this.encode_image({pixel_values:Q});if(Z&&H)({inputs_embeds:X,attention_mask:K}=this._merge_input_ids_with_image_features({inputs_embeds:Z,image_features:H,input_ids:J,attention_mask:K}));else X=Z||H;return{inputs_embeds:X,attention_mask:K}}async forward({input_ids:J,pixel_values:Q,attention_mask:X,decoder_input_ids:K,decoder_attention_mask:Z,encoder_outputs:H,past_key_values:Y,inputs_embeds:$,decoder_inputs_embeds:V}){if(!$)({inputs_embeds:$,attention_mask:X}=await this._prepare_inputs_embeds({input_ids:J,pixel_values:Q,inputs_embeds:$,attention_mask:X}));if(!H){let{last_hidden_state:q}=await R5(this,{inputs_embeds:$,attention_mask:X});H=q}if(!V){if(!K)throw Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");V=await this.encode_text({input_ids:K})}return await V5(this,{inputs_embeds:V,attention_mask:Z,encoder_attention_mask:X,encoder_hidden_states:H,past_key_values:Y},!0)}},AQ=class extends T{},PL=class extends AQ{},EL=class extends AQ{},PQ=class extends T{},wL=class extends PQ{},TL=class extends PQ{},bW=class extends T{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},W5=class extends bW{_merge_input_ids_with_image_features(J){let Q=J.image_features.dims.at(-1),X=J.image_features.view(-1,Q);return aJ({image_token_id:this.config.image_token_index??this.config.image_token_id,...J,image_features:X})}},IL=class extends W5{},vL=class extends W5{},fW=class extends T{},yL=class extends fW{},_W=class extends W5{},xL=class extends _W{},gW=class extends T{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"]},B7=class extends gW{async forward({input_ids:J=null,attention_mask:Q=null,pixel_values:X=null,input_features:K=null,input_features_mask:Z=null,position_ids:H=null,inputs_embeds:Y=null,per_layer_inputs:$=null,past_key_values:V=null,generation_config:W=null,logits_processor:q=null,...F}){if(!Y||!$){if({inputs_embeds:Y,per_layer_inputs:$}=await O0(this.sessions.embed_tokens,{input_ids:J}),J.dims[1]!==1){if(X){let{image_features:j}=await this._encode_vision({pixel_values:X,...F});({inputs_embeds:Y,attention_mask:Q}=this._merge_input_ids_with_image_features({image_features:j,inputs_embeds:Y,input_ids:J,attention_mask:Q}))}if(K){let{audio_features:j}=await O0(this.sessions.audio_encoder,{input_features:K,input_features_mask:Z});({inputs_embeds:Y,attention_mask:Q}=this._merge_input_ids_with_audio_features({audio_features:j,inputs_embeds:Y,input_ids:J,attention_mask:Q}))}}}return await V5(this,{inputs_embeds:Y,per_layer_inputs:$,past_key_values:V,attention_mask:Q,position_ids:H,generation_config:W,logits_processor:q},!0)}_encode_vision(J){return O0(this.sessions.vision_encoder,{pixel_values:J.pixel_values})}_merge_input_ids_with_image_features(J){let Q=J.image_features.dims.at(-1),X=J.image_features.view(-1,Q);return aJ({image_token_id:this.config.image_token_id,...J,image_features:X})}_merge_input_ids_with_audio_features(J){let Q=J.audio_features.dims.at(-1),X=J.audio_features.view(-1,Q);return zW({audio_token_id:this.config.audio_token_id,...J,audio_features:X})}},kL=class extends B7{},EQ=class extends B7{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","image_position_ids","input_features","input_features_mask","past_key_values"];_encode_vision(J){return O0(this.sessions.vision_encoder,{pixel_values:J.pixel_values,pixel_position_ids:J.image_position_ids})}},hL=class extends EQ{},wQ=class extends T{},bL=class extends wQ{},fL=class extends wQ{},TQ=class extends T{},_L=class extends TQ{},gL=class extends TQ{},cW=class extends T{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},IQ=class extends cW{image_grid_thw_name="grid_thw";_get_text_only_rope_index(J,Q){if(Q){let{data:X,dims:K}=NW(Q),Z=BigInt64Array.from({length:3*X.length},(Y,$)=>X[$%X.length]),H=Array.from({length:K[0]},(Y,$)=>c0(X.subarray(K[1]*$,K[1]*($+1)))[0]+1n+BigInt(K[1]));return[new u("int64",Z,[3,...K]),new u("int64",H,[H.length,1])]}else{let[X,K]=J.dims,Z=BigInt64Array.from({length:3*X*K},(H,Y)=>BigInt(Math.floor(Y%K/X)));return[new u("int64",Z,[3,...J.dims]),NV([X,1])]}}_reorder_and_write_positions(J,Q,X,K){let Z=J.reduce((V,W)=>V+W.length,0),H=Array(Z),Y=0;for(let V=0;V<3;++V)for(let W of J){let q=W.length/3;for(let F=V*q;F<(V+1)*q;++F)H[Y++]=W[F]}let $=0;for(let V=0;V{if(R==$)M.push(E);return M},[]).map((M)=>V[M+1]),F=q.filter((M)=>M==H).length,N=q.filter((M)=>M==Y).length,j=[],B=0,D=F,L=N;for(let M=0;Ma>B&&_==H),E=V.findIndex((_,a)=>a>B&&_==Y),P=D>0&&R!==-1?R:V.length+1,w=L>0&&E!==-1?E:V.length+1,k,C,c,g;if(P0?c0(j.at(-1))[0]+1:0;j.push(Array.from({length:3*p},(_,a)=>f+a%p));let v=p+f,o=d*r*i,Q0=Array.from({length:o},(_,a)=>v+Math.floor(a/(r*i))),x=Array.from({length:o},(_,a)=>v+Math.floor(a/i)%r),h=Array.from({length:o},(_,a)=>v+a%i);j.push([Q0,x,h].flat()),B=k+o}if(B0?c0(j.at(-1))[0]+1:0,R=V.length-B;j.push(Array.from({length:3*R},(E,P)=>M+P%R))}return j}get_rope_index(J,Q,X,K){let{vision_config:Z}=this.config,H=Z.spatial_merge_size??2;if(Q||X){let Y=J.tolist();if(!K)K=UV(J);let $=K.tolist(),V=Array.from({length:3},()=>Array.from({length:J.dims[0]},()=>Array.from({length:J.dims[1]},()=>0))),W=Q?Q.tolist():[],q=X?X.tolist():[],F={image_index:0,video_index:0},N=[];for(let j=0;j$[j][R]==1),D=this._get_multimodal_rope_positions({filtered_ids:B,image_grid_thw_list:W,video_grid_thw_list:q,spatial_merge_size:H,state:F}),L=this._reorder_and_write_positions(D,$[j],V,j);N.push(c0(L)[0]+1-Y[j].length)}return[new u("int64",V.flat(1/0),[3,J.dims[0],J.dims[1]]),new u("int64",N,[N.length,1])]}else return this._get_text_only_rope_index(J,K)}async encode_image({pixel_values:J,image_grid_thw:Q}){return(await O0(this.sessions.vision_encoder,{pixel_values:J,[this.image_grid_thw_name]:Q})).image_features}_merge_input_ids_with_image_features(J){return aJ({image_token_id:this.config.image_token_id,...J})}prepare_inputs_for_generation(J,Q,X){if(!Q.attention_mask||Q.position_ids)return Q;if(!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes("position_ids"))return Q;if(!Q.past_key_values)[Q.position_ids,Q.rope_deltas]=this.get_rope_index(Q.input_ids,Q.image_grid_thw,Q.video_grid_thw,Q.attention_mask);else{Q.pixel_values=null;let Z=Q.past_key_values.get_seq_length();if(ZH+$);Q.position_ids=$5([Y,Y,Y],0)}}return Q}},lW=class extends IQ{},vQ=class extends IQ{image_grid_thw_name="image_grid_thw"},uW=class extends lW{image_grid_thw_name="image_grid_thw"},cL=class extends vQ{get_vision_position_ids(J,Q,X,K){let Z=Math.floor(Q[0]/X),H=Math.floor(Q[1]/K),Y=Math.floor(Q[2]/K),$=H*Y*Z,V=Array.from({length:$},()=>J),W=Array.from({length:$},(F,N)=>J+Math.floor(N/(Y*Z))),q=Array.from({length:$},(F,N)=>J+N%Y);return[...V,...W,...q]}_get_multimodal_rope_positions({filtered_ids:J,image_grid_thw_list:Q,video_grid_thw_list:X,spatial_merge_size:K,state:Z}){let{image_token_id:H}=this.config,Y=[],$=0,V=J[0]==H?1:0;for(let F=1;F<=J.length;++F){let N=FW+L%B)),W+=B}else{let B=Q[Z.image_index++].map(Number),D=B[0];q.push(this.get_vision_position_ids(W,B,D,K)),W+=Math.max(B[1],B[2])/K}return q}},yQ=class extends T{},lL=class extends yQ{},uL=class extends yQ{},xQ=class extends T{},mL=class extends xQ{},dL=class extends xQ{},kQ=class extends T{},pL=class extends kQ{},iL=class extends kQ{},hQ=class extends T{},rL=class extends hQ{},aL=class extends hQ{},bQ=class extends T{},oL=class extends bQ{},nL=class extends bQ{},fQ=class extends T{},sL=class extends fQ{},tL=class extends fQ{},_Q=class extends T{},eL=class extends _Q{},JC=class extends _Q{},gQ=class extends T{},QC=class extends gQ{},XC=class extends gQ{},cQ=class extends T{},KC=class extends cQ{},ZC=class extends cQ{},mW=class extends T{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},lQ=class extends mW{_merge_input_ids_with_audio_features(J){let Q=J.audio_features.dims.at(-1),X=J.audio_features.view(-1,Q);return zW({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...J,audio_features:X})}},HC=class extends lQ{forward_params=["input_ids","attention_mask","input_features","past_key_values"]},dW=class extends T{},YC=class extends dW{},pW=class extends T{},$C=class extends pW{},uQ=class extends T{},VC=class extends uQ{},WC=class extends uQ{},mQ=class extends T{},GC=class extends mQ{},qC=class extends mQ{async _call(J){return new Z0(await super._call(J))}},A5=class extends T{},FC=class extends A5{},UC=class extends A5{async _call(J){return new m5(await super._call(J))}},NC=class extends A5{async _call(J){return new Z0(await super._call(J))}},jC=class extends A5{async _call(J){return new m0(await super._call(J))}},zC=class extends T{},OC=class extends A5{},BC=class extends A5{async _call(J){return new m5(await super._call(J))}},DC=class extends A5{async _call(J){return new Z0(await super._call(J))}},dQ=class extends T{},MC=class extends dQ{},SC=class extends dQ{},iW=class extends W5{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]},pQ=class extends T{},LC=class extends pQ{},CC=class extends pQ{async _call(J){return new Z0(await super._call(J))}},iQ=class extends T{},RC=class extends iQ{},AC=class extends iQ{},D7=class extends T{},PC=class extends D7{async forward(J){let Q=!J.input_ids,X=!J.pixel_values;if(Q&&X)throw Error("Either `input_ids` or `pixel_values` should be provided.");if(Q)J.input_ids=j6([J.pixel_values.dims[0],1]);if(X){let{image_size:V}=this.config.vision_config;J.pixel_values=$6([0,3,V,V],0)}let{text_embeddings:K,image_embeddings:Z,l2norm_text_embeddings:H,l2norm_image_embeddings:Y}=await super.forward(J),$={};if(!Q)$.text_embeddings=K,$.l2norm_text_embeddings=H;if(!X)$.image_embeddings=Z,$.l2norm_image_embeddings=Y;return $}},rW=class extends D7{static async from_pretrained(J,Q={}){return super.from_pretrained(J,{...Q,model_file_name:Q.model_file_name??"text_model"})}},EC=class extends D7{static async from_pretrained(J,Q={}){return super.from_pretrained(J,{...Q,model_file_name:Q.model_file_name??"vision_model"})}},rQ=class extends T{},wC=class extends rQ{},TC=class extends rQ{},IC=class extends W5{},aQ=class extends T{},vC=class extends aQ{},yC=class extends aQ{},xC=class extends W5{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"]},oQ=class extends T{},kC=class extends oQ{},hC=class extends oQ{},aW=class extends T{},bC=class extends aW{},nQ=class extends T{},fC=class extends nQ{},_C=class extends nQ{},sQ=class extends T{},gC=class extends sQ{},cC=class extends sQ{},tQ=class extends T{},lC=class extends tQ{},uC=class extends tQ{},eQ=class extends T{},mC=class extends eQ{},dC=class extends eQ{},G9=class extends T{},pC=class extends G9{},iC=class extends G9{},rC=class extends G9{async _call(J){return new Z0(await super._call(J))}},aC=class extends G9{},oW=class extends T{},oC=class extends oW{},nW=class extends T{},nC=class extends nW{},sW=class extends r0{constructor({char_logits:J,bpe_logits:Q,wp_logits:X}){super();this.char_logits=J,this.bpe_logits=Q,this.wp_logits=X}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},tW=class extends T{},sC=class extends tW{async _call(J){return new sW(await super._call(J))}},eW=class extends r0{constructor({audio_codes:J}){super();this.audio_codes=J}},JG=class extends r0{constructor({audio_values:J}){super();this.audio_values=J}},M7=class extends T{main_input_name="input_values";forward_params=["input_values"]},tC=class extends M7{async encode(J){return new eW(await O0(this.sessions.encoder_model,J))}async decode(J){return new JG(await O0(this.sessions.decoder_model,J))}},QG=class extends M7{static async from_pretrained(J,Q={}){return super.from_pretrained(J,{...Q,model_file_name:Q.model_file_name??"encoder_model"})}},XG=class extends M7{static async from_pretrained(J,Q={}){return super.from_pretrained(J,{...Q,model_file_name:Q.model_file_name??"decoder_model"})}},JX=class extends T{},eC=class extends JX{},JR=class extends JX{},QX=class extends T{},QR=class extends QX{},XR=class extends QX{},q9=class extends T{},KR=class extends q9{},ZR=class extends q9{async _call(J){return new a0(await super._call(J))}},HR=class extends q9{async _call(J){return new Z0(await super._call(J))}},YR=class extends q9{async _call(J){return new G6(await super._call(J))}},XX=class extends T{},$R=class extends XX{},VR=class extends XX{},S7=class extends T{},WR=class extends S7{},GR=class extends S7{async _call(J){return new Z0(await super._call(J))}},qR=class extends S7{},L7=class extends T{},FR=class extends L7{},UR=class extends L7{async _call(J){return new Z0(await super._call(J))}},NR=class extends L7{},C7=class extends T{},jR=class extends C7{},zR=class extends C7{async _call(J){return new Z0(await super._call(J))}},OR=class extends C7{},R7=class extends T{},BR=class extends R7{},DR=class extends R7{async _call(J){return new Z0(await super._call(J))}},MR=class extends R7{},KX=class extends T{},SR=class extends KX{},LR=class extends KX{async _call(J){return new Z0(await super._call(J))}},ZX=class extends T{},CR=class extends ZX{},RR=class extends ZX{async _call(J){return new Z0(await super._call(J))}},F9=class extends T{},AR=class extends F9{},PR=class extends F9{async _call(J){return new a0(await super._call(J))}},ER=class extends F9{async _call(J){return new Z0(await super._call(J))}},wR=class extends F9{async _call(J){return new m0(await super._call(J))}},HX=class extends T{},TR=class extends HX{},IR=class extends HX{},YX=class extends T{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},vR=class extends YX{},yR=class extends YX{},R8=class extends T{},xR=class extends R8{},kR=class extends R8{async _call(J){return new a0(await super._call(J))}},hR=class extends R8{async _call(J){return new Z0(await super._call(J))}},bR=class extends R8{async _call(J){return new m0(await super._call(J))}},fR=class extends R8{async _call(J){return new G6(await super._call(J))}},$X=class extends T{},_R=class extends $X{},gR=class extends $X{},VX=class extends T{},cR=class extends VX{},lR=class extends VX{},KG=class extends T{},uR=class extends KG{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...J){super(...J);this._generation_mode="text"}async forward(J){let Q=this._generation_mode??"text",X;if(Q==="text"||!J.past_key_values){let $=this.sessions.prepare_inputs_embeds,V=e0(J,$.inputNames);X=await O0($,V)}else{let $=this.sessions.gen_img_embeds,V=e0({image_ids:J.input_ids},$.inputNames);X=await O0($,V)}let K={...J,...X},Z=await V5(this,K),H=this.sessions[Q==="text"?"lm_head":"gen_head"];if(!H)throw Error(`Unable to find "${H}" generation head`);let Y=await O0(H,e0(Z,H.inputNames));return{...X,...Z,...Y}}prepare_inputs_for_generation(J,Q,X){let K=!!Q.past_key_values;if(X.guidance_scale!==null&&X.guidance_scale>1)if(K)Q.input_ids=h0([Q.input_ids,Q.input_ids],0);else Q.input_ids=h0([Q.input_ids,zJ(Q.input_ids,BigInt(X.pad_token_id))],0),Q.attention_mask=h0([Q.attention_mask,zJ(Q.attention_mask,0n)],0);if(K||!Q.pixel_values)Q.pixel_values=$6([0,0,3,384,384],1);if(K)Q.images_seq_mask=new u("bool",[,].fill(!0).fill(!1,0,1),[1,1]),Q.images_emb_mask=new u("bool",[].fill(!1),[1,1,0]);return Q}async generate(J){return this._generation_mode="text",super.generate(J)}async generate_images(J){this._generation_mode="image";let Q=(J.inputs??J[this.main_input_name]).dims[1],K=(await super.generate(J)).slice(null,[Q,null]),Z=this.sessions.image_decode,{decoded_image:H}=await O0(Z,{generated_tokens:K}),Y=H.add_(1).mul_(127.5).clamp_(0,255).to("uint8"),$=[];for(let V of Y){let W=h6.fromTensor(V);$.push(W)}return $}},WX=class extends T{},mR=class extends WX{},dR=class extends WX{},ZG=class extends T{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(J){let[Q,X]=J.dims,K=this.config.decoder.num_codebooks,Z=X-K,H=0;for(let V=0;V0&&F<=Z)J.data[H++]=J.data[V]}let Y=Math.floor(Q/K),$=H/(Y*K);return new u(J.type,J.data.slice(0,H),[Y,K,$])}prepare_inputs_for_generation(J,Q,X){let K=BigInt(this.config.decoder.pad_token_id),Z=structuredClone(J);for(let H=0;H=Y)Z[H][Y]=K;if(X.guidance_scale!==null&&X.guidance_scale>1)Z=Z.concat(Z);return X7(this,Z,Q,X)}async generate(J){let Q=await super.generate(J),X=this._apply_and_filter_by_delay_pattern_mask(Q).unsqueeze_(0),{audio_values:K}=await O0(this.sessions.encodec_decode,{audio_codes:X});return K}},GX=class extends T{},pR=class extends GX{},iR=class extends GX{},qX=class extends T{},rR=class extends qX{},aR=class extends qX{},A8=class extends T{},oR=class extends A8{},nR=class extends A8{async _call(J){return new a0(await super._call(J))}},sR=class extends A8{async _call(J){return new Z0(await super._call(J))}},tR=class extends A8{async _call(J){return new m0(await super._call(J))}},eR=class extends A8{async _call(J){return new G6(await super._call(J))}},HG=class extends T{},JA=class extends HG{},FX=class extends T{},QA=class extends FX{},XA=class extends FX{},UX=class extends T{},KA=class extends UX{},ZA=class extends UX{},NX=class extends T{},HA=class extends NX{},YA=class extends NX{},jX=class extends T{},$A=class extends jX{},VA=class extends jX{},zX=class extends T{},WA=class extends zX{},GA=class extends zX{async _call(J){return new Z0(await super._call(J))}},OX=class extends T{},qA=class extends OX{},FA=class extends OX{},BX=class extends T{},UA=class extends BX{},NA=class extends BX{},DX=class extends T{},jA=class extends DX{},zA=class extends DX{},MX=class extends T{},OA=class extends MX{},BA=class extends MX{},DA=class extends W5{},YG=class extends T{},MA=class extends YG{async _call(J){return new m5(await super._call(J))}},SX=class extends T{},SA=class extends SX{},LA=class extends SX{},LX=class extends T{},CA=class extends LX{},RA=class extends LX{},CX=class extends T{},AA=class extends CX{},PA=class extends CX{},RX=class extends T{},EA=class extends RX{},wA=class extends RX{},$G=class extends T{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},VG=class extends $G{async forward({input_ids:J=null,attention_mask:Q=null,pixel_values:X=null,image_sizes:K=null,position_ids:Z=null,inputs_embeds:H=null,past_key_values:Y=null,generation_config:$=null,logits_processor:V=null,...W}){if(!H){let F;if(X&&J.dims[1]!==1){if(!K)throw Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:F}=await O0(this.sessions.vision_encoder,{pixel_values:X,image_sizes:K}))}else{let N=this.config.normalized_config.hidden_size;F=new u("float32",[],[0,N])}({inputs_embeds:H}=await O0(this.sessions.prepare_inputs_embeds,{input_ids:J,image_features:F}))}return await V5(this,{inputs_embeds:H,past_key_values:Y,attention_mask:Q,position_ids:Z,generation_config:$,logits_processor:V},!1)}},AX=class extends T{},TA=class extends AX{},IA=class extends AX{async _call(J){return new Z0(await super._call(J))}},PX=class extends T{},vA=class extends PX{},yA=class extends PX{async _call(J){return new m0(await super._call(J))}},EX=class extends T{},xA=class extends EX{},kA=class extends EX{},wX=class extends T{},hA=class extends wX{},bA=class extends wX{},TX=class extends T{},fA=class extends TX{},_A=class extends TX{},IX=class extends T{},gA=class extends IX{},cA=class extends IX{},vX=class extends T{},lA=class extends vX{},uA=class extends vX{},yX=class extends vQ{},WG=class extends uW{},mA=class extends yX{},dA=class extends WG{},xX=class extends yX{},GG=class extends xX{},pA=class extends xX{},iA=class extends GG{},kX=class extends T{},rA=class extends kX{},aA=class extends kX{async _call(J){return new Z0(await super._call(J))}},hX=class extends T{},oA=class extends hX{},nA=class extends hX{async _call(J){return new qG(await super._call(J))}},qG=class extends $9{},P8=class extends T{},sA=class extends P8{},tA=class extends P8{async _call(J){return new a0(await super._call(J))}},eA=class extends P8{async _call(J){return new Z0(await super._call(J))}},JP=class extends P8{async _call(J){return new m0(await super._call(J))}},QP=class extends P8{async _call(J){return new G6(await super._call(J))}},E8=class extends T{},XP=class extends E8{},KP=class extends E8{async _call(J){return new a0(await super._call(J))}},ZP=class extends E8{async _call(J){return new Z0(await super._call(J))}},HP=class extends E8{async _call(J){return new m0(await super._call(J))}},YP=class extends E8{async _call(J){return new G6(await super._call(J))}},bX=class extends T{},$P=class extends bX{},VP=class extends bX{async _call(J){return new FG(await super._call(J))}},FG=class extends $9{},UG=class extends r0{constructor({iou_scores:J,pred_masks:Q}){super();this.iou_scores=J,this.pred_masks=Q}},NG=class extends T{},WP=class extends NG{async get_image_embeddings({pixel_values:J}){return await R5(this,{pixel_values:J})}async forward(J){if(!J.image_embeddings||!J.image_positional_embeddings)J={...J,...await this.get_image_embeddings(J)};else J={...J};J.input_labels??=j6(J.input_points.dims.slice(0,-1));let Q={image_embeddings:J.image_embeddings,image_positional_embeddings:J.image_positional_embeddings};if(J.input_points)Q.input_points=J.input_points;if(J.input_labels)Q.input_labels=J.input_labels;if(J.input_boxes)Q.input_boxes=J.input_boxes;return await O0(this.sessions.prompt_encoder_mask_decoder,Q)}async _call(J){return new UG(await super._call(J))}},jG=class extends r0{constructor({iou_scores:J,pred_masks:Q,object_score_logits:X}){super();this.iou_scores=J,this.pred_masks=Q,this.object_score_logits=X}},zG=class extends T{},fX=class extends zG{async get_image_embeddings({pixel_values:J}){return await R5(this,{pixel_values:J})}async forward(J){let{num_feature_levels:Q}=this.config.vision_config;if(Array.from({length:Q},(H,Y)=>`image_embeddings.${Y}`).some((H)=>!J[H]))J={...J,...await this.get_image_embeddings(J)};else J={...J};if(J.input_points){if(J.input_boxes&&J.input_boxes.dims[1]!==1)throw Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");let H=J.input_points.dims;J.input_labels??=j6(H.slice(0,-1)),J.input_boxes??=$6([H[0],0,4],0)}else if(J.input_boxes){let H=J.input_boxes.dims;J.input_labels=$6([H[0],H[1],0],-1n),J.input_points=$6([H[0],1,0,2],0)}else throw Error("At least one of `input_points` or `input_boxes` must be provided.");let K=this.sessions.prompt_encoder_mask_decoder,Z=e0(J,K.inputNames);return await O0(K,Z)}async _call(J){return new jG(await super._call(J))}},GP=class extends fX{},qP=class extends fX{},A7=class extends T{},FP=class extends A7{},UP=class extends A7{},NP=class extends A7{},P7=class extends T{},jP=class extends P7{},zP=class extends P7{},OP=class extends P7{},_X=class extends T{},BP=class extends _X{},OG=class extends _X{static async from_pretrained(J,Q={}){return super.from_pretrained(J,{...Q,model_file_name:Q.model_file_name??"text_model"})}},DP=class extends d5{static async from_pretrained(J,Q={}){return super.from_pretrained(J,{...Q,model_file_name:Q.model_file_name??"vision_model"})}},gX=class extends T{},MP=class extends gX{},SP=class extends gX{},LP=class extends iW{},E7=class extends T{main_input_name="input_values";forward_params=["input_values"]},CP=class extends E7{async encode(J){return await O0(this.sessions.encoder_model,J)}async decode(J){return await O0(this.sessions.decoder_model,J)}},BG=class extends E7{static async from_pretrained(J,Q={}){return super.from_pretrained(J,{...Q,model_file_name:Q.model_file_name??"encoder_model"})}},DG=class extends E7{static async from_pretrained(J,Q={}){return super.from_pretrained(J,{...Q,model_file_name:Q.model_file_name??"decoder_model"})}},cX=class extends T{},RP=class extends cX{},AP=class extends cX{},w7=class extends T{},PP=class extends w7{},EP=class extends w7{},wP=class extends w7{async generate_speech(J,Q,{threshold:X=0.5,minlenratio:K=0,maxlenratio:Z=20,vocoder:H=null}={}){let Y={input_ids:J},{encoder_outputs:$,encoder_attention_mask:V}=await R5(this,Y),W=$.dims[1]/this.config.reduction_factor,q=Math.floor(W*Z),F=Math.floor(W*K),N=this.config.num_mel_bins,j=[],B=null,D=null,L=0;while(!0){++L;let E=qW(!!D),P;if(D)P=D.output_sequence_out;else P=new u("float32",new Float32Array(N),[1,1,N]);let w={use_cache_branch:E,output_sequence:P,encoder_attention_mask:V,speaker_embeddings:Q,encoder_hidden_states:$};rJ(this,w,B),D=await O0(this.sessions.decoder_model_merged,w),B=LJ(D,B);let{prob:k,spectrum:C}=D;if(j.push(C),L>=F&&(Array.from(k.data).filter((c)=>c>=X).length>0||L>=q))break}let M=h0(j),{waveform:R}=await O0(H.sessions.model,{spectrogram:M});return{spectrogram:M,waveform:R}}},TP=class extends T{main_input_name="spectrogram"},U9=class extends T{},IP=class extends U9{},vP=class extends U9{async _call(J){return new a0(await super._call(J))}},yP=class extends U9{async _call(J){return new Z0(await super._call(J))}},xP=class extends U9{async _call(J){return new G6(await super._call(J))}},lX=class extends T{},kP=class extends lX{},hP=class extends lX{},uX=class extends T{},bP=class extends uX{},fP=class extends uX{},MG=class extends T{},_P=class extends MG{},SG=class extends T{},LG=class extends SG{async generate_speech({input_ids:J,attention_mask:Q,style:X,num_inference_steps:K=5,speed:Z=1.05}){let{sampling_rate:H,chunk_compress_factor:Y,base_chunk_size:$,latent_dim:V}=this.config,{last_hidden_state:W,durations:q}=await O0(this.sessions.text_encoder,{input_ids:J,attention_mask:Q,style:X}),F=q.div(Z).mul_(H),N=$*Y,j=F.data,B=Int32Array.from(j,(g)=>Math.ceil(g/N)),D=Math.max(...B),L=J.dims[0],M=new BigInt64Array(L*D);for(let g=0;gE*P,1),R=J9[D.type];V[D.name]=new u(D.type,new R(M),L)}let N=J9[F],j=new u(F,new N($*v$),[1,$,v$]),B=Q[Symbol.asyncIterator]?.()??Q[Symbol.iterator]?.();if(!B)throw Error("input_features must be iterable or async iterable");return{encoder_session:Z,enc_kv_cache:V,enc_padding_cache:j,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:B,text_hidden_size:X.hidden_size}}async function zE(J,Q){let X=Q.dims[2],K=Math.floor((NE+X-3)/2)+1,Z=new u("int64",BigInt64Array.from({length:K},(q,F)=>BigInt(J.enc_past_seq_len+F)),[1,K]),H=J.enc_past_seq_len+K,Y=j6([1,H]),{audio_embeds:$,present_padding_cache:V,...W}=await O0(J.encoder_session,{input_features:Q,attention_mask:Y,position_ids:Z,past_padding_cache:J.enc_padding_cache,...J.enc_kv_cache});if(J.enc_padding_cache.location==="gpu-buffer")J.enc_padding_cache.dispose();J.enc_padding_cache=V;for(let q in W)if(q.startsWith("present.")){let F=q.replace("present","past_key_values"),N=J.enc_kv_cache[F];if(N?.location==="gpu-buffer")N.dispose();J.enc_kv_cache[F]=W[q]}return J.enc_past_seq_len=H,$}async function OE(J,Q){while(J.audio_embed_total_tokens0&&J.audio_embed_queue.length>0){let Y=J.audio_embed_queue[0],$=Y.tokens-J.audio_queue_offset,V=Math.min(H,$),W=J.audio_queue_offset*J.text_hidden_size;for(let q=0;q=Y.tokens)J.audio_embed_queue.shift(),J.audio_queue_offset=0}J.audio_consumed+=X-H}var DE=class extends F7{constructor(J){super();this._s=J}_call(J){let Q=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return J.map(()=>Q)}},IG=class extends T{forward_params=["input_ids","attention_mask","position_ids","past_key_values"]},vG=class extends IG{async forward({input_ids:J,past_key_values:Q,...X}){let K=J.dims[1],Z=GJ.get(this);if(Z)await OE(Z,Z.audio_consumed+K);let{inputs_embeds:H}=await O0(this.sessions.embed_tokens,{input_ids:J});if(Z)BE(Z,H,K);let Y={inputs_embeds:H,...X};rJ(this,Y,Q);let $=this.sessions.decoder_model_merged,V=e0(Y,$.inputNames);return await O0($,V)}async generate({input_features:J,stopping_criteria:Q,...X}){if(!J)throw Error("input_features (generator/iterable) must be provided");let K=jE(this,J);GJ.set(this,K);let Z=new $W;if(Z.push(new DE(K)),Q)Z.extend(Q);try{return await super.generate({...X,stopping_criteria:Z})}finally{K.enc_kv_cache.dispose(),GJ.delete(this)}}},v7=class extends T{},ME=class extends v7{},SE=class extends v7{async _call(J){return new m5(await super._call(J))}},LE=class extends v7{async _call(J){return new Z0(await super._call(J))}},yG=class extends r0{constructor({logits:J,embeddings:Q}){super();this.logits=J,this.embeddings=Q}},w8=class extends T{},CE=class extends w8{},RE=class extends w8{async _call(J){return new m5(await super._call(J))}},AE=class extends w8{async _call(J){return new Z0(await super._call(J))}},PE=class extends w8{async _call(J){return new yG(await super._call(J))}},EE=class extends w8{async _call(J){return new m0(await super._call(J))}},xG=class extends T{},wE=class extends xG{},TE=class extends YW{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},oX=class extends T{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]},IE=class extends oX{},kG=class extends oX{_prepare_generation_config(J,Q){return super._prepare_generation_config(J,Q,TE)}_retrieve_init_tokens(J){let Q=[J.decoder_start_token_id],X=J.language,K=J.task;if(J.is_multilingual){if(!X)$0.warn("No language specified - defaulting to English (en)."),X="en";let H=`<|${ZO(X)}|>`;Q.push(J.lang_to_id[H]),Q.push(J.task_to_id[K??"transcribe"])}else if(X||K)throw 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.");if(!J.return_timestamps&&J.no_timestamps_token_id&&Q.at(-1)!==J.no_timestamps_token_id)Q.push(J.no_timestamps_token_id);else if(J.return_timestamps&&Q.at(-1)===J.no_timestamps_token_id)$0.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),Q.pop();return Q.filter((Z)=>Z!=null)}async generate({inputs:J=null,generation_config:Q=null,logits_processor:X=null,stopping_criteria:K=null,...Z}){Q=this._prepare_generation_config(Q,Z);let H=Z.decoder_input_ids instanceof u?bJ(Z.decoder_input_ids):Z.decoder_input_ids??this._retrieve_init_tokens(Q);if(Q.return_timestamps)X??=new MJ,X.push(new cD(Q,H));if(Q.begin_suppress_tokens)X??=new MJ,X.push(new HW(Q.begin_suppress_tokens,H.length));if(Q.return_token_timestamps){if(!Q.alignment_heads)throw 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.");if(Q.task==="translate")$0.warn("Token-level timestamps may not be reliable for task 'translate'.");Q.output_attentions=!0,Q.return_dict_in_generate=!0}if(Q.return_timestamps&&!Z.max_new_tokens)return this._generate_with_seek({inputs:J,generation_config:Q,logits_processor:X,init_tokens:H,kwargs:Z});let Y=await super.generate({inputs:J,generation_config:Q,logits_processor:X,decoder_input_ids:H,...Z});if(Q.return_token_timestamps)Y.token_timestamps=this._extract_token_timestamps(Y,Q.alignment_heads,Q.num_frames,0.02,H.length);return Y}async _generate_with_seek({inputs:J,generation_config:Q,logits_processor:X,init_tokens:K,kwargs:Z}){let H=Q.no_timestamps_token_id+1,Y=Array.isArray(Q.eos_token_id)?Q.eos_token_id[0]:Q.eos_token_id,$=Q.return_token_timestamps,V=J,W=V.dims[2],q=2,N=2*this.config.max_source_positions,j=0,B=[],D=[];while(jQ0+o)}if(C.length>0&&C.at(-1)===Y)C.pop();if(C.length===0)break;let g=C.map((o)=>o>=H),d=C.length>=2&&g[C.length-1]&&!g[C.length-2],r=[];for(let o=0;o0)if(d)i=M-j;else{let o=r.at(-1);i=(C[o-1]-H)*2,p=o}else i=M-j;let f=Math.floor(j/2),v=H+1500;for(let o=0;o=H)C[o]=Math.min(C[o]+f,v);if(B.push(...C.slice(0,p)),c)D.push(...c.slice(0,p));j+=i}B.push(Y);let L=[...K,...B];if($){let M=new u("int64",L.map(BigInt),[1,L.length]),R=[...Array(K.length).fill(0),...D,0],E=new u("float32",new Float32Array(R),[1,R.length]);return{sequences:M,token_timestamps:E}}return new u("int64",L.map(BigInt),[1,L.length])}_extract_token_timestamps(J,Q,X=null,K=0.02,Z=0){if(!J.cross_attentions)throw Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");if(X==null)$0.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 H=this.config.median_filter_width;if(H===void 0)$0.warn("Model config has no `median_filter_width`, using default value of 7."),H=7;let Y=J.cross_attentions,$=Array.from({length:this.config.decoder_layers},(L,M)=>h0(Y.map((R)=>R[M]),2)),V=$5(Q.map(([L,M])=>{if(L>=$.length)throw Error(`Layer index ${L} is out of bounds for cross attentions (length ${$.length}).`);return X?$[L].slice(null,M,null,[0,X]):$[L].slice(null,M)})).transpose(1,0,2,3),[W,q]=Vz(V,-2,0,!0),F=V.clone();for(let L=0;L0?F.slice(null,null,[Z,F.dims[2]],null):F,j=[kJ(N,1)],B=J.sequences.dims,D=new u("float32",new Float32Array(B[0]*B[1]),B);for(let L=0;LR[g+1]-R[g]),w=a6([1],P).map((c)=>!!c),k=[];for(let c=0;c0)C.push(k.at(-1));D[L].data.set(C)}return D}},vE=class extends kG{},T8=class extends T{},yE=class extends T8{},xE=class extends T8{async _call(J){return new a0(await super._call(J))}},kE=class extends T8{async _call(J){return new Z0(await super._call(J))}},hE=class extends T8{async _call(J){return new m0(await super._call(J))}},bE=class extends T8{async _call(J){return new G6(await super._call(J))}},I8=class extends T{},fE=class extends I8{},_E=class extends I8{async _call(J){return new a0(await super._call(J))}},gE=class extends I8{async _call(J){return new Z0(await super._call(J))}},cE=class extends I8{async _call(J){return new m0(await super._call(J))}},lE=class extends I8{async _call(J){return new G6(await super._call(J))}},nX=class extends T{},uE=class extends nX{},mE=class extends nX{async _call(J){return new hG(await super._call(J))}},hG=class extends r0{constructor({logits:J,pred_boxes:Q}){super();this.logits=J,this.pred_boxes=Q}},sX=class extends T{},dE=class extends sX{},pE=class extends sX{},iE=new Map([["bert","BertModel"],["eurobert","EuroBertModel"],["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"],["openai_privacy_filter","OpenAIPrivacyFilterModel"]]),rE=new Map([["t5","T5Model"],["longt5","LongT5Model"],["mt5","MT5Model"],["bart","BartModel"],["mbart","MBartModel"],["marian","MarianModel"],["whisper","WhisperModel"],["cohere_asr","CohereAsrModel"],["m2m_100","M2M100Model"],["blenderbot","BlenderbotModel"],["blenderbot-small","BlenderbotSmallModel"]]),aE=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),oE=new Map([["bloom","BloomModel"],["jais","JAISModel"],["gpt2","GPT2Model"],["gpt_oss","GptOssModel"],["gptj","GPTJModel"],["gpt_bigcode","GPTBigCodeModel"],["gpt_neo","GPTNeoModel"],["gpt_neox","GPTNeoXModel"],["codegen","CodeGenModel"],["llama","LlamaModel"],["apertus","ApertusModel"],["nanochat","NanoChatModel"],["arcee","ArceeModel"],["afmoe","AfmoeModel"],["lfm2","Lfm2Model"],["lfm2_moe","Lfm2MoeModel"],["smollm3","SmolLM3Model"],["exaone","ExaoneModel"],["olmo","OlmoModel"],["olmo2","Olmo2Model"],["olmo3","Olmo3Model"],["olmo_hybrid","OlmoHybridModel"],["mobilellm","MobileLLMModel"],["granite","GraniteModel"],["granitemoehybrid","GraniteMoeHybridModel"],["cohere","CohereModel"],["cohere2","Cohere2Model"],["gemma","GemmaModel"],["gemma2","Gemma2Model"],["vaultgemma","VaultGemmaModel"],["gemma3_text","Gemma3Model"],["helium","HeliumModel"],["glm","GlmModel"],["glm_moe_dsa","GlmMoeDsaModel"],["openelm","OpenELMModel"],["qwen2","Qwen2Model"],["qwen2_moe","Qwen2MoeModel"],["qwen3","Qwen3Model"],["qwen3_moe","Qwen3MoeModel"],["qwen3_next","Qwen3NextModel"],["phi","PhiModel"],["phi3","Phi3Model"],["mpt","MptModel"],["opt","OPTModel"],["mistral","MistralModel"],["mistral4","Mistral4Model"],["ministral","MinistralModel"],["ministral3","Ministral3Model"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2Model"],["deepseek_v3","DeepseekV3Model"],["falcon","FalconModel"],["falcon_h1","FalconH1Model"],["nemotron_h","NemotronHModel"],["solar_open","SolarOpenModel"],["stablelm","StableLmModel"],["modernbert-decoder","ModernBertDecoderModel"],["hunyuan_v1_dense","HunYuanDenseV1Model"],["youtu","YoutuModel"]]),bG=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"],["cohere_asr","CohereAsrForConditionalGeneration"]]),fG=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),_G=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),gG=new Map([["bert","BertForSequenceClassification"],["eurobert","EuroBertForSequenceClassification"],["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"]]),cG=new Map([["bert","BertForTokenClassification"],["eurobert","EuroBertForTokenClassification"],["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"],["openai_privacy_filter","OpenAIPrivacyFilterForTokenClassification"]]),lG=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),uG=new Map([["bloom","BloomForCausalLM"],["gpt2","GPT2LMHeadModel"],["gpt_oss","GptOssForCausalLM"],["jais","JAISLMHeadModel"],["gptj","GPTJForCausalLM"],["gpt_bigcode","GPTBigCodeForCausalLM"],["gpt_neo","GPTNeoForCausalLM"],["gpt_neox","GPTNeoXForCausalLM"],["codegen","CodeGenForCausalLM"],["llama","LlamaForCausalLM"],["nanochat","NanoChatForCausalLM"],["apertus","ApertusForCausalLM"],["llama4_text","Llama4ForCausalLM"],["arcee","ArceeForCausalLM"],["afmoe","AfmoeForCausalLM"],["lfm2","Lfm2ForCausalLM"],["lfm2_moe","Lfm2MoeForCausalLM"],["smollm3","SmolLM3ForCausalLM"],["exaone","ExaoneForCausalLM"],["olmo","OlmoForCausalLM"],["olmo2","Olmo2ForCausalLM"],["olmo3","Olmo3ForCausalLM"],["olmo_hybrid","OlmoHybridForCausalLM"],["mobilellm","MobileLLMForCausalLM"],["granite","GraniteForCausalLM"],["granitemoehybrid","GraniteMoeHybridForCausalLM"],["cohere","CohereForCausalLM"],["cohere2","Cohere2ForCausalLM"],["gemma","GemmaForCausalLM"],["gemma2","Gemma2ForCausalLM"],["vaultgemma","VaultGemmaForCausalLM"],["gemma3_text","Gemma3ForCausalLM"],["gemma3","Gemma3ForCausalLM"],["helium","HeliumForCausalLM"],["glm","GlmForCausalLM"],["glm_moe_dsa","GlmMoeDsaForCausalLM"],["openelm","OpenELMForCausalLM"],["qwen2","Qwen2ForCausalLM"],["qwen2_moe","Qwen2MoeForCausalLM"],["qwen3","Qwen3ForCausalLM"],["qwen3_moe","Qwen3MoeForCausalLM"],["qwen3_next","Qwen3NextForCausalLM"],["qwen2_vl","Qwen2VLForCausalLM"],["qwen2_5_vl","Qwen2_5_VLForCausalLM"],["qwen3_vl","Qwen3VLForCausalLM"],["qwen3_vl_moe","Qwen3VLMoeForCausalLM"],["qwen3_5","Qwen3_5ForCausalLM"],["qwen3_5_text","Qwen3_5ForCausalLM"],["qwen3_5_moe","Qwen3_5MoeForCausalLM"],["gemma3n","Gemma3nForCausalLM"],["gemma4","Gemma4ForCausalLM"],["phi","PhiForCausalLM"],["phi3","Phi3ForCausalLM"],["mpt","MptForCausalLM"],["opt","OPTForCausalLM"],["mbart","MBartForCausalLM"],["mistral","MistralForCausalLM"],["mistral4","Mistral4ForCausalLM"],["ministral","MinistralForCausalLM"],["ministral3","Ministral3ForCausalLM"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2ForCausalLM"],["deepseek_v3","DeepseekV3ForCausalLM"],["falcon","FalconForCausalLM"],["falcon_h1","FalconH1ForCausalLM"],["nemotron_h","NemotronHForCausalLM"],["trocr","TrOCRForCausalLM"],["solar_open","SolarOpenForCausalLM"],["stablelm","StableLmForCausalLM"],["modernbert-decoder","ModernBertDecoderForCausalLM"],["hunyuan_v1_dense","HunYuanDenseV1ForCausalLM"],["youtu","YoutuForCausalLM"],["phi3_v","Phi3VForCausalLM"]]),nE=new Map([["multi_modality","MultiModalityCausalLM"]]),mG=new Map([["bert","BertForMaskedLM"],["eurobert","EuroBertForMaskedLM"],["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"]]),dG=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"]]),pG=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),iG=new Map([["llava","LlavaForConditionalGeneration"],["llava_onevision","LlavaOnevisionForConditionalGeneration"],["moondream1","Moondream1ForConditionalGeneration"],["florence2","Florence2ForConditionalGeneration"],["qwen2_vl","Qwen2VLForConditionalGeneration"],["qwen2_5_vl","Qwen2_5_VLForConditionalGeneration"],["qwen3_vl","Qwen3VLForConditionalGeneration"],["qwen3_vl_moe","Qwen3VLMoeForConditionalGeneration"],["qwen3_5","Qwen3_5ForConditionalGeneration"],["qwen3_5_moe","Qwen3_5MoeForConditionalGeneration"],["lfm2_vl","Lfm2VlForConditionalGeneration"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"],["paligemma","PaliGemmaForConditionalGeneration"],["llava_qwen2","LlavaQwen2ForCausalLM"],["gemma3","Gemma3ForConditionalGeneration"],["gemma3n","Gemma3nForConditionalGeneration"],["gemma4","Gemma4ForConditionalGeneration"],["mistral3","Mistral3ForConditionalGeneration"],["lighton_ocr","LightOnOcrForConditionalGeneration"],["glm_ocr","GlmOcrForConditionalGeneration"]]),rG=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),sE=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),aG=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"]]),oG=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),nG=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),$8=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),sG=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),tG=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),eG=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),Jq=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),Qq=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),Xq=new Map([["wavlm","WavLMForXVector"]]),Kq=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),Zq=new Map([["vitmatte","VitMatteForImageMatting"]]),tE=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),Hq=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),Yq=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),$q=new Map([["sapiens","SapiensForNormalEstimation"]]),Vq=new Map([["vitpose","VitPoseForPoseEstimation"]]),Wq=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),Gq=[[iE,m.EncoderOnly],[rE,m.EncoderDecoder],[oE,m.DecoderOnlyWithoutHead],[aE,m.AutoEncoder],[gG,m.EncoderOnly],[cG,m.EncoderOnly],[lG,m.Seq2Seq],[bG,m.Seq2Seq],[uG,m.DecoderOnly],[nE,m.MultiModality],[mG,m.EncoderOnly],[dG,m.EncoderOnly],[pG,m.Vision2Seq],[iG,m.ImageTextToText],[rG,m.AudioTextToText],[aG,m.EncoderOnly],[$8,m.EncoderOnly],[tG,m.EncoderOnly],[sG,m.EncoderOnly],[Zq,m.EncoderOnly],[tE,m.EncoderOnly],[Hq,m.EncoderOnly],[Yq,m.EncoderOnly],[$q,m.EncoderOnly],[Vq,m.EncoderOnly],[oG,m.EncoderOnly],[nG,m.EncoderOnly],[eG,m.MaskGeneration],[Jq,m.EncoderOnly],[Qq,m.EncoderOnly],[fG,m.Seq2Seq],[_G,m.EncoderOnly],[Xq,m.EncoderOnly],[Kq,m.EncoderOnly],[Wq,m.EncoderOnly]];for(let[J,Q]of Gq)for(let X of J.values()){Y5.set(X,Q);let K=oJ[X];F8.set(K,X),iJ.set(X,K)}var eE=[["MusicgenForConditionalGeneration",ZG,m.Musicgen],["Phi3VForCausalLM",VG,m.Phi3V],["CLIPTextModelWithProjection",CW,m.EncoderOnly],["SiglipTextModel",OG,m.EncoderOnly],["JinaCLIPTextModel",rW,m.EncoderOnly],["ClapTextModelWithProjection",SW,m.EncoderOnly],["ClapAudioModelWithProjection",LW,m.EncoderOnly],["DacEncoderModel",PW,m.EncoderOnly],["DacDecoderModel",EW,m.EncoderOnly],["MimiEncoderModel",QG,m.EncoderOnly],["MimiDecoderModel",XG,m.EncoderOnly],["SnacEncoderModel",BG,m.EncoderOnly],["SnacDecoderModel",DG,m.EncoderOnly],["Gemma3nForConditionalGeneration",B7,m.ImageAudioTextToText],["Gemma4ForConditionalGeneration",EQ,m.ImageAudioTextToText],["SupertonicForConditionalGeneration",LG,m.Supertonic],["ChatterboxModel",BW,m.Chatterbox],["VoxtralRealtimeForConditionalGeneration",vG,m.VoxtralRealtime]];for(let[J,Q,X]of eE)Y5.set(J,X),F8.set(Q,J),iJ.set(J,Q);var qq=new Map([["modnet",$8],["birefnet",$8],["isnet",$8],["ben",$8]]);for(let[J,Q]of qq.entries())Q.set(J,"PreTrainedModel"),Y5.set(J,m.EncoderOnly),iJ.set(J,T);var Jw=new Set(qq.keys());Y5.set("PreTrainedModel",m.EncoderOnly);F8.set(T,"PreTrainedModel");var A0={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:gG,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:cG,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:fG,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:_G,MODEL_FOR_MASKED_LM_MAPPING_NAMES:mG,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:dG,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:aG,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:$8,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:sG,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:tG,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:oG,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:nG,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:eG,MODEL_FOR_CTC_MAPPING_NAMES:Jq,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:Qq,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:Xq,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:Kq,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:sE,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:Zq,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:Hq,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:Yq,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:$q,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:Vq,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:Wq,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:iG,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:rG,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:lG,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:bG,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:uG,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:pG};XM(A0);var P0=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(J){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(let Q of this.MODEL_CLASS_MAPPINGS)if(Q.has(J))return!0;return this.BASE_IF_FAIL}static async from_pretrained(J,{progress_callback:Q=null,config:X=null,cache_dir:K=null,local_files_only:Z=!1,revision:H="main",model_file_name:Y=null,subfolder:$="onnx",device:V=null,dtype:W=null,use_external_data_format:q=null,session_options:F={}}={}){let N={progress_callback:Q,config:X,cache_dir:K,local_files_only:Z,revision:H,model_file_name:Y,subfolder:$,device:V,dtype:W,use_external_data_format:q,session_options:F};if(N.config=await X9.from_pretrained(J,N),!this.MODEL_CLASS_MAPPINGS)throw Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let{model_type:j}=N.config;for(let B of this.MODEL_CLASS_MAPPINGS){let D=B.get(j);if(!D){for(let L of B.values())if(L[0]===j){D=L;break}if(!D)continue}return await oJ[D].from_pretrained(J,N)}if(this.BASE_IF_FAIL){if(!Jw.has(j))$0.warn(`Unknown model class "${j}", attempting to construct from base class.`);return await T.from_pretrained(J,N)}else throw Error(`Unsupported model type: ${j}`)}},n8=class extends P0{static MODEL_CLASS_MAPPINGS=Gq.map((J)=>J[0]);static BASE_IF_FAIL=!0},y$=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},Qw=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},qJ=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},Xw=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},Kw=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},Zw=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},Hw=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},Yw=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},$w=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},Vw=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},Ww=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},x$=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},k$=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},h$=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},Gw=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},qw=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]},HI=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]},Fw=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_CTC_MAPPING_NAMES]},Uw=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]},YI=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]},$I=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]},Nw=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]},VI=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]},jw=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},zw=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]},WI=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]},GI=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]},Ow=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]},qI=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]},FI=class extends P0{static MODEL_CLASS_MAPPINGS=[A0.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function c6(J){if(!Array.isArray(J))J=[J];return await Promise.all(J.map((Q)=>h6.read(Q)))}async function V8(J,Q){if(!Array.isArray(J))J=[J];return await Promise.all(J.map((X)=>{if(typeof X==="string"||X instanceof URL)return jO(X,Q);else if(X instanceof Float64Array)return new Float32Array(X);return X}))}function CJ(J,Q){if(Q)J=J.map((Y)=>Y|0);let[X,K,Z,H]=J;return{xmin:X,ymin:K,xmax:Z,ymax:H}}var g0=class extends z6{constructor({task:J,model:Q,tokenizer:X=null,processor:K=null}){super();this.task=J,this.model=Q,this.tokenizer=X,this.processor=K}async dispose(){await this.model.dispose()}},Bw=class extends g0{async _call(J,{top_k:Q=1}={}){let X=this.tokenizer(J,{padding:!0,truncation:!0}),K=await this.model(X),{problem_type:Z,id2label:H}=this.model.config,Y=Z==="multi_label_classification"?(V)=>V.sigmoid():(V)=>new u("float32",K6(V.data),V.dims),$=[];for(let V of K.logits){let W=Y(V),q=await z8(W,Q),F=q[0].tolist(),j=q[1].tolist().map((B,D)=>({label:H?H[B]:`LABEL_${B}`,score:F[D]}));if(Q===1)$.push(...j);else $.push(j)}return Array.isArray(J)||Q===1?$:$[0]}},Dw=class extends g0{async _call(J,{ignore_labels:Q=["O"],aggregation_strategy:X="none"}={}){if(X!=="none"&&X!=="simple")throw Error(`Invalid aggregation_strategy: "${X}". Must be one of "none" or "simple".`);let K=Array.isArray(J),Z=this.tokenizer(K?J:[J],{padding:!0,truncation:!0}),Y=(await this.model(Z)).logits,$=this.model.config.id2label,V=[];for(let W=0;W{let V=0,W=[];for(let q=Y;q<$;++q)V+=J[q].score,W.push(Q[J[q].index]);return{entity_group:H,score:V/($-Y),word:X.decode(W,{skip_special_tokens:!0})}})}var Lw=class extends g0{async _call(J,Q,{top_k:X=1}={}){let K=this.tokenizer(J,{text_pair:Q,padding:!0,truncation:!0}),Z=Array.isArray(J),{start_logits:H,end_logits:Y}=await this.model(K),$=K.input_ids.tolist(),V=K.attention_mask.tolist(),{all_special_ids:W,sep_token_id:q}=this.tokenizer,F=[];for(let N=0;Nw==q),D=H[N].tolist(),L=Y[N].tolist();for(let w=1;wk==j[w])!==-1)D[w]=-1/0,L[w]=-1/0;let M=K6(D).map((w,k)=>[w,k]),R=K6(L).map((w,k)=>[w,k]);M[0][0]=0,R[0][0]=0;let E=jU(M,R).filter((w)=>w[0][1]<=w[1][1]).map((w)=>[w[0][1],w[1][1],w[0][0]*w[1][0]]).sort((w,k)=>k[2]-w[2]),P=[];for(let w=0;wD==X);if(q===-1)throw Error(`Mask token (${K}) not found in text.`);let F=H[V][q],N=await z8(new u("float32",K6(F.data),F.dims),Q),j=N[0].tolist(),B=N[1].tolist();Y.push(B.map((D,L)=>{let M=W.slice();return M[q]=D,{score:j[L],token:Number(D),token_str:this.tokenizer.decode([D]),sequence:this.tokenizer.decode(M,{skip_special_tokens:!0})}}))}return Array.isArray(J)?Y:Y[0]}},tX=class extends g0{_default_generation_config={max_new_tokens:256};_key="generated_text";async _call(J,Q={}){if(!Array.isArray(J))J=[J];if(this.model.config.prefix)J=J.map(($)=>this.model.config.prefix+$);let X=this.model.config.task_specific_params;if(X&&X[this.task]){if(X[this.task].prefix)J=J.map(($)=>X[this.task].prefix+$)}let K=this.tokenizer,Z={padding:!0,truncation:!0},H;if(this.task==="translation"&&"_build_translation_inputs"in K)H=K._build_translation_inputs(J,Z,Q);else H=K(J,Z);let Y=await this.model.generate({...H,...this._default_generation_config,...Q});return K.batch_decode(Y,{skip_special_tokens:!0}).map(($)=>({[this._key]:$}))}},Rw=class extends tX{_key="summary_text"},Aw=class extends tX{_key="translation_text"};function b$(J){return Array.isArray(J)&&J.every((Q)=>("role"in Q)&&("content"in Q))}var Pw=class extends g0{_default_generation_config={max_new_tokens:256};async _call(J,Q={}){let{add_special_tokens:X,return_full_text:K,tools:Z,documents:H,chat_template:Y,tokenizer_encode_kwargs:$,...V}=Q,W=!1,q=!1,F=X??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,N=$,j;if(typeof J==="string")j=J=[J];else if(Array.isArray(J)&&J.every((P)=>typeof P==="string"))W=!0,j=J;else{if(b$(J))J=[J];else if(Array.isArray(J)&&J.every(b$))W=!0;else throw Error("Input must be a string, an array of strings, a Chat, or an array of Chats");q=!0;let P={tokenize:!1,add_generation_prompt:!0,...e0({tools:Z,documents:H,chat_template:Y},["tools","documents","chat_template"]),...N};j=J.map((w)=>this.tokenizer.apply_chat_template(w,P)),F=!1,N=void 0}let B=q?!1:K??!0;this.tokenizer.padding_side="left";let D=this.tokenizer(j,{add_special_tokens:F,padding:!0,truncation:!0,...N}),L=await this.model.generate({...D,...this._default_generation_config,...V}),M=this.tokenizer.batch_decode(L,{skip_special_tokens:!0}),R;if(!B&&D.input_ids.dims.at(-1)>0)R=this.tokenizer.batch_decode(D.input_ids,{skip_special_tokens:!0}).map((P)=>P.length);let E=Array.from({length:J.length},(P)=>[]);for(let P=0;P[Q.toLowerCase(),X])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0)$0.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2;if(this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0)$0.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0}async _call(J,Q,{hypothesis_template:X="This example is {}.",multi_label:K=!1}={}){let Z=Array.isArray(J);if(!Z)J=[J];if(!Array.isArray(Q))Q=[Q];let H=Q.map((V)=>X.replace("{}",V)),Y=K||Q.length===1,$=[];for(let V of J){let W=[];for(let N of H){let j=this.tokenizer(V,{text_pair:N,padding:!0,truncation:!0}),B=await this.model(j);if(Y)W.push([B.logits.data[this.contradiction_id],B.logits.data[this.entailment_id]]);else W.push(B.logits.data[this.entailment_id])}let F=(Y?W.map((N)=>K6(N)[1]):K6(W)).map((N,j)=>[N,j]).sort((N,j)=>j[0]-N[0]);$.push({sequence:V,labels:F.map((N)=>Q[N[1]]),scores:F.map((N)=>N[0])})}return Z?$:$[0]}},ww=class extends g0{async _call(J,{top_k:Q=5}={}){let X=this.processor.feature_extractor.config.sampling_rate,K=await V8(J,X),Z=this.model.config.id2label,H=[];for(let Y of K){let $=await this.processor(Y),W=(await this.model($)).logits[0],q=await z8(new u("float32",K6(W.data),W.dims),Q),F=q[0].tolist(),j=q[1].tolist().map((B,D)=>({label:Z?Z[B]:`LABEL_${B}`,score:F[D]}));H.push(j)}return Array.isArray(J)?H:H[0]}},Tw=class extends g0{async _call(J,Q,{hypothesis_template:X="This is a sound of {}."}={}){let K=!Array.isArray(J);if(K)J=[J];let Z=Q.map((W)=>X.replace("{}",W)),H=this.tokenizer(Z,{padding:!0,truncation:!0}),Y=this.processor.feature_extractor.config.sampling_rate,$=await V8(J,Y),V=[];for(let W of $){let q=await this.processor(W),F=await this.model({...H,...q}),N=K6(F.logits_per_audio.data);V.push([...N].map((j,B)=>({score:j,label:Q[B]})))}return K?V[0]:V}},Iw=class extends g0{_default_generation_config={};async _call(J,Q={}){switch(Q={...this._default_generation_config,...Q},this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(J,Q);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(J,Q);case"moonshine":return this._call_moonshine(J,Q);case"cohere_asr":return this._call_cohere_asr(J,Q);default:throw Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(J,Q){if(Q.language)$0.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".');if(Q.task)$0.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let X=!Array.isArray(J),K=X?[J]:J,Z=this.processor.feature_extractor.config.sampling_rate,H=await V8(K,Z),Y=[];for(let $ of H){let V=await this.processor($),q=(await this.model(V)).logits[0],F=[];for(let j of q)F.push(c0(j.data)[1]);let N=this.tokenizer.decode(F,{skip_special_tokens:!0}).trim();Y.push({text:N})}return X?Y[0]:Y}async _call_whisper(J,Q){let X=Q.return_timestamps??!1,K=Q.chunk_length_s??0,Z=Q.force_full_sequences??!1,H=Q.stride_length_s??null,Y={...Q};if(X==="word")Y.return_token_timestamps=!0,Y.return_timestamps=!0;let $=!Array.isArray(J),V=$?[J]:J,W=this.processor.feature_extractor.config,q=W.chunk_length/this.model.config.max_source_positions,F=W.hop_length,N=W.sampling_rate,j=await V8(V,N),B=[];for(let D of j){let L=[];if(K>0){if(H===null)H=K/6;else if(K<=H)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let E=N*K,P=N*H,w=E-2*P,k=0;while(!0){let C=k+E,c=D.subarray(k,C),g=await this.processor(c),d=k===0,r=C>=D.length;if(L.push({stride:[c.length,d?0:P,r?0:P],input_features:g.input_features,is_last:r}),r)break;k+=w}}else L=[{stride:[D.length,0,0],input_features:(await this.processor(D)).input_features,is_last:!0}];for(let E of L){Y.num_frames=Math.floor(E.stride[0]/F);let P=await this.model.generate({inputs:E.input_features,...Y});if(X==="word"){let w=P.sequences.tolist()[0],k=P.token_timestamps.tolist()[0],C=this.tokenizer.timestamp_begin,c=Math.max(w.findIndex((g)=>Number(g)>=C),0);E.tokens=w.slice(c),E.token_timestamps=k.slice(c).map((g)=>o8(g,2))}else E.tokens=P[0].tolist();E.stride=E.stride.map((w)=>w/N)}let[M,R]=this.tokenizer._decode_asr(L,{time_precision:q,return_timestamps:X,force_full_sequences:Z});B.push({text:M,...R})}return $?B[0]:B}async _call_moonshine(J,Q){let X=!Array.isArray(J),K=X?[J]:J,Z=this.processor.feature_extractor.config.sampling_rate,H=await V8(K,Z),Y=[];for(let $ of H){let V=await this.processor($),W=Math.floor($.length/Z)*6,q=await this.model.generate({max_new_tokens:W,...Q,...V}),F=this.processor.batch_decode(q,{skip_special_tokens:!0})[0];Y.push({text:F})}return X?Y[0]:Y}async _call_cohere_asr(J,Q){let X=!Array.isArray(J),K=X?[J]:J,Z=this.processor.feature_extractor,H=Z.config.sampling_rate,Y=await V8(K,H),$=Q.language??"en",V=this.processor.get_decoder_prompt_ids($),W=[];for(let q of Y){let F=Z.split_audio(q),N=[];for(let B of F){let D=await this.processor(B),L=await this.model.generate({...D,decoder_input_ids:V,...Q}),M=this.tokenizer.decode(L[0].tolist(),{skip_special_tokens:!0}).trim();N.push(M)}let j=this.processor.constructor.join_chunks(N,$);W.push({text:j})}return X?W[0]:W}},vw=class extends g0{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(J){super(J);this.vocoder=J.vocoder??null}async _prepare_speaker_embeddings(J,Q){if(typeof J==="string"||J instanceof URL)J=new Float32Array(await(await G0.fetch(J)).arrayBuffer());if(J instanceof Float32Array)J=new u("float32",J,[J.length]);else if(!(J instanceof u))throw Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(Q>1){if(J.dims[0]===1)J=J.repeat(Q,1);else if(J.dims[0]!==Q)throw Error(`Expected speaker embeddings batch size to be 1 or ${Q}, but got ${J.dims[0]}.`)}return J}_postprocess_waveform(J,Q,X,K=null){let Z=Q.data,[H,Y]=Q.dims,$=K?K.data:null,V=[];for(let W=0;W({generated_text:W.trim()}));H.push(V)}return X?H:H[0]}},xw=class extends g0{async _call(J,{top_k:Q=5}={}){let X=await c6(J),{pixel_values:K}=await this.processor(X),Z=await this.model({pixel_values:K}),{id2label:H}=this.model.config,Y=[];for(let $ of Z.logits){let V=await z8(new u("float32",K6($.data),$.dims),Q),W=V[0].tolist(),F=V[1].tolist().map((N,j)=>({label:H?H[N]:`LABEL_${N}`,score:W[j]}));Y.push(F)}return Array.isArray(J)?Y:Y[0]}},f$={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},Fq=class extends g0{async _call(J,{threshold:Q=0.5,mask_threshold:X=0.5,overlap_mask_area_threshold:K=0.8,label_ids_to_fuse:Z=null,target_sizes:H=null,subtask:Y=null}={}){if(Array.isArray(J)&&J.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");let V=await c6(J),W=V.map((M)=>[M.height,M.width]),q=await this.processor(V),{inputNames:F,outputNames:N}=this.model.sessions.model;if(!F.includes("pixel_values")){if(F.length!==1)throw Error(`Expected a single input name, but got ${F.length} inputs: ${F}.`);let M=F[0];if(M in q)throw Error(`Input name ${M} already exists in the inputs.`);q[M]=q.pixel_values}let j=await this.model(q),B=null;if(Y!==null)B=f$[Y];else if(this.processor.image_processor){for(let[M,R]of Object.entries(f$))if(R in this.processor.image_processor){B=this.processor.image_processor[R].bind(this.processor.image_processor),Y=M;break}}let D=this.model.config.id2label,L=[];if(!Y){let R=j[N[0]];for(let E=0;EC<-0.00001||C>1.00001))w.sigmoid_();let k=await h6.fromTensor(w.mul_(255).to("uint8")).resize(P[1],P[0]);L.push({label:null,score:null,mask:k})}}else if(Y==="panoptic"||Y==="instance"){let M=B(j,Q,X,K,Z,H??W)[0],R=M.segmentation;for(let E of M.segments_info){let P=new Uint8ClampedArray(R.data.length);for(let k=0;k{let $=H.clone();return $.putAlpha(K[Y].mask),$});return Array.isArray(J)?Z:Z[0]}},hw=class extends g0{async _call(J,Q,{hypothesis_template:X="This is a photo of {}"}={}){let K=Array.isArray(J),Z=await c6(J),H=Q.map((F)=>X.replace("{}",F)),Y=this.tokenizer(H,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:$}=await this.processor(Z),V=await this.model({...Y,pixel_values:$}),W=this.model.config.model_type==="siglip"?(F)=>F.sigmoid().data:(F)=>K6(F.data),q=[];for(let F of V.logits_per_image){let j=[...W(F)].map((B,D)=>({score:B,label:Q[D]}));j.sort((B,D)=>D.score-B.score),q.push(j)}return K?q:q[0]}},bw=class extends g0{async _call(J,{threshold:Q=0.9,percentage:X=!1}={}){let K=Array.isArray(J);if(K&&J.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");let Z=await c6(J),H=X?null:Z.map((N)=>[N.height,N.width]),{pixel_values:Y,pixel_mask:$}=await this.processor(Z),V=await this.model({pixel_values:Y,pixel_mask:$}),W=this.processor.image_processor.post_process_object_detection(V,Q,H),{id2label:q}=this.model.config,F=W.map((N)=>N.boxes.map((j,B)=>({score:N.scores[B],label:q[N.classes[B]],box:CJ(j,!X)})));return K?F:F[0]}},fw=class extends g0{async _call(J,Q,{threshold:X=0.1,top_k:K=null,percentage:Z=!1}={}){let H=Array.isArray(J),Y=await c6(J),$=this.tokenizer(Q,{padding:!0,truncation:!0}),V=await this.processor(Y),W=[];for(let q=0;q({score:L.scores[R],label:L.labels[R],box:CJ(M,!Z)}))}else{let L=this.processor.image_processor.post_process_object_detection(B,X,N,!0)[0];D=L.boxes.map((M,R)=>({score:L.scores[R],label:Q[L.classes[R]],box:CJ(M,!Z)}))}if(D.sort((L,M)=>M.score-L.score),K!==null)D=D.slice(0,K);W.push(D)}return H?W:W[0]}},_w=class extends g0{_default_generation_config={max_new_tokens:256};async _call(J,Q,X={}){if(Array.isArray(J)){if(J.length!==1)throw Error("Document Question Answering pipeline currently only supports a batch size of 1.");J=J[0]}let K=(await c6(J))[0],{pixel_values:Z}=await this.processor(K),H=`${Q}`,Y=this.tokenizer(H,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,$=await this.model.generate({inputs:Z,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Y,...this._default_generation_config,...X}),W=this.tokenizer.batch_decode($)[0].match(/(.*?)<\/s_answer>/),q=null;if(W&&W.length>=2)q=W[1].trim();return[{answer:q}]}},gw=class extends g0{async _call(J){let Q=await c6(J),X=await this.processor(Q),K=await this.model(X),Z=[];for(let H of K.reconstruction){let Y=H.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Z.push(h6.fromTensor(Y))}return Array.isArray(J)?Z:Z[0]}},cw=class extends g0{async _call(J){let Q=await c6(J),X=await this.processor(Q),{predicted_depth:K}=await this.model(X),Z=[];for(let H=0;H`onnx/${N}`);return $.filter((N)=>!N.startsWith("onnx/")||F.some((j)=>N.startsWith(j)))}}return $}async function Nq(J,Q=null,{progress_callback:X=null,config:K=null,cache_dir:Z=null,local_files_only:H=!1,revision:Y="main",device:$=null,dtype:V=null,subfolder:W="onnx",use_external_data_format:q=null,model_file_name:F=null,session_options:N={}}={}){J=Uq[J]??J;let j=K7[J.split("_",1)[0]];if(!j)throw Error(`Unsupported pipeline: ${J}. Must be one of [${Object.keys(K7)}]`);if(!Q){if(Q=j.default.model,$0.info(`No model specified. Using default model: "${Q}".`),!V&&j.default.dtype)V=j.default.dtype}let B=await pw(J,Q,{device:$,dtype:V}),D={};if(X)(await Promise.all(B.map(async(r)=>H9(Q,r)))).forEach((r,i)=>{if(r.exists)D[B[i]]={loaded:0,total:r.size??0}});let L={progress_callback:X?new FJ(X,D):void 0,config:K,cache_dir:Z,local_files_only:H,revision:Y,device:$,dtype:V,subfolder:W,use_external_data_format:q,model_file_name:F,session_options:N},M=B.includes("tokenizer.json"),R=B.includes("preprocessor_config.json"),E=j.model,P;if(Array.isArray(E)){let d=K??await X9.from_pretrained(Q,L),{model_type:r}=d,i=E.find((p)=>p.supports(r));if(!i)throw Error(`Unsupported model type "${r}" for task "${J}". None of the candidate model classes support this type.`);P=i.from_pretrained(Q,{...L,config:d})}else P=E.from_pretrained(Q,L);let[w,k,C]=await Promise.all([M?C0.from_pretrained(Q,L):null,R?ED.from_pretrained(Q,L):null,P]),c={task:J,model:C};if(w)c.tokenizer=w;if(k)c.processor=k;return C5(X,{status:"ready",task:J,model:Q}),new j.pipeline(c)}var UI=U0.IS_PROCESS_AVAILABLE?(J)=>process.stdout.write(J):(J)=>console.log(J);var NI=Object.keys(J7);function iw(J,Q){let X=[],K=null,Z=()=>{if(K){let{start:H,end:Y}=K;while(HH&&/\s/.test(Q[Y-1]))Y--;if(Y>H)X.push({start:H,end:Y,label:K.label,text:Q.slice(H,Y),score:K.score/K.n});K=null}};for(let H of J){if(H.start===H.end)continue;if(H.entity==="O"||!H.entity){Z();continue}let Y=H.entity.indexOf("-"),$=Y===-1?"S":H.entity.slice(0,Y),V=Y===-1?H.entity:H.entity.slice(Y+1);if($==="B"||$==="S"||K&&K.label!==V)Z();if(!K)K={label:V,start:H.start,end:H.end,score:H.score??0,n:1};else K.end=H.end,K.score+=H.score??0,K.n+=1;if($==="E"||$==="S")Z()}return Z(),X}function rw(J,Q,X=1){let K=[...J].sort((H,Y)=>H.start-Y.start),Z=[];for(let H of K){let Y=Z[Z.length-1];if(Y&&H.label===Y.label&&H.start-Y.end<=X&&Q.slice(Y.end,H.start).trim()==="")Y.end=Math.max(Y.end,H.end),Y.text=Q.slice(Y.start,Y.end);else Z.push({...H})}return Z}function Zo(J,Q,X="label"){let K=[...Q].sort((Y,$)=>Y.start-$.start),Z="",H=0;for(let Y of K){if(Y.start{let X=indexedDB.open("pi-cache-meta",1);X.onupgradeneeded=()=>X.result.createObjectStore("kv"),X.onsuccess=()=>J(X.result),X.onerror=()=>Q(X.error)})}function ow(J){return Bq().then((Q)=>new Promise((X,K)=>{let Z=Q.transaction("kv","readonly").objectStore("kv").get(J);Z.onsuccess=()=>X(Z.result),Z.onerror=()=>K(Z.error)}))}function nw(J,Q){return Bq().then((X)=>new Promise((K,Z)=>{let H=X.transaction("kv","readwrite");H.objectStore("kv").put(Q,J),H.oncomplete=()=>K(),H.onerror=()=>Z(H.error)}))}async function eX(){let J=globalThis;if(!J.caches?.keys)return;for(let Q of await J.caches.keys()){let X=await J.caches.open(Q);for(let K of await X.keys())if(/\/config\.json(\?|$)/.test(K.url))await X.delete(K)}}async function sw(){try{if(!globalThis.indexedDB){await eX();return}if(await ow("epoch")===Oq)return;await eX(),await nw("epoch",Oq)}catch{try{await eX()}catch{}}}async function tw(J="q4",Q="webgpu"){let X=performance.now();zq=J,await sw();let K={device:Q,progress_callback:(Y)=>postMessage({type:"progress",...Y})};if(J==="mixed48")K.model_file_name="model_mixed48",K.dtype="fp32";else K.dtype=J;if(J!=="q4")K.session_options={enableCpuMemArena:!1,enableMemPattern:!1};y7=await Nq("token-classification",aw,K);let Z=G0.backends?.onnx?.webgpu?.device??null;postMessage({type:"ready",device:Q==="webgpu"?Z?"webgpu":"FALLBACK(wasm — env.webgpu.device unset)":Q,dtype:zq,loadMs:Math.round(performance.now()-X)})}async function ew(J,Q){if(!y7)throw Error("pipeline not loaded");let X=performance.now(),K=y7.tokenizer,Z=y7.model,H=Z.config.id2label,Y=K(Q),$=Y.input_ids.tolist()[0]??Y.input_ids.tolist(),W=(await Z(Y)).logits,[,q,F]=W.dims,N=W.data,j=[],B=0;for(let L=0;Lk)k=g,w=c}let C=0;for(let c=0;c{try{if(J.data.type==="load")await tw(J.data.dtype,J.data.device);else if(J.data.type==="analyze")await ew(J.data.id,J.data.text)}catch(Q){postMessage({type:"error",message:Q instanceof Error?Q.message:String(Q),fatal:J.data.type==="load"})}};