tempest-react-sdk 0.10.0 → 0.12.0
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 +57 -27
- package/dist/charts.cjs +2 -0
- package/dist/charts.cjs.map +1 -0
- package/dist/charts.d.ts +139 -0
- package/dist/charts.js +196 -0
- package/dist/charts.js.map +1 -0
- package/dist/cn-C0Sxc9eb.js +19 -0
- package/dist/cn-C0Sxc9eb.js.map +1 -0
- package/dist/cn-CNScIEB4.cjs +2 -0
- package/dist/cn-CNScIEB4.cjs.map +1 -0
- package/dist/editor.cjs +2 -0
- package/dist/editor.cjs.map +1 -0
- package/dist/editor.d.ts +28 -0
- package/dist/editor.js +190 -0
- package/dist/editor.js.map +1 -0
- package/dist/styles.css +1 -1
- package/dist/tempest-react-sdk.cjs +3 -3
- package/dist/tempest-react-sdk.cjs.map +1 -1
- package/dist/tempest-react-sdk.d.ts +1001 -0
- package/dist/tempest-react-sdk.js +4326 -2983
- package/dist/tempest-react-sdk.js.map +1 -1
- package/dist/vision.cjs +2 -0
- package/dist/vision.cjs.map +1 -0
- package/dist/vision.d.ts +1030 -0
- package/dist/vision.js +1416 -0
- package/dist/vision.js.map +1 -0
- package/package.json +38 -1
package/dist/vision.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Xt=require("onnxruntime-web");function Kt(o){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const e in o)if(e!=="default"){const s=Object.getOwnPropertyDescriptor(o,e);Object.defineProperty(t,e,s.get?s:{enumerable:!0,get:()=>o[e]})}}return t.default=o,Object.freeze(t)}const Q=Kt(Xt);class B extends Error{constructor(t,e){super(t,e),this.name=new.target.name}}class At extends B{}class rt extends B{}class Gt extends B{}class C extends B{}class P extends B{}class N{constructor(t,e,s){if(this.data=t,this.width=e,this.height=s,t.length!==e*s*3)throw new C(`RGBImage data length ${t.length} does not match width * height * 3 = ${e*s*3}.`)}data;width;height}class ht{constructor(t,e,s,n){this.x1=t,this.y1=e,this.x2=s,this.y2=n}x1;y1;x2;y2;get width(){return Math.max(0,this.x2-this.x1)}get height(){return Math.max(0,this.y2-this.y1)}get area(){return this.width*this.height}get xyxy(){return[this.x1,this.y1,this.x2,this.y2]}get xywh(){return[(this.x1+this.x2)/2,(this.y1+this.y2)/2,this.width,this.height]}xyxyn(t){const[e,s]=t;return s<=0||e<=0?[0,0,0,0]:[this.x1/s,this.y1/e,this.x2/s,this.y2/e]}xywhn(t){const[e,s]=t;if(s<=0||e<=0)return[0,0,0,0];const[n,r,a,i]=this.xywh;return[n/s,r/e,a/s,i/e]}asXyxy(){return[this.x1,this.y1,this.x2,this.y2]}asXywh(){return[this.x1,this.y1,this.width,this.height]}asIntXyxy(){return[Math.trunc(this.x1),Math.trunc(this.y1),Math.trunc(this.x2),Math.trunc(this.y2)]}}class R{constructor(t,e,s){if(this.data=t,this.width=e,this.height=s,t.length!==e*s)throw new C(`Mask data length ${t.length} does not match width * height = ${e*s}.`)}data;width;height}class lt{constructor(t,e,s,n){this.xyxy=t,this.cls=e,this.conf=s,this.origShape=n}xyxy;cls;conf;origShape;get length(){return this.cls.length}get shape(){return[this.length,4]}get xywh(){const t=new Float32Array(this.xyxy.length);for(let e=0;e<this.length;e++){const s=this.xyxy[e*4],n=this.xyxy[e*4+1],r=this.xyxy[e*4+2],a=this.xyxy[e*4+3];t[e*4]=(s+r)/2,t[e*4+1]=(n+a)/2,t[e*4+2]=r-s,t[e*4+3]=a-n}return t}get xyxyn(){const[t,e]=this.origShape,s=new Float32Array(this.xyxy.length);if(this.length===0||e<=0||t<=0)return s;for(let n=0;n<this.length;n++)s[n*4]=this.xyxy[n*4]/e,s[n*4+1]=this.xyxy[n*4+1]/t,s[n*4+2]=this.xyxy[n*4+2]/e,s[n*4+3]=this.xyxy[n*4+3]/t;return s}get xywhn(){const t=this.xywh,[e,s]=this.origShape;if(this.length===0||s<=0||e<=0)return t;for(let n=0;n<this.length;n++)t[n*4]=t[n*4]/s,t[n*4+1]=t[n*4+1]/e,t[n*4+2]=t[n*4+2]/s,t[n*4+3]=t[n*4+3]/e;return t}get data(){const t=new Float32Array(this.length*6);for(let e=0;e<this.length;e++)t[e*6]=this.xyxy[e*4],t[e*6+1]=this.xyxy[e*4+1],t[e*6+2]=this.xyxy[e*4+2],t[e*6+3]=this.xyxy[e*4+3],t[e*6+4]=this.conf[e],t[e*6+5]=this.cls[e];return t}}class Tt{constructor(t){this.data=t}data;get length(){return this.data.length}get shape(){return[this.length]}get top1(){if(this.data.length===0)return 0;let t=0,e=this.data[0];for(let s=1;s<this.data.length;s++){const n=this.data[s];n>e&&(t=s,e=n)}return t}get top1conf(){return this.data.length===0?0:this.data[this.top1]}get top5(){return this._topK(5).indices}get top5conf(){return this._topK(5).values}_topK(t){const e=Math.min(t,this.data.length),s=[];for(let a=0;a<this.data.length;a++)s.push(a);s.sort((a,i)=>this.data[i]-this.data[a]);const n=new Int32Array(e),r=new Float32Array(e);for(let a=0;a<e;a++)n[a]=s[a],r[a]=this.data[s[a]];return{indices:n,values:r}}}class Ct{constructor(t,e,s){this.data=t,this.xyxy=e,this.origShape=s}data;xyxy;origShape;get length(){return this.data.length}get shape(){return[this.length]}[Symbol.iterator](){return this.data[Symbol.iterator]()}}class Et{constructor(t,e,s,n,r,a=null,i={}){this.boxes=t,this.detections=e,this.names=s,this.origImg=n,this.origShape=r,this.path=a,this.speed=i}boxes;detections;names;origImg;origShape;path;speed;get length(){return this.detections.length}get(t){return this.detections[t]}[Symbol.iterator](){return this.detections[Symbol.iterator]()}}class $t{constructor(t,e,s,n,r,a=null,i={}){this.probs=t,this.result=e,this.names=s,this.origImg=n,this.origShape=r,this.path=a,this.speed=i}probs;result;names;origImg;origShape;path;speed;get cls(){return this.probs.top1}get conf(){return this.probs.top1conf}get name(){return this.names[this.cls]??`class_${this.cls}`}get probabilities(){return this.result.probabilities}}class kt{constructor(t,e,s,n,r,a,i=null,c={}){this.boxes=t,this.masks=e,this.detections=s,this.names=n,this.origImg=r,this.origShape=a,this.path=i,this.speed=c}boxes;masks;detections;names;origImg;origShape;path;speed;get length(){return this.detections.length}get(t){return this.detections[t]}[Symbol.iterator](){return this.detections[Symbol.iterator]()}}const Ot=Object.freeze(["person","bicycle","car","motorcycle","airplane","bus","train","truck","boat","traffic light","fire hydrant","stop sign","parking meter","bench","bird","cat","dog","horse","sheep","cow","elephant","bear","zebra","giraffe","backpack","umbrella","handbag","tie","suitcase","frisbee","skis","snowboard","sports ball","kite","baseball bat","baseball glove","skateboard","surfboard","tennis racket","bottle","wine glass","cup","fork","knife","spoon","bowl","banana","apple","sandwich","orange","broccoli","carrot","hot dog","pizza","donut","cake","chair","couch","potted plant","bed","dining table","toilet","tv","laptop","mouse","remote","keyboard","cell phone","microwave","oven","toaster","sink","refrigerator","book","clock","vase","scissors","teddy bear","hair drier","toothbrush"]),_t={coco:Ot};function Z(o,t={}){const e=Ht(o,t.numClasses);if(t.numClasses!==void 0&&e.length!==t.numClasses)throw new P(`Resolved ${e.length} labels but the model has ${t.numClasses} classes.`);return e}function Ht(o,t){if(o==null){if(t===void 0)throw new P("Cannot auto-generate labels without numClasses. Pass an explicit labels spec or numClasses.");return Array.from({length:t},(e,s)=>`class_${s}`)}if(Array.isArray(o))return[...o];if(typeof o=="string"){const e=_t[o];if(e!==void 0)return e;throw new P(`Unknown labels preset: ${JSON.stringify(o)}. Known presets: ${Object.keys(_t).join(", ")}.`)}if(typeof o=="object"){const e=o,s=Object.keys(e).map(r=>Number(r));if(s.length===0)return[];const n=Math.max(...s);return Array.from({length:n+1},(r,a)=>e[a]??`class_${a}`)}throw new P(`Unsupported labels spec type: ${typeof o}.`)}const at=["webgpu","wasm"];function Ft(o){return o===void 0?[...at]:o.length===0?[...at]:[...o]}class U{constructor(t,e){this._session=t,this.providers=e}_session;providers;static async create(t,e={}){const s=Ft(e.providers),n={...e.sessionOptions??{},executionProviders:s};let r;try{typeof t=="string"?r=await Q.InferenceSession.create(t,n):t instanceof Uint8Array?r=await Q.InferenceSession.create(t,n):r=await Q.InferenceSession.create(t,n)}catch(a){throw new At(`Failed to load ONNX model: ${a.message}`,{cause:a})}return new U(r,s)}get inputNames(){return this._session.inputNames}get inputName(){const t=this._session.inputNames[0];if(t===void 0)throw new rt("Model has no inputs.");return t}get outputNames(){return this._session.outputNames}get raw(){return this._session}async run(t){try{return await this._session.run(t)}catch(e){throw new rt(`Inference failed: ${e.message}`,{cause:e})}}}function it(o,t){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(o,t);if(typeof document<"u"){const e=document.createElement("canvas");return e.width=o,e.height=t,e}throw new C("No canvas implementation available in this environment.")}function ct(o){const t=o.getContext("2d");if(t===null)throw new C("Failed to obtain 2D rendering context.");return t}function dt(o){const{data:t,width:e,height:s}=o;if(t.length!==e*s*4)throw new C(`Unexpected ImageData length ${t.length} for ${e}x${s} (expected ${e*s*4}).`);const n=new Uint8Array(e*s*3);for(let r=0,a=0;r<t.length;r+=4,a+=3)n[a]=t[r],n[a+1]=t[r+1],n[a+2]=t[r+2];return new N(n,e,s)}function Jt(o){const t=new Uint8ClampedArray(o.width*o.height*4);for(let e=0,s=0;e<o.data.length;e+=3,s+=4)t[s]=o.data[e],t[s+1]=o.data[e+1],t[s+2]=o.data[e+2],t[s+3]=255;return new ImageData(t,o.width,o.height)}async function q(o){if(o instanceof N)return o;if(typeof ImageData<"u"&&o instanceof ImageData)return dt(o);if(typeof o=="string")return Qt(o);if(typeof Blob<"u"&&o instanceof Blob)return Nt(o);if(typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement)return await Zt(o),V(o,o.naturalWidth,o.naturalHeight);if(typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&o instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&o instanceof ImageBitmap)return V(o,o.width,o.height);throw new C(`Unsupported image source type: ${Object.prototype.toString.call(o)}`)}async function Qt(o){let t;try{t=await fetch(o)}catch(s){throw new C(`Failed to fetch image from ${o}: ${s.message}`,{cause:s})}if(!t.ok)throw new C(`Failed to fetch image from ${o}: HTTP ${t.status} ${t.statusText}`);const e=await t.blob();return Nt(e)}async function Nt(o){let t;try{t=await createImageBitmap(o)}catch(e){throw new C(`Failed to decode image blob: ${e.message}`,{cause:e})}try{return V(t,t.width,t.height)}finally{t.close()}}function Zt(o){return o.complete&&o.naturalWidth>0?Promise.resolve():new Promise((t,e)=>{const s=()=>{r(),t()},n=()=>{r(),e(new C("Failed to load HTMLImageElement (load event errored)"))},r=()=>{o.removeEventListener("load",s),o.removeEventListener("error",n)};o.addEventListener("load",s,{once:!0}),o.addEventListener("error",n,{once:!0})})}function V(o,t,e){if(t===0||e===0)throw new C(`Cannot load image with zero dimension (${t}x${e}).`);const s=it(t,e),n=ct(s);n.drawImage(o,0,0);const r=n.getImageData(0,0,t,e);return dt(r)}function ut(o,t,e){if(t<=0||e<=0)throw new Error(`Invalid resize target ${t}x${e}.`);if(t===o.width&&e===o.height)return o;const s=it(o.width,o.height);ct(s).putImageData(Jt(o),0,0);const r=it(t,e),a=ct(r);a.imageSmoothingEnabled=!0,a.imageSmoothingQuality="high",a.drawImage(s,0,0,t,e);const i=a.getImageData(0,0,t,e);return dt(i)}function Lt(o,t,e,s=1/255){const n=new Float32Array(o.data.length),r=o.data,a=t[0],i=t[1],c=t[2],f=e[0],m=e[1],h=e[2];for(let l=0;l<r.length;l+=3)n[l]=(r[l]*s-a)/f,n[l+1]=(r[l+1]*s-i)/m,n[l+2]=(r[l+2]*s-c)/h;return n}function W(o,t=1/255){const e=new Float32Array(o.data.length),s=o.data;for(let n=0;n<s.length;n++)e[n]=s[n]*t;return e}function j(o,t,e,s=3){const n=t*e*s;if(o.length!==n)throw new Error(`toCHW: expected length ${n} for ${t}x${e}x${s}, got ${o.length}.`);const r=new Float32Array(n),a=t*e;for(let i=0;i<e;i++)for(let c=0;c<t;c++){const f=(i*t+c)*s,m=i*t+c;for(let h=0;h<s;h++)r[h*a+m]=o[f+h]}return r}function tt(o,t){return new Q.Tensor("float32",o,t)}function qt(o){const t=W(o);return j(t,o.width,o.height,3)}function Wt(o,t,e){if(o.length!==t*e*3)throw new Error(`fromCv2: data length ${o.length} does not match width * height * 3 = ${t*e*3}.`);const s=new Uint8Array(o.length);for(let n=0;n<o.length;n+=3)s[n]=o[n+2],s[n+1]=o[n+1],s[n+2]=o[n];return new N(s,t,e)}function te(o){const t=o.data,e=new Uint8Array(t.length);for(let s=0;s<t.length;s+=3)e[s]=t[s+2],e[s+1]=t[s+1],e[s+2]=t[s];return e}function ft(o,t,e,s=[114,114,114]){const n=Math.min(t/o.width,e/o.height),r=Math.round(o.width*n),a=Math.round(o.height*n),i=ut(o,r,a),c=new Uint8Array(t*e*3),f=s[0],m=s[1],h=s[2];for(let d=0;d<c.length;d+=3)c[d]=f,c[d+1]=m,c[d+2]=h;const l=Math.floor((t-r)/2),w=Math.floor((e-a)/2),x=r*3;for(let d=0;d<a;d++){const u=d*x,p=((w+d)*t+l)*3;c.set(i.data.subarray(u,u+x),p)}return{image:new N(c,t,e),scale:n,padLeft:l,padTop:w}}function zt(o){const t=o.length,e=new Float32Array(t);let s=-1/0;for(let r=0;r<t;r++){const a=o[r];a>s&&(s=a)}let n=0;for(let r=0;r<t;r++){const a=Math.exp(o[r]-s);e[r]=a,n+=a}for(let r=0;r<t;r++)e[r]=e[r]/n;return e}function Dt(o,t){const e=o.length,s=t===null?e:Math.min(Math.max(0,t),e),n=new Array(e);for(let i=0;i<e;i++)n[i]=i;n.sort((i,c)=>o[c]-o[i]);const r=new Int32Array(s),a=new Float32Array(s);for(let i=0;i<s;i++){const c=n[i];r[i]=c,a[i]=o[c]}return{indices:r,values:a}}function Yt(o,t,e){const s=t.length;if(s===0)return new Int32Array(0);const n=new Float32Array(s);for(let c=0;c<s;c++){const f=o[c*4],m=o[c*4+1],h=o[c*4+2],l=o[c*4+3];n[c]=Math.max(0,h-f)*Math.max(0,l-m)}const r=new Array(s);for(let c=0;c<s;c++)r[c]=c;r.sort((c,f)=>t[f]-t[c]);const a=new Uint8Array(s),i=[];for(let c=0;c<r.length;c++){const f=r[c];if(a[f])continue;i.push(f);const m=o[f*4],h=o[f*4+1],l=o[f*4+2],w=o[f*4+3],x=n[f];for(let d=c+1;d<r.length;d++){const u=r[d];if(a[u])continue;const p=o[u*4],_=o[u*4+1],g=o[u*4+2],A=o[u*4+3],S=Math.max(m,p),M=Math.max(h,_),v=Math.min(l,g),E=Math.min(w,A),$=Math.max(0,v-S),y=Math.max(0,E-M),b=$*y,I=x+n[u]-b;(I>0?b/I:0)>e&&(a[u]=1)}}return Int32Array.from(i)}function Rt(o,t,e,s){if(t.length===0)return new Int32Array(0);const n=new Map;for(let a=0;a<e.length;a++){const i=e[a],c=n.get(i);c===void 0?n.set(i,[a]):c.push(a)}const r=[];for(const a of n.values()){const i=a.length,c=new Float32Array(i*4),f=new Float32Array(i);for(let h=0;h<i;h++){const l=a[h];c[h*4]=o[l*4],c[h*4+1]=o[l*4+1],c[h*4+2]=o[l*4+2],c[h*4+3]=o[l*4+3],f[h]=t[l]}const m=Yt(c,f,s);for(let h=0;h<m.length;h++)r.push(a[m[h]])}return r.sort((a,i)=>t[i]-t[a]),Int32Array.from(r)}function et(o,t,e){let s=t;if(s.length===3){if(s[0]!==1)throw new Error(`decodeYoloAnchors: expected batch size 1, got ${s[0]}.`);s=[s[1],s[2]]}if(s.length!==2)throw new Error(`decodeYoloAnchors: expected 2-D output after batch removal, got dims=${JSON.stringify(t)}.`);const n=s[0],r=s[1],{numClasses:a,originalWidth:i,originalHeight:c,padLeft:f,padTop:m,scale:h,confThreshold:l,iouThreshold:w,maxDetections:x}=e;if(a<1||a+4>n)throw new Error(`decodeYoloAnchors: invalid numClasses=${a} for channels=${n}.`);if(o.length!==n*r)throw new Error(`decodeYoloAnchors: data length ${o.length} does not match channels*numAnchors=${n*r}.`);const d=[];for(let y=0;y<r;y++){let b=0,I=-1/0;for(let Y=0;Y<a;Y++){const z=o[(4+Y)*r+y];z!==void 0&&z>I&&(I=z,b=Y)}if(I<l)continue;const T=o[y],X=o[r+y],K=o[2*r+y],G=o[3*r+y];let D=T-K/2,k=X-G/2,O=T+K/2,L=X+G/2;D=(D-f)/h,k=(k-m)/h,O=(O-f)/h,L=(L-m)/h,D=Math.max(0,Math.min(i,D)),k=Math.max(0,Math.min(c,k)),O=Math.max(0,Math.min(i,O)),L=Math.max(0,Math.min(c,L)),d.push({anchorIdx:y,x1:D,y1:k,x2:O,y2:L,classId:b,confidence:I})}if(d.length===0)return vt();const u=new Float32Array(d.length*4),p=new Float32Array(d.length),_=new Int32Array(d.length);for(let y=0;y<d.length;y++){const b=d[y];u[y*4]=b.x1,u[y*4+1]=b.y1,u[y*4+2]=b.x2,u[y*4+3]=b.y2,p[y]=b.confidence,_[y]=b.classId}const g=Rt(u,p,_,w);if(g.length===0)return vt();const A=Array.from(g).slice(0,x),S=A.length,M=new Int32Array(S),v=new Float32Array(S*4),E=new Int32Array(S),$=new Float32Array(S);for(let y=0;y<S;y++){const b=d[A[y]];M[y]=b.anchorIdx,v[y*4]=b.x1,v[y*4+1]=b.y1,v[y*4+2]=b.x2,v[y*4+3]=b.y2,E[y]=b.classId,$[y]=b.confidence}return{anchorIndices:M,boxesXyxy:v,classIds:E,confidences:$}}function vt(){return{anchorIndices:new Int32Array(0),boxesXyxy:new Float32Array(0),classIds:new Int32Array(0),confidences:new Float32Array(0)}}function mt(o,t,e){const s=t.length===3?t[1]:t[0];if(s===void 0||s<5)throw new Error(`decodeYolo: invalid output channel count ${s} (expected >= 5).`);const n=s-4,r=et(o,t,{numClasses:n,...e}),a=[];for(let i=0;i<r.classIds.length;i++)a.push({bbox:new ht(r.boxesXyxy[i*4],r.boxesXyxy[i*4+1],r.boxesXyxy[i*4+2],r.boxesXyxy[i*4+3]),classId:r.classIds[i],confidence:r.confidences[i]});return a}let Mt=!1,St=!1;function ee(o,t,e){return Mt||(Mt=!0,console.warn("[@ort-vision-sdk/web] decodeYoloV8 is deprecated since 0.2.0; use decodeYolo. The alias will be removed in 0.3.0.")),mt(o,t,e)}function ne(o,t,e){return St||(St=!0,console.warn("[@ort-vision-sdk/web] decodeYoloV8Anchors is deprecated since 0.2.0; use decodeYoloAnchors. The alias will be removed in 0.3.0.")),et(o,t,e)}function yt(o,t,e,s,n){let r=s;if(r.length===4){if(r[0]!==1)throw new Error(`decodeYoloSeg: expected batch size 1 in prototypes, got ${r[0]}.`);r=[r[1],r[2],r[3]]}if(r.length!==3)throw new Error(`decodeYoloSeg: expected 3-D prototypes after batch removal, got dims=${JSON.stringify(s)}.`);const a=r[0],i=r[1],c=r[2],f=t.length===3?t[1]:t[0],m=t.length===3?t[2]:t[1];if(f===void 0||m===void 0)throw new Error(`decodeYoloSeg: cannot read channels/numAnchors from dims=${JSON.stringify(t)}.`);const h=4+n.numClasses+a;if(f!==h)throw new Error(`decodeYoloSeg: channels=${f} does not match 4 + numClasses(${n.numClasses}) + numMaskCoefs(${a}) = ${h}.`);if(e.length!==a*i*c)throw new Error(`decodeYoloSeg: prototype length ${e.length} does not match dims=${JSON.stringify(s)}.`);const l=et(o,t,{numClasses:n.numClasses,originalWidth:n.originalWidth,originalHeight:n.originalHeight,padLeft:n.padLeft,padTop:n.padTop,scale:n.scale,confThreshold:n.confThreshold,iouThreshold:n.iouThreshold,maxDetections:n.maxDetections});if(l.anchorIndices.length===0)return[];const w=n.maskThreshold??.5,x=c/n.inputWidth,d=i/n.inputHeight,u=i*c,p=(4+n.numClasses)*m,_=[];for(let g=0;g<l.anchorIndices.length;g++){const A=l.anchorIndices[g],S=l.boxesXyxy[g*4],M=l.boxesXyxy[g*4+1],v=l.boxesXyxy[g*4+2],E=l.boxesXyxy[g*4+3],$=new ht(S,M,v,E),y=l.classIds[g],b=l.confidences[g],I=Math.max(0,Math.trunc(v)-Math.trunc(S)),T=Math.max(0,Math.trunc(E)-Math.trunc(M));if(I===0||T===0){_.push({bbox:$,classId:y,confidence:b,mask:new R(new Uint8Array(0),0,0)});continue}const X=S*n.scale+n.padLeft,K=M*n.scale+n.padTop,G=v*n.scale+n.padLeft,D=E*n.scale+n.padTop,k=Math.max(0,Math.floor(X*x)),O=Math.max(0,Math.floor(K*d)),L=Math.min(c,Math.ceil(G*x)),Y=Math.min(i,Math.ceil(D*d));if(L<=k||Y<=O){_.push({bbox:$,classId:y,confidence:b,mask:new R(new Uint8Array(I*T),I,T)});continue}const z=L-k,st=Y-O,pt=new Float32Array(z*st);for(let F=0;F<st;F++){const Ut=O+F;for(let H=0;H<z;H++){const Vt=k+H;let bt=0;for(let J=0;J<a;J++){const Pt=o[p+J*m+A],jt=e[J*u+Ut*c+Vt];bt+=Pt*jt}pt[F*z+H]=se(bt)}}const Bt=re(pt,z,st,I,T),ot=new Uint8Array(I*T);for(let F=0;F<ot.length;F++)ot[F]=Bt[F]>=w?255:0;_.push({bbox:$,classId:y,confidence:b,mask:new R(ot,I,T)})}return _}function se(o){if(o>=0)return 1/(1+Math.exp(-o));const t=Math.exp(o);return t/(1+t)}let It=!1;function oe(o,t,e,s,n){return It||(It=!0,console.warn("[@ort-vision-sdk/web] decodeYoloV8Seg is deprecated since 0.2.0; use decodeYoloSeg. The alias will be removed in 0.3.0.")),yt(o,t,e,s,n)}function re(o,t,e,s,n){const r=new Float32Array(s*n);if(s===0||n===0||t===0||e===0)return r;if(s===t&&n===e)return r.set(o),r;const a=t/s,i=e/n;for(let c=0;c<n;c++){const f=(c+.5)*i-.5,m=Math.max(0,Math.floor(f)),h=Math.min(e-1,m+1),l=Math.max(0,Math.min(1,f-m));for(let w=0;w<s;w++){const x=(w+.5)*a-.5,d=Math.max(0,Math.floor(x)),u=Math.min(t-1,d+1),p=Math.max(0,Math.min(1,x-d)),_=o[m*t+d],g=o[m*t+u],A=o[h*t+d],S=o[h*t+u],M=_*(1-p)+g*p,v=A*(1-p)+S*p;r[c*s+w]=M*(1-l)+v*l}}return r}class nt{constructor(t){this._session=t}_session;get session(){return this._session}}const ae=[.485,.456,.406],ie=[.229,.224,.225];class wt extends nt{constructor(t,e,s,n,r,a,i){super(t),this._labels=e,this._names=s,this._inputSize=n,this._mean=r,this._std=a,this._applySoftmax=i}_labels;_names;_inputSize;_mean;_std;_applySoftmax;static async create(t,e){const s=await U.create(t,e),n=Z(e.labels,{numClasses:e.numClasses}),r={};for(let a=0;a<n.length;a++)r[a]=n[a];return new wt(s,n,r,e.inputSize??[224,224],e.mean??ae,e.std??ie,e.applySoftmax??!0)}get labels(){return this._labels}get names(){return this._names}get numClasses(){return this._labels.length}async call(t,e={}){return this.predict(t,e)}async predict(t,e={}){const s=typeof t=="string"?t:null,n=await q(t),r=this._preprocess(n),a=await this._session.run({[this._session.inputName]:r}),i=this._session.outputNames[0];if(i===void 0)throw new Error("Classifier model has no outputs.");const c=a[i];if(c===void 0)throw new Error(`Classifier model output ${i} missing from run() result.`);const f=this._postprocess(c.data),{indices:m,values:h}=Dt(f,e.topK??null),l=[];for(let u=0;u<m.length;u++){const p=m[u],_=this._labels[p]??`class_${p}`;l.push({classId:p,className:_,probability:h[u],cls:p,name:_,conf:h[u]})}if(l.length===0)throw new Error("Classifier produced no probabilities (empty output).");const w=l[0],x={classId:w.classId,className:w.className,confidence:w.probability,cls:w.classId,name:w.className,conf:w.probability,image:n,probabilities:l},d=[n.height,n.width];return[new $t(new Tt(f),x,this._names,n,d,s)]}_preprocess(t){const[e,s]=this._inputSize,n=ut(t,e,s),r=Lt(n,this._mean,this._std),a=j(r,n.width,n.height,3);return tt(a,[1,3,n.height,n.width])}_postprocess(t){return this._applySoftmax?zt(t):new Float32Array(t)}}class gt extends nt{constructor(t,e,s,n,r,a,i,c){super(t),this._head=e,this._labels=s,this._names=n,this._inputSize=r,this._confThreshold=a,this._iouThreshold=i,this._maxDetections=c}_head;_labels;_names;_inputSize;_confThreshold;_iouThreshold;_maxDetections;static async create(t,e={}){const s=e.head??"yolo";if(s!=="yolo")throw new Error(`Unsupported detector head '${s}'. Supported: 'yolo'.`);const n=await U.create(t,e),r=Z(e.labels??"coco",{numClasses:e.numClasses}),a={};for(let i=0;i<r.length;i++)a[i]=r[i];return new gt(n,s,r,a,e.inputSize??[640,640],e.confThreshold??.25,e.iouThreshold??.45,e.maxDetections??300)}get head(){return this._head}get labels(){return this._labels}get names(){return this._names}get numClasses(){return this._labels.length}async call(t,e={}){return this.predict(t,e)}async predict(t,e={}){const s=typeof t=="string"?t:null,n=await q(t),{tensor:r,scale:a,padLeft:i,padTop:c}=this._preprocess(n),f=await this._session.run({[this._session.inputName]:r}),m=this._session.outputNames[0];if(m===void 0)throw new Error("Detector model has no outputs.");const h=f[m];if(h===void 0)throw new Error(`Detector model output ${m} missing from run() result.`);const l=mt(h.data,h.dims,{originalWidth:n.width,originalHeight:n.height,padLeft:i,padTop:c,scale:a,confThreshold:e.confThreshold??this._confThreshold,iouThreshold:e.iouThreshold??this._iouThreshold,maxDetections:this._maxDetections}),x=(e.classes!==void 0?(()=>{const u=new Set(e.classes);return l.filter(p=>u.has(p.classId))})():l).map(u=>this._buildResult(n,u.bbox,u.classId,u.confidence)),d=[n.height,n.width];return[new Et(this._buildBoxes(x,d),x,this._names,n,d,s)]}_preprocess(t){const[e,s]=this._inputSize,n=ft(t,e,s),r=W(n.image),a=j(r,n.image.width,n.image.height,3);return{tensor:tt(a,[1,3,n.image.height,n.image.width]),scale:n.scale,padLeft:n.padLeft,padTop:n.padTop}}_buildResult(t,e,s,n){const[r,a,i,c]=e.asIntXyxy(),f=Math.max(0,r),m=Math.max(0,a),h=Math.min(t.width,i),l=Math.min(t.height,c);let w;if(h>f&&l>m){const d=h-f,u=l-m,p=new Uint8Array(d*u*3);for(let _=0;_<u;_++){const g=((m+_)*t.width+f)*3;p.set(t.data.subarray(g,g+d*3),_*d*3)}w=new N(p,d,u)}else w=new N(new Uint8Array(0),0,0);const x=this._names[s]??`class_${s}`;return{classId:s,className:x,confidence:n,bbox:e,cls:s,name:x,conf:n,box:e,croppedImage:w}}_buildBoxes(t,e){const s=t.length,n=new Float32Array(s*4),r=new Int32Array(s),a=new Float32Array(s);for(let i=0;i<s;i++){const c=t[i];n[i*4]=c.bbox.x1,n[i*4+1]=c.bbox.y1,n[i*4+2]=c.bbox.x2,n[i*4+3]=c.bbox.y2,r[i]=c.classId,a[i]=c.confidence}return new lt(n,r,a,e)}}class xt extends nt{constructor(t,e,s,n,r,a,i,c,f){super(t),this._head=e,this._labels=s,this._names=n,this._inputSize=r,this._confThreshold=a,this._iouThreshold=i,this._maxDetections=c,this._maskThreshold=f}_head;_labels;_names;_inputSize;_confThreshold;_iouThreshold;_maxDetections;_maskThreshold;static async create(t,e={}){const s=e.head??"yolo-seg";if(s!=="yolo-seg")throw new Error(`Unsupported segmenter head '${s}'. Supported: 'yolo-seg'.`);const n=await U.create(t,e),r=Z(e.labels??"coco",{numClasses:e.numClasses}),a={};for(let i=0;i<r.length;i++)a[i]=r[i];return new xt(n,s,r,a,e.inputSize??[640,640],e.confThreshold??.25,e.iouThreshold??.45,e.maxDetections??300,e.maskThreshold??.5)}get head(){return this._head}get labels(){return this._labels}get names(){return this._names}get numClasses(){return this._labels.length}async call(t,e={}){return this.predict(t,e)}async predict(t,e={}){const s=typeof t=="string"?t:null,n=await q(t),{tensor:r,scale:a,padLeft:i,padTop:c}=this._preprocess(n),f=await this._session.run({[this._session.inputName]:r}),{perAnchor:m,prototypes:h}=this._splitOutputs(f),l=yt(m.data,m.dims,h.data,h.dims,{numClasses:this._labels.length,inputWidth:this._inputSize[0],inputHeight:this._inputSize[1],originalWidth:n.width,originalHeight:n.height,padLeft:i,padTop:c,scale:a,confThreshold:e.confThreshold??this._confThreshold,iouThreshold:e.iouThreshold??this._iouThreshold,maxDetections:this._maxDetections,maskThreshold:this._maskThreshold}),x=(e.classes!==void 0?(()=>{const u=new Set(e.classes);return l.filter(p=>u.has(p.classId))})():l).map(u=>this._buildResult(n,u.bbox,u.classId,u.confidence,u.mask)),d=[n.height,n.width];return[new kt(this._buildBoxes(x,d),this._buildMasks(x,d),x,this._names,n,d,s)]}_preprocess(t){const[e,s]=this._inputSize,n=ft(t,e,s),r=W(n.image),a=j(r,n.image.width,n.image.height,3);return{tensor:tt(a,[1,3,n.image.height,n.image.width]),scale:n.scale,padLeft:n.padLeft,padTop:n.padTop}}_splitOutputs(t){let e,s;for(const n of this._session.outputNames){const r=t[n];r!==void 0&&(r.dims.length===3&&e===void 0?e=r:r.dims.length===4&&s===void 0&&(s=r))}if(e===void 0||s===void 0){const n=this._session.outputNames.map(r=>`${r}: ${JSON.stringify(t[r]?.dims??[])}`);throw new Error(`Segmenter expected one 3-D and one 4-D output, got [${n.join(", ")}].`)}return{perAnchor:e,prototypes:s}}_buildResult(t,e,s,n,r){const[a,i,c,f]=e.asIntXyxy(),m=Math.max(0,a),h=Math.max(0,i),l=Math.min(t.width,c),w=Math.min(t.height,f);let x,d=r;if(l>m&&w>h&&r.data.length>0){const p=l-m,_=w-h,g=Math.min(r.width,p),A=Math.min(r.height,_),S=new Uint8Array(g*A*3);for(let M=0;M<A;M++){const v=((h+M)*t.width+m)*3,E=M*g*3,$=M*r.width;for(let y=0;y<g;y++)if(r.data[$+y]!==0){const I=v+y*3,T=E+y*3;S[T]=t.data[I],S[T+1]=t.data[I+1],S[T+2]=t.data[I+2]}}if(x=new N(S,g,A),g!==r.width||A!==r.height){const M=new Uint8Array(g*A);for(let v=0;v<A;v++)M.set(r.data.subarray(v*r.width,v*r.width+g),v*g);d=new R(M,g,A)}}else d=new R(new Uint8Array(0),0,0),x=new N(new Uint8Array(0),0,0);const u=this._names[s]??`class_${s}`;return{classId:s,className:u,confidence:n,bbox:e,cls:s,name:u,conf:n,box:e,mask:d,segmentedImage:x}}_buildBoxes(t,e){const s=t.length,n=new Float32Array(s*4),r=new Int32Array(s),a=new Float32Array(s);for(let i=0;i<s;i++){const c=t[i];n[i*4]=c.bbox.x1,n[i*4+1]=c.bbox.y1,n[i*4+2]=c.bbox.x2,n[i*4+3]=c.bbox.y2,r[i]=c.classId,a[i]=c.confidence}return new lt(n,r,a,e)}_buildMasks(t,e){const s=new Float32Array(t.length*4);for(let n=0;n<t.length;n++){const r=t[n];s[n*4]=r.bbox.x1,s[n*4+1]=r.bbox.y1,s[n*4+2]=r.bbox.x2,s[n*4+3]=r.bbox.y2}return new Ct(t.map(n=>n.mask),s,e)}}const ce="0.2.1";exports.BoundingBox=ht;exports.Boxes=lt;exports.COCO_CLASSES=Ot;exports.ClassificationResults=$t;exports.Classifier=wt;exports.DEFAULT_PROVIDERS=at;exports.DetectionResults=Et;exports.Detector=gt;exports.ImageLoadError=C;exports.InferenceError=rt;exports.LabelMapError=P;exports.Mask=R;exports.Masks=Ct;exports.ModelLoadError=At;exports.OrtSession=U;exports.OrtVisionError=B;exports.Probs=Tt;exports.ProviderNotAvailableError=Gt;exports.RGBImage=N;exports.SegmentationResults=kt;exports.Segmenter=xt;exports.VERSION=ce;exports.VisionTask=nt;exports.batchedNms=Rt;exports.decodeYolo=mt;exports.decodeYoloAnchors=et;exports.decodeYoloSeg=yt;exports.decodeYoloV8=ee;exports.decodeYoloV8Anchors=ne;exports.decodeYoloV8Seg=oe;exports.fromCv2=Wt;exports.letterbox=ft;exports.loadImage=q;exports.nms=Yt;exports.normalize=Lt;exports.resize=ut;exports.resolveLabels=Z;exports.resolveProviders=Ft;exports.softmax=zt;exports.toCHW=j;exports.toCv2=te;exports.toFloat32=W;exports.toFloat32Tensor=tt;exports.toTensor=qt;exports.topK=Dt;
|
|
2
|
+
//# sourceMappingURL=vision.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vision.cjs","sources":["../src/vision/core/exceptions.ts","../src/vision/types.ts","../src/vision/results.ts","../src/vision/labels.ts","../src/vision/core/providers.ts","../src/vision/core/session.ts","../src/vision/core/canvas.ts","../src/vision/io/image.ts","../src/vision/preprocess/image.ts","../src/vision/postprocess/classification.ts","../src/vision/postprocess/detection.ts","../src/vision/postprocess/segmentation.ts","../src/vision/tasks/base.ts","../src/vision/tasks/classifier.ts","../src/vision/tasks/detector.ts","../src/vision/tasks/segmenter.ts","../src/vision/index.ts"],"sourcesContent":["/**\n * Exceptions raised by the SDK.\n *\n * All exceptions inherit from {@link OrtVisionError}, so callers can catch\n * the base class to handle any SDK-originated failure uniformly.\n */\n\nexport class OrtVisionError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n }\n}\n\n/** Raised when an ONNX model cannot be loaded into an inference session. */\nexport class ModelLoadError extends OrtVisionError {}\n\n/** Raised when ONNX Runtime fails while executing a model. */\nexport class InferenceError extends OrtVisionError {}\n\n/** Raised when a requested execution provider is not available. */\nexport class ProviderNotAvailableError extends OrtVisionError {}\n\n/** Raised when an input image cannot be decoded into the canonical format. */\nexport class ImageLoadError extends OrtVisionError {}\n\n/** Raised when class labels cannot be resolved from the supplied spec. */\nexport class LabelMapError extends OrtVisionError {}\n","/**\n * Public output types returned by the SDK's vision tasks.\n *\n * These types form the contract between the SDK and its callers. They mirror\n * the Python `ort-vision-sdk` output dataclasses 1-to-1.\n *\n * Naming is intentionally compatible with the Ultralytics / torchvision idiom\n * (`cls`, `conf`, `box`, `xyxy`, `xywh`, normalized variants) so code ported\n * from those projects keeps working with minimal edits. The original verbose\n * names (`classId`, `className`, `confidence`, `bbox`) are still populated for\n * backwards compatibility.\n */\n\nimport { ImageLoadError } from \"./core/exceptions\";\n\n/**\n * HWC RGB uint8 image — the canonical image format used across the SDK.\n *\n * `data.length` must equal `width * height * 3`. The buffer is laid out row\n * by row, top-to-bottom, with each pixel as `[R, G, B]`.\n */\nexport class RGBImage {\n constructor(\n public readonly data: Uint8Array,\n public readonly width: number,\n public readonly height: number,\n ) {\n if (data.length !== width * height * 3) {\n throw new ImageLoadError(\n `RGBImage data length ${data.length} does not match width * height * 3 = ${\n width * height * 3\n }.`,\n );\n }\n }\n}\n\n/**\n * Axis-aligned bounding box in absolute pixel coordinates (xyxy format).\n *\n * Coordinates refer to the original input image (before any internal resize),\n * so callers can map detections back onto their source image without any\n * additional bookkeeping.\n */\nexport class BoundingBox {\n constructor(\n public readonly x1: number,\n public readonly y1: number,\n public readonly x2: number,\n public readonly y2: number,\n ) {}\n\n /** Box width in pixels (clamped to non-negative). */\n get width(): number {\n return Math.max(0, this.x2 - this.x1);\n }\n\n /** Box height in pixels (clamped to non-negative). */\n get height(): number {\n return Math.max(0, this.y2 - this.y1);\n }\n\n /** Box area in pixels squared. */\n get area(): number {\n return this.width * this.height;\n }\n\n /** The box as `[x1, y1, x2, y2]` in absolute pixels (Ultralytics-style). */\n get xyxy(): readonly [number, number, number, number] {\n return [this.x1, this.y1, this.x2, this.y2];\n }\n\n /**\n * The box as `[cx, cy, w, h]` with `(cx, cy)` at the center.\n *\n * Matches Ultralytics' `boxes.xywh` and YOLO's native head format. For the\n * top-left `[x, y, w, h]` convention, use {@link asXywh}.\n */\n get xywh(): readonly [number, number, number, number] {\n return [(this.x1 + this.x2) / 2, (this.y1 + this.y2) / 2, this.width, this.height];\n }\n\n /**\n * The box as `[x1, y1, x2, y2]` normalized to `[0, 1]`.\n *\n * @param origShape `[height, width]` of the source image, in pixels.\n */\n xyxyn(origShape: readonly [number, number]): readonly [number, number, number, number] {\n const [h, w] = origShape;\n if (w <= 0 || h <= 0) return [0, 0, 0, 0];\n return [this.x1 / w, this.y1 / h, this.x2 / w, this.y2 / h];\n }\n\n /**\n * The box as `[cx, cy, w, h]` normalized to `[0, 1]`.\n *\n * @param origShape `[height, width]` of the source image, in pixels.\n */\n xywhn(origShape: readonly [number, number]): readonly [number, number, number, number] {\n const [h, w] = origShape;\n if (w <= 0 || h <= 0) return [0, 0, 0, 0];\n const [cx, cy, bw, bh] = this.xywh;\n return [cx / w, cy / h, bw / w, bh / h];\n }\n\n /** Returns `[x1, y1, x2, y2]`. */\n asXyxy(): readonly [number, number, number, number] {\n return [this.x1, this.y1, this.x2, this.y2];\n }\n\n /**\n * Returns `[x, y, width, height]` with `(x, y)` at the **top-left**.\n *\n * Note: this is the top-left convention. Ultralytics' `xywh` getter uses\n * **center** coordinates — for that, read {@link xywh}.\n */\n asXywh(): readonly [number, number, number, number] {\n return [this.x1, this.y1, this.width, this.height];\n }\n\n /** Returns `[x1, y1, x2, y2]` truncated to integers, useful for slicing arrays. */\n asIntXyxy(): readonly [number, number, number, number] {\n return [Math.trunc(this.x1), Math.trunc(this.y1), Math.trunc(this.x2), Math.trunc(this.y2)];\n }\n}\n\n/**\n * Probability assigned to a single class for a classification prediction.\n *\n * `cls` / `name` / `conf` are Ultralytics-style aliases populated alongside\n * the verbose `classId` / `className` / `probability` fields.\n */\nexport interface ClassProbability {\n readonly classId: number;\n readonly className: string;\n readonly probability: number;\n /** Alias for `classId` (Ultralytics-style). */\n readonly cls: number;\n /** Alias for `className`. */\n readonly name: string;\n /** Alias for `probability` (Ultralytics-style). */\n readonly conf: number;\n}\n\n/**\n * Output of an image classification inference.\n */\nexport interface ClassificationResult {\n readonly classId: number;\n readonly className: string;\n readonly confidence: number;\n /** Alias for `classId` (Ultralytics-style). */\n readonly cls: number;\n /** Alias for `className`. */\n readonly name: string;\n /** Alias for `confidence` (Ultralytics-style). */\n readonly conf: number;\n /** The original input image as an HWC RGB uint8 array. */\n readonly image: RGBImage;\n /**\n * Probabilities per class, sorted in descending order. The first entry\n * mirrors `classId`, `className`, and `confidence`. When `topK` was passed\n * to `predict`, the array is truncated to that length.\n */\n readonly probabilities: readonly ClassProbability[];\n}\n\n/**\n * Single detected object produced by an object-detection model.\n */\nexport interface DetectionResult {\n readonly classId: number;\n readonly className: string;\n readonly confidence: number;\n readonly bbox: BoundingBox;\n /** Alias for `classId` (Ultralytics-style). */\n readonly cls: number;\n /** Alias for `className`. */\n readonly name: string;\n /** Alias for `confidence` (Ultralytics-style). */\n readonly conf: number;\n /** Alias for `bbox` (Ultralytics-style). */\n readonly box: BoundingBox;\n /**\n * The original image cropped to `bbox`, HWC RGB uint8. Empty boxes\n * (zero area) yield a zero-sized `RGBImage`.\n */\n readonly croppedImage: RGBImage;\n}\n\n/**\n * Single-channel binary or grayscale mask, laid out row-major.\n *\n * `data.length` must equal `width * height`. For binary masks, values are\n * `0` (background) or `255` (foreground); soft masks may use the full\n * `[0, 255]` range.\n */\nexport class Mask {\n constructor(\n public readonly data: Uint8Array,\n public readonly width: number,\n public readonly height: number,\n ) {\n if (data.length !== width * height) {\n throw new ImageLoadError(\n `Mask data length ${data.length} does not match width * height = ${\n width * height\n }.`,\n );\n }\n }\n}\n\n/**\n * Single segmented instance produced by an instance-segmentation model.\n *\n * Mirrors {@link DetectionResult} and adds the per-instance binary mask\n * plus a \"ready-to-display\" background-removed crop.\n */\nexport interface SegmentationResult {\n readonly classId: number;\n readonly className: string;\n readonly confidence: number;\n readonly bbox: BoundingBox;\n /** Alias for `classId` (Ultralytics-style). */\n readonly cls: number;\n /** Alias for `className`. */\n readonly name: string;\n /** Alias for `confidence` (Ultralytics-style). */\n readonly conf: number;\n /** Alias for `bbox` (Ultralytics-style). */\n readonly box: BoundingBox;\n /**\n * Binary mask cropped to `bbox`. Values are `0` (background) or `255`\n * (foreground). Empty boxes yield a zero-sized `Mask`.\n */\n readonly mask: Mask;\n /**\n * The original image cropped to `bbox` with background pixels (where\n * `mask.data[i] === 0`) zeroed out. Empty boxes yield a zero-sized\n * `RGBImage`.\n */\n readonly segmentedImage: RGBImage;\n}\n","/**\n * Per-image result envelopes — Ultralytics-style `Results` for the SDK.\n *\n * Each `predict()` call returns a 1-element array of these envelopes,\n * mirroring `YOLO(\"img.jpg\")`. Each envelope holds:\n *\n * - A bulk-array view of the predictions (`Boxes`, `Probs`, `Masks`) with\n * the exact attribute names Ultralytics uses (`xyxy`, `xywh`, `xyxyn`,\n * `xywhn`, `cls`, `conf`, `data`, `top1`, `top5`).\n * - Per-instance dataclasses (`DetectionResult`, `SegmentationResult`,\n * `ClassProbability`) for callers who prefer the OO interface.\n * - `names`: `Record<number, string>` matching Ultralytics' `model.names`.\n * - `origImg` / `origShape` / `path`: provenance for the original input.\n */\n\nimport {\n type ClassificationResult,\n type DetectionResult,\n type RGBImage,\n type SegmentationResult,\n} from \"./types\";\n\n/**\n * Bulk numpy-style view of detected boxes for a single image.\n *\n * Mirrors Ultralytics' `Boxes` interface. Coordinates in {@link xyxy} and\n * {@link xywh} are absolute pixels in the original image; the `*n` variants\n * are normalized to `[0, 1]` using `origShape`.\n */\nexport class Boxes {\n /**\n * @param xyxy Flat array of length `4 * N` in `[x1, y1, x2, y2, ...]` order.\n * @param cls One class index per box, length `N`.\n * @param conf One confidence per box, length `N`.\n * @param origShape `[height, width]` of the original image.\n */\n constructor(\n public readonly xyxy: Float32Array,\n public readonly cls: Int32Array,\n public readonly conf: Float32Array,\n public readonly origShape: readonly [number, number],\n ) {}\n\n /** Number of detected boxes. */\n get length(): number {\n return this.cls.length;\n }\n\n /** `[N, 4]` shape of the `xyxy` view. */\n get shape(): readonly [number, number] {\n return [this.length, 4];\n }\n\n /** Boxes as `[N, 4]` `[cx, cy, w, h]` flat array in absolute pixels. */\n get xywh(): Float32Array {\n const out = new Float32Array(this.xyxy.length);\n for (let i = 0; i < this.length; i++) {\n const x1 = this.xyxy[i * 4] as number;\n const y1 = this.xyxy[i * 4 + 1] as number;\n const x2 = this.xyxy[i * 4 + 2] as number;\n const y2 = this.xyxy[i * 4 + 3] as number;\n out[i * 4] = (x1 + x2) / 2;\n out[i * 4 + 1] = (y1 + y2) / 2;\n out[i * 4 + 2] = x2 - x1;\n out[i * 4 + 3] = y2 - y1;\n }\n return out;\n }\n\n /** Boxes as `[N, 4]` `[x1, y1, x2, y2]` normalized to `[0, 1]`. */\n get xyxyn(): Float32Array {\n const [h, w] = this.origShape;\n const out = new Float32Array(this.xyxy.length);\n if (this.length === 0 || w <= 0 || h <= 0) return out;\n for (let i = 0; i < this.length; i++) {\n out[i * 4] = (this.xyxy[i * 4] as number) / w;\n out[i * 4 + 1] = (this.xyxy[i * 4 + 1] as number) / h;\n out[i * 4 + 2] = (this.xyxy[i * 4 + 2] as number) / w;\n out[i * 4 + 3] = (this.xyxy[i * 4 + 3] as number) / h;\n }\n return out;\n }\n\n /** Boxes as `[N, 4]` `[cx, cy, w, h]` normalized to `[0, 1]`. */\n get xywhn(): Float32Array {\n const xywh = this.xywh;\n const [h, w] = this.origShape;\n if (this.length === 0 || w <= 0 || h <= 0) return xywh;\n for (let i = 0; i < this.length; i++) {\n xywh[i * 4] = (xywh[i * 4] as number) / w;\n xywh[i * 4 + 1] = (xywh[i * 4 + 1] as number) / h;\n xywh[i * 4 + 2] = (xywh[i * 4 + 2] as number) / w;\n xywh[i * 4 + 3] = (xywh[i * 4 + 3] as number) / h;\n }\n return xywh;\n }\n\n /**\n * Concatenated `[N, 6]` array of `[x1, y1, x2, y2, conf, cls]`.\n *\n * Matches Ultralytics' `boxes.data`.\n */\n get data(): Float32Array {\n const out = new Float32Array(this.length * 6);\n for (let i = 0; i < this.length; i++) {\n out[i * 6] = this.xyxy[i * 4] as number;\n out[i * 6 + 1] = this.xyxy[i * 4 + 1] as number;\n out[i * 6 + 2] = this.xyxy[i * 4 + 2] as number;\n out[i * 6 + 3] = this.xyxy[i * 4 + 3] as number;\n out[i * 6 + 4] = this.conf[i] as number;\n out[i * 6 + 5] = this.cls[i] as number;\n }\n return out;\n }\n}\n\n/**\n * Top-k classification probabilities for a single image.\n *\n * Mirrors Ultralytics' `Probs` interface.\n */\nexport class Probs {\n /** @param data `[numClasses]` per-class probabilities, indexed by class id. */\n constructor(public readonly data: Float32Array) {}\n\n /** Number of classes. */\n get length(): number {\n return this.data.length;\n }\n\n /** `[numClasses]` shape of the underlying vector. */\n get shape(): readonly [number] {\n return [this.length];\n }\n\n /** Index of the most probable class. */\n get top1(): number {\n if (this.data.length === 0) return 0;\n let best = 0;\n let bestVal = this.data[0] as number;\n for (let i = 1; i < this.data.length; i++) {\n const v = this.data[i] as number;\n if (v > bestVal) {\n best = i;\n bestVal = v;\n }\n }\n return best;\n }\n\n /** Probability of the top-1 class. */\n get top1conf(): number {\n if (this.data.length === 0) return 0;\n return this.data[this.top1] as number;\n }\n\n /** Indices of the top-5 most probable classes, descending. */\n get top5(): Int32Array {\n return this._topK(5).indices;\n }\n\n /** Probabilities of the top-5 classes, descending. */\n get top5conf(): Float32Array {\n return this._topK(5).values;\n }\n\n private _topK(k: number): { indices: Int32Array; values: Float32Array } {\n const n = Math.min(k, this.data.length);\n const order: number[] = [];\n for (let i = 0; i < this.data.length; i++) order.push(i);\n order.sort((a, b) => (this.data[b] as number) - (this.data[a] as number));\n const indices = new Int32Array(n);\n const values = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n indices[i] = order[i] as number;\n values[i] = this.data[order[i] as number] as number;\n }\n return { indices, values };\n }\n}\n\n/**\n * Per-instance binary masks for a single image.\n *\n * Each mask is cropped to its instance's bounding box. To paint masks onto\n * a full-image canvas, use `xyxy[i]` as the top-left target.\n */\nexport class Masks {\n /**\n * @param data Per-instance binary masks (`Mask` objects from `types.ts`).\n * @param xyxy Flat `[N, 4]` of bounding-box coordinates in original pixels.\n * @param origShape `[height, width]` of the original image.\n */\n constructor(\n public readonly data: ReadonlyArray<{\n readonly data: Uint8Array;\n readonly width: number;\n readonly height: number;\n }>,\n public readonly xyxy: Float32Array,\n public readonly origShape: readonly [number, number],\n ) {}\n\n /** Number of instance masks. */\n get length(): number {\n return this.data.length;\n }\n\n /** `[N]` shape of the masks collection. */\n get shape(): readonly [number] {\n return [this.length];\n }\n\n [Symbol.iterator](): Iterator<{\n readonly data: Uint8Array;\n readonly width: number;\n readonly height: number;\n }> {\n return this.data[Symbol.iterator]();\n }\n}\n\n/**\n * Per-image detection envelope (Ultralytics-style `Results`).\n *\n * Iterating yields per-instance {@link DetectionResult} entries, so legacy\n * code that did `for (const d of detector.predict(img))` only needs an\n * extra `[0]` to bridge:\n *\n * ```typescript\n * for (const d of (await detector.predict(img))[0]) {\n * console.log(d.cls, d.conf, d.box.xyxy);\n * }\n * ```\n *\n * For numpy-style bulk access, use the `boxes` collection.\n */\nexport class DetectionResults implements Iterable<DetectionResult> {\n constructor(\n public readonly boxes: Boxes,\n public readonly detections: readonly DetectionResult[],\n public readonly names: Readonly<Record<number, string>>,\n public readonly origImg: RGBImage,\n public readonly origShape: readonly [number, number],\n public readonly path: string | null = null,\n public readonly speed: Readonly<Record<string, number>> = {},\n ) {}\n\n /** Number of surviving detections. */\n get length(): number {\n return this.detections.length;\n }\n\n /** Index into the per-instance detections. */\n get(index: number): DetectionResult | undefined {\n return this.detections[index];\n }\n\n [Symbol.iterator](): Iterator<DetectionResult> {\n return this.detections[Symbol.iterator]();\n }\n}\n\n/**\n * Per-image classification envelope (Ultralytics-style `Results`).\n */\nexport class ClassificationResults {\n constructor(\n public readonly probs: Probs,\n public readonly result: ClassificationResult,\n public readonly names: Readonly<Record<number, string>>,\n public readonly origImg: RGBImage,\n public readonly origShape: readonly [number, number],\n public readonly path: string | null = null,\n public readonly speed: Readonly<Record<string, number>> = {},\n ) {}\n\n /** Top-1 class index (Ultralytics-style alias). */\n get cls(): number {\n return this.probs.top1;\n }\n\n /** Top-1 confidence (Ultralytics-style alias). */\n get conf(): number {\n return this.probs.top1conf;\n }\n\n /** Top-1 class name. */\n get name(): string {\n return this.names[this.cls] ?? `class_${this.cls}`;\n }\n\n /** Per-class probability list, sorted descending (legacy field). */\n get probabilities(): readonly ClassificationResult[\"probabilities\"][number][] {\n return this.result.probabilities;\n }\n}\n\n/**\n * Per-image instance-segmentation envelope (Ultralytics-style `Results`).\n *\n * Iterating yields per-instance {@link SegmentationResult} entries. `boxes`\n * and `masks` mirror Ultralytics' bulk-array views.\n */\nexport class SegmentationResults implements Iterable<SegmentationResult> {\n constructor(\n public readonly boxes: Boxes,\n public readonly masks: Masks,\n public readonly detections: readonly SegmentationResult[],\n public readonly names: Readonly<Record<number, string>>,\n public readonly origImg: RGBImage,\n public readonly origShape: readonly [number, number],\n public readonly path: string | null = null,\n public readonly speed: Readonly<Record<string, number>> = {},\n ) {}\n\n /** Number of surviving instances. */\n get length(): number {\n return this.detections.length;\n }\n\n /** Index into the per-instance results. */\n get(index: number): SegmentationResult | undefined {\n return this.detections[index];\n }\n\n [Symbol.iterator](): Iterator<SegmentationResult> {\n return this.detections[Symbol.iterator]();\n }\n}\n","/**\n * Class label resolution: presets, lists, dicts, or auto-generated.\n *\n * Tasks call {@link resolveLabels} once at construction time to turn whatever\n * the caller passed (preset name, array, dict, or `null`) into an ordered\n * array of class names indexed by class id.\n *\n * In the browser there is no filesystem, so this module does not load labels\n * from a path — fetch the file yourself and pass an array.\n */\n\nimport { LabelMapError } from \"./core/exceptions\";\n\n/**\n * Anything accepted by {@link resolveLabels}.\n *\n * - `string[]` / `readonly string[]`: explicit names indexed by class id.\n * - `Record<number, string>`: sparse mapping (gaps filled with `class_<id>`).\n * - `string`: a preset name (e.g. `\"coco\"`).\n * - `null` / `undefined`: auto-generate `class_0` ... `class_{numClasses-1}`.\n */\nexport type LabelSpec = readonly string[] | Record<number, string> | string | null | undefined;\n\n/** COCO 2017 80-class labels in canonical class-id order. */\nexport const COCO_CLASSES: readonly string[] = Object.freeze([\n \"person\",\n \"bicycle\",\n \"car\",\n \"motorcycle\",\n \"airplane\",\n \"bus\",\n \"train\",\n \"truck\",\n \"boat\",\n \"traffic light\",\n \"fire hydrant\",\n \"stop sign\",\n \"parking meter\",\n \"bench\",\n \"bird\",\n \"cat\",\n \"dog\",\n \"horse\",\n \"sheep\",\n \"cow\",\n \"elephant\",\n \"bear\",\n \"zebra\",\n \"giraffe\",\n \"backpack\",\n \"umbrella\",\n \"handbag\",\n \"tie\",\n \"suitcase\",\n \"frisbee\",\n \"skis\",\n \"snowboard\",\n \"sports ball\",\n \"kite\",\n \"baseball bat\",\n \"baseball glove\",\n \"skateboard\",\n \"surfboard\",\n \"tennis racket\",\n \"bottle\",\n \"wine glass\",\n \"cup\",\n \"fork\",\n \"knife\",\n \"spoon\",\n \"bowl\",\n \"banana\",\n \"apple\",\n \"sandwich\",\n \"orange\",\n \"broccoli\",\n \"carrot\",\n \"hot dog\",\n \"pizza\",\n \"donut\",\n \"cake\",\n \"chair\",\n \"couch\",\n \"potted plant\",\n \"bed\",\n \"dining table\",\n \"toilet\",\n \"tv\",\n \"laptop\",\n \"mouse\",\n \"remote\",\n \"keyboard\",\n \"cell phone\",\n \"microwave\",\n \"oven\",\n \"toaster\",\n \"sink\",\n \"refrigerator\",\n \"book\",\n \"clock\",\n \"vase\",\n \"scissors\",\n \"teddy bear\",\n \"hair drier\",\n \"toothbrush\",\n]);\n\nconst PRESETS: Readonly<Record<string, readonly string[]>> = {\n coco: COCO_CLASSES,\n};\n\nexport interface ResolveLabelsOptions {\n /**\n * Expected number of classes.\n *\n * - When `spec` is `null`/`undefined`, this is required to auto-generate names.\n * - When `spec` is provided, it validates that the resolved length matches.\n */\n readonly numClasses?: number;\n}\n\n/**\n * Resolve a labels specification into an ordered array of class names.\n *\n * @throws {@link LabelMapError} if the spec is invalid, the preset is unknown,\n * or the resolved length disagrees with `numClasses`.\n */\nexport function resolveLabels(\n spec: LabelSpec,\n options: ResolveLabelsOptions = {},\n): readonly string[] {\n const labels = resolve(spec, options.numClasses);\n if (options.numClasses !== undefined && labels.length !== options.numClasses) {\n throw new LabelMapError(\n `Resolved ${labels.length} labels but the model has ${options.numClasses} classes.`,\n );\n }\n return labels;\n}\n\nfunction resolve(spec: LabelSpec, numClasses: number | undefined): readonly string[] {\n if (spec === null || spec === undefined) {\n if (numClasses === undefined) {\n throw new LabelMapError(\n \"Cannot auto-generate labels without numClasses. Pass an explicit labels spec or numClasses.\",\n );\n }\n return Array.from({ length: numClasses }, (_, i) => `class_${i}`);\n }\n\n if (Array.isArray(spec)) {\n return [...spec];\n }\n\n if (typeof spec === \"string\") {\n const preset = PRESETS[spec];\n if (preset !== undefined) {\n return preset;\n }\n throw new LabelMapError(\n `Unknown labels preset: ${JSON.stringify(spec)}. Known presets: ${Object.keys(PRESETS).join(\", \")}.`,\n );\n }\n\n if (typeof spec === \"object\") {\n const map = spec as Record<number, string>;\n const ids = Object.keys(map).map((k) => Number(k));\n if (ids.length === 0) {\n return [];\n }\n const maxId = Math.max(...ids);\n return Array.from({ length: maxId + 1 }, (_, i) => map[i] ?? `class_${i}`);\n }\n\n throw new LabelMapError(`Unsupported labels spec type: ${typeof spec}.`);\n}\n","/**\n * Execution-provider defaults for ONNX Runtime Web sessions.\n *\n * Unlike Node ORT, the browser ORT cannot enumerate \"available providers\" at\n * runtime — `webgpu` either works or ORT silently falls back to the next\n * provider in the list. We just expose a sensible default order.\n */\n\n/**\n * Default execution provider preference order for browser ORT.\n *\n * `webgpu` is tried first when available; ORT-Web falls back to `wasm`\n * automatically when WebGPU is not supported by the browser or device.\n */\nexport const DEFAULT_PROVIDERS: readonly string[] = [\"webgpu\", \"wasm\"];\n\n/**\n * Resolve the execution providers to pass to `InferenceSession.create`.\n *\n * @param requested Explicit provider list in preference order; `undefined` returns the default.\n */\nexport function resolveProviders(requested?: readonly string[]): string[] {\n if (requested === undefined) {\n return [...DEFAULT_PROVIDERS];\n }\n if (requested.length === 0) {\n return [...DEFAULT_PROVIDERS];\n }\n return [...requested];\n}\n","/**\n * Thin wrapper around `onnxruntime-web` `InferenceSession` with typed metadata.\n */\n\nimport type * as ort from \"onnxruntime-web\";\nimport * as ortRuntime from \"onnxruntime-web\";\n\nimport { InferenceError, ModelLoadError } from \"./exceptions\";\nimport { resolveProviders } from \"./providers\";\n\n/** Anything `InferenceSession.create` accepts. */\nexport type ModelSource = string | ArrayBufferLike | Uint8Array;\n\nexport interface OrtSessionOptions {\n /** Execution providers in preference order. `undefined` uses {@link DEFAULT_PROVIDERS}. */\n readonly providers?: readonly string[];\n /** Optional ORT session options forwarded to `InferenceSession.create`. */\n readonly sessionOptions?: ort.InferenceSession.SessionOptions;\n}\n\n/**\n * Wrap an ONNX Runtime Web `InferenceSession` with convenient metadata access.\n *\n * The wrapper exposes input/output names, manages execution-provider\n * selection, and provides a typed {@link OrtSession.run} method.\n */\nexport class OrtSession {\n private constructor(\n private readonly _session: ort.InferenceSession,\n public readonly providers: readonly string[],\n ) {}\n\n /**\n * Load an ONNX model into an ORT inference session.\n *\n * @param model Either a URL string fetched by ORT, or a `Uint8Array`/`ArrayBuffer` containing the model bytes.\n * @param options Provider list and pass-through `SessionOptions`.\n * @throws {@link ModelLoadError} if the model cannot be loaded.\n */\n static async create(model: ModelSource, options: OrtSessionOptions = {}): Promise<OrtSession> {\n const providers = resolveProviders(options.providers);\n const sessionOptions: ort.InferenceSession.SessionOptions = {\n ...(options.sessionOptions ?? {}),\n executionProviders:\n providers as ort.InferenceSession.SessionOptions[\"executionProviders\"],\n };\n\n let session: ort.InferenceSession;\n try {\n if (typeof model === \"string\") {\n session = await ortRuntime.InferenceSession.create(model, sessionOptions);\n } else if (model instanceof Uint8Array) {\n session = await ortRuntime.InferenceSession.create(model, sessionOptions);\n } else {\n session = await ortRuntime.InferenceSession.create(\n model as ArrayBuffer,\n sessionOptions,\n );\n }\n } catch (err) {\n throw new ModelLoadError(`Failed to load ONNX model: ${(err as Error).message}`, {\n cause: err,\n });\n }\n\n return new OrtSession(session, providers);\n }\n\n /** Names of the model's inputs, in declaration order. */\n get inputNames(): readonly string[] {\n return this._session.inputNames;\n }\n\n /** Name of the first (and usually only) input. */\n get inputName(): string {\n const name = this._session.inputNames[0];\n if (name === undefined) {\n throw new InferenceError(\"Model has no inputs.\");\n }\n return name;\n }\n\n /** Names of the model's outputs, in declaration order. */\n get outputNames(): readonly string[] {\n return this._session.outputNames;\n }\n\n /** The underlying `onnxruntime-web` session, for advanced use cases. */\n get raw(): ort.InferenceSession {\n return this._session;\n }\n\n /**\n * Run inference and return all outputs.\n *\n * @param feeds Map of input name to `ort.Tensor`. Keys must match {@link inputNames}.\n * @throws {@link InferenceError} if ORT raises any error during execution.\n */\n async run(feeds: Record<string, ort.Tensor>): Promise<Record<string, ort.Tensor>> {\n try {\n const result = await this._session.run(feeds);\n return result as Record<string, ort.Tensor>;\n } catch (err) {\n throw new InferenceError(`Inference failed: ${(err as Error).message}`, { cause: err });\n }\n }\n}\n","/**\n * Canvas plumbing shared by `io/image.ts` and `preprocess/image.ts`.\n *\n * Browsers and workers expose two canvas types (`HTMLCanvasElement` and\n * `OffscreenCanvas`) with slightly different surfaces. These helpers pick the\n * right one for the current environment, return a unified 2D context, and\n * convert between RGBA `ImageData` and the SDK's canonical HWC RGB\n * `RGBImage`.\n */\n\nimport { ImageLoadError } from \"./exceptions\";\nimport { RGBImage } from \"../types\";\n\nexport type Canvas2D = HTMLCanvasElement | OffscreenCanvas;\nexport type Context2D = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;\n\n/** Allocate a `Canvas2D`, preferring `OffscreenCanvas` when available. */\nexport function createCanvas(width: number, height: number): Canvas2D {\n if (typeof OffscreenCanvas !== \"undefined\") {\n return new OffscreenCanvas(width, height);\n }\n if (typeof document !== \"undefined\") {\n const c = document.createElement(\"canvas\");\n c.width = width;\n c.height = height;\n return c;\n }\n throw new ImageLoadError(\"No canvas implementation available in this environment.\");\n}\n\n/** Get a 2D context from a canvas, throwing a typed error if the browser refuses. */\nexport function get2DContext(canvas: Canvas2D): Context2D {\n const ctx = canvas.getContext(\"2d\") as Context2D | null;\n if (ctx === null) {\n throw new ImageLoadError(\"Failed to obtain 2D rendering context.\");\n }\n return ctx;\n}\n\n/** Convert RGBA `ImageData` into the canonical HWC RGB `RGBImage`. */\nexport function imageDataToRGB(imageData: ImageData): RGBImage {\n const { data, width, height } = imageData;\n if (data.length !== width * height * 4) {\n throw new ImageLoadError(\n `Unexpected ImageData length ${data.length} for ${width}x${height} (expected ${\n width * height * 4\n }).`,\n );\n }\n const rgb = new Uint8Array(width * height * 3);\n for (let i = 0, j = 0; i < data.length; i += 4, j += 3) {\n rgb[j] = data[i] as number;\n rgb[j + 1] = data[i + 1] as number;\n rgb[j + 2] = data[i + 2] as number;\n }\n return new RGBImage(rgb, width, height);\n}\n\n/** Convert an `RGBImage` into RGBA `ImageData` (alpha forced to 255). */\nexport function rgbToImageData(image: RGBImage): ImageData {\n const data = new Uint8ClampedArray(image.width * image.height * 4);\n for (let i = 0, j = 0; i < image.data.length; i += 3, j += 4) {\n data[j] = image.data[i] as number;\n data[j + 1] = image.data[i + 1] as number;\n data[j + 2] = image.data[i + 2] as number;\n data[j + 3] = 255;\n }\n return new ImageData(data, image.width, image.height);\n}\n","/**\n * Image loading utilities — convert any supported source into the canonical\n * {@link RGBImage} format.\n *\n * Browser-only: uses `fetch`, `createImageBitmap`, and a Canvas 2D context to\n * decode arbitrary inputs into a tightly-packed `Uint8Array` of HWC RGB pixels.\n */\n\nimport { createCanvas, get2DContext, imageDataToRGB } from \"../core/canvas\";\nimport { ImageLoadError } from \"../core/exceptions\";\nimport { RGBImage } from \"../types\";\n\n/** Anything {@link loadImage} accepts as an image input. */\nexport type ImageInput =\n | string\n | Blob\n | HTMLImageElement\n | HTMLCanvasElement\n | OffscreenCanvas\n | ImageBitmap\n | ImageData\n | RGBImage;\n\n/**\n * Load an image from any supported source into a HWC uint8 RGB array.\n *\n * @throws {@link ImageLoadError} if the source cannot be decoded or has an unsupported shape.\n */\nexport async function loadImage(source: ImageInput): Promise<RGBImage> {\n if (source instanceof RGBImage) {\n return source;\n }\n\n if (typeof ImageData !== \"undefined\" && source instanceof ImageData) {\n return imageDataToRGB(source);\n }\n\n if (typeof source === \"string\") {\n return loadFromUrl(source);\n }\n\n if (typeof Blob !== \"undefined\" && source instanceof Blob) {\n return loadFromBlob(source);\n }\n\n if (typeof HTMLImageElement !== \"undefined\" && source instanceof HTMLImageElement) {\n await waitForImageElement(source);\n return drawableToRGB(source, source.naturalWidth, source.naturalHeight);\n }\n\n if (typeof HTMLCanvasElement !== \"undefined\" && source instanceof HTMLCanvasElement) {\n return drawableToRGB(source, source.width, source.height);\n }\n\n if (typeof OffscreenCanvas !== \"undefined\" && source instanceof OffscreenCanvas) {\n return drawableToRGB(source, source.width, source.height);\n }\n\n if (typeof ImageBitmap !== \"undefined\" && source instanceof ImageBitmap) {\n return drawableToRGB(source, source.width, source.height);\n }\n\n throw new ImageLoadError(\n `Unsupported image source type: ${Object.prototype.toString.call(source)}`,\n );\n}\n\nasync function loadFromUrl(url: string): Promise<RGBImage> {\n let response: Response;\n try {\n response = await fetch(url);\n } catch (err) {\n throw new ImageLoadError(`Failed to fetch image from ${url}: ${(err as Error).message}`, {\n cause: err,\n });\n }\n if (!response.ok) {\n throw new ImageLoadError(\n `Failed to fetch image from ${url}: HTTP ${response.status} ${response.statusText}`,\n );\n }\n const blob = await response.blob();\n return loadFromBlob(blob);\n}\n\nasync function loadFromBlob(blob: Blob): Promise<RGBImage> {\n let bitmap: ImageBitmap;\n try {\n bitmap = await createImageBitmap(blob);\n } catch (err) {\n throw new ImageLoadError(`Failed to decode image blob: ${(err as Error).message}`, {\n cause: err,\n });\n }\n try {\n return drawableToRGB(bitmap, bitmap.width, bitmap.height);\n } finally {\n bitmap.close();\n }\n}\n\nfunction waitForImageElement(img: HTMLImageElement): Promise<void> {\n if (img.complete && img.naturalWidth > 0) {\n return Promise.resolve();\n }\n return new Promise<void>((resolve, reject) => {\n const onLoad = (): void => {\n cleanup();\n resolve();\n };\n const onError = (): void => {\n cleanup();\n reject(new ImageLoadError(\"Failed to load HTMLImageElement (load event errored)\"));\n };\n const cleanup = (): void => {\n img.removeEventListener(\"load\", onLoad);\n img.removeEventListener(\"error\", onError);\n };\n img.addEventListener(\"load\", onLoad, { once: true });\n img.addEventListener(\"error\", onError, { once: true });\n });\n}\n\nfunction drawableToRGB(drawable: CanvasImageSource, width: number, height: number): RGBImage {\n if (width === 0 || height === 0) {\n throw new ImageLoadError(`Cannot load image with zero dimension (${width}x${height}).`);\n }\n const canvas = createCanvas(width, height);\n const ctx = get2DContext(canvas);\n ctx.drawImage(drawable, 0, 0);\n const imageData = ctx.getImageData(0, 0, width, height);\n return imageDataToRGB(imageData);\n}\n","/**\n * Composable image preprocessing primitives (resize, normalize, letterbox, layout).\n *\n * Mirrors the Python `preprocess.image` module. Operates on the canonical\n * {@link RGBImage} (HWC RGB uint8) and produces uint8 or float32 buffers\n * depending on the operation.\n */\n\nimport * as ortRuntime from \"onnxruntime-web\";\nimport type * as ort from \"onnxruntime-web\";\n\nimport { createCanvas, get2DContext, imageDataToRGB, rgbToImageData } from \"../core/canvas\";\nimport { RGBImage } from \"../types\";\n\n/** Resize an image to `(targetWidth, targetHeight)` using high-quality canvas resampling. */\nexport function resize(image: RGBImage, targetWidth: number, targetHeight: number): RGBImage {\n if (targetWidth <= 0 || targetHeight <= 0) {\n throw new Error(`Invalid resize target ${targetWidth}x${targetHeight}.`);\n }\n if (targetWidth === image.width && targetHeight === image.height) {\n return image;\n }\n\n const srcCanvas = createCanvas(image.width, image.height);\n const srcCtx = get2DContext(srcCanvas);\n srcCtx.putImageData(rgbToImageData(image), 0, 0);\n\n const dstCanvas = createCanvas(targetWidth, targetHeight);\n const dstCtx = get2DContext(dstCanvas);\n dstCtx.imageSmoothingEnabled = true;\n dstCtx.imageSmoothingQuality = \"high\";\n dstCtx.drawImage(srcCanvas as CanvasImageSource, 0, 0, targetWidth, targetHeight);\n\n const imageData = dstCtx.getImageData(0, 0, targetWidth, targetHeight);\n return imageDataToRGB(imageData);\n}\n\n/**\n * Convert a uint8 image to a normalized float32 array (HWC layout preserved).\n *\n * Applies `(pixel * scale - mean) / std` channel-wise.\n */\nexport function normalize(\n image: RGBImage,\n mean: readonly [number, number, number],\n std: readonly [number, number, number],\n scale: number = 1 / 255,\n): Float32Array {\n const out = new Float32Array(image.data.length);\n const data = image.data;\n const m0 = mean[0];\n const m1 = mean[1];\n const m2 = mean[2];\n const s0 = std[0];\n const s1 = std[1];\n const s2 = std[2];\n for (let i = 0; i < data.length; i += 3) {\n out[i] = ((data[i] as number) * scale - m0) / s0;\n out[i + 1] = ((data[i + 1] as number) * scale - m1) / s1;\n out[i + 2] = ((data[i + 2] as number) * scale - m2) / s2;\n }\n return out;\n}\n\n/** Convert a uint8 image to a `Float32Array` in `[0, 1]` (HWC layout preserved). */\nexport function toFloat32(image: RGBImage, scale: number = 1 / 255): Float32Array {\n const out = new Float32Array(image.data.length);\n const data = image.data;\n for (let i = 0; i < data.length; i++) {\n out[i] = (data[i] as number) * scale;\n }\n return out;\n}\n\n/**\n * Transpose interleaved HWC data to planar CHW layout.\n *\n * @param hwc Source array of length `width * height * channels`.\n */\nexport function toCHW(\n hwc: Float32Array,\n width: number,\n height: number,\n channels: number = 3,\n): Float32Array {\n const expected = width * height * channels;\n if (hwc.length !== expected) {\n throw new Error(\n `toCHW: expected length ${expected} for ${width}x${height}x${channels}, got ${hwc.length}.`,\n );\n }\n const chw = new Float32Array(expected);\n const plane = width * height;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const hwcBase = (y * width + x) * channels;\n const planeIdx = y * width + x;\n for (let c = 0; c < channels; c++) {\n chw[c * plane + planeIdx] = hwc[hwcBase + c] as number;\n }\n }\n }\n return chw;\n}\n\n/** Wrap a Float32 buffer into an `ort.Tensor`. */\nexport function toFloat32Tensor(data: Float32Array, dims: readonly number[]): ort.Tensor {\n return new ortRuntime.Tensor(\"float32\", data, dims as number[]);\n}\n\n/**\n * Convert an HWC uint8 image to a CHW `Float32Array` scaled to `[0, 1]`.\n *\n * Mirrors `torchvision.transforms.ToTensor()` semantics: HWC → CHW,\n * `uint8 → float32 / 255`. Useful as input to YOLO-style detectors that\n * don't require ImageNet normalization.\n *\n * @returns CHW `Float32Array` of length `width * height * 3`.\n */\nexport function toTensor(image: RGBImage): Float32Array {\n const f32 = toFloat32(image);\n return toCHW(f32, image.width, image.height, 3);\n}\n\n/**\n * Convert an HWC BGR uint8 buffer (OpenCV layout) to the SDK's HWC RGB.\n *\n * Use when you receive image bytes from `cv2.imencode` over the wire and\n * want to feed them to the SDK without going through a canvas decode.\n *\n * @param bgr Flat BGR Uint8Array of length `width * height * 3`.\n */\nexport function fromCv2(bgr: Uint8Array, width: number, height: number): RGBImage {\n if (bgr.length !== width * height * 3) {\n throw new Error(\n `fromCv2: data length ${bgr.length} does not match width * height * 3 = ${width * height * 3}.`,\n );\n }\n const rgb = new Uint8Array(bgr.length);\n for (let i = 0; i < bgr.length; i += 3) {\n rgb[i] = bgr[i + 2] as number;\n rgb[i + 1] = bgr[i + 1] as number;\n rgb[i + 2] = bgr[i] as number;\n }\n return new RGBImage(rgb, width, height);\n}\n\n/**\n * Convert the SDK's HWC RGB image to an HWC BGR `Uint8Array` (OpenCV layout).\n *\n * Useful for round-tripping data to a Python OpenCV consumer.\n */\nexport function toCv2(image: RGBImage): Uint8Array {\n const rgb = image.data;\n const bgr = new Uint8Array(rgb.length);\n for (let i = 0; i < rgb.length; i += 3) {\n bgr[i] = rgb[i + 2] as number;\n bgr[i + 1] = rgb[i + 1] as number;\n bgr[i + 2] = rgb[i] as number;\n }\n return bgr;\n}\n\nexport interface LetterboxResult {\n /** The padded image at the target size. */\n readonly image: RGBImage;\n /** The factor applied to the original image (`< 1` if downscaled). */\n readonly scale: number;\n /** Horizontal padding in pixels (left side; right side has the same or +1). */\n readonly padLeft: number;\n /** Vertical padding in pixels (top side). */\n readonly padTop: number;\n}\n\n/**\n * Resize preserving aspect ratio, padding to `(targetWidth, targetHeight)`\n * with a constant fill color.\n *\n * Standard YOLO preprocessing — returning `scale` and `padLeft`/`padTop`\n * lets callers map detections back to the original image coordinates.\n */\nexport function letterbox(\n image: RGBImage,\n targetWidth: number,\n targetHeight: number,\n fill: readonly [number, number, number] = [114, 114, 114],\n): LetterboxResult {\n const scale = Math.min(targetWidth / image.width, targetHeight / image.height);\n const newW = Math.round(image.width * scale);\n const newH = Math.round(image.height * scale);\n const resized = resize(image, newW, newH);\n\n const out = new Uint8Array(targetWidth * targetHeight * 3);\n const f0 = fill[0];\n const f1 = fill[1];\n const f2 = fill[2];\n for (let i = 0; i < out.length; i += 3) {\n out[i] = f0;\n out[i + 1] = f1;\n out[i + 2] = f2;\n }\n\n const padLeft = Math.floor((targetWidth - newW) / 2);\n const padTop = Math.floor((targetHeight - newH) / 2);\n const rowBytes = newW * 3;\n for (let y = 0; y < newH; y++) {\n const srcOffset = y * rowBytes;\n const dstOffset = ((padTop + y) * targetWidth + padLeft) * 3;\n out.set(resized.data.subarray(srcOffset, srcOffset + rowBytes), dstOffset);\n }\n\n return {\n image: new RGBImage(out, targetWidth, targetHeight),\n scale,\n padLeft,\n padTop,\n };\n}\n","/**\n * Classification head postprocessing — softmax + top-k.\n */\n\n/** Apply numerically-stable softmax to a 1-D vector of logits. */\nexport function softmax(logits: Float32Array | readonly number[]): Float32Array {\n const n = logits.length;\n const out = new Float32Array(n);\n let max = -Infinity;\n for (let i = 0; i < n; i++) {\n const v = logits[i] as number;\n if (v > max) max = v;\n }\n let sum = 0;\n for (let i = 0; i < n; i++) {\n const e = Math.exp((logits[i] as number) - max);\n out[i] = e;\n sum += e;\n }\n for (let i = 0; i < n; i++) {\n out[i] = (out[i] as number) / sum;\n }\n return out;\n}\n\nexport interface TopKResult {\n readonly indices: Int32Array;\n readonly values: Float32Array;\n}\n\n/**\n * Return the top-k entries of a 1-D probability vector, sorted descending.\n *\n * @param k Number of entries to return; `null` returns all entries.\n */\nexport function topK(probabilities: Float32Array, k: number | null): TopKResult {\n const n = probabilities.length;\n const kEff = k === null ? n : Math.min(Math.max(0, k), n);\n\n const idx = new Array<number>(n);\n for (let i = 0; i < n; i++) idx[i] = i;\n idx.sort((a, b) => (probabilities[b] as number) - (probabilities[a] as number));\n\n const indices = new Int32Array(kEff);\n const values = new Float32Array(kEff);\n for (let i = 0; i < kEff; i++) {\n const j = idx[i] as number;\n indices[i] = j;\n values[i] = probabilities[j] as number;\n }\n return { indices, values };\n}\n","/**\n * Detection head postprocessing: anchor-free YOLO decoding + non-maximum suppression.\n *\n * The shared {@link decodeYoloAnchors} helper does the per-anchor work that\n * is identical for plain detection and segmentation (transpose, xywh→xyxy,\n * letterbox unmap, per-class NMS, sort & cap). {@link decodeYolo} is a thin\n * wrapper around it; the segmentation module ({@link ./segmentation.js})\n * calls the helper directly so it can also recover the per-anchor mask\n * coefficients.\n *\n * Works for any YOLO export with the post-v8 anchor-free head:\n * **YOLOv8 / v9 / v10 / v11 / v12** detect heads, all of which share the\n * `[1, 4 + nc, N]` output layout.\n */\n\nimport { BoundingBox } from \"../types\";\n\n/**\n * Greedy non-maximum suppression on axis-aligned bounding boxes.\n *\n * Mirrors `torchvision.ops.nms` (keeps boxes with the highest score, drops\n * any subsequent box whose IoU exceeds the threshold).\n *\n * @param boxes Flat array of length `4 * N` in xyxy order: `[x1,y1,x2,y2, ...]`.\n * @param scores Detection score per box, length `N`.\n * @param iouThreshold Boxes with IoU above this threshold relative to a kept box are suppressed.\n * @returns Indices of kept boxes, in descending score order.\n */\nexport function nms(boxes: Float32Array, scores: Float32Array, iouThreshold: number): Int32Array {\n const n = scores.length;\n if (n === 0) return new Int32Array(0);\n\n const areas = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const x1 = boxes[i * 4] as number;\n const y1 = boxes[i * 4 + 1] as number;\n const x2 = boxes[i * 4 + 2] as number;\n const y2 = boxes[i * 4 + 3] as number;\n areas[i] = Math.max(0, x2 - x1) * Math.max(0, y2 - y1);\n }\n\n const order = new Array<number>(n);\n for (let i = 0; i < n; i++) order[i] = i;\n order.sort((a, b) => (scores[b] as number) - (scores[a] as number));\n\n const suppressed = new Uint8Array(n);\n const keep: number[] = [];\n\n for (let oi = 0; oi < order.length; oi++) {\n const i = order[oi] as number;\n if (suppressed[i]) continue;\n keep.push(i);\n\n const ax1 = boxes[i * 4] as number;\n const ay1 = boxes[i * 4 + 1] as number;\n const ax2 = boxes[i * 4 + 2] as number;\n const ay2 = boxes[i * 4 + 3] as number;\n const ai = areas[i] as number;\n\n for (let oj = oi + 1; oj < order.length; oj++) {\n const j = order[oj] as number;\n if (suppressed[j]) continue;\n\n const bx1 = boxes[j * 4] as number;\n const by1 = boxes[j * 4 + 1] as number;\n const bx2 = boxes[j * 4 + 2] as number;\n const by2 = boxes[j * 4 + 3] as number;\n\n const ix1 = Math.max(ax1, bx1);\n const iy1 = Math.max(ay1, by1);\n const ix2 = Math.min(ax2, bx2);\n const iy2 = Math.min(ay2, by2);\n const iw = Math.max(0, ix2 - ix1);\n const ih = Math.max(0, iy2 - iy1);\n const inter = iw * ih;\n const union = ai + (areas[j] as number) - inter;\n const iou = union > 0 ? inter / union : 0;\n if (iou > iouThreshold) suppressed[j] = 1;\n }\n }\n\n return Int32Array.from(keep);\n}\n\n/**\n * Per-class NMS — boxes are suppressed only by other boxes of the same class.\n *\n * Mirrors `torchvision.ops.batched_nms`.\n *\n * @param boxes Flat array of length `4 * N` in xyxy order.\n * @param scores Detection score per box, length `N`.\n * @param idxs Class index per box, length `N`. Boxes with different `idxs`\n * never suppress each other.\n * @param iouThreshold IoU threshold for suppression within a class.\n */\nexport function batchedNms(\n boxes: Float32Array,\n scores: Float32Array,\n idxs: Int32Array,\n iouThreshold: number,\n): Int32Array {\n if (scores.length === 0) return new Int32Array(0);\n\n const byClass = new Map<number, number[]>();\n for (let i = 0; i < idxs.length; i++) {\n const c = idxs[i] as number;\n const list = byClass.get(c);\n if (list === undefined) byClass.set(c, [i]);\n else list.push(i);\n }\n\n const keep: number[] = [];\n for (const indices of byClass.values()) {\n const m = indices.length;\n const subBoxes = new Float32Array(m * 4);\n const subScores = new Float32Array(m);\n for (let k = 0; k < m; k++) {\n const i = indices[k] as number;\n subBoxes[k * 4] = boxes[i * 4] as number;\n subBoxes[k * 4 + 1] = boxes[i * 4 + 1] as number;\n subBoxes[k * 4 + 2] = boxes[i * 4 + 2] as number;\n subBoxes[k * 4 + 3] = boxes[i * 4 + 3] as number;\n subScores[k] = scores[i] as number;\n }\n const subKeep = nms(subBoxes, subScores, iouThreshold);\n for (let k = 0; k < subKeep.length; k++) {\n keep.push(indices[subKeep[k] as number] as number);\n }\n }\n\n keep.sort((a, b) => (scores[b] as number) - (scores[a] as number));\n return Int32Array.from(keep);\n}\n\nexport interface DecodeYoloAnchorsOptions {\n /** Number of class-score channels following the 4 box channels. */\n readonly numClasses: number;\n readonly originalWidth: number;\n readonly originalHeight: number;\n readonly padLeft: number;\n readonly padTop: number;\n readonly scale: number;\n readonly confThreshold: number;\n readonly iouThreshold: number;\n readonly maxDetections: number;\n}\n\nexport interface DecodedAnchors {\n /** Indices into the original `numAnchors` axis, in descending confidence order. */\n readonly anchorIndices: Int32Array;\n /** `[k, 4]` boxes in original-image pixel coords, flat row-major xyxy. */\n readonly boxesXyxy: Float32Array;\n /** Predicted class id per survivor. */\n readonly classIds: Int32Array;\n /** Confidence per survivor. */\n readonly confidences: Float32Array;\n}\n\n/**\n * Shared YOLO per-anchor decode used by both detection and segmentation\n * (v8 / v9 / v10 / v11 / v12).\n *\n * Only the first `4 + numClasses` channels are read; later channels (e.g.\n * mask coefficients) are ignored — callers can fetch them via the returned\n * {@link DecodedAnchors.anchorIndices}.\n *\n * @param data Flat per-anchor output, length `channels * numAnchors`.\n * @param dims Dims as reported by ORT, e.g. `[1, 84, 8400]` (det) or\n * `[1, 116, 8400]` (seg). The leading batch dim must be 1.\n */\nexport function decodeYoloAnchors(\n data: Float32Array,\n dims: readonly number[],\n options: DecodeYoloAnchorsOptions,\n): DecodedAnchors {\n let normalized = dims;\n if (normalized.length === 3) {\n if (normalized[0] !== 1) {\n throw new Error(`decodeYoloAnchors: expected batch size 1, got ${normalized[0]}.`);\n }\n normalized = [normalized[1] as number, normalized[2] as number];\n }\n if (normalized.length !== 2) {\n throw new Error(\n `decodeYoloAnchors: expected 2-D output after batch removal, got dims=${JSON.stringify(dims)}.`,\n );\n }\n const channels = normalized[0] as number;\n const numAnchors = normalized[1] as number;\n\n const {\n numClasses,\n originalWidth,\n originalHeight,\n padLeft,\n padTop,\n scale,\n confThreshold,\n iouThreshold,\n maxDetections,\n } = options;\n\n if (numClasses < 1 || numClasses + 4 > channels) {\n throw new Error(\n `decodeYoloAnchors: invalid numClasses=${numClasses} for channels=${channels}.`,\n );\n }\n if (data.length !== channels * numAnchors) {\n throw new Error(\n `decodeYoloAnchors: data length ${data.length} does not match channels*numAnchors=${channels * numAnchors}.`,\n );\n }\n\n type Candidate = {\n anchorIdx: number;\n x1: number;\n y1: number;\n x2: number;\n y2: number;\n classId: number;\n confidence: number;\n };\n const candidates: Candidate[] = [];\n\n for (let a = 0; a < numAnchors; a++) {\n let bestCls = 0;\n let bestScore = -Infinity;\n for (let c = 0; c < numClasses; c++) {\n const s = data[(4 + c) * numAnchors + a];\n if (s !== undefined && s > bestScore) {\n bestScore = s;\n bestCls = c;\n }\n }\n if (bestScore < confThreshold) continue;\n\n const cx = data[a] as number;\n const cy = data[numAnchors + a] as number;\n const w = data[2 * numAnchors + a] as number;\n const h = data[3 * numAnchors + a] as number;\n\n let x1 = cx - w / 2;\n let y1 = cy - h / 2;\n let x2 = cx + w / 2;\n let y2 = cy + h / 2;\n\n x1 = (x1 - padLeft) / scale;\n y1 = (y1 - padTop) / scale;\n x2 = (x2 - padLeft) / scale;\n y2 = (y2 - padTop) / scale;\n\n x1 = Math.max(0, Math.min(originalWidth, x1));\n y1 = Math.max(0, Math.min(originalHeight, y1));\n x2 = Math.max(0, Math.min(originalWidth, x2));\n y2 = Math.max(0, Math.min(originalHeight, y2));\n\n candidates.push({ anchorIdx: a, x1, y1, x2, y2, classId: bestCls, confidence: bestScore });\n }\n\n if (candidates.length === 0) return emptyDecoded();\n\n // Build flat arrays then delegate to batchedNms — same algorithm as before\n // but funnelled through the public per-class NMS helper.\n const flatBoxes = new Float32Array(candidates.length * 4);\n const scoresArr = new Float32Array(candidates.length);\n const idxsArr = new Int32Array(candidates.length);\n for (let i = 0; i < candidates.length; i++) {\n const c = candidates[i] as Candidate;\n flatBoxes[i * 4] = c.x1;\n flatBoxes[i * 4 + 1] = c.y1;\n flatBoxes[i * 4 + 2] = c.x2;\n flatBoxes[i * 4 + 3] = c.y2;\n scoresArr[i] = c.confidence;\n idxsArr[i] = c.classId;\n }\n const kept = batchedNms(flatBoxes, scoresArr, idxsArr, iouThreshold);\n if (kept.length === 0) return emptyDecoded();\n\n const limited = Array.from(kept).slice(0, maxDetections);\n const k = limited.length;\n const anchorIndices = new Int32Array(k);\n const boxesXyxy = new Float32Array(k * 4);\n const classIds = new Int32Array(k);\n const confidences = new Float32Array(k);\n for (let i = 0; i < k; i++) {\n const c = candidates[limited[i] as number] as Candidate;\n anchorIndices[i] = c.anchorIdx;\n boxesXyxy[i * 4] = c.x1;\n boxesXyxy[i * 4 + 1] = c.y1;\n boxesXyxy[i * 4 + 2] = c.x2;\n boxesXyxy[i * 4 + 3] = c.y2;\n classIds[i] = c.classId;\n confidences[i] = c.confidence;\n }\n return { anchorIndices, boxesXyxy, classIds, confidences };\n}\n\nfunction emptyDecoded(): DecodedAnchors {\n return {\n anchorIndices: new Int32Array(0),\n boxesXyxy: new Float32Array(0),\n classIds: new Int32Array(0),\n confidences: new Float32Array(0),\n };\n}\n\nexport interface DecodeYoloOptions {\n readonly originalWidth: number;\n readonly originalHeight: number;\n readonly padLeft: number;\n readonly padTop: number;\n readonly scale: number;\n readonly confThreshold: number;\n readonly iouThreshold: number;\n readonly maxDetections: number;\n}\n\nexport interface DecodedDetection {\n readonly bbox: BoundingBox;\n readonly classId: number;\n readonly confidence: number;\n}\n\n/**\n * Decode an anchor-free YOLO detection output into a list of detections.\n *\n * Works for **YOLOv8 / v9 / v10 / v11 / v12** detect heads.\n *\n * Expected raw shape: `[1, 4 + numClasses, N]`. `numClasses` is inferred\n * from the channel count.\n */\nexport function decodeYolo(\n output: Float32Array,\n outputDims: readonly number[],\n options: DecodeYoloOptions,\n): DecodedDetection[] {\n const channels = outputDims.length === 3 ? outputDims[1] : outputDims[0];\n if (channels === undefined || channels < 5) {\n throw new Error(`decodeYolo: invalid output channel count ${channels} (expected >= 5).`);\n }\n const numClasses = channels - 4;\n\n const decoded = decodeYoloAnchors(output, outputDims, {\n numClasses,\n ...options,\n });\n\n const results: DecodedDetection[] = [];\n for (let i = 0; i < decoded.classIds.length; i++) {\n results.push({\n bbox: new BoundingBox(\n decoded.boxesXyxy[i * 4] as number,\n decoded.boxesXyxy[i * 4 + 1] as number,\n decoded.boxesXyxy[i * 4 + 2] as number,\n decoded.boxesXyxy[i * 4 + 3] as number,\n ),\n classId: decoded.classIds[i] as number,\n confidence: decoded.confidences[i] as number,\n });\n }\n return results;\n}\n\nlet _warnedDecodeYoloV8 = false;\nlet _warnedDecodeYoloV8Anchors = false;\n\n/**\n * @deprecated since 0.2.0 — use {@link decodeYolo}. Same behavior; the\n * decoder covers v8/v9/v10/v11/v12 detect heads. Will be removed in 0.3.0.\n */\nexport function decodeYoloV8(\n output: Float32Array,\n outputDims: readonly number[],\n options: DecodeYoloOptions,\n): DecodedDetection[] {\n if (!_warnedDecodeYoloV8) {\n _warnedDecodeYoloV8 = true;\n console.warn(\n \"[@ort-vision-sdk/web] decodeYoloV8 is deprecated since 0.2.0; use decodeYolo. \" +\n \"The alias will be removed in 0.3.0.\",\n );\n }\n return decodeYolo(output, outputDims, options);\n}\n\n/**\n * @deprecated since 0.2.0 — use {@link decodeYoloAnchors}. Will be removed in 0.3.0.\n */\nexport function decodeYoloV8Anchors(\n data: Float32Array,\n dims: readonly number[],\n options: DecodeYoloAnchorsOptions,\n): DecodedAnchors {\n if (!_warnedDecodeYoloV8Anchors) {\n _warnedDecodeYoloV8Anchors = true;\n console.warn(\n \"[@ort-vision-sdk/web] decodeYoloV8Anchors is deprecated since 0.2.0; use decodeYoloAnchors. \" +\n \"The alias will be removed in 0.3.0.\",\n );\n }\n return decodeYoloAnchors(data, dims, options);\n}\n\n/** @deprecated since 0.2.0 — use {@link DecodeYoloAnchorsOptions}. */\nexport type DecodeYoloV8AnchorsOptions = DecodeYoloAnchorsOptions;\n\n/** @deprecated since 0.2.0 — use {@link DecodeYoloOptions}. */\nexport type DecodeYoloV8Options = DecodeYoloOptions;\n","/**\n * Segmentation head postprocessing: YOLO instance-segmentation decoding.\n *\n * Compatible with YOLOv8-seg / YOLOv11-seg exports (and any later seg head\n * sharing the layout). The model produces two output tensors:\n *\n * - `output0` of shape `(1, 4 + numClasses + numMaskCoefs, numAnchors)` — the\n * same per-anchor predictions as plain YOLO detection plus an extra\n * `numMaskCoefs` (typically 32) channels of mask coefficients.\n * - `output1` of shape `(1, numMaskCoefs, maskH, maskW)` — a set of \"prototype\"\n * masks shared across all anchors.\n *\n * The per-anchor decode (xywh→xyxy, undo letterbox, per-class NMS, sort & cap)\n * is delegated to {@link decodeYoloAnchors}; this module only handles the\n * mask-specific work: matmul against prototypes, sigmoid, bilinear resize and\n * thresholding.\n */\n\nimport { decodeYoloAnchors } from \"./detection\";\nimport { BoundingBox, Mask } from \"../types\";\n\nexport interface DecodeYoloSegOptions {\n readonly numClasses: number;\n /** Model input `[width, height]` (post-letterbox). */\n readonly inputWidth: number;\n readonly inputHeight: number;\n /** Original image `[width, height]`. */\n readonly originalWidth: number;\n readonly originalHeight: number;\n /** Letterbox horizontal padding in input-tensor pixels. */\n readonly padLeft: number;\n /** Letterbox vertical padding in input-tensor pixels. */\n readonly padTop: number;\n /** Letterbox scale factor. */\n readonly scale: number;\n readonly confThreshold: number;\n readonly iouThreshold: number;\n readonly maxDetections: number;\n /** Probability cutoff applied to the soft mask. Defaults to `0.5`. */\n readonly maskThreshold?: number;\n}\n\nexport interface DecodedSegmentation {\n readonly bbox: BoundingBox;\n readonly classId: number;\n readonly confidence: number;\n /** Binary mask cropped to `bbox`. Width/height match `bbox.asIntXyxy()` extents. */\n readonly mask: Mask;\n}\n\n/**\n * Decode YOLO segmentation raw outputs into a list of segmented instances.\n *\n * Compatible with YOLOv8-seg / YOLOv11-seg.\n *\n * @param perAnchorData Flat `output0`, length `(4 + numClasses + numMaskCoefs) * numAnchors`.\n * @param perAnchorDims Dims as reported by ORT, e.g. `[1, 116, 8400]`.\n * @param prototypeData Flat `output1`, length `numMaskCoefs * maskH * maskW`.\n * @param prototypeDims Dims as reported by ORT, e.g. `[1, 32, 160, 160]`.\n */\nexport function decodeYoloSeg(\n perAnchorData: Float32Array,\n perAnchorDims: readonly number[],\n prototypeData: Float32Array,\n prototypeDims: readonly number[],\n options: DecodeYoloSegOptions,\n): DecodedSegmentation[] {\n // Strip batch dim from prototypes; perAnchor batch is validated by the helper.\n let pDims = prototypeDims;\n if (pDims.length === 4) {\n if (pDims[0] !== 1) {\n throw new Error(`decodeYoloSeg: expected batch size 1 in prototypes, got ${pDims[0]}.`);\n }\n pDims = [pDims[1] as number, pDims[2] as number, pDims[3] as number];\n }\n if (pDims.length !== 3) {\n throw new Error(\n `decodeYoloSeg: expected 3-D prototypes after batch removal, got dims=${JSON.stringify(prototypeDims)}.`,\n );\n }\n const numMaskCoefs = pDims[0] as number;\n const maskH = pDims[1] as number;\n const maskW = pDims[2] as number;\n\n const channels = perAnchorDims.length === 3 ? perAnchorDims[1] : perAnchorDims[0];\n const numAnchors = perAnchorDims.length === 3 ? perAnchorDims[2] : perAnchorDims[1];\n if (channels === undefined || numAnchors === undefined) {\n throw new Error(\n `decodeYoloSeg: cannot read channels/numAnchors from dims=${JSON.stringify(perAnchorDims)}.`,\n );\n }\n\n const expectedChannels = 4 + options.numClasses + numMaskCoefs;\n if (channels !== expectedChannels) {\n throw new Error(\n `decodeYoloSeg: channels=${channels} does not match 4 + numClasses(${options.numClasses}) + numMaskCoefs(${numMaskCoefs}) = ${expectedChannels}.`,\n );\n }\n if (prototypeData.length !== numMaskCoefs * maskH * maskW) {\n throw new Error(\n `decodeYoloSeg: prototype length ${prototypeData.length} does not match dims=${JSON.stringify(prototypeDims)}.`,\n );\n }\n\n const decoded = decodeYoloAnchors(perAnchorData, perAnchorDims, {\n numClasses: options.numClasses,\n originalWidth: options.originalWidth,\n originalHeight: options.originalHeight,\n padLeft: options.padLeft,\n padTop: options.padTop,\n scale: options.scale,\n confThreshold: options.confThreshold,\n iouThreshold: options.iouThreshold,\n maxDetections: options.maxDetections,\n });\n\n if (decoded.anchorIndices.length === 0) return [];\n\n const maskThreshold = options.maskThreshold ?? 0.5;\n const scaleX = maskW / options.inputWidth;\n const scaleY = maskH / options.inputHeight;\n const protoPlane = maskH * maskW;\n const coefBase = (4 + options.numClasses) * numAnchors;\n\n const results: DecodedSegmentation[] = [];\n\n for (let i = 0; i < decoded.anchorIndices.length; i++) {\n const a = decoded.anchorIndices[i] as number;\n const x1 = decoded.boxesXyxy[i * 4] as number;\n const y1 = decoded.boxesXyxy[i * 4 + 1] as number;\n const x2 = decoded.boxesXyxy[i * 4 + 2] as number;\n const y2 = decoded.boxesXyxy[i * 4 + 3] as number;\n const bbox = new BoundingBox(x1, y1, x2, y2);\n const classId = decoded.classIds[i] as number;\n const confidence = decoded.confidences[i] as number;\n\n const bboxW = Math.max(0, Math.trunc(x2) - Math.trunc(x1));\n const bboxH = Math.max(0, Math.trunc(y2) - Math.trunc(y1));\n\n if (bboxW === 0 || bboxH === 0) {\n results.push({ bbox, classId, confidence, mask: new Mask(new Uint8Array(0), 0, 0) });\n continue;\n }\n\n // Bbox in input-tensor coords, then in low-res mask coords.\n const ibx1 = x1 * options.scale + options.padLeft;\n const iby1 = y1 * options.scale + options.padTop;\n const ibx2 = x2 * options.scale + options.padLeft;\n const iby2 = y2 * options.scale + options.padTop;\n\n const mbx1 = Math.max(0, Math.floor(ibx1 * scaleX));\n const mby1 = Math.max(0, Math.floor(iby1 * scaleY));\n const mbx2 = Math.min(maskW, Math.ceil(ibx2 * scaleX));\n const mby2 = Math.min(maskH, Math.ceil(iby2 * scaleY));\n\n if (mbx2 <= mbx1 || mby2 <= mby1) {\n results.push({\n bbox,\n classId,\n confidence,\n mask: new Mask(new Uint8Array(bboxW * bboxH), bboxW, bboxH),\n });\n continue;\n }\n\n // Compute soft mask only within the prototype region under this bbox.\n const cropW = mbx2 - mbx1;\n const cropH = mby2 - mby1;\n const softCrop = new Float32Array(cropW * cropH);\n for (let y = 0; y < cropH; y++) {\n const py = mby1 + y;\n for (let x = 0; x < cropW; x++) {\n const px = mbx1 + x;\n let sum = 0;\n for (let kk = 0; kk < numMaskCoefs; kk++) {\n const coef = perAnchorData[coefBase + kk * numAnchors + a];\n const proto = prototypeData[kk * protoPlane + py * maskW + px];\n sum += coef * proto;\n }\n softCrop[y * cropW + x] = sigmoid(sum);\n }\n }\n\n const resized = resizeBilinear(softCrop, cropW, cropH, bboxW, bboxH);\n const binary = new Uint8Array(bboxW * bboxH);\n for (let j = 0; j < binary.length; j++) {\n binary[j] = resized[j] >= maskThreshold ? 255 : 0;\n }\n\n results.push({ bbox, classId, confidence, mask: new Mask(binary, bboxW, bboxH) });\n }\n\n return results;\n}\n\nfunction sigmoid(x: number): number {\n if (x >= 0) {\n return 1 / (1 + Math.exp(-x));\n }\n const e = Math.exp(x);\n return e / (1 + e);\n}\n\nlet _warnedDecodeYoloV8Seg = false;\n\n/** @deprecated since 0.2.0 — use {@link decodeYoloSeg}. Will be removed in 0.3.0. */\nexport function decodeYoloV8Seg(\n perAnchorData: Float32Array,\n perAnchorDims: readonly number[],\n prototypeData: Float32Array,\n prototypeDims: readonly number[],\n options: DecodeYoloSegOptions,\n): DecodedSegmentation[] {\n if (!_warnedDecodeYoloV8Seg) {\n _warnedDecodeYoloV8Seg = true;\n console.warn(\n \"[@ort-vision-sdk/web] decodeYoloV8Seg is deprecated since 0.2.0; use decodeYoloSeg. \" +\n \"The alias will be removed in 0.3.0.\",\n );\n }\n return decodeYoloSeg(perAnchorData, perAnchorDims, prototypeData, prototypeDims, options);\n}\n\n/** @deprecated since 0.2.0 — use {@link DecodeYoloSegOptions}. */\nexport type DecodeYoloV8SegOptions = DecodeYoloSegOptions;\n\nfunction resizeBilinear(\n src: Float32Array,\n srcWidth: number,\n srcHeight: number,\n targetWidth: number,\n targetHeight: number,\n): Float32Array {\n const out = new Float32Array(targetWidth * targetHeight);\n if (targetWidth === 0 || targetHeight === 0 || srcWidth === 0 || srcHeight === 0) {\n return out;\n }\n if (targetWidth === srcWidth && targetHeight === srcHeight) {\n out.set(src);\n return out;\n }\n const sx = srcWidth / targetWidth;\n const sy = srcHeight / targetHeight;\n for (let y = 0; y < targetHeight; y++) {\n const yy = (y + 0.5) * sy - 0.5;\n const y0 = Math.max(0, Math.floor(yy));\n const y1 = Math.min(srcHeight - 1, y0 + 1);\n const wy = Math.max(0, Math.min(1, yy - y0));\n for (let x = 0; x < targetWidth; x++) {\n const xx = (x + 0.5) * sx - 0.5;\n const x0 = Math.max(0, Math.floor(xx));\n const x1 = Math.min(srcWidth - 1, x0 + 1);\n const wx = Math.max(0, Math.min(1, xx - x0));\n const v00 = src[y0 * srcWidth + x0];\n const v01 = src[y0 * srcWidth + x1];\n const v10 = src[y1 * srcWidth + x0];\n const v11 = src[y1 * srcWidth + x1];\n const top = v00 * (1 - wx) + v01 * wx;\n const bot = v10 * (1 - wx) + v11 * wx;\n out[y * targetWidth + x] = top * (1 - wy) + bot * wy;\n }\n }\n return out;\n}\n","/**\n * Common foundation for task-oriented vision SDK objects.\n *\n * The base only owns the {@link OrtSession} — label resolution lives in each\n * subclass because how `numClasses` is read from the model differs per task.\n */\n\nimport type { OrtSession } from \"../core/session\";\n\nexport abstract class VisionTask {\n protected constructor(protected readonly _session: OrtSession) {}\n\n /** The underlying {@link OrtSession} used to run inference. */\n get session(): OrtSession {\n return this._session;\n }\n}\n","/**\n * Image classification task using ONNX Runtime Web.\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { type ModelSource, type OrtSessionOptions, OrtSession } from \"../core/session\";\nimport { type ImageInput, loadImage } from \"../io/image\";\nimport { type LabelSpec, resolveLabels } from \"../labels\";\nimport { softmax, topK } from \"../postprocess/classification\";\nimport { normalize, resize, toCHW, toFloat32Tensor } from \"../preprocess/image\";\nimport { ClassificationResults, Probs } from \"../results\";\nimport { VisionTask } from \"./base\";\nimport { type ClassProbability, type ClassificationResult, type RGBImage } from \"../types\";\n\nconst IMAGENET_MEAN: readonly [number, number, number] = [0.485, 0.456, 0.406];\nconst IMAGENET_STD: readonly [number, number, number] = [0.229, 0.224, 0.225];\n\nexport interface ClassifierOptions extends OrtSessionOptions {\n /** Class label spec — see {@link resolveLabels}. */\n readonly labels: LabelSpec;\n /**\n * Number of classes the model can predict. Required when `labels` is `null`\n * or when you want to validate that the supplied labels match the model.\n */\n readonly numClasses?: number;\n /** Model input `[width, height]` in pixels. Defaults to `[224, 224]`. */\n readonly inputSize?: readonly [number, number];\n /** Per-channel RGB mean used for normalization. Defaults to ImageNet. */\n readonly mean?: readonly [number, number, number];\n /** Per-channel RGB standard deviation. Defaults to ImageNet. */\n readonly std?: readonly [number, number, number];\n /**\n * If `true` (default), apply softmax to the raw model output. Set to\n * `false` for models whose final layer already produces a probability\n * distribution.\n */\n readonly applySoftmax?: boolean;\n}\n\nexport interface ClassifierPredictOptions {\n /**\n * If set, the per-class probability list in `results[0].result.probabilities`\n * is truncated to the top-K entries. The bulk `probs` view always exposes\n * the full vector.\n */\n readonly topK?: number;\n}\n\n/**\n * Image classifier wrapping an ONNX model with ImageNet-style preprocessing.\n *\n * `predict()` returns `Promise<ClassificationResults[]>` (length 1 for a\n * single image), mirroring Ultralytics' API. The envelope exposes a `probs`\n * collection (`top1`, `top1conf`, `top5`, `top5conf`, `data`) plus the\n * legacy per-class probability list with names already resolved.\n *\n * Defaults: 224×224 RGB input, `float32` normalized with ImageNet mean/std,\n * NCHW layout, batch size 1, softmax applied to the raw output.\n *\n * @example\n * ```typescript\n * const clf = await Classifier.create(\"/models/resnet50.onnx\", {\n * labels: [\"tench\", \"goldfish\", ...] // 1000 ImageNet labels\n * });\n * const r = (await clf.predict(\"/images/dog.jpg\"))[0];\n * console.log(r.cls, r.conf, r.name);\n * console.log(r.probs.top5, r.probs.top5conf);\n * ```\n */\nexport class Classifier extends VisionTask {\n private constructor(\n session: OrtSession,\n private readonly _labels: readonly string[],\n private readonly _names: Readonly<Record<number, string>>,\n private readonly _inputSize: readonly [number, number],\n private readonly _mean: readonly [number, number, number],\n private readonly _std: readonly [number, number, number],\n private readonly _applySoftmax: boolean,\n ) {\n super(session);\n }\n\n /** Load the model and resolve labels. */\n static async create(model: ModelSource, options: ClassifierOptions): Promise<Classifier> {\n const session = await OrtSession.create(model, options);\n const labels = resolveLabels(options.labels, { numClasses: options.numClasses });\n const names: Record<number, string> = {};\n for (let i = 0; i < labels.length; i++) {\n names[i] = labels[i] as string;\n }\n return new Classifier(\n session,\n labels,\n names,\n options.inputSize ?? [224, 224],\n options.mean ?? IMAGENET_MEAN,\n options.std ?? IMAGENET_STD,\n options.applySoftmax ?? true,\n );\n }\n\n /** Class labels indexed by class id. */\n get labels(): readonly string[] {\n return this._labels;\n }\n\n /** Class id → class name dict (matches Ultralytics' `model.names`). */\n get names(): Readonly<Record<number, string>> {\n return this._names;\n }\n\n /** Number of classes the model can predict. */\n get numClasses(): number {\n return this._labels.length;\n }\n\n /** Alias for {@link predict} (parity with PyTorch `nn.Module.__call__`). */\n async call(\n image: ImageInput,\n options: ClassifierPredictOptions = {},\n ): Promise<ClassificationResults[]> {\n return this.predict(image, options);\n }\n\n /** Run classification on a single image. */\n async predict(\n image: ImageInput,\n options: ClassifierPredictOptions = {},\n ): Promise<ClassificationResults[]> {\n const path = typeof image === \"string\" ? image : null;\n const original = await loadImage(image);\n const tensor = this._preprocess(original);\n const outputs = await this._session.run({ [this._session.inputName]: tensor });\n const firstOutputName = this._session.outputNames[0];\n if (firstOutputName === undefined) {\n throw new Error(\"Classifier model has no outputs.\");\n }\n const raw = outputs[firstOutputName];\n if (raw === undefined) {\n throw new Error(\n `Classifier model output ${firstOutputName} missing from run() result.`,\n );\n }\n const fullProbs = this._postprocess(raw.data as Float32Array);\n\n const { indices, values } = topK(fullProbs, options.topK ?? null);\n const probabilities: ClassProbability[] = [];\n for (let i = 0; i < indices.length; i++) {\n const id = indices[i] as number;\n const className = this._labels[id] ?? `class_${id}`;\n probabilities.push({\n classId: id,\n className,\n probability: values[i] as number,\n cls: id,\n name: className,\n conf: values[i] as number,\n });\n }\n if (probabilities.length === 0) {\n throw new Error(\"Classifier produced no probabilities (empty output).\");\n }\n\n const top = probabilities[0] as ClassProbability;\n const result: ClassificationResult = {\n classId: top.classId,\n className: top.className,\n confidence: top.probability,\n cls: top.classId,\n name: top.className,\n conf: top.probability,\n image: original,\n probabilities,\n };\n\n const orig: readonly [number, number] = [original.height, original.width];\n return [\n new ClassificationResults(\n new Probs(fullProbs),\n result,\n this._names,\n original,\n orig,\n path,\n ),\n ];\n }\n\n private _preprocess(image: RGBImage): ort.Tensor {\n const [tw, th] = this._inputSize;\n const resized = resize(image, tw, th);\n const normalized = normalize(resized, this._mean, this._std);\n const chw = toCHW(normalized, resized.width, resized.height, 3);\n return toFloat32Tensor(chw, [1, 3, resized.height, resized.width]);\n }\n\n private _postprocess(raw: Float32Array): Float32Array {\n return this._applySoftmax ? softmax(raw) : new Float32Array(raw);\n }\n}\n","/**\n * Object detection task using anchor-free YOLO ONNX models (v8/v9/v10/v11/v12).\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { type ModelSource, type OrtSessionOptions, OrtSession } from \"../core/session\";\nimport { type ImageInput, loadImage } from \"../io/image\";\nimport { type LabelSpec, resolveLabels } from \"../labels\";\nimport { decodeYolo } from \"../postprocess/detection\";\nimport { letterbox, toCHW, toFloat32, toFloat32Tensor } from \"../preprocess/image\";\nimport { Boxes, DetectionResults } from \"../results\";\nimport { VisionTask } from \"./base\";\nimport { type BoundingBox, type DetectionResult, RGBImage } from \"../types\";\n\n/**\n * Decoder family for the model's detection head.\n *\n * - `\"yolo\"`: anchor-free YOLO head with output shape `[1, 4 + nc, N]` —\n * covers YOLOv8, v9, v10, v11, v12, v26 detect exports.\n *\n * The SDK does **not** auto-detect the head from the model — the caller is\n * responsible for picking a head that matches their export. Future families\n * (v5/v6/v7 with `[1, N, 5+nc]`) will be added as new literal members.\n */\nexport type DetectorHead = \"yolo\";\n\nexport interface DetectorOptions extends OrtSessionOptions {\n /**\n * Decoder family for the detection head. Default `\"yolo\"` covers\n * YOLOv8/v9/v10/v11/v12/v26.\n */\n readonly head?: DetectorHead;\n /** Class label spec — see {@link resolveLabels}. Defaults to the COCO 80-class preset. */\n readonly labels?: LabelSpec;\n /** Number of classes — used to validate the supplied labels. */\n readonly numClasses?: number;\n /** Model input `[width, height]` for letterboxing. Defaults to `[640, 640]`. */\n readonly inputSize?: readonly [number, number];\n /** Default minimum class score to keep a candidate. */\n readonly confThreshold?: number;\n /** Default IoU threshold for non-maximum suppression. */\n readonly iouThreshold?: number;\n /** Maximum number of detections per image. */\n readonly maxDetections?: number;\n}\n\nexport interface DetectorPredictOptions {\n /** Override the default confidence threshold. */\n readonly confThreshold?: number;\n /** Override the default IoU threshold. */\n readonly iouThreshold?: number;\n /**\n * If set, keep only detections whose `classId` is in this list.\n * Mirrors Ultralytics' `model.predict(img, classes=[0, 16])`.\n */\n readonly classes?: readonly number[];\n}\n\n/**\n * Object detector for anchor-free YOLO ONNX models (v8/v9/v10/v11/v12).\n *\n * `predict()` returns `Promise<DetectionResults[]>` (length 1 for a single\n * image), mirroring Ultralytics' `YOLO(\"img.jpg\")`. Iterate the envelope for\n * per-instance dataclasses, or use the bulk `boxes` view (`.xyxy`, `.xywh`,\n * `.xyxyn`, `.xywhn`, `.cls`, `.conf`).\n *\n * @example\n * ```typescript\n * const det = await Detector.create(\"/models/yolov8n.onnx\");\n * const results = await det.predict(\"/images/street.jpg\");\n * const r = results[0];\n * console.log(r.boxes.xyxy, r.boxes.cls, r.boxes.conf, r.names);\n * for (const d of r) {\n * console.log(d.cls, d.conf, d.box.xyxy);\n * }\n * ```\n */\nexport class Detector extends VisionTask {\n private constructor(\n session: OrtSession,\n private readonly _head: DetectorHead,\n private readonly _labels: readonly string[],\n private readonly _names: Readonly<Record<number, string>>,\n private readonly _inputSize: readonly [number, number],\n private readonly _confThreshold: number,\n private readonly _iouThreshold: number,\n private readonly _maxDetections: number,\n ) {\n super(session);\n }\n\n /** Load the model and resolve labels. */\n static async create(model: ModelSource, options: DetectorOptions = {}): Promise<Detector> {\n const head: DetectorHead = options.head ?? \"yolo\";\n if (head !== \"yolo\") {\n throw new Error(`Unsupported detector head '${head}'. Supported: 'yolo'.`);\n }\n const session = await OrtSession.create(model, options);\n const labels = resolveLabels(options.labels ?? \"coco\", {\n numClasses: options.numClasses,\n });\n const names: Record<number, string> = {};\n for (let i = 0; i < labels.length; i++) {\n names[i] = labels[i] as string;\n }\n return new Detector(\n session,\n head,\n labels,\n names,\n options.inputSize ?? [640, 640],\n options.confThreshold ?? 0.25,\n options.iouThreshold ?? 0.45,\n options.maxDetections ?? 300,\n );\n }\n\n /** The decoder family used to interpret the model's output. */\n get head(): DetectorHead {\n return this._head;\n }\n\n /** Class labels indexed by class id. */\n get labels(): readonly string[] {\n return this._labels;\n }\n\n /** Class id → class name dict (matches Ultralytics' `model.names`). */\n get names(): Readonly<Record<number, string>> {\n return this._names;\n }\n\n /** Number of classes the model predicts. */\n get numClasses(): number {\n return this._labels.length;\n }\n\n /**\n * Alias for {@link predict} — call the detector like a torch `nn.Module`.\n *\n * Use as `det.call(img)` since JavaScript class instances are not callable;\n * for direct invocation, prefer `det.predict(img)`. The full\n * {@link DetectorPredictOptions} (including `classes`) is supported.\n */\n async call(\n image: ImageInput,\n options: DetectorPredictOptions = {},\n ): Promise<DetectionResults[]> {\n return this.predict(image, options);\n }\n\n /** Run detection on a single image. */\n async predict(\n image: ImageInput,\n options: DetectorPredictOptions = {},\n ): Promise<DetectionResults[]> {\n const path = typeof image === \"string\" ? image : null;\n const original = await loadImage(image);\n const { tensor, scale, padLeft, padTop } = this._preprocess(original);\n const outputs = await this._session.run({ [this._session.inputName]: tensor });\n\n const firstOutputName = this._session.outputNames[0];\n if (firstOutputName === undefined) {\n throw new Error(\"Detector model has no outputs.\");\n }\n const raw = outputs[firstOutputName];\n if (raw === undefined) {\n throw new Error(`Detector model output ${firstOutputName} missing from run() result.`);\n }\n\n const decodedAll = decodeYolo(raw.data as Float32Array, raw.dims, {\n originalWidth: original.width,\n originalHeight: original.height,\n padLeft,\n padTop,\n scale,\n confThreshold: options.confThreshold ?? this._confThreshold,\n iouThreshold: options.iouThreshold ?? this._iouThreshold,\n maxDetections: this._maxDetections,\n });\n\n const decoded =\n options.classes !== undefined\n ? (() => {\n const allowed = new Set(options.classes);\n return decodedAll.filter((d) => allowed.has(d.classId));\n })()\n : decodedAll;\n\n const detections = decoded.map((d) =>\n this._buildResult(original, d.bbox, d.classId, d.confidence),\n );\n\n const orig: readonly [number, number] = [original.height, original.width];\n return [\n new DetectionResults(\n this._buildBoxes(detections, orig),\n detections,\n this._names,\n original,\n orig,\n path,\n ),\n ];\n }\n\n private _preprocess(image: RGBImage): {\n tensor: ort.Tensor;\n scale: number;\n padLeft: number;\n padTop: number;\n } {\n const [tw, th] = this._inputSize;\n const lb = letterbox(image, tw, th);\n const f32 = toFloat32(lb.image);\n const chw = toCHW(f32, lb.image.width, lb.image.height, 3);\n return {\n tensor: toFloat32Tensor(chw, [1, 3, lb.image.height, lb.image.width]),\n scale: lb.scale,\n padLeft: lb.padLeft,\n padTop: lb.padTop,\n };\n }\n\n private _buildResult(\n original: RGBImage,\n bbox: BoundingBox,\n classId: number,\n confidence: number,\n ): DetectionResult {\n const [x1, y1, x2, y2] = bbox.asIntXyxy();\n const cx1 = Math.max(0, x1);\n const cy1 = Math.max(0, y1);\n const cx2 = Math.min(original.width, x2);\n const cy2 = Math.min(original.height, y2);\n\n let cropped: RGBImage;\n if (cx2 > cx1 && cy2 > cy1) {\n const cw = cx2 - cx1;\n const ch = cy2 - cy1;\n const out = new Uint8Array(cw * ch * 3);\n for (let row = 0; row < ch; row++) {\n const srcOffset = ((cy1 + row) * original.width + cx1) * 3;\n out.set(original.data.subarray(srcOffset, srcOffset + cw * 3), row * cw * 3);\n }\n cropped = new RGBImage(out, cw, ch);\n } else {\n cropped = new RGBImage(new Uint8Array(0), 0, 0);\n }\n\n const className = this._names[classId] ?? `class_${classId}`;\n\n return {\n classId,\n className,\n confidence,\n bbox,\n cls: classId,\n name: className,\n conf: confidence,\n box: bbox,\n croppedImage: cropped,\n };\n }\n\n private _buildBoxes(\n detections: readonly DetectionResult[],\n origShape: readonly [number, number],\n ): Boxes {\n const n = detections.length;\n const xyxy = new Float32Array(n * 4);\n const cls = new Int32Array(n);\n const conf = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const d = detections[i] as DetectionResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n cls[i] = d.classId;\n conf[i] = d.confidence;\n }\n return new Boxes(xyxy, cls, conf, origShape);\n }\n}\n","/**\n * Instance-segmentation task using YOLO seg ONNX models (v8-seg / v11-seg / ...).\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { type ModelSource, type OrtSessionOptions, OrtSession } from \"../core/session\";\nimport { type ImageInput, loadImage } from \"../io/image\";\nimport { type LabelSpec, resolveLabels } from \"../labels\";\nimport { decodeYoloSeg } from \"../postprocess/segmentation\";\nimport { letterbox, toCHW, toFloat32, toFloat32Tensor } from \"../preprocess/image\";\nimport { Boxes, Masks, SegmentationResults } from \"../results\";\nimport { VisionTask } from \"./base\";\nimport { type BoundingBox, type SegmentationResult, Mask, RGBImage } from \"../types\";\n\n/**\n * Decoder family for the segmentation head.\n *\n * - `\"yolo-seg\"`: YOLO instance-segmentation head with two outputs —\n * `[1, 4 + nc + nm, N]` per-anchor predictions plus `[1, nm, mh, mw]`\n * prototype masks. Covers YOLOv8-seg, v11-seg, v26-seg.\n *\n * The SDK does **not** auto-detect this — the caller is responsible for\n * picking a head that matches their export.\n */\nexport type SegmenterHead = \"yolo-seg\";\n\nexport interface SegmenterOptions extends OrtSessionOptions {\n /**\n * Decoder family for the segmentation head. Default `\"yolo-seg\"` covers\n * YOLOv8-seg/v11-seg/v26-seg.\n */\n readonly head?: SegmenterHead;\n /** Class label spec — see {@link resolveLabels}. Defaults to the COCO 80-class preset. */\n readonly labels?: LabelSpec;\n /** Number of classes — used to validate the supplied labels. */\n readonly numClasses?: number;\n /** Model input `[width, height]` for letterboxing. Defaults to `[640, 640]`. */\n readonly inputSize?: readonly [number, number];\n /** Default minimum class score to keep a candidate. */\n readonly confThreshold?: number;\n /** Default IoU threshold for non-maximum suppression. */\n readonly iouThreshold?: number;\n /** Maximum number of instances per image. */\n readonly maxDetections?: number;\n /** Probability cutoff applied to soft masks. Defaults to `0.5`. */\n readonly maskThreshold?: number;\n}\n\nexport interface SegmenterPredictOptions {\n readonly confThreshold?: number;\n readonly iouThreshold?: number;\n /**\n * If set, keep only instances whose `classId` is in this list.\n * Mirrors Ultralytics' `model.predict(img, classes=[0, 16])`.\n */\n readonly classes?: readonly number[];\n}\n\n/**\n * Instance segmenter for YOLO seg ONNX models (v8-seg / v11-seg / ...).\n *\n * The model is expected to expose two outputs:\n *\n * 1. `output0`: `(1, 4 + numClasses + numMaskCoefs, numAnchors)` — per-anchor\n * predictions (boxes, class scores, mask coefficients).\n * 2. `output1`: `(1, numMaskCoefs, maskH, maskW)` — prototype masks.\n *\n * `predict()` returns `Promise<SegmentationResults[]>` (length 1 for a\n * single image), mirroring Ultralytics' API. The envelope exposes:\n *\n * - `boxes`: bulk numpy view (`xyxy`, `xywh`, `xyxyn`, `xywhn`, `cls`, `conf`).\n * - `masks`: per-instance binary masks cropped to each box.\n * - per-instance {@link SegmentationResult} via iteration.\n *\n * @example\n * ```typescript\n * const seg = await Segmenter.create(\"/models/yolov8n-seg.onnx\");\n * const r = (await seg.predict(\"/images/street.jpg\"))[0];\n * for (const inst of r) {\n * console.log(inst.cls, inst.conf, inst.box.xyxy);\n * }\n * ```\n */\nexport class Segmenter extends VisionTask {\n private constructor(\n session: OrtSession,\n private readonly _head: SegmenterHead,\n private readonly _labels: readonly string[],\n private readonly _names: Readonly<Record<number, string>>,\n private readonly _inputSize: readonly [number, number],\n private readonly _confThreshold: number,\n private readonly _iouThreshold: number,\n private readonly _maxDetections: number,\n private readonly _maskThreshold: number,\n ) {\n super(session);\n }\n\n /** Load the model and resolve labels. */\n static async create(model: ModelSource, options: SegmenterOptions = {}): Promise<Segmenter> {\n const head: SegmenterHead = options.head ?? \"yolo-seg\";\n if (head !== \"yolo-seg\") {\n throw new Error(`Unsupported segmenter head '${head}'. Supported: 'yolo-seg'.`);\n }\n const session = await OrtSession.create(model, options);\n const labels = resolveLabels(options.labels ?? \"coco\", {\n numClasses: options.numClasses,\n });\n const names: Record<number, string> = {};\n for (let i = 0; i < labels.length; i++) {\n names[i] = labels[i] as string;\n }\n return new Segmenter(\n session,\n head,\n labels,\n names,\n options.inputSize ?? [640, 640],\n options.confThreshold ?? 0.25,\n options.iouThreshold ?? 0.45,\n options.maxDetections ?? 300,\n options.maskThreshold ?? 0.5,\n );\n }\n\n /** The decoder family used to interpret the model's output. */\n get head(): SegmenterHead {\n return this._head;\n }\n\n /** Class labels indexed by class id. */\n get labels(): readonly string[] {\n return this._labels;\n }\n\n /** Class id → class name dict (matches Ultralytics' `model.names`). */\n get names(): Readonly<Record<number, string>> {\n return this._names;\n }\n\n /** Number of classes the model predicts. */\n get numClasses(): number {\n return this._labels.length;\n }\n\n /** Alias for {@link predict} (parity with PyTorch `nn.Module.__call__`). */\n async call(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n return this.predict(image, options);\n }\n\n /** Run instance segmentation on a single image. */\n async predict(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n const path = typeof image === \"string\" ? image : null;\n const original = await loadImage(image);\n const { tensor, scale, padLeft, padTop } = this._preprocess(original);\n const outputs = await this._session.run({ [this._session.inputName]: tensor });\n\n const { perAnchor, prototypes } = this._splitOutputs(outputs);\n\n const decodedAll = decodeYoloSeg(\n perAnchor.data as Float32Array,\n perAnchor.dims,\n prototypes.data as Float32Array,\n prototypes.dims,\n {\n numClasses: this._labels.length,\n inputWidth: this._inputSize[0],\n inputHeight: this._inputSize[1],\n originalWidth: original.width,\n originalHeight: original.height,\n padLeft,\n padTop,\n scale,\n confThreshold: options.confThreshold ?? this._confThreshold,\n iouThreshold: options.iouThreshold ?? this._iouThreshold,\n maxDetections: this._maxDetections,\n maskThreshold: this._maskThreshold,\n },\n );\n\n const decoded =\n options.classes !== undefined\n ? (() => {\n const allowed = new Set(options.classes);\n return decodedAll.filter((d) => allowed.has(d.classId));\n })()\n : decodedAll;\n\n const detections = decoded.map((d) =>\n this._buildResult(original, d.bbox, d.classId, d.confidence, d.mask),\n );\n\n const orig: readonly [number, number] = [original.height, original.width];\n return [\n new SegmentationResults(\n this._buildBoxes(detections, orig),\n this._buildMasks(detections, orig),\n detections,\n this._names,\n original,\n orig,\n path,\n ),\n ];\n }\n\n private _preprocess(image: RGBImage): {\n tensor: ort.Tensor;\n scale: number;\n padLeft: number;\n padTop: number;\n } {\n const [tw, th] = this._inputSize;\n const lb = letterbox(image, tw, th);\n const f32 = toFloat32(lb.image);\n const chw = toCHW(f32, lb.image.width, lb.image.height, 3);\n return {\n tensor: toFloat32Tensor(chw, [1, 3, lb.image.height, lb.image.width]),\n scale: lb.scale,\n padLeft: lb.padLeft,\n padTop: lb.padTop,\n };\n }\n\n private _splitOutputs(outputs: Record<string, ort.Tensor>): {\n perAnchor: ort.Tensor;\n prototypes: ort.Tensor;\n } {\n let perAnchor: ort.Tensor | undefined;\n let prototypes: ort.Tensor | undefined;\n for (const name of this._session.outputNames) {\n const t = outputs[name];\n if (t === undefined) continue;\n if (t.dims.length === 3 && perAnchor === undefined) {\n perAnchor = t;\n } else if (t.dims.length === 4 && prototypes === undefined) {\n prototypes = t;\n }\n }\n if (perAnchor === undefined || prototypes === undefined) {\n const shapes = this._session.outputNames.map(\n (n) => `${n}: ${JSON.stringify(outputs[n]?.dims ?? [])}`,\n );\n throw new Error(\n `Segmenter expected one 3-D and one 4-D output, got [${shapes.join(\", \")}].`,\n );\n }\n return { perAnchor, prototypes };\n }\n\n private _buildResult(\n original: RGBImage,\n bbox: BoundingBox,\n classId: number,\n confidence: number,\n mask: Mask,\n ): SegmentationResult {\n const [x1, y1, x2, y2] = bbox.asIntXyxy();\n const cx1 = Math.max(0, x1);\n const cy1 = Math.max(0, y1);\n const cx2 = Math.min(original.width, x2);\n const cy2 = Math.min(original.height, y2);\n\n let segmentedImage: RGBImage;\n let finalMask = mask;\n if (cx2 > cx1 && cy2 > cy1 && mask.data.length > 0) {\n const cropW = cx2 - cx1;\n const cropH = cy2 - cy1;\n const mw = Math.min(mask.width, cropW);\n const mh = Math.min(mask.height, cropH);\n const segData = new Uint8Array(mw * mh * 3);\n for (let row = 0; row < mh; row++) {\n const srcRowOffset = ((cy1 + row) * original.width + cx1) * 3;\n const dstRowOffset = row * mw * 3;\n const maskRowOffset = row * mask.width;\n for (let col = 0; col < mw; col++) {\n const m = mask.data[maskRowOffset + col];\n if (m !== 0) {\n const s = srcRowOffset + col * 3;\n const d = dstRowOffset + col * 3;\n segData[d] = original.data[s];\n segData[d + 1] = original.data[s + 1];\n segData[d + 2] = original.data[s + 2];\n }\n }\n }\n segmentedImage = new RGBImage(segData, mw, mh);\n if (mw !== mask.width || mh !== mask.height) {\n const trimmed = new Uint8Array(mw * mh);\n for (let row = 0; row < mh; row++) {\n trimmed.set(\n mask.data.subarray(row * mask.width, row * mask.width + mw),\n row * mw,\n );\n }\n finalMask = new Mask(trimmed, mw, mh);\n }\n } else {\n finalMask = new Mask(new Uint8Array(0), 0, 0);\n segmentedImage = new RGBImage(new Uint8Array(0), 0, 0);\n }\n\n const className = this._names[classId] ?? `class_${classId}`;\n\n return {\n classId,\n className,\n confidence,\n bbox,\n cls: classId,\n name: className,\n conf: confidence,\n box: bbox,\n mask: finalMask,\n segmentedImage,\n };\n }\n\n private _buildBoxes(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Boxes {\n const n = detections.length;\n const xyxy = new Float32Array(n * 4);\n const cls = new Int32Array(n);\n const conf = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n cls[i] = d.classId;\n conf[i] = d.confidence;\n }\n return new Boxes(xyxy, cls, conf, origShape);\n }\n\n private _buildMasks(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Masks {\n const xyxy = new Float32Array(detections.length * 4);\n for (let i = 0; i < detections.length; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n }\n return new Masks(\n detections.map((d) => d.mask),\n xyxy,\n origShape,\n );\n }\n}\n","/**\n * `tempest-react-sdk/vision` — browser computer-vision inference with ONNX\n * Runtime Web (classification, detection, segmentation).\n *\n * Vendored from `@mauriciobenjamin700/ort-vision-sdk-web@0.2.1` (MIT, same\n * author) so it ships inside this SDK without an extra package install.\n * `onnxruntime-web` stays an optional peer dependency — install it (and ship\n * the matching `.wasm` files) only when you use this subpath.\n *\n * Do not hand-edit — regenerate with `npm run vendor:vision`.\n */\n\nexport {\n BoundingBox,\n Mask,\n RGBImage,\n type ClassProbability,\n type ClassificationResult,\n type DetectionResult,\n type SegmentationResult,\n} from \"./types\";\n\nexport {\n Boxes,\n ClassificationResults,\n DetectionResults,\n Masks,\n Probs,\n SegmentationResults,\n} from \"./results\";\n\nexport { COCO_CLASSES, type LabelSpec, type ResolveLabelsOptions, resolveLabels } from \"./labels\";\n\nexport {\n ImageLoadError,\n InferenceError,\n LabelMapError,\n ModelLoadError,\n OrtVisionError,\n ProviderNotAvailableError,\n} from \"./core/exceptions\";\n\nexport { type ModelSource, type OrtSessionOptions, OrtSession } from \"./core/session\";\nexport { DEFAULT_PROVIDERS, resolveProviders } from \"./core/providers\";\n\nexport { type ImageInput, loadImage } from \"./io/image\";\n\nexport {\n type LetterboxResult,\n fromCv2,\n letterbox,\n normalize,\n resize,\n toCHW,\n toCv2,\n toFloat32,\n toFloat32Tensor,\n toTensor,\n} from \"./preprocess/image\";\n\nexport { type TopKResult, softmax, topK } from \"./postprocess/classification\";\n\nexport {\n type DecodeYoloAnchorsOptions,\n type DecodeYoloOptions,\n type DecodeYoloV8AnchorsOptions,\n type DecodeYoloV8Options,\n type DecodedAnchors,\n type DecodedDetection,\n batchedNms,\n decodeYolo,\n decodeYoloAnchors,\n decodeYoloV8,\n decodeYoloV8Anchors,\n nms,\n} from \"./postprocess/detection\";\n\nexport {\n type DecodeYoloSegOptions,\n type DecodeYoloV8SegOptions,\n type DecodedSegmentation,\n decodeYoloSeg,\n decodeYoloV8Seg,\n} from \"./postprocess/segmentation\";\n\nexport { VisionTask } from \"./tasks/base\";\nexport {\n type ClassifierOptions,\n type ClassifierPredictOptions,\n Classifier,\n} from \"./tasks/classifier\";\nexport {\n type DetectorHead,\n type DetectorOptions,\n type DetectorPredictOptions,\n Detector,\n} from \"./tasks/detector\";\nexport {\n type SegmenterHead,\n type SegmenterOptions,\n type SegmenterPredictOptions,\n Segmenter,\n} from \"./tasks/segmenter\";\n\nexport const VERSION: string = \"0.2.1\";\n"],"names":["OrtVisionError","message","options","ModelLoadError","InferenceError","ProviderNotAvailableError","ImageLoadError","LabelMapError","RGBImage","data","width","height","BoundingBox","x1","y1","x2","y2","origShape","h","w","cx","cy","bw","bh","Mask","Boxes","xyxy","cls","conf","out","i","xywh","Probs","best","bestVal","v","k","n","order","b","indices","values","Masks","DetectionResults","boxes","detections","names","origImg","path","speed","index","ClassificationResults","probs","result","SegmentationResults","masks","COCO_CLASSES","PRESETS","resolveLabels","spec","labels","resolve","numClasses","_","preset","map","ids","maxId","DEFAULT_PROVIDERS","resolveProviders","requested","OrtSession","_session","providers","model","sessionOptions","session","ortRuntime","err","name","feeds","createCanvas","c","get2DContext","canvas","ctx","imageDataToRGB","imageData","rgb","j","rgbToImageData","image","loadImage","source","loadFromUrl","loadFromBlob","waitForImageElement","drawableToRGB","url","response","blob","bitmap","img","reject","onLoad","cleanup","onError","drawable","resize","targetWidth","targetHeight","srcCanvas","dstCanvas","dstCtx","normalize","mean","std","scale","m0","m1","m2","s0","s1","s2","toFloat32","toCHW","hwc","channels","expected","chw","plane","y","x","hwcBase","planeIdx","toFloat32Tensor","dims","toTensor","f32","fromCv2","bgr","toCv2","letterbox","fill","newW","newH","resized","f0","f1","f2","padLeft","padTop","rowBytes","srcOffset","dstOffset","softmax","logits","max","sum","e","topK","probabilities","kEff","idx","a","nms","scores","iouThreshold","areas","suppressed","keep","oi","ax1","ay1","ax2","ay2","ai","oj","bx1","by1","bx2","by2","ix1","iy1","ix2","iy2","iw","ih","inter","union","batchedNms","idxs","byClass","list","m","subBoxes","subScores","subKeep","decodeYoloAnchors","normalized","numAnchors","originalWidth","originalHeight","confThreshold","maxDetections","candidates","bestCls","bestScore","s","emptyDecoded","flatBoxes","scoresArr","idxsArr","kept","limited","anchorIndices","boxesXyxy","classIds","confidences","decodeYolo","output","outputDims","decoded","results","_warnedDecodeYoloV8","_warnedDecodeYoloV8Anchors","decodeYoloV8","decodeYoloV8Anchors","decodeYoloSeg","perAnchorData","perAnchorDims","prototypeData","prototypeDims","pDims","numMaskCoefs","maskH","maskW","expectedChannels","maskThreshold","scaleX","scaleY","protoPlane","coefBase","bbox","classId","confidence","bboxW","bboxH","ibx1","iby1","ibx2","iby2","mbx1","mby1","mbx2","mby2","cropW","cropH","softCrop","py","px","kk","coef","proto","sigmoid","resizeBilinear","binary","_warnedDecodeYoloV8Seg","decodeYoloV8Seg","src","srcWidth","srcHeight","sx","sy","yy","y0","wy","xx","x0","wx","v00","v01","v10","v11","top","bot","VisionTask","IMAGENET_MEAN","IMAGENET_STD","Classifier","_labels","_names","_inputSize","_mean","_std","_applySoftmax","original","tensor","outputs","firstOutputName","raw","fullProbs","id","className","orig","tw","th","Detector","_head","_confThreshold","_iouThreshold","_maxDetections","head","decodedAll","allowed","d","lb","cx1","cy1","cx2","cy2","cropped","cw","ch","row","Segmenter","_maskThreshold","perAnchor","prototypes","t","shapes","mask","segmentedImage","finalMask","mw","mh","segData","srcRowOffset","dstRowOffset","maskRowOffset","col","trimmed","VERSION"],"mappings":"iZAOO,MAAMA,UAAuB,KAAM,CACtC,YAAYC,EAAiBC,EAAwB,CACjD,MAAMD,EAASC,CAAO,EACtB,KAAK,KAAO,WAAW,IAC3B,CACJ,CAGO,MAAMC,WAAuBH,CAAe,CAAC,CAG7C,MAAMI,WAAuBJ,CAAe,CAAC,CAG7C,MAAMK,WAAkCL,CAAe,CAAC,CAGxD,MAAMM,UAAuBN,CAAe,CAAC,CAG7C,MAAMO,UAAsBP,CAAe,CAAC,CCN5C,MAAMQ,CAAS,CAClB,YACoBC,EACAC,EACAC,EAClB,CACE,GAJgB,KAAA,KAAAF,EACA,KAAA,MAAAC,EACA,KAAA,OAAAC,EAEZF,EAAK,SAAWC,EAAQC,EAAS,EACjC,MAAM,IAAIL,EACN,wBAAwBG,EAAK,MAAM,wCAC/BC,EAAQC,EAAS,CACrB,GAAA,CAGZ,CAXoB,KACA,MACA,MAUxB,CASO,MAAMC,EAAY,CACrB,YACoBC,EACAC,EACAC,EACAC,EAClB,CAJkB,KAAA,GAAAH,EACA,KAAA,GAAAC,EACA,KAAA,GAAAC,EACA,KAAA,GAAAC,CACjB,CAJiB,GACA,GACA,GACA,GAIpB,IAAI,OAAgB,CAChB,OAAO,KAAK,IAAI,EAAG,KAAK,GAAK,KAAK,EAAE,CACxC,CAGA,IAAI,QAAiB,CACjB,OAAO,KAAK,IAAI,EAAG,KAAK,GAAK,KAAK,EAAE,CACxC,CAGA,IAAI,MAAe,CACf,OAAO,KAAK,MAAQ,KAAK,MAC7B,CAGA,IAAI,MAAkD,CAClD,MAAO,CAAC,KAAK,GAAI,KAAK,GAAI,KAAK,GAAI,KAAK,EAAE,CAC9C,CAQA,IAAI,MAAkD,CAClD,MAAO,EAAE,KAAK,GAAK,KAAK,IAAM,GAAI,KAAK,GAAK,KAAK,IAAM,EAAG,KAAK,MAAO,KAAK,MAAM,CACrF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A,KAAA+B,EACA,KAAA,MAAAC,CACjB,CARiB,MACA,MACA,WACA,MACA,QACA,UACA,KACA,MAIpB,IAAI,QAAiB,CACjB,OAAO,KAAK,WAAW,MAC3B,CAGA,IAAIC,EAA+C,CAC/C,OAAO,KAAK,WAAWA,CAAK,CAChC,CAEA,CAAC,OAAO,QAAQ,GAAkC,CAC9C,OAAO,KAAK,WAAW,OAAO,QAAQ,EAAA,CAC1C,CACJ,CCjTO,MAAMM,GAAkC,OAAO,OAAO,CACzD,SACA,UACA,MACA,aACA,WACA,MACA,QACA,QACA,OACA,gBACA,eACA,YACA,gBACA,QACA,OACA,MACA,MACA,QACA,QACA,MACA,WACA,OACA,QACA,UACA,WACA,WACA,UACA,MACA,WACA,UACA,OACA,YACA,cACA,OACA,eACA,iBACA,aACA,YACA,gBACA,SACA,aACA,MACA,OACA,QACA,QACA,OACA,SACA,QACA,WACA,SACA,WACA,SACA,UACA,QACA,QACA,OACA,QACA,QACA,eACA,MACA,eACA,SACA,KACA,SACA,QACA,SACA,WACA,aACA,YACA,OACA,UACA,OACA,eACA,OACA,QACA,OACA,WACA,aACA,aACA,YACJ,CAAC,EAEKC,GAAuD,CACzD,KAAMD,EACV,EAkBO,SAASE,EACZC,EACAzD,EAAgC,GACf,CACjB,MAAM0D,EAASC,GAAQF,EAAMzD,EAAQ,UAAU,EAC/C,GAAIA,EAAQ,aAAe,QAAa0D,EAAO,SAAW1D,EAAQ,WAC9D,MAAM,IAAIK,EACN,YAAYqD,EAAO,MAAM,6BAA6B1D,EAAQ,UAAU,WAAA,EAGhF,OAAO0D,CACX,CAEA,SAASC,GAAQF,EAAiBG,EAAmD,CACjF,GAAIH,GAAS,KAA4B,CACrC,GAAIG,IAAe,OACf,MAAM,IAAIvD,EACN,6FAAA,EAGR,OAAO,MAAM,KAAK,CAAE,OAAQuD,CAAA,EAAc,CAACC,EAAGjC,IAAM,SAASA,CAAC,EAAE,CACpE,CAEA,GAAI,MAAM,QAAQ6B,CAAI,EAClB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