@richardmcquiston01/ai-tools 0.0.0-stage → 0.2.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Richard McQuiston
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,79 @@
1
- # Temporary Holding Version
1
+ # @richardmcquiston01/ai-tools
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ In-browser AI image tools for laser, CNC and other maker-machine workflows: background removal, upscaling and subject-aware auto-crop. Everything runs client-side — no API keys and no server.
4
+
5
+ Part of [maker-image-tools](https://github.com/RichardMcQuiston01/maker-image-tools). Built on [`@richardmcquiston01/core-image`](https://www.npmjs.com/package/@richardmcquiston01/core-image).
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm i @richardmcquiston01/ai-tools
11
+ ```
12
+
13
+ Requires an environment with `ImageData` (browser, or a polyfill in Node). ESM only.
14
+
15
+ ## Usage
16
+
17
+ ```ts
18
+ import {
19
+ computeCropRegion,
20
+ loadBackgroundRemovalModel,
21
+ loadUpscaleModel,
22
+ } from "@richardmcquiston01/ai-tools";
23
+
24
+ // Background removal + auto-crop (U²-Net-P via onnxruntime-web).
25
+ // Pass a URL, ArrayBuffer or Uint8Array of the bundled `models/u2netp.onnx`.
26
+ const bg = await loadBackgroundRemovalModel("/models/u2netp.onnx", {
27
+ wasmPaths: "/ort/", // where ort-wasm*.wasm is served from (bundlers like Vite need this)
28
+ });
29
+ const cutout: ImageData = await bg.removeBackground(image);
30
+
31
+ const mask = await bg.computeSaliencyMask(image);
32
+ const region = computeCropRegion(mask, { threshold: 0.5, margin: 8 });
33
+
34
+ // Upscaling (ESRGAN-slim via TensorFlow.js).
35
+ const upscaler = await loadUpscaleModel(4);
36
+ const bigger: ImageData = await upscaler.upscale(image);
37
+ ```
38
+
39
+ ## As an `ImageGenerator` (optional)
40
+
41
+ `@richardmcquiston01/ai-tools/provider` wraps background removal as an `ImageGenerator` from [`@richardmcquiston01/ai-providers`](https://www.npmjs.com/package/@richardmcquiston01/ai-providers), so an app can offer it next to other providers (a local ComfyUI, a hosted API) and swap between them through one interface. `ai-providers` is an optional peer dependency: install it only if you use this entry point.
42
+
43
+ ```ts
44
+ import {
45
+ browserImageCodec,
46
+ lazyBackgroundRemovalModel,
47
+ OnnxBackgroundRemover,
48
+ REMOVE_BACKGROUND_MODE,
49
+ } from "@richardmcquiston01/ai-tools/provider";
50
+
51
+ const remover = new OnnxBackgroundRemover({
52
+ // ONNX Runtime is imported on first use, so listing the provider costs nothing.
53
+ loadModel: lazyBackgroundRemovalModel("/models/u2netp.onnx"),
54
+ // Providers exchange encoded images; the codec turns them into pixels and back.
55
+ codec: browserImageCodec,
56
+ });
57
+
58
+ const result = await remover.generateImage({
59
+ instructions: "",
60
+ prompt: "",
61
+ images: [{ mimeType: "image/png", data: pngBytes }],
62
+ mode: REMOVE_BACKGROUND_MODE,
63
+ });
64
+ if (result.ok)
65
+ use(result.value.image); // a PNG with a transparent background
66
+ else console.error(result.error); // names the provider and what failed
67
+ ```
68
+
69
+ `browserImageCodec` needs the DOM (canvas); pass your own `ImageCodec` elsewhere. The model is loaded once and shared between runs, and a failed load is retried on the next call.
70
+
71
+ ## Model files and offline use
72
+
73
+ - **Background removal:** the package ships `models/u2netp.onnx` (about 4.5 MB). Serve or import it yourself and pass it to `loadBackgroundRemovalModel`; nothing is fetched on your behalf.
74
+ - **Upscaling:** by default the model definitions load their weights from a public CDN mirror of `@upscalerjs/esrgan-slim`. For a self-contained deployment, serve that package's `models/<scale>x/` directory and pass the resolved `model.json` URL as `modelUrl`.
75
+ - **Size:** TensorFlow.js and ONNX Runtime are large. Load this package lazily (`await import(...)`) rather than in your main bundle.
76
+
77
+ ## Licenses
78
+
79
+ The code is MIT (see `LICENSE`). The bundled `models/u2netp.onnx` is the Apache-2.0 U²-Net-P checkpoint; its attribution is in `models/NOTICE.md` and the licence text is in `models/LICENSE-APACHE-2.0.txt`.
@@ -0,0 +1,26 @@
1
+ import type { SaliencyMask } from "./background-removal.js";
2
+ export interface CropRegion {
3
+ x: number;
4
+ y: number;
5
+ width: number;
6
+ height: number;
7
+ }
8
+ export interface ComputeCropRegionOptions {
9
+ /**
10
+ * Foreground-probability threshold in [0, 1] above which a pixel counts as
11
+ * "subject". Defaults to 0.5.
12
+ */
13
+ threshold?: number;
14
+ /**
15
+ * Extra padding added on each side of the tight subject bounding box, in
16
+ * pixels. Defaults to 0.
17
+ */
18
+ margin?: number;
19
+ }
20
+ /**
21
+ * Computes the tight (plus optional margin) bounding box around the
22
+ * foreground of a saliency mask, clamped to the mask's own bounds. Falls
23
+ * back to the full mask extent if no pixel clears the threshold.
24
+ */
25
+ export declare function computeCropRegion(mask: SaliencyMask, options?: ComputeCropRegionOptions): CropRegion;
26
+ //# sourceMappingURL=auto-crop.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auto-crop.d.ts","sourceRoot":"","sources":["../src/auto-crop.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAE5D,MAAM,WAAW,UAAU;IACzB,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,wBAAwB;IACvC;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,YAAY,EAClB,OAAO,CAAC,EAAE,wBAAwB,GACjC,UAAU,CAqCZ"}
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Computes the tight (plus optional margin) bounding box around the
3
+ * foreground of a saliency mask, clamped to the mask's own bounds. Falls
4
+ * back to the full mask extent if no pixel clears the threshold.
5
+ */
6
+ export function computeCropRegion(mask, options) {
7
+ const threshold = options?.threshold ?? 0.5;
8
+ const margin = options?.margin ?? 0;
9
+ const { width, height, values } = mask;
10
+ let minX = width;
11
+ let minY = height;
12
+ let maxX = -1;
13
+ let maxY = -1;
14
+ for (let y = 0; y < height; y++) {
15
+ for (let x = 0; x < width; x++) {
16
+ const value = values[y * width + x] ?? 0;
17
+ if (value >= threshold) {
18
+ if (x < minX)
19
+ minX = x;
20
+ if (x > maxX)
21
+ maxX = x;
22
+ if (y < minY)
23
+ minY = y;
24
+ if (y > maxY)
25
+ maxY = y;
26
+ }
27
+ }
28
+ }
29
+ if (maxX < minX || maxY < minY) {
30
+ return { x: 0, y: 0, width, height };
31
+ }
32
+ const x = Math.max(0, minX - margin);
33
+ const y = Math.max(0, minY - margin);
34
+ const clampedMaxX = Math.min(width - 1, maxX + margin);
35
+ const clampedMaxY = Math.min(height - 1, maxY + margin);
36
+ return {
37
+ x,
38
+ y,
39
+ width: clampedMaxX - x + 1,
40
+ height: clampedMaxY - y + 1,
41
+ };
42
+ }
43
+ //# sourceMappingURL=auto-crop.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auto-crop.js","sourceRoot":"","sources":["../src/auto-crop.ts"],"names":[],"mappings":"AAsBA;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAC/B,IAAkB,EAClB,OAAkC;IAElC,MAAM,SAAS,GAAG,OAAO,EAAE,SAAS,IAAI,GAAG,CAAC;IAC5C,MAAM,MAAM,GAAG,OAAO,EAAE,MAAM,IAAI,CAAC,CAAC;IACpC,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IAEvC,IAAI,IAAI,GAAG,KAAK,CAAC;IACjB,IAAI,IAAI,GAAG,MAAM,CAAC;IAClB,IAAI,IAAI,GAAG,CAAC,CAAC,CAAC;IACd,IAAI,IAAI,GAAG,CAAC,CAAC,CAAC;IAEd,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QAChC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC;YAC/B,MAAM,KAAK,GAAG,MAAM,CAAC,CAAC,GAAG,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;YACzC,IAAI,KAAK,IAAI,SAAS,EAAE,CAAC;gBACvB,IAAI,CAAC,GAAG,IAAI;oBAAE,IAAI,GAAG,CAAC,CAAC;gBACvB,IAAI,CAAC,GAAG,IAAI;oBAAE,IAAI,GAAG,CAAC,CAAC;gBACvB,IAAI,CAAC,GAAG,IAAI;oBAAE,IAAI,GAAG,CAAC,CAAC;gBACvB,IAAI,CAAC,GAAG,IAAI;oBAAE,IAAI,GAAG,CAAC,CAAC;YACzB,CAAC;QACH,CAAC;IACH,CAAC;IAED,IAAI,IAAI,GAAG,IAAI,IAAI,IAAI,GAAG,IAAI,EAAE,CAAC;QAC/B,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC;IACvC,CAAC;IAED,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,CAAC;IACrC,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,CAAC;IACrC,MAAM,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,GAAG,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,CAAC;IACvD,MAAM,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,CAAC;IAExD,OAAO;QACL,CAAC;QACD,CAAC;QACD,KAAK,EAAE,WAAW,GAAG,CAAC,GAAG,CAAC;QAC1B,MAAM,EAAE,WAAW,GAAG,CAAC,GAAG,CAAC;KAC5B,CAAC;AACJ,CAAC"}
@@ -0,0 +1,33 @@
1
+ export interface LoadBackgroundRemovalModelOptions {
2
+ /**
3
+ * Base URL onnxruntime-web should use to locate its own WASM runtime files
4
+ * (ort-wasm*.wasm), passed through to `ort.env.wasm.wasmPaths`. Bundlers
5
+ * that don't automatically resolve onnxruntime-web's WASM assets (e.g.
6
+ * Vite, unless configured) need this pointed at wherever those files were
7
+ * copied. If omitted, onnxruntime-web's own default resolution is used.
8
+ */
9
+ wasmPaths?: string;
10
+ }
11
+ export interface SaliencyMask {
12
+ /** Row-major foreground-probability values in [0, 1], one per pixel of the source image. */
13
+ values: Float32Array;
14
+ width: number;
15
+ height: number;
16
+ }
17
+ export interface BackgroundRemovalModel {
18
+ /**
19
+ * Removes the background from `image`, returning a same-size ImageData
20
+ * whose background pixels are made transparent (alpha scaled by the
21
+ * predicted foreground mask).
22
+ */
23
+ removeBackground(image: ImageData): Promise<ImageData>;
24
+ /**
25
+ * Runs the same underlying saliency model as `removeBackground` but
26
+ * returns the raw upsampled mask instead of compositing it into an image —
27
+ * useful for anything that just needs to know *where* the subject is (e.g.
28
+ * auto-crop) without paying for a full alpha-composite pass.
29
+ */
30
+ computeSaliencyMask(image: ImageData): Promise<SaliencyMask>;
31
+ }
32
+ export declare function loadBackgroundRemovalModel(model: string | ArrayBuffer | Uint8Array, options?: LoadBackgroundRemovalModelOptions): Promise<BackgroundRemovalModel>;
33
+ //# sourceMappingURL=background-removal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"background-removal.d.ts","sourceRoot":"","sources":["../src/background-removal.ts"],"names":[],"mappings":"AAaA,MAAM,WAAW,iCAAiC;IAChD;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,YAAY;IAC3B,4FAA4F;IAC5F,MAAM,EAAE,YAAY,CAAC;IACrB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,sBAAsB;IACrC;;;;OAIG;IACH,gBAAgB,CAAC,KAAK,EAAE,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;IACvD;;;;;OAKG;IACH,mBAAmB,CAAC,KAAK,EAAE,SAAS,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC;CAC9D;AAoED,wBAAsB,0BAA0B,CAC9C,KAAK,EAAE,MAAM,GAAG,WAAW,GAAG,UAAU,EACxC,OAAO,CAAC,EAAE,iCAAiC,GAC1C,OAAO,CAAC,sBAAsB,CAAC,CAoDjC"}
@@ -0,0 +1,116 @@
1
+ import { createImageData, resize } from "@richardmcquiston01/core-image";
2
+ import * as ort from "onnxruntime-web";
3
+ /**
4
+ * U2NETP (see models/NOTICE.md) expects a 320x320 RGB input, normalized with
5
+ * ImageNet mean/std, laid out channel-first (NCHW). Its first output is the
6
+ * final fused, sigmoid-activated saliency mask; the remaining six outputs are
7
+ * the network's deep-supervision side outputs and are not used here.
8
+ */
9
+ const MODEL_INPUT_SIZE = 320;
10
+ const CHANNEL_MEAN = [0.485, 0.456, 0.406];
11
+ const CHANNEL_STD = [0.229, 0.224, 0.225];
12
+ function preprocess(image) {
13
+ const resized = resize(image, {
14
+ width: MODEL_INPUT_SIZE,
15
+ height: MODEL_INPUT_SIZE,
16
+ method: "bilinear",
17
+ });
18
+ const pixelCount = MODEL_INPUT_SIZE * MODEL_INPUT_SIZE;
19
+ const chw = new Float32Array(3 * pixelCount);
20
+ const data = resized.data;
21
+ for (let i = 0; i < pixelCount; i++) {
22
+ const r = (data[i * 4] ?? 0) / 255;
23
+ const g = (data[i * 4 + 1] ?? 0) / 255;
24
+ const b = (data[i * 4 + 2] ?? 0) / 255;
25
+ chw[i] = (r - CHANNEL_MEAN[0]) / CHANNEL_STD[0];
26
+ chw[pixelCount + i] = (g - CHANNEL_MEAN[1]) / CHANNEL_STD[1];
27
+ chw[pixelCount * 2 + i] = (b - CHANNEL_MEAN[2]) / CHANNEL_STD[2];
28
+ }
29
+ return new ort.Tensor("float32", chw, [1, 3, MODEL_INPUT_SIZE, MODEL_INPUT_SIZE]);
30
+ }
31
+ /** Min-max normalizes the raw mask output to [0, 1], matching U2Net's standard postprocessing. */
32
+ function normalizeMask(mask) {
33
+ let min = Infinity;
34
+ let max = -Infinity;
35
+ for (const v of mask) {
36
+ if (v < min)
37
+ min = v;
38
+ if (v > max)
39
+ max = v;
40
+ }
41
+ const range = max - min;
42
+ if (range < 1e-6) {
43
+ return mask;
44
+ }
45
+ const normalized = new Float32Array(mask.length);
46
+ for (let i = 0; i < mask.length; i++) {
47
+ normalized[i] = ((mask[i] ?? 0) - min) / range;
48
+ }
49
+ return normalized;
50
+ }
51
+ /** Upsamples a 320x320 [0,1] mask to `width`x`height` by round-tripping it through the RGBA resize filter. */
52
+ function upsampleMask(mask, width, height) {
53
+ const maskImage = createImageData(MODEL_INPUT_SIZE, MODEL_INPUT_SIZE);
54
+ const maskData = maskImage.data;
55
+ for (let i = 0; i < mask.length; i++) {
56
+ const value = Math.round((mask[i] ?? 0) * 255);
57
+ maskData[i * 4] = value;
58
+ maskData[i * 4 + 1] = value;
59
+ maskData[i * 4 + 2] = value;
60
+ maskData[i * 4 + 3] = 255;
61
+ }
62
+ const resized = resize(maskImage, { width, height, method: "bilinear" });
63
+ const result = new Float32Array(width * height);
64
+ for (let i = 0; i < result.length; i++) {
65
+ result[i] = (resized.data[i * 4] ?? 0) / 255;
66
+ }
67
+ return result;
68
+ }
69
+ function supportsWebGpu() {
70
+ return typeof navigator !== "undefined" && "gpu" in navigator && navigator.gpu != null;
71
+ }
72
+ export async function loadBackgroundRemovalModel(model, options) {
73
+ if (options?.wasmPaths !== undefined) {
74
+ ort.env.wasm.wasmPaths = options.wasmPaths;
75
+ }
76
+ const executionProviders = supportsWebGpu() ? ["webgpu", "wasm"] : ["wasm"];
77
+ const session = typeof model === "string"
78
+ ? await ort.InferenceSession.create(model, { executionProviders })
79
+ : await ort.InferenceSession.create(model instanceof Uint8Array ? model : new Uint8Array(model), { executionProviders });
80
+ const rawInputName = session.inputNames[0];
81
+ const rawOutputName = session.outputNames[0];
82
+ if (!rawInputName || !rawOutputName) {
83
+ throw new Error("Background removal model has no input/output names");
84
+ }
85
+ const inputName = rawInputName;
86
+ const outputName = rawOutputName;
87
+ async function computeSaliencyMask(image) {
88
+ const tensor = preprocess(image);
89
+ const results = await session.run({ [inputName]: tensor });
90
+ const output = results[outputName];
91
+ if (!output) {
92
+ throw new Error(`Background removal model did not produce output "${outputName}"`);
93
+ }
94
+ const mask = normalizeMask(output.data);
95
+ const values = upsampleMask(mask, image.width, image.height);
96
+ return { values, width: image.width, height: image.height };
97
+ }
98
+ return {
99
+ computeSaliencyMask,
100
+ async removeBackground(image) {
101
+ const { values: upsampled } = await computeSaliencyMask(image);
102
+ const result = createImageData(image.width, image.height);
103
+ const srcData = image.data;
104
+ const dstData = result.data;
105
+ for (let i = 0; i < upsampled.length; i++) {
106
+ const srcAlpha = srcData[i * 4 + 3] ?? 255;
107
+ dstData[i * 4] = srcData[i * 4] ?? 0;
108
+ dstData[i * 4 + 1] = srcData[i * 4 + 1] ?? 0;
109
+ dstData[i * 4 + 2] = srcData[i * 4 + 2] ?? 0;
110
+ dstData[i * 4 + 3] = Math.round((upsampled[i] ?? 0) * srcAlpha);
111
+ }
112
+ return result;
113
+ },
114
+ };
115
+ }
116
+ //# sourceMappingURL=background-removal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"background-removal.js","sourceRoot":"","sources":["../src/background-removal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,KAAK,GAAG,MAAM,iBAAiB,CAAC;AAEvC;;;;;GAKG;AACH,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAC7B,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;AAC3C,MAAM,WAAW,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;AAoC1C,SAAS,UAAU,CAAC,KAAgB;IAClC,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,EAAE;QAC5B,KAAK,EAAE,gBAAgB;QACvB,MAAM,EAAE,gBAAgB;QACxB,MAAM,EAAE,UAAU;KACnB,CAAC,CAAC;IAEH,MAAM,UAAU,GAAG,gBAAgB,GAAG,gBAAgB,CAAC;IACvD,MAAM,GAAG,GAAG,IAAI,YAAY,CAAC,CAAC,GAAG,UAAU,CAAC,CAAC;IAC7C,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAE1B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,UAAU,EAAE,CAAC,EAAE,EAAE,CAAC;QACpC,MAAM,CAAC,GAAG,CAAC,IAAI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,IAAI,CAAC;YAC5B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;gBAC1C,MAAM,QAAQ,GAAG,OAAO,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,IAAI,GAAG,CAAC;gBAC3C,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;gBACrC,OAAO,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;gBAC7C,OAAO,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;gBAC7C,OAAO,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC;YAClE,CAAC;YACD,OAAO,MAAM,CAAC;QAChB,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { ImageCodec } from "./onnx-background-remover.js";
2
+ export declare const browserImageCodec: ImageCodec;
3
+ //# sourceMappingURL=browser-image-codec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-image-codec.d.ts","sourceRoot":"","sources":["../src/browser-image-codec.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,UAAU,EAAe,MAAM,8BAA8B,CAAC;AAW5E,eAAO,MAAM,iBAAiB,EAAE,UA4B/B,CAAC"}
@@ -0,0 +1,32 @@
1
+ function createContext(width, height) {
2
+ const canvas = document.createElement("canvas");
3
+ canvas.width = width;
4
+ canvas.height = height;
5
+ const ctx = canvas.getContext("2d", { willReadFrequently: true });
6
+ if (!ctx)
7
+ throw new Error("Canvas is unavailable in this browser.");
8
+ return ctx;
9
+ }
10
+ export const browserImageCodec = {
11
+ async encode(image) {
12
+ const ctx = createContext(image.width, image.height);
13
+ ctx.putImageData(new ImageData(image.data, image.width, image.height), 0, 0);
14
+ const blob = await new Promise((resolve) => ctx.canvas.toBlob(resolve, "image/png"));
15
+ if (!blob)
16
+ throw new Error("The browser could not encode the image as PNG.");
17
+ return { mimeType: "image/png", data: new Uint8Array(await blob.arrayBuffer()) };
18
+ },
19
+ async decode(image) {
20
+ const bitmap = await createImageBitmap(new Blob([image.data], { type: image.mimeType }));
21
+ try {
22
+ const ctx = createContext(bitmap.width, bitmap.height);
23
+ ctx.drawImage(bitmap, 0, 0);
24
+ const { data } = ctx.getImageData(0, 0, bitmap.width, bitmap.height);
25
+ return { width: bitmap.width, height: bitmap.height, data };
26
+ }
27
+ finally {
28
+ bitmap.close();
29
+ }
30
+ },
31
+ };
32
+ //# sourceMappingURL=browser-image-codec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-image-codec.js","sourceRoot":"","sources":["../src/browser-image-codec.ts"],"names":[],"mappings":"AAOA,SAAS,aAAa,CAAC,KAAa,EAAE,MAAc;IAClD,MAAM,MAAM,GAAG,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;IAChD,MAAM,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,MAAM,GAAG,GAAG,MAAM,CAAC,UAAU,CAAC,IAAI,EAAE,EAAE,kBAAkB,EAAE,IAAI,EAAE,CAAC,CAAC;IAClE,IAAI,CAAC,GAAG;QAAE,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;IACpE,OAAO,GAAG,CAAC;AACb,CAAC;AAED,MAAM,CAAC,MAAM,iBAAiB,GAAe;IAC3C,KAAK,CAAC,MAAM,CAAC,KAAkB;QAC7B,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gBAAS,CAAC;YACT,MAAM,CAAC,KAAK,EAAE,CAAC;QACjB,CAAC;IACH,CAAC;CACF,CAAC"}
@@ -0,0 +1,4 @@
1
+ export * from "./background-removal.js";
2
+ export * from "./upscale.js";
3
+ export * from "./auto-crop.js";
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,yBAAyB,CAAC;AACxC,cAAc,cAAc,CAAC;AAC7B,cAAc,gBAAgB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./background-removal.js";
2
+ export * from "./upscale.js";
3
+ export * from "./auto-crop.js";
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,yBAAyB,CAAC;AACxC,cAAc,cAAc,CAAC;AAC7B,cAAc,gBAAgB,CAAC"}
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The in-browser U²-Net background remover, as an `ImageGenerator`.
3
+ *
4
+ * It runs the model from this package (ONNX Runtime Web) on the visitor's own
5
+ * machine, so it needs no server, no account and no network once the model is
6
+ * cached — and, being an `ImageGenerator` from
7
+ * `@richardmcquiston01/ai-providers`, it is interchangeable with any other
8
+ * provider (a local ComfyUI, a hosted API). Providers exchange *encoded*
9
+ * images, so an {@link ImageCodec} turns them into pixels and back.
10
+ */
11
+ import { type AiImage, type ImageGenerator, type ImageRequest, type ImageResult, type Result } from "@richardmcquiston01/ai-providers";
12
+ import type { BackgroundRemovalModel, LoadBackgroundRemovalModelOptions } from "./background-removal.js";
13
+ /** The one thing this provider does. */
14
+ export declare const REMOVE_BACKGROUND_MODE = "remove-background";
15
+ /** RGBA pixels, row-major: structurally an `ImageData`, without needing one. */
16
+ export interface PixelBuffer {
17
+ width: number;
18
+ height: number;
19
+ data: Uint8ClampedArray;
20
+ }
21
+ /** Converts between the encoded images providers exchange and RGBA pixels. */
22
+ export interface ImageCodec {
23
+ encode(image: PixelBuffer): Promise<AiImage>;
24
+ decode(image: AiImage): Promise<PixelBuffer>;
25
+ }
26
+ export interface OnnxBackgroundRemoverOptions {
27
+ /** Loads the model. Called once; a failed load is retried on the next run. */
28
+ loadModel: () => Promise<BackgroundRemovalModel>;
29
+ codec: ImageCodec;
30
+ }
31
+ export declare class OnnxBackgroundRemover implements ImageGenerator {
32
+ readonly provider = "onnx-web";
33
+ readonly model = "u2netp";
34
+ private readonly loadModel;
35
+ private readonly codec;
36
+ private modelPromise;
37
+ constructor(options: OnnxBackgroundRemoverOptions);
38
+ listModes(): Promise<Result<readonly string[]>>;
39
+ generateImage(request: ImageRequest): Promise<Result<ImageResult>>;
40
+ /** Load the model once and share it; forget a failed load so it can retry. */
41
+ private getModel;
42
+ }
43
+ /**
44
+ * A `loadModel` for {@link OnnxBackgroundRemover} that imports ONNX Runtime
45
+ * only when the model is first needed, so a bundler keeps it out of the chunk
46
+ * that merely lists the provider.
47
+ */
48
+ export declare function lazyBackgroundRemovalModel(model: string | ArrayBuffer | Uint8Array, options?: LoadBackgroundRemovalModelOptions): () => Promise<BackgroundRemovalModel>;
49
+ //# sourceMappingURL=onnx-background-remover.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"onnx-background-remover.d.ts","sourceRoot":"","sources":["../src/onnx-background-remover.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAIL,KAAK,OAAO,EACZ,KAAK,cAAc,EACnB,KAAK,YAAY,EACjB,KAAK,WAAW,EAChB,KAAK,MAAM,EACZ,MAAM,kCAAkC,CAAC;AAC1C,OAAO,KAAK,EACV,sBAAsB,EACtB,iCAAiC,EAClC,MAAM,yBAAyB,CAAC;AAEjC,wCAAwC;AACxC,eAAO,MAAM,sBAAsB,sBAAsB,CAAC;AAE1D,gFAAgF;AAChF,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,iBAAiB,CAAC;CACzB;AAED,8EAA8E;AAC9E,MAAM,WAAW,UAAU;IACzB,MAAM,CAAC,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAC7C,MAAM,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;CAC9C;AAED,MAAM,WAAW,4BAA4B;IAC3C,8EAA8E;IAC9E,SAAS,EAAE,MAAM,OAAO,CAAC,sBAAsB,CAAC,CAAC;IACjD,KAAK,EAAE,UAAU,CAAC;CACnB;AAED,qBAAa,qBAAsB,YAAW,cAAc;IAC1D,QAAQ,CAAC,QAAQ,cAAc;IAC/B,QAAQ,CAAC,KAAK,YAAY;IAE1B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAwC;IAClE,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAa;IACnC,OAAO,CAAC,YAAY,CAAgD;gBAExD,OAAO,EAAE,4BAA4B;IAK3C,SAAS,IAAI,OAAO,CAAC,MAAM,CAAC,SAAS,MAAM,EAAE,CAAC,CAAC;IAI/C,aAAa,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IAqCxE,8EAA8E;IAC9E,OAAO,CAAC,QAAQ;CASjB;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,CACxC,KAAK,EAAE,MAAM,GAAG,WAAW,GAAG,UAAU,EACxC,OAAO,CAAC,EAAE,iCAAiC,GAC1C,MAAM,OAAO,CAAC,sBAAsB,CAAC,CAKvC"}
@@ -0,0 +1,80 @@
1
+ /**
2
+ * The in-browser U²-Net background remover, as an `ImageGenerator`.
3
+ *
4
+ * It runs the model from this package (ONNX Runtime Web) on the visitor's own
5
+ * machine, so it needs no server, no account and no network once the model is
6
+ * cached — and, being an `ImageGenerator` from
7
+ * `@richardmcquiston01/ai-providers`, it is interchangeable with any other
8
+ * provider (a local ComfyUI, a hosted API). Providers exchange *encoded*
9
+ * images, so an {@link ImageCodec} turns them into pixels and back.
10
+ */
11
+ import { describeUnknownError, err, ok, } from "@richardmcquiston01/ai-providers";
12
+ /** The one thing this provider does. */
13
+ export const REMOVE_BACKGROUND_MODE = "remove-background";
14
+ export class OnnxBackgroundRemover {
15
+ provider = "onnx-web";
16
+ model = "u2netp";
17
+ loadModel;
18
+ codec;
19
+ modelPromise = null;
20
+ constructor(options) {
21
+ this.loadModel = options.loadModel;
22
+ this.codec = options.codec;
23
+ }
24
+ async listModes() {
25
+ return ok([REMOVE_BACKGROUND_MODE]);
26
+ }
27
+ async generateImage(request) {
28
+ const label = `${this.provider} (model "${this.model}")`;
29
+ if (request.mode !== null && request.mode !== REMOVE_BACKGROUND_MODE) {
30
+ return err(`${label} has no mode "${request.mode}"; its only mode is "${REMOVE_BACKGROUND_MODE}".`);
31
+ }
32
+ const input = request.images[0];
33
+ if (!input) {
34
+ return err(`${label} needs the image to cut out, but the request had none.`);
35
+ }
36
+ if (request.signal?.aborted) {
37
+ return err(`${label} was cancelled before it started.`);
38
+ }
39
+ try {
40
+ const model = await this.getModel();
41
+ const pixels = await this.codec.decode(input);
42
+ const cutout = await model.removeBackground(new ImageData(pixels.data, pixels.width, pixels.height));
43
+ // The model can't be interrupted mid-run, so honour a cancel afterwards.
44
+ if (request.signal?.aborted) {
45
+ return err(`${label} was cancelled while it was running.`);
46
+ }
47
+ const image = await this.codec.encode({
48
+ width: cutout.width,
49
+ height: cutout.height,
50
+ data: cutout.data,
51
+ });
52
+ return ok({ image, notes: null });
53
+ }
54
+ catch (cause) {
55
+ return err(`${label} failed: ${describeUnknownError(cause)}`, cause);
56
+ }
57
+ }
58
+ /** Load the model once and share it; forget a failed load so it can retry. */
59
+ getModel() {
60
+ if (!this.modelPromise) {
61
+ this.modelPromise = this.loadModel().catch((cause) => {
62
+ this.modelPromise = null;
63
+ throw cause;
64
+ });
65
+ }
66
+ return this.modelPromise;
67
+ }
68
+ }
69
+ /**
70
+ * A `loadModel` for {@link OnnxBackgroundRemover} that imports ONNX Runtime
71
+ * only when the model is first needed, so a bundler keeps it out of the chunk
72
+ * that merely lists the provider.
73
+ */
74
+ export function lazyBackgroundRemovalModel(model, options) {
75
+ return async () => {
76
+ const { loadBackgroundRemovalModel } = await import("./background-removal.js");
77
+ return loadBackgroundRemovalModel(model, options);
78
+ };
79
+ }
80
+ //# sourceMappingURL=onnx-background-remover.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"onnx-background-remover.js","sourceRoot":"","sources":["../src/onnx-background-remover.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EACL,oBAAoB,EACpB,GAAG,EACH,EAAE,GAMH,MAAM,kCAAkC,CAAC;AAM1C,wCAAwC;AACxC,MAAM,CAAC,MAAM,sBAAsB,GAAG,mBAAmB,CAAC;AAqB1D,MAAM,OAAO,qBAAqB;IACvB,QAAQ,GAAG,UAAU,CAAC;IACtB,KAAK,GAAG,QAAQ,CAAC;IAET,SAAS,CAAwC;IACjD,KAAK,CAAa;IAC3B,YAAY,GAA2C,IAAI,CAAC;IAEpE,YAAY,OAAqC;QAC/C,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QACnC,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;IAC7B,CAAC;IAED,KAAK,CAAC,SAAS;QACb,OAAO,EAAE,CAAC,CAAC,sBAAsB,CAAC,CAAC,CAAC;IACtC,CAAC;IAED,KAAK,CAAC,aAAa,CAAC,OAAqB;QACvC,MAAM,KAAK,GAAG,GAAG,IAAI,CAAC,QAAQ,YAAY,IAAI,CAAC,KAAK,IAAI,CAAC;QAEzD,IAAI,OAAO,CAAC,IAAI,KAAK,IAAI,IAAI,OAAO,CAAC,IAAI,KAAK,sBAAsB,EAAE,CAAC;YACrE,OAAO,GAAG,CACR,GAAG,KAAK,iBAAiB,OAAO,CAAC,IAAI,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CAAC;IAED,8EAA8E;IACtE,QAAQ;QACd,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC;YACvB,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;gBAC5D,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;gBACzB,MAAM,KAAK,CAAC;YACd,CAAC,CAAC,CAAC;QACL,CAAC;QACD,OAAO,IAAI,CAAC,YAAY,CAAC;IAC3B,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,UAAU,0BAA0B,CACxC,KAAwC,EACxC,OAA2C;IAE3C,OAAO,KAAK,IAAI,EAAE;QAChB,MAAM,EAAE,0BAA0B,EAAE,GAAG,MAAM,MAAM,CAAC,yBAAyB,CAAC,CAAC;QAC/E,OAAO,0BAA0B,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IACpD,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,3 @@
1
+ export * from "./onnx-background-remover.js";
2
+ export * from "./browser-image-codec.js";
3
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAGA,cAAc,8BAA8B,CAAC;AAC7C,cAAc,0BAA0B,CAAC"}
@@ -0,0 +1,6 @@
1
+ // Entry point for `@richardmcquiston01/ai-tools/provider`: the background
2
+ // remover as an `ImageGenerator`. Kept apart from the main entry so that code
3
+ // that only wants the raw models never needs `@richardmcquiston01/ai-providers`.
4
+ export * from "./onnx-background-remover.js";
5
+ export * from "./browser-image-codec.js";
6
+ //# sourceMappingURL=provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.js","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,8EAA8E;AAC9E,iFAAiF;AACjF,cAAc,8BAA8B,CAAC;AAC7C,cAAc,0BAA0B,CAAC"}
@@ -0,0 +1,20 @@
1
+ export type UpscaleFactor = 2 | 3 | 4 | 8;
2
+ export interface LoadUpscaleModelOptions {
3
+ /**
4
+ * Full URL to this scale factor's `model.json` (with its weight-shard files
5
+ * served alongside it), overriding the library's default behavior of
6
+ * fetching from the jsdelivr/unpkg CDN mirrors of the npm package. Needed
7
+ * for a fully self-contained deployment with no external CDN dependency —
8
+ * the caller is expected to serve the vendored model files (bundled from
9
+ * `@upscalerjs/esrgan-slim`'s own `models/<scale>x/` directory) and pass
10
+ * their resolved URL here.
11
+ */
12
+ modelUrl?: string;
13
+ }
14
+ export interface UpscaleModel {
15
+ readonly scaleFactor: UpscaleFactor;
16
+ /** Upscales `image` by this model's scale factor, preserving the alpha channel. */
17
+ upscale(image: ImageData): Promise<ImageData>;
18
+ }
19
+ export declare function loadUpscaleModel(scaleFactor: UpscaleFactor, options?: LoadUpscaleModelOptions): Promise<UpscaleModel>;
20
+ //# sourceMappingURL=upscale.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upscale.d.ts","sourceRoot":"","sources":["../src/upscale.ts"],"names":[],"mappings":"AAQA,MAAM,MAAM,aAAa,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AAc1C,MAAM,WAAW,uBAAuB;IACtC;;;;;;;;OAQG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,WAAW,EAAE,aAAa,CAAC;IACpC,mFAAmF;IACnF,OAAO,CAAC,KAAK,EAAE,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;CAC/C;AAkCD,wBAAsB,gBAAgB,CACpC,WAAW,EAAE,aAAa,EAC1B,OAAO,CAAC,EAAE,uBAAuB,GAChC,OAAO,CAAC,YAAY,CAAC,CAyCvB"}
@@ -0,0 +1,83 @@
1
+ import { createImageData, resize } from "@richardmcquiston01/core-image";
2
+ import * as tf from "@tensorflow/tfjs";
3
+ import x2 from "@upscalerjs/esrgan-slim/2x";
4
+ import x3 from "@upscalerjs/esrgan-slim/3x";
5
+ import x4 from "@upscalerjs/esrgan-slim/4x";
6
+ import x8 from "@upscalerjs/esrgan-slim/8x";
7
+ import Upscaler from "upscaler";
8
+ const MODEL_DEFINITIONS = {
9
+ 2: x2,
10
+ 3: x3,
11
+ 4: x4,
12
+ 8: x8,
13
+ };
14
+ function imageToRgbTensor(image) {
15
+ const pixelCount = image.width * image.height;
16
+ const rgb = new Int32Array(pixelCount * 3);
17
+ const data = image.data;
18
+ for (let i = 0; i < pixelCount; i++) {
19
+ rgb[i * 3] = data[i * 4] ?? 0;
20
+ rgb[i * 3 + 1] = data[i * 4 + 1] ?? 0;
21
+ rgb[i * 3 + 2] = data[i * 4 + 2] ?? 0;
22
+ }
23
+ return tf.tensor3d(rgb, [image.height, image.width, 3], "int32");
24
+ }
25
+ /** Upsamples the alpha channel to the output size by round-tripping it through the RGBA resize filter (the upscaling model only understands RGB). */
26
+ function upsampleAlpha(image, outWidth, outHeight) {
27
+ const alphaImage = createImageData(image.width, image.height);
28
+ const src = image.data;
29
+ const dst = alphaImage.data;
30
+ for (let i = 0; i < image.width * image.height; i++) {
31
+ const a = src[i * 4 + 3] ?? 255;
32
+ dst[i * 4] = a;
33
+ dst[i * 4 + 1] = a;
34
+ dst[i * 4 + 2] = a;
35
+ dst[i * 4 + 3] = 255;
36
+ }
37
+ const resized = resize(alphaImage, { width: outWidth, height: outHeight, method: "bilinear" });
38
+ const result = new Uint8ClampedArray(outWidth * outHeight);
39
+ for (let i = 0; i < result.length; i++) {
40
+ result[i] = resized.data[i * 4] ?? 255;
41
+ }
42
+ return result;
43
+ }
44
+ export async function loadUpscaleModel(scaleFactor, options) {
45
+ const baseDefinition = MODEL_DEFINITIONS[scaleFactor];
46
+ const modelDefinition = options?.modelUrl
47
+ ? { ...baseDefinition, path: options.modelUrl }
48
+ : baseDefinition;
49
+ const upscaler = new Upscaler({ model: modelDefinition });
50
+ await upscaler.ready;
51
+ return {
52
+ scaleFactor,
53
+ async upscale(image) {
54
+ const inputTensor = imageToRgbTensor(image);
55
+ let outputTensor;
56
+ try {
57
+ outputTensor = await upscaler.upscale(inputTensor, { output: "tensor" });
58
+ }
59
+ finally {
60
+ inputTensor.dispose();
61
+ }
62
+ const [outHeight, outWidth] = outputTensor.shape;
63
+ if (outHeight === undefined || outWidth === undefined) {
64
+ outputTensor.dispose();
65
+ throw new Error("Upscale model produced a tensor with an unexpected shape");
66
+ }
67
+ const pixels = await outputTensor.data();
68
+ outputTensor.dispose();
69
+ const alpha = upsampleAlpha(image, outWidth, outHeight);
70
+ const result = createImageData(outWidth, outHeight);
71
+ const dst = result.data;
72
+ const pixelCount = outWidth * outHeight;
73
+ for (let i = 0; i < pixelCount; i++) {
74
+ dst[i * 4] = pixels[i * 3] ?? 0;
75
+ dst[i * 4 + 1] = pixels[i * 3 + 1] ?? 0;
76
+ dst[i * 4 + 2] = pixels[i * 3 + 2] ?? 0;
77
+ dst[i * 4 + 3] = alpha[i] ?? 255;
78
+ }
79
+ return result;
80
+ },
81
+ };
82
+ }
83
+ //# sourceMappingURL=upscale.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upscale.js","sourceRoot":"","sources":["../src/upscale.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACvC,OAAO,EAAE,MAAM,4BAA4B,CAAC;AAC5C,OAAO,EAAE,MAAM,4BAA4B,CAAC;AAC5C,OAAO,EAAE,MAAM,4BAA4B,CAAC;AAC5C,OAAO,EAAE,MAAM,4BAA4B,CAAC;AAC5C,OAAO,QAAQ,MAAM,UAAU,CAAC;AAShC,MAAM,iBAAiB,GAAmD;IACxE,CAAC,EAAE,EAA6B;IAChC,CAAC,EAAE,EAA6B;IAChC,CAAC,EAAE,EAA6B;IAChC,CAAC,EAAE,EAA6B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AC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;gBACxC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;gBACxC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC;YACnC,CAAC;YACD,OAAO,MAAM,CAAC;QAChB,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,18 @@
1
+ # Model attribution
2
+
3
+ ## `u2netp.onnx`
4
+
5
+ - **Architecture**: U²-Net (small variant, "U2NETP"), from Qin et al., _"U^2-Net: Going
6
+ Deeper with Nested U-Structure for Salient Object Detection"_, Pattern Recognition 2020.
7
+ - **Source repository**: https://github.com/xuebinqin/U-2-Net
8
+ - **License**: Apache License 2.0 — full text in `LICENSE-APACHE-2.0.txt` alongside this file (the u2net/u2netp checkpoints — NOT the separate
9
+ `u2net_portrait` checkpoint, which carries a non-commercial restriction and is not
10
+ used here).
11
+ - **File obtained from**: the pre-exported ONNX release published by
12
+ https://github.com/danielgatis/rembg (MIT-licensed project; this file is an
13
+ unmodified redistribution of the original Apache-2.0 licensed weights), at
14
+ https://github.com/danielgatis/rembg/releases/download/v0.0.0/u2netp.onnx
15
+ (SHA-256: `309c8469258dda742793dce0ebea8e6dd393174f89934733ecc8b14c76f4ddd8`).
16
+
17
+ Vendored directly into this package so background removal runs fully offline with
18
+ no runtime dependency on any external CDN or model-hosting service.
Binary file
package/package.json CHANGED
@@ -1,6 +1,76 @@
1
1
  {
2
2
  "name": "@richardmcquiston01/ai-tools",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "In-browser AI image tools (background removal, upscaling, auto-crop) for laser/CNC/maker workflows",
5
+ "keywords": [
6
+ "background-removal",
7
+ "upscaling",
8
+ "auto-crop",
9
+ "onnx",
10
+ "image-processing",
11
+ "laser",
12
+ "cnc",
13
+ "engraving",
14
+ "maker",
15
+ "typescript",
16
+ "image-generator"
17
+ ],
18
+ "license": "MIT",
19
+ "homepage": "https://github.com/RichardMcQuiston01/maker-image-tools#readme",
20
+ "bugs": {
21
+ "url": "https://github.com/RichardMcQuiston01/maker-image-tools/issues"
22
+ },
23
+ "type": "module",
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/RichardMcQuiston01/maker-image-tools.git",
27
+ "directory": "packages/ai-tools"
28
+ },
29
+ "main": "./dist/index.js",
30
+ "types": "./dist/index.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "default": "./dist/index.js"
35
+ },
36
+ "./provider": {
37
+ "types": "./dist/provider.d.ts",
38
+ "default": "./dist/provider.js"
39
+ }
40
+ },
41
+ "files": [
42
+ "dist",
43
+ "models",
44
+ "README.md",
45
+ "LICENSE"
46
+ ],
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "scripts": {
51
+ "build": "tsc -p tsconfig.json",
52
+ "test": "vitest run",
53
+ "typecheck": "tsc -p tsconfig.json --noEmit"
54
+ },
55
+ "dependencies": {
56
+ "@richardmcquiston01/core-image": "0.2.0",
57
+ "@tensorflow/tfjs": "4.11.0",
58
+ "@upscalerjs/esrgan-slim": "1.0.0",
59
+ "onnxruntime-web": "1.27.0",
60
+ "upscaler": "1.0.0"
61
+ },
62
+ "devDependencies": {
63
+ "@richardmcquiston01/ai-providers": "^0.1.0",
64
+ "jsdom": "^25.0.1",
65
+ "typescript": "^5.7.3",
66
+ "vitest": "^3.0.4"
67
+ },
68
+ "peerDependencies": {
69
+ "@richardmcquiston01/ai-providers": "^0.1.0"
70
+ },
71
+ "peerDependenciesMeta": {
72
+ "@richardmcquiston01/ai-providers": {
73
+ "optional": true
74
+ }
75
+ }
76
+ }