@beeintel/batch-image 1.2.0 → 1.2.2

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.
Files changed (38) hide show
  1. package/dist/assets/{transformers.web-DB57cIO5.js → standard-cutout.worker-By1cNYtF.js} +9291 -8024
  2. package/dist/chunks/{AdjustToolPanel-JuZOeF1k.js → AdjustToolPanel-DbFH5M15.js} +2 -2
  3. package/dist/chunks/{BackgroundToolPanel-NAH0gwan.js → BackgroundToolPanel-DjjMMsbb.js} +3 -3
  4. package/dist/chunks/{BatchMaterials-G2YYHu2n.js → BatchMaterials-DMsOcFy-.js} +1 -1
  5. package/dist/chunks/{BatchModeChoices-Du-SOWOC.js → BatchModeChoices-CeXykaXh.js} +1 -1
  6. package/dist/chunks/{BatchOutputColorPicker-BsX8fDgK.js → BatchOutputColorPicker-D-PIHag3.js} +1 -1
  7. package/dist/chunks/{BatchReferenceFields-DroXLmsO.js → BatchReferenceFields-D3aPIGEW.js} +3 -3
  8. package/dist/chunks/{BeautifyToolPanel-DQSkssvi.js → BeautifyToolPanel-B7SIlVDu.js} +4 -4
  9. package/dist/chunks/{BrandMarkToolPanel-BIF_KhE5.js → BrandMarkToolPanel-DPqP_dv5.js} +3 -3
  10. package/dist/chunks/{ContentTrimControl-B-2aFBP0.js → ContentTrimControl-CL7xHnxH.js} +1 -1
  11. package/dist/chunks/{CropToolPanel-C75_UWJ8.js → CropToolPanel-CDlJ9VGe.js} +3 -3
  12. package/dist/chunks/{CutoutToolPanel-SerddJYR.js → CutoutToolPanel-DbDollqT.js} +4 -4
  13. package/dist/chunks/{DisclosureToolPanel-CZAb3aD1.js → DisclosureToolPanel-DpVyboej.js} +2 -2
  14. package/dist/chunks/{ExpandToolPanel-LNL_pq7e.js → ExpandToolPanel-gFYJg-3I.js} +2 -2
  15. package/dist/chunks/{ImageEffectsToolPanel-DNbpno1P.js → ImageEffectsToolPanel-B2srVafK.js} +3 -3
  16. package/dist/chunks/{IpAuditToolPanel-_Kn3ogos.js → IpAuditToolPanel-CUazlW14.js} +2 -2
  17. package/dist/chunks/{ListingToolPanel-B5Hl18nG.js → ListingToolPanel-0w4xKIbW.js} +3 -3
  18. package/dist/chunks/{MaterialSelectionPlate-jDE8hec7.js → MaterialSelectionPlate-BIuxi0Yo.js} +1 -1
  19. package/dist/chunks/{MetadataToolPanel-CCpL5G9d.js → MetadataToolPanel-JesH-Eas.js} +2 -2
  20. package/dist/chunks/{OrientToolPanel-BJhAc1hU.js → OrientToolPanel-uTcto8y7.js} +2 -2
  21. package/dist/chunks/{PluginActionFooter.vue_vue_type_script_setup_true_lang-BqwHbNNa.js → PluginActionFooter.vue_vue_type_script_setup_true_lang-93c0J8cv.js} +2 -2
  22. package/dist/chunks/{ResizeToolPanel-Cn0chMaX.js → ResizeToolPanel-BBMFL_sj.js} +6 -6
  23. package/dist/chunks/{RetouchToolPanel-B-C2vU85.js → RetouchToolPanel-D3qF3AOL.js} +3 -3
  24. package/dist/chunks/{ShadowToolPanel-CKZMgpNb.js → ShadowToolPanel-B2wczd4I.js} +2 -2
  25. package/dist/chunks/{SvgExportToolPanel-Bnh5bcst.js → SvgExportToolPanel-C2btAdGo.js} +2 -2
  26. package/dist/chunks/{TranslationToolPanel-8SddGK7x.js → TranslationToolPanel-DDshfhg6.js} +2 -2
  27. package/dist/chunks/{UpscaleToolPanel-BerqoX0B.js → UpscaleToolPanel-B3IyR-6V.js} +3 -3
  28. package/dist/chunks/{arrow-up-D2gMUXae.js → arrow-up-CzMLmifH.js} +1 -1
  29. package/dist/chunks/{entry-D43rPO3k.js → entry-BFJ0v3bZ.js} +8808 -8737
  30. package/dist/chunks/{loader-circle-CPbCP_og.js → loader-circle-XmqYCdO5.js} +1 -1
  31. package/dist/chunks/{motionFeatures-CtNuOAaT.js → motionFeatures-DchE5oNa.js} +1 -1
  32. package/dist/chunks/{search-BRWGm1i8.js → search-DkUbLI9i.js} +1 -1
  33. package/dist/chunks/{standard-cutout-42ZR6RiC.js → standard-cutout-DB11bgEH.js} +8 -8
  34. package/dist/index.js +1 -1
  35. package/dist/resources.json +72 -77
  36. package/dist/style.css +1 -1
  37. package/package.json +1 -1
  38. package/dist/assets/standard-cutout.worker-BYLzdpR-.js +0 -1261
