@omnimedia/omnitool
Version:
open source video processing tools
7 lines • 885 kB
JavaScript
var DT=Object.defineProperty;var yo=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var $f=(e,r)=>{for(var t in r)DT(e,t,{get:r[t],enumerable:!0})};function ls(){let e,r,t=new Promise((o,a)=>{e=o,r=a});function s(o){return o.then(e).catch(r),t}return{promise:t,resolve:e,reject:r,entangle:s}}var Df=Object.freeze({happy:e=>e!=null,sad:e=>e==null,boolean:e=>typeof e=="boolean",number:e=>typeof e=="number",string:e=>typeof e=="string",bigint:e=>typeof e=="bigint",object:e=>typeof e=="object"&&e!==null,array:e=>Array.isArray(e),fn:e=>typeof e=="function",symbol:e=>typeof e=="symbol"});var Ua=class extends Error{milliseconds;name=this.constructor.name;constructor(r){super(`deadline exceeded (${(r/1e3).toFixed(1)} seconds)`),this.milliseconds=r}};function Of(e,r){return e<=0||e===1/0?r():new Promise((t,s)=>{let o=setTimeout(()=>s(new Ua(e)),e);r().then(t).catch(s).finally(()=>clearTimeout(o))})}function ui(){let e=[];function r(){for(let t of e)t();e=[]}return r.schedule=(...t)=>(e.push(...t),r),r}function Lf(e,r){let t=e;for(let s of r)if(t=t[s],Df.sad(t))break;return t}function Bf(e){let r=!1,t;return((...s)=>(r||(r=!0,t=e(...s)),t))}function OT(){let e=new Set;async function r(...l){await Promise.all([...e].map(c=>c(...l)))}function t(l){return e.add(l),()=>{e.delete(l)}}async function s(...l){return r(...l)}function o(l){return t(l)}async function a(l){let{promise:c,resolve:_}=ls(),u=o(async(...d)=>{l&&await l(...d),_(d),u()});return c}function n(){e.clear()}let i={pub:s,sub:o,publish:r,subscribe:t,on:t,next:a,clear:n};return Object.assign(o,i),Object.assign(s,i),i}function _i(e){let r=OT();return e&&r.sub(e),r.pub}function Ec(e,r){return{error:t=>e.error({...r,...t}),rpcRequest:t=>e.rpcRequest({...r,...t}),rpcError:t=>e.rpcError({...r,...t})}}var pi=()=>e=>({plain:e.none,errMessage:e.mix(e.brightRed,e.bold),errName:e.red,errStack:e.mix(e.red,e.dim),timestamp:e.blue,timestampErr:e.red});function zf(){return pi()}var io=Object.freeze({black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",brightBlack:"\x1B[90m",brightRed:"\x1B[91m",brightGreen:"\x1B[92m",brightYellow:"\x1B[93m",brightBlue:"\x1B[94m",brightMagenta:"\x1B[95m",brightCyan:"\x1B[96m",brightWhite:"\x1B[97m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m",bgBrightBlack:"\x1B[100m",bgBrightRed:"\x1B[101m",bgBrightGreen:"\x1B[102m",bgBrightYellow:"\x1B[103m",bgBrightBlue:"\x1B[104m",bgBrightMagenta:"\x1B[105m",bgBrightCyan:"\x1B[106m",bgBrightWhite:"\x1B[107m",bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",inverse:"\x1B[7m",hidden:"\x1B[8m",strikethrough:"\x1B[9m",reset:"\x1B[0m"});var mi=()=>({none:e=>e,uncolor:BT,mix:zT,hex:RT,rgb:Rf,bgRgb:NT});function BT(e){return e.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"")}function zT(...e){return r=>{for(let t of e)r=t(r);return r}}function RT(e){e=e.replace(/^#/,"");let r,t,s,o;if(e.length===3)r=parseInt(e.split("").map(a=>a+a).join(""),16);else if(e.length===6)r=parseInt(e,16);else throw new Error("Invalid hex color");return t=r>>16&255,s=r>>8&255,o=r&255,Rf(t,s,o)}function Rf(e,r,t){let s=`\x1B[38;2;${e};${r};${t}m`;return o=>`${s}${o}${io.reset}`}function NT(e,r,t){let s=`\x1B[48;2;${e};${r};${t}m`;return o=>`${s}${o}${io.reset}`}var Ga={...Object.fromEntries(Object.entries(io).map(([e])=>[e,r=>r])),...mi()};var Ka={...Object.fromEntries(Object.entries(io).map(([e,r])=>[e,t=>`${r}${t}${io.reset}`])),...mi()};function kc(){return typeof Deno<"u"&&typeof Deno.version<"u"}function Cc(){return typeof process<"u"&&process.versions&&process.versions.node}function Nf(){return Cc()?process.env.FORCE_COLOR||process.stdout.isTTY&&process.env.TERM!=="dumb":kc()?Deno.env.get("FORCE_COLOR")||Deno.isatty(Deno.stdout.rid)&&Deno.env.get("TERM")!=="dumb":!1}var Sc=()=>Nf()?Ka:Ga;var hi=()=>({colors:e,theme:r})=>{let t=r(e);function s(n){let i=n.stack?`
`+n.stack+`
`:"";return[t.errName(n.name+":"),t.errMessage(n.message)].join(" ")+t.errStack(i)}function o(n){return n&&n instanceof Error?s(n):n}function a(n){return n&&n instanceof Error?s(n):t.errMessage(n)}return{stdout:n=>n.map(o),stderr:n=>n.map(a)}};function Ha(...e){return r=>({stdout:t=>{for(let s of e)t=s(r).stdout(t);return t},stderr:t=>{for(let s of e)t=s(r).stderr(t);return t}})}function jT(){return{icon:"\u{1F6A8}",now:()=>Date.now()}}var fi=e=>({colors:r,theme:t})=>{let s={...jT(),...e},o=t(r),a=new Date(s.now()),n=a.getUTCFullYear().toString().padStart(4,"0"),i=(a.getUTCMonth()+1).toString().padStart(2,"0"),l=a.getUTCDate().toString().padStart(2,"0"),c=`${n}-${i}-${l}`,_=a.getUTCHours().toString().padStart(2,"0"),u=a.getUTCMinutes().toString().padStart(2,"0"),d=a.getUTCSeconds().toString().padStart(2,"0"),g=a.getUTCMilliseconds().toString().padStart(3,"0"),h=`${_}:${u}:${d}.${g}`,x=`${c}::${h}`;return{stdout:F=>[o.timestamp(x),...F],stderr:F=>[o.timestampErr(x),...[s.icon].filter(Boolean),...F]}};function jf(){return Ha(hi(),fi())}var gi=()=>({stdout:async e=>{await Deno.stdout.write(new TextEncoder().encode(e+`
`))},stderr:async e=>{await Deno.stderr.write(new TextEncoder().encode(e+`
`))}});var Mi=()=>({stdout:async e=>{process.stdout.write(e+`
`)},stderr:async e=>{process.stderr.write(e+`
`)}});var wi=()=>({stdout:async e=>console.log(e),stderr:async e=>console.error(e)});var Vf=()=>kc()?gi():Cc()?Mi():wi();var Wf=()=>({stdout:async()=>{},stderr:async()=>{}});function Uf(){return()=>({stdout:e=>e,stderr:e=>e})}var la=class e{static writers={auto:Vf,void:Wf,deno:gi,node:Mi,console:wi};static colors={auto:Sc,colorful:()=>Ka,colorless:()=>Ga};static themes={auto:zf,basic:pi};static shapers={auto:jf,none:Uf,errors:hi,timestamp:fi};writer=e.writers.auto();colors=e.colors.auto();theme=e.themes.auto();shaper=e.shapers.auto();async log(...r){await this.writer.stdout(this.shaper(this).stdout(r).join(" "))}async error(...r){await this.writer.stderr(this.shaper(this).stderr(r).join(" "))}setWriter(r){return this.writer=r,this}setColors(r){return this.colors=r,this}setTheme(r){return this.theme=r,this}setShaper(...r){return this.shaper=Ha(...r),this}};var qa=class extends la{static dummy(){return new this().setWriter(la.writers.void())}rpcRequest=async({request:r,...t})=>{let s=this.colors.none;this.log(...this.#e(t),s(`${r.method}()`))};rpcError=async({request:r,error:t,...s})=>{this.error(...this.#e(s),`${r.method}()`,t)};#e({meta:r,label:t,remote:s}){let o=this.colors.mix(this.colors.blue,this.colors.dim),a=this.colors.mix(this.colors.cyan,this.colors.dim);return[r?this.#t(r):void 0,t||void 0,s===void 0?void 0:s?o("<-"):a("->")].filter(Boolean)}#t(r){let{headers:t}=r.request;return[this.colors.yellow(`[${r.ip}]`),this.colors.green(t.origin?t.origin:"(no-origin)")].join(" ")}};var Ls=class extends qa{rpcRequest=async()=>{}};var Ks;(function(e){e.version="2.0";function r(t){return"id"in t?t.id:null}e.getId=r,e.errorCodes={serverError:-32e3,unexposedError:-32001}})(Ks||(Ks={}));var To=class extends Error{name=this.constructor.name},Po=class extends Error{name=this.constructor.name};async function Gf({tap:e,request:r,action:t}){let s=Ks.getId(r);try{let o=await t();return s===null?null:{id:s,result:o,jsonrpc:Ks.version}}catch(o){return e.rpcError({request:r,error:o}),s===null?null:{id:s,jsonrpc:Ks.version,error:o instanceof To?{code:Ks.errorCodes.serverError,message:o.message}:{code:Ks.errorCodes.unexposedError,message:"unexposed error"}}}}function bi(e){let r=e.tap??new Ls;return async t=>{let s=t.method.split("."),o=Lf(e.fns,s),a=async()=>await o(...t.params);return r.rpcRequest({request:t}),await Gf({tap:r,request:t,action:a})}}var Kf=Symbol("tune"),VT=Symbol("query"),WT=Symbol("notify"),UT=Symbol("settings");function Hf(e){function r(t){let s={notify:void 0};return new Proxy((()=>{}),{apply:(o,a,n)=>e(t,n,s),get:(o,a)=>{if(a!=="then")return a===Kf?n=>(...i)=>e(t,i,{...s,...n}):a===WT?(...n)=>e(t,n,{...s,notify:!0}):a===VT?(...n)=>e(t,n,{...s,notify:!1}):a===UT?s:(o[a]||(o[a]=r([...t,a])),o[a])},set:(o,a,n)=>(o[a]=n,!0)})}return r([])}function Eo(e){let{endpoint:r,tap:t=new Ls}=e,s=1;return Hf(async(o,a,n)=>{let i=n.notify??e.notify??!1,l=n.transfer,c={jsonrpc:"2.0",method:o.join("."),params:a},_=i?c:{...c,id:s++};t.rpcRequest({request:_});let u=await r(_,{transfer:l});if(i&&!u)return null;if(!u)throw new Po("response was null, but shouldn't be, because the request was not a notification");if("error"in u)throw new Po(e.label?`${e.label}: ${u.error.message}`:u.error.message);return u.result})}function Qa(e){return Eo({endpoint:bi(e),tap:e.tap})}var ko=class{recv=_i();sendRequest=_i();sendResponse=_i();static makeEntangledPair({origin:r="example.e280.org"}={}){let t=new this,s=new this,o=[t.sendRequest.sub(n=>s.recv(n,{origin:r})),t.sendResponse.sub(n=>s.recv(n,{origin:r})),s.sendRequest.sub(n=>t.recv(n,{origin:r})),s.sendResponse.sub(n=>t.recv(n,{origin:r}))];return[t,s,()=>o.forEach(n=>n())]}};function vi(e,r){return e.addEventListener("message",r),()=>e.removeEventListener("message",r)}function qf(e,r){return async(t,{transfer:s}={})=>{if("id"in t){let o=ls();return r(t,s,o.promise),e.wait(t.id,t.method).then(a=>(o.resolve(a),a))}else{let o=Promise.resolve(null);return r(t,s,o),o}}}function Qf(e){let r=[],t=[];for(let s of Array.isArray(e)?e:[e])"method"in s?r.push(s):t.push(s);return{requests:r,responses:t}}async function Xf(e,r){let t=(await Promise.all(r.map(async s=>e(s)))).filter(s=>s!==null);return t.length===0?null:t.length===1?t[0]:t}var ca=class extends ko{dispose=ui();constructor(r){super(),this.dispose.schedule(this.sendRequest.sub((t,s)=>r.postMessage(t,s)),this.sendResponse.sub((t,s)=>r.postMessage(t,s)),vi(r,t=>this.recv(t.data,t)))}};var xi=class{remote;transfer;constructor(r){this.remote=r}};var Fc=Object.freeze({timeout:6e4,maxRequestBytes:1e7});var yi=class{timeout;pending=new Map;constructor(r){this.timeout=r}async wait(r,t){let s=ls();return this.pending.set(r,{method:t,deferred:s}),await Of(this.timeout,()=>s.promise).catch(o=>{throw o instanceof Ua&&(o.message=`request #${r} ${t}(), ${o.message}`),o})}deliverResponse(r){let t=this.pending.get(r.id);t&&("error"in r?t.deferred.reject(new Po(r.error.message)):t.deferred.resolve(r))}};var Co=class{options;remote;remoteEndpoint;dispose=ui();#e;constructor(r){this.options=r;let{conduit:t,tap:s}=r;this.#e=new yi(r.timeout??Fc.timeout),this.remoteEndpoint=qf(this.#e,t.sendRequest.pub.bind(t.sendRequest)),this.remote=Eo({endpoint:this.remoteEndpoint,tap:s&&Ec(s,{remote:!0})}),this.dispose.schedule(t.recv.sub(o=>this.recv(o)))}async recv(r){let t=new xi(this.remote),{conduit:s,rpc:o,tap:a}=this.options,{requests:n,responses:i}=Qf(r);for(let u of i)this.#e.deliverResponse(u);if(!o)return;let l=await o(t),c=bi({fns:l,tap:a&&Ec(a,{remote:!1})}),_=await Xf(c,n);_&&await s.sendResponse(_,t.transfer)}};var Hs={derive:{host:e=>({host:e.remote.host,get transfer(){return e.transfer},set transfer(r){e.transfer=r}}),work:e=>({work:e.remote,get transfer(){return e.transfer},set transfer(r){e.transfer=r}})},mock:{host:()=>({host:void 0,transfer:void 0}),work:()=>({work:void 0,transfer:void 0})}};var qs=new Ls;async function Jf(e,r,t={}){let s=t.tap??qs,o=new Co({tap:s,timeout:t.timeout??1/0,conduit:new ca(e.getSelf()),rpc:async a=>r(Hs.derive.host(a))});return await o.remote.infra.ready(),o.remote.host}var da=class{worker;messenger;constructor(r,t){this.worker=r,this.messenger=t}static async make(r,t){let s=t.tap??qs,o=t.label??"comrade",a=r.loadWorker(t.workerUrl,o),n=ls(),i={async ready(){n.resolve()}},l=new Co({tap:s,timeout:t.timeout??1/0,conduit:new ca(a),rpc:async c=>({infra:i,host:t.setupHost(Hs.derive.work(c))})});return await n.promise,new this(a,l)}get work(){return this.messenger.remote}terminate(){this.worker.terminate()}};var Ti=class{threads;static async make(r,t){let s=t.workerCount??r.guessOptimalThreadCount(),o=await Promise.all([...Array(s)].map(async(a,n)=>da.make(r,{...t,label:t.label??`${t.label??"comrade"}_${n+1}`})));return new this(o,{tap:t.tap})}work;#e=new Set;#t=[];constructor(r,t={}){this.threads=r;let s=t.tap??qs,o=async(a,n)=>this.#s({request:a,prom:ls(),transfer:n?.transfer});this.work=Eo({tap:s,endpoint:o}),r.forEach(a=>this.#e.add(a))}get threadCount(){return this.threads.length}terminate(){for(let r of this.threads)r.terminate()}#s(r){return this.#t.push(r),this.#r(),r.prom.promise}#r(){for(;this.#e.size>0&&this.#t.length>0;){let r=[...this.#e].pop();this.#e.delete(r);let t=this.#t.shift();this.#e.delete(r);let s=r.messenger.remoteEndpoint(t.request,{transfer:t.transfer});t.prom.entangle(s).finally(()=>{this.#e.add(r),this.#r()})}}};var Yf=e=>({thread:r=>da.make(e,r),cluster:r=>Ti.make(e,r),worker:(r,t={})=>Jf(e,r,t),work:r=>r,host:r=>r,mocks(r){let{setupWork:t,setupHost:s,tap:o=qs}=r,a=Hs.mock.host(),n=Hs.mock.work();return n.work=Qa({tap:o,fns:t(a)}),a.host=Qa({tap:o,fns:s(n)}),{workShell:n,hostShell:a,work:n.work,host:a.host}},mockWork(r,t=qs){let s=Hs.mock.host(),o=Hs.mock.work();return o.work=Qa({tap:t,fns:r(s)}),{workShell:o,hostShell:s,work:o.work,mockHost:a=>(s.host=Qa({tap:t,fns:a(o)}),{workShell:o,hostShell:s,work:o.work,host:s.host})}}});var Zf=()=>({getSelf(){return self},guessOptimalThreadCount(){let e=navigator.hardwareConcurrency??1;return Math.max(1,e-1)},loadWorker(e,r){return new window.Worker(e,{name:r,type:"module"})},async loadWasm(e){return WebAssembly.instantiateStreaming(fetch(e))}});var HT=Zf(),eg=Yf(HT);var Ac={};$f(Ac,{InferenceSession:()=>XT,TRACE:()=>fg,TRACE_FUNC_BEGIN:()=>Ei,TRACE_FUNC_END:()=>ki,Tensor:()=>Io,env:()=>QT,registerBackend:()=>tg});var Pi=new Map,So=[],tg=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){let s=Pi.get(e);if(s===void 0)Pi.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){let o=So.indexOf(e);o!==-1&&So.splice(o,1);for(let a=0;a<So.length;a++)if(Pi.get(So[a]).priority<=t){So.splice(a,0,e);return}So.push(e)}return}throw new TypeError("not a valid backend")},qT=async e=>{let r=Pi.get(e);if(!r)return"backend not found.";if(r.initialized)return r.backend;if(r.aborted)return r.error;{let t=!!r.initPromise;try{return t||(r.initPromise=r.backend.init(e)),await r.initPromise,r.initialized=!0,r.backend}catch(s){return t||(r.error=`${s}`,r.aborted=!0),r.error}finally{delete r.initPromise}}},rg=async e=>{let r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?So:t,o,a=[],n=new Set;for(let l of s){let c=await qT(l);typeof c=="string"?a.push({name:l,err:c}):(o||(o=c),o===c&&n.add(l))}if(!o)throw new Error(`no available backend found. ERR: ${a.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of a)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=r.filter(l=>n.has(typeof l=="string"?l:l.name));return[o,new Proxy(e,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]};var sg="1.21.0";var og="warning",ts={wasm:{},webgl:{},webgpu:{},versions:{common:sg},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);og=e}},get logLevel(){return og}};Object.defineProperty(ts,"logLevel",{enumerable:!0});var QT=ts;var ag=(e,r)=>{let t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];let s=t.getContext("2d");if(s!=null){let o,a;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],a=e.dims[3]):(o=e.dims[3],a=e.dims[2]);let n=r?.format!==void 0?r.format:"RGB",i=r?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let _=a*o,u=0,d=_,g=_*2,h=-1;n==="RGBA"?(u=0,d=_,g=_*2,h=_*3):n==="RGB"?(u=0,d=_,g=_*2):n==="RBG"&&(u=0,g=_,d=_*2);for(let x=0;x<a;x++)for(let F=0;F<o;F++){let v=(e.data[u++]-c[0])*l[0],b=(e.data[d++]-c[1])*l[1],C=(e.data[g++]-c[2])*l[2],y=h===-1?255:(e.data[h++]-c[3])*l[3];s.fillStyle="rgba("+v+","+b+","+C+","+y+")",s.fillRect(F,x,1,1)}if("toDataURL"in t)return t.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},ng=(e,r)=>{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(t!=null){let o,a,n;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],a=e.dims[1],n=e.dims[3]):(o=e.dims[3],a=e.dims[2],n=e.dims[1]);let i=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r?.norm,c,_;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?_=[0,0,0,0]:typeof l.bias=="number"?_=[l.bias,l.bias,l.bias,l.bias]:(_=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(_[3]=l.bias[3]));let u=a*o;if(r!==void 0&&(r.format!==void 0&&n===4&&r.format!=="RGBA"||n===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let d=4,g=0,h=1,x=2,F=3,v=0,b=u,C=u*2,y=-1;i==="RGBA"?(v=0,b=u,C=u*2,y=u*3):i==="RGB"?(v=0,b=u,C=u*2):i==="RBG"&&(v=0,C=u,b=u*2),s=t.createImageData(o,a);for(let P=0;P<a*o;g+=d,h+=d,x+=d,F+=d,P++)s.data[g]=(e.data[v++]-_[0])*c[0],s.data[h]=(e.data[b++]-_[1])*c[1],s.data[x]=(e.data[C++]-_[2])*c[2],s.data[F]=y===-1?255:(e.data[y++]-_[3])*c[3]}else throw new Error("Can not access image data");return s};var Ic=(e,r)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:t,width:s}=r,o=r.norm??{mean:255,bias:0},a,n;typeof o.mean=="number"?a=[o.mean,o.mean,o.mean,o.mean]:a=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?n=[o.bias,o.bias,o.bias,o.bias]:n=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let i=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",c=t*s,_=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),u=4,d=0,g=1,h=2,x=3,F=0,v=c,b=c*2,C=-1;i==="RGB"&&(u=3,d=0,g=1,h=2,x=-1),l==="RGBA"?C=c*3:l==="RBG"?(F=0,b=c,v=c*2):l==="BGR"&&(b=0,v=c,F=c*2);for(let P=0;P<c;P++,d+=u,h+=u,g+=u,x+=u)_[F++]=(e[d]+n[0])/a[0],_[v++]=(e[g]+n[1])/a[1],_[b++]=(e[h]+n[2])/a[2],C!==-1&&x!==-1&&(_[C++]=(e[x]+n[3])/a[3]);return l==="RGBA"?new Vr("float32",_,[1,4,t,s]):new Vr("float32",_,[1,3,t,s])},ig=async(e,r)=>{let t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",n,i=r??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=_=>typeof HTMLCanvasElement<"u"&&_ instanceof HTMLCanvasElement||_ instanceof OffscreenCanvas?_.getContext("2d"):null;if(t){let _=l();_.width=e.width,_.height=e.height;let u=c(_);if(u!=null){let d=e.height,g=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(d=r.resizedHeight,g=r.resizedWidth),r!==void 0){if(i=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=d,i.width=g}else i.tensorFormat="RGBA",i.height=d,i.width=g;u.drawImage(e,0,0),n=u.getImageData(0,0,g,d).data}else throw new Error("Can not access image data")}else if(s){let _,u;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(_=r.resizedHeight,u=r.resizedWidth):(_=e.height,u=e.width),r!==void 0&&(i=r),i.format="RGBA",i.height=_,i.width=u,r!==void 0){let d=l();d.width=u,d.height=_;let g=c(d);if(g!=null)g.putImageData(e,0,0),n=g.getImageData(0,0,u,_).data;else throw new Error("Can not access image data")}else n=e.data}else if(o){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");let _=l();_.width=e.width,_.height=e.height;let u=c(_);if(u!=null){let d=e.height,g=e.width;return u.drawImage(e,0,0,g,d),n=u.getImageData(0,0,g,d).data,i.height=d,i.width=g,Ic(n,i)}else throw new Error("Can not access image data")}else{if(a)return new Promise((_,u)=>{let d=l(),g=c(d);if(!e||!g)return u();let h=new Image;h.crossOrigin="Anonymous",h.src=e,h.onload=()=>{d.width=h.width,d.height=h.height,g.drawImage(h,0,0,d.width,d.height);let x=g.getImageData(0,0,d.width,d.height);i.height=d.height,i.width=d.width,_(Ic(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(n!==void 0)return Ic(n,i);throw new Error("Input data provided is not supported - aborted tensor creation")},lg=(e,r)=>{let{width:t,height:s,download:o,dispose:a}=r,n=[1,s,t,4];return new Vr({location:"texture",type:"float32",texture:e,dims:n,download:o,dispose:a})},cg=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:a}=r;return new Vr({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:a})},dg=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:a}=r;return new Vr({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:a})},ug=(e,r,t)=>new Vr({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]});var Fo=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Xa=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),_g=!1,pg=()=>{if(!_g){_g=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(Fo.set("int64",BigInt64Array),Xa.set(BigInt64Array,"int64")),r&&(Fo.set("uint64",BigUint64Array),Xa.set(BigUint64Array,"uint64")),s?(Fo.set("float16",t),Xa.set(t,"float16")):Fo.set("float16",Uint16Array)}};var mg=e=>{let r=1;for(let t=0;t<e.length;t++){let s=e[t];if(typeof s!="number"||!Number.isSafeInteger(s))throw new TypeError(`dims[${t}] must be an integer, got: ${s}`);if(s<0)throw new RangeError(`dims[${t}] must be a non-negative integer, got: ${s}`);r*=s}return r},hg=(e,r)=>{switch(e.location){case"cpu":return new Vr(e.type,e.data,r);case"cpu-pinned":return new Vr({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Vr({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Vr({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Vr({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};var Vr=class{constructor(r,t,s){pg();let o,a;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,o=r.type,a=r.dims,r.location){case"cpu-pinned":{let i=Fo.get(o);if(!i)throw new TypeError(`unsupported type "${o}" to create tensor from pinned buffer`);if(!(r.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=r.data;break}case"texture":{if(o!=="float32")throw new TypeError(`unsupported type "${o}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.dispose;break}case"gpu-buffer":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from gpu buffer`);this.gpuBufferData=r.gpuBuffer,this.downloader=r.download,this.disposer=r.dispose;break}case"ml-tensor":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint64"&&o!=="int8"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from MLTensor`);this.mlTensorData=r.mlTensor,this.downloader=r.download,this.disposer=r.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,l;if(typeof r=="string")if(o=r,l=s,r==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");i=t}else{let c=Fo.get(r);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(t)){if(r==="float16"&&c===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${c.name} as data.`);r==="uint64"||r==="int64"?i=c.from(t,BigInt):i=c.from(t)}else if(t instanceof c)i=t;else if(t instanceof Uint8ClampedArray)if(r==="uint8")i=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(r==="float16"&&t instanceof Uint16Array&&c!==Uint16Array)i=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${o} tensor's data must be type of ${c}`)}else if(l=t,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let c=typeof r[0];if(c==="string")o="string",i=r;else if(c==="boolean")o="bool",i=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(r instanceof Uint8ClampedArray)o="uint8",i=Uint8Array.from(r);else{let c=Xa.get(r.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);o=c,i=r}if(l===void 0)l=[i.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");a=l,this.cpuData=i,this.dataLocation="cpu"}let n=mg(a);if(this.cpuData&&n!==this.cpuData.length&&!((o==="uint4"||o==="int4")&&Math.ceil(n/2)===this.cpuData.length))throw new Error(`Tensor's size(${n}) does not match data length(${this.cpuData.length}).`);this.type=o,this.dims=a,this.size=n}static async fromImage(r,t){return ig(r,t)}static fromTexture(r,t){return lg(r,t)}static fromGpuBuffer(r,t){return cg(r,t)}static fromMLTensor(r,t){return dg(r,t)}static fromPinnedBuffer(r,t,s){return ug(r,t,s)}toDataURL(r){return ag(this,r)}toImageData(r){return ng(this,r)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(r){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,r&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(r){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return hg(this,r)}};var Io=Vr;var fg=(e,r)=>{(typeof ts.trace>"u"?!ts.wasm.trace:!ts.trace)||console.timeStamp(`${e}::ORT::${r}`)},gg=(e,r)=>{let t=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let o=0;o<t.length;o++){if(s&&!t[o].includes("TRACE_FUNC")){let a=`FUNC_${e}::${t[o].trim().split(" ")[1]}`;r&&(a+=`::${r}`),fg("CPU",a);return}t[o].includes("TRACE_FUNC")&&(s=!0)}},Ei=e=>{(typeof ts.trace>"u"?!ts.wasm.trace:!ts.trace)||gg("BEGIN",e)},ki=e=>{(typeof ts.trace>"u"?!ts.wasm.trace:!ts.trace)||gg("END",e)};var Ci=class e{constructor(r){this.handler=r}async run(r,t,s){Ei();let o={},a={};if(typeof r!="object"||r===null||r instanceof Io||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let n=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof Io)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");n=!1;for(let c of t){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);o[c]=null}if(typeof s=="object"&&s!==null)a=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,_=Object.getOwnPropertyNames(t);for(let u of this.outputNames)if(_.indexOf(u)!==-1){let d=t[u];(d===null||d instanceof Io)&&(c=!0,n=!1,o[u]=d)}if(c){if(typeof s=="object"&&s!==null)a=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else a=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof r[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(n)for(let c of this.outputNames)o[c]=null;let i=await this.handler.run(r,o,a),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let _=i[c];_ instanceof Io?l[c]=_:l[c]=new Io(_.type,_.data,_.dims)}return ki(),l}async release(){return this.handler.dispose()}static async create(r,t,s,o){Ei();let a,n={};if(typeof r=="string"){if(a=r,typeof t=="object"&&t!==null)n=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(a=r,typeof t=="object"&&t!==null)n=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){let _=r,u=0,d=r.byteLength;if(typeof t=="object"&&t!==null)n=t;else if(typeof t=="number"){if(u=t,!Number.isSafeInteger(u))throw new RangeError("'byteOffset' must be an integer.");if(u<0||u>=_.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${_.byteLength}).`);if(d=r.byteLength-u,typeof s=="number"){if(d=s,!Number.isSafeInteger(d))throw new RangeError("'byteLength' must be an integer.");if(d<=0||u+d>_.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${_.byteLength-u}].`);if(typeof o=="object"&&o!==null)n=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof t<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(_,u,d)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await rg(n),c=await i.createInferenceSessionHandler(a,l);return ki(),new e(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}};var XT=Ci;var Tu={};$f(Tu,{InferenceSession:()=>Xd,TRACE:()=>mn,TRACE_FUNC_BEGIN:()=>Es,TRACE_FUNC_END:()=>us,Tensor:()=>Ps,default:()=>fE,env:()=>Zt,registerBackend:()=>zo});var qd=Object.defineProperty,JT=Object.getOwnPropertyDescriptor,YT=Object.getOwnPropertyNames,ZT=Object.prototype.hasOwnProperty,eP=(e=>typeof yo<"u"?yo:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof yo<"u"?yo:r)[t]}):e)(function(e){if(typeof yo<"u")return yo.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Ve=(e,r)=>()=>(e&&(r=e(e=0)),r),fa=(e,r)=>{for(var t in r)qd(e,t,{get:r[t],enumerable:!0})},tP=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of YT(r))!ZT.call(e,o)&&o!==t&&qd(e,o,{get:()=>r[o],enumerable:!(s=JT(r,o))||s.enumerable});return e},pn=e=>tP(qd({},"__esModule",{value:!0}),e),Ja,lo,zo,Mg,Xb,Jb=Ve(()=>{"use strict";Ja=new Map,lo=[],zo=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){let s=Ja.get(e);if(s===void 0)Ja.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){let o=lo.indexOf(e);o!==-1&&lo.splice(o,1);for(let a=0;a<lo.length;a++)if(Ja.get(lo[a]).priority<=t){lo.splice(a,0,e);return}lo.push(e)}return}throw new TypeError("not a valid backend")},Mg=async e=>{let r=Ja.get(e);if(!r)return"backend not found.";if(r.initialized)return r.backend;if(r.aborted)return r.error;{let t=!!r.initPromise;try{return t||(r.initPromise=r.backend.init(e)),await r.initPromise,r.initialized=!0,r.backend}catch(s){return t||(r.error=`${s}`,r.aborted=!0),r.error}finally{delete r.initPromise}}},Xb=async e=>{let r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?lo:t,o,a=[],n=new Set;for(let l of s){let c=await Mg(l);typeof c=="string"?a.push({name:l,err:c}):(o||(o=c),o===c&&n.add(l))}if(!o)throw new Error(`no available backend found. ERR: ${a.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of a)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=r.filter(l=>n.has(typeof l=="string"?l:l.name));return[o,new Proxy(e,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),rP=Ve(()=>{"use strict";Jb()}),Yb,sP=Ve(()=>{"use strict";Yb="1.22.0-dev.20250409-89f8206ba4"}),$c,ds,Zb=Ve(()=>{"use strict";sP(),$c="warning",ds={wasm:{},webgl:{},webgpu:{},versions:{common:Yb},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);$c=e}},get logLevel(){return $c}},Object.defineProperty(ds,"logLevel",{enumerable:!0})}),Zt,oP=Ve(()=>{"use strict";Zb(),Zt=ds}),ev,tv,aP=Ve(()=>{"use strict";ev=(e,r)=>{let t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];let s=t.getContext("2d");if(s!=null){let o,a;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],a=e.dims[3]):(o=e.dims[3],a=e.dims[2]);let n=r?.format!==void 0?r.format:"RGB",i=r?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let _=a*o,u=0,d=_,g=_*2,h=-1;n==="RGBA"?(u=0,d=_,g=_*2,h=_*3):n==="RGB"?(u=0,d=_,g=_*2):n==="RBG"&&(u=0,g=_,d=_*2);for(let x=0;x<a;x++)for(let F=0;F<o;F++){let v=(e.data[u++]-c[0])*l[0],b=(e.data[d++]-c[1])*l[1],C=(e.data[g++]-c[2])*l[2],y=h===-1?255:(e.data[h++]-c[3])*l[3];s.fillStyle="rgba("+v+","+b+","+C+","+y+")",s.fillRect(F,x,1,1)}if("toDataURL"in t)return t.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},tv=(e,r)=>{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(t!=null){let o,a,n;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],a=e.dims[1],n=e.dims[3]):(o=e.dims[3],a=e.dims[2],n=e.dims[1]);let i=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r?.norm,c,_;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?_=[0,0,0,0]:typeof l.bias=="number"?_=[l.bias,l.bias,l.bias,l.bias]:(_=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(_[3]=l.bias[3]));let u=a*o;if(r!==void 0&&(r.format!==void 0&&n===4&&r.format!=="RGBA"||n===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let d=4,g=0,h=1,x=2,F=3,v=0,b=u,C=u*2,y=-1;i==="RGBA"?(v=0,b=u,C=u*2,y=u*3):i==="RGB"?(v=0,b=u,C=u*2):i==="RBG"&&(v=0,C=u,b=u*2),s=t.createImageData(o,a);for(let P=0;P<a*o;g+=d,h+=d,x+=d,F+=d,P++)s.data[g]=(e.data[v++]-_[0])*c[0],s.data[h]=(e.data[b++]-_[1])*c[1],s.data[x]=(e.data[C++]-_[2])*c[2],s.data[F]=y===-1?255:(e.data[y++]-_[3])*c[3]}else throw new Error("Can not access image data");return s}}),Si,rv,sv,ov,av,nv,nP=Ve(()=>{"use strict";Qd(),Si=(e,r)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:t,width:s}=r,o=r.norm??{mean:255,bias:0},a,n;typeof o.mean=="number"?a=[o.mean,o.mean,o.mean,o.mean]:a=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?n=[o.bias,o.bias,o.bias,o.bias]:n=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let i=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",c=t*s,_=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),u=4,d=0,g=1,h=2,x=3,F=0,v=c,b=c*2,C=-1;i==="RGB"&&(u=3,d=0,g=1,h=2,x=-1),l==="RGBA"?C=c*3:l==="RBG"?(F=0,b=c,v=c*2):l==="BGR"&&(b=0,v=c,F=c*2);for(let y=0;y<c;y++,d+=u,h+=u,g+=u,x+=u)_[F++]=(e[d]+n[0])/a[0],_[v++]=(e[g]+n[1])/a[1],_[b++]=(e[h]+n[2])/a[2],C!==-1&&x!==-1&&(_[C++]=(e[x]+n[3])/a[3]);return l==="RGBA"?new ss("float32",_,[1,4,t,s]):new ss("float32",_,[1,3,t,s])},rv=async(e,r)=>{let t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",n,i=r??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=_=>typeof HTMLCanvasElement<"u"&&_ instanceof HTMLCanvasElement||_ instanceof OffscreenCanvas?_.getContext("2d"):null;if(t){let _=l();_.width=e.width,_.height=e.height;let u=c(_);if(u!=null){let d=e.height,g=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(d=r.resizedHeight,g=r.resizedWidth),r!==void 0){if(i=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=d,i.width=g}else i.tensorFormat="RGBA",i.height=d,i.width=g;u.drawImage(e,0,0),n=u.getImageData(0,0,g,d).data}else throw new Error("Can not access image data")}else if(s){let _,u;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(_=r.resizedHeight,u=r.resizedWidth):(_=e.height,u=e.width),r!==void 0&&(i=r),i.format="RGBA",i.height=_,i.width=u,r!==void 0){let d=l();d.width=u,d.height=_;let g=c(d);if(g!=null)g.putImageData(e,0,0),n=g.getImageData(0,0,u,_).data;else throw new Error("Can not access image data")}else n=e.data}else if(o){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");let _=l();_.width=e.width,_.height=e.height;let u=c(_);if(u!=null){let d=e.height,g=e.width;return u.drawImage(e,0,0,g,d),n=u.getImageData(0,0,g,d).data,i.height=d,i.width=g,Si(n,i)}else throw new Error("Can not access image data")}else{if(a)return new Promise((_,u)=>{let d=l(),g=c(d);if(!e||!g)return u();let h=new Image;h.crossOrigin="Anonymous",h.src=e,h.onload=()=>{d.width=h.width,d.height=h.height,g.drawImage(h,0,0,d.width,d.height);let x=g.getImageData(0,0,d.width,d.height);i.height=d.height,i.width=d.width,_(Si(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(n!==void 0)return Si(n,i);throw new Error("Input data provided is not supported - aborted tensor creation")},sv=(e,r)=>{let{width:t,height:s,download:o,dispose:a}=r,n=[1,s,t,4];return new ss({location:"texture",type:"float32",texture:e,dims:n,download:o,dispose:a})},ov=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:a}=r;return new ss({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:a})},av=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:a}=r;return new ss({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:a})},nv=(e,r,t)=>new ss({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]})}),Lo,ln,Dc,iv,iP=Ve(()=>{"use strict";Lo=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ln=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Dc=!1,iv=()=>{if(!Dc){Dc=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(Lo.set("int64",BigInt64Array),ln.set(BigInt64Array,"int64")),r&&(Lo.set("uint64",BigUint64Array),ln.set(BigUint64Array,"uint64")),s?(Lo.set("float16",t),ln.set(t,"float16")):Lo.set("float16",Uint16Array)}}}),lv,cv,lP=Ve(()=>{"use strict";Qd(),lv=e=>{let r=1;for(let t=0;t<e.length;t++){let s=e[t];if(typeof s!="number"||!Number.isSafeInteger(s))throw new TypeError(`dims[${t}] must be an integer, got: ${s}`);if(s<0)throw new RangeError(`dims[${t}] must be a non-negative integer, got: ${s}`);r*=s}return r},cv=(e,r)=>{switch(e.location){case"cpu":return new ss(e.type,e.data,r);case"cpu-pinned":return new ss({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new ss({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new ss({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new ss({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),ss,Qd=Ve(()=>{"use strict";aP(),nP(),iP(),lP(),ss=class{constructor(e,r,t){iv();let s,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,o=e.dims,e.location){case"cpu-pinned":{let n=Lo.get(s);if(!n)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof n))throw new TypeError(`buffer should be of type ${n.name}`);this.cpuData=e.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let n,i;if(typeof e=="string")if(s=e,i=t,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");n=r}else{let l=Lo.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);e==="uint64"||e==="int64"?n=l.from(r,BigInt):n=l.from(r)}else if(r instanceof l)n=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")n=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&r instanceof Uint16Array&&l!==Uint16Array)n=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(i=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")s="string",n=e;else if(l==="boolean")s="bool",n=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",n=Uint8Array.from(e);else{let l=ln.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=l,n=e}if(i===void 0)i=[n.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");o=i,this.cpuData=n,this.dataLocation="cpu"}let a=lv(o);if(this.cpuData&&a!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=o,this.size=a}static async fromImage(e,r){return rv(e,r)}static fromTexture(e,r){return sv(e,r)}static fromGpuBuffer(e,r){return ov(e,r)}static fromMLTensor(e,r){return av(e,r)}static fromPinnedBuffer(e,r,t){return nv(e,r,t)}toDataURL(e){return ev(this,e)}toImageData(e){return tv(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return cv(this,e)}}}),Ps,dv=Ve(()=>{"use strict";Qd(),Ps=ss}),mn,Oc,Es,us,uv=Ve(()=>{"use strict";Zb(),mn=(e,r)=>{(typeof ds.trace>"u"?!ds.wasm.trace:!ds.trace)||console.timeStamp(`${e}::ORT::${r}`)},Oc=(e,r)=>{let t=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let o=0;o<t.length;o++){if(s&&!t[o].includes("TRACE_FUNC")){let a=`FUNC_${e}::${t[o].trim().split(" ")[1]}`;r&&(a+=`::${r}`),mn("CPU",a);return}t[o].includes("TRACE_FUNC")&&(s=!0)}},Es=e=>{(typeof ds.trace>"u"?!ds.wasm.trace:!ds.trace)||Oc("BEGIN",e)},us=e=>{(typeof ds.trace>"u"?!ds.wasm.trace:!ds.trace)||Oc("END",e)}}),_v,cP=Ve(()=>{"use strict";Jb(),dv(),uv(),_v=class pv{constructor(r){this.handler=r}async run(r,t,s){Es();let o={},a={};if(typeof r!="object"||r===null||r instanceof Ps||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let n=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof Ps)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");n=!1;for(let c of t){if(typeof c!="string")throw new TypeError("'fetches' must be a string a