@fleox/agentphoto 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +177 -72
- package/changelog.json +18 -0
- package/dist/agent/agentphoto.mjs +64 -17
- package/dist/agent/chunks/{assets-CDQo3VqD.mjs → assets-BZVUUHjg.mjs} +3 -3
- package/dist/agent/chunks/{context-DoLoLF9f.mjs → context-CNpRboiC.mjs} +1 -1
- package/dist/agent/chunks/{doc-BjY_j4Su.mjs → doc-D_v_yE07.mjs} +25 -286
- package/dist/agent/chunks/{export-CLmpFART.mjs → export-aNJcPNbJ.mjs} +1 -1
- package/dist/agent/chunks/geometry-BKIhUO9x.mjs +315 -0
- package/dist/agent/chunks/{models-C4i_hicr.mjs → models-CxrjmA0W.mjs} +1 -1
- package/dist/agent/chunks/{package-DSmAxrla.mjs → package-Cu1GyvKL.mjs} +2 -2
- package/dist/agent/chunks/{project-CUykGysG.mjs → project-o1DH2nOw.mjs} +12 -10
- package/dist/agent/chunks/{templates--YGpGuHh.mjs → templates-BJ2me4XZ.mjs} +24 -3
- package/dist/agent/chunks/{tools-Dnh8g6F9.mjs → tools-DKaAPEV5.mjs} +92 -27
- package/dist/agent/chunks/{tree-DO7N0UDV.mjs → tree-D8qZKPAb.mjs} +2 -2
- package/dist/engine/agentphoto-engine.js +408 -352
- package/dist/studio/assets/index-CmOzzoXv.css +1 -0
- package/dist/studio/assets/index-D3Iw5q8v.js +28 -0
- package/dist/studio/assets/{transformers.web-DgnCIB_X.js → transformers.web-osEqoMhg.js} +1 -1
- package/dist/studio/index.html +2 -2
- package/dist/studio/templates/index.json +1 -1
- package/dist/studio/templates/product-white/photo.json +2 -2
- package/dist/studio/templates/product-white/preview.jpg +0 -0
- package/dist/studio/templates/product-white/template.json +1 -1
- package/package.json +2 -2
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/skills/agentphoto-cutout/SKILL.md +30 -25
- package/plugin/skills/agentphoto-design/SKILL.md +24 -24
- package/plugin/skills/agentphoto-publish/SKILL.md +10 -10
- package/plugin/skills/agentphoto-retouch/SKILL.md +26 -26
- package/plugin/skills/agentphoto-retouch/references/filters.md +1 -1
- package/plugin/skills/agentphoto-retouch/references/patch-ops.md +14 -13
- package/plugin/skills/agentphoto-retouch/references/recipes.md +3 -3
- package/templates/product-white/photo.json +2 -2
- package/templates/product-white/preview.jpg +0 -0
- package/templates/product-white/template.json +1 -1
- package/dist/studio/assets/index-Be8JnaFy.js +0 -28
- package/dist/studio/assets/index-DwPms2S5.css +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e,t}from"./index-Be8JnaFy.js";var n=t({InferenceSession:()=>je,TRACE:()=>Se,TRACE_EVENT_BEGIN:()=>Ee,TRACE_EVENT_END:()=>De,TRACE_FUNC_BEGIN:()=>we,TRACE_FUNC_END:()=>Te,Tensor:()=>be,default:()=>nr,env:()=>w,registerBackend:()=>m}),r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(t=>typeof e<`u`?e:typeof Proxy<`u`?new Proxy(t,{get:(t,n)=>(typeof e<`u`?e:t)[n]}):t)(function(t){if(typeof e<`u`)return e.apply(this,arguments);throw Error(`Dynamic require of "`+t+`" is not supported`)}),c=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},l=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},u=(e,t,n,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},d=e=>u(r({},`__esModule`,{value:!0}),e),f,p,m,h,g,_=c(()=>{f=new Map,p=[],m=(e,t,n)=>{if(t&&typeof t.init==`function`&&typeof t.createInferenceSessionHandler==`function`){let r=f.get(e);if(r===void 0)f.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let t=p.indexOf(e);t!==-1&&p.splice(t,1);for(let t=0;t<p.length;t++)if(f.get(p[t]).priority<=n){p.splice(t,0,e);return}p.push(e)}}else throw TypeError(`not a valid backend`)},h=async e=>{let t=f.get(e);if(!t)return`backend not found.`;if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},g=async e=>{let t=e.executionProviders||[],n=t.map(e=>typeof e==`string`?e:e.name),r=n.length===0?p:n,i,a=[],o=new Set;for(let e of r){let t=await h(e);typeof t==`string`?a.push({name:e,err:t}):(i||=t,i===t&&o.add(e))}if(!i)throw Error(`no available backend found. ERR: ${a.map(e=>`[${e.name}] ${e.err}`).join(`, `)}`);for(let{name:e,err:t}of a)n.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);let s=t.filter(e=>o.has(typeof e==`string`?e:e.name));return[i,new Proxy(e,{get:(e,t)=>t===`executionProviders`?s:Reflect.get(e,t)})]}}),v=c(()=>{_()}),y,b=c(()=>{y=`1.31.0-dev.20260911-2a43ec07e`}),x,S,C=c(()=>{b(),x=`warning`,S={wasm:{},webgl:{},webgpu:{},versions:{common:y},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);x=e}},get logLevel(){return x}},Object.defineProperty(S,"logLevel",{enumerable:!0})}),w,ee=c(()=>{C(),w=S}),te,ne,re=c(()=>{te=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t<a;t++)for(let n=0;n<i;n++){let i=(e.data[d++]-l[0])*c[0],a=(e.data[f++]-l[1])*c[1],o=(e.data[p++]-l[2])*c[2],s=m===-1?255:(e.data[m++]-l[3])*c[3];r.fillStyle=`rgba(`+i+`,`+a+`,`+o+`,`+s+`)`,r.fillRect(n,t,1,1)}if(`toDataURL`in n)return n.toDataURL();throw Error(`toDataURL is not supported`)}throw Error(`Can not access image data`)},ne=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t!==void 0&&t.format!==void 0?t.format:`RGB`,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t<a*i;f+=4,p+=4,m+=4,h+=4,t++)r.data[f]=(e.data[g++]-u[0])*l[0],r.data[p]=(e.data[_++]-u[1])*l[1],r.data[m]=(e.data[v++]-u[2])*l[2],r.data[h]=y===-1?255:(e.data[y++]-u[3])*l[3]}else throw Error(`Can not access image data`);return r}}),ie,ae,oe,se,ce,le,ue=c(()=>{ye(),ie=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:`RGB`,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t<l;t++,f+=d,m+=d,p+=d,h+=d)u[g++]=(e[f]+o[0])/a[0],u[_++]=(e[p]+o[1])/a[1],u[v++]=(e[m]+o[2])/a[2],y!==-1&&h!==-1&&(u[y++]=(e[h]+o[3])/a[3]);return c===`RGBA`?new ve(`float32`,u,[1,4,n,r]):new ve(`float32`,u,[1,3,n,r])},ae=async(e,t)=>{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,ie(o,s)}throw Error(`Can not access image data`)}else{if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(ie(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return ie(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},oe=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new ve({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},se=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new ve({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},ce=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new ve({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},le=(e,t,n)=>new ve({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),T,de,fe,pe,me=c(()=>{T=new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),de=new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),fe=!1,pe=()=>{if(!fe){fe=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(T.set(`int64`,BigInt64Array),de.set(BigInt64Array,`int64`)),t&&(T.set(`uint64`,BigUint64Array),de.set(BigUint64Array,`uint64`)),r?(T.set(`float16`,n),de.set(n,`float16`)):T.set(`float16`,Uint16Array)}}}),he,ge,_e=c(()=>{ye(),he=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},ge=(e,t)=>{switch(e.location){case`cpu`:return new ve(e.type,e.data,t);case`cpu-pinned`:return new ve({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new ve({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new ve({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new ve({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),ve,ye=c(()=>{re(),ue(),me(),_e(),ve=class{constructor(e,t,n){pe();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=T.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`){if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=T.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray){if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`)}else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=de.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=he(i);if(this.cpuData&&a!==this.cpuData.length&&(r!==`uint4`&&r!==`int4`||Math.ceil(a/2)!==this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return ae(e,t)}static fromTexture(e,t){return oe(e,t)}static fromGpuBuffer(e,t){return se(e,t)}static fromMLTensor(e,t){return ce(e,t)}static fromPinnedBuffer(e,t,n){return le(e,t,n)}toDataURL(e){return te(this,e)}toImageData(e){return ne(this,e)}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(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw 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 t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);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(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return ge(this,e)}}}),be,xe=c(()=>{ye(),be=ve}),Se,Ce,we,Te,Ee,De,Oe=c(()=>{C(),Se=(e,t)=>{(typeof S.trace>`u`?!S.wasm.trace:!S.trace)||console.timeStamp(`${e}::ORT::${t}`)},Ce=(e,t)=>{let n=Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i<n.length;i++){if(r&&!n[i].includes(`TRACE_FUNC`)){let r=`FUNC_${e}::${n[i].trim().split(` `)[1]}`;t&&(r+=`::${t}`),Se(`CPU`,r);return}n[i].includes(`TRACE_FUNC`)&&(r=!0)}},we=e=>{(typeof S.trace>`u`?!S.wasm.trace:!S.trace)||Ce(`BEGIN`,e)},Te=e=>{(typeof S.trace>`u`?!S.wasm.trace:!S.trace)||Ce(`END`,e)},Ee=e=>{(typeof S.trace>`u`?!S.wasm.trace:!S.trace)||console.time(`ORT::${e}`)},De=e=>{(typeof S.trace>`u`?!S.wasm.trace:!S.trace)||console.timeEnd(`ORT::${e}`)}}),ke,Ae=c(()=>{_(),xe(),Oe(),ke=class e{constructor(e){this.handler=e}async run(e,t,n){we(),Ee(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof be||Array.isArray(e))throw TypeError(`'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.`);let a=!0;if(typeof t==`object`){if(t===null)throw TypeError(`Unexpected argument[1]: cannot be null.`);if(t instanceof be)throw TypeError(`'fetches' cannot be a Tensor`);if(Array.isArray(t)){if(t.length===0)throw TypeError(`'fetches' cannot be an empty array.`);a=!1;for(let e of t){if(typeof e!=`string`)throw TypeError(`'fetches' must be a string array or an object.`);if(this.outputNames.indexOf(e)===-1)throw RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else{let e=!1,o=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(o.indexOf(n)!==-1){let i=t[n];(i===null||i instanceof be)&&(e=!0,a=!1,r[n]=i)}if(e){if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else i=t}}else if(typeof t<`u`)throw TypeError(`Unexpected argument[1]: must be 'fetches' or 'options'.`);for(let t of this.inputNames)if(typeof e[t]>`u`)throw Error(`input '${t}' is missing in 'feeds'.`);if(a)for(let e of this.outputNames)r[e]=null;let o=await this.handler.run(e,r,i),s={};for(let e in o)if(Object.hasOwnProperty.call(o,e)){let t=o[e];s[e]=t instanceof be?t:new be(t.type,t.data,t.dims)}return De(`InferenceSession.run`),Te(),s}async release(){return this.handler.dispose()}static async create(t,n,r,i){we(),Ee(`InferenceSession.create`);let a,o={};if(typeof t==`string`){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof Uint8Array){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer){let e=t,s=0,c=t.byteLength;if(typeof n==`object`&&n)o=n;else if(typeof n==`number`){if(s=n,!Number.isSafeInteger(s))throw RangeError(`'byteOffset' must be an integer.`);if(s<0||s>=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(c=t.byteLength-s,typeof r==`number`){if(c=r,!Number.isSafeInteger(c))throw RangeError(`'byteLength' must be an integer.`);if(c<=0||s+c>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if(typeof i==`object`&&i)o=i;else if(typeof i<`u`)throw TypeError(`'options' must be an object.`)}else if(typeof r<`u`)throw TypeError(`'byteLength' must be a number.`)}else if(typeof n<`u`)throw TypeError(`'options' must be an object.`);a=new Uint8Array(e,s,c)}else throw TypeError(`Unexpected argument[0]: must be 'path' or 'buffer'.`);let[s,c]=await g(o),l=await s.createInferenceSessionHandler(a,c);return De(`InferenceSession.create`),Te(),new e(l)}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}}}),je,Me=c(()=>{Ae(),je=ke}),Ne=c(()=>{}),Pe=c(()=>{}),Fe=c(()=>{}),Ie=c(()=>{}),Le={};l(Le,{InferenceSession:()=>je,TRACE:()=>Se,TRACE_EVENT_BEGIN:()=>Ee,TRACE_EVENT_END:()=>De,TRACE_FUNC_BEGIN:()=>we,TRACE_FUNC_END:()=>Te,Tensor:()=>be,env:()=>w,registerBackend:()=>m});var Re=c(()=>{v(),ee(),Me(),xe(),Ne(),Pe(),Oe(),Fe(),Ie()}),ze=c(()=>{}),Be={};l(Be,{default:()=>Ue});var Ve,He,Ue,We=c(()=>{En(),mt(),at(),Ve=`ort-wasm-proxy-worker`,He=globalThis.self?.name===Ve,He&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:pt(n.wasm).then(()=>{mn(n).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})})},e=>{postMessage({type:t,err:e})});break;case`init-ep`:{let{epName:e,env:r}=n;hn(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=yn(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;bn(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:xn(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;Cn(e,r,i,a,Array(a.length).fill(null),o).then(e=>{e.some(e=>e[3]!==`cpu`)?postMessage({type:t,err:`Proxy does not support non-cpu tensor location.`}):postMessage({type:t,out:e},Tn([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:wn(n),postMessage({type:t})}}catch(e){postMessage({type:t,err:e})}}),Ue=He?null:e=>new Worker(e??Je,{type:`module`,name:Ve})}),Ge,Ke,qe,Je,Ye,Xe,Ze,Qe,$e,et,tt,nt,rt,it,at=c(()=>{ze(),Ge=typeof location>`u`?void 0:location.origin,Ke=import.meta.url>`file:`&&import.meta.url<`file;`,qe=()=>Ke?new URL(new URL(`ort.webgpu.min.mjs`,import.meta.url).href,Ge).href:import.meta.url,Je=qe(),Ye=()=>{if(Je&&!Je.startsWith(`blob:`))return Je.substring(0,Je.lastIndexOf(`/`)+1)},Xe=(e,t)=>{try{let n=t??Je;return(n?new URL(e,n):new URL(e)).origin===Ge}catch{return!1}},Ze=(e,t)=>{let n=t??Je;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},Qe=(e,t)=>`${t??`./`}${e}`,$e=async e=>{let t=await(await fetch(e,{credentials:`same-origin`})).blob();return URL.createObjectURL(t)},et=async e=>(await import(e)).default,tt=(We(),d(Be)).default,nt=async()=>{if(!Je)throw Error(`Failed to load proxy worker: cannot determine the script source URL.`);if(Xe(Je))return[void 0,tt()];let e=await $e(Je);return[e,tt(e)]},rt=void 0,it=async(e,t,n,r)=>{let i=rt&&!(e||t);if(i){if(Je)i=Xe(Je)||r&&!n;else if(r&&!n)i=!0;else throw Error(`cannot determine the script source URL.`)}if(i)return[void 0,rt];{let r=`ort-wasm-simd-threaded.asyncify.mjs`,i=e??Ze(r,t),a=n&&i&&!Xe(i,t),o=a?await $e(i):i??Qe(r,t);return[a?o:void 0,await et(o)]}}}),ot,st,ct,lt,ut,dt,ft,pt,E,mt=c(()=>{at(),st=!1,ct=!1,lt=!1,ut=()=>{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}},dt=()=>{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}},ft=()=>{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}},pt=async e=>{if(st)return Promise.resolve();if(ct)throw Error(`multiple calls to 'initializeWebAssembly()' detected.`);if(lt)throw Error(`previous call to 'initializeWebAssembly()' failed.`);ct=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd===`relaxed`){if(!ft())throw Error(`Relaxed WebAssembly SIMD is not supported in the current environment.`)}else if(!dt())throw Error(`WebAssembly SIMD is not supported in the current environment.`)}let r=ut();n>1&&!r&&(typeof self<`u`&&!self.crossOriginIsolated&&console.warn(`env.wasm.numThreads is set to `+n+`, but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info.`),console.warn(`WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading.`),e.numThreads=n=1);let i=e.wasmPaths,a=typeof i==`string`?i:void 0,o=i?.mjs,s=o?.href??o,c=i?.wasm,l=c?.href??c,u=e.wasmBinary,[d,f]=await it(s,a,n>1,!!u||!!l),p=!1,m=[];if(t>0&&m.push(new Promise(e=>{setTimeout(()=>{p=!0,e()},t)})),m.push(new Promise((e,t)=>{let r={numThreads:n};if(u)r.wasmBinary=u,r.locateFile=e=>e;else if(l||a)r.locateFile=e=>l??a+e;else if(s&&s.indexOf(`blob:`)!==0)r.locateFile=e=>new URL(e,s).href;else if(d){let e=Ye();e&&(r.locateFile=t=>e+t)}f(r).then(t=>{ct=!1,st=!0,ot=t,e(),d&&URL.revokeObjectURL(d)},e=>{ct=!1,lt=!0,t(e)})})),await Promise.race(m),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},E=()=>{if(st&&ot)return ot;throw Error(`WebAssembly is not initialized yet.`)}}),ht,gt,D,_t=c(()=>{mt(),ht=(e,t)=>{let n=E(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},gt=(e,t,n,r)=>{if(typeof e==`object`&&e){if(n.has(e))throw Error(`Circular reference in options`);n.add(e)}Object.entries(e).forEach(([e,i])=>{let a=t?t+e:e;if(typeof i==`object`)gt(i,a+`.`,n,r);else if(typeof i==`string`||typeof i==`number`)r(a,i.toString());else if(typeof i==`boolean`)r(a,i?`1`:`0`);else throw Error(`Can't handle extra config type: ${typeof i}`)})},D=e=>{let t=E(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetLastError(r,r+n);let i=Number(t.getValue(r,n===4?`i32`:`i64`)),a=t.getValue(r+n,`*`),o=a?t.UTF8ToString(a):``;throw Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${o}`)}finally{t.stackRestore(n)}}}),vt,yt=c(()=>{mt(),_t(),vt=e=>{let t=E(),n=0,r=[],i=e||{};try{if(e?.logSeverityLevel===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!=`number`||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!=`number`||!Number.isInteger(e.logVerbosityLevel))throw Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(i.terminate=!1);let a=0;return e?.tag!==void 0&&(a=ht(e.tag,r)),n=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),n===0&&D(`Can't create run options.`),e?.extra!==void 0&>(e.extra,``,new WeakSet,(e,i)=>{let a=ht(e,r),o=ht(i,r);t._OrtAddRunConfigEntry(n,a,o)!==0&&D(`Can't set a run config entry: ${e} - ${i}.`)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseRunOptions(n),r.forEach(e=>t._free(e)),e}}}),bt,xt,St,Ct,wt,Tt,Et,Dt=c(()=>{mt(),_t(),bt=e=>{switch(e){case`disabled`:return 0;case`basic`:return 1;case`extended`:return 2;case`layout`:return 3;case`all`:return 99;default:throw Error(`unsupported graph optimization level: ${e}`)}},xt=e=>{switch(e){case`sequential`:return 0;case`parallel`:return 1;default:throw Error(`unsupported execution mode: ${e}`)}},St=e=>{e.extra||={},e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||=`1`,e.executionProviders&&e.executionProviders.some(e=>(typeof e==`string`?e:e.name)===`webgpu`)&&(e.enableMemPattern=!1)},Ct=(e,t,n,r)=>{let i=ht(t,r),a=ht(n,r);E()._OrtAddSessionConfigEntry(e,i,a)!==0&&D(`Can't set a session config entry: ${t} - ${n}.`)},wt=(e,t,n,r)=>{let i=ht(t,r),a=ht(n,r);e.push([i,a])},Tt=async(e,t,n)=>{let r=t.executionProviders;for(let i of r){let r=typeof i==`string`?i:i.name,a=[];switch(r){case`webnn`:if(r=`WEBNN`,Ct(e,`session.disable_quant_qdq`,`1`,n),Ct(e,`session.disable_qdq_constant_folding`,`1`,n),typeof i!=`string`){let t=i?.deviceType;t&&Ct(e,`deviceType`,t,n)}break;case`webgpu`:{r=`WebGPU`;let e;if(typeof i!=`string`){let r=i;if(r.device){if(typeof GPUDevice<`u`&&r.device instanceof GPUDevice)e=r.device;else throw Error(`Invalid GPU device set in WebGPU EP options.`)}let{enableGraphCapture:o}=t;if(typeof o==`boolean`&&o&&wt(a,`enableGraphCapture`,`1`,n),typeof r.preferredLayout==`string`&&wt(a,`preferredLayout`,r.preferredLayout,n),r.forceCpuNodeNames){let e=Array.isArray(r.forceCpuNodeNames)?r.forceCpuNodeNames:[r.forceCpuNodeNames];wt(a,`forceCpuNodeNames`,e.join(`
|
|
1
|
+
import{n as e,t}from"./index-D3Iw5q8v.js";var n=t({InferenceSession:()=>je,TRACE:()=>Se,TRACE_EVENT_BEGIN:()=>Ee,TRACE_EVENT_END:()=>De,TRACE_FUNC_BEGIN:()=>we,TRACE_FUNC_END:()=>Te,Tensor:()=>be,default:()=>nr,env:()=>w,registerBackend:()=>m}),r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,s=(t=>typeof e<`u`?e:typeof Proxy<`u`?new Proxy(t,{get:(t,n)=>(typeof e<`u`?e:t)[n]}):t)(function(t){if(typeof e<`u`)return e.apply(this,arguments);throw Error(`Dynamic require of "`+t+`" is not supported`)}),c=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},l=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},u=(e,t,n,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of a(t))!o.call(e,c)&&c!==n&&r(e,c,{get:()=>t[c],enumerable:!(s=i(t,c))||s.enumerable});return e},d=e=>u(r({},`__esModule`,{value:!0}),e),f,p,m,h,g,_=c(()=>{f=new Map,p=[],m=(e,t,n)=>{if(t&&typeof t.init==`function`&&typeof t.createInferenceSessionHandler==`function`){let r=f.get(e);if(r===void 0)f.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let t=p.indexOf(e);t!==-1&&p.splice(t,1);for(let t=0;t<p.length;t++)if(f.get(p[t]).priority<=n){p.splice(t,0,e);return}p.push(e)}}else throw TypeError(`not a valid backend`)},h=async e=>{let t=f.get(e);if(!t)return`backend not found.`;if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},g=async e=>{let t=e.executionProviders||[],n=t.map(e=>typeof e==`string`?e:e.name),r=n.length===0?p:n,i,a=[],o=new Set;for(let e of r){let t=await h(e);typeof t==`string`?a.push({name:e,err:t}):(i||=t,i===t&&o.add(e))}if(!i)throw Error(`no available backend found. ERR: ${a.map(e=>`[${e.name}] ${e.err}`).join(`, `)}`);for(let{name:e,err:t}of a)n.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);let s=t.filter(e=>o.has(typeof e==`string`?e:e.name));return[i,new Proxy(e,{get:(e,t)=>t===`executionProviders`?s:Reflect.get(e,t)})]}}),v=c(()=>{_()}),y,b=c(()=>{y=`1.31.0-dev.20260911-2a43ec07e`}),x,S,C=c(()=>{b(),x=`warning`,S={wasm:{},webgl:{},webgpu:{},versions:{common:y},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);x=e}},get logLevel(){return x}},Object.defineProperty(S,"logLevel",{enumerable:!0})}),w,ee=c(()=>{C(),w=S}),te,ne,re=c(()=>{te=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t<a;t++)for(let n=0;n<i;n++){let i=(e.data[d++]-l[0])*c[0],a=(e.data[f++]-l[1])*c[1],o=(e.data[p++]-l[2])*c[2],s=m===-1?255:(e.data[m++]-l[3])*c[3];r.fillStyle=`rgba(`+i+`,`+a+`,`+o+`,`+s+`)`,r.fillRect(n,t,1,1)}if(`toDataURL`in n)return n.toDataURL();throw Error(`toDataURL is not supported`)}throw Error(`Can not access image data`)},ne=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t!==void 0&&t.format!==void 0?t.format:`RGB`,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t<a*i;f+=4,p+=4,m+=4,h+=4,t++)r.data[f]=(e.data[g++]-u[0])*l[0],r.data[p]=(e.data[_++]-u[1])*l[1],r.data[m]=(e.data[v++]-u[2])*l[2],r.data[h]=y===-1?255:(e.data[y++]-u[3])*l[3]}else throw Error(`Can not access image data`);return r}}),ie,ae,oe,se,ce,le,ue=c(()=>{ye(),ie=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:`RGB`,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t<l;t++,f+=d,m+=d,p+=d,h+=d)u[g++]=(e[f]+o[0])/a[0],u[_++]=(e[p]+o[1])/a[1],u[v++]=(e[m]+o[2])/a[2],y!==-1&&h!==-1&&(u[y++]=(e[h]+o[3])/a[3]);return c===`RGBA`?new ve(`float32`,u,[1,4,n,r]):new ve(`float32`,u,[1,3,n,r])},ae=async(e,t)=>{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,ie(o,s)}throw Error(`Can not access image data`)}else{if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(ie(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return ie(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},oe=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new ve({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},se=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new ve({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},ce=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new ve({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},le=(e,t,n)=>new ve({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),T,de,fe,pe,me=c(()=>{T=new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),de=new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),fe=!1,pe=()=>{if(!fe){fe=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(T.set(`int64`,BigInt64Array),de.set(BigInt64Array,`int64`)),t&&(T.set(`uint64`,BigUint64Array),de.set(BigUint64Array,`uint64`)),r?(T.set(`float16`,n),de.set(n,`float16`)):T.set(`float16`,Uint16Array)}}}),he,ge,_e=c(()=>{ye(),he=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},ge=(e,t)=>{switch(e.location){case`cpu`:return new ve(e.type,e.data,t);case`cpu-pinned`:return new ve({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new ve({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new ve({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new ve({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),ve,ye=c(()=>{re(),ue(),me(),_e(),ve=class{constructor(e,t,n){pe();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=T.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`){if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=T.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray){if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`)}else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=de.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=he(i);if(this.cpuData&&a!==this.cpuData.length&&(r!==`uint4`&&r!==`int4`||Math.ceil(a/2)!==this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return ae(e,t)}static fromTexture(e,t){return oe(e,t)}static fromGpuBuffer(e,t){return se(e,t)}static fromMLTensor(e,t){return ce(e,t)}static fromPinnedBuffer(e,t,n){return le(e,t,n)}toDataURL(e){return te(this,e)}toImageData(e){return ne(this,e)}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(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw 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 t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);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(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return ge(this,e)}}}),be,xe=c(()=>{ye(),be=ve}),Se,Ce,we,Te,Ee,De,Oe=c(()=>{C(),Se=(e,t)=>{(typeof S.trace>`u`?!S.wasm.trace:!S.trace)||console.timeStamp(`${e}::ORT::${t}`)},Ce=(e,t)=>{let n=Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i<n.length;i++){if(r&&!n[i].includes(`TRACE_FUNC`)){let r=`FUNC_${e}::${n[i].trim().split(` `)[1]}`;t&&(r+=`::${t}`),Se(`CPU`,r);return}n[i].includes(`TRACE_FUNC`)&&(r=!0)}},we=e=>{(typeof S.trace>`u`?!S.wasm.trace:!S.trace)||Ce(`BEGIN`,e)},Te=e=>{(typeof S.trace>`u`?!S.wasm.trace:!S.trace)||Ce(`END`,e)},Ee=e=>{(typeof S.trace>`u`?!S.wasm.trace:!S.trace)||console.time(`ORT::${e}`)},De=e=>{(typeof S.trace>`u`?!S.wasm.trace:!S.trace)||console.timeEnd(`ORT::${e}`)}}),ke,Ae=c(()=>{_(),xe(),Oe(),ke=class e{constructor(e){this.handler=e}async run(e,t,n){we(),Ee(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof be||Array.isArray(e))throw TypeError(`'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.`);let a=!0;if(typeof t==`object`){if(t===null)throw TypeError(`Unexpected argument[1]: cannot be null.`);if(t instanceof be)throw TypeError(`'fetches' cannot be a Tensor`);if(Array.isArray(t)){if(t.length===0)throw TypeError(`'fetches' cannot be an empty array.`);a=!1;for(let e of t){if(typeof e!=`string`)throw TypeError(`'fetches' must be a string array or an object.`);if(this.outputNames.indexOf(e)===-1)throw RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else{let e=!1,o=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(o.indexOf(n)!==-1){let i=t[n];(i===null||i instanceof be)&&(e=!0,a=!1,r[n]=i)}if(e){if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else i=t}}else if(typeof t<`u`)throw TypeError(`Unexpected argument[1]: must be 'fetches' or 'options'.`);for(let t of this.inputNames)if(typeof e[t]>`u`)throw Error(`input '${t}' is missing in 'feeds'.`);if(a)for(let e of this.outputNames)r[e]=null;let o=await this.handler.run(e,r,i),s={};for(let e in o)if(Object.hasOwnProperty.call(o,e)){let t=o[e];s[e]=t instanceof be?t:new be(t.type,t.data,t.dims)}return De(`InferenceSession.run`),Te(),s}async release(){return this.handler.dispose()}static async create(t,n,r,i){we(),Ee(`InferenceSession.create`);let a,o={};if(typeof t==`string`){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof Uint8Array){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer){let e=t,s=0,c=t.byteLength;if(typeof n==`object`&&n)o=n;else if(typeof n==`number`){if(s=n,!Number.isSafeInteger(s))throw RangeError(`'byteOffset' must be an integer.`);if(s<0||s>=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(c=t.byteLength-s,typeof r==`number`){if(c=r,!Number.isSafeInteger(c))throw RangeError(`'byteLength' must be an integer.`);if(c<=0||s+c>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if(typeof i==`object`&&i)o=i;else if(typeof i<`u`)throw TypeError(`'options' must be an object.`)}else if(typeof r<`u`)throw TypeError(`'byteLength' must be a number.`)}else if(typeof n<`u`)throw TypeError(`'options' must be an object.`);a=new Uint8Array(e,s,c)}else throw TypeError(`Unexpected argument[0]: must be 'path' or 'buffer'.`);let[s,c]=await g(o),l=await s.createInferenceSessionHandler(a,c);return De(`InferenceSession.create`),Te(),new e(l)}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}}}),je,Me=c(()=>{Ae(),je=ke}),Ne=c(()=>{}),Pe=c(()=>{}),Fe=c(()=>{}),Ie=c(()=>{}),Le={};l(Le,{InferenceSession:()=>je,TRACE:()=>Se,TRACE_EVENT_BEGIN:()=>Ee,TRACE_EVENT_END:()=>De,TRACE_FUNC_BEGIN:()=>we,TRACE_FUNC_END:()=>Te,Tensor:()=>be,env:()=>w,registerBackend:()=>m});var Re=c(()=>{v(),ee(),Me(),xe(),Ne(),Pe(),Oe(),Fe(),Ie()}),ze=c(()=>{}),Be={};l(Be,{default:()=>Ue});var Ve,He,Ue,We=c(()=>{En(),mt(),at(),Ve=`ort-wasm-proxy-worker`,He=globalThis.self?.name===Ve,He&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:pt(n.wasm).then(()=>{mn(n).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})})},e=>{postMessage({type:t,err:e})});break;case`init-ep`:{let{epName:e,env:r}=n;hn(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=yn(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;bn(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:xn(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;Cn(e,r,i,a,Array(a.length).fill(null),o).then(e=>{e.some(e=>e[3]!==`cpu`)?postMessage({type:t,err:`Proxy does not support non-cpu tensor location.`}):postMessage({type:t,out:e},Tn([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:wn(n),postMessage({type:t})}}catch(e){postMessage({type:t,err:e})}}),Ue=He?null:e=>new Worker(e??Je,{type:`module`,name:Ve})}),Ge,Ke,qe,Je,Ye,Xe,Ze,Qe,$e,et,tt,nt,rt,it,at=c(()=>{ze(),Ge=typeof location>`u`?void 0:location.origin,Ke=import.meta.url>`file:`&&import.meta.url<`file;`,qe=()=>Ke?new URL(new URL(`ort.webgpu.min.mjs`,import.meta.url).href,Ge).href:import.meta.url,Je=qe(),Ye=()=>{if(Je&&!Je.startsWith(`blob:`))return Je.substring(0,Je.lastIndexOf(`/`)+1)},Xe=(e,t)=>{try{let n=t??Je;return(n?new URL(e,n):new URL(e)).origin===Ge}catch{return!1}},Ze=(e,t)=>{let n=t??Je;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},Qe=(e,t)=>`${t??`./`}${e}`,$e=async e=>{let t=await(await fetch(e,{credentials:`same-origin`})).blob();return URL.createObjectURL(t)},et=async e=>(await import(e)).default,tt=(We(),d(Be)).default,nt=async()=>{if(!Je)throw Error(`Failed to load proxy worker: cannot determine the script source URL.`);if(Xe(Je))return[void 0,tt()];let e=await $e(Je);return[e,tt(e)]},rt=void 0,it=async(e,t,n,r)=>{let i=rt&&!(e||t);if(i){if(Je)i=Xe(Je)||r&&!n;else if(r&&!n)i=!0;else throw Error(`cannot determine the script source URL.`)}if(i)return[void 0,rt];{let r=`ort-wasm-simd-threaded.asyncify.mjs`,i=e??Ze(r,t),a=n&&i&&!Xe(i,t),o=a?await $e(i):i??Qe(r,t);return[a?o:void 0,await et(o)]}}}),ot,st,ct,lt,ut,dt,ft,pt,E,mt=c(()=>{at(),st=!1,ct=!1,lt=!1,ut=()=>{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}},dt=()=>{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}},ft=()=>{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}},pt=async e=>{if(st)return Promise.resolve();if(ct)throw Error(`multiple calls to 'initializeWebAssembly()' detected.`);if(lt)throw Error(`previous call to 'initializeWebAssembly()' failed.`);ct=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd===`relaxed`){if(!ft())throw Error(`Relaxed WebAssembly SIMD is not supported in the current environment.`)}else if(!dt())throw Error(`WebAssembly SIMD is not supported in the current environment.`)}let r=ut();n>1&&!r&&(typeof self<`u`&&!self.crossOriginIsolated&&console.warn(`env.wasm.numThreads is set to `+n+`, but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info.`),console.warn(`WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading.`),e.numThreads=n=1);let i=e.wasmPaths,a=typeof i==`string`?i:void 0,o=i?.mjs,s=o?.href??o,c=i?.wasm,l=c?.href??c,u=e.wasmBinary,[d,f]=await it(s,a,n>1,!!u||!!l),p=!1,m=[];if(t>0&&m.push(new Promise(e=>{setTimeout(()=>{p=!0,e()},t)})),m.push(new Promise((e,t)=>{let r={numThreads:n};if(u)r.wasmBinary=u,r.locateFile=e=>e;else if(l||a)r.locateFile=e=>l??a+e;else if(s&&s.indexOf(`blob:`)!==0)r.locateFile=e=>new URL(e,s).href;else if(d){let e=Ye();e&&(r.locateFile=t=>e+t)}f(r).then(t=>{ct=!1,st=!0,ot=t,e(),d&&URL.revokeObjectURL(d)},e=>{ct=!1,lt=!0,t(e)})})),await Promise.race(m),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},E=()=>{if(st&&ot)return ot;throw Error(`WebAssembly is not initialized yet.`)}}),ht,gt,D,_t=c(()=>{mt(),ht=(e,t)=>{let n=E(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},gt=(e,t,n,r)=>{if(typeof e==`object`&&e){if(n.has(e))throw Error(`Circular reference in options`);n.add(e)}Object.entries(e).forEach(([e,i])=>{let a=t?t+e:e;if(typeof i==`object`)gt(i,a+`.`,n,r);else if(typeof i==`string`||typeof i==`number`)r(a,i.toString());else if(typeof i==`boolean`)r(a,i?`1`:`0`);else throw Error(`Can't handle extra config type: ${typeof i}`)})},D=e=>{let t=E(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetLastError(r,r+n);let i=Number(t.getValue(r,n===4?`i32`:`i64`)),a=t.getValue(r+n,`*`),o=a?t.UTF8ToString(a):``;throw Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${o}`)}finally{t.stackRestore(n)}}}),vt,yt=c(()=>{mt(),_t(),vt=e=>{let t=E(),n=0,r=[],i=e||{};try{if(e?.logSeverityLevel===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!=`number`||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!=`number`||!Number.isInteger(e.logVerbosityLevel))throw Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(i.terminate=!1);let a=0;return e?.tag!==void 0&&(a=ht(e.tag,r)),n=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),n===0&&D(`Can't create run options.`),e?.extra!==void 0&>(e.extra,``,new WeakSet,(e,i)=>{let a=ht(e,r),o=ht(i,r);t._OrtAddRunConfigEntry(n,a,o)!==0&&D(`Can't set a run config entry: ${e} - ${i}.`)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseRunOptions(n),r.forEach(e=>t._free(e)),e}}}),bt,xt,St,Ct,wt,Tt,Et,Dt=c(()=>{mt(),_t(),bt=e=>{switch(e){case`disabled`:return 0;case`basic`:return 1;case`extended`:return 2;case`layout`:return 3;case`all`:return 99;default:throw Error(`unsupported graph optimization level: ${e}`)}},xt=e=>{switch(e){case`sequential`:return 0;case`parallel`:return 1;default:throw Error(`unsupported execution mode: ${e}`)}},St=e=>{e.extra||={},e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||=`1`,e.executionProviders&&e.executionProviders.some(e=>(typeof e==`string`?e:e.name)===`webgpu`)&&(e.enableMemPattern=!1)},Ct=(e,t,n,r)=>{let i=ht(t,r),a=ht(n,r);E()._OrtAddSessionConfigEntry(e,i,a)!==0&&D(`Can't set a session config entry: ${t} - ${n}.`)},wt=(e,t,n,r)=>{let i=ht(t,r),a=ht(n,r);e.push([i,a])},Tt=async(e,t,n)=>{let r=t.executionProviders;for(let i of r){let r=typeof i==`string`?i:i.name,a=[];switch(r){case`webnn`:if(r=`WEBNN`,Ct(e,`session.disable_quant_qdq`,`1`,n),Ct(e,`session.disable_qdq_constant_folding`,`1`,n),typeof i!=`string`){let t=i?.deviceType;t&&Ct(e,`deviceType`,t,n)}break;case`webgpu`:{r=`WebGPU`;let e;if(typeof i!=`string`){let r=i;if(r.device){if(typeof GPUDevice<`u`&&r.device instanceof GPUDevice)e=r.device;else throw Error(`Invalid GPU device set in WebGPU EP options.`)}let{enableGraphCapture:o}=t;if(typeof o==`boolean`&&o&&wt(a,`enableGraphCapture`,`1`,n),typeof r.preferredLayout==`string`&&wt(a,`preferredLayout`,r.preferredLayout,n),r.forceCpuNodeNames){let e=Array.isArray(r.forceCpuNodeNames)?r.forceCpuNodeNames:[r.forceCpuNodeNames];wt(a,`forceCpuNodeNames`,e.join(`
|
|
2
2
|
`),n)}r.validationMode&&wt(a,`validationMode`,r.validationMode,n),typeof r.enableMatmulFp32Accumulation==`boolean`&&wt(a,`enableMatmulFp32Accumulation`,r.enableMatmulFp32Accumulation?`1`:`0`,n);for(let e of[`storageBufferCacheMode`,`uniformBufferCacheMode`,`queryResolveBufferCacheMode`,`defaultBufferCacheMode`]){let t=r[e];if(t){if(t!==`disabled`&&t!==`lazyRelease`&&t!==`simple`&&t!==`bucket`)throw Error(`${e} must be one of 'disabled', 'lazyRelease', 'simple' or 'bucket': ${t}`);wt(a,e,t,n)}}}let o=E().webgpuRegisterDevice(e);if(o){let[e,t,r]=o;wt(a,`deviceId`,e.toString(),n),wt(a,`webgpuInstance`,t.toString(),n),wt(a,`webgpuDevice`,r.toString(),n)}}break;case`wasm`:case`cpu`:continue;default:throw Error(`not supported execution provider: ${r}`)}let o=ht(r,n),s=a.length,c=0,l=0;if(s>0){c=E()._malloc(s*E().PTR_SIZE),n.push(c),l=E()._malloc(s*E().PTR_SIZE),n.push(l);for(let e=0;e<s;e++)E().setValue(c+e*E().PTR_SIZE,a[e][0],`*`),E().setValue(l+e*E().PTR_SIZE,a[e][1],`*`)}await E()._OrtAppendExecutionProvider(e,o,c,l,s)!==0&&D(`Can't append execution provider: ${r}.`)}},Et=async e=>{let t=E(),n=0,r=[],i=e||{};St(i);try{let e=bt(i.graphOptimizationLevel??`all`),a=xt(i.executionMode??`sequential`),o=typeof i.logId==`string`?ht(i.logId,r):0,s=i.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw Error(`log severity level is not valid: ${s}`);let c=i.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw Error(`log verbosity level is not valid: ${c}`);let l=typeof i.optimizedModelFilePath==`string`?ht(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,o,s,c,l),n===0&&D(`Can't create session options.`),i.executionProviders&&await Tt(n,i,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!=`boolean`)throw Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);Ct(n,`enableGraphCapture`,i.enableGraphCapture.toString(),r)}if(i.freeDimensionOverrides)for(let[e,a]of Object.entries(i.freeDimensionOverrides)){if(typeof e!=`string`)throw Error(`free dimension override name must be a string: ${e}`);if(typeof a!=`number`||!Number.isInteger(a)||a<0)throw Error(`free dimension override value must be a non-negative integer: ${a}`);let i=ht(e,r);t._OrtAddFreeDimensionOverride(n,i,a)!==0&&D(`Can't set a free dimension override: ${e} - ${a}.`)}return i.extra!==void 0&>(i.extra,``,new WeakSet,(e,t)=>{Ct(n,e,t,r)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&D(`Can't release session options.`),r.forEach(e=>t._free(e)),e}}}),Ot,kt,At,jt,Mt,Nt,Pt,Ft,It=c(()=>{Ot=e=>{switch(e){case`int8`:return 3;case`uint8`:return 2;case`bool`:return 9;case`int16`:return 5;case`uint16`:return 4;case`int32`:return 6;case`uint32`:return 12;case`float16`:return 10;case`float32`:return 1;case`float64`:return 11;case`string`:return 8;case`int64`:return 7;case`uint64`:return 13;case`int4`:return 22;case`uint4`:return 21;default:throw Error(`unsupported data type: ${e}`)}},kt=e=>{switch(e){case 3:return`int8`;case 2:return`uint8`;case 9:return`bool`;case 5:return`int16`;case 4:return`uint16`;case 6:return`int32`;case 12:return`uint32`;case 10:return`float16`;case 1:return`float32`;case 11:return`float64`;case 8:return`string`;case 7:return`int64`;case 13:return`uint64`;case 22:return`int4`;case 21:return`uint4`;default:throw Error(`unsupported data type: ${e}`)}},At=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r=typeof t==`number`?t:t.reduce((e,t)=>e*t,1);return n>0?Math.ceil(r*n):void 0},jt=e=>{switch(e){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: ${e}`)}},Mt=e=>{switch(e){case`verbose`:return 0;case`info`:return 1;case`warning`:return 2;case`error`:return 3;case`fatal`:return 4;default:throw Error(`unsupported logging level: ${e}`)}},Nt=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,Pt=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint64`||e===`int8`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,Ft=e=>{switch(e){case`none`:return 0;case`cpu`:return 1;case`cpu-pinned`:return 2;case`texture`:return 3;case`gpu-buffer`:return 4;case`ml-tensor`:return 5;default:throw Error(`unsupported data location: ${e}`)}}}),Lt,Rt=c(()=>{ze(),Lt=async e=>{if(typeof e==`string`){let t=await fetch(e);if(!t.ok)throw Error(`failed to load external data file: ${e}`);let n=t.headers.get(`Content-Length`),r=n?parseInt(n,10):0;if(r<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),i;try{i=new ArrayBuffer(r)}catch(e){if(e instanceof RangeError){let e=Math.ceil(r/65536);i=new WebAssembly.Memory({initial:e,maximum:e}).buffer}else throw e}let a=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;let r=t.byteLength;new Uint8Array(i,a,r).set(t),a+=r}return new Uint8Array(i,0,r)}}return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),zt,Bt=c(()=>{It(),zt=(e,t)=>new(jt(t))(e)}),Vt,Ht,Ut,Wt,Gt,Kt,qt,Jt=c(()=>{It(),Vt=[`V`,`I`,`W`,`E`,`F`],Ht=(e,t)=>{console.log(`[${Vt[e]},${new Date().toISOString()}]${t}`)},Gt=(e,t)=>{Ut=e,Wt=t},Kt=(e,t)=>{let n=Mt(e);n>=Mt(Ut)&&Ht(n,typeof t==`function`?t():t)},qt=(...e)=>{Wt&&Kt(...e)}}),Yt,Xt,Zt,Qt,$t,en,tn,nn,rn,an,on,sn=c(()=>{It(),Jt(),Yt=new Map([[`float32`,32],[`float16`,16],[`int32`,32],[`uint32`,32],[`int64`,64],[`uint64`,64],[`int8`,8],[`uint8`,8],[`int4`,4],[`uint4`,4]]),Xt=(e,t)=>{if(t===`int32`)return e;let n=Yt.get(t);if(!n)throw Error(`WebNN backend does not support data type: ${t}`);let r=n/8;if(e.byteLength%r!==0)throw Error(`Invalid Uint8Array length - must be a multiple of ${r}.`);let i=e.byteLength/r,a=new(jt(t))(e.buffer,e.byteOffset,i);switch(t){case`int64`:case`uint64`:{let e=new Int32Array(i);for(let t=0;t<i;t++){let n=a[t];if(n>2147483647n||n<-2147483648n)throw Error(`Can not convert int64 data to int32 - value out of range.`);e[t]=Number(n)}return new Uint8Array(e.buffer)}case`int8`:case`uint8`:case`uint32`:{if(t===`uint32`&&a.some(e=>e>2147483647))throw Error(`Can not convert uint32 data to int32 - value out of range.`);let e=Int32Array.from(a,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from ${t} to 'int32'`)}},Zt=(e,t)=>{if(t===`int32`)return e;if(e.byteLength%4!=0)throw Error(`Invalid Uint8Array length - must be a multiple of 4 (int32).`);let n=e.byteLength/4,r=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case`int64`:{let e=BigInt64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`uint64`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uin64 - negative value found.`);let e=BigUint64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`int8`:{if(r.some(e=>e<-128||e>127))throw Error(`Can not convert int32 data to int8 - value out of range.`);let e=Int8Array.from(r,Number);return new Uint8Array(e.buffer)}case`uint8`:if(r.some(e=>e<0||e>255))throw Error(`Can not convert int32 data to uint8 - value out of range.`);return Uint8Array.from(r,Number);case`uint32`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uint32 - negative value found.`);let e=Uint32Array.from(r,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from 'int32' to ${t}`)}},Qt=1,$t=()=>Qt++,en=new Map([[`int8`,`int32`],[`uint8`,`int32`],[`uint32`,`int32`],[`int64`,`int32`]]),tn=(e,t)=>{let n=Yt.get(e);if(!n)throw Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((e,t)=>e*t)*n/8):0},nn=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:r,dataType:i,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=r,this.dataType=i,this.tensorShape=a,this.fallbackDataType=o}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return tn(this.dataType,this.tensorShape)}destroy(){qt(`verbose`,()=>`[WebNN] TensorWrapper.destroy`),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),n=Zt(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}return new Uint8Array(n).buffer}return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((e,t)=>e===n[t])}setIsDataConverted(e){this.isDataConverted=e}},rn=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n,r){let i=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!a?.input.dataTypes.includes(t)){if(o=en.get(t),!o||!a?.input.dataTypes.includes(o))throw Error(`WebNN backend does not support data type: ${t}`);qt(`verbose`,()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(i,t,n))return this.wrapper.tensor;if(r){if(this.wrapper.byteLength!==tn(t,n))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 s=typeof MLTensorUsage>`u`?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,s,!0,!0,o),r&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType){if(this.wrapper.fallbackType===`int32`)t=Xt(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`)}if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}qt(`verbose`,()=>`Data size does not match tensor size. Releasing tensor.`),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?Zt(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}return t.buffer}if(!this.wrapper)throw Error(`Tensor has not been created.`);return e?this.wrapper.read(e):this.wrapper.read()}},an=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw Error(`MLContext not found for session.`);return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=$t();return this.tensorTrackersById.set(e,new rn(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,r,i){qt(`verbose`,()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${r}, copyOld: ${i}}`);let a=this.tensorTrackersById.get(t);if(!a)throw Error(`Tensor not found.`);return a.ensureTensor(e,n,r,i)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);n.upload(t)}async download(e,t){qt(`verbose`,()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);return n.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,n,r){let i=this.getMLContext(e),a=$t(),o=new nn({sessionId:e,context:i,tensor:t,dataType:n,shape:r});return this.tensorTrackersById.set(a,new rn(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,n,r,i,a,o){let s=this.getMLContext(e);for(let[r,i]of this.freeTensors.entries())if(i.canReuseTensor(s,t,n)){qt(`verbose`,()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}`);let i=this.freeTensors.splice(r,1)[0];return i.sessionId=e,i}qt(`verbose`,()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}}`);let c=await s.createTensor({dataType:o??t,shape:n,dimensions:n,usage:r,writable:i,readable:a});return new nn({sessionId:e,context:s,tensor:c,dataType:t,shape:n,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},on=(...e)=>new an(...e)}),cn={};l(cn,{WebNNBackend:()=>dn});var ln,un,dn,fn=c(()=>{It(),mt(),Bt(),sn(),Jt(),ln=new Map([[1,`float32`],[10,`float16`],[6,`int32`],[12,`uint32`],[7,`int64`],[13,`uint64`],[22,`int4`],[21,`uint4`],[3,`int8`],[2,`uint8`],[9,`uint8`]]),un=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((n,i)=>n===r[i]&&e[n]===t[n])},dn=class{constructor(e){this.tensorManager=on(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,Gt(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw Error(`No active session`);return this.activeSessionId}onRunStart(e){qt(`verbose`,()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){qt(`verbose`,()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let e of t)qt(`verbose`,()=>`[WebNN] releasing temporary tensor {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(t=>t.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:t}),t}}if(e===void 0){let e=this.mlContextCache.findIndex(e=>e.options===void 0&&e.gpuDevice===void 0);if(e!==-1)return this.mlContextCache[e].mlContext;{let e=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:e}),e}}let t=this.mlContextCache.findIndex(t=>un(t.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=new Set,this.sessionIdsByMLContext.set(t,n)),n.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let n=this.sessionIdsByMLContext.get(t);if(n.delete(e),n.size===0){this.sessionIdsByMLContext.delete(t);let e=this.mlContextCache.findIndex(e=>e.mlContext===t);e!==-1&&this.mlContextCache.splice(e,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){qt(`verbose`,()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,r,i){let a=ln.get(n);if(!a)throw Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,r,i)}async createTemporaryTensor(e,t,n){qt(`verbose`,()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let r=ln.get(t);if(!r)throw Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,i,r,n,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(i):this.temporarySessionTensorIds.set(e,[i]),i}uploadTensor(e,t){if(!E().shouldTransferToMLTensor)throw Error(`Trying to upload to a MLTensor while shouldTransferToMLTensor is false`);qt(`verbose`,()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let n=await this.tensorManager.download(e);return zt(n,t)}}registerMLTensor(e,t,n,r){let i=ln.get(n);if(!i)throw Error(`Unsupported ONNX data type: ${n}`);let a=this.tensorManager.registerTensor(e,t,i,r);return qt(`verbose`,()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${i}, dimensions: ${r}} -> {tensorId: ${a}}`),a}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return n?n.includes(t):!1}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return n?n.includes(t):!1}isGraphInputOutputTypeSupported(e,t,n=!0){let r=ln.get(Ot(t)),i=this.mlOpSupportLimitsBySessionId.get(e);return typeof r>`u`?!1:n?!!i?.input.dataTypes.includes(r):!!i?.output.dataTypes.includes(r)}flush(){}}}),pn,mn,hn,gn,_n,vn,yn,bn,xn,Sn,Cn,wn,Tn,En=c(()=>{Re(),yt(),Dt(),It(),mt(),_t(),Rt(),pn=(e,t)=>{E()._OrtInit(e,t)!==0&&D(`Can't initialize onnxruntime.`)},mn=async e=>{pn(e.wasm.numThreads,Mt(e.logLevel))},hn=async(e,t)=>{E().asyncInit?.();let n=e.webgpu.adapter;if(t===`webgpu`){if(typeof navigator>`u`||!navigator.gpu)throw Error(`WebGPU is not supported in current environment`);if(n){if(typeof n.limits!=`object`||typeof n.features!=`object`||typeof n.requestDevice!=`function`)throw Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let t=e.webgpu.powerPreference;if(t!==void 0&&t!==`low-power`&&t!==`high-performance`)throw Error(`Invalid powerPreference setting: "${t}"`);let r=e.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!=`boolean`)throw Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:r}),!n)throw Error(`Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.`)}}if(t===`webnn`&&(typeof navigator>`u`||!navigator.ml))throw Error(`WebNN is not supported in current environment`);if(t===`webgpu`&&E().webgpuInit(t=>{e.webgpu.device=t}),t===`webnn`){let t=new(fn(),d(cn)).WebNNBackend(e);E().webnnInit([t,()=>t.reserveTensorId(),e=>t.releaseTensorId(e),async(e,n,r,i,a)=>t.ensureTensor(e,n,r,i,a),(e,n)=>{t.uploadTensor(e,n)},async(e,n)=>t.downloadTensor(e,n),(e,n)=>t.registerMLContext(e,n),!!e.trace])}},gn=new Map,_n=e=>{let t=E(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&D(`Can't get session input/output count.`);let i=n===4?`i32`:`i64`;return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},vn=(e,t)=>{let n=E(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&D(`Can't get session input/output metadata.`);let o=Number(n.getValue(a,`*`));i=Number(n.getValue(a+r,`*`));let s=n.HEAP32[i/4];if(s===0)return[o,0];let c=n.HEAPU32[i/4+1],l=[];for(let e=0;e<c;e++){let t=Number(n.getValue(i+8+e*r,`*`));l.push(t===0?Number(n.getValue(i+8+(e+c)*r,`*`)):n.UTF8ToString(t))}return[o,s,l]}finally{n.stackRestore(r),i!==0&&n._OrtFree(i)}},yn=e=>{let t=E(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},bn=async(e,t)=>{let n,r,i=E();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=yn(e);let a=0,o=0,s=0,c=[],l=[],u=[];try{if([o,c]=await Et(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path,r=typeof n==`string`?n:n.data;e.push(Lt(r).then(e=>{i.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if((typeof e==`string`?e:e.name)===`webnn`){if(i.shouldTransferToMLTensor=!1,typeof e!=`string`){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,o=t?.powerPreference;i.currentContext=n||(r?await i.webnnCreateMLContext(r):await i.webnnCreateMLContext({deviceType:a,powerPreference:o}))}else i.currentContext=await i.webnnCreateMLContext();break}a=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(a),a===0&&D(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,d]=_n(a),f=!!t?.enableGraphCapture,p=[],m=[],h=[],g=[],_=[];for(let t=0;t<e;t++){let[e,n,r]=vn(a,t);e===0&&D(`Can't get an input name.`),l.push(e);let o=i.UTF8ToString(e);p.push(o),h.push(n===0?{name:o,isTensor:!1}:{name:o,isTensor:!0,type:kt(n),shape:r})}for(let n=0;n<d;n++){let[r,o,s]=vn(a,n+e);r===0&&D(`Can't get an output name.`),u.push(r);let c=i.UTF8ToString(r);m.push(c),g.push(o===0?{name:c,isTensor:!1}:{name:c,isTensor:!0,type:kt(o),shape:s});{if(f&&t?.preferredOutputLocation===void 0){_.push(`gpu-buffer`);continue}let e=typeof t?.preferredOutputLocation==`string`?t.preferredOutputLocation:t?.preferredOutputLocation?.[c]??`cpu`,n=i.webnnIsGraphOutput;if(e===`cpu`&&n&&n(a,c)){_.push(`ml-tensor-cpu-output`);continue}if(e!==`cpu`&&e!==`cpu-pinned`&&e!==`gpu-buffer`&&e!==`ml-tensor`)throw Error(`Not supported preferred output location: ${e}.`);if(f&&e!==`gpu-buffer`)throw Error(`Not supported preferred output location: ${e}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(e)}}let v=null;return _.some(e=>e===`gpu-buffer`||e===`ml-tensor`||e===`ml-tensor-cpu-output`)&&(s=i._OrtCreateBinding(a),s===0&&D(`Can't create IO binding.`),v={handle:s,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(e=>e===`ml-tensor-cpu-output`?`ml-tensor`:e).map(e=>Ft(e))}),gn.set(a,[a,l,u,v,f,!1]),[a,p,m,h,g]}catch(e){throw l.forEach(e=>i._OrtFree(e)),u.forEach(e=>i._OrtFree(e)),s!==0&&i._OrtReleaseBinding(s)!==0&&D(`Can't release IO binding.`),a!==0&&i._OrtReleaseSession(a)!==0&&D(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&D(`Can't release session options.`),c.forEach(e=>i._free(e)),i.unmountExternalData?.()}},xn=e=>{let t=E(),n=gn.get(e);if(!n)throw Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,o,s]=n;o&&(s&&t._OrtClearBoundOutputs(o.handle)!==0&&D(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&D(`Can't release IO binding.`)),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),i.forEach(e=>t._OrtFree(e)),a.forEach(e=>t._OrtFree(e)),t._OrtReleaseSession(r)!==0&&D(`Can't release session.`),gn.delete(e)},Sn=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=E(),c=s.PTR_SIZE,l=e[0],u=e[1],d=e[3],f=d,p,m;if(l===`string`&&(d===`gpu-buffer`||d===`ml-tensor`))throw Error(`String tensor is not supported on GPU.`);if(o&&d!==`gpu-buffer`)throw Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(d===`gpu-buffer`){let t=e[2].gpuBuffer;m=At(Ot(l),u);{let e=s.webgpuRegisterBuffer;if(!e)throw Error(`Tensor location "gpu-buffer" is not supported without using WebGPU.`);p=e(t,r)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=At(Ot(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);p=n(r,t,Ot(l),u)}else{let t=e[2];if(Array.isArray(t)){m=c*t.length,p=s._malloc(m),n.push(p);for(let e=0;e<t.length;e++){if(typeof t[e]!=`string`)throw TypeError(`tensor data at index ${e} is not a string`);s.setValue(p+e*c,ht(t[e],n),`*`)}}else{let e=s.webnnIsGraphInput,a=s.webnnIsGraphOutput;if(l!==`string`&&e&&a){let o=s.UTF8ToString(i);if(e(r,o)||a(r,o)){let e=Ot(l);m=At(e,u),f=`ml-tensor`;let n=s.webnnCreateTemporaryTensor,i=s.webnnUploadTensor;if(!n||!i)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);let a=await n(r,e,u);i(a,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),p=a}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}}let h=s.stackSave(),g=s.stackAlloc(4*u.length);try{u.forEach((e,t)=>s.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(Ot(l),p,m,g,u.length,Ft(f));e===0&&D(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},Cn=async(e,t,n,r,i,a)=>{let o=E(),s=o.PTR_SIZE,c=gn.get(e);if(!c)throw Error(`cannot run inference. invalid session id: ${e}`);let l=c[0],u=c[1],d=c[2],f=c[3],p=c[4],m=c[5],h=t.length,g=r.length,_=0,v=[],y=[],b=[],x=[],S=[],C=o.stackSave(),w=o.stackAlloc(h*s),ee=o.stackAlloc(h*s),te=o.stackAlloc(g*s),ne=o.stackAlloc(g*s);try{[_,v]=vt(a),Ee(`wasm prepareInputOutputTensor`);for(let r=0;r<h;r++)await Sn(n[r],y,x,e,u[t[r]],t[r],p);for(let t=0;t<g;t++)await Sn(i[t],b,x,e,d[r[t]],h+r[t],p);De(`wasm prepareInputOutputTensor`);for(let e=0;e<h;e++)o.setValue(w+e*s,y[e],`*`),o.setValue(ee+e*s,u[t[e]],`*`);for(let e=0;e<g;e++)o.setValue(te+e*s,b[e],`*`),o.setValue(ne+e*s,d[r[e]],`*`);if(f&&!m){let{handle:n,outputPreferredLocations:a,outputPreferredLocationsEncoded:s}=f;if(u.length!==h)throw Error(`input count from feeds (${h}) is expected to be always equal to model's input count (${u.length}).`);Ee(`wasm bindInputsOutputs`);for(let r=0;r<h;r++){let i=t[r];await o._OrtBindInput(n,u[i],y[r])!==0&&D(`Can't bind input[${r}] for session=${e}.`)}for(let t=0;t<g;t++){let c=r[t];i[t]?.[3]?(S.push(b[t]),o._OrtBindOutput(n,d[c],b[t],0)!==0&&D(`Can't bind pre-allocated output[${t}] for session=${e}.`)):o._OrtBindOutput(n,d[c],0,s[c])!==0&&D(`Can't bind output[${t}] to ${a[t]} for session=${e}.`)}De(`wasm bindInputsOutputs`),gn.set(e,[l,u,d,f,p,!0])}o.jsepOnRunStart?.(l),o.webnnOnRunStart?.(l);let c;c=f?await o._OrtRunWithBinding(l,f.handle,g,te,_):await o._OrtRun(l,ee,w,h,ne,g,te,_),c!==0&&D(`failed to call OrtRun().`);let C=[],re=[];Ee(`wasm ProcessOutputTensor`);for(let t=0;t<g;t++){let n=Number(o.getValue(te+t*s,`*`));if(n===b[t]||S.includes(b[t])){C.push(i[t]),n!==b[t]&&o._OrtReleaseTensor(n)!==0&&D(`Can't release tensor.`);continue}let a=o.stackSave(),c=o.stackAlloc(4*s),l=!1,u,d=0;try{o._OrtGetTensorData(n,c,c+s,c+2*s,c+3*s)!==0&&D(`Can't access output tensor data on index ${t}.`);let i=s===4?`i32`:`i64`,a=Number(o.getValue(c,i));d=o.getValue(c+s,`*`);let p=o.getValue(c+s*2,`*`),m=Number(o.getValue(c+s*3,i)),h=[];for(let e=0;e<m;e++)h.push(Number(o.getValue(p+e*s,i)));o._OrtFree(p)!==0&&D(`Can't free memory for tensor dims.`);let g=h.reduce((e,t)=>e*t,1);u=kt(a);let _=f?.outputPreferredLocations[r[t]];if(u===`string`){if(_===`gpu-buffer`||_===`ml-tensor`)throw Error(`String tensor is not supported on GPU.`);let e=[];for(let t=0;t<g;t++){let n=o.getValue(d+t*s,`*`),r=o.getValue(d+(t+1)*s,`*`),i=t===g-1?void 0:r-n;e.push(o.UTF8ToString(n,i))}C.push([u,h,e,`cpu`])}else if(_===`gpu-buffer`&&g>0){let t=o.webgpuGetBuffer;if(!t)throw Error(`preferredLocation "gpu-buffer" is not supported without using WebGPU.`);let r=t(d),i=At(a,g);if(i===void 0||!Nt(u))throw Error(`Unsupported data type: ${u}`);l=!0;{o.webgpuRegisterBuffer(r,e,d);let t=o.webgpuCreateDownloader(r,i,e);C.push([u,h,{gpuBuffer:r,download:async()=>{let e=await t();return new(jt(u))(e)},dispose:()=>{o._OrtReleaseTensor(n)!==0&&D(`Can't release tensor.`)}},`gpu-buffer`])}}else if(_===`ml-tensor`&&g>0){let t=o.webnnEnsureTensor,r=o.webnnIsGraphInputOutputTypeSupported;if(!t||!r)throw Error(`preferredLocation "ml-tensor" is not supported without using WebNN.`);if(At(a,g)===void 0||!Pt(u))throw Error(`Unsupported data type: ${u}`);if(!r(e,u,!1))throw Error(`preferredLocation "ml-tensor" for ${u} output is not supported by current WebNN Context.`);let i=await t(e,d,a,h,!1);l=!0,C.push([u,h,{mlTensor:i,download:o.webnnCreateMLTensorDownloader(d,u),dispose:()=>{o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n)}},`ml-tensor`])}else if(_===`ml-tensor-cpu-output`&&g>0){let e=o.webnnCreateMLTensorDownloader(d,u)(),t=C.length;l=!0,re.push((async()=>{let r=[t,await e];return o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n),r})()),C.push([u,h,[],`cpu`])}else{let e=new(jt(u))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o.HEAPU8.subarray(d,d+e.byteLength)),C.push([u,h,e,`cpu`])}}finally{o.stackRestore(a),u===`string`&&d&&o._free(d),l||o._OrtReleaseTensor(n)}}f&&!p&&(o._OrtClearBoundOutputs(f.handle)!==0&&D(`Can't clear bound outputs.`),gn.set(e,[l,u,d,f,p,!1]));for(let[e,t]of await Promise.all(re))C[e][2]=t;return De(`wasm ProcessOutputTensor`),C}finally{o.webnnOnRunEnd?.(l),o.stackRestore(C),n.forEach(e=>{e&&e[3]===`gpu-buffer`&&o.webgpuUnregisterBuffer(e[2].gpuBuffer)}),i.forEach(e=>{e&&e[3]===`gpu-buffer`&&o.webgpuUnregisterBuffer(e[2].gpuBuffer)}),y.forEach(e=>o._OrtReleaseTensor(e)),b.forEach(e=>o._OrtReleaseTensor(e)),x.forEach(e=>o._free(e)),_!==0&&o._OrtReleaseRunOptions(_),v.forEach(e=>o._free(e))}},wn=e=>{let t=E(),n=gn.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&D(`Can't get an profile file name.`),t._OrtFree(i)},Tn=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),Dn,On,kn,An,jn,Mn,Nn,Pn,Fn,In,Ln,Rn,zn,Bn,Vn,Hn,Un,Wn,Gn=c(()=>{Re(),En(),mt(),at(),Dn=()=>!!w.wasm.proxy&&typeof document<`u`,kn=!1,An=!1,jn=!1,Pn=new Map,Fn=(e,t)=>{let n=Pn.get(e);n?n.push(t):Pn.set(e,[t])},In=()=>{if(kn||!An||jn||!On)throw Error(`worker not ready`)},Ln=e=>{switch(e.data.type){case`init-wasm`:kn=!1,e.data.err?(jn=!0,Nn[1](e.data.err)):(An=!0,Nn[0]()),Mn&&=(URL.revokeObjectURL(Mn),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=Pn.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Rn=async()=>{if(!An){if(kn)throw Error(`multiple calls to 'initWasm()' detected.`);if(jn)throw Error(`previous call to 'initWasm()' failed.`);if(kn=!0,Dn())return new Promise((e,t)=>{On?.terminate(),nt().then(([n,r])=>{try{On=r,On.onerror=e=>t(e),On.onmessage=Ln,Nn=[e,t];let i={type:`init-wasm`,in:w};if(!i.in.wasm.wasmPaths&&n){let e=Ye();e&&(i.in.wasm.wasmPaths=e)}On.postMessage(i),Mn=n}catch(e){t(e)}},t)});try{await pt(w.wasm),await mn(w),An=!0}catch(e){throw jn=!0,e}finally{kn=!1}}},zn=async e=>{if(Dn())return In(),new Promise((t,n)=>{Fn(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:w}};On.postMessage(r)});await hn(w,e)},Bn=async e=>Dn()?(In(),new Promise((t,n)=>{Fn(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};On.postMessage(r,[e.buffer])})):yn(e),Vn=async(e,t)=>{if(Dn()){if(t?.preferredOutputLocation)throw Error(`session option "preferredOutputLocation" is not supported for proxy.`);return In(),new Promise((n,r)=>{Fn(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),On.postMessage(i,a)})}return bn(e,t)},Hn=async e=>{if(Dn())return In(),new Promise((t,n)=>{Fn(`release`,[t,n]);let r={type:`release`,in:e};On.postMessage(r)});xn(e)},Un=async(e,t,n,r,i,a)=>{if(Dn()){if(n.some(e=>e[3]!==`cpu`))throw Error(`input tensor on GPU is not supported for proxy.`);if(i.some(e=>e))throw Error(`pre-allocated output tensor is not supported for proxy.`);return In(),new Promise((i,o)=>{Fn(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};On.postMessage(c,Tn(s))})}return Cn(e,t,n,r,i,a)},Wn=async e=>{if(Dn())return In(),new Promise((t,n)=>{Fn(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};On.postMessage(r)});wn(e)}}),Kn,qn,Jn,Yn=c(()=>{Re(),Gn(),It(),ze(),Rt(),Kn=(e,t)=>{switch(e.location){case`cpu`:return[e.type,e.dims,e.data,`cpu`];case`gpu-buffer`:return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},`gpu-buffer`];case`ml-tensor`:return[e.type,e.dims,{mlTensor:e.mlTensor},`ml-tensor`];default:throw Error(`invalid data location: ${e.location} for ${t()}`)}},qn=e=>{switch(e[3]){case`cpu`:return new be(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!Nt(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return be.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!Pt(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return be.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},Jn=class{async fetchModelAndCopyToWasmMemory(e){return Bn(await Lt(e))}async loadModel(e,t){we();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Vn(n,t),Te()}async dispose(){return Hn(this.sessionId)}async run(e,t,n){we();let r=[],i=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],a=this.inputNames.indexOf(t);if(a===-1)throw Error(`invalid input '${t}'`);r.push(n),i.push(a)});let a=[],o=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(r===-1)throw Error(`invalid output '${t}'`);a.push(n),o.push(r)});let s=r.map((e,t)=>Kn(e,()=>`input "${this.inputNames[i[t]]}"`)),c=a.map((e,t)=>e?Kn(e,()=>`output "${this.outputNames[o[t]]}"`):null),l=await Un(this.sessionId,i,s,o,c,n),u={};for(let e=0;e<l.length;e++)u[this.outputNames[o[e]]]=a[e]??qn(l[e]);return Te(),u}startProfiling(){}endProfiling(){Wn(this.sessionId)}}}),Xn={};l(Xn,{OnnxruntimeWebAssemblyBackend:()=>Qn,initializeFlags:()=>Zn,wasmBackend:()=>$n});var Zn,Qn,$n,er=c(()=>{Re(),Gn(),Yn(),Zn=()=>{(typeof w.wasm.initTimeout!=`number`||w.wasm.initTimeout<0)&&(w.wasm.initTimeout=0);let e=w.wasm.simd;if(typeof e!=`boolean`&&e!==void 0&&e!==`fixed`&&e!==`relaxed`&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),w.wasm.simd=!1),typeof w.wasm.proxy!=`boolean`&&(w.wasm.proxy=!1),typeof w.wasm.trace!=`boolean`&&(w.wasm.trace=!1),typeof w.wasm.numThreads!=`number`||!Number.isInteger(w.wasm.numThreads)||w.wasm.numThreads<=0){if(typeof self<`u`&&!self.crossOriginIsolated)w.wasm.numThreads=1;else{let e=typeof navigator>`u`?s(`node:os`).cpus().length:navigator.hardwareConcurrency;w.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}}},Qn=class{async init(e){Zn(),await Rn(),await zn(e)}async createInferenceSessionHandler(e,t){let n=new Jn;return await n.loadModel(e,t),n}},$n=new Qn});Re(),Re(),Re();var tr=`1.31.0-dev.20260914-8d85527a0`,nr=Le;{let e=(er(),d(Xn)).wasmBackend;m(`webgpu`,e,5),m(`webnn`,e,5),m(`cpu`,e,10),m(`wasm`,e,10)}Object.defineProperty(w.versions,"web",{value:tr,enumerable:!0});var rr=`1.30.0`,ir=`warning`;Object.defineProperty({wasm:{},webgl:{},webgpu:{},versions:{common:rr},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);ir=e}},get logLevel(){return ir}},"logLevel",{enumerable:!0});var ar=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t<a;t++)for(let n=0;n<i;n++){let i=(e.data[d++]-l[0])*c[0],a=(e.data[f++]-l[1])*c[1],o=(e.data[p++]-l[2])*c[2],s=m===-1?255:(e.data[m++]-l[3])*c[3];r.fillStyle=`rgba(`+i+`,`+a+`,`+o+`,`+s+`)`,r.fillRect(n,t,1,1)}if(`toDataURL`in n)return n.toDataURL();throw Error(`toDataURL is not supported`)}throw Error(`Can not access image data`)},or=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t===void 0||t.format===void 0?`RGB`:t.format,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t<a*i;f+=4,p+=4,m+=4,h+=4,t++)r.data[f]=(e.data[g++]-u[0])*l[0],r.data[p]=(e.data[_++]-u[1])*l[1],r.data[m]=(e.data[v++]-u[2])*l[2],r.data[h]=y===-1?255:(e.data[y++]-u[3])*l[3]}else throw Error(`Can not access image data`);return r},sr=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat===void 0||t.tensorFormat===void 0?`RGB`:t.tensorFormat,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t<l;t++,f+=d,m+=d,p+=d,h+=d)u[g++]=(e[f]+o[0])/a[0],u[_++]=(e[p]+o[1])/a[1],u[v++]=(e[m]+o[2])/a[2],y!==-1&&h!==-1&&(u[y++]=(e[h]+o[3])/a[3]);return c===`RGBA`?new yr(`float32`,u,[1,4,n,r]):new yr(`float32`,u,[1,3,n,r])},cr=async(e,t)=>{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,sr(o,s)}throw Error(`Can not access image data`)}else if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(sr(e.data,s))}});else throw Error(`Input data provided is not supported - aborted tensor creation`);if(o!==void 0)return sr(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},lr=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new yr({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},ur=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new yr({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},dr=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new yr({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},fr=(e,t,n)=>new yr({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]}),pr=new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),mr=new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),hr=!1,gr=()=>{if(!hr){hr=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=n!==void 0&&n.from;e&&(pr.set(`int64`,BigInt64Array),mr.set(BigInt64Array,`int64`)),t&&(pr.set(`uint64`,BigUint64Array),mr.set(BigUint64Array,`uint64`)),r?(pr.set(`float16`,n),mr.set(n,`float16`)):pr.set(`float16`,Uint16Array)}},_r=e=>{let t=1;for(let n=0;n<e.length;n++){let r=e[n];if(typeof r!=`number`||!Number.isSafeInteger(r))throw TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);t*=r}return t},vr=(e,t)=>{switch(e.location){case`cpu`:return new yr(e.type,e.data,t);case`cpu-pinned`:return new yr({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new yr({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new yr({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new yr({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}},yr=class{constructor(e,t,n){gr();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=pr.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`){if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=pr.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray){if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`)}else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=mr.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=_r(i);if(this.cpuData&&a!==this.cpuData.length&&(r!==`uint4`&&r!==`int4`||Math.ceil(a/2)!==this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return cr(e,t)}static fromTexture(e,t){return lr(e,t)}static fromGpuBuffer(e,t){return ur(e,t)}static fromMLTensor(e,t){return dr(e,t)}static fromPinnedBuffer(e,t,n){return fr(e,t,n)}toDataURL(e){return ar(this,e)}toImageData(e){return or(this,e)}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(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw 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 t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);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(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return vr(this,e)}},br=yr,xr=Object.defineProperty,Sr=(e,t)=>{for(var n in t)xr(e,n,{get:t[n],enumerable:!0})},Cr={},wr={},Tr={},Er=`4.3.2`,Dr=typeof self<`u`,Or=!Qr(Cr),kr=!Qr(wr),Ar=Dr&&`caches`in self,jr=globalThis.Deno!==void 0;globalThis.Bun;var Mr=jr&&Ar&&!Or,Nr=typeof process<`u`,Pr=Nr&&process?.release?.name===`node`&&!Mr,Fr=typeof window<`u`&&window.document!==void 0,Ir=Dr&&[`DedicatedWorkerGlobalScope`,`ServiceWorkerGlobalScope`,`SharedWorkerGlobalScope`].includes(self.constructor?.name),Lr=Fr||Ir||Mr,Rr=Pr||typeof navigator<`u`&&`gpu`in navigator,zr=typeof navigator<`u`&&`ml`in navigator,Br=typeof crypto<`u`&&typeof crypto.getRandomValues==`function`,Vr=typeof chrome<`u`&&chrome.runtime!==void 0&&typeof chrome.runtime.id==`string`,Hr=typeof ServiceWorkerGlobalScope<`u`&&Dr&&self instanceof ServiceWorkerGlobalScope,Ur=(()=>{if(typeof navigator>`u`)return!1;let e=navigator.userAgent;if(!((navigator.vendor||``).indexOf(`Apple`)>-1&&!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes(`Chrome`)&&!e.includes(`Android`)))return!1;let t=e.match(/Version\/(\d+)/);return t?parseInt(t[1],10)<26:!1})(),O=Object.freeze({IS_BROWSER_ENV:Fr,IS_WEBWORKER_ENV:Ir,IS_WEB_ENV:Lr,IS_SERVICE_WORKER_ENV:Hr,IS_DENO_WEB_RUNTIME:Mr,IS_WEB_CACHE_AVAILABLE:Ar,IS_WEBGPU_AVAILABLE:Rr,IS_WEBNN_AVAILABLE:zr,IS_SAFARI_BELOW_26:Ur,IS_PROCESS_AVAILABLE:Nr,IS_NODE_ENV:Pr,IS_FS_AVAILABLE:Or,IS_PATH_AVAILABLE:kr,IS_CRYPTO_AVAILABLE:Br,IS_CHROME_AVAILABLE:Vr}),Wr=Or&&kr,Gr=`./`;if(Wr){let e=import.meta.url;e?Gr=wr.dirname(wr.dirname(Tr.fileURLToPath(e))):typeof __dirname<`u`&&(Gr=wr.dirname(__dirname))}var Kr=Wr?wr.join(Gr,`/.cache/`):null,qr=`/models/`,Jr=Wr?wr.join(Gr,qr):qr,Yr=typeof globalThis.fetch==`function`?globalThis.fetch.bind(globalThis):void 0,Xr=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),Zr=Xr.WARNING,k={version:Er,backends:{onnx:{}},get logLevel(){return Zr},set logLevel(e){Zr=e,k.backends.onnx?.setLogLevel?.(e)},allowRemoteModels:!0,remoteHost:`https://huggingface.co/`,remotePathTemplate:`{model}/resolve/{revision}/`,allowLocalModels:!(Fr||Ir||Mr),localModelPath:Jr,useFS:Or,useBrowserCache:Ar,useFSCache:Or,cacheDir:Kr,useCustomCache:!1,customCache:null,useWasmCache:Ar||Or,cacheKey:`transformers-cache`,experimental_useCrossOriginStorage:!1,fetch:Yr};function Qr(e){return Object.keys(e).length===0}var $r=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error(`Must implement _call method in subclass`)}};function ei(e,t){e&&e(t)}var ti=class extends $r{constructor(e,t){super(),this.callback=e,this.files_loading=t,this.loads=new Map}_call(e){if(e.status===`progress`){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let t=Object.values(this.files_loading).reduce((e,t)=>e+t.loaded,0),n=Object.values(this.files_loading).reduce((e,t)=>e+t.total,0),r=n>0?t/n*100:0;this.callback({status:`progress_total`,name:e.name,progress:r,loaded:t,total:n,files:structuredClone(this.files_loading)})}this.callback(e)}};function ni(e){return Number.isInteger(e)||typeof e==`bigint`}function ri(e){return e==null||e===-1}function ii(e){let t=[],n=e;for(;Array.isArray(n);)t.push(n.length),n=n[0];return t}function ai(...e){return Array.prototype.concat.apply([],e)}function oi(...e){return e.reduce((e,t)=>e.flatMap(e=>t.map(t=>[e,t])))}function si(e,t){return Math.abs((e+t)%(2*t)-t)}function ci(e,t){return Object.assign({},...t.map(t=>{if(e[t]!==void 0)return{[t]:e[t]}}))}function li(e,t){let n=0;for(let r of e)r===t&&++n;return n}var A={error(...e){k.logLevel<=Xr.ERROR&&console.error(...e)},warn(...e){k.logLevel<=Xr.WARNING&&console.warn(...e)},info(...e){k.logLevel<=Xr.INFO&&console.log(...e)},debug(...e){k.logLevel<=Xr.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},ui=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){let t=Object.create(null);for(let n of e){let e=t;for(let t=0;t<n.length;++t){let r=n[t];e=e[r]??=Object.create(null)}e.end=n}return t}split(e){let t=[],n=e.length,r=0,i=0;for(;i<n;){let a=this.trie,o=null,s=i;for(;s<n&&(a=a[e[s]]);)a.end&&(o=a.end),++s;o?(i>r&&t.push(e.slice(r,i)),t.push(o),i+=o.length,r=i):++i}return r<n&&t.push(e.slice(r)),t}},di=class{constructor(e){this.content=e.content,this.id=e.id,this.single_word=e.single_word??!1,this.lstrip=e.lstrip??!1,this.rstrip=e.rstrip??!1,this.special=e.special??!1,this.normalized=e.normalized??!this.special}},fi=(e,t)=>{try{return new RegExp(e,t)}catch(n){if(!(n instanceof SyntaxError))throw n;let r=new Map,i=e.replace(/(\\[pP])\{([^}=]+)\}/g,(t,n,i,a)=>{let o=0;for(let t=a-1;t>=0&&e[t]===`\\`;--t)++o;if(o%2==1)return t;let s=r.get(i);if(s===void 0){try{RegExp(`\\p{${i}}`,`u`),s=i}catch{s=`Script=${i}`}r.set(i,s)}return`${n}{${s}}`});if(i===e)throw n;try{return new RegExp(i,t)}catch{throw n}}},pi=e=>e.replace(/ \./g,`.`).replace(/ \?/g,`?`).replace(/ \!/g,`!`).replace(/ ,/g,`,`).replace(/ \' /g,`'`).replace(/ n't/g,`n't`).replace(/ 'm/g,`'m`).replace(/ 's/g,`'s`).replace(/ 've/g,`'ve`).replace(/ 're/g,`'re`),mi=(e,t=!0)=>{if(e.Regex!==void 0)return fi(Qi(Bi(e.Regex)),`gu`);if(e.String!==void 0){let n=$i(e.String);return new RegExp(t?n:`(${n})`,`gu`)}return console.warn(`Unknown pattern type:`,e),null},hi=`\\p{Alphabetic}\\p{M}\\p{Nd}\\p{Pc}`,gi=`${hi}\\u00B2\\u00B3\\u00B9\\u00BC-\\u00BE`,_i=`[${gi}]`,vi=`[^${gi}]`,yi=`(?:(?<!${_i})(?=${_i})|(?<=${_i})(?!${_i}))`,bi=`(?:(?<!${_i})(?!${_i})|(?<=${_i})(?=${_i}))`,xi=`(?:(?<![\\s\\S])|(?<=\\n))`,Si=`(?:(?=\\n)|(?![\\s\\S]))`,Ci=`0-9A-Fa-f`,wi=new Map([[`A`,`(?<![\\s\\S])`],[`z`,`(?![\\s\\S])`],[`Z`,`(?=\\n?(?![\\s\\S]))`],[`h`,`[${Ci}]`],[`H`,`[^${Ci}]`],[`w`,_i],[`W`,vi],[`d`,`\\p{Nd}`],[`D`,`\\P{Nd}`],[`s`,`\\p{White_Space}`],[`S`,`\\P{White_Space}`],[`b`,yi],[`B`,bi],[`a`,`\\x07`],[`e`,`\\x1B`]]),Ti=new Map([[`h`,Ci],[`w`,hi],[`d`,`\\p{Nd}`],[`D`,`\\P{Nd}`],[`s`,`\\p{White_Space}`],[`S`,`\\P{White_Space}`],[`a`,`\\x07`],[`e`,`\\x1B`]]),Ei=new Map([[`W`,`[^${hi}]`],[`H`,`[^${Ci}]`]]),Di=new Map([[`
|
|
3
3
|
`,`\\n`],[`\r`,`\\r`],[` `,`\\t`],[`\f`,`\\f`],[`\v`,`\\v`]]),Oi=new Map([[`alpha`,`\\p{Alphabetic}`],[`alnum`,`\\p{Alphabetic}\\p{Nd}`],[`digit`,`\\p{Nd}`],[`lower`,`\\p{Lowercase}`],[`upper`,`\\p{Uppercase}`],[`space`,`\\p{White_Space}`],[`blank`,`\\t\\p{Zs}`],[`punct`,`\\p{P}\\p{S}`],[`cntrl`,`\\p{Cc}`],[`word`,hi],[`xdigit`,Ci]]),ki=`^$\\.*+?()[]{}|/`,Ai=/^\(\?(?:<[=!]|<[A-Za-z_][A-Za-z0-9_]*>|[:=!>])/,ji=/^\\([pPxu])\{([^}]*)\}/,Mi=/^\{(\d+(?:,\d*)?|,\d+)\}/,Ni=/^\[:(\^?)(\p{Alphabetic}+):\]/u,Pi=/^\[:\^:\]/,Fi=/^\[(?:\.[^\]]*\.\]|=[^\]]*=\])/,Ii=/^(?:\\x[0-9A-Fa-f]{2}|\\u[0-9A-Fa-f]{4}|\\c[A-Za-z])/,Li=e=>e>=`A`&&e<=`Z`||e>=`a`&&e<=`z`,Ri=(e,t)=>String.fromCodePoint(e.codePointAt(t)),zi=e=>{if(!/^[0-9A-Fa-f]{1,8}$/.test(e))return null;let t=Number.parseInt(e,16);if(t>127)return null;let n=String.fromCharCode(t);return Li(n)?`[${n.toLowerCase()}${n.toUpperCase()}]`:null},Bi=e=>e.replace(/\[\^\(\\s\|\[([^\]]+)\]\)\]/g,`[^()|\\s$1]`),Vi=`[\\s\\S]`,Hi=256,Ui=()=>({fragment:``,alternatives:[],tail:null,contains_complex_set:!1}),Wi=e=>{throw SyntaxError(`Unsupported range with a set-valued character-class operand at index ${e}`)},Gi=(e,t,n,r=!0)=>{e.tail===`range`&&Wi(n),e.alternatives.push(t),e.tail=`set`,e.contains_complex_set=e.contains_complex_set||r},Ki=(e,t,n=!1,r=-1)=>{n&&e.tail===`range`&&Wi(r),e.tail===`range`?(e.fragment+=t,e.tail=`complete_range`):(e.fragment+=t,e.tail=n?`set`:`scalar`,e.contains_complex_set=e.contains_complex_set||n)},qi=(e,t,n)=>{let r=ji.exec(e.slice(t));if(r){let[e,i,a]=r;return i===`P`&&a===`Word`?Gi(n,`[^${hi}]`,t):Ki(n,i===`x`?`\\u{${a}}`:i===`p`&&a===`Word`?hi:e,i===`p`||i===`P`,t),t+e.length}let i=Ii.exec(e.slice(t));if(i)return Ki(n,i[0]),t+i[0].length;if(t+1>=e.length)throw SyntaxError(`Unterminated escape in character class at index ${t}`);let a=Ri(e,t+1),o=t+1+a.length,s=Di.get(a);if(s!==void 0)return Ki(n,s),o;let c=Ei.get(a);if(c!==void 0)return Gi(n,c,t),o;let l=Ti.get(a),u,d=!1;return l===void 0?u=/[A-Za-z0-9]/.test(a)||ki.includes(a)||a===`-`?`\\${a}`:a:(u=l,d=a!==`a`&&a!==`e`),Ki(n,u,d,t),o},Ji=e=>e.length===1?e[0]:`(?:(?=(?:${e.join(`|`)}))${Vi})`,Yi=e=>Ji(e.fragment.length===0?e.alternatives:[`[${e.fragment}]`,...e.alternatives]),Xi=e=>{let t=fi(`^(?:${e})$`,`u`),n=``;for(let e=0;e<26;++e){let r=String.fromCharCode(65+e),i=String.fromCharCode(97+e),a=t.test(r);a!==t.test(i)&&(n+=a?i:r)}return n},Zi=(e,t,n,r=!0,i=1)=>{if(i>Hi)throw SyntaxError(`Maximum character-class nesting depth of ${Hi} exceeded at index ${t}`);let a=t+1,o=e[a]===`^`;o&&++a;let s=a,c=[Ui()],l=c[0],u=!1;for(;a<e.length;){let d=Ri(e,a);if(d===`\\`)a=qi(e,a,l);else{if(d===`]`){if(a===s){Ki(l,`\\]`),++a;continue}if(l.tail===null)throw c.length>1?SyntaxError(`Malformed character-class intersection with an empty operand at index ${a}`):SyntaxError(`Empty character class at index ${t}`);let e=c.some(e=>e.contains_complex_set);if(o&&c.length>1&&u)throw SyntaxError(`Unsupported outer-negated character-class intersection with a nested negated class containing a Unicode property, POSIX class, or shorthand at index ${t}`);let i=Yi(c[0]),d=i;if(c.length>1){let e=``;for(let t=1;t<c.length;++t)e+=`(?=${Yi(c[t])})`;d=`(?:${e}${i})`}let f=c.length===1&&l.alternatives.length===0,p=l.fragment;if(n&&r){let e=Xi(d);e.length>0&&(f?(p+=e,d=`[${p}]`):d=Ji([d,`[${e}]`]))}return{atom:o?f?`[^${p}]`:`(?:(?!${d})${Vi})`:d,end:a+1,negated:o,contains_complex_set:e,contains_nested_negated_complex_set:u}}if(e.startsWith(`&&`,a)){if(l.tail===null)throw SyntaxError(`Malformed character-class intersection with an empty operand at index ${a}`);l=Ui(),c.push(l),a+=2}else if(d===`[`){let t=e.slice(a);if(Pi.test(t))throw SyntaxError(`Malformed empty negated POSIX character class at index ${a}`);let r=Ni.exec(t);if(r){let[,e,t]=r,i=Oi.get(t);if(i===void 0)throw SyntaxError(`Unsupported POSIX character class "${t}" at index ${a}`);if(n&&e&&(t===`lower`||t===`upper`))throw SyntaxError(`Unsupported negated POSIX ${t} class inside an inline case-insensitive group`);e?Gi(l,`[^${i}]`,a):Ki(l,i,!0,a),a+=r[0].length;continue}if(Fi.test(t))throw SyntaxError(`Unsupported POSIX collating or equivalence bracket expression at index ${a}`);let o=Zi(e,a,n,!1,i+1);Gi(l,o.atom,a,o.contains_complex_set),u||=o.contains_nested_negated_complex_set||o.negated&&o.contains_complex_set,a=o.end}else if(d===`-`){let t=e[a+1]===`]`||e.startsWith(`&&`,a+1);l.tail===`set`&&!t&&Wi(a),l.tail===null||l.tail===`range`||l.tail===`complete_range`||t?Ki(l,`\\-`):(l.fragment+=`-`,l.tail=`range`),++a}else Ki(l,d===`^`&&l.fragment.length===0?`\\^`:d),a+=d.length}}throw SyntaxError(`${c.length>1?`Unterminated character-class intersection`:`Unterminated character class`} at index ${t}`)},Qi=e=>{let t=``,n=-1,r=!1,i=!1,a=[],o=e=>{n=t.length,t+=e,r=!1};for(let s=0;s<e.length;){let c=Ri(e,s);if(c===`\\`){let n=ji.exec(e.slice(s));if(n){let[e,t,r]=n,a=e;if(t===`x`){let e=`\\u{${r}}`;a=i?zi(r)??e:e}else r===`Word`&&(a=t===`p`?_i:vi);o(a),s+=e.length;continue}let r=Ii.exec(e.slice(s));if(r){let e=r[0];o(i&&e[1]!==`c`?zi(e.slice(2))??e:e),s+=e.length;continue}if(s+1>=e.length){t+=c;break}let a=Ri(e,s+1);if(s+=1+a.length,a===`G`)continue;let l=Di.get(a);if(l!==void 0){o(l);continue}let u=wi.get(a),d;d=u===void 0?/[A-Za-z0-9]/.test(a)||ki.includes(a)?`\\${a}`:a:u,o(d)}else switch(c){case`[`:{let t=Zi(e,s,i);o(t.atom),s=t.end;continue}case`]`:o(`\\]`),++s;continue;case`.`:o(`[^\\n]`),++s;continue;case`^`:o(xi),++s;continue;case`$`:o(Si),++s;continue;case`(`:{let n=e.startsWith(`(?i:`,s),o=n?`(?i:`:Ai.exec(e.slice(s))?.[0]??`(`,c=n||o===`(?>`?`(?:`:o;a.push([t.length,i]),n&&(i=!0),t+=c,r=!1,s+=o.length;continue}case`)`:t+=c,[n,i]=a.pop()??[-1,!1],r=!1,++s;continue;case`|`:t+=c,n=-1,r=!1,++s;continue;case`{`:{let i=Mi.exec(e.slice(s));if(!i||n<0){o(`\\{`),++s;continue}let a=i[1].startsWith(`,`)?`0${i[1]}`:i[1];s+=i[0].length;let c=e[s];c===`+`||c===`*`?(t=`${t.slice(0,n)}(?:${t.slice(n)}{${a}})${c}`,++s):t+=`{${a}}`,r=!0;continue}case`}`:o(`\\}`),++s;continue;case`+`:if(r){++s;continue}t+=c,r=!0,++s;continue;case`*`:case`?`:t+=c,r=!0,++s;continue;default:o(i&&Li(c)?`[${c.toLowerCase()}${c.toUpperCase()}]`:c),s+=c.length;continue}}return t},$i=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),ea=(e,t,n)=>{let r=[],i=0;for(;i<e.length;)if(r.push(e[i]),(t.get(e[i])??n)!==n)++i;else for(;++i<e.length&&(t.get(e[i])??n)===n;)t.get(r.at(-1))!==n&&(r[r.length-1]+=e[i]);return r},ta=e=>e>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,na=e=>Number.isInteger(e)||typeof e==`bigint`,ra=e=>{let t=0;for(let n of e)++t;return t},ia=e=>ca(e.toLowerCase()),aa=(...e)=>Array.prototype.concat.apply([],e),oa=e=>new Map(Object.entries(e)),sa=(e,t)=>{let n=[],r=0;for(let i of e.matchAll(t)){let t=i[0];r<i.index&&n.push(e.slice(r,i.index)),t.length>0&&n.push(t),r=i.index+t.length}return r<e.length&&n.push(e.slice(r)),n},ca=e=>e.replace(/\p{M}/gu,``),la=(e,t,n=[])=>{if(!e||Array.isArray(e)||typeof e!=`object`)return`${t} must be a valid object`;for(let r of n)if(!(r in e))return`${t} must contain a "${r}" property`;return null},ua=e=>e.match(/\S+/g)||[],da=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},fa=class extends da{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},pa=class extends fa{tokenize_chinese_chars(e){let t=[];for(let n=0;n<e.length;++n){let r=e[n];ta(r.charCodeAt(0))?(t.push(` `),t.push(r),t.push(` `)):t.push(r)}return t.join(``)}strip_accents(e){return e.normalize(`NFD`).replace(/\p{Mn}/gu,``)}is_control(e){switch(e){case` `:case`
|
|
4
4
|
`:case`\r`:return!1;default:return/^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(e)}}clean_text(e){let t=[];for(let n of e){let e=n.charCodeAt(0);e===0||e===65533||this.is_control(n)||(/^\s$/.test(n)?t.push(` `):t.push(n))}return t.join(``)}normalize(e){return this.config.clean_text&&(e=this.clean_text(e)),this.config.handle_chinese_chars&&(e=this.tokenize_chinese_chars(e)),this.config.lowercase?(e=e.toLowerCase(),this.config.strip_accents!==!1&&(e=this.strip_accents(e))):this.config.strip_accents&&(e=this.strip_accents(e)),e}},ma=class extends fa{constructor(e){super(e),this.charsmap=e.precompiled_charsmap??null}normalize(e){return e=e.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,``),e=e.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm,` `),e=e.includes(`~`)?e.split(`~`).map(e=>e.normalize(`NFKC`)).join(`~`):e.normalize(`NFKC`),e}},ha=class extends fa{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(e=>Da(e))}normalize(e){return this.normalizers.reduce((e,t)=>t?t.normalize(e):e,e)}},ga=class extends fa{constructor(e){super(e),this.pattern=mi(this.config.pattern??{})}normalize(e){return this.pattern===null?e:e.replaceAll(this.pattern,this.config.content??``)}},_a=class extends fa{constructor(){super(...arguments),this.form=`NFC`}normalize(e){return e=e.normalize(this.form),e}},va=class extends _a{constructor(){super(...arguments),this.form=`NFC`}},ya=class extends _a{constructor(){super(...arguments),this.form=`NFD`}},ba=class extends _a{constructor(){super(...arguments),this.form=`NFKC`}},xa=class extends _a{constructor(){super(...arguments),this.form=`NFKD`}},Sa=class extends fa{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}},Ca=class extends fa{normalize(e){return ca(e)}},wa=class extends fa{normalize(e){return e.toLowerCase()}},Ta=class extends fa{normalize(e){return e=this.config.prepend+e,e}};function Ea(e){if(e===null)return null;switch(e.type){case`BertNormalizer`:return new pa(e);case`Precompiled`:return new ma(e);case`Sequence`:return new ha(e);case`Replace`:return new ga(e);case`NFC`:return new va(e);case`NFD`:return new ya(e);case`NFKC`:return new ba(e);case`NFKD`:return new xa(e);case`Strip`:return new Sa(e);case`StripAccents`:return new Ca(e);case`Lowercase`:return new wa(e);case`Prepend`:return new Ta(e);default:throw Error(`Unknown Normalizer type: ${e.type}`)}}var Da=Ea,Oa=class extends da{pre_tokenize(e,t){return(Array.isArray(e)?e.map(e=>this.pre_tokenize_text(e,t)):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}},ka=(()=>{let e=[...Array.from({length:94},(e,t)=>t+33),...Array.from({length:12},(e,t)=>t+161),...Array.from({length:82},(e,t)=>t+174)],t=e.slice(),n=0;for(let r=0;r<256;++r)e.includes(r)||(e.push(r),t.push(256+n),n+=1);let r=t.map(e=>String.fromCharCode(e));return Object.fromEntries(e.map((e,t)=>[e,r[t]]))})(),Aa=(e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])))(ka),ja=`\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E`,Ma=class extends Oa{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=ka,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){return this.add_prefix_space&&!e.startsWith(` `)&&(e=` `+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(e=>Array.from(this.text_encoder.encode(e),e=>this.byte_encoder[e]).join(``))}},Na=class extends Oa{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},Pa=class extends Oa{constructor(e){super(),this.replacement=e.replacement??`▁`,this.str_rep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??`always`}pre_tokenize_text(e,t){let{section_index:n=void 0}=t??{},r=e.replaceAll(` `,this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme===`always`||this.prepend_scheme===`first`&&n===0)&&(r=this.str_rep+r),[r]}},Fa=class extends Oa{constructor(e){super(),this.config=e,this.pattern=mi(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){return this.pattern===null?[]:this.config.invert?(e.match(this.pattern)||[]).filter(e=>e):this.config.behavior?.toLowerCase()===`removed`?e.split(this.pattern).filter(e=>e):sa(e,this.pattern)}},Ia=class extends Oa{constructor(e){super(),this.config=e,this.pattern=RegExp(`[^${ja}]+|[${ja}]+`,`gu`)}pre_tokenize_text(e){return e.match(this.pattern)||[]}},La=class extends Oa{constructor(e){super(),this.config=e;let t=`[^\\d]+|\\d${this.config.individual_digits?``:`+`}`;this.pattern=new RegExp(t,`gu`)}pre_tokenize_text(e){return e.match(this.pattern)||[]}},Ra=class extends Oa{constructor(){super(),this.pattern=RegExp(`[^\\s${ja}]+|[${ja}]`,`gu`)}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},za=class extends Oa{constructor(e){super(),this.config=e,this.pattern=mi(this.config.pattern??{}),this.content=this.config.content??``}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??``)]}},Ba=class extends Oa{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(e=>Wa(e))}pre_tokenize_text(e,t){return this.tokenizers.reduce((e,n)=>n?n.pre_tokenize(e,t):e,[e])}},Va=class extends Oa{pre_tokenize_text(e){return ua(e)}},Ha=class extends Oa{constructor(e){super(),this.config=e,this._length=e.length}pre_tokenize_text(e){let t=[];for(let n=0;n<e.length;n+=this._length)t.push(e.slice(n,n+this._length));return t}};function Ua(e){if(e===null)return null;switch(e.type){case`BertPreTokenizer`:return new Ra;case`Sequence`:return new Ba(e);case`Whitespace`:return new Na;case`WhitespaceSplit`:return new Va;case`Metaspace`:return new Pa(e);case`ByteLevel`:return new Ma(e);case`Split`:return new Fa(e);case`Punctuation`:return new Ia(e);case`Digits`:return new La(e);case`Replace`:return new za(e);case`FixedLength`:return new Ha(e);default:throw Error(`Unknown PreTokenizer type: ${e.type}`)}}var Wa=Ua,Ga=class extends da{constructor(e){super(),this.config=e,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(e){let t=this.encode(e);return this.fuse_unk&&(t=ea(t,this.tokens_to_ids,this.unk_token_id)),t}},Ka=class extends Ga{constructor(e){super(e),this.max_input_chars_per_word=100,this.tokens_to_ids=oa(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=Array(this.tokens_to_ids.size);for(let[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){let t=[];for(let n of e){let e=[...n];if(e.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let r=!1,i=0,a=[];for(;i<e.length;){let t=e.length,n=null;for(;i<t;){let r=e.slice(i,t).join(``);if(i>0&&(r=this.config.continuing_subword_prefix+r),this.tokens_to_ids.has(r)){n=r;break}--t}if(n===null){r=!0;break}a.push(n),i=t}r?t.push(this.unk_token):t.push(...a)}return t}},qa=class e{constructor(e,t){this.is_leaf=e,this.children=t}static default(){return new e(!1,new Map)}},Ja=class{constructor(){this.root=qa.default()}extend(e){for(let t of e)this.push(t)}push(e){let t=this.root;for(let n of e){let e=t.children.get(n);e===void 0&&(e=qa.default(),t.children.set(n,e)),t=e}t.is_leaf=!0}*common_prefix_search(e,t=0){let n=this.root;if(n===void 0)return;let r=``;for(let i=t;i<e.length;++i){let t=e[i];if(r+=t,n=n.children.get(t),n===void 0)return;n.is_leaf&&(yield r)}}},Ya=class e{constructor(e,t,n,r,i){this.token_id=e,this.node_id=t,this.pos=n,this.length=r,this.score=i,this.prev=null,this.backtrace_score=0}clone(){let t=new e(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},Xa=class{constructor(e,t,n){this.chars=Array.from(e),this.len=this.chars.length,this.bos_token_id=t,this.eos_token_id=n,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let r=new Ya(this.bos_token_id??0,0,0,0,0),i=new Ya(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(i.clone()),this.begin_nodes[this.len].push(i),this.end_nodes[0].push(r)}insert(e,t,n,r){let i=this.nodes.length,a=new Ya(r,i,e,t,n);this.begin_nodes[e].push(a),this.end_nodes[e+t].push(a),this.nodes.push(a)}viterbi(){let e=this.len,t=0;for(;t<=e;){if(this.begin_nodes[t].length==0)return[];for(let e of this.begin_nodes[t]){e.prev=null;let n=0,r=null;for(let i of this.end_nodes[t]){let t=i.backtrace_score+e.score;(r===null||t>n)&&(r=i.clone(),n=t)}if(r!==null)e.prev=r,e.backtrace_score=n;else return[]}++t}let n=[],r=this.begin_nodes[e][0].prev;if(r===null)return[];let i=r.clone();for(;i.prev!==null;)n.push(i.clone()),i=i.clone().prev.clone();return n.reverse(),n}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join(``)}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}};function Za(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;r<e.length;++r)e[r]<t&&(t=e[r],n=r);return[t,n]}var Qa=class extends Ga{constructor(e,t){super(e);let n=e.vocab.length;this.vocab=Array(n),this.scores=Array(n);for(let t=0;t<n;++t)[this.vocab[t],this.scores[t]]=e.vocab[t];this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map((e,t)=>[e,t])),this.bos_token=` `,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=Za(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new Ja,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){let t=e.chars,n=0;for(;n<t.length;){let r=!1,i=this.trie.common_prefix_search(t,n);for(let t of i){let i=this.tokens_to_ids.get(t),a=this.scores[i],o=ra(t);e.insert(n,o,a,i),!r&&o===1&&(r=!0)}r||e.insert(n,1,this.unk_score,this.unk_token_id),n+=1}}tokenize(e){let t=new Xa(e,this.bos_token_id,this.eos_token_id);return this.populate_nodes(t),t.tokens()}encode(e){let t=[];for(let n of e){let e=this.tokenize(n);t.push(...e)}return t}},$a=class{constructor(e=(e,t)=>e>t,t=1/0){this._heap=[],this._comparator=e,this._max_size=t}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(let t of e)if(this.size<this._max_size)this._heap.push(t),this._sift_up();else{let e=this._smallest();this._comparator(t,this._heap[e])&&(this._heap[e]=t,this._sift_up_from(e))}return this.size}pop(){let e=this.peek(),t=this.size-1;return t>0&&this._swap(0,t),this._heap.pop(),this._sift_down(),e}replace(e){let t=this.peek();return this._heap[0]=e,this._sift_down(),t}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){let n=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=n}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(e){for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_sift_down(){let e=0;for(;this._left(e)<this.size&&this._greater(this._left(e),e)||this._right(e)<this.size&&this._greater(this._right(e),e);){let t=this._right(e)<this.size&&this._greater(this._right(e),this._left(e))?this._right(e):this._left(e);this._swap(e,t),e=t}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},eo=class{constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){this.cache.has(e)&&this.cache.delete(e),this.cache.set(e,t),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},to=class extends Ga{constructor(e){super(e),this.tokens_to_ids=oa(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=Array(this.tokens_to_ids.size);for(let[e,t]of this.tokens_to_ids)this.vocab[t]=e;let t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map(e=>e.split(` `,2)),this.bpe_ranks=new Map(this.merges.map((e,t)=>[JSON.stringify(e),t])),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new eo(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(e){if(e.length===0)return[];let t=this.cache.get(e);if(t!==void 0)return t;let n=Array.from(e);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){let e=new $a((e,t)=>e.score<t.score),t={token:n[0],bias:0,prev:null,next:null},i=t;for(let t=1;t<n.length;++t){let r={bias:t/n.length,token:n[t],prev:i,next:null};i.next=r,this.add_node(e,i),i=r}for(;!e.is_empty();){let n=e.pop();if(n.deleted||!n.next||n.next.deleted)continue;if(n.deleted=!0,n.next.deleted=!0,n.prev){let e={...n.prev};n.prev.deleted=!0,n.prev=e,e.prev?e.prev.next=e:t=e}let r={token:n.token+n.next.token,bias:n.bias,prev:n.prev,next:n.next.next};r.prev?(r.prev.next=r,this.add_node(e,r.prev)):t=r,r.next&&(r.next.prev=r,this.add_node(e,r))}for(let e=t;e!==null;e=e.next)r.push(e.token)}else r=n;if(this.continuing_subword_suffix)for(let e=0;e<r.length-1;++e)r[e]+=this.continuing_subword_suffix;return e.length<this.max_length_to_cache&&this.cache.put(e,r),r}add_node(e,t){let n=this.bpe_ranks.get(JSON.stringify([t.token,t.next.token]));n!==void 0&&(t.score=n+t.bias,e.push(t))}encode(e){let t=[];for(let n of e){if(this.ignore_merges&&this.tokens_to_ids.has(n)){t.push(n);continue}let e=this.bpe(n);for(let n of e)if(this.tokens_to_ids.has(n))t.push(n);else if(this.byte_fallback){let e=Array.from(this.text_encoder.encode(n)).map(e=>`<0x${e.toString(16).toUpperCase().padStart(2,`0`)}>`);e.every(e=>this.tokens_to_ids.has(e))?t.push(...e):this.unk_token!=null&&t.push(this.unk_token)}else this.unk_token!=null&&t.push(this.unk_token)}return t}},no=class extends Ga{constructor(e,t){super(e);let n=e.vocab;this.tokens_to_ids=oa(t.target_lang?n[t.target_lang]:n),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=Array(this.tokens_to_ids.size);for(let[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){return e}};function ro(e,t){switch(e.type){case`WordPiece`:return new Ka(e);case`Unigram`:return new Qa(e,t.eos_token);case`BPE`:return new to(e);default:if(e.vocab)return Array.isArray(e.vocab)?new Qa(e,t.eos_token):Object.hasOwn(e,`continuing_subword_prefix`)&&Object.hasOwn(e,`unk_token`)?Object.hasOwn(e,`merges`)?new to(e):new Ka(e):new no(e,{target_lang:t.target_lang,bos_token:t.bos_token,eos_token:t.eos_token,pad_token:t.pad_token,unk_token:t.unk_token});throw Error(`Unknown TokenizerModel type: ${e?.type}`)}}var io=ro,ao=class extends da{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},oo=class extends ao{post_process(e,t=null,n=!0){let r=t===null?this.config.single:this.config.pair,i=[],a=[];for(let o of r)`SpecialToken`in o?n&&(i.push(o.SpecialToken.id),a.push(o.SpecialToken.type_id)):`Sequence`in o&&(o.Sequence.id===`A`?(i=aa(i,e),a=aa(a,Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id===`B`&&(i=aa(i,t),a=aa(a,Array(t.length).fill(o.Sequence.type_id))));return{tokens:i,token_type_ids:a}}},so=class extends ao{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},co=class extends ao{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,n=!0){n&&(e=aa([this.cls[0]],e,[this.sep[0]]));let r=Array(e.length).fill(0);if(t){let i=[],a=n?[this.sep[0]]:[];e=aa(e,i,t,a),r=aa(r,Array(t.length+i.length+a.length).fill(1))}return{tokens:e,token_type_ids:r}}},lo=class extends ao{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,n=!0){n&&(e=aa([this.cls[0]],e,[this.sep[0]]));let r=Array(e.length).fill(0);if(t){let i=n?[this.sep[0]]:[],a=n?[this.sep[0]]:[];e=aa(e,i,t,a),r=aa(r,Array(t.length+i.length+a.length).fill(1))}return{tokens:e,token_type_ids:r}}},uo=class extends ao{constructor(e){super(e),this.processors=(e.processors??[]).map(e=>po(e))}post_process(e,t=null,n=!0){let r={tokens:e,tokens_pair:t};for(let e of this.processors)r=e.post_process(r.tokens,r.tokens_pair,n);return r}};function fo(e){if(e===null)return null;switch(e.type){case`TemplateProcessing`:return new oo(e);case`ByteLevel`:return new so(e);case`BertProcessing`:return new co(e);case`RobertaProcessing`:return new lo(e);case`Sequence`:return new uo(e);default:throw Error(`Unknown PostProcessor type: ${e.type}`)}}var po=fo,mo=class extends da{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=`trim_offsets`in e&&e.trim_offsets}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join(``)}},ho=class extends mo{constructor(e){super(e),this.byte_decoder=Aa,this.text_decoder=new TextDecoder(`utf-8`,{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){let t=e.join(``),n=new Uint8Array([...t].map(e=>this.byte_decoder[e]));return this.text_decoder.decode(n)}decode_chain(e){let t=[],n=[];for(let r of e)this.added_tokens.find(e=>e.content===r)===void 0?n.push(r):(n.length>0&&(t.push(this.convert_tokens_to_string(n)),n=[]),t.push(r));return n.length>0&&t.push(this.convert_tokens_to_string(n)),t}},go=class extends mo{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((e,t)=>{if(t!==0){let t=this.config.prefix;e=t&&e.startsWith(t)?e.replace(t,``):` `+e}return this.cleanup&&(e=pi(e)),e})}},_o=class extends mo{constructor(e){super(e),this.replacement=e.replacement??`▁`}decode_chain(e){let t=[];for(let n=0;n<e.length;++n){let r=e[n].replaceAll(this.replacement,` `);n==0&&r.startsWith(` `)&&(r=r.substring(1)),t.push(r)}return t}},vo=class extends mo{constructor(e){super(e),this.suffix=e.suffix??``}decode_chain(e){return e.map((t,n)=>t.replaceAll(this.suffix,n===e.length-1?``:` `))}},yo=class extends mo{constructor(e){super(e),this.pad_token=e.pad_token??``,this.word_delimiter_token=e.word_delimiter_token??``,this.cleanup=e.cleanup}convert_tokens_to_string(e){if(e.length===0)return``;let t=[e[0]];for(let n=1;n<e.length;++n)e[n]!==t.at(-1)&&t.push(e[n]);let n=t.filter(e=>e!==this.pad_token).join(``);return this.cleanup&&(n=pi(n).replaceAll(this.word_delimiter_token,` `).trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}},bo=class extends mo{constructor(e){super(e),this.decoders=(e.decoders??[]).map(e=>Eo(e))}decode_chain(e){return this.decoders.reduce((e,t)=>t.decode_chain(e),e)}},xo=class extends mo{constructor(e){super(e),this.pattern=mi(this.config.pattern)}decode_chain(e){let t=this.config.content??``,n=this.pattern;return n===null?e:e.map(e=>e.replaceAll(n,t))}},So=class extends mo{decode_chain(e){return[e.join(``)]}},Co=class extends mo{constructor(e){super(e),this.content=e.content??``,this.start=e.start??0,this.stop=e.stop??0}decode_chain(e){return e.map(e=>{let t=0;for(let n=0;n<this.start&&e[n]===this.content;++n)t=n+1;let n=e.length;for(let t=0;t<this.stop;++t){let r=e.length-t-1;if(e[r]===this.content)n=r;else break}return e.slice(t,n)})}},wo=class extends mo{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){let t=[],n=[];for(let r of e){let e=null;if(r.length===6&&r.startsWith(`<0x`)&&r.endsWith(`>`)){let t=parseInt(r.slice(3,5),16);isNaN(t)||(e=t)}if(e!==null)n.push(e);else{if(n.length>0){let e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}t.push(r)}}if(n.length>0){let e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}return t}};function To(e){if(e===null)return null;switch(e.type){case`ByteLevel`:return new ho(e);case`WordPiece`:return new go(e);case`Metaspace`:return new _o(e);case`BPEDecoder`:return new vo(e);case`CTC`:return new yo(e);case`Sequence`:return new bo(e);case`Replace`:return new xo(e);case`Fuse`:return new So(e);case`Strip`:return new Co(e);case`ByteFallback`:return new wo(e);default:throw Error(`Unknown Decoder type: ${e.type}`)}}var Eo=To,Do=class{constructor(e,t){let n=la(e,`Tokenizer`,[`model`,`decoder`,`post_processor`,`pre_tokenizer`,`normalizer`]);if(n)throw Error(n);let r=la(t,`Config`);if(r)throw Error(r);this.tokenizer=e,this.config=t,this.normalizer=Da(this.tokenizer.normalizer),this.pre_tokenizer=Wa(this.tokenizer.pre_tokenizer),this.model=io(this.tokenizer.model,this.config),this.post_processor=po(this.tokenizer.post_processor),this.decoder=Eo(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let i=[],a=[];this.added_tokens_map=new Map;for(let e of this.tokenizer.added_tokens){let t=new di(e);if(this.added_tokens.push(t),this.model.tokens_to_ids.set(t.content,t.id),this.model.vocab[t.id]=t.content,t.special&&(this.special_tokens.push(t.content),this.all_special_ids.push(t.id)),this.added_tokens_map.set(t.content,t),t.normalized&&this.normalizer!==null){let e=this.normalizer(t.content);a.push(e),this.added_tokens_map.set(e,t)}else i.push(t.content)}(this.config.additional_special_tokens??[]).forEach(e=>{this.special_tokens.includes(e)||this.special_tokens.push(e)}),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 ui(i),this.splitter_normalized=new ui(a),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){let{tokens:i,token_type_ids:a}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:n}),o=i.map(e=>this.added_tokens_map.get(e)?.id??this.model.tokens_to_ids.get(e)??this.model.unk_token_id),s={ids:o,tokens:i,attention_mask:Array(o.length).fill(1)};return r&&a&&(s.token_type_ids=a),s}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!na(e[0]))throw Error(`token_ids must be a non-empty array of integers.`);let n=e.map(e=>this.model.vocab[Number(e)]??this.model.unk_token);t.skip_special_tokens&&(n=n.filter(e=>!this.special_tokens.includes(e)));let r=this.decoder?this.decoder(n):n.join(` `);return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix,` `),t.skip_special_tokens&&(r=r.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(r=pi(r)),r}tokenize(e,{text_pair:t=null,add_special_tokens:n=!1}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:n}).tokens}encode_text(e){if(e===null)return null;let t=this.splitter_unnormalized.split(e);return t.forEach((e,n)=>{let r=this.added_tokens_map.get(e);r&&(r.lstrip&&n>0&&(t[n-1]=t[n-1].trimEnd()),r.rstrip&&n<t.length-1&&(t[n+1]=t[n+1].trimStart()))}),t.flatMap((e,t)=>{if(e.length===0)return[];if(this.added_tokens_map.has(e))return[e];if(this.remove_space===!0&&(e=e.trim().split(/\s+/).join(` `)),this.do_lowercase_and_remove_accent&&(e=ia(e)),this.normalizer!==null&&(e=this.normalizer(e)),e.length===0)return[];let n=this.splitter_normalized.split(e);return n.forEach((e,t)=>{let r=this.added_tokens_map.get(e);r&&(r.lstrip&&t>0&&(n[t-1]=n[t-1].trimEnd()),r.rstrip&&t<n.length-1&&(n[t+1]=n[t+1].trimStart()))}),n.flatMap(e=>{if(e.length===0)return[];if(this.added_tokens_map.has(e))return[e];let n=this.pre_tokenizer===null?[e]:this.pre_tokenizer(e,{section_index:t});return this.model(n)})})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:n=!0}){let r=this.encode_text(e),i=this.encode_text(t||null);return this.post_processor?this.post_processor(r,i,n):{tokens:aa(r??[],i??[])}}token_to_id(e){return this.model.tokens_to_ids.get(e)}id_to_token(e){return this.model.vocab[e]}get_added_tokens_decoder(){let e=new Map;for(let t of this.added_tokens)e.set(t.id,t);return e}get_vocab(e=!0){let t=new Map;for(let n=0;n<this.model.vocab.length;++n){let r=this.model.vocab[n];(e||!this.added_tokens_map.has(r))&&t.set(r,n)}return t}},Oo=Object.defineProperty,ko=(e,t,n)=>t in e?Oo(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ao=(e,t,n)=>(ko(e,typeof t==`symbol`?t:t+``,n),n),j=Object.freeze({Text:`Text`,NumericLiteral:`NumericLiteral`,StringLiteral:`StringLiteral`,Identifier:`Identifier`,Equals:`Equals`,OpenParen:`OpenParen`,CloseParen:`CloseParen`,OpenStatement:`OpenStatement`,CloseStatement:`CloseStatement`,OpenExpression:`OpenExpression`,CloseExpression:`CloseExpression`,OpenSquareBracket:`OpenSquareBracket`,CloseSquareBracket:`CloseSquareBracket`,OpenCurlyBracket:`OpenCurlyBracket`,CloseCurlyBracket:`CloseCurlyBracket`,Comma:`Comma`,Dot:`Dot`,Colon:`Colon`,Pipe:`Pipe`,CallOperator:`CallOperator`,AdditiveBinaryOperator:`AdditiveBinaryOperator`,MultiplicativeBinaryOperator:`MultiplicativeBinaryOperator`,ExponentiationBinaryOperator:`ExponentiationBinaryOperator`,ComparisonBinaryOperator:`ComparisonBinaryOperator`,UnaryOperator:`UnaryOperator`,Comment:`Comment`}),jo=class{constructor(e,t){this.value=e,this.type=t}};function Mo(e){return/\w/.test(e)}function No(e){return/[0-9]/.test(e)}function Po(e){return/\s/.test(e)}var Fo=[[`{%`,j.OpenStatement],[`%}`,j.CloseStatement],[`{{`,j.OpenExpression],[`}}`,j.CloseExpression],[`(`,j.OpenParen],[`)`,j.CloseParen],[`{`,j.OpenCurlyBracket],[`}`,j.CloseCurlyBracket],[`[`,j.OpenSquareBracket],[`]`,j.CloseSquareBracket],[`,`,j.Comma],[`.`,j.Dot],[`:`,j.Colon],[`|`,j.Pipe],[`<=`,j.ComparisonBinaryOperator],[`>=`,j.ComparisonBinaryOperator],[`==`,j.ComparisonBinaryOperator],[`!=`,j.ComparisonBinaryOperator],[`<`,j.ComparisonBinaryOperator],[`>`,j.ComparisonBinaryOperator],[`+`,j.AdditiveBinaryOperator],[`-`,j.AdditiveBinaryOperator],[`~`,j.AdditiveBinaryOperator],[`**`,j.ExponentiationBinaryOperator],[`*`,j.MultiplicativeBinaryOperator],[`//`,j.MultiplicativeBinaryOperator],[`/`,j.MultiplicativeBinaryOperator],[`%`,j.MultiplicativeBinaryOperator],[`=`,j.Equals]],Io=new Map([[`n`,`
|
package/dist/studio/index.html
CHANGED
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
<meta name="color-scheme" content="dark" />
|
|
7
7
|
<title>AgentPhoto Studio</title>
|
|
8
8
|
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Cdefs%3E%3ClinearGradient id='g' x1='0' y1='0' x2='0' y2='1'%3E%3Cstop offset='0' stop-color='%232a2a30'/%3E%3Cstop offset='1' stop-color='%230c0c0f'/%3E%3C/linearGradient%3E%3ClinearGradient id='d' x1='0' y1='0' x2='1' y2='1'%3E%3Cstop offset='0' stop-color='%237aa5ff'/%3E%3Cstop offset='1' stop-color='%233d6bff'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect width='32' height='32' rx='7.5' fill='url(%23g)'/%3E%3Crect x='7' y='9' width='18' height='14' rx='2.5' fill='none' stroke='%23fff' stroke-width='2.2'/%3E%3Cpath d='M9 21l5-5 3 3 2.5-2.5L23 20' fill='none' stroke='%23fff' stroke-width='1.8' stroke-linejoin='round'/%3E%3Ccircle cx='20.5' cy='13.5' r='2' fill='url(%23d)'/%3E%3C/svg%3E" />
|
|
9
|
-
<script type="module" crossorigin src="./assets/index-
|
|
10
|
-
<link rel="stylesheet" crossorigin href="./assets/index-
|
|
9
|
+
<script type="module" crossorigin src="./assets/index-D3Iw5q8v.js"></script>
|
|
10
|
+
<link rel="stylesheet" crossorigin href="./assets/index-CmOzzoXv.css">
|
|
11
11
|
</head>
|
|
12
12
|
<body>
|
|
13
13
|
<div id="root"></div>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
[{"id":"avatar-pro","title":"Professional avatar","description":"Round profile picture: subject cut out (run remove_background) on a soft brand-colour backdrop, gently retouched.","category":"portrait","tags":["avatar","linkedin","profile","portrait","cutout"],"width":800,"height":800,"slot":"photo","files":["assets/masks/photo-cutout.png","photo.json","preview.jpg","template.json"]},{"id":"og-article","title":"Article link preview","description":"1200×630 Open Graph card: photo on the right fading into a solid panel, headline and site name on the left.","category":"web","tags":["og","blog","link","social"],"width":1200,"height":630,"slot":"photo","files":["photo.json","preview.jpg","template.json"]},{"id":"polaroid","title":"Polaroid memory","description":"Instant-photo card tilted on a warm paper background, vintage look and a handwritten caption.","category":"social","tags":["polaroid","vintage","memory","handwriting"],"width":1080,"height":1350,"slot":"photo","files":["photo.json","preview.jpg","template.json"]},{"id":"product-white","title":"Product on white","description":"E-commerce square: product cut out (run remove_background on the photo layer), centred on a soft white backdrop with a contact shadow.","category":"product","tags":["ecommerce","packshot","cutout","white"],"width":2000,"height":2000,"slot":"photo","files":["assets/masks/photo-cutout.png","photo.json","preview.jpg","template.json"]},{"id":"sale-banner","title":"Sale banner","description":"Wide web hero banner: gradient background, photo fading in from the right, big discount and a starburst badge.","category":"ad","tags":["banner","sale","ecommerce","hero"],"width":1920,"height":600,"slot":"photo","files":["photo.json","preview.jpg","template.json"]},{"id":"social-quote","title":"Quote post","description":"Square post: photo in the background, darkened and softened, with an elegant serif quote and author.","category":"social","tags":["instagram","quote","square","serif"],"width":1080,"height":1080,"slot":"photo","files":["photo.json","preview.jpg","template.json"]},{"id":"story-promo","title":"Story promo","description":"9:16 story / reel cover: full-bleed photo, dark gradient at the bottom, big title and a call-to-action pill.","category":"social","tags":["story","reel","tiktok","vertical","promo"],"width":1080,"height":1920,"slot":"photo","files":["photo.json","preview.jpg","template.json"]},{"id":"youtube-thumbnail","title":"YouTube thumbnail","description":"Bold 16:9 thumbnail: big condensed title, subject with a white outline (run remove_background on the photo layer for a cut-out), punchy gradient.","category":"thumbnail","tags":["youtube","video","cutout","bold"],"width":1280,"height":720,"slot":"photo","files":["photo.json","preview.jpg","template.json"]}]
|
|
1
|
+
[{"id":"avatar-pro","title":"Professional avatar","description":"Round profile picture: subject cut out (run remove_background) on a soft brand-colour backdrop, gently retouched.","category":"portrait","tags":["avatar","linkedin","profile","portrait","cutout"],"width":800,"height":800,"slot":"photo","files":["assets/masks/photo-cutout.png","photo.json","preview.jpg","template.json"]},{"id":"og-article","title":"Article link preview","description":"1200×630 Open Graph card: photo on the right fading into a solid panel, headline and site name on the left.","category":"web","tags":["og","blog","link","social"],"width":1200,"height":630,"slot":"photo","files":["photo.json","preview.jpg","template.json"]},{"id":"polaroid","title":"Polaroid memory","description":"Instant-photo card tilted on a warm paper background, vintage look and a handwritten caption.","category":"social","tags":["polaroid","vintage","memory","handwriting"],"width":1080,"height":1350,"slot":"photo","files":["photo.json","preview.jpg","template.json"]},{"id":"product-white","title":"Product on white","description":"E-commerce square: product cut out (run remove_background on the photo layer), centred on a soft white backdrop with a contact shadow. With your own photo, the first cut-out also scales and places the product on the floor shadow.","category":"product","tags":["ecommerce","packshot","cutout","white"],"width":2000,"height":2000,"slot":"photo","subjectArea":{"x":550,"y":470,"width":900,"height":800,"anchor":"bottom"},"files":["assets/masks/photo-cutout.png","photo.json","preview.jpg","template.json"]},{"id":"sale-banner","title":"Sale banner","description":"Wide web hero banner: gradient background, photo fading in from the right, big discount and a starburst badge.","category":"ad","tags":["banner","sale","ecommerce","hero"],"width":1920,"height":600,"slot":"photo","files":["photo.json","preview.jpg","template.json"]},{"id":"social-quote","title":"Quote post","description":"Square post: photo in the background, darkened and softened, with an elegant serif quote and author.","category":"social","tags":["instagram","quote","square","serif"],"width":1080,"height":1080,"slot":"photo","files":["photo.json","preview.jpg","template.json"]},{"id":"story-promo","title":"Story promo","description":"9:16 story / reel cover: full-bleed photo, dark gradient at the bottom, big title and a call-to-action pill.","category":"social","tags":["story","reel","tiktok","vertical","promo"],"width":1080,"height":1920,"slot":"photo","files":["photo.json","preview.jpg","template.json"]},{"id":"youtube-thumbnail","title":"YouTube thumbnail","description":"Bold 16:9 thumbnail: big condensed title, subject with a white outline (run remove_background on the photo layer for a cut-out), punchy gradient.","category":"thumbnail","tags":["youtube","video","cutout","bold"],"width":1280,"height":720,"slot":"photo","files":["photo.json","preview.jpg","template.json"]}]
|
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{ "id": "product-white", "title": "Product on white", "description": "E-commerce square: product cut out (run remove_background on the photo layer), centred on a soft white backdrop with a contact shadow.", "category": "product", "tags": ["ecommerce", "packshot", "cutout", "white"], "width": 2000, "height": 2000, "slot": "photo" }
|
|
1
|
+
{ "id": "product-white", "title": "Product on white", "description": "E-commerce square: product cut out (run remove_background on the photo layer), centred on a soft white backdrop with a contact shadow. With your own photo, the first cut-out also scales and places the product on the floor shadow.", "category": "product", "tags": ["ecommerce", "packshot", "cutout", "white"], "width": 2000, "height": 2000, "slot": "photo", "subjectArea": { "x": 550, "y": 470, "width": 900, "height": 800, "anchor": "bottom" } }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fleox/agentphoto",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "The photo studio your AI agent can run: retouch, layers, masks, background removal, subject cutout, filters and looks as a non-destructive JSON document, previewed headless and exported as PNG / JPEG / WebP. With a Studio to finish by hand. No server, no account.",
|
|
6
6
|
"license": "SEE LICENSE IN LICENSE",
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
"check:docs": "node scripts/build-cli-docs.mjs --check",
|
|
37
37
|
"hermes:build": "node scripts/build-hermes.mjs",
|
|
38
38
|
"check:hermes": "node scripts/build-hermes.mjs --check && python3 -m unittest discover -s hermes/tests",
|
|
39
|
-
"version": "node scripts/sync-version.mjs && npm run build && node scripts/build-hermes.mjs && node scripts/build-cli-docs.mjs && git add -A plugin hermes .claude-plugin README.md docs",
|
|
39
|
+
"version": "node scripts/sync-version.mjs && npm run build && node scripts/build-hermes.mjs && node scripts/build-cli-docs.mjs && git add -A plugin hermes .claude-plugin README.md AGENTS.md docs",
|
|
40
40
|
"prepublishOnly": "npm run typecheck && npm test && npm run build && npm run check:skills"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentphoto",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "Skills to run AgentPhoto (the photo studio your AI agent can run): retouch photos (colour and light correction, looks, portrait retouch, crop and straighten), remove backgrounds and make masks with local AI, build social / marketing visuals from templates with text, shapes and layer effects, look at headless renders to check every change, and export PNG / JPEG / WebP in every size. Non-destructive JSON layer stack, nothing uploaded, no server, no account.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "fleox"
|
|
@@ -4,7 +4,7 @@ description: Remove the background of a photo and work with masks in AgentPhoto,
|
|
|
4
4
|
license: PolyForm-Noncommercial-1.0.0
|
|
5
5
|
compatibility: Requires Node.js 22+ and Google Chrome (or Chromium/Edge/Brave). AI models (25-170 MB) download once into ~/.cache/agentphoto/models.
|
|
6
6
|
metadata:
|
|
7
|
-
version: "0.1.
|
|
7
|
+
version: "0.1.1"
|
|
8
8
|
repository: "https://github.com/fleox/agentphoto"
|
|
9
9
|
allowed-tools: Bash Read Write
|
|
10
10
|
---
|
|
@@ -17,18 +17,23 @@ A cut-out is **non-destructive**: the AI writes a mask PNG to `assets/masks/` an
|
|
|
17
17
|
|
|
18
18
|
**Language:** talk to the user in their language; keep commands, ids and files in English.
|
|
19
19
|
|
|
20
|
-
Every command is `npx -y @fleox/agentphoto@0.1.
|
|
20
|
+
Every command is `npx -y @fleox/agentphoto@0.1.1 <command> --json` with `--project <dir>`. Read `error.hint` when `ok` is false. Basics (projects, render, filters): skill `agentphoto-retouch`.
|
|
21
21
|
|
|
22
22
|
## 1. Remove the background
|
|
23
23
|
|
|
24
24
|
```bash
|
|
25
|
-
npx -y @fleox/agentphoto@0.1.
|
|
26
|
-
npx -y @fleox/agentphoto@0.1.
|
|
27
|
-
npx -y @fleox/agentphoto@0.1.
|
|
25
|
+
npx -y @fleox/agentphoto@0.1.1 new my-photo --image ./photo.jpg --json
|
|
26
|
+
npx -y @fleox/agentphoto@0.1.1 remove-bg photo --project my-photo --json
|
|
27
|
+
npx -y @fleox/agentphoto@0.1.1 render --project my-photo --json
|
|
28
28
|
```
|
|
29
29
|
|
|
30
30
|
- Models: `rmbg-1.4` (default: products, people, animals, objects) or `--model modnet` (portraits only, soft hair). `models list` shows what is cached.
|
|
31
|
-
- `data.subject` is the kept area in canvas px `{ x, y, width, height }` (null = nothing found): use it to recentre and
|
|
31
|
+
- `data.subject` is the kept area in canvas px `{ x, y, width, height }` (null = nothing found): use it to recentre, rescale and crop.
|
|
32
|
+
- Recentre and rescale the cut-out in one op: `fitLayer` scales the layer (uniformly) and moves it so `subject` fits `box` (canvas px), aligned on `anchor` (`center`, `bottom` = standing on a floor line, `top`, `left`…). Example on a 1600×900 canvas with a 10 % margin:
|
|
33
|
+
```bash
|
|
34
|
+
npx -y @fleox/agentphoto@0.1.1 doc patch --project my-photo --json '[{"op":"fitLayer","id":"photo","subject":{"x":881,"y":306,"width":475,"height":329},"box":{"x":160,"y":90,"width":1280,"height":720},"anchor":"center"}]'
|
|
35
|
+
```
|
|
36
|
+
Or let `remove-bg` do it: `--fit x,y,width,height --anchor bottom`. Scaling a small subject up a lot gives an `upscaled` warning in `check`: the source has too few pixels for that size.
|
|
32
37
|
- `--threshold 128` gives a hard edge (products with clean outlines); the default soft alpha is best for hair and fur. `--feather 2` softens a jagged edge.
|
|
33
38
|
- An empty canvas shows as transparent (white in the preview): export PNG or WebP to keep the transparency.
|
|
34
39
|
|
|
@@ -39,21 +44,21 @@ npx -y @fleox/agentphoto@0.1.0 render --project my-photo --json
|
|
|
39
44
|
On a colour or gradient, with a soft drop shadow, in one command:
|
|
40
45
|
|
|
41
46
|
```bash
|
|
42
|
-
npx -y @fleox/agentphoto@0.1.
|
|
47
|
+
npx -y @fleox/agentphoto@0.1.1 remove-bg photo --background "#ffffff" --shadow --project my-photo --json
|
|
43
48
|
```
|
|
44
49
|
|
|
45
50
|
It adds a fill layer `photo-background` under the subject. Change it later like any layer:
|
|
46
51
|
|
|
47
52
|
```bash
|
|
48
|
-
npx -y @fleox/agentphoto@0.1.
|
|
53
|
+
npx -y @fleox/agentphoto@0.1.1 layer update photo-background --set 'fill={"type":"radial","stops":["#ffffff","#e8edf3"]}' --project my-photo --json
|
|
49
54
|
```
|
|
50
55
|
|
|
51
56
|
On another photo: import it as a layer and move it under the subject, then match the light (`temperature`, `exposure` on the subject) so it does not look pasted:
|
|
52
57
|
|
|
53
58
|
```bash
|
|
54
|
-
npx -y @fleox/agentphoto@0.1.
|
|
55
|
-
npx -y @fleox/agentphoto@0.1.
|
|
56
|
-
npx -y @fleox/agentphoto@0.1.
|
|
59
|
+
npx -y @fleox/agentphoto@0.1.1 assets add ./beach.jpg --license proprietary --add-layer --layer-id backdrop --project my-photo --json
|
|
60
|
+
npx -y @fleox/agentphoto@0.1.1 layer move backdrop --below photo --project my-photo --json
|
|
61
|
+
npx -y @fleox/agentphoto@0.1.1 filter add backdrop --type blur --set radius=6 --project my-photo --json
|
|
57
62
|
```
|
|
58
63
|
|
|
59
64
|
A slight blur on the new background sells the depth. The built-in CC0 photos (`assets library --kind image`) work as `"src": "library:<id>"`.
|
|
@@ -63,18 +68,18 @@ A slight blur on the new background sells the depth. The built-in CC0 photos (`a
|
|
|
63
68
|
1. `remove-bg photo --background "#ffffff" --shadow --threshold 128` (clean edge).
|
|
64
69
|
2. Crop a square around `data.subject` with about 15 % margin on each side: side = max(width, height) / 0.7, centred on the subject. Example for `subject` = `{ "x": 881, "y": 306, "width": 475, "height": 329 }`:
|
|
65
70
|
```bash
|
|
66
|
-
npx -y @fleox/agentphoto@0.1.
|
|
71
|
+
npx -y @fleox/agentphoto@0.1.1 doc patch --project my-photo --json '[{"op":"crop","x":769,"y":121,"width":700,"height":700}]'
|
|
67
72
|
```
|
|
68
73
|
3. Tune the shadow so it reads as contact, not as a halo: `layer update photo --set effects.dropShadow.opacity=0.28 --set effects.dropShadow.distance=14 --set effects.dropShadow.blur=22`.
|
|
69
|
-
4. Render, zoom on the edges, `check`, then export at the size the shop wants (`export --format jpeg --width 2000`, skill `agentphoto-publish`). The template `product-white` (`new shop --template product-white --image ./mug.jpg`) gives a ready backdrop and floor shadow: run `remove-bg photo` on it.
|
|
74
|
+
4. Render, zoom on the edges, `check`, then export at the size the shop wants (`export --format jpeg --width 2000`, skill `agentphoto-publish`). The template `product-white` (`new shop --template product-white --image ./mug.jpg`) gives a ready backdrop and floor shadow: run `remove-bg photo` on it — the first cut-out of your photo also scales the product and stands it on the floor shadow (`data.fitted` says where; `--fit none` keeps the layer where it is).
|
|
70
75
|
|
|
71
76
|
## 4. Check and refine the edge
|
|
72
77
|
|
|
73
78
|
Always zoom on difficult edges (hair, fur, fingers, transparent glass, the handle of a mug) at 1:1:
|
|
74
79
|
|
|
75
80
|
```bash
|
|
76
|
-
npx -y @fleox/agentphoto@0.1.
|
|
77
|
-
npx -y @fleox/agentphoto@0.1.
|
|
81
|
+
npx -y @fleox/agentphoto@0.1.1 render --project my-photo --zoom 420,220,200,200 --json
|
|
82
|
+
npx -y @fleox/agentphoto@0.1.1 render --project my-photo --layer photo --json
|
|
78
83
|
```
|
|
79
84
|
|
|
80
85
|
| What you see | Fix |
|
|
@@ -89,10 +94,10 @@ npx -y @fleox/agentphoto@0.1.0 render --project my-photo --layer photo --json
|
|
|
89
94
|
`mask generate` makes a mask from pixels. Coordinates are **layer pixels** (from the layer's top-left, before rotation; for a full-canvas photo that is canvas px). `--target copy` duplicates the layer and masks the copy (the original stays whole), `--invert` keeps everything except the selection.
|
|
90
95
|
|
|
91
96
|
```bash
|
|
92
|
-
npx -y @fleox/agentphoto@0.1.
|
|
93
|
-
npx -y @fleox/agentphoto@0.1.
|
|
94
|
-
npx -y @fleox/agentphoto@0.1.
|
|
95
|
-
npx -y @fleox/agentphoto@0.1.
|
|
97
|
+
npx -y @fleox/agentphoto@0.1.1 mask generate photo --method points --points '[[700,420,1],[760,600,1],[1200,200,0]]' --target copy --copy-id subject --project my-photo --json
|
|
98
|
+
npx -y @fleox/agentphoto@0.1.1 mask generate photo --method box --box 400,200,1200,900 --target copy --copy-id boxed --project my-photo --json
|
|
99
|
+
npx -y @fleox/agentphoto@0.1.1 mask generate photo --method color --color "#579bd6" --tolerance 25 --target copy --copy-id sky --project my-photo --json
|
|
100
|
+
npx -y @fleox/agentphoto@0.1.1 mask generate photo --method subject --invert --feather 20 --target copy --copy-id bg --project my-photo --json
|
|
96
101
|
```
|
|
97
102
|
|
|
98
103
|
Then change only that region with filters on the copy:
|
|
@@ -106,9 +111,9 @@ Pick colours for `--method color` from `analyze` (`dominant`). Points: `1` = inc
|
|
|
106
111
|
Hand-made masks (no AI) with `mask set`: an ellipse or rect with `feather` (vignette, spotlight), or a gradient (fade a photo into a panel):
|
|
107
112
|
|
|
108
113
|
```bash
|
|
109
|
-
npx -y @fleox/agentphoto@0.1.
|
|
110
|
-
npx -y @fleox/agentphoto@0.1.
|
|
111
|
-
npx -y @fleox/agentphoto@0.1.
|
|
114
|
+
npx -y @fleox/agentphoto@0.1.1 mask set photo --mask '{"shape":"ellipse","x":200,"y":100,"width":1200,"height":860,"feather":120}' --project my-photo --json
|
|
115
|
+
npx -y @fleox/agentphoto@0.1.1 mask set photo --mask '{"gradient":{"type":"linear","angle":0,"stops":["black","white"]}}' --project my-photo --json
|
|
116
|
+
npx -y @fleox/agentphoto@0.1.1 mask clear photo --project my-photo --json
|
|
112
117
|
```
|
|
113
118
|
|
|
114
119
|
A mask object also takes `invert`, `feather` (px), `density` (0..1: how much it hides) and `enabled`. Shape and gradient masks on image / text / shape layers are in layer pixels.
|
|
@@ -116,9 +121,9 @@ A mask object also takes `invert`, `feather` (px), `density` (0..1: how much it
|
|
|
116
121
|
## 6. Sticker (transparent PNG with an outline)
|
|
117
122
|
|
|
118
123
|
```bash
|
|
119
|
-
npx -y @fleox/agentphoto@0.1.
|
|
120
|
-
npx -y @fleox/agentphoto@0.1.
|
|
121
|
-
npx -y @fleox/agentphoto@0.1.
|
|
124
|
+
npx -y @fleox/agentphoto@0.1.1 remove-bg photo --threshold 128 --project my-photo --json
|
|
125
|
+
npx -y @fleox/agentphoto@0.1.1 layer update photo --set effects.stroke.color=#ffffff --set effects.stroke.width=14 --set effects.dropShadow.opacity=0.35 --set effects.dropShadow.blur=12 --project my-photo --json
|
|
126
|
+
npx -y @fleox/agentphoto@0.1.1 export --project my-photo --format png --background transparent --json
|
|
122
127
|
```
|
|
123
128
|
|
|
124
129
|
The stroke follows the mask's outline (`position`: outside by default). Crop around `data.subject` first so the sticker has no empty margin (leave room for the stroke: + 2 × width).
|