1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
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 });
}
};
|