@64tensor/retouch-ml 0.0.0-stage → 0.4.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/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ ## 0.4.0
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [[`66f0e7c`](https://github.com/64Tensor/retouch/commit/66f0e7c402547fc4044b833be327f339c4b38608)]:
8
+ - @64tensor/retouch@0.4.0
9
+
10
+ All notable changes to `@64tensor/retouch-ml`. It shares its version number with
11
+ `@64tensor/retouch`, whose changelog also holds both packages' history before 0.3.0.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 64Tensor LLC
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,265 @@
1
- # Temporary Holding Version
1
+ # @64tensor/retouch-ml
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
+ <p>
4
+ <a href="https://www.npmjs.com/package/@64tensor/retouch-ml"><img src="https://img.shields.io/npm/v/@64tensor/retouch-ml?color=D4572A&label=npm" alt="npm version" /></a>
5
+ <a href="https://github.com/64Tensor/retouch/blob/main/packages/ml/LICENSE"><img src="https://img.shields.io/npm/l/@64tensor/retouch-ml?color=1A1815" alt="license" /></a>
6
+ </p>
7
+
8
+ On-device ML tools for [Rétouch](https://github.com/64Tensor/retouch) — no
9
+ server, no API keys. Models run in the browser through ONNX Runtime Web
10
+ (WebGPU when available, WASM otherwise, inference in a worker so the UI never
11
+ freezes); weights download on first use and are cached via the Cache API.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ npm install @64tensor/retouch @64tensor/retouch-ml
17
+ ```
18
+
19
+ `@64tensor/retouch` is a peer dependency — the tools register into its editor
20
+ through the plugin API and ride its edit model.
21
+
22
+ ## Features
23
+
24
+ - **Cutout (background removal)** — MODNet (Apache-2.0, ~25 MB) by default;
25
+ point `modelUrl` at any BiRefNet ONNX export for higher fidelity. Registers
26
+ a "Cutout" tool in the editor that clears the photo's background to
27
+ transparent in place (the photo becomes a PNG), as one step you can undo.
28
+ - **Upscale (4× super-resolution)** — Real-ESRGAN x4plus (BSD-3-Clause,
29
+ ~67 MB), run tile-by-tile with overlap so seams never show. WebGPU when the
30
+ device can take it, automatic WASM fallback when a kernel fails mid-run.
31
+ Inputs are capped at a 2048px long edge; transparency is preserved.
32
+ - **Detect (faces + objects)** — UltraFace (MIT, ~1.2 MB) for faces and
33
+ YOLOX-nano (Apache-2.0, ~3.5 MB) for 80 COCO object classes with labeled
34
+ boxes. Either feeds three one-click actions: add a radial mask per box
35
+ (tune it in the Masks tool), **pixelate** for privacy (replaces the image
36
+ in place), or **crop to the detected boxes**. Mask/crop actions ride the
37
+ non-destructive edit model, so they undo like any other edit. What it finds
38
+ is a layer over the photo: point at a box or its row to bring it forward,
39
+ and pick one to act on it alone.
40
+ - **Track (video)** — the same YOLOX-nano, run on a video's frames, with a
41
+ tracker that follows each object from the frame it enters to the frame it
42
+ leaves under one number. Boxes match by overlap with where each track is
43
+ heading; a class the detector wavers on (bicycle or motorcycle) doesn't
44
+ split a track, a one-frame false positive never gets a number, and a
45
+ track survives a few missed frames. Registers a "Track" tool for videos:
46
+ follow everything, or only people, vehicles or animals, through the
47
+ trimmed clip; each track plays boxed and numbered with a trail, and is
48
+ listed with its span on a timeline, on the same layer as Detect. Point at a
49
+ box or row to bring it forward. Pick a row to jump to it, or a box where it
50
+ is, then **trim** the video to it or **crop** to where it goes, or save the
51
+ tracks as JSON.
52
+ `trackVideo(video)` seeks through a clip and returns every frame's boxes
53
+ plus a summary of each track; `createTracker()` takes detections from any
54
+ source, frame by frame.
55
+ - **Read text (OCR)** — PaddleOCR's two stages (Apache-2.0, ~13 MB together):
56
+ PP-OCRv4 finds the lines, at any angle, and PP-OCRv5's Latin recognizer
57
+ reads them in 32 languages, accents included (é, ñ, ş, ø…). The lines are
58
+ outlined on the photo and listed in reading order: **Copy text**, or
59
+ **Pixelate it** to hide every line (replaces the image in place).
60
+ - **Select (click-to-segment)** — SlimSAM-77 (Apache-2.0, ~38 MB in two
61
+ files). Click any object to segment it on-device, refine with more clicks
62
+ (Subtract mode / shift-click removes), then **Cut out** to a transparent
63
+ PNG or **Erase object** in place (dilated mask through the LaMa
64
+ inpainter). The image encodes once and is cached, so refinement clicks
65
+ land in tens of milliseconds.
66
+ - **Depth (bokeh)** — Depth Anything V2 Small (Apache-2.0, ~27 MB). One
67
+ analysis produces a depth map, its edges snapped to the photo's own with a
68
+ guided filter. The focus starts on the middle of the photo; click anything
69
+ to move it, then scrub Aperture with instant feedback (the blur is built
70
+ once per focus, in levels blended per pixel). The background blurs without
71
+ the sharp subject, so nothing glows around it, and what's in front of the
72
+ focus blurs over what's behind it, as through a lens. Apply renders the
73
+ result at full resolution and replaces the image in place.
74
+ - **Denoise** — SCUNet real-PSNR (Apache-2.0 or MIT, ~77 MB as a small graph stub
75
+ plus a weights sidecar). One click removes real-world noise — sensor
76
+ grain, compression speckle — tile-by-tile at native resolution and
77
+ replaces the image in place; transparency is preserved and Reset brings
78
+ the original back. Inputs are capped at a 2048px long edge.
79
+ - **Erase (heal brush)** — LaMa inpainting (Apache-2.0, ~208 MB). Paint over
80
+ an object, hit Erase: a padded square around the strokes runs through the
81
+ network and the fill composites back at full resolution, feathered and
82
+ masked-pixels-only. The result **replaces the image in place**, as one
83
+ undo step. Needs neutral geometry — reset
84
+ crop/transform/liquify first, or erase before transforming.
85
+
86
+ ## Usage
87
+
88
+ ```ts
89
+ import { Retouch } from "@64tensor/retouch";
90
+ import { installMlTools } from "@64tensor/retouch-ml";
91
+
92
+ const retouch = new Retouch({ target: "#editor" });
93
+ installMlTools(retouch);
94
+ ```
95
+
96
+ In the editor, every tool leads with where its model stands: a Download button
97
+ with the size, then the same button filling up with how much is in and the
98
+ time left, then Ready. Which model it is, and what it runs on, sit behind an
99
+ info button. The tool's own button says what it does and comes on once the
100
+ model is here; the run shows on one line under it, then what to do next, and
101
+ results wipe in over the photo. The AI tools menu says Ready beside each tool
102
+ whose model is saved. With a self-hosted `modelUrl` the size shows once the
103
+ download starts.
104
+
105
+ Every tool is also a plain function you can call without the editor. Each
106
+ takes an `HTMLImageElement | HTMLCanvasElement` plus options, and accepts
107
+ `onDownloadProgress` for the first-run weight download:
108
+
109
+ ```ts
110
+ import {
111
+ denoiseImage, detectFaces, detectObjects, estimateDepth,
112
+ inpaintStrokes, linesToText, recognizeText, removeBackground, trackVideo,
113
+ upscaleImage,
114
+ } from "@64tensor/retouch-ml";
115
+
116
+ const cutout = await removeBackground(image, {
117
+ onDownloadProgress: ({ loaded, total }) => console.log(loaded / total),
118
+ }); // HTMLCanvasElement (RGBA)
119
+ const big = await upscaleImage(image, { onTileProgress: (done, total) => … });
120
+ const clean = await denoiseImage(image);
121
+ const faces = await detectFaces(image); // [{ x, y, w, h, score }], normalized 0–1
122
+ const things = await detectObjects(image); // …plus `label` (COCO class)
123
+ const lines = await recognizeText(image); // [{ text, score, quad, x, y, w, h }], reading order
124
+ linesToText(lines); // "COTOPAXI\nCORAZÓN 4786m\n…"
125
+ const healed = await inpaintStrokes(image, [{ x, y, r }, …]);
126
+ const depth = await estimateDepth(image); // { width, height, data: Float32Array } (0–1, higher = closer)
127
+ const tracked = await trackVideo(video, { // an HTMLVideoElement; it seeks through it
128
+ fps: 6, // frames read per second of video
129
+ labels: ["person", "bicycle", "car"], // optional: only these classes
130
+ onFrame: (frame, progress) => …,
131
+ }); // { fps, frames: [{ time, boxes: [{ id, label, x, y, w, h, score }] }],
132
+ // tracks: [{ id, label, firstSeen, lastSeen, hits }] }
133
+ ```
134
+
135
+ `trackVideo` reads frames at up to 640 px (`maxSize`) and ignores boxes
136
+ smaller than `minSize` (a fraction of the frame). To track detections from
137
+ your own loop — a live camera, say — feed them to a tracker:
138
+
139
+ ```ts
140
+ import { createTracker, detectObjects } from "@64tensor/retouch-ml";
141
+
142
+ const tracker = createTracker(); // { matchThreshold, maxMissed, minHits, trailLength }
143
+ const tracks = tracker.update(await detectObjects(canvas), video.currentTime);
144
+ // [{ id, label, x, y, w, h, score, firstSeen, lastSeen, hits, missed, trail }]
145
+ ```
146
+
147
+ For your own bokeh UI: `prepareBokeh(image, depth)` once, then
148
+ `composeBokeh(prep, focus, strength)` (focus is a depth, such as
149
+ `depthAt(depth, x, y)` for a click; strength 0–1) for a preview, and
150
+ `renderBokeh(prep, image, depth, focus, strength)` for the full-size result.
151
+
152
+ `inpaintMask(image, maskCanvas)` takes a painted mask instead of strokes; the
153
+ SAM pieces are exposed as `encodeSamImage` / `decodeSamClicks` / `pickBestMask`.
154
+
155
+ ## Options
156
+
157
+ ```ts
158
+ installMlTools(retouch, {
159
+ cutout: { refSize: 512 }, // or false to skip the tool
160
+ upscale: { tileSize: 64, tileOverlap: 8, maxInputDim: 2048 },
161
+ denoise: { tileSize: 192, tileOverlap: 16, maxInputDim: 2048 },
162
+ erase: { modelUrl }, // LaMa inpainting (also backs Select → Erase object)
163
+ detect: { scoreThreshold: 0.7, iouThreshold: 0.35, // faces (UltraFace)
164
+ objects: { scoreThreshold: 0.35, iouThreshold: 0.45 } }, // YOLOX
165
+ select: { encoderUrl, decoderUrl },
166
+ text: { detectorUrl, recognizerUrl, dictionaryUrl, maxSide: 1280, minScore: 0.5 },
167
+ track: { fps: 6, minSize: 0.04, scoreThreshold: 0.35, matchThreshold: 0.2 }, // YOLOX + tracker
168
+ depth: { modelUrl },
169
+ openResults: true,
170
+ });
171
+ ```
172
+
173
+ Any of the nine keys can be `false` to leave that tool out. The tools share
174
+ one AI launcher on the editor's rail, and its menu lists each with a line on
175
+ what it does and its download size. Every option
176
+ group also accepts the runtime options below (`wasmPaths`,
177
+ `executionProviders`, `externalDataUrl`, `onDownloadProgress`).
178
+ `openResults` (default `true`) opens results that land in the gallery —
179
+ Upscale, and Select's **Cut out** — in the editor as soon as they finish; pass
180
+ `false` to leave them in the gallery quietly.
181
+
182
+ ## Self-hosting
183
+
184
+ By default, model weights load from the Hugging Face CDN (UltraFace from its
185
+ author's GitHub repo) and the ONNX Runtime `.wasm` binaries from jsDelivr. To
186
+ stay fully first-party, host both yourself:
187
+
188
+ ```ts
189
+ installMlTools(retouch, {
190
+ cutout: { modelUrl: "https://your.cdn/models/modnet.onnx", wasmPaths: "https://your.cdn/ort/" },
191
+ upscale: { modelUrl: "https://your.cdn/models/realesrgan-x4plus.onnx" },
192
+ erase: { modelUrl: "https://your.cdn/models/lama_fp32.onnx" },
193
+ detect: {
194
+ modelUrl: "https://your.cdn/models/ultraface-rfb-320.onnx",
195
+ objects: { modelUrl: "https://your.cdn/models/yolox_nano.onnx" },
196
+ },
197
+ track: { modelUrl: "https://your.cdn/models/yolox_nano.onnx" },
198
+ select: { encoderUrl: "https://your.cdn/models/sam-encoder.onnx", decoderUrl: "https://your.cdn/models/sam-decoder.onnx" },
199
+ depth: { modelUrl: "https://your.cdn/models/depth-anything-v2-small.onnx" },
200
+ text: {
201
+ detectorUrl: "https://your.cdn/models/ppocr-v4-det.onnx",
202
+ recognizerUrl: "https://your.cdn/models/ppocr-v5-latin-rec.onnx",
203
+ dictionaryUrl: "https://your.cdn/models/ppocr-v5-latin-dict.txt",
204
+ },
205
+ denoise: {
206
+ modelUrl: "https://your.cdn/models/scunet.onnx",
207
+ externalDataUrl: "https://your.cdn/models/scunet.onnx.data",
208
+ },
209
+ });
210
+ ```
211
+
212
+ Default model URLs are pinned to a commit of the repo that serves them, so a
213
+ later change there can never alter what your users download; the
214
+ `DEFAULT_*_MODEL_URL` constants expose them. Except for UltraFace, those repos
215
+ are third-party ONNX conversions or mirrors, not the model authors' own.
216
+ `wasmPaths` is page-global —
217
+ setting it in any tool's options applies to every session. `executionProviders`
218
+ (default `["webgpu", "wasm"]`) sets the preference order; a run that fails on
219
+ WebGPU retries on WASM automatically.
220
+
221
+ `await isModelCached(urls)` tells you whether a run would download anything
222
+ (all of `urls` saved in the cache), and `await clearModelCache()` drops the
223
+ cached weights.
224
+
225
+ The denoise default is a split export: a graph stub plus a `.onnx.data`
226
+ weights sidecar. When self-hosting it, keep the sidecar's filename identical
227
+ to the location the graph references (`scunet_color_real_psnr.onnx.data` for
228
+ the default). A custom `modelUrl` without `externalDataUrl` is treated as a
229
+ single-file export — no sidecar is fetched.
230
+
231
+ Self-hosting makes you the one distributing the weights, so keep
232
+ [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md) with your copies.
233
+ [`third-party-models.json`](third-party-models.json) lists every default file's
234
+ SHA-256 to check them against. A model you pick through `modelUrl` brings its
235
+ own license, which is yours to check.
236
+
237
+ ## Licenses
238
+
239
+ The package's code is MIT. That doesn't cover the models: the package contains
240
+ no weights, and each model keeps its own license.
241
+ [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md) has their copyright lines and
242
+ license texts, and [`third-party-models.json`](third-party-models.json) has each
243
+ file's pinned URL, SHA-256, license evidence and training data, checked at
244
+ source on 2026-11-07.
245
+
246
+ | Default model | License |
247
+ |---|---|
248
+ | MODNet | Apache-2.0 |
249
+ | Real-ESRGAN x4plus | BSD-3-Clause, inferred from the author's repo |
250
+ | LaMa | Apache-2.0, inferred from the author's repo |
251
+ | UltraFace | MIT |
252
+ | YOLOX-nano | Apache-2.0 |
253
+ | SlimSAM-77 | Apache-2.0 |
254
+ | Depth Anything V2 Small | Apache-2.0 |
255
+ | SCUNet | Apache-2.0 or MIT: the author's sources differ, so both notices ship |
256
+ | PP-OCRv4 detector, PP-OCRv5 Latin recognizer | Apache-2.0 |
257
+
258
+ ONNX Runtime Web is MIT.
259
+
260
+ These licenses don't settle training data. Several models were trained on
261
+ datasets whose terms limit commercial use, such as WIDER FACE (UltraFace),
262
+ Places2 (LaMa) and DIV2K (Real-ESRGAN), and whether those terms reach the weights
263
+ is an unsettled legal question. If that matters for your product, read the
264
+ notices and ask your counsel. See `docs/ADVANCED-FEATURES.md` in the repo root
265
+ for the per-model audit.