@@ -1,1261 +0,0 @@
1
- function F() {
2
- return typeof document > "u" ? new OffscreenCanvas(1, 1) : document.createElement("canvas");
3
- }
4
- function be(e) {
5
- return "convertToBlob" in e ? e.convertToBlob({ type: "image/png" }) : new Promise(
6
- (t, r) => e.toBlob(
7
- (i) => i ? t(i) : r(new Error("PNG export failed")),
8
- "image/png"
9
- )
10
- );
11
- }
12
- function j(e, t) {
13
- return e.getContext("2d", t);
14
- }
15
- const Te = "bg0-model-cache", I = "files", Le = 1, H = 16 * 1024 * 1024;
16
- function te(e) {
17
- return typeof e == "string" ? e : e instanceof URL ? e.href : e.url;
18
- }
19
- function re(e) {
20
- return `${e}#meta`;
21
- }
22
- function ne(e, t) {
23
- return `${e}#${t}`;
24
- }
25
- function Fe() {
26
- return new Promise((e, t) => {
27
- const r = indexedDB.open(Te, Le);
28
- r.onupgradeneeded = () => {
29
- r.result.objectStoreNames.contains(I) || r.result.createObjectStore(I);
30
- }, r.onsuccess = () => e(r.result), r.onerror = () => t(r.error ?? new Error("IndexedDB unavailable")), r.onblocked = () => t(new Error("IndexedDB is blocked"));
31
- });
32
- }
33
- function oe(e) {
34
- return new Promise((t, r) => {
35
- e.onsuccess = () => t(e.result), e.onerror = () => r(e.error ?? new Error("IndexedDB request failed"));
36
- });
37
- }
38
- function ie(e) {
39
- return new Promise((t, r) => {
40
- e.oncomplete = () => t(), e.onerror = () => r(e.error ?? new Error("IndexedDB transaction failed")), e.onabort = () => r(e.error ?? new Error("IndexedDB transaction aborted"));
41
- });
42
- }
43
- function ve() {
44
- return typeof indexedDB < "u";
45
- }
46
- function Ee() {
47
- let e;
48
- const t = () => (e || (e = Fe()), e), r = /* @__PURE__ */ new Set();
49
- async function i(n, o, s) {
50
- const a = Math.max(1, Math.ceil(o.byteLength / H)), c = await t();
51
- for (let u = 0; u < a; u += 1) {
52
- const f = c.transaction(I, "readwrite"), h = o.slice(u * H, (u + 1) * H);
53
- f.objectStore(I).put(h, ne(n, u)), await ie(f);
54
- }
55
- const l = { headers: s, size: o.byteLength, chunks: a }, d = c.transaction(I, "readwrite");
56
- d.objectStore(I).put(l, re(n)), await ie(d);
57
- }
58
- return {
59
- async match(n) {
60
- const o = te(n);
61
- if (!r.has(o))
62
- try {
63
- const s = await t(), a = s.transaction(I, "readonly").objectStore(I), c = await oe(a.get(re(o)));
64
- if (!c) return;
65
- const l = [];
66
- for (let u = 0; u < c.chunks; u += 1) {
67
- const f = s.transaction(I, "readonly").objectStore(I), h = await oe(
68
- f.get(ne(o, u))
69
- );
70
- if (!h) return;
71
- l.push(h);
72
- }
73
- const d = new Headers(c.headers);
74
- return d.set("content-length", String(c.size)), new Response(new Blob(l), { headers: d });
75
- } catch {
76
- return;
77
- }
78
- },
79
- async put(n, o) {
80
- const s = te(n), a = await o.arrayBuffer(), c = [];
81
- for (const [l, d] of o.headers)
82
- l.toLowerCase() !== "content-length" && c.push([l, d]);
83
- r.add(s), i(s, a, c).catch((l) => {
84
- console.warn("BG0 could not cache the model locally:", l);
85
- }).finally(() => r.delete(s));
86
- }
87
- };
88
- }
89
- class E extends Error {
90
- code;
91
- constructor(t, r, i) {
92
- super(r, i), this.name = "BackgroundRemovalError", this.code = t;
93
- }
94
- }
95
- function ke(e) {
96
- if (e instanceof E) return e;
97
- const t = e instanceof Error ? e.message.toLowerCase() : "";
98
- return t.includes("memory") || t.includes("allocation") || t.includes("bad_alloc") ? new E(
99
- "out-of-memory",
100
- "This image needs more memory than your browser can provide. Try a smaller image.",
101
- { cause: e }
102
- ) : new E(
103
- "inference-failed",
104
- "Local processing could not finish. Try again or use a smaller image.",
105
- { cause: e }
106
- );
107
- }
108
- const je = 40 * 1024 * 1024, ze = "PNG, JPG, WebP, HEIC, or HEIF", De = /* @__PURE__ */ new Map([
109
- ["image/jpeg", "jpeg"],
110
- ["image/jpg", "jpeg"],
111
- ["image/pjpeg", "jpeg"],
112
- ["image/png", "png"],
113
- ["image/webp", "webp"],
114
- ["image/heic", "heic"],
115
- ["image/heif", "heic"],
116
- ["image/x-heic", "heic"],
117
- ["image/x-heif", "heic"]
118
- ]), We = /* @__PURE__ */ new Map([
119
- ["jpg", "jpeg"],
120
- ["jpeg", "jpeg"],
121
- ["png", "png"],
122
- ["webp", "webp"],
123
- ["heic", "heic"],
124
- ["heif", "heic"],
125
- ["hif", "heic"]
126
- ]), qe = /* @__PURE__ */ new Set(["", "application/octet-stream", "application/binary"]), ae = /* @__PURE__ */ new Set(["heic", "heix", "heim", "heis"]), He = /* @__PURE__ */ new Set(["hevc", "hevx", "hevm", "hevs", "msf1"]), se = /* @__PURE__ */ new Set([...He, "avif", "avis"]);
127
- async function ee(e) {
128
- if (e.size > je)
129
- throw new E(
130
- "image-too-large",
131
- "This image is over 40 MB. Choose a smaller file."
132
- );
133
- const t = await $e(e);
134
- if (!t)
135
- throw new E(
136
- "unsupported-image",
137
- `Choose a ${ze} image.`
138
- );
139
- return t;
140
- }
141
- async function $e(e) {
142
- const t = e.type.toLowerCase().trim(), r = De.get(t);
143
- if (!r && !qe.has(t)) return null;
144
- const i = new Uint8Array(await e.slice(0, 4096).arrayBuffer()), n = Ge(i, e.size <= i.length);
145
- if (n.kind === "unsupported") return null;
146
- if (n.kind === "supported") return n.format;
147
- if (r === "heic") return null;
148
- if (r) return r;
149
- if (typeof File < "u" && e instanceof File) {
150
- const o = e.name.split(".").pop()?.toLowerCase(), s = o ? We.get(o) : void 0;
151
- if (s !== "heic") return s ?? null;
152
- }
153
- return null;
154
- }
155
- function Ge(e, t = !0) {
156
- if (e.length >= 8 && e[0] === 137 && e[1] === 80 && e[2] === 78 && e[3] === 71 && e[4] === 13 && e[5] === 10 && e[6] === 26 && e[7] === 10)
157
- return { kind: "supported", format: "png" };
158
- if (e.length >= 3 && e[0] === 255 && e[1] === 216 && e[2] === 255)
159
- return { kind: "supported", format: "jpeg" };
160
- if (e.length >= 12 && N(e, 0, 4) === "RIFF" && N(e, 8, 12) === "WEBP")
161
- return { kind: "supported", format: "webp" };
162
- if (e.length >= 8 && N(e, 4, 8) === "ftyp") {
163
- const r = $(e, 0);
164
- let i = 8, n = r;
165
- if (r === 0) {
166
- if (!t) return { kind: "unknown" };
167
- n = e.length;
168
- } else if (r === 1) {
169
- if (e.length < 16) return { kind: "unknown" };
170
- const c = $(e, 8), l = $(e, 12);
171
- if (c !== 0) return { kind: "unknown" };
172
- i = 16, n = l;
173
- }
174
- const o = 8;
175
- if (n < i + o || n > e.length || (n - i - o) % 4 !== 0)
176
- return { kind: "unknown" };
177
- const s = N(e, i, i + 4);
178
- if (se.has(s))
179
- return { kind: "unsupported" };
180
- let a = !1;
181
- for (let c = i + o; c < n; c += 4) {
182
- const l = N(e, c, c + 4);
183
- if (se.has(l))
184
- return { kind: "unsupported" };
185
- ae.has(l) && (a = !0);
186
- }
187
- return ae.has(s) ? { kind: "supported", format: "heic" } : s === "mif1" ? a ? { kind: "supported", format: "heic" } : { kind: "unsupported" } : { kind: "unknown" };
188
- }
189
- return { kind: "unknown" };
190
- }
191
- async function T(e, t, r = Ye) {
192
- try {
193
- if ((t ?? await ee(e)) !== "heic") return await r.native(e);
194
- try {
195
- return await r.native(e);
196
- } catch {
197
- return await r.heic(e);
198
- }
199
- } catch (i) {
200
- throw new E(
201
- "decode-failed",
202
- "This image could not be opened. Try exporting it as PNG or JPG.",
203
- { cause: i }
204
- );
205
- }
206
- }
207
- const Ye = {
208
- native: (e) => createImageBitmap(e, { imageOrientation: "from-image" }),
209
- heic: async (e) => {
210
- const t = new URL("./vendor/heic-to.js", import.meta.url).href, { heicTo: r } = await import(
211
- /* @vite-ignore */
212
- t
213
- );
214
- return r({
215
- blob: e,
216
- type: "bitmap",
217
- options: { imageOrientation: "from-image" }
218
- });
219
- }
220
- };
221
- function N(e, t, r) {
222
- return String.fromCharCode(...e.subarray(t, r));
223
- }
224
- function $(e, t) {
225
- return e[t] * 16777216 + e[t + 1] * 65536 + e[t + 2] * 256 + e[t + 3] >>> 0;
226
- }
227
- async function Me(e, t = 512, r = 512, i) {
228
- const n = await T(e, i);
229
- let o;
230
- try {
231
- o = F(), o.width = t, o.height = r;
232
- const s = j(o, { willReadFrequently: !0 });
233
- if (!s) throw new Error("Canvas is unavailable");
234
- return s.drawImage(n, 0, 0, t, r), {
235
- data: s.getImageData(0, 0, t, r).data,
236
- width: t,
237
- height: r,
238
- sourceWidth: n.width,
239
- sourceHeight: n.height
240
- };
241
- } finally {
242
- o && A(o), n.close();
243
- }
244
- }
245
- const Qe = 0.1, Ve = 0.12, Xe = 0.85, Ke = 0.8, Je = 0.4;
246
- function Q(e, t) {
247
- if (e.length !== t || e.length === 0)
248
- return { valid: !1, hasForegroundSignal: !1 };
249
- let r = Number.POSITIVE_INFINITY, i = Number.NEGATIVE_INFINITY;
250
- for (const n of e) {
251
- if (!Number.isFinite(n))
252
- return { valid: !1, hasForegroundSignal: !1 };
253
- r = Math.min(r, n), i = Math.max(i, n);
254
- }
255
- return {
256
- valid: !0,
257
- hasForegroundSignal: i >= 0.05 && i - r >= 5e-3
258
- };
259
- }
260
- function Se(e, t, r, i, n) {
261
- let o = t, s = r, a = -1, c = -1, l = 0;
262
- for (let w = 0; w < r; w += 1)
263
- for (let v = 0; v < t; v += 1)
264
- e[w * t + v] < Qe || (l += 1, o = Math.min(o, v), s = Math.min(s, w), a = Math.max(a, v), c = Math.max(c, w));
265
- if (a < o || c < s) return null;
266
- const d = i / t, u = n / r;
267
- let f = Math.floor(o * d), h = Math.floor(s * u), g = Math.ceil((a + 1) * d), b = Math.ceil((c + 1) * u);
268
- const m = Math.ceil(Math.max(g - f, b - h) * Ve);
269
- f = Math.max(0, f - m), h = Math.max(0, h - m), g = Math.min(i, g + m), b = Math.min(n, b + m);
270
- const p = g - f, k = b - h, C = p * k, x = i * n;
271
- if (p < 32 || k < 32 || C >= x * Xe) return null;
272
- const O = l * d * u;
273
- return C >= x * Ke && O / C < Je ? null : { left: f, top: h, right: g, bottom: b };
274
- }
275
- async function Ie(e, t, r, i, n, o) {
276
- const s = [];
277
- try {
278
- const a = ce(t, r, i, n);
279
- s.push(a);
280
- const c = F();
281
- s.push(c), c.width = e.width, c.height = e.height;
282
- const l = j(c);
283
- if (!l) throw new Error("Canvas is unavailable");
284
- if (l.imageSmoothingEnabled = !0, l.imageSmoothingQuality = n === "quality" ? "high" : "medium", l.drawImage(a, 0, 0, e.width, e.height), A(a), o) {
285
- const d = ce(
286
- o.mask,
287
- o.maskWidth,
288
- o.maskHeight,
289
- n
290
- );
291
- s.push(d);
292
- const { left: u, top: f, right: h, bottom: g } = o.crop;
293
- l.clearRect(u, f, h - u, g - f), l.drawImage(d, u, f, h - u, g - f), A(d);
294
- }
295
- return l.globalCompositeOperation = "source-in", l.drawImage(e, 0, 0), await be(c);
296
- } finally {
297
- for (const a of s) A(a);
298
- }
299
- }
300
- async function xe(e) {
301
- const t = F();
302
- try {
303
- t.width = e.width, t.height = e.height;
304
- const r = j(t);
305
- if (!r) throw new Error("Canvas is unavailable");
306
- return r.drawImage(e, 0, 0), await be(t);
307
- } finally {
308
- A(t);
309
- }
310
- }
311
- function A(e) {
312
- e.width = 0, e.height = 0;
313
- }
314
- function ce(e, t, r, i) {
315
- const n = F();
316
- try {
317
- n.width = t, n.height = r;
318
- const o = j(n);
319
- if (!o) throw new Error("Canvas is unavailable");
320
- const s = o.createImageData(t, r);
321
- for (let a = 0; a < e.length; a += 1) {
322
- const c = i === "quality" ? e[a] : Ze(0.08, 0.92, e[a]), l = a * 4;
323
- s.data[l] = 255, s.data[l + 1] = 255, s.data[l + 2] = 255, s.data[l + 3] = Math.round(c * 255);
324
- }
325
- return o.putImageData(s, 0, 0), n;
326
- } catch (o) {
327
- throw A(n), o;
328
- }
329
- }
330
- function Ze(e, t, r) {
331
- const i = Math.max(0, Math.min(1, (r - e) / (t - e)));
332
- return i * i * (3 - 2 * i);
333
- }
334
- const Re = /\b(?:iPhone|iPad|iPod)\b/i, et = /\bMacintosh\b/i, tt = /\b(?:Chrome|Chromium|Edg|OPR|SamsungBrowser)\/\d+/i;
335
- function rt(e, t) {
336
- return t && !Re.test(e) && tt.test(e);
337
- }
338
- function Ce(e, t = 0) {
339
- return Re.test(e) || et.test(e) && t > 1;
340
- }
341
- const V = {
342
- name: "birefnet-lite",
343
- id: "studioludens/birefnet-lite-512",
344
- revision: "4a3c40c36c94093cc1e724d9ea428b8fa4b57dc7",
345
- bytes: 98484532,
346
- inputSize: 512
347
- }, X = {
348
- name: "birefnet",
349
- id: "naddy24/birefnet-512-webgpu",
350
- revision: "ca02a86c094927479e2be583abe87f8ea73fcfda",
351
- bytes: 473435223,
352
- inputSize: 512
353
- };
354
- function nt(e) {
355
- return `https://huggingface.co/${e.id}/resolve/${e.revision}/onnx/model_fp16.onnx`;
356
- }
357
- function W(e) {
358
- return `${e.definition.id}:${e.definition.revision}:${e.provider}`;
359
- }
360
- async function ot(e = typeof navigator > "u" ? void 0 : navigator) {
361
- const t = [], r = e?.deviceMemory, i = !!(r && r < 4);
362
- if (e && rt(e.userAgent, !!e.gpu))
363
- try {
364
- const n = await e.gpu?.requestAdapter();
365
- n && !n.isFallbackAdapter && n.features.has("shader-f16") && (!i && n.limits.maxBufferSize >= 256 * 1024 * 1024 && n.limits.maxStorageBufferBindingSize >= 128 * 1024 * 1024 && t.push({ definition: X, provider: "webgpu" }), t.push({ definition: V, provider: "webgpu" }));
366
- } catch {
367
- }
368
- return t.length === 0 && e && !i && (e.hardwareConcurrency ?? 0) >= 4 && !Ce(e.userAgent, e.maxTouchPoints) && t.push({ definition: X, provider: "wasm" }), t.push({ definition: V, provider: "wasm" }), t;
369
- }
370
- async function it({
371
- quality: e,
372
- source: t,
373
- highResSource: r,
374
- outputWidth: i,
375
- outputHeight: n,
376
- base: o,
377
- signal: s,
378
- onRefining: a,
379
- infer: c
380
- }) {
381
- if (e !== "quality") return;
382
- const l = r ?? t, d = Se(
383
- o.alpha,
384
- o.maskWidth,
385
- o.maskHeight,
386
- l.width,
387
- l.height
388
- );
389
- if (d) {
390
- G(s), a();
391
- try {
392
- const u = await l.clone().crop([d.left, d.top, d.right - 1, d.bottom - 1]), f = await c(u);
393
- return G(s), !f.inspection.valid || !f.inspection.hasForegroundSignal ? void 0 : {
394
- mask: f.alpha,
395
- maskWidth: f.maskWidth,
396
- maskHeight: f.maskHeight,
397
- crop: {
398
- left: Math.floor(d.left * i / l.width),
399
- top: Math.floor(d.top * n / l.height),
400
- right: Math.ceil(d.right * i / l.width),
401
- bottom: Math.ceil(d.bottom * n / l.height)
402
- }
403
- };
404
- } catch {
405
- G(s);
406
- return;
407
- }
408
- }
409
- }
410
- function G(e) {
411
- if (e?.aborted)
412
- throw new E("cancelled", "Processing was cancelled.");
413
- }
414
- var at = "" + new URL("worker-DfrCFP3O.js", import.meta.url).href;
415
- function st(e, t = {}) {
416
- const r = e instanceof URL ? e : new URL(e, typeof location > "u" ? import.meta.url : location.href), i = { ...t, type: "module" };
417
- if (typeof location > "u" || r.origin === location.origin)
418
- return new Worker(r, i);
419
- const n = URL.createObjectURL(
420
- new Blob([`import ${JSON.stringify(r.href)};`], { type: "text/javascript" })
421
- ), o = () => URL.revokeObjectURL(n);
422
- let s;
423
- try {
424
- s = new Worker(n, i);
425
- } catch (d) {
426
- throw o(), d;
427
- }
428
- const a = s.terminate.bind(s);
429
- let c = !1;
430
- const l = () => {
431
- c || (c = !0, o());
432
- };
433
- return s.addEventListener("message", l, { once: !0 }), s.addEventListener("error", l, { once: !0 }), s.terminate = () => {
434
- l(), a();
435
- }, s;
436
- }
437
- function ct(e, t, r) {
438
- if (e.length !== t * r * 4) throw new Error("Invalid pixel buffer");
439
- const i = new Float32Array(3 * t * r), n = [0.485, 0.456, 0.406], o = [0.229, 0.224, 0.225];
440
- for (let s = 0; s < t * r; s++)
441
- for (let a = 0; a < 3; a++)
442
- i[a * t * r + s] = (e[s * 4 + a] / 255 - n[a]) / o[a];
443
- return i;
444
- }
445
- function lt(e, t) {
446
- const r = Math.min(1, 1280 / Math.max(e, t));
447
- return {
448
- width: Math.max(1, Math.round(e * r)),
449
- height: Math.max(1, Math.round(t * r))
450
- };
451
- }
452
- let le = Promise.resolve(), M, de;
453
- function dt(e, t) {
454
- return new Promise((r, i) => {
455
- const n = () => i(new E("cancelled", "Processing was cancelled."));
456
- if (t?.aborted) {
457
- n();
458
- return;
459
- }
460
- t?.addEventListener("abort", n, { once: !0 }), le = le.then(async () => {
461
- if (t?.removeEventListener("abort", n), !t?.aborted)
462
- try {
463
- r(await e());
464
- } catch (o) {
465
- i(o);
466
- }
467
- });
468
- });
469
- }
470
- function S(e) {
471
- if (e?.aborted) throw new E("cancelled", "Processing was cancelled.");
472
- }
473
- function ut() {
474
- return (!M || M.isDisposed) && (M = new ht()), M;
475
- }
476
- function ft(e, t) {
477
- return dt(async () => {
478
- const r = performance.now(), i = t.quality ?? "fast";
479
- let n, o, s = 0;
480
- const a = (l, d, u) => {
481
- s = Math.max(s, d), t.onProgress?.({ stage: l, progress: s, message: u });
482
- }, c = () => {
483
- o?.dispose(new E("cancelled", "Processing was cancelled.")), M === o && (M = void 0);
484
- };
485
- try {
486
- S(t.signal);
487
- const l = await ee(e);
488
- a("preparing", 0.03, "Preparing image…");
489
- const d = await Me(e, 512, 512, l);
490
- S(t.signal), o = ut(), de = o, t.signal?.addEventListener("abort", c, { once: !0 }), S(t.signal), o.onStage = (m) => a(
491
- m === "loading" ? "downloading" : "preparing",
492
- m === "loading" ? 0.08 : 0.6,
493
- m === "loading" ? "Downloading local model…" : "Starting local model…"
494
- ), await o.load(), S(t.signal), a("processing", 0.7, "Removing background…");
495
- const u = await o.run(d.data);
496
- if (S(t.signal), !Q(u, 512 * 512).valid) throw new Error("Invalid alpha mask");
497
- const f = lt(d.sourceWidth, d.sourceHeight);
498
- let h;
499
- if (i === "quality") {
500
- const m = Se(u, 512, 512, 512, 512);
501
- if (m) {
502
- a("processing", 0.84, "Refining fine details…");
503
- const p = document.createElement("canvas"), k = document.createElement("canvas");
504
- try {
505
- p.width = p.height = k.width = k.height = 512;
506
- const C = p.getContext("2d"), x = k.getContext("2d", {
507
- willReadFrequently: !0
508
- });
509
- if (!C || !x) throw new Error("Canvas unavailable");
510
- C.putImageData(
511
- new ImageData(new Uint8ClampedArray(d.data), 512, 512),
512
- 0,
513
- 0
514
- ), x.drawImage(
515
- p,
516
- m.left,
517
- m.top,
518
- m.right - m.left,
519
- m.bottom - m.top,
520
- 0,
521
- 0,
522
- 512,
523
- 512
524
- );
525
- const O = await o.run(x.getImageData(0, 0, 512, 512).data);
526
- Q(O, 512 * 512).hasForegroundSignal && (h = {
527
- mask: O,
528
- maskWidth: 512,
529
- maskHeight: 512,
530
- crop: {
531
- left: Math.floor(m.left * f.width / 512),
532
- top: Math.floor(m.top * f.height / 512),
533
- right: Math.ceil(m.right * f.width / 512),
534
- bottom: Math.ceil(m.bottom * f.height / 512)
535
- }
536
- });
537
- } catch {
538
- o.isDisposed && M === o && (M = void 0), S(t.signal);
539
- } finally {
540
- p.width = p.height = k.width = k.height = 0;
541
- }
542
- }
543
- }
544
- if (S(t.signal), a("finishing", 0.92, "Finishing edges…"), n = await T(e, l), n.width !== f.width || n.height !== f.height) {
545
- const m = await createImageBitmap(n, {
546
- resizeWidth: f.width,
547
- resizeHeight: f.height,
548
- resizeQuality: "high"
549
- });
550
- n.close(), n = m;
551
- }
552
- S(t.signal);
553
- const g = await xe(n), b = await Ie(n, u, 512, 512, i, h);
554
- return S(t.signal), a("finishing", 1, "Background removed"), {
555
- blob: b,
556
- sourceBlob: g,
557
- width: f.width,
558
- height: f.height,
559
- model: "birefnet-lite",
560
- provider: "wasm",
561
- quality: i,
562
- durationMs: Math.round(performance.now() - r)
563
- };
564
- } catch (l) {
565
- throw o && M === o && (M = void 0), S(t.signal), ke(l);
566
- } finally {
567
- t.signal?.removeEventListener("abort", c), n?.close(), de = void 0, o && (o.onStage = void 0, M !== o && o.dispose());
568
- }
569
- }, t.signal);
570
- }
571
- class ht {
572
- worker;
573
- nextId = 0;
574
- pending = /* @__PURE__ */ new Map();
575
- loaded;
576
- dead = !1;
577
- onStage;
578
- constructor(t = () => st(at, {
579
- type: "module"
580
- })) {
581
- this.worker = t(), this.worker.onmessage = ({ data: r }) => {
582
- if (r.stage) {
583
- this.onStage?.(r.stage);
584
- return;
585
- }
586
- const i = this.pending.get(r.id);
587
- i && (this.pending.delete(r.id), r.error ? i.reject(
588
- new E(
589
- r.error === "model-load-failed" ? "model-load-failed" : "inference-failed",
590
- r.error === "model-load-failed" ? "The local model could not be loaded. Check your connection and try again." : "Local processing could not finish. Try a smaller image."
591
- )
592
- ) : i.resolve(r));
593
- }, this.worker.onerror = () => this.dispose(
594
- new E(
595
- "model-load-failed",
596
- "The local model stopped. Please try again."
597
- )
598
- ), this.worker.onmessageerror = () => this.dispose(new Error("Worker response unavailable"));
599
- }
600
- get isDisposed() {
601
- return this.dead;
602
- }
603
- load() {
604
- return this.loaded ??= this.request("load").then(() => {
605
- }), this.loaded;
606
- }
607
- async run(t) {
608
- const r = ct(t, 512, 512).buffer, i = await this.request("run", r);
609
- if (!i.alpha || i.alpha.byteLength !== 512 * 512 * 4)
610
- throw new Error("Invalid mask shape");
611
- return new Float32Array(i.alpha);
612
- }
613
- request(t, r) {
614
- if (this.dead) return Promise.reject(new Error("Worker stopped"));
615
- const i = ++this.nextId;
616
- return new Promise((n, o) => {
617
- this.pending.set(i, { resolve: n, reject: o });
618
- try {
619
- this.worker.postMessage({ id: i, type: t, buffer: r }, r ? [r] : []);
620
- } catch (s) {
621
- this.pending.delete(i), o(s);
622
- }
623
- });
624
- }
625
- dispose(t = new Error("Worker stopped")) {
626
- if (!this.dead) {
627
- this.dead = !0, this.worker.terminate();
628
- for (const r of this.pending.values()) r.reject(t);
629
- this.pending.clear();
630
- }
631
- }
632
- }
633
- const K = /^[a-f0-9]{64}$/, gt = 600 * 1024 * 1024;
634
- function L(e, t = !1) {
635
- const r = new URL(e);
636
- if (!["https:", "http:"].includes(r.protocol) || r.username || r.password || r.search || r.hash || t && !r.pathname.endsWith("/")) throw Error("Invalid explicit cutout resource URL");
637
- return r;
638
- }
639
- function ue(e) {
640
- return typeof e == "string" && /^[a-zA-Z0-9_.@/-]+$/.test(e) && !e.startsWith("/") && !e.split("/").some((t) => !t || t === "." || t === "..");
641
- }
642
- function mt(e) {
643
- if (L(e.manifestUrl), L(e.modelBaseUrl, !0), L(e.runtimeBaseUrl, !0), !K.test(e.manifestSha256)) throw Error("Pinned manifest SHA-256 required");
644
- }
645
- async function Be(e) {
646
- return Array.from(
647
- new Uint8Array(await crypto.subtle.digest("SHA-256", e)),
648
- (t) => t.toString(16).padStart(2, "0")
649
- ).join("");
650
- }
651
- async function fe(e, t, r, i) {
652
- const n = await fetch(e, { signal: i, redirect: "error" });
653
- if (!n.ok || Number(n.headers.get("content-length")) > r)
654
- throw await n.body?.cancel(), Error(n.ok ? "Cutout resource exceeds declared size" : `Cutout resource unavailable: ${e.pathname}`);
655
- const o = n.body?.getReader();
656
- if (!o) throw Error("Cutout resource body missing");
657
- const s = [];
658
- let a = 0;
659
- try {
660
- for (; ; ) {
661
- i?.throwIfAborted();
662
- const d = await o.read();
663
- if (d.done) break;
664
- if (a += d.value.length, a > r) throw Error("Cutout resource exceeds declared size");
665
- s.push(d.value);
666
- }
667
- } finally {
668
- await o.cancel();
669
- }
670
- const c = new Uint8Array(a);
671
- let l = 0;
672
- for (const d of s)
673
- c.set(d, l), l += d.length;
674
- if (await Be(c) !== t) throw Error(`Cutout resource SHA-256 mismatch: ${e.pathname}`);
675
- return c;
676
- }
677
- async function wt(e, t, r, i = () => {
678
- }) {
679
- t = Object.freeze({
680
- manifestUrl: t.manifestUrl,
681
- manifestSha256: t.manifestSha256,
682
- modelBaseUrl: t.modelBaseUrl,
683
- runtimeBaseUrl: t.runtimeBaseUrl
684
- }), mt(t);
685
- const n = await fe(L(t.manifestUrl), t.manifestSha256, 1024 * 1024, r), o = JSON.parse(new TextDecoder().decode(n));
686
- if (o.schemaVersion !== 1 || o.model !== e || typeof o.revision != "string" || !o.revision || o.revision.length > 200 || e === "isnet_fp16" || o.modelId !== "naddy24/birefnet-512-webgpu" || o.revision !== "ca02a86c094927479e2be583abe87f8ea73fcfda" || o.runtimeVersion !== "1.31.0-dev.20260914-8d85527a0" || !o.files || Array.isArray(o.files) || !Object.keys(o.files).length || Object.keys(o.files).length > 64) throw Error("Cutout model/runtime manifest mismatch");
687
- for (const [a, c] of Object.entries(o.files)) {
688
- if (!ue(a) || !["model", "runtime"].includes(c.kind) || !Number.isSafeInteger(c.size) || c.size < 1 || c.size > gt || !K.test(c.sha256) || typeof c.mime != "string" || !c.mime || c.mime.length > 128 || a.startsWith("onnxruntime-web/") && c.kind !== "runtime" || !Array.isArray(c.chunks) || c.chunks.length > 1024)
689
- throw Error("Invalid cutout resource declaration");
690
- let l = 0;
691
- for (const d of c.chunks) {
692
- if (!ue(d.name) || !K.test(d.sha256) || !Array.isArray(d.offsets) || d.offsets[0] !== l || !Number.isSafeInteger(d.offsets[1]) || d.offsets[1] <= l || d.offsets[1] > c.size || d.offsets[1] - l > 64 * 1024 * 1024)
693
- throw Error("Invalid cutout resource chunk");
694
- l = d.offsets[1];
695
- }
696
- if (l !== c.size) throw Error("Incomplete cutout resource chunks");
697
- for (const d of c.chunks)
698
- Object.freeze(d.offsets), Object.freeze(d);
699
- Object.freeze(c.chunks), Object.freeze(c);
700
- }
701
- return Object.freeze(o.files), Object.freeze(o), { manifest: o, source: t, read: async (a) => {
702
- const c = o.files[a];
703
- if (!Object.hasOwn(o.files, a) || !c) return Promise.reject(Error(`Undeclared cutout resource: ${a}`));
704
- const l = L(c.kind === "model" ? t.modelBaseUrl : t.runtimeBaseUrl, !0), d = new Uint8Array(c.size);
705
- for (const u of c.chunks) {
706
- const f = await fe(new URL(u.name, l), u.sha256, u.offsets[1] - u.offsets[0], r);
707
- if (f.length !== u.offsets[1] - u.offsets[0]) throw Error("Cutout resource chunk size mismatch");
708
- d.set(f, u.offsets[0]), i(`fetch:${a}`, u.offsets[1], c.size);
709
- }
710
- if (await Be(d) !== c.sha256) throw Error(`Cutout resource SHA-256 mismatch: ${a}`);
711
- return d;
712
- } };
713
- }
714
- let D;
715
- function Oe() {
716
- return D !== void 0;
717
- }
718
- async function pt(e, t) {
719
- const r = JSON.stringify(e);
720
- if (D) {
721
- if (D !== r) throw Error("A cutout Worker cannot change resource identity");
722
- return;
723
- }
724
- const i = await wt("birefnet_quality", e, void 0, t), { env: n } = await import("./transformers.web-DB57cIO5.js"), o = n.backends.onnx.wasm;
725
- if (!o) throw Error("Standard cutout ORT runtime unavailable");
726
- const s = o.wasmPaths, a = (f, h) => {
727
- const g = f?.split("/").at(-1);
728
- if (!g || !new RegExp(`^ort-wasm-simd-threaded(?:\\.asyncify|\\.jsep)?\\.${h}$`).test(g))
729
- throw Error("Standard cutout runtime variant must be explicitly declared");
730
- return g;
731
- }, [c, l] = await Promise.all([
732
- i.read(`onnxruntime-web/${a(s?.wasm, "wasm")}`),
733
- i.read(`onnxruntime-web/${a(s?.mjs, "mjs")}`)
734
- ]), d = URL.createObjectURL(new Blob([l], { type: "text/javascript" })), u = URL.createObjectURL(new Blob([c], { type: "application/wasm" }));
735
- n.allowRemoteModels = !1, n.allowLocalModels = !0, n.localModelPath = e.modelBaseUrl, n.useBrowserCache = !1, n.useCustomCache = !1, n.useFSCache = !1, n.fetch = async (f) => {
736
- const h = new URL(String(f)), g = new URL(e.modelBaseUrl);
737
- if (h.origin !== g.origin || !h.pathname.startsWith(g.pathname) || h.search || h.hash)
738
- throw Error("Undeclared standard cutout model URL");
739
- const b = h.pathname.slice(g.pathname.length), m = i.manifest.files[b];
740
- if (!m || m.kind !== "model") throw Error(`Undeclared standard cutout model file: ${b}`);
741
- return new Response(await i.read(b), { headers: { "content-type": m.mime, "content-length": String(m.size) } });
742
- }, o.proxy = !1, o.wasmPaths = { wasm: u, mjs: d }, o.wasmBinary = c, D = r;
743
- }
744
- function yt() {
745
- return typeof navigator < "u" && Ce(navigator.userAgent, navigator.maxTouchPoints);
746
- }
747
- const Pe = `bg0:webgpu-failure:v4:${V.revision}`, B = /* @__PURE__ */ new Map(), J = /* @__PURE__ */ new Set();
748
- let he, Ue = !0;
749
- async function bt(e, t = {}) {
750
- if (!Oe())
751
- throw Error("MISSING_RESOURCE: explicit standard model/runtime resources required");
752
- if (yt()) {
753
- if (t.requiredModel === "birefnet")
754
- throw new Error("当前设备不支持完整 BiRefNet Quality,请选择快速模式。");
755
- return ft(e, t);
756
- }
757
- const r = performance.now(), i = t.quality ?? "fast";
758
- let n = 0;
759
- const o = (c) => {
760
- n = Math.max(n, c.progress), t.onProgress?.({ ...c, progress: n });
761
- };
762
- let s, a;
763
- try {
764
- y(t.signal);
765
- const c = await ee(e);
766
- o({ stage: "preparing", progress: 0.03, message: "Preparing image…" });
767
- let l = e, d = c, u;
768
- if (c === "heic") {
769
- const w = await T(e, c);
770
- try {
771
- y(t.signal), u = await xe(w);
772
- } finally {
773
- w.close();
774
- }
775
- l = u, d = "png";
776
- }
777
- y(t.signal);
778
- const f = (await vt()).filter(
779
- (w) => !t.requiredModel || w.definition.name === t.requiredModel
780
- );
781
- if (!f.length) throw new Error("当前设备不支持所选完整模型,请选择其它模式。");
782
- y(t.signal);
783
- const h = await Me(
784
- l,
785
- f[0].definition.inputSize,
786
- f[0].definition.inputSize,
787
- d
788
- );
789
- y(t.signal), a = await ge(
790
- f,
791
- (w, v, R) => {
792
- o({
793
- stage: R || v ? "preparing" : "downloading",
794
- progress: 0.08 + w * 0.58,
795
- downloadFraction: R || v ? void 0 : w,
796
- message: v ? "Starting local model…" : R ? "Loading cached model…" : "Downloading local model…"
797
- });
798
- },
799
- t.signal
800
- );
801
- let g = a.engine;
802
- y(t.signal), o({
803
- stage: "processing",
804
- progress: 0.7,
805
- message: "Removing background…"
806
- });
807
- const { RawImage: b } = await import("./transformers.web-DB57cIO5.js"), m = new b(
808
- h.data,
809
- h.width,
810
- h.height,
811
- 4
812
- );
813
- let p;
814
- for (; ; ) {
815
- y(t.signal);
816
- try {
817
- if (p = await pe(g, m), !p.inspection.valid || g.provider === "webgpu" && !p.inspection.hasForegroundSignal)
818
- throw new Error("The model returned an invalid alpha mask");
819
- break;
820
- } catch (w) {
821
- if (y(t.signal), g.provider === "wasm" && g.definition.name === "birefnet-lite" || (Ae(g), await a.retire(), await a.release(), a = void 0, t.requiredModel)) throw w;
822
- y(t.signal), o({
823
- stage: "preparing",
824
- progress: 0.74,
825
- message: "Switching to a compatible model…"
826
- }), a = await ge(
827
- f,
828
- (v, R, P) => {
829
- o({
830
- stage: R || P ? "preparing" : "downloading",
831
- progress: 0.74 + v * 0.14,
832
- message: R ? "Starting compatibility mode…" : "Preparing compatibility mode…"
833
- });
834
- },
835
- t.signal
836
- ), g = a.engine, y(t.signal), o({
837
- stage: "processing",
838
- progress: 0.89,
839
- message: "Retrying background removal…"
840
- });
841
- }
842
- }
843
- y(t.signal);
844
- let k;
845
- if (i === "quality")
846
- try {
847
- y(t.signal);
848
- const w = await T(l, d);
849
- try {
850
- const v = Math.max(w.width, w.height), R = v > 1024 ? 1024 / v : 1, P = Math.round(w.width * R), z = Math.round(w.height * R), _ = F();
851
- _.width = P, _.height = z;
852
- try {
853
- const q = j(_, { willReadFrequently: !0 });
854
- if (q) {
855
- q.drawImage(w, 0, 0, P, z);
856
- const Ne = q.getImageData(0, 0, P, z).data;
857
- k = new b(Ne, P, z, 4);
858
- }
859
- } finally {
860
- _.width = 0, _.height = 0;
861
- }
862
- } finally {
863
- w.close();
864
- }
865
- } catch {
866
- y(t.signal);
867
- }
868
- const C = await it({
869
- quality: i,
870
- source: m,
871
- highResSource: k,
872
- outputWidth: h.sourceWidth,
873
- outputHeight: h.sourceHeight,
874
- base: p,
875
- signal: t.signal,
876
- onRefining: () => {
877
- o({
878
- stage: "processing",
879
- progress: 0.84,
880
- message: "Refining fine details…"
881
- });
882
- },
883
- infer: (w) => pe(g, w)
884
- });
885
- o({ stage: "finishing", progress: 0.92, message: "Finishing edges…" });
886
- const x = await T(l, d);
887
- s = x, y(t.signal);
888
- const O = await Ie(
889
- x,
890
- p.alpha,
891
- p.maskWidth,
892
- p.maskHeight,
893
- i,
894
- C
895
- );
896
- return y(t.signal), o({ stage: "finishing", progress: 1, message: "Background removed" }), {
897
- blob: O,
898
- sourceBlob: u,
899
- width: h.sourceWidth,
900
- height: h.sourceHeight,
901
- provider: g.provider,
902
- model: g.definition.name,
903
- quality: i,
904
- durationMs: Math.round(performance.now() - r)
905
- };
906
- } catch (c) {
907
- throw ke(c);
908
- } finally {
909
- s?.close(), await a?.release();
910
- }
911
- }
912
- async function ge(e, t, r) {
913
- let i;
914
- for (const n of e) {
915
- if (y(r), J.has(W(n))) continue;
916
- const o = await Et(n.definition);
917
- if (y(r), !J.has(W(n)))
918
- try {
919
- return await St(n, (s, a) => {
920
- t(s, a, o);
921
- });
922
- } catch (s) {
923
- i = s, (n.provider === "webgpu" || n.definition.name === "birefnet") && Ae(n);
924
- }
925
- }
926
- throw It(i);
927
- }
928
- async function vt() {
929
- return he ??= ot(), (await he).filter((t) => t.provider !== "webgpu" || kt());
930
- }
931
- async function Et(e) {
932
- const t = nt(e);
933
- try {
934
- if (typeof caches < "u")
935
- return !!await (await caches.open("transformers-cache")).match(t);
936
- if (ve())
937
- return !!await Ee().match(t);
938
- } catch {
939
- }
940
- return !1;
941
- }
942
- function Ae(e) {
943
- J.add(W(e)), e.provider === "webgpu" && e.definition.name === "birefnet-lite" && Mt();
944
- }
945
- async function me(e) {
946
- e.retired = !0, !(e.users > 0) && (e.disposal ??= e.promise.then((t) => t.model.dispose()).then(() => {
947
- }).catch(() => {
948
- }), await e.disposal);
949
- }
950
- function kt() {
951
- if (!Ue) return !1;
952
- try {
953
- return localStorage.getItem(Pe) !== navigator.userAgent;
954
- } catch {
955
- return !0;
956
- }
957
- }
958
- function Mt() {
959
- Ue = !1;
960
- try {
961
- localStorage.setItem(Pe, navigator.userAgent);
962
- } catch {
963
- }
964
- }
965
- async function St(e, t) {
966
- const r = W(e);
967
- let i = B.get(r);
968
- if (!i) {
969
- const a = /* @__PURE__ */ new Set();
970
- let c;
971
- c = { promise: Rt(e, (d, u) => {
972
- if (B.get(r) === c) {
973
- c.progress = { progress: d, initializing: u };
974
- for (const f of c.listeners)
975
- we(f, c.progress);
976
- }
977
- }), listeners: a, users: 0, retired: !1 }, i = c, B.set(r, i);
978
- }
979
- const n = i;
980
- n.users++;
981
- let o = !1;
982
- const s = async () => {
983
- o || (o = !0, n.users--, n.retired && await me(n));
984
- };
985
- n.listeners.add(t);
986
- try {
987
- n.progress && we(t, n.progress);
988
- const a = await n.promise;
989
- return B.get(r) === n && (n.progress = void 0), {
990
- engine: a,
991
- retire: () => (B.get(r) === n && B.delete(r), me(n)),
992
- release: s
993
- };
994
- } catch (a) {
995
- throw B.get(r) === n && B.delete(r), await s(), a;
996
- } finally {
997
- n.listeners.delete(t);
998
- }
999
- }
1000
- function we(e, t) {
1001
- try {
1002
- e(t.progress, t.initializing);
1003
- } catch {
1004
- }
1005
- }
1006
- function It(e) {
1007
- return new E(
1008
- "model-load-failed",
1009
- "The local model could not be loaded. Check your connection and try again.",
1010
- { cause: e }
1011
- );
1012
- }
1013
- async function pe(e, t) {
1014
- const i = (await e.processor(t)).pixel_values;
1015
- if (!i) throw new Error("Image preprocessing failed");
1016
- const n = await e.model({ input_image: i }), o = n.logits ?? n.output_image;
1017
- if (!o) throw new Error("The model returned no alpha mask");
1018
- const s = o.sigmoid().data;
1019
- if (!(s instanceof Float32Array))
1020
- throw new Error("The model returned an invalid alpha mask");
1021
- const a = o.dims.at(-2), c = o.dims.at(-1);
1022
- if (!c || !a)
1023
- throw new Error("The model returned an invalid mask shape");
1024
- return {
1025
- alpha: s,
1026
- maskWidth: c,
1027
- maskHeight: a,
1028
- inspection: Q(s, c * a)
1029
- };
1030
- }
1031
- function xt(e, t) {
1032
- const r = /* @__PURE__ */ new Map();
1033
- let i = 0;
1034
- const n = (s, a) => a && a > 0 ? a : s.endsWith(".onnx") ? e : 4096, o = () => {
1035
- let s = 0, a = 0, c = !1;
1036
- for (const [d, u] of r)
1037
- s += Math.min(u.loaded, u.total), a += u.total, d.endsWith(".onnx") && (c = !0);
1038
- c || (a += e);
1039
- const l = a > 0 ? s / a : 0;
1040
- l > i && (i = l, t(Math.min(1, l), !1));
1041
- };
1042
- return (s) => {
1043
- if (!s || typeof s != "object") return;
1044
- const a = s;
1045
- if (!a.file) return;
1046
- const c = r.get(a.file);
1047
- if (a.status === "initiate")
1048
- c || r.set(a.file, { loaded: 0, total: n(a.file, 0) });
1049
- else if (a.status === "progress") {
1050
- const l = n(a.file, a.total);
1051
- r.set(a.file, {
1052
- loaded: Math.max(c?.loaded ?? 0, a.loaded ?? 0),
1053
- total: l
1054
- });
1055
- } else if (a.status === "done") {
1056
- const l = c?.total ?? n(a.file, 0);
1057
- r.set(a.file, { loaded: l, total: l });
1058
- } else
1059
- return;
1060
- o(), a.status === "done" && a.file.endsWith(".onnx") && t(1, !0);
1061
- };
1062
- }
1063
- async function Rt(e, t) {
1064
- const { provider: r, definition: i } = e, { AutoModel: n, AutoProcessor: o, env: s } = await import("./transformers.web-DB57cIO5.js");
1065
- Oe() ? (s.useBrowserCache = !1, s.useCustomCache = !1, s.useFSCache = !1) : typeof caches < "u" ? s.useBrowserCache = !0 : ve() ? (s.useBrowserCache = !1, s.useCustomCache = !0, s.customCache = Ee()) : s.useBrowserCache = !1;
1066
- const a = xt(i.bytes, t), c = await o.from_pretrained(i.id, {
1067
- revision: i.revision,
1068
- progress_callback: a
1069
- });
1070
- return { model: await n.from_pretrained(i.id, {
1071
- revision: i.revision,
1072
- device: r,
1073
- dtype: "fp16",
1074
- progress_callback: a
1075
- }), processor: c, ...e };
1076
- }
1077
- function y(e) {
1078
- if (e?.aborted)
1079
- throw new E("cancelled", "Processing was cancelled.");
1080
- }
1081
- function Ct(e) {
1082
- if (e.quality !== "quality" || e.model !== "birefnet")
1083
- throw new Error("标准模式需要完整 BiRefNet 模型;当前设备未满足运行条件,请改用轻量模式。 ");
1084
- return e;
1085
- }
1086
- async function Bt(e, t, r) {
1087
- const i = await bt(e, {
1088
- quality: "quality",
1089
- requiredModel: "birefnet",
1090
- signal: r,
1091
- onProgress: (o) => t(Ot(o))
1092
- }), n = Ct(i);
1093
- return {
1094
- blob: n.blob,
1095
- latency_ms: n.durationMs,
1096
- model: n.model,
1097
- provider: n.provider
1098
- };
1099
- }
1100
- function Ot(e) {
1101
- return e.stage === "downloading" ? {
1102
- label: "正在下载 BiRefNet Quality 模型(首次约 473 MB)",
1103
- fraction: e.downloadFraction ?? null
1104
- } : e.stage === "preparing" ? { label: "正在加载 BiRefNet Quality 模型", fraction: null } : e.stage === "processing" ? { label: "正在运行 BiRefNet Quality", fraction: null } : { label: "正在生成透明背景", fraction: null };
1105
- }
1106
- function Pt(e, t) {
1107
- if (!e || typeof e != "object" || Object.getPrototypeOf(e) !== Object.prototype && Object.getPrototypeOf(e) !== null)
1108
- throw new Error("图片参数无效");
1109
- const r = Reflect.ownKeys(e);
1110
- if (r.length !== t.length || r.some((i) => !t.includes(i)))
1111
- throw new Error("图片参数字段无效");
1112
- }
1113
- function Ut(e) {
1114
- if (!Number.isSafeInteger(e) || e < 0 || e > 4096)
1115
- throw new Error("透明边距须为0至4096的整数");
1116
- return e;
1117
- }
1118
- function Z(e, t) {
1119
- if (!Number.isSafeInteger(e) || !Number.isSafeInteger(t) || e < 1 || t < 1 || e * t > 24e6)
1120
- throw new Error("图片像素尺寸无效或超过24MP");
1121
- }
1122
- function _e(e, t, r) {
1123
- if (Z(t, r), !(e instanceof Uint8ClampedArray) || e.length !== t * r * 4)
1124
- throw new Error("图片RGBA数据无效");
1125
- }
1126
- function At(e, t, r) {
1127
- _e(e, t, r);
1128
- let i = t, n = r, o = -1, s = -1;
1129
- for (let a = 0; a < r; a++)
1130
- for (let c = 0; c < t; c++)
1131
- e[(a * t + c) * 4 + 3] !== 0 && (i = Math.min(i, c), n = Math.min(n, a), o = Math.max(o, c), s = Math.max(s, a));
1132
- return o < 0 ? { kind: "skip", reason: "fully-transparent" } : i === 0 && n === 0 && o === t - 1 && s === r - 1 ? { kind: "skip", reason: "no-transparent-border" } : {
1133
- kind: "crop",
1134
- rect: { x: i, y: n, width: o - i + 1, height: s - n + 1 }
1135
- };
1136
- }
1137
- function _t(e, t, r, i = 0) {
1138
- if (Z(t, r), Ut(i), e.kind === "skip" && e.reason === "fully-transparent") return e;
1139
- const n = e.kind === "crop" ? e.rect : { x: 0, y: 0, width: t, height: r }, o = n.width + 2 * i, s = n.height + 2 * i;
1140
- return Z(o, s), { kind: "render", sourceRect: n, width: o, height: s, padding: i };
1141
- }
1142
- function Nt(e, t, r, i) {
1143
- if (_e(e, t, r), Pt(i, ["x", "y", "width", "height"]), ![i.x, i.y, i.width, i.height].every(Number.isSafeInteger) || i.x < 0 || i.y < 0 || i.width < 1 || i.height < 1 || i.x + i.width > t || i.y + i.height > r)
1144
- throw new Error("裁切框无效或超出图片边界");
1145
- const n = new Uint8ClampedArray(i.width * i.height * 4), o = i.width * 4;
1146
- for (let s = 0; s < i.height; s++) {
1147
- const a = ((i.y + s) * t + i.x) * 4;
1148
- n.set(e.subarray(a, a + o), s * o);
1149
- }
1150
- return n;
1151
- }
1152
- function Tt(e, t = !1, r = "transparent", i = 0) {
1153
- if (r !== "transparent" && !/^#[0-9a-f]{6}$/i.test(r))
1154
- throw new Error("输出底色无效");
1155
- let n = e, o = 0;
1156
- if (t) {
1157
- const s = e.getContext("2d", { willReadFrequently: !0 });
1158
- if (!s) throw new Error("无法读取抠图alpha");
1159
- const a = s.getImageData(0, 0, e.width, e.height), c = At(a.data, e.width, e.height);
1160
- if (_t(c, e.width, e.height, i).kind === "render" && (o = i), c.kind === "crop") {
1161
- const d = c.rect;
1162
- n = new OffscreenCanvas(d.width, d.height);
1163
- const u = n.getContext("2d");
1164
- if (!u) throw new Error("无法生成裁边结果");
1165
- u.putImageData(
1166
- new ImageData(
1167
- new Uint8ClampedArray(Nt(a.data, e.width, e.height, d)),
1168
- d.width,
1169
- d.height
1170
- ),
1171
- 0,
1172
- 0
1173
- );
1174
- }
1175
- }
1176
- if (r !== "transparent") {
1177
- const s = n.getContext("2d");
1178
- if (!s) throw new Error("无法合成输出底色");
1179
- s.globalCompositeOperation = "destination-over", s.fillStyle = r, s.fillRect(0, 0, n.width, n.height), s.globalCompositeOperation = "source-over";
1180
- }
1181
- if (o > 0) {
1182
- const s = new OffscreenCanvas(n.width + 2 * o, n.height + 2 * o), a = s.getContext("2d");
1183
- if (!a) throw new Error("无法生成透明边距");
1184
- a.drawImage(n, o, o), n = s;
1185
- }
1186
- return n;
1187
- }
1188
- async function Lt(e, t, r, i, n = !1, o = 0) {
1189
- if (r !== "transparent" && !/^#[0-9a-f]{6}$/i.test(r))
1190
- throw new Error("输出底色无效");
1191
- const s = await Bt(e, t);
1192
- if (s.blob.type !== "image/png" || !s.blob.size) throw new Error("抠图原始输出须为PNG");
1193
- if (s.blob.size > 25 * 1024 * 1024) throw new Error("抠图原始输出超过25 MiB");
1194
- const a = await createImageBitmap(s.blob);
1195
- let c;
1196
- try {
1197
- if (c = await createImageBitmap(e), a.width !== c.width || a.height !== c.height || a.width * a.height > 24e6)
1198
- throw new Error("输出尺寸与原图不一致。");
1199
- let l = s.blob, d = a.width, u = a.height;
1200
- if (n || r !== "transparent") {
1201
- const f = new OffscreenCanvas(a.width, a.height), h = f.getContext("2d", { willReadFrequently: !0 });
1202
- if (!h) throw new Error("无法合成输出底色");
1203
- h.drawImage(a, 0, 0);
1204
- const g = Tt(f, n, r, o);
1205
- d = g.width, u = g.height, l = await g.convertToBlob({ type: "image/png" });
1206
- }
1207
- if (l.size > 25 * 1024 * 1024) throw new Error("抠图输出超过25 MiB");
1208
- return {
1209
- blob: l,
1210
- width: d,
1211
- height: u,
1212
- latency_ms: s.latency_ms,
1213
- cold_start: i,
1214
- backend: s.provider,
1215
- engine_version: `bg0-full-quality-worker/${X.revision}`
1216
- };
1217
- } finally {
1218
- a.close(), c?.close();
1219
- }
1220
- }
1221
- const U = self;
1222
- let Y = !1, ye = !1;
1223
- U.onmessage = async ({
1224
- data: e
1225
- }) => {
1226
- const { id: t, blob: r, background: i, trimTransparent: n, trimPadding: o } = e;
1227
- if (Y) {
1228
- U.postMessage({ id: t, type: "error", error: "标准模式上一项尚未结束" });
1229
- return;
1230
- }
1231
- Y = !0;
1232
- try {
1233
- if (!e.resources)
1234
- throw Error("MISSING_RESOURCE: standard cutout requires explicit resources");
1235
- await pt(
1236
- e.resources,
1237
- (a, c, l) => U.postMessage({
1238
- id: t,
1239
- type: "progress",
1240
- progress: { label: a, fraction: l ? c / l : null }
1241
- })
1242
- );
1243
- const s = await Lt(
1244
- r,
1245
- (a) => U.postMessage({ id: t, type: "progress", progress: a }),
1246
- i,
1247
- !ye,
1248
- n,
1249
- o
1250
- );
1251
- ye = !0, U.postMessage({ id: t, type: "result", result: s });
1252
- } catch (s) {
1253
- U.postMessage({
1254
- id: t,
1255
- type: "error",
1256
- error: s instanceof Error ? s.message : String(s)
1257
- });
1258
- } finally {
1259
- Y = !1;
1260
- }
1261
- };