UNPKG

latentimg

Version:

Lightweight browser-side encoder/decoder for images using ONNX

3 lines (2 loc) 2.68 kB
function t(t,n,e,o){return new(e||(e=Promise))((function(i,r){function a(t){try{d(o.next(t))}catch(t){r(t)}}function c(t){try{d(o.throw(t))}catch(t){r(t)}}function d(t){var n;t.done?i(t.value):(n=t.value,n instanceof e?n:new e((function(t){t(n)}))).then(a,c)}d((o=o.apply(t,n||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;let n=!1,e=null;function o(){return t(this,void 0,void 0,(function*(){if(n)return;if(e=yield new Function('return import("https://cdn.jsdelivr.net/npm/onnxruntime-web@1.21.0/dist/ort.bundle.min.mjs")')(),!e)throw new Error("ORT could not be loaded");e.env.wasm.numThreads=1,n=!0,console.log("🧠 ORT init complete (esm)")}))}function i(){if(!e)throw new Error("ORT not initialized. Call ensureOrtInitialized() first.");return e}function r(n){return t(this,void 0,void 0,(function*(){const t=i();return new Promise((e=>{const o=new Image;o.crossOrigin="anonymous",o.onload=()=>{const n=1080,i=document.createElement("canvas");i.width=n,i.height=n;const r=i.getContext("2d");r.fillStyle="black",r.fillRect(0,0,n,n);const a=Math.min(n/o.width,n/o.height),c=o.width*a,d=o.height*a,u=(n-c)/2,l=(n-d)/2;r.drawImage(o,u,l,c,d);const s=r.getImageData(0,0,n,n).data,h=new Float32Array(3499200);for(let t=0;t<1166400;t++)h[t]=s[4*t]/255,h[t+1166400]=s[4*t+1]/255,h[t+2332800]=s[4*t+2]/255;e(new t.Tensor("float32",h,[1,3,n,n]))},o.src=n}))}))}function a(n){return t(this,void 0,void 0,(function*(){i();const[t,e,o,r]=n.dims,a=n.data,c=document.createElement("canvas");c.width=r,c.height=o;const d=c.getContext("2d"),u=d.createImageData(r,o);for(let t=0;t<o*r;t++){let n=255*a[t],e=255*a[t+o*r],i=255*a[t+2*o*r];n=Math.max(0,Math.min(255,n)),e=Math.max(0,Math.min(255,e)),i=Math.max(0,Math.min(255,i)),u.data[4*t+0]=n,u.data[4*t+1]=e,u.data[4*t+2]=i,u.data[4*t+3]=255}return d.putImageData(u,0,0),c.toDataURL()}))}function c(t){return new Float32Array(t.data)}function d(n,e){return t(this,void 0,void 0,(function*(){yield o();const t=i(),a=yield r(n),d=(null==e?void 0:e.encoderUrl)||"https://huggingface.co/devcwPark/latentimg-cae/resolve/main/encoder.quant.onnx",u=yield t.InferenceSession.create(d),l={input:a};return c((yield u.run(l)).latent)}))}function u(n,e){return t(this,void 0,void 0,(function*(){const t=i(),o=new t.Tensor("float32",n,[1,n.length]),r=(null==e?void 0:e.decoderUrl)||"https://huggingface.co/devcwPark/latentimg-cae/resolve/main/decoder.quant.onnx",c=yield t.InferenceSession.create(r),d={latent:o};return a((yield c.run(d)).recon)}))}export{u as decodeLatent,d as encodeImage,o as ensureOrtInitialized,i as getOrt,r as imageToTensor,a as tensorToImage,c as tensorToLatent}; //# sourceMappingURL=latentimg.esm.js.map