-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.mjs.fix
698 lines (683 loc) · 20.5 KB
/
index.mjs.fix
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
// src/index.ts
import lodash from 'lodash';
import ndarray5 from "ndarray";
// src/utils.ts
import ndarray2 from "ndarray";
// src/codecs.ts
import ndarray from "ndarray";
const { memoize } = lodash;
async function imageDecode(blob) {
const mime = MimeType.fromString(blob.type);
switch (mime.type) {
case "image/x-alpha8": {
const width = parseInt(mime.params["width"]);
const height = parseInt(mime.params["height"]);
return ndarray(new Uint8Array(await blob.arrayBuffer()), [
height,
width,
1
]);
}
case "image/x-rgba8": {
const width = parseInt(mime.params["width"]);
const height = parseInt(mime.params["height"]);
return ndarray(new Uint8Array(await blob.arrayBuffer()), [
height,
width,
4
]);
}
case "application/octet-stream":
case `image/png`:
case `image/jpeg`:
case `image/webp`: {
const imageBitmap = await createImageBitmap(blob);
const imageData = imageBitmapToImageData(imageBitmap);
return ndarray(new Uint8Array(imageData.data), [
imageData.height,
imageData.width,
4
]);
}
default:
throw new Error(
`Invalid format: ${mime.type} with params: ${mime.params}`
);
}
}
async function imageEncode(imageTensor, quality = 0.8, format = "image/png") {
const [height, width, channels] = imageTensor.shape;
switch (format) {
case "image/x-alpha8":
case "image/x-rgba8": {
const mime = MimeType.create(format, {
width: width.toString(),
height: height.toString()
});
return new Blob([imageTensor.data], { type: mime.toString() });
}
case `image/png`:
case `image/jpeg`:
case `image/webp`: {
const imageData = new ImageData(
new Uint8ClampedArray(imageTensor.data),
width,
height
);
var canvas = createCanvas(imageData.width, imageData.height);
var ctx = canvas.getContext("2d");
ctx.putImageData(imageData, 0, 0);
return canvas.convertToBlob({ quality, type: format });
}
default:
throw new Error(`Invalid format: ${format}`);
}
}
var MimeType = class _MimeType {
type = "application/octet-stream";
params = {};
constructor(type, params) {
this.type = type;
this.params = params;
}
toString() {
const paramsStr = [];
for (const key in this.params) {
const value = this.params[key];
paramsStr.push(`${key}=${value}`);
}
return [this.type, ...paramsStr].join(";");
}
static create(type, params) {
return new _MimeType(type, params);
}
isIdentical(other) {
return this.type === other.type && this.params === other.params;
}
isEqual(other) {
return this.type === other.type;
}
static fromString(mimeType) {
const [type, ...paramsArr] = mimeType.split(";");
const params = {};
for (const param of paramsArr) {
const [key, value] = param.split("=");
params[key.trim()] = value.trim();
}
return new _MimeType(type, params);
}
};
// src/url.ts
function isAbsoluteURI(url) {
const regExp = new RegExp("^(?:[a-z+]+:)?//", "i");
return regExp.test(url);
}
function ensureAbsoluteURI(url, baseUrl) {
if (isAbsoluteURI(url)) {
return url;
} else {
return new URL(url, baseUrl).href;
}
}
// src/utils.ts
function imageBitmapToImageData(imageBitmap) {
var canvas = createCanvas(imageBitmap.width, imageBitmap.height);
var ctx = canvas.getContext("2d");
ctx.drawImage(imageBitmap, 0, 0);
return ctx.getImageData(0, 0, canvas.width, canvas.height);
}
function tensorResizeBilinear(imageTensor, newWidth, newHeight) {
const [srcHeight, srcWidth, srcChannels] = imageTensor.shape;
const scaleX = srcWidth / newWidth;
const scaleY = srcHeight / newHeight;
const resizedImageData = ndarray2(
new Uint8Array(srcChannels * newWidth * newHeight),
[newHeight, newWidth, srcChannels]
);
for (let y = 0; y < newHeight; y++) {
for (let x = 0; x < newWidth; x++) {
const srcX = x * scaleX;
const srcY = y * scaleY;
const x1 = Math.max(Math.floor(srcX), 0);
const x2 = Math.min(Math.ceil(srcX), srcWidth - 1);
const y1 = Math.max(Math.floor(srcY), 0);
const y2 = Math.min(Math.ceil(srcY), srcHeight - 1);
const dx = srcX - x1;
const dy = srcY - y1;
for (let c = 0; c < srcChannels; c++) {
const p1 = imageTensor.get(y1, x1, c);
const p2 = imageTensor.get(y1, x2, c);
const p3 = imageTensor.get(y2, x1, c);
const p4 = imageTensor.get(y2, x2, c);
const interpolatedValue = (1 - dx) * (1 - dy) * p1 + dx * (1 - dy) * p2 + (1 - dx) * dy * p3 + dx * dy * p4;
resizedImageData.set(y, x, c, Math.round(interpolatedValue));
}
}
}
return resizedImageData;
}
function tensorHWCtoBCHW(imageTensor, mean = [128, 128, 128], std = [256, 256, 256]) {
var imageBufferData = imageTensor.data;
const [srcHeight, srcWidth, srcChannels] = imageTensor.shape;
const stride = srcHeight * srcWidth;
const float32Data = new Float32Array(3 * stride);
for (let i = 0, j = 0; i < imageBufferData.length; i += 4, j += 1) {
float32Data[j] = (imageBufferData[i] - mean[0]) / std[0];
float32Data[j + stride] = (imageBufferData[i + 1] - mean[1]) / std[1];
float32Data[j + stride + stride] = (imageBufferData[i + 2] - mean[2]) / std[2];
}
return ndarray2(float32Data, [1, 3, srcHeight, srcWidth]);
}
async function imageSourceToImageData(image, config) {
if (typeof image === "string") {
image = ensureAbsoluteURI(image, config.publicPath);
image = new URL(image);
}
if (image instanceof URL) {
const response = await fetch(image, {});
image = await response.blob();
}
if (image instanceof ArrayBuffer || ArrayBuffer.isView(image)) {
image = new Blob([image]);
}
if (image instanceof Blob) {
image = await imageDecode(image);
}
return image;
}
function convertFloat32ToUint8(float32Array) {
const uint8Array = new Uint8Array(float32Array.data.length);
for (let i = 0; i < float32Array.data.length; i++) {
uint8Array[i] = float32Array.data[i] * 255;
}
return ndarray2(uint8Array, float32Array.shape);
}
function createCanvas(width, height) {
let canvas = void 0;
if (typeof OffscreenCanvas !== "undefined") {
canvas = new OffscreenCanvas(width, height);
} else {
canvas = document.createElement("canvas");
}
if (!canvas) {
throw new Error(
`Canvas nor OffscreenCanvas are available in the current context.`
);
}
return canvas;
}
// src/onnx.ts
import ndarray3 from "ndarray";
import * as ort from "onnxruntime-web";
// src/resource.ts
async function preload(config) {
const resourceUrl = new URL("resources.json", config.publicPath);
const resourceResponse = await fetch(resourceUrl);
if (!resourceResponse.ok) {
throw new Error(
`Resource metadata not found. Ensure that the config.publicPath is configured correctl: ${config.publicPath}`
);
}
const resourceMap = await resourceResponse.json();
const keys = Object.keys(resourceMap);
await Promise.all(
keys.map(async (key) => {
return loadAsBlob(key, config);
})
);
}
async function loadAsUrl(url, config) {
return URL.createObjectURL(await loadAsBlob(url, config));
}
async function loadAsBlob(key, config) {
const resourceUrl = new URL("resources.json", config.publicPath);
const resourceResponse = await fetch(resourceUrl);
if (!resourceResponse.ok) {
throw new Error(
`Resource metadata not found. Ensure that the config.publicPath is configured correctly.`
);
}
const resourceMap = await resourceResponse.json();
const entry = resourceMap[key];
if (!entry) {
throw new Error(
`Resource ${key} not found. Ensure that the config.publicPath is configured correctly.`
);
}
const chunks = entry.chunks;
let downloadedSize = 0;
const responses = chunks.map(async (chunk) => {
const chunkSize = chunk.offsets[1] - chunk.offsets[0];
const url = config.publicPath ? new URL(chunk.hash, config.publicPath).toString() : chunk.hash;
const response = await fetch(url, config.fetchArgs);
const blob = await response.blob();
if (chunkSize !== blob.size) {
throw new Error(
`Failed to fetch ${key} with size ${chunkSize} but got ${blob.size}`
);
}
if (config.progress) {
downloadedSize += chunkSize;
config.progress(`fetch:${key}`, downloadedSize, entry.size);
}
return blob;
});
const allChunkData = await Promise.all(responses);
const data = new Blob(allChunkData, { type: entry.mime });
if (data.size !== entry.size) {
throw new Error(
`Failed to fetch ${key} with size ${entry.size} but got ${data.size}`
);
}
return data;
}
// src/feature-detect.js
var simd = async () => WebAssembly.validate(
new Uint8Array([
0,
97,
115,
109,
1,
0,
0,
0,
1,
5,
1,
96,
0,
1,
123,
3,
2,
1,
0,
10,
10,
1,
8,
0,
65,
0,
253,
15,
253,
98,
11
])
);
var threads = () => (async (e) => {
try {
return "undefined" != typeof MessageChannel && new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)), WebAssembly.validate(e);
} catch (e2) {
return false;
}
})(
new Uint8Array([
0,
97,
115,
109,
1,
0,
0,
0,
1,
4,
1,
96,
0,
0,
3,
2,
1,
0,
5,
4,
1,
3,
1,
1,
10,
11,
1,
9,
0,
65,
0,
254,
16,
2,
0,
26,
11
])
);
// src/onnx.ts
async function createOnnxSession(model, config) {
const capabilities = {
simd: await simd(),
threads: await threads(),
numThreads: navigator.hardwareConcurrency ?? 4,
// @ts-ignore
webgpu: navigator.gpu !== void 0
};
if (config.debug) {
console.debug("Capabilities:", capabilities);
ort.env.debug = true;
ort.env.logLevel = "verbose";
}
ort.env.wasm.numThreads = capabilities.numThreads;
ort.env.wasm.simd = capabilities.simd;
ort.env.wasm.proxy = config.proxyToWorker;
ort.env.wasm.wasmPaths = {
"ort-wasm-simd-threaded.wasm": capabilities.simd && capabilities.threads ? await loadAsUrl(
"/onnxruntime-web/ort-wasm-simd-threaded.wasm",
config
) : void 0,
"ort-wasm-simd.wasm": capabilities.simd && !capabilities.threads ? await loadAsUrl("/onnxruntime-web/ort-wasm-simd.wasm", config) : void 0,
"ort-wasm-threaded.wasm": !capabilities.simd && capabilities.threads ? await loadAsUrl("/onnxruntime-web/ort-wasm-threaded.wasm", config) : void 0,
"ort-wasm.wasm": !capabilities.simd && !capabilities.threads ? await loadAsUrl("/onnxruntime-web/ort-wasm.wasm", config) : void 0
};
if (config.debug) {
console.debug("ort.env.wasm:", ort.env.wasm);
}
const ort_config = {
executionProviders: ["wasm"],
graphOptimizationLevel: "all",
executionMode: "parallel",
enableCpuMemArena: true
};
const session = await ort.InferenceSession.create(model, ort_config).catch(
(e) => {
throw new Error(
`Failed to create session: ${e}. Please check if the publicPath is set correctly.`
);
}
);
return session;
}
async function runOnnxSession(session, inputs, outputs) {
const feeds = {};
for (const [key, tensor] of inputs) {
feeds[key] = new ort.Tensor(
"float32",
new Float32Array(tensor.data),
tensor.shape
);
}
const outputData = await session.run(feeds, {});
const outputKVPairs = [];
for (const key of outputs) {
const output = outputData[key];
const shape = output.dims;
const data = output.data;
const tensor = ndarray3(data, shape);
outputKVPairs.push(tensor);
}
return outputKVPairs;
}
// src/schema.ts
import { z } from "zod";
// package.json
var package_default = {
name: "@imgly/background-removal",
version: "1.4.4",
description: "Background Removal in the Browser",
keywords: [
"background-removal",
"client-side",
"data-privacy",
"image-segmentation",
"image-matting",
"onnx"
],
repository: {
type: "git",
url: "git+https://github.com/imgly/background-removal-js.git"
},
license: "SEE LICENSE IN LICENSE.md",
author: {
name: "IMG.LY GmbH",
email: "support@img.ly",
url: "https://img.ly"
},
bugs: {
email: "support@img.ly"
},
source: "./src/index.ts",
main: "./dist/index.cjs",
module: "./dist/index.mjs",
types: "./dist/src/index.d.ts",
exports: {
".": {
require: "./dist/index.cjs",
import: "./dist/index.mjs",
types: "./dist/src/index.d.ts"
}
},
homepage: "https://img.ly/showcases/cesdk/web/background-removal",
files: [
"LICENSE.md",
"README.md",
"CHANGELOG.md",
"dist/",
"bin/"
],
scripts: {
start: "npm run watch",
clean: "npx rimraf dist",
test: "true",
resources: "node ../../scripts/package-resources.mjs",
"changelog:create": "node ../../scripts/changelog/changelog-create.mjs",
"changelog:generate": "node ../../scripts/changelog/changelog-generate.mjs",
build: "npm run clean && npm run types && npm run resources && npm run changelog:generate && node scripts/build.mjs",
types: " npx tsc --declaration --emitDeclarationOnly --declarationDir dist --declarationMap",
watch: "npm run clean && npm run resources && npm run changelog:generate && node scripts/watch.mjs",
"publish:latest": "npm run build && npm publish --tag latest --access public",
"publish:next": "npm run build && npm publish --tag next --access public",
"package:pack": "npm run build && npm pack . --pack-destination ../../releases",
lint: "npx prettier --write ."
},
dependencies: {
"@types/lodash": "~4.14.0",
"@types/node": "~20.3.0",
"@types/ndarray": "~1.0.14",
lodash: "~4.17.0",
ndarray: "~1.0.0",
"onnxruntime-web": "~1.17.0",
zod: "~3.21.0"
},
devDependencies: {
assert: "~2.0.0",
esbuild: "~0.18.0",
glob: "~10.3.0",
"npm-dts": "~1.3.0",
process: "~0.11.0",
"ts-loader": "~9.4.0",
tslib: "~2.5.0",
typescript: "~5.1.0",
util: "~0.12.0",
webpack: "~5.85.0",
"webpack-cli": "~5.1.0"
}
};
// src/schema.ts
var ConfigSchema = z.object({
publicPath: z.string().optional().describe("The public path to the wasm files and the onnx model.").default(
"https://staticimgly.com/@imgly/background-removal-data/${PACKAGE_VERSION}/dist/"
).transform((val) => {
return val.replace("${PACKAGE_NAME}", package_default.name).replace("${PACKAGE_VERSION}", package_default.version);
}),
debug: z.boolean().default(false).describe("Whether to enable debug logging."),
proxyToWorker: z.boolean().default(true).describe("Whether to proxy inference to a web worker."),
fetchArgs: z.any().default({}).describe("Arguments to pass to fetch when loading the model."),
progress: z.function().args(z.string(), z.number(), z.number()).returns(z.void()).describe("Progress callback.").optional(),
model: z.enum(["small", "medium"]).default("medium"),
output: z.object({
format: z.enum([
"image/png",
"image/jpeg",
"image/webp",
"image/x-rgba8",
"image/x-alpha8"
]).default("image/png"),
quality: z.number().default(0.8)
}).default({})
}).default({});
function validateConfig(configuration) {
const config = ConfigSchema.parse(configuration ?? {});
if (config.debug)
console.log("Config:", config);
if (config.debug && !config.progress) {
config.progress = config.progress ?? ((key, current, total) => {
console.debug(`Downloading ${key}: ${current} of ${total}`);
});
if (!crossOriginIsolated) {
console.debug(
"Cross-Origin-Isolated is not enabled. Performance will be degraded. Please see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer."
);
}
}
return config;
}
// src/inference.ts
import ndarray4 from "ndarray";
async function initInference(config) {
config = validateConfig(config);
if (config.debug)
console.debug("Loading model...");
const model = config.model;
const blob = await loadAsBlob(`/models/${model}`, config);
const arrayBuffer = await blob.arrayBuffer();
const session = await createOnnxSession(arrayBuffer, config);
return { config, session };
}
async function runInference(imageTensor, config, session) {
if (config.progress)
config.progress("compute:inference", 0, 1);
const resolution = 1024;
const [srcHeight, srcWidth, srcChannels] = imageTensor.shape;
let tensorImage = tensorResizeBilinear(imageTensor, resolution, resolution);
const inputTensor = tensorHWCtoBCHW(tensorImage);
const predictionsDict = await runOnnxSession(
session,
[["input", inputTensor]],
["output"]
);
let alphamask = ndarray4(predictionsDict[0].data, [resolution, resolution, 1]);
let alphamaskU8 = convertFloat32ToUint8(alphamask);
alphamaskU8 = tensorResizeBilinear(alphamaskU8, srcWidth, srcHeight);
if (config.progress)
config.progress("compute:inference", 1, 1);
return alphamaskU8;
}
// src/index.ts
var src_default = removeBackground;
var init = memoize(initInference, (config) => JSON.stringify(config));
async function preload2(configuration) {
const config = validateConfig(configuration);
await preload(config);
return;
}
async function removeBackground(image, configuration) {
const { config, session } = await init(configuration);
const imageTensor = await imageSourceToImageData(image, config);
const [width, height, channels] = imageTensor.shape;
const alphamask = await runInference(imageTensor, config, session);
const stride = width * height;
const outImageTensor = imageTensor;
for (let i = 0; i < stride; i += 1) {
outImageTensor.data[4 * i + 3] = alphamask.data[i];
}
const outImage = await imageEncode(
outImageTensor,
config.output.quality,
config.output.format
);
return outImage;
}
async function removeForeground(image, configuration) {
const { config, session } = await init(configuration);
const imageTensor = await imageSourceToImageData(image, config);
const [width, height, channels] = imageTensor.shape;
const alphamask = await runInference(imageTensor, config, session);
const stride = width * height;
const outImageTensor = imageTensor;
for (let i = 0; i < stride; i += 1) {
outImageTensor.data[4 * i + 3] = 255 - alphamask.data[i];
}
const outImage = await imageEncode(
outImageTensor,
config.output.quality,
config.output.format
);
return outImage;
}
async function segmentForeground(image, configuration) {
const { config, session } = await init(configuration);
const imageTensor = await imageSourceToImageData(image, config);
const [height, width, channels] = imageTensor.shape;
const alphamask = await runInference(imageTensor, config, session);
switch (config.output.format) {
case "image/x-alpha8": {
const outImage = await imageEncode(
alphamask,
config.output.quality,
config.output.format
);
return outImage;
}
default: {
const stride = width * height;
const outImageTensor = ndarray5(new Uint8Array(channels * stride), [
height,
width,
channels
]);
for (let i = 0; i < stride; i += 1) {
const index = 4 * i + 3;
outImageTensor.data[index] = alphamask.data[i];
outImageTensor.data[index + 1] = alphamask.data[i];
outImageTensor.data[index + 2] = alphamask.data[i];
outImageTensor.data[index + 3] = 255;
}
const outImage = await imageEncode(
outImageTensor,
config.output.quality,
config.output.format
);
return outImage;
}
}
}
async function applySegmentationMask(image, mask, config) {
config = validateConfig(config);
const imageTensor = await imageSourceToImageData(image, config);
const [imageHeight, imageWidth, imageChannels] = imageTensor.shape;
const maskTensor = await imageSourceToImageData(mask, config);
const [maskHeight, maskWidth, maskChannels] = maskTensor.shape;
const alphaMask = maskHeight !== imageHeight || maskWidth !== imageWidth ? tensorResizeBilinear(maskTensor, imageWidth, imageHeight) : maskTensor;
const stride = imageWidth * imageHeight;
for (let i = 0; i < stride; i += 1) {
const idxImage = imageChannels * i;
const idxMask = maskChannels * i;
imageTensor.data[idxImage + 3] = alphaMask.data[idxMask];
}
const outImage = await imageEncode(
imageTensor,
config.output.quality,
config.output.format
);
return outImage;
}
export {
applySegmentationMask,
src_default as default,
preload2 as preload,
removeBackground,
removeForeground,
segmentForeground
};
//# sourceMappingURL=index.mjs.map