ensemble / backend-client.js
nanye's picture
support for random forest & extra trees, mlp basis for boosting, multiple class, and improve UI
6ed536f
Raw History Blame Contribute Delete
1.33 kB
class PythonBackend {
constructor(onStatus){
this.pending=new Map();this.sequence=0;
this.ready=new Promise((resolve,reject)=>{this.resolveReady=resolve;this.rejectReady=reject;});
try{
this.worker=new Worker('./pyodide-worker.js?v=multiclass-1', {type:'module'});
this.worker.onmessage=({data})=>{
if(data.type==='progress'){onStatus(data.message);return;}
if(data.type==='ready'){this.resolveReady(data.classifiers);return;}
if(data.type==='fatal'){this.fail(data.message);return;}
const pending=this.pending.get(data.id);
if(pending){this.pending.delete(data.id);data.error?pending.reject(new Error(data.error)):pending.resolve(data.model);}
};
this.worker.onerror=event=>this.fail(event.message||'Python worker could not start.');
}catch(error){this.fail(error.message);}
}
fail(message){
const error=new Error(message);this.failure=error;this.rejectReady(error);
for(const p of this.pending.values()) p.reject(error);
this.pending.clear();this.worker?.terminate();
}
async add(request){
await this.ready;
if(this.failure)throw this.failure;
return new Promise((resolve,reject)=>{
const id=++this.sequence;this.pending.set(id,{resolve,reject});
this.worker.postMessage({id,request});
});
}
}