UNPKG

latentimg

Version:

Lightweight browser-side encoder/decoder for images using ONNX

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