@hackbuild/vision 0.1.1 → 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 CHANGED
@@ -1,136 +1,252 @@
1
1
  # @hackbuild/vision
2
2
 
3
- Perception through the `@hackbuild/models` hub: depth, detection,
4
- segmentation, face, hand and pose landmarks with a fallback chain, and
5
- captions and questions through small VLMs, plus a webcam loop helper and
6
- a result cache. Code MIT; this README CC-BY-4.0 with the code samples
7
- also MIT. No weights ship here.
8
-
9
- # not on npm yet: the @hackbuild scope is unpublished; build from this repository
10
- npm install @hackbuild/vision
11
-
12
- ## Wire it once
13
-
14
- import { createHub, stubFactory } from "@hackbuild/models";
15
- import { tjsProvider, loadTransformers } from "@hackbuild/devices";
16
- import { attachVision, mediapipeProvider, loadTasksVision, visionStubs, depth, detect, landmarks, caption } from "@hackbuild/vision";
17
-
18
- const tjs = tjsProvider({ runtime: loadTransformers() });
19
- const hub = createHub({ env, stub: new URLSearchParams(location.search).has("stub") });
20
- attachVision(hub, tjs); // records plus transformers.js loaders
21
- hub.provide("tjs", tjs.factory);
22
- hub.provide("mediapipe", mediapipeProvider({ runtime: loadTasksVision() }));
23
- hub.provide("stub", stubFactory(visionStubs()));
24
-
25
- const map = await depth(hub, imageOrCanvas); // 0 to 1, larger is nearer, plus the raw range
26
- const boxes = await detect(hub, video, { scoreThreshold: 0.4 });
27
- const face = await landmarks(hub, "face", video); // falls through the chain, face.failures says what failed
28
- const line = await caption(hub, frame); // serialized on the vlm chain
29
-
30
- ## Models
31
-
32
- | capability | record | runtime | weight licence |
33
- |---|---|---|---|
34
- | depth | depth-anything-v2-small | transformers.js, fp16 then fp32 on webgpu, q8 then fp32 on wasm (as earlier builds did) | Apache-2.0 |
35
- | detect | efficientdet-lite0 (default) | MediaPipe, GPU then CPU delegate | Apache-2.0 |
36
- | detect | `yoloRecord({ url })`, optional and external | onnxruntime-web, 640 letterbox, per class NMS at 0.45, 13 boxes (as earlier builds did) | AGPL-3.0 (Ultralytics), supplied by the app |
37
- | segment (points) | slimsam-77-uniform | transformers.js, one embedding per image | Apache-2.0 |
38
- | segment.person | selfie-segmenter | MediaPipe | Apache-2.0 |
39
- | landmarks.face | face-landmarker, then `faceApiRecord(url)` | MediaPipe with blendshapes, then face-api.js tiny 68 points | Apache-2.0; MIT |
40
- | landmarks.hand, landmarks.pose | hand-landmarker, pose-landmarker-lite | MediaPipe | Apache-2.0 |
41
- | landmarks.gesture (optional) | gesture-recognizer | MediaPipe, hand points plus 7 canned gestures | unknown, model card not checked |
42
- | vision.caption, vision.ask | smolvlm-256m-instruct | transformers.js, per sub graph dtypes, repetition penalty 1.3 | Apache-2.0 |
43
- | vision.caption, vision.ask | lfm2-vl-450m | transformers.js, q4f16 on webgpu only (as earlier builds did) | LFM Open License v1.0, commercial use limited by revenue |
44
-
45
- The YOLO decoder is written from the published output layout
46
- ([1, 84, 8400]); no Ultralytics code is used. YOLO is never registered by
47
- default.
48
-
49
- ## Sharing the GPU with a scene
50
-
51
- Every call takes `schedule` (passed to `hub.run`: `minIntervalMs`,
52
- `idleOnly`, `frameBudgetMs`, `when: "skip"`) and `size` or `maxMB` to
53
- route to a smaller model. Report frame times with `hub.reportFrame(ms)`
54
- and show `hub.onBusy` in the UI:
55
-
56
- hub.onBusy((n) => (pill.textContent = n ? "model busy" : ""));
57
- await depth(hub, frame, { size: "tiny", schedule: { minIntervalMs: 1200, frameBudgetMs: 20, when: "skip" } });
58
-
59
- The schedule alone did not hold the scene's frames on an Apple M1: with
60
- `frameBudgetMs` 20 and `minIntervalMs` 200 the frame p95 stayed at 49.8
61
- ms with no main thread task over 50 ms (measured, Chrome 150). Running
62
- the model in a worker did: `depthWorker({ urls: transformersUrls(),
63
- device })` loads transformers.js and Depth Anything V2 small (Apache-2.0)
64
- in a dedicated worker and takes RGBA pixels, so pre and post processing,
65
- the readback and the normalization leave the page's thread:
66
-
67
- const w = await depthWorker({ urls: transformersUrls(), device: "webgpu" });
68
- paint(await w.estimate(ctx2d.getImageData(0, 0, 512, 288)));
69
-
70
- `readbackLoop({ read, onFrame, maxHz })` is the agent eye pattern: an
71
- async readback (`readRenderTargetPixelsAsync`), a busy flag that skips
72
- frames instead of queueing them, and a rate cap (default 10 Hz).
73
-
74
- ## Loop and cache
75
-
76
- `perceptionLoop({ step, interval })` runs one step at a time beside the
77
- render loop; `detectCadenceMs(latency)` is the earlier scene app's max(0.45 s, 4 times
78
- the last latency). `ResultCache` keeps results by key so a depth map is
79
- computed once per image (as earlier builds did). `depthToRgba` and `fitSize` (as earlier builds did) help with canvases.
80
-
81
- ## Prompts, the embedding cache, mask operations and export
82
-
83
- `segment` takes points (label 1 object, 0 background), a box, or both.
84
- The image is encoded once and every later prompt on it decodes from the
85
- cached embedding. Pass a stable `key` (an image hash) and your own
86
- `EmbeddingCache` to see and drop what is kept:
87
-
88
- const cache = new EmbeddingCache(4); // four images, least recently used out
89
- const opts = { key: imageHash, cache };
90
- const [m] = await segment(hub, img, { box: { x: 40, y: 30, w: 200, h: 160 } }, opts);
91
- const [n] = await segment(hub, img, { points: [{ x: 90, y: 80 }, { x: 120, y: 90, label: 0 }] }, opts);
92
- cache.hits; // 1, the second prompt did not encode
93
- cache.delete(imageHash);
94
-
95
- `promptSegmenter({ encode, decode })` builds the same cached segmenter
96
- around any encoder and decoder; scores come back clamped to 0 to 1.
97
-
98
- Mask operations are functions on `Mask` (128 and up is inside):
99
- `maskUnion`, `maskIntersect`, `maskSubtract`, `maskInvert`,
100
- `maskThreshold`, `maskFeather(m, r)` (gaussian, sigma r / 2, soft edges),
101
- `maskDilate(m, r)` and `maskErode(m, r)` (a disc of radius r through an
102
- exact distance transform; the image border is not treated as outside),
103
- `maskLargestComponent(m, 8 | 4)` and `maskArea`.
104
-
105
- Export: `maskToPng` (grey), `cutoutPng(pixels, mask)` (the image with
106
- the mask as alpha), `maskToSvg` (one even odd path along pixel edges,
107
- loops from `maskOutline`), `maskToRle` and `maskFromRle` (COCO style
108
- uncompressed run length, column major). `encodePng` deflates through
109
- CompressionStream where the runtime has it and writes stored blocks
110
- otherwise.
111
-
112
- ## Perception signals and seen notes
113
-
114
- `SignalTracker` turns per frame face and hand readings into steady
115
- signals and a few events: `arrived`, `left`, `smiled`, `gesture`. The
116
- clock comes in with each frame. Hands are optional; it runs on faces
117
- alone.
118
-
119
- const tracker = new SignalTracker();
120
- const notes = new SeenNotes();
121
- const f = await landmarks(hub, "face", video, { timestamp: now });
122
- const h = everyOther ? await landmarks(hub, "gesture", video, { timestamp: now }) : null;
123
- for (const e of tracker.feed(rawFromLandmarks(f, h), now)) for (const r of reactionsFor(e, rng)) play(r);
124
- const seen = notes.next(tracker.perception, wantsLook(text) ? await caption(hub, still) : null); // null when nothing changed
125
-
126
- Thresholds are vendor figures from earlier builds, none measured here:
127
- presence grace 2.5 s, "left" after 8 s, "arrived" after 20 s away, smile
128
- on at 0.55 and off at 0.3 held 500 ms with a 10 s cooldown, gestures held
129
- 350 ms with a 4 s cooldown and a 0.6 score floor, a wave as 2 wrist
130
- reversals inside 1.5 s above face level. `DEFAULT_REACTIONS` is data
131
- (smile back after 600 ms at 0.7 chance, drawn from the injected rng);
132
- `gazeTarget` applies a gain of 1.3. Frames never leave the tab; only the
133
- signals and the lowercase note do.
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
+ [![npm](https://img.shields.io/npm/v/@hackbuild/vision)](https://www.npmjs.com/package/@hackbuild/vision) [![licence MIT](https://img.shields.io/badge/licence-MIT-blue)](../../LICENSE) ![gzip 23.8 kB measured](https://img.shields.io/badge/gzip-23.8%20kB-blue) ![types included](https://img.shields.io/badge/types-included-blue)
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.
134
250
 
135
251
  ## What is verified, and what is not
136
252
 
@@ -138,52 +254,23 @@ signals and the lowercase note do.
138
254
 
139
255
  ### Verified on this machine
140
256
 
141
- - 2026-11-22: `npx vitest run packages/vision` passes 15 tests (19 on 2026-11-23) under Node
142
- 22.18.0 with fake runtimes: licences on every record and YOLO kept
143
- external, every capability in stub mode, depth normalization from
144
- predicted_depth and from the 8 bit image, the depth record walking fp16
145
- to fp32 through the transformers.js provider, the MediaPipe provider
146
- falling from the GPU to the CPU delegate and mapping detections, masks,
147
- hands and blendshapes, the face fallback to face-api.js after the
148
- MediaPipe record fails, YOLO letterbox, decode and NMS, an external YOLO
149
- record through an ort model, VLM questions serialized on one chain,
150
- SlimSAM embedding an image once for several prompts, the loop's busy
151
- guard and interval, the LRU cache, schedule options reaching the hub
152
- (interval wait, skip, frame budget skip) with routing to a smaller
153
- model and busy reports, and the readback loop's rate cap and busy
154
- skips.
155
-
156
- - 2026-11-23, Chrome 150 on an Apple M1, the vision page (#35): the
157
- scene alone at 16.7 / 18.3 ms frame p50 / p95; depth on the main thread
158
- 16.7 / 49.9 unscheduled and 16.7 / 49.8 with the frame budget; depth in
159
- the worker on webgpu 16.7 / 18.3 (22 runs in 6 s, 280 ms p50), with a
160
- 200 ms gap 16.7 / 18.3, on wasm 16.7 / 18.2 (4,664 ms per run); no main
161
- thread task over 50 ms in any mode (measured). Unit tests run the worker
162
- source on the inline rung with a fake transformers.js module.
163
- - 2026-11-23: LFM2-VL 450M (LFM Open License v1.0) loads and captions on
164
- webgpu after the images first processor fix: load 8,743 ms, caption
165
- 4,671 ms, the caption names the cube and the scene (measured).
166
-
167
- - 2026-11-24: `npx vitest run packages/vision` passes 30 tests: one
168
- encode for point, negative point and box prompts on one image, shared
169
- encodes in flight, failed encodes dropped, least recently used
170
- eviction, SlimSAM fed `input_boxes` and negative labels from one
171
- embedding, a box prompt routed through the hub to the stub, union,
172
- subtract, invert, a radius 3 dilate giving 29 pixels (computed),
173
- erode keeping the border, feather, largest piece at 4 and 8
174
- connectivity, PNG grey and alpha read back through zlib, the SVG
175
- 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) |
176
263
 
177
264
  ### Not verified by anything
178
265
 
179
- - Any model in a browser: tasks-vision 1.2.3 (as earlier builds did) task
266
+ - Any model in a browser beyond the automated pass: tasks-vision 1.2.3 task
180
267
  options and result shapes, transformers.js 4.3.2 SmolVLM, LFM2-VL and
181
268
  SlimSAM class names and processor calls (box prompts through
182
269
  `input_boxes` included), a real YOLOv8n export's output
183
270
  name and layout.
184
271
  - FastSAM: not built. Its weights are AGPL-3.0 and its mask decoder is
185
272
  not written; SlimSAM covers point prompts.
186
- - Accuracy and speed of every model (no numbers measured).
273
+ - Accuracy and speed of every model: no numbers taken.
187
274
  - Whether the frame budget and idle waits remove stutter in a real scene
188
275
  (needs a person looking at real frame rate).
189
276
 
@@ -191,9 +278,9 @@ signals and the lowercase note do.
191
278
 
192
279
  | file | gzip (measured) | ceiling |
193
280
  |---|---|---|
194
- | `dist/index.js` (main entry, imports external) | 21,326 bytes | 22,392 bytes |
195
- | `dist/single/index.iife.js` (single file build) | 51,302 bytes | 53,867 bytes |
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 |
196
283
 
197
- Measured 2026-11-24 by `node tools/lint-packages.mjs` (gzip level 9) from the packed
284
+ Measured 2026-11-25 by `node tools/lint-packages.mjs` (gzip level 9) from the packed
198
285
  tarball. Generated from `tools/size-budget.json`; CI fails when a file moves more than
199
286
  5 percent from its row.
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 (as earlier builds did).
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 (as earlier builds did).
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/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export type { ImageInput, Pixels, DepthMap, DepthModel, Box, Detection, Detector, Mask, SegmentPrompt, SegmentOptions, Segmenter, LandmarkKind, Landmarks, Landmarker, Vlm, } from "./types.js";
2
- export { VISION_RECORDS, MP_MODELS, mediapipeLadder, faceApiRecord, yoloRecord } from "./records.js";
2
+ export { VISION_RECORDS, PICKER_RECORDS, MP_MODELS, mediapipeLadder, faceApiRecord, yoloRecord } from "./records.js";
3
3
  export { attachVision, depth, detect, segment, landmarks, landmarkChain, caption, ask, type CallOptions } from "./api.js";
4
4
  export { depthLoader, vlmLoader, samLoader, depthFromOutput } from "./loaders.js";
5
5
  export { mediapipeProvider, loadTasksVision, tasksVisionUrls, tasksVisionWasm, TASKS_VISION, type TasksVision, type MediapipeProviderOptions } from "./mediapipe.js";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { VISION_RECORDS, MP_MODELS, mediapipeLadder, faceApiRecord, yoloRecord } from "./records.js";
1
+ export { VISION_RECORDS, PICKER_RECORDS, MP_MODELS, mediapipeLadder, faceApiRecord, yoloRecord } from "./records.js";
2
2
  export { attachVision, depth, detect, segment, landmarks, landmarkChain, caption, ask } from "./api.js";
3
3
  export { depthLoader, vlmLoader, samLoader, depthFromOutput } from "./loaders.js";
4
4
  export { mediapipeProvider, loadTasksVision, tasksVisionUrls, tasksVisionWasm, TASKS_VISION } from "./mediapipe.js";
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 (as earlier builds did); depth is the 8 bit image (as earlier builds did). */
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>;