@hackbuild/vision 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Moheeb Zara
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,199 @@
1
- # Temporary Holding Version
1
+ # @hackbuild/vision
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
+ 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.
134
+
135
+ ## What is verified, and what is not
136
+
137
+ - Signals: the tracker's rules (noise, smile hold and cooldown, presence grace, left and arrived, wave and low hand, gesture score floor) and the seen note run in unit tests on synthetic frames. Not tuned against a live camera in this repository.
138
+
139
+ ### Verified on this machine
140
+
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.
176
+
177
+ ### Not verified by anything
178
+
179
+ - Any model in a browser: tasks-vision 1.2.3 (as earlier builds did) task
180
+ options and result shapes, transformers.js 4.3.2 SmolVLM, LFM2-VL and
181
+ SlimSAM class names and processor calls (box prompts through
182
+ `input_boxes` included), a real YOLOv8n export's output
183
+ name and layout.
184
+ - FastSAM: not built. Its weights are AGPL-3.0 and its mask decoder is
185
+ not written; SlimSAM covers point prompts.
186
+ - Accuracy and speed of every model (no numbers measured).
187
+ - Whether the frame budget and idle waits remove stutter in a real scene
188
+ (needs a person looking at real frame rate).
189
+
190
+ ## Size budget
191
+
192
+ | file | gzip (measured) | ceiling |
193
+ |---|---|---|
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 |
196
+
197
+ Measured 2026-11-24 by `node tools/lint-packages.mjs` (gzip level 9) from the packed
198
+ tarball. Generated from `tools/size-budget.json`; CI fails when a file moves more than
199
+ 5 percent from its row.
package/dist/api.d.ts ADDED
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The vision calls. Each routes through the hub (`use`, `run`, `release`),
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).
5
+ * Landmarks walk a fallback chain of records: MediaPipe GPU, MediaPipe
6
+ * CPU (both rungs of one record), then any other record for the same
7
+ * capability, such as face-api.js.
8
+ */
9
+ import type { TjsProvider } from "@hackbuild/devices";
10
+ import type { Hub, ModelRecord, RunOptions, SizeClass } from "@hackbuild/models";
11
+ import type { DepthMap, Detection, ImageInput, LandmarkKind, Landmarks, Mask, Pixels, SegmentOptions, SegmentPrompt } from "./types.js";
12
+ /** Add the vision records and register the transformers.js loaders. MediaPipe and ort factories are provided by the app. */
13
+ export declare function attachVision(hub: Hub, tjs?: TjsProvider): void;
14
+ export interface CallOptions {
15
+ /** A record id instead of routing by capability. */
16
+ model?: string;
17
+ /** Route to a smaller model: a size class, or a download cap in MB. */
18
+ size?: SizeClass;
19
+ maxMB?: number;
20
+ signal?: AbortSignal;
21
+ /** Scheduling around rendering: minimum interval, idle only, frame time budget, wait or skip (see the models hub). */
22
+ schedule?: RunOptions;
23
+ }
24
+ export declare function depth(hub: Hub, image: ImageInput, o?: CallOptions): Promise<DepthMap>;
25
+ export declare function detect(hub: Hub, image: ImageInput, o?: CallOptions & {
26
+ scoreThreshold?: number;
27
+ maxResults?: number;
28
+ timestamp?: number;
29
+ toPixels?: (img: unknown) => Pixels;
30
+ }): Promise<Detection[]>;
31
+ /**
32
+ * Point, negative point and box prompted masks (SlimSAM), or a person mask
33
+ * without a prompt (selfie segmenter). Best first. The image is encoded
34
+ * once: pass `key` (an image hash) and your own `cache` to keep and drop
35
+ * embeddings yourself.
36
+ */
37
+ export declare function segment(hub: Hub, image: ImageInput, prompt?: SegmentPrompt, o?: CallOptions & SegmentOptions): Promise<Mask[]>;
38
+ /** Records for a landmark kind in fallback order: the routed record first, then the rest. */
39
+ export declare function landmarkChain(hub: Hub, kind: LandmarkKind): ModelRecord[];
40
+ /** Landmarks through the fallback chain. `failures` lists the records that failed before the one that answered. */
41
+ export declare function landmarks(hub: Hub, kind: LandmarkKind, image: ImageInput, o?: CallOptions & {
42
+ timestamp?: number;
43
+ }): Promise<Landmarks & {
44
+ failures: {
45
+ id: string;
46
+ error: string;
47
+ }[];
48
+ }>;
49
+ /** Caption an image. VLM calls are serialized on one chain. */
50
+ export declare function caption(hub: Hub, image: ImageInput, o?: CallOptions & {
51
+ maxTokens?: number;
52
+ }): Promise<string>;
53
+ export declare function ask(hub: Hub, image: ImageInput, question: string, o?: CallOptions & {
54
+ maxTokens?: number;
55
+ }): Promise<string>;
package/dist/api.js ADDED
@@ -0,0 +1,109 @@
1
+ /**
2
+ * The vision calls. Each routes through the hub (`use`, `run`, `release`),
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).
5
+ * Landmarks walk a fallback chain of records: MediaPipe GPU, MediaPipe
6
+ * CPU (both rungs of one record), then any other record for the same
7
+ * capability, such as face-api.js.
8
+ */
9
+ import { depthLoader, samLoader, vlmLoader } from "./loaders.js";
10
+ import { VISION_RECORDS } from "./records.js";
11
+ import { hasPrompt } from "./segment.js";
12
+ import { yoloDetector } from "./yolo.js";
13
+ /** Add the vision records and register the transformers.js loaders. MediaPipe and ort factories are provided by the app. */
14
+ export function attachVision(hub, tjs) {
15
+ hub.registry.add(...VISION_RECORDS);
16
+ if (tjs) {
17
+ tjs.loader("depth", depthLoader);
18
+ tjs.loader("vision.caption", vlmLoader);
19
+ tjs.loader("vision.ask", vlmLoader);
20
+ tjs.loader("segment", samLoader);
21
+ }
22
+ }
23
+ async function withModel(hub, what, fn, o = {}) {
24
+ const uo = {};
25
+ if (o.signal)
26
+ uo.signal = o.signal;
27
+ if (o.size)
28
+ uo.size = o.size;
29
+ if (o.maxMB !== undefined)
30
+ uo.maxMB = o.maxMB;
31
+ const l = await hub.use(what, uo);
32
+ try {
33
+ const ro = { ...(o.schedule ?? {}) };
34
+ if (o.signal && !ro.signal)
35
+ ro.signal = o.signal;
36
+ return await hub.run(l, (v) => fn(v, l), ro);
37
+ }
38
+ finally {
39
+ hub.release(l);
40
+ }
41
+ }
42
+ const target = (cap, o) => (o.model ? { id: o.model } : cap);
43
+ export function depth(hub, image, o = {}) {
44
+ return withModel(hub, target("depth", o), (m) => m.estimate(image), o);
45
+ }
46
+ function asDetector(v, toPixels) {
47
+ if (v && typeof v === "object" && "sessions" in v)
48
+ return yoloDetector(v, toPixels ? { toPixels } : {});
49
+ return v;
50
+ }
51
+ export function detect(hub, image, o = {}) {
52
+ const opts = {};
53
+ if (o.scoreThreshold !== undefined)
54
+ opts.scoreThreshold = o.scoreThreshold;
55
+ if (o.maxResults !== undefined)
56
+ opts.maxResults = o.maxResults;
57
+ if (o.timestamp !== undefined)
58
+ opts.timestamp = o.timestamp;
59
+ return withModel(hub, target("detect", o), (v) => asDetector(v, o.toPixels).detect(image, opts), o);
60
+ }
61
+ /**
62
+ * Point, negative point and box prompted masks (SlimSAM), or a person mask
63
+ * without a prompt (selfie segmenter). Best first. The image is encoded
64
+ * once: pass `key` (an image hash) and your own `cache` to keep and drop
65
+ * embeddings yourself.
66
+ */
67
+ export function segment(hub, image, prompt, o = {}) {
68
+ const cap = hasPrompt(prompt) ? "segment" : "segment.person";
69
+ const so = {};
70
+ if (o.key !== undefined)
71
+ so.key = o.key;
72
+ if (o.cache)
73
+ so.cache = o.cache;
74
+ return withModel(hub, target(cap, o), (m) => m.segment(image, prompt, so), o);
75
+ }
76
+ /** Records for a landmark kind in fallback order: the routed record first, then the rest. */
77
+ export function landmarkChain(hub, kind) {
78
+ const cap = `landmarks.${kind}`;
79
+ const all = hub.registry.find({ provides: cap, ...(hub.env ? { env: hub.env } : {}) });
80
+ const first = hub.registry.route({ provides: cap, ...(hub.env ? { env: hub.env } : {}) });
81
+ return first ? [first, ...all.filter((r) => r.id !== first.id)] : all;
82
+ }
83
+ /** Landmarks through the fallback chain. `failures` lists the records that failed before the one that answered. */
84
+ export async function landmarks(hub, kind, image, o = {}) {
85
+ const failures = [];
86
+ const chain = o.model ? [{ id: o.model }] : hub.registry.list().length ? landmarkChain(hub, kind) : [];
87
+ const targets = chain.length ? chain.map((r) => ({ id: r.id })) : [`landmarks.${kind}`];
88
+ for (const t of targets) {
89
+ try {
90
+ const r = await withModel(hub, t, (m) => m.detect(image, o.timestamp !== undefined ? { timestamp: o.timestamp } : {}), o);
91
+ return { ...r, failures };
92
+ }
93
+ catch (e) {
94
+ if (e.code === "skipped")
95
+ throw e;
96
+ failures.push({ id: typeof t === "string" ? t : t.id, error: e instanceof Error ? e.message : String(e) });
97
+ if (o.signal?.aborted)
98
+ break;
99
+ }
100
+ }
101
+ throw Object.assign(new Error(`no ${kind} landmark model loaded: ${failures.map((f) => `${f.id} (${f.error})`).join("; ")}`), { failures });
102
+ }
103
+ /** Caption an image. VLM calls are serialized on one chain. */
104
+ export function caption(hub, image, o = {}) {
105
+ return hub.chain("vlm")(() => withModel(hub, target("vision.caption", o), (m) => m.ask(image, undefined, o.maxTokens ? { maxTokens: o.maxTokens } : {}), o));
106
+ }
107
+ export function ask(hub, image, question, o = {}) {
108
+ return hub.chain("vlm")(() => withModel(hub, target("vision.ask", o), (m) => m.ask(image, question, o.maxTokens ? { maxTokens: o.maxTokens } : {}), o));
109
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * The face landmark fallback over face-api.js (code MIT, weights MIT from
3
+ * @vladmandic/face-api): the tiny face detector plus the 68 point tiny
4
+ * landmark net, on the wasm or cpu backend (FaceSwap forced wasm). Points
5
+ * come back normalized to the image like MediaPipe's.
6
+ */
7
+ import type { Factory } from "@hackbuild/models";
8
+ import type { Landmarker } from "./types.js";
9
+ /** The parts of face-api.js the provider touches. Tests pass a fake. */
10
+ export interface FaceApi {
11
+ nets: {
12
+ tinyFaceDetector: {
13
+ loadFromUri(u: string): Promise<void>;
14
+ };
15
+ faceLandmark68TinyNet: {
16
+ loadFromUri(u: string): Promise<void>;
17
+ };
18
+ };
19
+ TinyFaceDetectorOptions: new (o?: Record<string, unknown>) => unknown;
20
+ detectAllFaces(img: unknown, o: unknown): {
21
+ withFaceLandmarks(tiny: boolean): Promise<{
22
+ landmarks: {
23
+ positions: {
24
+ x: number;
25
+ y: number;
26
+ }[];
27
+ };
28
+ detection: {
29
+ imageWidth: number;
30
+ imageHeight: number;
31
+ };
32
+ }[]>;
33
+ };
34
+ }
35
+ export declare function faceApiProvider(opts: {
36
+ runtime: () => Promise<FaceApi>;
37
+ }): Factory<Landmarker>;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The face landmark fallback over face-api.js (code MIT, weights MIT from
3
+ * @vladmandic/face-api): the tiny face detector plus the 68 point tiny
4
+ * landmark net, on the wasm or cpu backend (FaceSwap forced wasm). Points
5
+ * come back normalized to the image like MediaPipe's.
6
+ */
7
+ export function faceApiProvider(opts) {
8
+ return async ({ record }) => {
9
+ const fa = await opts.runtime();
10
+ const base = record.source.url;
11
+ await fa.nets.tinyFaceDetector.loadFromUri(base);
12
+ await fa.nets.faceLandmark68TinyNet.loadFromUri(base);
13
+ return {
14
+ async detect(image) {
15
+ const res = await fa.detectAllFaces(image, new fa.TinyFaceDetectorOptions({ inputSize: 320 })).withFaceLandmarks(true);
16
+ return {
17
+ points: res.map((r) => r.landmarks.positions.map((p) => [p.x / r.detection.imageWidth, p.y / r.detection.imageHeight, 0])),
18
+ source: record.id,
19
+ };
20
+ },
21
+ };
22
+ };
23
+ }
@@ -0,0 +1,13 @@
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";
3
+ export { attachVision, depth, detect, segment, landmarks, landmarkChain, caption, ask, type CallOptions } from "./api.js";
4
+ export { depthLoader, vlmLoader, samLoader, depthFromOutput } from "./loaders.js";
5
+ export { mediapipeProvider, loadTasksVision, tasksVisionUrls, tasksVisionWasm, TASKS_VISION, type TasksVision, type MediapipeProviderOptions } from "./mediapipe.js";
6
+ export { faceApiProvider, type FaceApi } from "./faceapi.js";
7
+ export { yoloDetector, decodeYolo, letterboxParams, letterboxTensor, nms, iou, detectCadenceMs, COCO_LABELS, type Letterbox } from "./yolo.js";
8
+ export { perceptionLoop, readbackLoop, ResultCache, depthToRgba, fitSize, type Loop, type LoopOptions, type ReadbackOptions } from "./loop.js";
9
+ export { depthWorker, DEPTH_WORKER_SOURCE, type DepthWorker, type DepthWorkerOptions, type Pixels as WorkerPixels } from "./worker.js";
10
+ export { visionStubs, rampDepth, centreDetector, discSegmenter, fixedLandmarker, fixedVlm } from "./stubs.js";
11
+ export { EmbeddingCache, promptSegmenter, hasPrompt, type PromptSegmenterOptions } from "./segment.js";
12
+ export { emptyMask, maskArea, maskThreshold, maskUnion, maskIntersect, maskSubtract, maskInvert, maskDilate, maskErode, maskFeather, maskLargestComponent, maskToRgba, cutoutRgba, encodePng, maskToPng, cutoutPng, maskOutline, maskToSvg, maskToRle, maskFromRle, type MaskRle, } from "./masks.js";
13
+ export { SignalTracker, SeenNotes, describePerception, rawFace, rawHands, rawFromLandmarks, wantsLook, reactionsFor, gazeTarget, LOOK_PATTERN, CANNED_GESTURES, DEFAULT_REACTIONS, type HandGesture, type Perception, type PerceptionEvent, type RawFace, type RawHand, type RawFrame, type Reaction, } from "./signals.js";
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ export { VISION_RECORDS, MP_MODELS, mediapipeLadder, faceApiRecord, yoloRecord } from "./records.js";
2
+ export { attachVision, depth, detect, segment, landmarks, landmarkChain, caption, ask } from "./api.js";
3
+ export { depthLoader, vlmLoader, samLoader, depthFromOutput } from "./loaders.js";
4
+ export { mediapipeProvider, loadTasksVision, tasksVisionUrls, tasksVisionWasm, TASKS_VISION } from "./mediapipe.js";
5
+ export { faceApiProvider } from "./faceapi.js";
6
+ export { yoloDetector, decodeYolo, letterboxParams, letterboxTensor, nms, iou, detectCadenceMs, COCO_LABELS } from "./yolo.js";
7
+ export { perceptionLoop, readbackLoop, ResultCache, depthToRgba, fitSize } from "./loop.js";
8
+ export { depthWorker, DEPTH_WORKER_SOURCE } from "./worker.js";
9
+ export { visionStubs, rampDepth, centreDetector, discSegmenter, fixedLandmarker, fixedVlm } from "./stubs.js";
10
+ export { EmbeddingCache, promptSegmenter, hasPrompt } from "./segment.js";
11
+ export { emptyMask, maskArea, maskThreshold, maskUnion, maskIntersect, maskSubtract, maskInvert, maskDilate, maskErode, maskFeather, maskLargestComponent, maskToRgba, cutoutRgba, encodePng, maskToPng, cutoutPng, maskOutline, maskToSvg, maskToRle, maskFromRle, } from "./masks.js";
12
+ export { SignalTracker, SeenNotes, describePerception, rawFace, rawHands, rawFromLandmarks, wantsLook, reactionsFor, gazeTarget, LOOK_PATTERN, CANNED_GESTURES, DEFAULT_REACTIONS, } from "./signals.js";
@@ -0,0 +1,28 @@
1
+ /**
2
+ * transformers.js loaders for the vision capabilities, registered on the
3
+ * shared devices provider with `tjs.loader(capability, fn)`. Each returns
4
+ * the package's model shape.
5
+ */
6
+ import type { TjsLoadContext } from "@hackbuild/devices";
7
+ import type { DepthMap, DepthModel, Segmenter, Vlm } from "./types.js";
8
+ interface TensorLike {
9
+ data: ArrayLike<number>;
10
+ dims: number[];
11
+ slice?(...a: unknown[]): TensorLike;
12
+ }
13
+ interface RawImageLike {
14
+ width: number;
15
+ height: number;
16
+ channels?: number;
17
+ data: ArrayLike<number>;
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). */
20
+ export declare function depthFromOutput(out: {
21
+ predicted_depth?: TensorLike;
22
+ depth?: RawImageLike;
23
+ }): DepthMap;
24
+ export declare function depthLoader(ctx: TjsLoadContext): Promise<DepthModel>;
25
+ export declare function vlmLoader(ctx: TjsLoadContext): Promise<Vlm>;
26
+ /** SlimSAM: one embedding per image, kept in an `EmbeddingCache`, then point, negative point and box prompts. */
27
+ export declare function samLoader(ctx: TjsLoadContext): Promise<Segmenter>;
28
+ export {};
@@ -0,0 +1,115 @@
1
+ /**
2
+ * transformers.js loaders for the vision capabilities, registered on the
3
+ * shared devices provider with `tjs.loader(capability, fn)`. Each returns
4
+ * the package's model shape.
5
+ */
6
+ import { promptSegmenter } from "./segment.js";
7
+ const cls = (tjs, ...names) => {
8
+ for (const n of names)
9
+ if (tjs[n])
10
+ return tjs[n];
11
+ throw new Error(`the transformers.js module has none of ${names.join(", ")}`);
12
+ };
13
+ async function toRaw(tjs, img) {
14
+ const R = tjs.RawImage;
15
+ return R?.read ? R.read(img) : img;
16
+ }
17
+ /** 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). */
18
+ export function depthFromOutput(out) {
19
+ const pd = out.predicted_depth;
20
+ if (pd && pd.data && pd.dims?.length >= 2) {
21
+ const h = pd.dims[pd.dims.length - 2];
22
+ const w = pd.dims[pd.dims.length - 1];
23
+ let mn = Infinity;
24
+ let mx = -Infinity;
25
+ for (let i = 0; i < w * h; i++) {
26
+ const v = pd.data[i];
27
+ if (v < mn)
28
+ mn = v;
29
+ if (v > mx)
30
+ mx = v;
31
+ }
32
+ const inv = mx > mn ? 1 / (mx - mn) : 0;
33
+ const data = new Float32Array(w * h);
34
+ for (let i = 0; i < w * h; i++)
35
+ data[i] = (pd.data[i] - mn) * inv;
36
+ return { width: w, height: h, data, range: [mn, mx] };
37
+ }
38
+ const d = out.depth;
39
+ if (!d)
40
+ throw new Error("depth pipeline returned neither predicted_depth nor depth");
41
+ const ch = d.channels ?? 1;
42
+ const data = new Float32Array(d.width * d.height);
43
+ for (let i = 0; i < data.length; i++)
44
+ data[i] = d.data[i * ch] / 255;
45
+ return { width: d.width, height: d.height, data, range: [0, 255] };
46
+ }
47
+ export async function depthLoader(ctx) {
48
+ const pipe = (await ctx.tjs.pipeline("depth-estimation", ctx.record.source.modelId, ctx.options));
49
+ return {
50
+ estimate: async (image) => depthFromOutput((await pipe(image))),
51
+ dispose: () => pipe.dispose?.(),
52
+ };
53
+ }
54
+ export async function vlmLoader(ctx) {
55
+ const id = ctx.record.source.modelId;
56
+ const processor = (await cls(ctx.tjs, "AutoProcessor").from_pretrained(id));
57
+ const model = (await cls(ctx.tjs, "AutoModelForImageTextToText", "AutoModelForVision2Seq").from_pretrained(id, ctx.options));
58
+ const rp = ctx.record.quirks?.repetitionPenalty;
59
+ const cap = ctx.record.quirks?.maxTokensAction ?? 64;
60
+ const imagesFirst = ctx.record.quirks?.processorImagesFirst === true;
61
+ return {
62
+ async ask(image, question, o = {}) {
63
+ const text = processor.apply_chat_template([{ role: "user", content: [{ type: "image" }, { type: "text", text: question ?? "Describe this image in one sentence." }] }], { add_generation_prompt: true });
64
+ const raw = [await toRaw(ctx.tjs, image)];
65
+ const inputs = (await (imagesFirst ? processor(raw, text) : processor(text, raw)));
66
+ const ids = await model.generate({ ...inputs, max_new_tokens: o.maxTokens ?? cap, do_sample: false, ...(rp ? { repetition_penalty: rp } : {}) });
67
+ const start = inputs.input_ids.dims[inputs.input_ids.dims.length - 1];
68
+ const gen = ids.slice ? ids.slice(null, [start, null]) : ids;
69
+ return (processor.batch_decode(gen, { skip_special_tokens: true })[0] ?? "").trim();
70
+ },
71
+ dispose: () => model.dispose?.(),
72
+ };
73
+ }
74
+ /** SlimSAM: one embedding per image, kept in an `EmbeddingCache`, then point, negative point and box prompts. */
75
+ export async function samLoader(ctx) {
76
+ const id = ctx.record.source.modelId;
77
+ const processor = (await cls(ctx.tjs, "AutoProcessor").from_pretrained(id));
78
+ const model = (await cls(ctx.tjs, "SamModel").from_pretrained(id, ctx.options));
79
+ return promptSegmenter({
80
+ async encode(image) {
81
+ const raw = await toRaw(ctx.tjs, image);
82
+ const inputs = (await processor(raw));
83
+ return { raw, inputs, emb: await model.get_image_embeddings(inputs) };
84
+ },
85
+ async decode(e, prompt) {
86
+ const pts = prompt.points?.length ? prompt.points : null;
87
+ const b = prompt.box;
88
+ const q = {};
89
+ if (pts) {
90
+ q.input_points = [[pts.map((p) => [p.x, p.y])]];
91
+ q.input_labels = [[pts.map((p) => p.label ?? 1)]];
92
+ }
93
+ if (b)
94
+ q.input_boxes = [[[b.x, b.y, b.x + b.w, b.y + b.h]]];
95
+ const p = (await processor(e.raw, q));
96
+ const feed = { ...e.emb };
97
+ for (const k of ["input_points", "input_labels", "input_boxes"])
98
+ if (p[k] !== undefined)
99
+ feed[k] = p[k];
100
+ const out = (await model(feed));
101
+ const masks = await processor.post_process_masks(out.pred_masks, e.inputs.original_sizes, e.inputs.reshaped_input_sizes);
102
+ const m = masks[0];
103
+ const [n, h, w] = m.dims.slice(-3);
104
+ const res = [];
105
+ for (let k = 0; k < n; k++) {
106
+ const data = new Uint8Array(w * h);
107
+ for (let i = 0; i < w * h; i++)
108
+ data[i] = m.data[k * w * h + i] ? 255 : 0;
109
+ res.push({ width: w, height: h, data, score: out.iou_scores.data[k] ?? 0 });
110
+ }
111
+ return res;
112
+ },
113
+ dispose: () => model.dispose?.(),
114
+ });
115
+ }