import { removeBackground, segmentForeground, preload, Config } from '@imgly/background-removal'; // Preload the model when the worker starts let modelLoaded = false; preload() .then(() => { modelLoaded = true; console.log('Background removal model preloaded successfully.'); }) .catch(error => { console.error('Failed to preload background removal model:', error); }); self.onmessage = async (event: MessageEvent) => { const { imagePath, config, docId } = event.data; const configWithDefaults: Config = { ...config, debug: true, // You can set default config values here if needed onProgress: (progress: number) => { console.log('Progress: ' + progress); // Send progress updates to the main thread self.postMessage({ type: 'progress', docId, progress }); }, }; try { // Ensure the model is preloaded before processing if (!modelLoaded) { await preload(configWithDefaults); modelLoaded = true; } // Simulate progress updates (if the library doesn't provide them natively) self.postMessage({ type: 'progress', docId, progress: 0 }); const resultProm = config.output.type === 'mask' ? segmentForeground(imagePath, configWithDefaults) // : removeBackground(imagePath, configWithDefaults); // Send the result back to the main thread self.postMessage({ success: true, result: await resultProm, docId }); } catch (error) { // Send the error back to the main thread // eslint-disable-next-line @typescript-eslint/no-explicit-any self.postMessage({ success: false, docId, error: (error as any).message }); } };