Spaces:
Running
Running
| class d{worker;pending=new Map;nextId=0;ready;readySettled=!1;resolveReady;rejectReady;onStatus;constructor(e,r){this.worker=e,this.onStatus=r,this.ready=new Promise((t,i)=>{this.resolveReady=t,this.rejectReady=i}),this.worker.addEventListener("message",t=>{this.handleMessage(t.data)}),this.worker.addEventListener("error",t=>{this.failReady(new Error(t.message||"Detection worker failed"))}),this.worker.postMessage({type:"init"})}static async create(e){const r=new Worker(new URL("/assets/detection.worker-dQwGGgA8.js",import.meta.url),{type:"module"}),t=new d(r,e);return await t.ready,t}async warmup(e,r=.5){await this.detect(e,{threshold:r})}async detect(e,r){await this.ready;const t=this.nextId++;return new Promise((i,s)=>{this.pending.set(t,{resolve:i,reject:s}),this.worker.postMessage({type:"detect",id:t,threshold:r.threshold,frame:e},[e])})}dispose(){for(const{reject:e}of this.pending.values())e(new Error("Detection worker terminated"));this.pending.clear(),this.worker.terminate()}handleMessage(e){if(e.type==="status"){this.onStatus?.(e.message);return}if(e.type==="ready"){this.readySettled||(this.readySettled=!0,this.resolveReady());return}if(e.type==="detect-result"){const r=this.pending.get(e.id);r&&(this.pending.delete(e.id),r.resolve(e.results));return}if(e.type==="error"){const r=new Error(e.error);if(e.id!==void 0){const t=this.pending.get(e.id);t&&(this.pending.delete(e.id),t.reject(r));return}this.failReady(r)}}failReady(e){this.readySettled||(this.readySettled=!0,this.rejectReady(e))}}export{d as ObjectDetector}; | |