@hackbuild/vision 0.1.2 → 0.1.3
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/README.md +257 -178
- package/dist/api.d.ts +5 -1
- package/dist/api.js +4 -1
- package/dist/faceapi.d.ts +1 -0
- package/dist/faceapi.js +1 -0
- package/dist/loaders.d.ts +3 -1
- package/dist/loaders.js +3 -1
- package/dist/loop.d.ts +11 -8
- package/dist/loop.js +8 -7
- package/dist/masks.d.ts +9 -4
- package/dist/masks.js +9 -4
- package/dist/mediapipe.d.ts +7 -1
- package/dist/mediapipe.js +6 -1
- package/dist/records.d.ts +3 -0
- package/dist/records.js +13 -11
- package/dist/segment.d.ts +3 -2
- package/dist/segment.js +2 -2
- package/dist/signals.d.ts +8 -2
- package/dist/signals.js +3 -2
- package/dist/single/index.iife.js +69 -29
- package/dist/single/index.js +69 -29
- package/dist/stubs.d.ts +4 -0
- package/dist/stubs.js +4 -0
- package/dist/types.d.ts +13 -1
- package/dist/worker.d.ts +3 -0
- package/dist/yolo.d.ts +5 -1
- package/dist/yolo.js +4 -1
- package/llms.md +982 -0
- package/package.json +6 -5
package/README.md
CHANGED
|
@@ -1,144 +1,252 @@
|
|
|
1
1
|
# @hackbuild/vision
|
|
2
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
|
-
|
|
3
|
+
Get depth, objects, masks, landmarks and captions from an image or a webcam in your tab, through one models hub that shares the GPU with your scene.
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/@hackbuild/vision) [](../../LICENSE)  
|
|
6
|
+
|
|
7
|
+
Browser status: Depth Anything V2 small on webgpu and wasm, the EfficientDet detector on a still frame, SmolVLM 256M and LFM2-VL 450M captions and SlimSAM point masks ran in one automated pass in Chrome 150 on an Apple M1 that nobody has looked at. The webcam landmarkers, the person segmenter, YOLO, and every other browser and device have not run.
|
|
8
|
+
|
|
9
|
+
## What it does
|
|
10
|
+
|
|
11
|
+
- Runs depth, detection, segmentation, face, hand and pose landmarks, captions and questions through the `@hackbuild/models` hub.
|
|
12
|
+
- Falls through a chain of landmark models when one fails, and says which failed.
|
|
13
|
+
- Keeps image embeddings so later point and box prompts on the same image skip the encoder, and gives mask operations and PNG, SVG and run length export.
|
|
14
|
+
- Runs depth in a worker and schedules calls around your render loop so the scene keeps its frames.
|
|
15
|
+
- Turns face and hand landmarks into steady presence, expression and gesture signals for a character.
|
|
16
|
+
|
|
17
|
+
## Install
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
npm install @hackbuild/vision
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
It depends on [@hackbuild/ai-env](../ai-env/README.md), [@hackbuild/models](../models/README.md), [@hackbuild/devices](../devices/README.md) and [@hackbuild/weights](../weights/README.md). The model runtimes are not bundled; they load at run time from pinned URLs, and each is optional:
|
|
24
|
+
|
|
25
|
+
| subpath | runtime | pin |
|
|
26
|
+
|---|---|---|
|
|
27
|
+
| `.` (depth, segment, caption, ask) | @huggingface/transformers, through `loadTransformers` from @hackbuild/devices | 4.3.2 |
|
|
28
|
+
| `.` (detect, segment.person, landmarks) | @mediapipe/tasks-vision, through `loadTasksVision` | 1.2.3 |
|
|
29
|
+
| `.` (YOLO, optional) | onnxruntime-web, through `loadOrt` from @hackbuild/devices | 1.27.0 |
|
|
30
|
+
| `.` (face fallback, optional) | face-api.js, a runtime you pass to `faceApiProvider` | unknown |
|
|
31
|
+
|
|
32
|
+
## Quick start
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
import { probe } from "@hackbuild/ai-env";
|
|
36
|
+
import { loadTransformers, tjsProvider } from "@hackbuild/devices";
|
|
37
|
+
import { createHub } from "@hackbuild/models";
|
|
38
|
+
import { attachVision, caption, depth, detect, loadTasksVision, mediapipeProvider } from "@hackbuild/vision";
|
|
39
|
+
|
|
40
|
+
// one hub; transformers.js and MediaPipe tasks-vision load at run time from pinned urls
|
|
41
|
+
const tjs = tjsProvider({ runtime: loadTransformers() });
|
|
42
|
+
const hub = createHub({ env: await probe() });
|
|
43
|
+
attachVision(hub, tjs); // the vision records plus the transformers.js loaders
|
|
44
|
+
hub.provide("tjs", tjs.factory);
|
|
45
|
+
hub.provide("mediapipe", mediapipeProvider({ runtime: loadTasksVision() }));
|
|
46
|
+
|
|
47
|
+
// each call loads its model on first use, runs it under the gpu lock, and releases it
|
|
48
|
+
const video = document.querySelector("video")!;
|
|
49
|
+
video.srcObject = await navigator.mediaDevices.getUserMedia({ video: true }); // the webcam
|
|
50
|
+
await video.play();
|
|
51
|
+
const map = await depth(hub, video); // Depth Anything V2 small, weights Apache-2.0
|
|
52
|
+
const boxes = await detect(hub, video, { scoreThreshold: 0.4 }); // MediaPipe EfficientDet lite0, Apache-2.0
|
|
53
|
+
const line = await caption(hub, video); // SmolVLM 256M, Apache-2.0
|
|
54
|
+
console.log(map.width, map.height, boxes.map((b) => b.label), line);
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Live example
|
|
58
|
+
|
|
59
|
+
The vision tool in the suite runs this package: [hackbuild-suite vision](https://hackbuild.github.io/hackbuild-suite/#/image/vision). The demo page runs Depth Anything, MediaPipe detection, SlimSAM masks and SmolVLM captions on a scene built in code, with the frame cost of each: [hackbuild-browser-ai/vision](https://hackbuild.github.io/hackbuild-browser-ai/vision/).
|
|
60
|
+
|
|
61
|
+
## Concepts
|
|
62
|
+
|
|
63
|
+
### wire it once
|
|
64
|
+
|
|
65
|
+
Make one hub, attach the vision records, and provide the runtimes you use. In stub mode every capability answers from `visionStubs()` with no weights.
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
import { createHub, stubFactory } from "@hackbuild/models";
|
|
69
|
+
import { tjsProvider, loadTransformers } from "@hackbuild/devices";
|
|
70
|
+
import { attachVision, mediapipeProvider, loadTasksVision, visionStubs, depth, detect, landmarks, caption } from "@hackbuild/vision";
|
|
71
|
+
|
|
72
|
+
const tjs = tjsProvider({ runtime: loadTransformers() });
|
|
73
|
+
const hub = createHub({ env, stub: new URLSearchParams(location.search).has("stub") });
|
|
74
|
+
attachVision(hub, tjs); // records plus transformers.js loaders
|
|
75
|
+
hub.provide("tjs", tjs.factory);
|
|
76
|
+
hub.provide("mediapipe", mediapipeProvider({ runtime: loadTasksVision() }));
|
|
77
|
+
hub.provide("stub", stubFactory(visionStubs()));
|
|
78
|
+
|
|
79
|
+
const map = await depth(hub, imageOrCanvas); // 0 to 1, larger is nearer, plus the raw range
|
|
80
|
+
const boxes = await detect(hub, video, { scoreThreshold: 0.4 });
|
|
81
|
+
const face = await landmarks(hub, "face", video); // falls through the chain, face.failures says what failed
|
|
82
|
+
const line = await caption(hub, frame); // serialized on the vlm chain
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Each call routes through the hub (`use`, `run`, `release`), so WebGPU models take the gpu lock and idle models fall out under the budget. VLM calls also go through one serial chain. Landmarks walk a fallback chain of records: MediaPipe GPU, MediaPipe CPU (both rungs of one record), then any other record for the same capability, such as face-api.js. The MediaPipe provider loads one wasm fileset per page and creates one task per record, with the GPU delegate on a webgl rung and the CPU delegate on a wasm rung.
|
|
86
|
+
|
|
87
|
+
### sharing the GPU with a scene
|
|
88
|
+
|
|
89
|
+
Every call takes `schedule` (passed to `hub.run`: `minIntervalMs`, `idleOnly`, `frameBudgetMs`, `when: "skip"`) and `size` or `maxMB` to route to a smaller model. Report frame times with `hub.reportFrame(ms)` and show `hub.onBusy` in the UI:
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
hub.onBusy((n) => (pill.textContent = n ? "model busy" : ""));
|
|
93
|
+
await depth(hub, frame, { size: "tiny", schedule: { minIntervalMs: 1200, frameBudgetMs: 20, when: "skip" } });
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
The schedule alone did not hold the scene's frames on an Apple M1 in Chrome 150, even with `frameBudgetMs` 20 and `minIntervalMs` 200; the frame times are in the verified table below. Running the model in a worker did: `depthWorker({ urls: transformersUrls(), device })` loads transformers.js and Depth Anything V2 small (Apache-2.0) in a dedicated worker and takes RGBA pixels, so pre and post processing, the readback and the normalization leave the page's thread. Only models of the registered depth records load in the worker, at their pinned commit, since Depth Anything base and large carry CC-BY-NC-4.0 weights; pass `record` for another model with its licence named.
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
const w = await depthWorker({ urls: transformersUrls(), device: "webgpu" });
|
|
100
|
+
paint(await w.estimate(ctx2d.getImageData(0, 0, 512, 288)));
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
`readbackLoop({ read, onFrame, maxHz })` is the agent eye pattern: an async readback (`readRenderTargetPixelsAsync`), a busy flag that skips frames instead of queueing them, and a rate cap (default 10 Hz).
|
|
104
|
+
|
|
105
|
+
### loop and cache
|
|
106
|
+
|
|
107
|
+
`perceptionLoop({ step, interval })` runs one step at a time beside the render loop; `detectCadenceMs(latency)` waits max(0.45 s, 4 times the last latency). `ResultCache` keeps results by key so a depth map is computed once per image. `depthToRgba` and `fitSize` help with canvases.
|
|
108
|
+
|
|
109
|
+
### prompts and the embedding cache
|
|
110
|
+
|
|
111
|
+
`segment` takes points (label 1 object, 0 background), a box, or both; with no prompt it routes to the person segmenter. The image is encoded once and every later prompt on it decodes from the cached embedding. Pass a stable `key` (an image hash) and your own `EmbeddingCache` to see and drop what is kept:
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
const cache = new EmbeddingCache(4); // four images, least recently used out
|
|
115
|
+
const opts = { key: imageHash, cache };
|
|
116
|
+
const [m] = await segment(hub, img, { box: { x: 40, y: 30, w: 200, h: 160 } }, opts);
|
|
117
|
+
const [n] = await segment(hub, img, { points: [{ x: 90, y: 80 }, { x: 120, y: 90, label: 0 }] }, opts);
|
|
118
|
+
cache.hits; // 1, the second prompt did not encode
|
|
119
|
+
cache.delete(imageHash);
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
`promptSegmenter({ encode, decode })` builds the same cached segmenter around any encoder and decoder; scores come back clamped to 0 to 1.
|
|
123
|
+
|
|
124
|
+
### mask operations and export
|
|
125
|
+
|
|
126
|
+
Mask operations are functions on `Mask` (128 and up is inside): `maskUnion`, `maskIntersect`, `maskSubtract`, `maskInvert`, `maskThreshold`, `maskFeather(m, r)` (gaussian, sigma r / 2, soft edges), `maskDilate(m, r)` and `maskErode(m, r)` (a disc of radius r through an exact distance transform; the image border is not treated as outside), `maskLargestComponent(m, 8 | 4)` and `maskArea`.
|
|
127
|
+
|
|
128
|
+
Export: `maskToPng` (grey), `cutoutPng(pixels, mask)` (the image with the mask as alpha), `maskToSvg` (one even odd path along pixel edges, loops from `maskOutline`), `maskToRle` and `maskFromRle` (COCO style uncompressed run length, column major). `encodePng` deflates through CompressionStream where the runtime has it and writes stored blocks otherwise.
|
|
129
|
+
|
|
130
|
+
### perception signals and seen notes
|
|
131
|
+
|
|
132
|
+
`SignalTracker` turns per frame face and hand readings into steady signals and a few events: `arrived`, `left`, `smiled`, `gesture`. The clock comes in with each frame. Hands are optional; it runs on faces alone.
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
const tracker = new SignalTracker();
|
|
136
|
+
const notes = new SeenNotes();
|
|
137
|
+
const f = await landmarks(hub, "face", video, { timestamp: now });
|
|
138
|
+
const h = everyOther ? await landmarks(hub, "gesture", video, { timestamp: now }) : null;
|
|
139
|
+
for (const e of tracker.feed(rawFromLandmarks(f, h), now)) for (const r of reactionsFor(e, rng)) play(r);
|
|
140
|
+
const seen = notes.next(tracker.perception, wantsLook(text) ? await caption(hub, still) : null); // null when nothing changed
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
Thresholds are vendor figures, none measured here:
|
|
144
|
+
|
|
145
|
+
| threshold | value |
|
|
146
|
+
|---|---|
|
|
147
|
+
| presence grace | 2.5 s (vendor) |
|
|
148
|
+
| "left" after | 8 s (vendor) |
|
|
149
|
+
| "arrived" after time away | 20 s (vendor) |
|
|
150
|
+
| smile on, off, hold, cooldown | 0.55, 0.3, 500 ms, 10 s (vendor) |
|
|
151
|
+
| gesture hold, cooldown, score floor | 350 ms, 4 s, 0.6 (vendor) |
|
|
152
|
+
| wave | 2 wrist reversals inside 1.5 s above face level (vendor) |
|
|
153
|
+
| smile back reaction | after 600 ms at 0.7 chance (vendor) |
|
|
154
|
+
| `gazeTarget` gain | 1.3 (vendor) |
|
|
155
|
+
|
|
156
|
+
`DEFAULT_REACTIONS` is data, drawn from the injected rng. Frames never leave the tab; only the signals and the lowercase note do.
|
|
157
|
+
|
|
158
|
+
### yolo stays external
|
|
159
|
+
|
|
160
|
+
The YOLO decoder is written from the published output layout ([1, 84, 8400]); no Ultralytics code is used. YOLO is never registered by default: `yoloRecord({ url })` builds a record for a URL the app supplies, with a 640 letterbox and per class NMS at 0.45 keeping 13 boxes.
|
|
161
|
+
|
|
162
|
+
## API overview
|
|
163
|
+
|
|
164
|
+
| export | what it does |
|
|
165
|
+
|---|---|
|
|
166
|
+
| [`attachVision`](../../docs/api/vision/README.md#attachvision) | register the vision records and transformers.js loaders on a hub |
|
|
167
|
+
| [`depth`](../../docs/api/vision/README.md#depth) | a depth map, 0 to 1 with larger nearer |
|
|
168
|
+
| [`detect`](../../docs/api/vision/README.md#detect) | boxes with labels and scores |
|
|
169
|
+
| [`segment`](../../docs/api/vision/README.md#segment) | masks from points and a box, or a person mask |
|
|
170
|
+
| [`landmarks`](../../docs/api/vision/README.md#landmarks) | face, hand, pose or gesture landmarks through a fallback chain |
|
|
171
|
+
| [`caption`](../../docs/api/vision/README.md#caption) | a one sentence caption from a small VLM |
|
|
172
|
+
| [`ask`](../../docs/api/vision/README.md#ask) | a VLM's answer to a question about an image |
|
|
173
|
+
| [`mediapipeProvider`](../../docs/api/vision/README.md#mediapipeprovider) | the MediaPipe tasks-vision provider for the hub |
|
|
174
|
+
| [`depthWorker`](../../docs/api/vision/README.md#depthworker) | Depth Anything in a dedicated worker |
|
|
175
|
+
| [`perceptionLoop`](../../docs/api/vision/README.md#perceptionloop) | one perception step at a time beside a render loop |
|
|
176
|
+
| [`readbackLoop`](../../docs/api/vision/README.md#readbackloop) | rate capped async readback that skips frames while busy |
|
|
177
|
+
| [`ResultCache`](../../docs/api/vision/README.md#resultcache) | a small LRU of results by key |
|
|
178
|
+
| [`EmbeddingCache`](../../docs/api/vision/README.md#embeddingcache) | image embeddings kept for later prompts |
|
|
179
|
+
| [`maskUnion`](../../docs/api/vision/README.md#maskunion) | one of the mask operations; the rest sit beside it |
|
|
180
|
+
| [`cutoutPng`](../../docs/api/vision/README.md#cutoutpng) | the image with the mask as alpha, as a PNG |
|
|
181
|
+
| [`maskToSvg`](../../docs/api/vision/README.md#masktosvg) | the mask outline as an SVG path |
|
|
182
|
+
| [`maskToRle`](../../docs/api/vision/README.md#masktorle) | COCO style run length |
|
|
183
|
+
| [`SignalTracker`](../../docs/api/vision/README.md#signaltracker) | steady perception signals and events from face and hand frames |
|
|
184
|
+
| [`SeenNotes`](../../docs/api/vision/README.md#seennotes) | one lowercase line for a language model when the signals change |
|
|
185
|
+
| [`VISION_RECORDS`](../../docs/api/vision/README.md#vision_records) | the records `attachVision` registers |
|
|
186
|
+
| [`PICKER_RECORDS`](../../docs/api/vision/README.md#picker_records) | records for pickers, never registered by default |
|
|
187
|
+
| [`yoloRecord`](../../docs/api/vision/README.md#yolorecord) | an external YOLOv8n record for a URL you supply |
|
|
188
|
+
| [`visionStubs`](../../docs/api/vision/README.md#visionstubs) | weightless models for stub pages and tests |
|
|
189
|
+
|
|
190
|
+
The full reference is in [docs/api/vision](../../docs/api/vision/README.md).
|
|
191
|
+
|
|
192
|
+
## Models and weights
|
|
193
|
+
|
|
194
|
+
| capability | record | runtime | size | weight licence |
|
|
195
|
+
|---|---|---|---|---|
|
|
196
|
+
| depth | `depth-anything-v2-small` (`onnx-community/depth-anything-v2-small`) | transformers.js, fp16 then fp32 on webgpu, q8 then fp32 on wasm | 100 MB (inferred) | Apache-2.0 |
|
|
197
|
+
| detect | `efficientdet-lite0` (default) | MediaPipe, GPU then CPU delegate | 7 MB (inferred) | Apache-2.0 |
|
|
198
|
+
| detect | `yoloRecord({ url })`, optional and external | onnxruntime-web, 640 letterbox, per class NMS at 0.45, 13 boxes | unknown | AGPL-3.0 (Ultralytics), supplied by the app |
|
|
199
|
+
| segment (points) | `slimsam-77-uniform` (`Xenova/slimsam-77-uniform`) | transformers.js, one embedding per image | 38 MiB (vendor) | Apache-2.0 |
|
|
200
|
+
| segment.person | `selfie-segmenter` | MediaPipe | 1 MB (inferred) | Apache-2.0 |
|
|
201
|
+
| landmarks.face | `face-landmarker`, then `faceApiRecord(url)` | MediaPipe with blendshapes, then face-api.js tiny 68 points | 4 MB, 1 MB (inferred) | Apache-2.0; MIT |
|
|
202
|
+
| landmarks.hand, landmarks.pose | `hand-landmarker`, `pose-landmarker-lite` | MediaPipe | 8 MB, 6 MB (inferred) | Apache-2.0 |
|
|
203
|
+
| landmarks.gesture (optional) | `gesture-recognizer` | MediaPipe, hand points plus 7 canned gestures | 8 MB (inferred) | unknown, model card not checked |
|
|
204
|
+
| vision.caption, vision.ask | `smolvlm-256m-instruct` (`HuggingFaceTB/SmolVLM-256M-Instruct`) | transformers.js, per sub graph dtypes, repetition penalty 1.3 | 260 MB (inferred) | Apache-2.0 |
|
|
205
|
+
| vision.caption, vision.ask | `lfm2-vl-450m` (`onnx-community/LFM2-VL-450M-ONNX`) | transformers.js, q4f16 on webgpu only | 320 MB (inferred) | LFM Open License v1.0, commercial use limited by revenue |
|
|
206
|
+
|
|
207
|
+
MediaPipe models load from `MP_MODELS` (Google's MediaPipe model storage); transformers.js models load from the Hugging Face hub. Weights are never bundled; @hackbuild/weights caches the files read through it. `PICKER_RECORDS` lists models for pickers that no hub registers by default, so routing by capability keeps the small defaults above: SmolVLM 500M and SmolVLM2 256M video, Gemma 4 E2B, depth anything v2 base (CC-BY-NC-4.0) and v1 small, YOLOv10 nano, small and medium and FastSAM-s (AGPL-3.0 upstream), and the face swap set (scrfd 10g, ArcFace r50, inswapper 128; InsightFace, non-commercial). Their sizes are vendor figures from the Hugging Face file listings, taken without a download. A hub that runs one adds the record.
|
|
208
|
+
|
|
209
|
+
## Browser support
|
|
210
|
+
|
|
211
|
+
| feature | needs | Chrome | Safari | Firefox | phone |
|
|
212
|
+
|---|---|---|---|---|---|
|
|
213
|
+
| transformers.js models on WebGPU | a WebGPU adapter | yes, Chrome 150 on an Apple M1 (measured) | unknown | unknown | unknown |
|
|
214
|
+
| transformers.js models on WASM | WebAssembly | yes (inferred) | unknown | unknown | unknown |
|
|
215
|
+
| MediaPipe tasks | WebGL for the GPU delegate, wasm for the CPU one | yes (inferred) | unknown | unknown | unknown |
|
|
216
|
+
| LFM2-VL 450M | WebGPU, no wasm rung | yes, Chrome 150 on an Apple M1 (measured) | unknown | unknown | unknown |
|
|
217
|
+
| depth worker | a module or classic Worker | yes, Chrome 150 (measured) | unknown | unknown | unknown |
|
|
218
|
+
| threads | the probe's safe wasm thread count | from the probe | from the probe | from the probe | from the probe |
|
|
219
|
+
|
|
220
|
+
Without WebGPU the transformers.js ladders fall to wasm, and MediaPipe falls from the GPU delegate to the CPU one. LFM2-VL has no fallback.
|
|
221
|
+
|
|
222
|
+
## Errors and troubleshooting
|
|
223
|
+
|
|
224
|
+
| message | cause | what to do |
|
|
225
|
+
|---|---|---|
|
|
226
|
+
| `no face landmark model loaded: ID (ERROR); ...` | every record in the landmark chain failed; `failures` lists each | read `failures`; add `faceApiRecord(url)` as a fallback, or check the provider is registered |
|
|
227
|
+
| `maskUnion: masks are W x H and W2 x H2` (and the other two mask operations) | masks of different sizes | resize one mask to the other first |
|
|
228
|
+
| `cutoutRgba: image is W x H, mask W2 x H2` | image and mask differ in size | pass the mask made from this image |
|
|
229
|
+
| `encodePng: N bytes for W x H x C` | data shorter than width times height times channels | pass the full buffer |
|
|
230
|
+
| `maskFromRle: counts cover N pixels of M` | the run length does not match its size | check `size` is `[height, width]` |
|
|
231
|
+
| `a prompt needs at least one point or a box` | a prompted segmenter got an empty prompt | pass points or a box, or call `segment` with no prompt for a person mask |
|
|
232
|
+
| `ID: no mediapipe task for CAPABILITY` | the record's capability has no MediaPipe task | use detect, segment.person or a landmarks capability |
|
|
233
|
+
| `ID: a mediapipe record needs source.url` | the record names no model file | set `source.url` |
|
|
234
|
+
| `the transformers.js module has none of NAMES` | the runtime lacks the model class | use the pinned transformers.js 4.3.2 |
|
|
235
|
+
| `depth pipeline returned neither predicted_depth nor depth` | the pipeline gave another output | use a depth-estimation model |
|
|
236
|
+
| `depth worker: ID is not a registered depth record; pass record with its licence named` | `modelId` is not one of the depth records | pass `record` with its licence |
|
|
237
|
+
| `depth worker is not loaded` / `no transformers.js url loaded` | the worker could not import transformers.js | check the `urls`; use `transformersUrls()` |
|
|
238
|
+
|
|
239
|
+
## Works with
|
|
240
|
+
|
|
241
|
+
- [@hackbuild/models](../models/README.md) is the hub every call routes through.
|
|
242
|
+
- [@hackbuild/devices](../devices/README.md) gives the transformers.js and ort providers and the pinned runtime loaders.
|
|
243
|
+
- [@hackbuild/weights](../weights/README.md) caches the weights the providers read.
|
|
244
|
+
- [@hackbuild/depth-mesh](../depth-mesh/README.md) turns a depth map or a mask into a relief solid you can print.
|
|
245
|
+
- [@hackbuild/media](../media/README.md) picks keyframes from a video for `caption`.
|
|
246
|
+
|
|
247
|
+
## Changelog and licences
|
|
248
|
+
|
|
249
|
+
Changes are in the repository [CHANGELOG](../../CHANGELOG.md). Code is MIT ([LICENSE](../../LICENSE)); this README is CC-BY-4.0 with its code samples also MIT. Weight licences: Depth Anything V2 small, MediaPipe models, SlimSAM and SmolVLM, Apache-2.0; face-api.js tiny nets, MIT; LFM2-VL, LFM Open License v1.0; YOLO, AGPL-3.0 (external, supplied by the app); the gesture recognizer, unknown.
|
|
142
250
|
|
|
143
251
|
## What is verified, and what is not
|
|
144
252
|
|
|
@@ -146,52 +254,23 @@ signals and the lowercase note do.
|
|
|
146
254
|
|
|
147
255
|
### Verified on this machine
|
|
148
256
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
hands and blendshapes, the face fallback to face-api.js after the
|
|
156
|
-
MediaPipe record fails, YOLO letterbox, decode and NMS, an external YOLO
|
|
157
|
-
record through an ort model, VLM questions serialized on one chain,
|
|
158
|
-
SlimSAM embedding an image once for several prompts, the loop's busy
|
|
159
|
-
guard and interval, the LRU cache, schedule options reaching the hub
|
|
160
|
-
(interval wait, skip, frame budget skip) with routing to a smaller
|
|
161
|
-
model and busy reports, and the readback loop's rate cap and busy
|
|
162
|
-
skips.
|
|
163
|
-
|
|
164
|
-
- 2026-11-23, Chrome 150 on an Apple M1, the vision page (#35): the
|
|
165
|
-
scene alone at 16.7 / 18.3 ms frame p50 / p95; depth on the main thread
|
|
166
|
-
16.7 / 49.9 unscheduled and 16.7 / 49.8 with the frame budget; depth in
|
|
167
|
-
the worker on webgpu 16.7 / 18.3 (22 runs in 6 s, 280 ms p50), with a
|
|
168
|
-
200 ms gap 16.7 / 18.3, on wasm 16.7 / 18.2 (4,664 ms per run); no main
|
|
169
|
-
thread task over 50 ms in any mode (measured). Unit tests run the worker
|
|
170
|
-
source on the inline rung with a fake transformers.js module.
|
|
171
|
-
- 2026-11-23: LFM2-VL 450M (LFM Open License v1.0) loads and captions on
|
|
172
|
-
webgpu after the images first processor fix: load 8,743 ms, caption
|
|
173
|
-
4,671 ms, the caption names the cube and the scene (measured).
|
|
174
|
-
|
|
175
|
-
- 2026-11-24: `npx vitest run packages/vision` passes 30 tests: one
|
|
176
|
-
encode for point, negative point and box prompts on one image, shared
|
|
177
|
-
encodes in flight, failed encodes dropped, least recently used
|
|
178
|
-
eviction, SlimSAM fed `input_boxes` and negative labels from one
|
|
179
|
-
embedding, a box prompt routed through the hub to the stub, union,
|
|
180
|
-
subtract, invert, a radius 3 dilate giving 29 pixels (computed),
|
|
181
|
-
erode keeping the border, feather, largest piece at 4 and 8
|
|
182
|
-
connectivity, PNG grey and alpha read back through zlib, the SVG
|
|
183
|
-
outline of a square and a ring, and the run length round trip.
|
|
257
|
+
| date | check | result |
|
|
258
|
+
|---|---|---|
|
|
259
|
+
| 2026-11-22 | `npx vitest run packages/vision` under Node 22.18.0 with fake runtimes: licences on every record and YOLO kept external, every capability in stub mode, depth normalization from predicted_depth and from the 8 bit image, the depth record walking fp16 to fp32 through the transformers.js provider, the MediaPipe provider falling from the GPU to the CPU delegate and mapping detections, masks, hands and blendshapes, the face fallback to face-api.js after the MediaPipe record fails, YOLO letterbox, decode and NMS, an external YOLO record through an ort model, VLM questions serialized on one chain, SlimSAM embedding an image once for several prompts, the loop's busy guard and interval, the LRU cache, schedule options reaching the hub (interval wait, skip, frame budget skip) with routing to a smaller model and busy reports, and the readback loop's rate cap and busy skips | passes 15 tests (19 on 2026-11-23) |
|
|
260
|
+
| 2026-11-23 | Chrome 150 on an Apple M1, the vision page (#35), frame p50 / p95 beside depth; unit tests run the worker source on the inline rung with a fake transformers.js module | scene alone 16.7 / 18.3 ms; depth on the main thread 16.7 / 49.9 unscheduled and 16.7 / 49.8 with the frame budget; depth in the worker on webgpu 16.7 / 18.3 (22 runs in 6 s, 280 ms p50), with a 200 ms gap 16.7 / 18.3, on wasm 16.7 / 18.2 (4,664 ms per run); no main thread task over 50 ms in any mode (measured) |
|
|
261
|
+
| 2026-11-23 | LFM2-VL 450M (LFM Open License v1.0) loads and captions on webgpu after the images first processor fix | load 8,743 ms, caption 4,671 ms, the caption names the cube and the scene (measured) |
|
|
262
|
+
| 2026-11-24 | `npx vitest run packages/vision`: one encode for point, negative point and box prompts on one image, shared encodes in flight, failed encodes dropped, least recently used eviction, SlimSAM fed `input_boxes` and negative labels from one embedding, a box prompt routed through the hub to the stub, union, subtract, invert, a radius 3 dilate, erode keeping the border, feather, largest piece at 4 and 8 connectivity, PNG grey and alpha read back through zlib, the SVG outline of a square and a ring, and the run length round trip | passes 30 tests; the radius 3 dilate gives 29 pixels (computed) |
|
|
184
263
|
|
|
185
264
|
### Not verified by anything
|
|
186
265
|
|
|
187
|
-
- Any model in a browser: tasks-vision 1.2.3
|
|
266
|
+
- Any model in a browser beyond the automated pass: tasks-vision 1.2.3 task
|
|
188
267
|
options and result shapes, transformers.js 4.3.2 SmolVLM, LFM2-VL and
|
|
189
268
|
SlimSAM class names and processor calls (box prompts through
|
|
190
269
|
`input_boxes` included), a real YOLOv8n export's output
|
|
191
270
|
name and layout.
|
|
192
271
|
- FastSAM: not built. Its weights are AGPL-3.0 and its mask decoder is
|
|
193
272
|
not written; SlimSAM covers point prompts.
|
|
194
|
-
- Accuracy and speed of every model
|
|
273
|
+
- Accuracy and speed of every model: no numbers taken.
|
|
195
274
|
- Whether the frame budget and idle waits remove stutter in a real scene
|
|
196
275
|
(needs a person looking at real frame rate).
|
|
197
276
|
|
|
@@ -199,8 +278,8 @@ signals and the lowercase note do.
|
|
|
199
278
|
|
|
200
279
|
| file | gzip (measured) | ceiling |
|
|
201
280
|
|---|---|---|
|
|
202
|
-
| `dist/index.js` (main entry, imports external) | 23,
|
|
203
|
-
| `dist/single/index.iife.js` (single file build) |
|
|
281
|
+
| `dist/index.js` (main entry, imports external) | 23,813 bytes | 25,003 bytes |
|
|
282
|
+
| `dist/single/index.iife.js` (single file build) | 54,219 bytes | 56,929 bytes |
|
|
204
283
|
|
|
205
284
|
Measured 2026-11-25 by `node tools/lint-packages.mjs` (gzip level 9) from the packed
|
|
206
285
|
tarball. Generated from `tools/size-budget.json`; CI fails when a file moves more than
|
package/dist/api.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The vision calls. Each routes through the hub (`use`, `run`, `release`),
|
|
3
3
|
* so webgpu models take the gpu lock and idle models fall out under the
|
|
4
|
-
* budget. VLM calls also go through one serial chain
|
|
4
|
+
* budget. VLM calls also go through one serial chain.
|
|
5
5
|
* Landmarks walk a fallback chain of records: MediaPipe GPU, MediaPipe
|
|
6
6
|
* CPU (both rungs of one record), then any other record for the same
|
|
7
7
|
* capability, such as face-api.js.
|
|
@@ -11,6 +11,7 @@ import type { Hub, ModelRecord, RunOptions, SizeClass } from "@hackbuild/models"
|
|
|
11
11
|
import type { DepthMap, Detection, ImageInput, LandmarkKind, Landmarks, Mask, Pixels, SegmentOptions, SegmentPrompt } from "./types.js";
|
|
12
12
|
/** Add the vision records and register the transformers.js loaders. MediaPipe and ort factories are provided by the app. */
|
|
13
13
|
export declare function attachVision(hub: Hub, tjs?: TjsProvider): void;
|
|
14
|
+
/** Options for each vision call: a record id, a size class or MB cap to route to a smaller model, an abort signal and the hub's scheduling. */
|
|
14
15
|
export interface CallOptions {
|
|
15
16
|
/** A record id instead of routing by capability. */
|
|
16
17
|
model?: string;
|
|
@@ -21,7 +22,9 @@ export interface CallOptions {
|
|
|
21
22
|
/** Scheduling around rendering: minimum interval, idle only, frame time budget, wait or skip (see the models hub). */
|
|
22
23
|
schedule?: RunOptions;
|
|
23
24
|
}
|
|
25
|
+
/** A depth map of an image from the routed depth model (Depth Anything V2 small by default), loaded and released through the hub. */
|
|
24
26
|
export declare function depth(hub: Hub, image: ImageInput, o?: CallOptions): Promise<DepthMap>;
|
|
27
|
+
/** Objects in an image from the routed detector (MediaPipe EfficientDet by default, or a YOLO ort model), loaded and released through the hub. */
|
|
25
28
|
export declare function detect(hub: Hub, image: ImageInput, o?: CallOptions & {
|
|
26
29
|
scoreThreshold?: number;
|
|
27
30
|
maxResults?: number;
|
|
@@ -50,6 +53,7 @@ export declare function landmarks(hub: Hub, kind: LandmarkKind, image: ImageInpu
|
|
|
50
53
|
export declare function caption(hub: Hub, image: ImageInput, o?: CallOptions & {
|
|
51
54
|
maxTokens?: number;
|
|
52
55
|
}): Promise<string>;
|
|
56
|
+
/** Answer a question about an image with the routed vision language model. VLM calls are serialized on one chain. */
|
|
53
57
|
export declare function ask(hub: Hub, image: ImageInput, question: string, o?: CallOptions & {
|
|
54
58
|
maxTokens?: number;
|
|
55
59
|
}): Promise<string>;
|
package/dist/api.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The vision calls. Each routes through the hub (`use`, `run`, `release`),
|
|
3
3
|
* so webgpu models take the gpu lock and idle models fall out under the
|
|
4
|
-
* budget. VLM calls also go through one serial chain
|
|
4
|
+
* budget. VLM calls also go through one serial chain.
|
|
5
5
|
* Landmarks walk a fallback chain of records: MediaPipe GPU, MediaPipe
|
|
6
6
|
* CPU (both rungs of one record), then any other record for the same
|
|
7
7
|
* capability, such as face-api.js.
|
|
@@ -40,6 +40,7 @@ async function withModel(hub, what, fn, o = {}) {
|
|
|
40
40
|
}
|
|
41
41
|
}
|
|
42
42
|
const target = (cap, o) => (o.model ? { id: o.model } : cap);
|
|
43
|
+
/** A depth map of an image from the routed depth model (Depth Anything V2 small by default), loaded and released through the hub. */
|
|
43
44
|
export function depth(hub, image, o = {}) {
|
|
44
45
|
return withModel(hub, target("depth", o), (m) => m.estimate(image), o);
|
|
45
46
|
}
|
|
@@ -48,6 +49,7 @@ function asDetector(v, toPixels) {
|
|
|
48
49
|
return yoloDetector(v, toPixels ? { toPixels } : {});
|
|
49
50
|
return v;
|
|
50
51
|
}
|
|
52
|
+
/** Objects in an image from the routed detector (MediaPipe EfficientDet by default, or a YOLO ort model), loaded and released through the hub. */
|
|
51
53
|
export function detect(hub, image, o = {}) {
|
|
52
54
|
const opts = {};
|
|
53
55
|
if (o.scoreThreshold !== undefined)
|
|
@@ -104,6 +106,7 @@ export async function landmarks(hub, kind, image, o = {}) {
|
|
|
104
106
|
export function caption(hub, image, o = {}) {
|
|
105
107
|
return hub.chain("vlm")(() => withModel(hub, target("vision.caption", o), (m) => m.ask(image, undefined, o.maxTokens ? { maxTokens: o.maxTokens } : {}), o));
|
|
106
108
|
}
|
|
109
|
+
/** Answer a question about an image with the routed vision language model. VLM calls are serialized on one chain. */
|
|
107
110
|
export function ask(hub, image, question, o = {}) {
|
|
108
111
|
return hub.chain("vlm")(() => withModel(hub, target("vision.ask", o), (m) => m.ask(image, question, o.maxTokens ? { maxTokens: o.maxTokens } : {}), o));
|
|
109
112
|
}
|
package/dist/faceapi.d.ts
CHANGED
|
@@ -32,6 +32,7 @@ export interface FaceApi {
|
|
|
32
32
|
}[]>;
|
|
33
33
|
};
|
|
34
34
|
}
|
|
35
|
+
/** The face-api.js provider for the models hub: the tiny face detector and 68 point tiny landmark net, as a face {@link Landmarker}. */
|
|
35
36
|
export declare function faceApiProvider(opts: {
|
|
36
37
|
runtime: () => Promise<FaceApi>;
|
|
37
38
|
}): Factory<Landmarker>;
|
package/dist/faceapi.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* landmark net, on the wasm or cpu backend (FaceSwap forced wasm). Points
|
|
5
5
|
* come back normalized to the image like MediaPipe's.
|
|
6
6
|
*/
|
|
7
|
+
/** The face-api.js provider for the models hub: the tiny face detector and 68 point tiny landmark net, as a face {@link Landmarker}. */
|
|
7
8
|
export function faceApiProvider(opts) {
|
|
8
9
|
return async ({ record }) => {
|
|
9
10
|
const fa = await opts.runtime();
|
package/dist/loaders.d.ts
CHANGED
|
@@ -16,12 +16,14 @@ interface RawImageLike {
|
|
|
16
16
|
channels?: number;
|
|
17
17
|
data: ArrayLike<number>;
|
|
18
18
|
}
|
|
19
|
-
/** Normalize a depth pipeline result. predicted_depth keeps the raw range
|
|
19
|
+
/** Normalize a depth pipeline result. predicted_depth keeps the raw range; depth is the 8 bit image. */
|
|
20
20
|
export declare function depthFromOutput(out: {
|
|
21
21
|
predicted_depth?: TensorLike;
|
|
22
22
|
depth?: RawImageLike;
|
|
23
23
|
}): DepthMap;
|
|
24
|
+
/** The transformers.js loader for depth records: a depth-estimation pipeline wrapped as a {@link DepthModel}. */
|
|
24
25
|
export declare function depthLoader(ctx: TjsLoadContext): Promise<DepthModel>;
|
|
26
|
+
/** The transformers.js loader for caption and question records: the VLM's processor and model wrapped as a {@link Vlm}. */
|
|
25
27
|
export declare function vlmLoader(ctx: TjsLoadContext): Promise<Vlm>;
|
|
26
28
|
/** SlimSAM: one embedding per image, kept in an `EmbeddingCache`, then point, negative point and box prompts. */
|
|
27
29
|
export declare function samLoader(ctx: TjsLoadContext): Promise<Segmenter>;
|
package/dist/loaders.js
CHANGED
|
@@ -14,7 +14,7 @@ async function toRaw(tjs, img) {
|
|
|
14
14
|
const R = tjs.RawImage;
|
|
15
15
|
return R?.read ? R.read(img) : img;
|
|
16
16
|
}
|
|
17
|
-
/** Normalize a depth pipeline result. predicted_depth keeps the raw range
|
|
17
|
+
/** Normalize a depth pipeline result. predicted_depth keeps the raw range; depth is the 8 bit image. */
|
|
18
18
|
export function depthFromOutput(out) {
|
|
19
19
|
const pd = out.predicted_depth;
|
|
20
20
|
if (pd && pd.data && pd.dims?.length >= 2) {
|
|
@@ -44,6 +44,7 @@ export function depthFromOutput(out) {
|
|
|
44
44
|
data[i] = d.data[i * ch] / 255;
|
|
45
45
|
return { width: d.width, height: d.height, data, range: [0, 255] };
|
|
46
46
|
}
|
|
47
|
+
/** The transformers.js loader for depth records: a depth-estimation pipeline wrapped as a {@link DepthModel}. */
|
|
47
48
|
export async function depthLoader(ctx) {
|
|
48
49
|
const pipe = (await ctx.tjs.pipeline("depth-estimation", ctx.record.source.modelId, ctx.options));
|
|
49
50
|
return {
|
|
@@ -51,6 +52,7 @@ export async function depthLoader(ctx) {
|
|
|
51
52
|
dispose: () => pipe.dispose?.(),
|
|
52
53
|
};
|
|
53
54
|
}
|
|
55
|
+
/** The transformers.js loader for caption and question records: the VLM's processor and model wrapped as a {@link Vlm}. */
|
|
54
56
|
export async function vlmLoader(ctx) {
|
|
55
57
|
const id = ctx.record.source.modelId;
|
|
56
58
|
const processor = (await cls(ctx.tjs, "AutoProcessor").from_pretrained(id));
|