@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/llms.md ADDED
@@ -0,0 +1,982 @@
1
+ # @hackbuild/vision
2
+
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
+ Generated by tools/llms.mjs from the TypeDoc JSON, the README and the examples of hackbuild-browser-ai. Human docs: https://hackbuild.github.io/hackbuild-browser-ai/docs/vision/
6
+
7
+ ## Purpose
8
+
9
+ - Runs depth, detection, segmentation, face, hand and pose landmarks, captions and questions through the `@hackbuild/models` hub.
10
+ - Falls through a chain of landmark models when one fails, and says which failed.
11
+ - 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.
12
+ - Runs depth in a worker and schedules calls around your render loop so the scene keeps its frames.
13
+ - Turns face and hand landmarks into steady presence, expression and gesture signals for a character.
14
+
15
+ ## Install
16
+
17
+ ```sh
18
+ npm install @hackbuild/vision
19
+ ```
20
+
21
+ It depends on [@hackbuild/ai-env](https://hackbuild.github.io/hackbuild-browser-ai/docs/ai-env/llms.md), [@hackbuild/models](https://hackbuild.github.io/hackbuild-browser-ai/docs/models/llms.md), [@hackbuild/devices](https://hackbuild.github.io/hackbuild-browser-ai/docs/devices/llms.md) and [@hackbuild/weights](https://hackbuild.github.io/hackbuild-browser-ai/docs/weights/llms.md). The model runtimes are not bundled; they load at run time from pinned URLs, and each is optional:
22
+
23
+ | subpath | runtime | pin |
24
+ |---|---|---|
25
+ | `.` (depth, segment, caption, ask) | @huggingface/transformers, through `loadTransformers` from @hackbuild/devices | 4.3.2 |
26
+ | `.` (detect, segment.person, landmarks) | @mediapipe/tasks-vision, through `loadTasksVision` | 1.2.3 |
27
+ | `.` (YOLO, optional) | onnxruntime-web, through `loadOrt` from @hackbuild/devices | 1.27.0 |
28
+ | `.` (face fallback, optional) | face-api.js, a runtime you pass to `faceApiProvider` | unknown |
29
+
30
+ ## Exports
31
+
32
+ ### @hackbuild/vision
33
+
34
+ ```ts
35
+ function ask(hub: Hub, image: unknown, question: string, o?: CallOptions & { maxTokens?: number }): Promise<string>
36
+ ```
37
+
38
+ Answer a question about an image with the routed vision language model.
39
+
40
+ ```ts
41
+ function attachVision(hub: Hub, tjs?: TjsProvider): void
42
+ ```
43
+
44
+ Add the vision records and register the transformers.js loaders.
45
+
46
+ ```ts
47
+ interface Box {
48
+ h: number;
49
+ w: number;
50
+ x: number;
51
+ y: number;
52
+ }
53
+ ```
54
+
55
+ A rectangle in image pixels: left, top, width and height.
56
+
57
+ ```ts
58
+ interface CallOptions {
59
+ maxMB?: number;
60
+ model?: string;
61
+ schedule?: RunOptions;
62
+ signal?: AbortSignal;
63
+ size?: SizeClass;
64
+ }
65
+ ```
66
+
67
+ 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.
68
+
69
+ ```ts
70
+ const CANNED_GESTURES: Readonly<Record<string, HandGesture>>
71
+ ```
72
+
73
+ Canned recognizer labels to gesture names.
74
+
75
+ ```ts
76
+ function caption(hub: Hub, image: unknown, o?: CallOptions & { maxTokens?: number }): Promise<string>
77
+ ```
78
+
79
+ Caption an image.
80
+
81
+ ```ts
82
+ function centreDetector(label?: string): Detector
83
+ ```
84
+
85
+ A stub detector with no weights: one centred box with the given label.
86
+
87
+ ```ts
88
+ const COCO_LABELS: string[]
89
+ ```
90
+
91
+ The 80 COCO class names, in YOLO class index order.
92
+
93
+ ```ts
94
+ function cutoutPng(image: Pixels, m: Mask, o?: { compress?: boolean }): Promise<Uint8Array<ArrayBufferLike>>
95
+ ```
96
+
97
+ The image with the mask as alpha, as a PNG (the cutout).
98
+
99
+ ```ts
100
+ function cutoutRgba(image: Pixels, m: Mask): Uint8ClampedArray
101
+ ```
102
+
103
+ The image's RGBA with the mask as alpha (the cutout).
104
+
105
+ ```ts
106
+ function decodeYolo(out: ArrayLike<number>, dims: readonly number[], lb: Letterbox, src: { height: number; width: number }, o?: { iou?: number; labels?: readonly string[]; max?: number; scoreThreshold?: number }): Detection[]
107
+ ```
108
+
109
+ Decode a [4 + classes, anchors] output (batch 1) into boxes in source pixels.
110
+
111
+ ```ts
112
+ const DEFAULT_REACTIONS: readonly Reaction[]
113
+ ```
114
+
115
+ Default reactions (vendor): greet on arrival, smile back after 600 ms at 0.7 chance, answer waves and a few gestures.
116
+
117
+ ```ts
118
+ function depth(hub: Hub, image: unknown, o?: CallOptions): Promise<DepthMap>
119
+ ```
120
+
121
+ A depth map of an image from the routed depth model (Depth Anything V2 small by default), loaded and released through the hub.
122
+
123
+ ```ts
124
+ const DEPTH_WORKER_SOURCE: "\nlet pipe = null;\nlet RawImage = null;\nconst norm = (out) => {\n const pd = out.predicted_depth;\n if (pd && pd.data && pd.dims && pd.dims.length >= 2) {\n const h = pd.dims[pd.dims.length - 2], w = pd.dims[pd.dims.length - 1];\n let mn = Infinity, mx = -Infinity;\n for (let i = 0; i < w * h; i++) { const v = pd.data[i]; if (v < mn) mn = v; if (v > mx) mx = v; }\n const inv = mx > mn ? 1 / (mx - mn) : 0;\n const data = new Float32Array(w * h);\n for (let i = 0; i < w * h; i++) data[i] = (pd.data[i] - mn) * inv;\n return { width: w, height: h, data, range: [mn, mx] };\n }\n const d = out.depth;\n if (!d) throw new Error(\"depth pipeline returned neither predicted_depth nor depth\");\n const ch = d.channels || 1;\n const data = new Float32Array(d.width * d.height);\n for (let i = 0; i < data.length; i++) data[i] = d.data[i * ch] / 255;\n return { width: d.width, height: d.height, data, range: [0, 255] };\n};\nself.onmessage = async (ev) => {\n const m = ev.data;\n if (!m || typeof m !== \"object\" || !(\"op\" in m)) return;\n try {\n if (m.op === \"load\") {\n let tjs = null, err = null;\n const load = self.__import || ((u) => import(u));\n for (const u of m.urls) { try { tjs = await load(u); break; } catch (e) { err = e; } }\n if (!tjs) throw err || new Error(\"no transformers.js url loaded\");\n RawImage = tjs.RawImage;\n pipe = await tjs.pipeline(\"depth-estimation\", m.modelId, { device: m.device, dtype: m.dtype, revision: m.revision });\n self.postMessage({ id: m.id, ok: true });\n } else if (m.op === \"run\") {\n if (!pipe) throw new Error(\"depth worker is not loaded\");\n const img = new RawImage(new Uint8ClampedArray(m.data), m.width, m.height, 4);\n const d = norm(await pipe(img));\n self.postMessage({ id: m.id, ok: true, depth: d }, [d.data.buffer]);\n }\n } catch (e) {\n self.postMessage({ id: m.id, ok: false, error: String((e && e.message) || e) });\n }\n};\n"
125
+ ```
126
+
127
+ The worker's source.
128
+
129
+ ```ts
130
+ function depthFromOutput(out: { depth?: RawImageLike; predicted_depth?: TensorLike }): DepthMap
131
+ ```
132
+
133
+ Normalize a depth pipeline result.
134
+
135
+ ```ts
136
+ function depthLoader(ctx: TjsLoadContext): Promise<DepthModel>
137
+ ```
138
+
139
+ The transformers.js loader for depth records: a depth-estimation pipeline wrapped as a DepthModel.
140
+
141
+ ```ts
142
+ interface DepthMap {
143
+ data: Float32Array;
144
+ height: number;
145
+ range: [min: number, max: number];
146
+ width: number;
147
+ }
148
+ ```
149
+
150
+ A depth map: width, height, 0 to 1 per pixel with larger nearer, and the raw output range.
151
+
152
+ ```ts
153
+ interface DepthModel {
154
+ dispose?(): unknown;
155
+ estimate(image: unknown): Promise<DepthMap>;
156
+ }
157
+ ```
158
+
159
+ A loaded depth model: `estimate` returns a DepthMap for an image.
160
+
161
+ ```ts
162
+ function depthToRgba(d: { data: Float32Array; height: number; width: number }): Uint8ClampedArray
163
+ ```
164
+
165
+ A depth map as an 8 bit grey RGBA buffer, for a canvas or a PNG (store it as a PNG data URL to keep it with a design).
166
+
167
+ ```ts
168
+ function depthWorker(o: DepthWorkerOptions): Promise<DepthWorker>
169
+ ```
170
+
171
+ Spawns the worker and loads the model in it.
172
+
173
+ ```ts
174
+ interface DepthWorker {
175
+ readonly device: "webgpu" | "wasm";
176
+ readonly rung: WorkerRung;
177
+ dispose(): void;
178
+ estimate(image: Pixels): Promise<DepthMap>;
179
+ }
180
+ ```
181
+
182
+ A depth model in a worker: the worker rung that started, the device, `estimate` and `dispose`.
183
+
184
+ ```ts
185
+ interface DepthWorkerOptions {
186
+ device?: "webgpu" | "wasm";
187
+ dtype?: string;
188
+ modelId?: string;
189
+ onLicence?: (line: string) => void;
190
+ record?: ModelRecord;
191
+ spawn?: Pick<SpawnOptions, "prefer" | "Worker" | "createObjectURL" | "readyMs" | "prelude">;
192
+ urls: readonly string[];
193
+ }
194
+ ```
195
+
196
+ Options for depthWorker: the transformers.js URLs, the depth model or record, the licence callback, device, dtype and worker rungs.
197
+
198
+ ```ts
199
+ function describePerception(p: Perception): string
200
+ ```
201
+
202
+ Perception as one short lowercase line for a language model.
203
+
204
+ ```ts
205
+ function detect(hub: Hub, image: unknown, o?: CallOptions & { maxResults?: number; scoreThreshold?: number; timestamp?: number; toPixels?: (img: unknown) => Pixels }): Promise<Detection[]>
206
+ ```
207
+
208
+ Objects in an image from the routed detector (MediaPipe EfficientDet by default, or a YOLO ort model), loaded and released through the hub.
209
+
210
+ ```ts
211
+ function detectCadenceMs(lastLatencyMs: number): number
212
+ ```
213
+
214
+ Detection cadence: wait max(0.45 s, 4 times the last latency) between runs.
215
+
216
+ ```ts
217
+ interface Detection {
218
+ box: Box;
219
+ label: string;
220
+ score: number;
221
+ }
222
+ ```
223
+
224
+ One detected object: its label, score and box.
225
+
226
+ ```ts
227
+ interface Detector {
228
+ detect(image: unknown, opts?: { maxResults?: number; scoreThreshold?: number; timestamp?: number }): Promise<Detection[]>;
229
+ dispose?(): unknown;
230
+ }
231
+ ```
232
+
233
+ A loaded detector: `detect` returns the objects in an image.
234
+
235
+ ```ts
236
+ function discSegmenter(): Segmenter & { cache: EmbeddingCache<{ height: number; width: number }>; encodes: number }
237
+ ```
238
+
239
+ A disc at the first positive point, or in the middle of the box, with a hole at each negative point.
240
+
241
+ ```ts
242
+ class EmbeddingCache<E = unknown> {
243
+ constructor(max?: number);
244
+ hits: number;
245
+ readonly max: number;
246
+ misses: number;
247
+ readonly size: number;
248
+ clear(): void;
249
+ delete(key: unknown): boolean;
250
+ getOr(key: unknown, make: () => Promise<E>): Promise<E>;
251
+ has(key: unknown): boolean;
252
+ peek(key: unknown): Promise<E> | undefined;
253
+ set(key: unknown, v: E | Promise<E>): void;
254
+ }
255
+ ```
256
+
257
+ Least recently used embeddings by image.
258
+
259
+ ```ts
260
+ function emptyMask(width: number, height: number): Mask
261
+ ```
262
+
263
+ An empty mask.
264
+
265
+ ```ts
266
+ function encodePng(width: number, height: number, data: ArrayLike<number>, o?: { channels?: 1 | 4; compress?: boolean }): Promise<Uint8Array<ArrayBufferLike>>
267
+ ```
268
+
269
+ A PNG file from RGBA (4 channels) or grey (1 channel) bytes.
270
+
271
+ ```ts
272
+ interface FaceApi {
273
+ nets: { faceLandmark68TinyNet: { loadFromUri(u: string): Promise<void> }; tinyFaceDetector: { loadFromUri(u: string): Promise<void> } };
274
+ TinyFaceDetectorOptions: new (o?: Record<string, unknown>) => unknown;
275
+ detectAllFaces(img: unknown, o: unknown): { withFaceLandmarks(tiny: boolean): Promise<{ detection: { imageHeight: number; imageWidth: number }; landmarks: { positions: { x: number; y: number }[] } }[]> };
276
+ }
277
+ ```
278
+
279
+ The parts of face-api.js the provider touches.
280
+
281
+ ```ts
282
+ function faceApiProvider(opts: { runtime: () => Promise<FaceApi> }): Factory<Landmarker>
283
+ ```
284
+
285
+ The face-api.js provider for the models hub: the tiny face detector and 68 point tiny landmark net, as a face Landmarker.
286
+
287
+ ```ts
288
+ function faceApiRecord(baseUrl: string): ModelRecord
289
+ ```
290
+
291
+ A face landmark fallback record over face-api.js tiny nets (code MIT; weights MIT from @vladmandic/face-api).
292
+
293
+ ```ts
294
+ function fitSize(w: number, h: number, maxPx?: number): { height: number; scale: number; width: number }
295
+ ```
296
+
297
+ Scale so the longest side is at most maxPx.
298
+
299
+ ```ts
300
+ function fixedLandmarker(count: number, source?: string): Landmarker
301
+ ```
302
+
303
+ A stub landmarker with no weights: one list of `count` fixed points.
304
+
305
+ ```ts
306
+ function fixedVlm(text?: string): Vlm
307
+ ```
308
+
309
+ A stub vision language model with no weights: a fixed caption, or a fixed answer that repeats the question.
310
+
311
+ ```ts
312
+ function gazeTarget(p: Perception, gain?: number): { x: number; y: number } | null
313
+ ```
314
+
315
+ Where the character should look, -1 to 1, with a gain (vendor 1.3) so small head moves read; null when nobody is in view.
316
+
317
+ ```ts
318
+ type HandGesture = "wave" | "thumbs_up" | "thumbs_down" | "open_palm" | "victory" | "pointing_up" | "fist" | "love"
319
+ ```
320
+
321
+ The hand gestures the tracker reports: a wave from wrist motion, and the canned recognizer gestures by name.
322
+
323
+ ```ts
324
+ function hasPrompt(p?: SegmentPrompt): boolean
325
+ ```
326
+
327
+ True when the prompt has a point or a box.
328
+
329
+ ```ts
330
+ type ImageInput = unknown
331
+ ```
332
+
333
+ Anything the runtimes accept: an image, canvas, video frame, bitmap, URL or data URL.
334
+
335
+ ```ts
336
+ function iou(a: Box, b: Box): number
337
+ ```
338
+
339
+ Intersection over union of two boxes, 0 to 1.
340
+
341
+ ```ts
342
+ function landmarkChain(hub: Hub, kind: LandmarkKind): ModelRecord[]
343
+ ```
344
+
345
+ Records for a landmark kind in fallback order: the routed record first, then the rest.
346
+
347
+ ```ts
348
+ interface Landmarker {
349
+ detect(image: unknown, opts?: { timestamp?: number }): Promise<Landmarks>;
350
+ dispose?(): unknown;
351
+ }
352
+ ```
353
+
354
+ A loaded landmark model: `detect` returns Landmarks for an image.
355
+
356
+ ```ts
357
+ type LandmarkKind = "face" | "hand" | "pose" | "gesture"
358
+ ```
359
+
360
+ "gesture" is hand landmarks plus a canned gesture label per hand (MediaPipe gesture recognizer).
361
+
362
+ ```ts
363
+ function landmarks(hub: Hub, kind: LandmarkKind, image: unknown, o?: CallOptions & { timestamp?: number }): Promise<Landmarks & { failures: { error: string; id: string }[] }>
364
+ ```
365
+
366
+ Landmarks through the fallback chain.
367
+
368
+ ```ts
369
+ interface Landmarks {
370
+ blendshapes?: Record<string, number>[];
371
+ gestures?: ({ name: string; score: number } | null)[];
372
+ handedness?: string[];
373
+ points: [number, number, number][][];
374
+ source: string;
375
+ }
376
+ ```
377
+
378
+ Landmarks for each face, hand or body, with blendshapes, handedness and gestures where the model gives them, and the record that answered.
379
+
380
+ ```ts
381
+ interface Letterbox {
382
+ padX: number;
383
+ padY: number;
384
+ scale: number;
385
+ size: number;
386
+ }
387
+ ```
388
+
389
+ How an image was fitted into the square input: scale, left and top padding, and the square side.
390
+
391
+ ```ts
392
+ function letterboxParams(w: number, h: number, size?: number): Letterbox
393
+ ```
394
+
395
+ The scale and padding that fit a `w` by `h` image into a `size` square (640 by default), centred.
396
+
397
+ ```ts
398
+ function letterboxTensor(px: Pixels, size?: number): { data: Float32Array; lb: Letterbox }
399
+ ```
400
+
401
+ RGBA pixels to a planar float tensor [1, 3, size, size] in 0 to 1, nearest neighbour, grey padding.
402
+
403
+ ```ts
404
+ function loadTasksVision(version?: string): () => Promise<TasksVision>
405
+ ```
406
+
407
+ A loader that imports the pinned @mediapipe/tasks-vision at run time; pass it as `runtime` to mediapipeProvider.
408
+
409
+ ```ts
410
+ const LOOK_PATTERN: RegExp
411
+ ```
412
+
413
+ Questions that call for an on demand look rather than the steady signals.
414
+
415
+ ```ts
416
+ interface Loop {
417
+ readonly busy: boolean;
418
+ readonly lastLatencyMs: number;
419
+ readonly running: boolean;
420
+ readonly steps: number;
421
+ stop(): void;
422
+ }
423
+ ```
424
+
425
+ A running loop: `stop`, whether it runs or is busy, the last step's latency and the step count.
426
+
427
+ ```ts
428
+ interface LoopOptions<T> {
429
+ interval?: (lastLatencyMs: number) => number;
430
+ now?: () => number;
431
+ onBusy?: () => void;
432
+ onError?: (e: unknown) => void;
433
+ onResult?: (r: T, latencyMs: number) => void;
434
+ schedule?: (fn: () => void) => void;
435
+ signal?: AbortSignal;
436
+ step: (tick: number) => Promise<T>;
437
+ }
438
+ ```
439
+
440
+ A perception loop beside a render loop: one step at a time (a busy guard), each step started no sooner than `interval(lastLatency)` after the previous one began (an adaptive cadence or a fixed period), stopped by `stop()` or an abort signal.
441
+
442
+ ```ts
443
+ interface Mask {
444
+ data: Uint8Array;
445
+ height: number;
446
+ score?: number;
447
+ width: number;
448
+ }
449
+ ```
450
+
451
+ A mask the size of its image: 0 or 255 per pixel, or a confidence 0 to 255, with an optional score.
452
+
453
+ ```ts
454
+ function maskArea(m: Mask): number
455
+ ```
456
+
457
+ Inside pixels (128 and up).
458
+
459
+ ```ts
460
+ function maskDilate(m: Mask, r: number): Mask
461
+ ```
462
+
463
+ Grow by a disc of radius `r` pixels (expand).
464
+
465
+ ```ts
466
+ function maskErode(m: Mask, r: number): Mask
467
+ ```
468
+
469
+ Shrink by a disc of radius `r` pixels; the image border does not count as outside.
470
+
471
+ ```ts
472
+ function maskFeather(m: Mask, r: number): Mask
473
+ ```
474
+
475
+ Soft edges: a gaussian of radius `r` with sigma r / 2 (a smooth without a rethreshold), edges clamped.
476
+
477
+ ```ts
478
+ function maskFromRle(r: MaskRle): Mask
479
+ ```
480
+
481
+ A mask from COCO style run length, inside 255.
482
+
483
+ ```ts
484
+ function maskIntersect(a: Mask, b: Mask): Mask
485
+ ```
486
+
487
+ Pixels inside both masks, the smaller value of each.
488
+
489
+ ```ts
490
+ function maskInvert(m: Mask): Mask
491
+ ```
492
+
493
+ The mask with inside and outside swapped, 255 minus each value.
494
+
495
+ ```ts
496
+ function maskLargestComponent(m: Mask, connectivity?: 4 | 8): Mask
497
+ ```
498
+
499
+ Keep only the largest connected piece (8 connected by default).
500
+
501
+ ```ts
502
+ function maskOutline(m: Mask): [number, number][][]
503
+ ```
504
+
505
+ Outline loops along pixel edges, inside on the right going clockwise in image space (y down); holes run the other way.
506
+
507
+ ```ts
508
+ interface MaskRle {
509
+ counts: number[];
510
+ size: [height: number, width: number];
511
+ }
512
+ ```
513
+
514
+ COCO style uncompressed run length: column major, the first run counts outside pixels.
515
+
516
+ ```ts
517
+ function maskSubtract(a: Mask, b: Mask): Mask
518
+ ```
519
+
520
+ `a` with `b` taken out (shift with a selection tool in a mask editor).
521
+
522
+ ```ts
523
+ function maskThreshold(m: Mask, t?: number): Mask
524
+ ```
525
+
526
+ Every value to 0 or 255 at `t`.
527
+
528
+ ```ts
529
+ function maskToPng(m: Mask, o?: { compress?: boolean }): Promise<Uint8Array<ArrayBufferLike>>
530
+ ```
531
+
532
+ The mask as a grey PNG.
533
+
534
+ ```ts
535
+ function maskToRgba(m: Mask): Uint8ClampedArray
536
+ ```
537
+
538
+ Grey RGBA, opaque, for a canvas or a PNG.
539
+
540
+ ```ts
541
+ function maskToRle(m: Mask): MaskRle
542
+ ```
543
+
544
+ The mask as COCO style uncompressed run length, column major, 128 and up inside.
545
+
546
+ ```ts
547
+ function maskToSvg(m: Mask, o?: { fill?: string }): string
548
+ ```
549
+
550
+ The outline as an SVG file, one even odd path in image pixels.
551
+
552
+ ```ts
553
+ function maskUnion(a: Mask, b: Mask): Mask
554
+ ```
555
+
556
+ Pixels inside either mask, the larger value of each.
557
+
558
+ ```ts
559
+ function mediapipeLadder(): Rung[]
560
+ ```
561
+
562
+ MediaPipe ladder: GPU delegate (webgl), then the CPU delegate (wasm).
563
+
564
+ ```ts
565
+ function mediapipeProvider(opts: MediapipeProviderOptions): Factory
566
+ ```
567
+
568
+ The MediaPipe tasks-vision provider for the models hub: one task per record, the GPU delegate on a webgl rung and the CPU delegate on a wasm rung.
569
+
570
+ ```ts
571
+ interface MediapipeProviderOptions {
572
+ runtime: () => Promise<TasksVision>;
573
+ store?: WeightStore;
574
+ wasmBase?: string;
575
+ }
576
+ ```
577
+
578
+ Options for mediapipeProvider: the runtime loader, the wasm fileset directory, and a weight store to read model files through.
579
+
580
+ ```ts
581
+ const MP_MODELS: "https://storage.googleapis.com/mediapipe-models/"
582
+ ```
583
+
584
+ The MediaPipe model storage base URL the MediaPipe records load from.
585
+
586
+ ```ts
587
+ function nms(dets: Detection[], iouThreshold?: number, max?: number): Detection[]
588
+ ```
589
+
590
+ Greedy NMS within each label, best first, then the top `max` overall.
591
+
592
+ ```ts
593
+ interface Perception {
594
+ face: { x: number; y: number } | null;
595
+ facing: boolean;
596
+ frown: number;
597
+ gesture: HandGesture | null;
598
+ present: boolean;
599
+ smile: number;
600
+ surprise: number;
601
+ }
602
+ ```
603
+
604
+ Steady signals for one moment: present, where the face is, facing, smile, surprise and frown strengths, and the held gesture.
605
+
606
+ ```ts
607
+ type PerceptionEvent = { type: "arrived" } | { type: "left" } | { type: "smiled" } | { gesture: HandGesture; type: "gesture" }
608
+ ```
609
+
610
+ A discrete perception event: someone arrived, left, smiled, or made a gesture.
611
+
612
+ ```ts
613
+ function perceptionLoop<T>(o: LoopOptions<T>): Loop
614
+ ```
615
+
616
+ Run a perception step beside a render loop, one at a time, each started no sooner than `interval(lastLatency)` after the previous one began.
617
+
618
+ ```ts
619
+ const PICKER_RECORDS: ModelRecord[]
620
+ ```
621
+
622
+ Records listed for pickers and never registered by default: larger alternates, and records under licences that limit use (YOLOv10, FastSAM, the face swap set).
623
+
624
+ ```ts
625
+ interface Pixels {
626
+ data: Uint8ClampedArray<ArrayBufferLike> | Uint8Array<ArrayBufferLike>;
627
+ height: number;
628
+ width: number;
629
+ }
630
+ ```
631
+
632
+ RGBA pixels, as ImageData has them.
633
+
634
+ ```ts
635
+ function promptSegmenter<E>(o: PromptSegmenterOptions<E>): Segmenter & { cache: EmbeddingCache<E> }
636
+ ```
637
+
638
+ A segmenter from an encoder and a decoder, with the embedding cache on `cache`.
639
+
640
+ ```ts
641
+ interface PromptSegmenterOptions<E> {
642
+ cache?: EmbeddingCache<E>;
643
+ decode(embedding: E, prompt: SegmentPrompt, image: unknown): Promise<Mask[]>;
644
+ dispose?(): unknown;
645
+ encode(image: unknown): Promise<E>;
646
+ }
647
+ ```
648
+
649
+ The parts of a prompted segmenter: an image encoder run once per image, a prompt decoder, and the embedding cache.
650
+
651
+ ```ts
652
+ function rampDepth(): DepthModel
653
+ ```
654
+
655
+ A stub depth model with no weights: a left to right ramp at the image's size.
656
+
657
+ ```ts
658
+ function rawFace(lm: Landmarks, index?: number): RawFace | null
659
+ ```
660
+
661
+ One raw face from a face landmark result, or null.
662
+
663
+ ```ts
664
+ interface RawFace {
665
+ frown: number;
666
+ pitch: number;
667
+ smile: number;
668
+ surprise: number;
669
+ x: number;
670
+ y: number;
671
+ yaw: number;
672
+ }
673
+ ```
674
+
675
+ One face reading before smoothing.
676
+
677
+ ```ts
678
+ interface RawFrame {
679
+ face: RawFace | null;
680
+ hands: RawHand[] | null;
681
+ }
682
+ ```
683
+
684
+ One frame's readings for SignalTracker: the face, and the hands when they were checked.
685
+
686
+ ```ts
687
+ function rawFromLandmarks(face: Landmarks | null | undefined, hands?: Landmarks | null): RawFrame
688
+ ```
689
+
690
+ A tracker frame from `landmarks` results.
691
+
692
+ ```ts
693
+ interface RawHand {
694
+ gesture: string | null;
695
+ score: number;
696
+ x: number;
697
+ y: number;
698
+ }
699
+ ```
700
+
701
+ One hand reading before smoothing: wrist position, the recognizer's canned label and its score.
702
+
703
+ ```ts
704
+ function rawHands(lm: Landmarks): RawHand[]
705
+ ```
706
+
707
+ Raw hands from a gesture recognizer or hand landmarker result: the wrist (point 0) and the top gesture.
708
+
709
+ ```ts
710
+ interface Reaction {
711
+ chance?: number;
712
+ delayMs?: number;
713
+ gesture?: HandGesture;
714
+ kind: "gesture" | "mood";
715
+ name: string;
716
+ on: "gesture" | "arrived" | "left" | "smiled";
717
+ }
718
+ ```
719
+
720
+ One reaction to a perception event: a mood or a gesture by common name, after a delay, with a chance.
721
+
722
+ ```ts
723
+ function reactionsFor(e: PerceptionEvent, rng: () => number, table?: readonly Reaction[]): Reaction[]
724
+ ```
725
+
726
+ The reactions an event calls for.
727
+
728
+ ```ts
729
+ function readbackLoop<T>(o: ReadbackOptions<T>): Loop & { readonly skipped: number }
730
+ ```
731
+
732
+ Agent eye style readback: one read at a time (a busy flag guards re-entry; frames while busy are counted as skipped instead of queued), capped at maxHz.
733
+
734
+ ```ts
735
+ interface ReadbackOptions<T> {
736
+ maxHz?: number;
737
+ now?: () => number;
738
+ onError?: (e: unknown) => void;
739
+ onFrame: (frame: T) => void | Promise<void>;
740
+ read: () => Promise<T>;
741
+ schedule?: (fn: () => void) => void;
742
+ signal?: AbortSignal;
743
+ }
744
+ ```
745
+
746
+ Options for readbackLoop: the async read, the frame consumer, a rate cap (10 Hz), and an abort signal.
747
+
748
+ ```ts
749
+ class ResultCache<T> {
750
+ constructor(max?: number);
751
+ readonly size: number;
752
+ get(key: string): T | undefined;
753
+ getOr(key: string, make: () => Promise<T>): Promise<T>;
754
+ set(key: string, v: T): void;
755
+ }
756
+ ```
757
+
758
+ A small LRU of results by key, so a depth map is computed once per image.
759
+
760
+ ```ts
761
+ function samLoader(ctx: TjsLoadContext): Promise<Segmenter>
762
+ ```
763
+
764
+ SlimSAM: one embedding per image, kept in an `EmbeddingCache`, then point, negative point and box prompts.
765
+
766
+ ```ts
767
+ class SeenNotes {
768
+ constructor();
769
+ next(p: Perception, caption?: string | null): string | null;
770
+ reset(): void;
771
+ }
772
+ ```
773
+
774
+ The seen note for a turn: null when nothing changed since the last note, so a chat about anything else is not padded with the same observation.
775
+
776
+ ```ts
777
+ function segment(hub: Hub, image: unknown, prompt?: SegmentPrompt, o?: CallOptions & SegmentOptions): Promise<Mask[]>
778
+ ```
779
+
780
+ Point, negative point and box prompted masks (SlimSAM), or a person mask without a prompt (selfie segmenter).
781
+
782
+ ```ts
783
+ interface Segmenter {
784
+ dispose?(): unknown;
785
+ segment(image: unknown, prompt?: SegmentPrompt, o?: SegmentOptions): Promise<Mask[]>;
786
+ }
787
+ ```
788
+
789
+ A loaded segmenter: `segment` returns masks for an image and prompt, best first.
790
+
791
+ ```ts
792
+ interface SegmentOptions {
793
+ cache?: EmbeddingCache<unknown>;
794
+ key?: string;
795
+ }
796
+ ```
797
+
798
+ How a segmenter keeps image embeddings: a stable key for the image and the cache to keep them in.
799
+
800
+ ```ts
801
+ interface SegmentPrompt {
802
+ box?: Box;
803
+ points?: { label?: 0 | 1; x: number; y: number }[];
804
+ }
805
+ ```
806
+
807
+ What to cut out: points (object or background) and a box, in image pixels.
808
+
809
+ ```ts
810
+ class SignalTracker {
811
+ constructor();
812
+ readonly perception: Perception;
813
+ feed(raw: RawFrame, now: number): PerceptionEvent[];
814
+ reset(): void;
815
+ }
816
+ ```
817
+
818
+ Turns raw face and hand frames into steady signals and discrete events, smoothed or held so one noisy frame never fires a reaction.
819
+
820
+ ```ts
821
+ const TASKS_VISION: "1.2.3"
822
+ ```
823
+
824
+ The pinned @mediapipe/tasks-vision version, 1.2.3.
825
+
826
+ ```ts
827
+ interface TasksVision {
828
+ FaceLandmarker?: TaskClass;
829
+ FilesetResolver: { forVisionTasks(base: string): Promise<unknown> };
830
+ GestureRecognizer?: TaskClass;
831
+ HandLandmarker?: TaskClass;
832
+ ImageSegmenter?: TaskClass;
833
+ ObjectDetector?: TaskClass;
834
+ PoseLandmarker?: TaskClass;
835
+ }
836
+ ```
837
+
838
+ The parts of @mediapipe/tasks-vision the provider touches.
839
+
840
+ ```ts
841
+ function tasksVisionUrls(version?: string): string[]
842
+ ```
843
+
844
+ The URL @mediapipe/tasks-vision is imported from, on jsDelivr.
845
+
846
+ ```ts
847
+ function tasksVisionWasm(version?: string): string
848
+ ```
849
+
850
+ The directory of the tasks-vision wasm fileset, on jsDelivr.
851
+
852
+ ```ts
853
+ const VISION_RECORDS: ModelRecord[]
854
+ ```
855
+
856
+ The vision records registered by `attachVision`: Depth Anything V2 small, MediaPipe detection, segmentation and landmarks, SlimSAM, SmolVLM 256M and LFM2-VL 450M.
857
+
858
+ ```ts
859
+ function visionStubs(): Record<string, (r: ModelRecord) => unknown>
860
+ ```
861
+
862
+ Stub builders to merge into `stubFactory({...})`.
863
+
864
+ ```ts
865
+ interface Vlm {
866
+ ask(image: unknown, question?: string, opts?: { maxTokens?: number; signal?: AbortSignal }): Promise<string>;
867
+ dispose?(): unknown;
868
+ }
869
+ ```
870
+
871
+ A loaded vision language model: `ask` answers a question about an image, or captions it.
872
+
873
+ ```ts
874
+ function vlmLoader(ctx: TjsLoadContext): Promise<Vlm>
875
+ ```
876
+
877
+ The transformers.js loader for caption and question records: the VLM's processor and model wrapped as a Vlm.
878
+
879
+ ```ts
880
+ function wantsLook(text: string, pattern?: RegExp): boolean
881
+ ```
882
+
883
+ True when a message asks the character to look, by LOOK_PATTERN or the pattern you pass.
884
+
885
+ ```ts
886
+ interface WorkerPixels {
887
+ data: Uint8ClampedArray<ArrayBufferLike> | Uint8Array<ArrayBufferLike>;
888
+ height: number;
889
+ width: number;
890
+ }
891
+ ```
892
+
893
+ RGBA pixels the page sends to the depth worker: ImageData, or anything with width, height and data.
894
+
895
+ ```ts
896
+ function yoloDetector(m: OrtModel, o?: { labels?: readonly string[]; size?: number; toPixels?: (img: unknown) => Pixels }): Detector
897
+ ```
898
+
899
+ Wrap an ort model as a Detector.
900
+
901
+ ```ts
902
+ function yoloRecord(o: { id?: string; labels?: string[]; licence?: string; sha256?: string; url: string }): ModelRecord
903
+ ```
904
+
905
+ YOLOv8n exported to ONNX (640 input, [1, 84, 8400] output).
906
+
907
+ ## Examples
908
+
909
+ ### quick start
910
+
911
+ ```ts
912
+ import { probe } from "@hackbuild/ai-env";
913
+ import { loadTransformers, tjsProvider } from "@hackbuild/devices";
914
+ import { createHub } from "@hackbuild/models";
915
+ import { attachVision, caption, depth, detect, loadTasksVision, mediapipeProvider } from "@hackbuild/vision";
916
+
917
+ // one hub; transformers.js and MediaPipe tasks-vision load at run time from pinned urls
918
+ const tjs = tjsProvider({ runtime: loadTransformers() });
919
+ const hub = createHub({ env: await probe() });
920
+ attachVision(hub, tjs); // the vision records plus the transformers.js loaders
921
+ hub.provide("tjs", tjs.factory);
922
+ hub.provide("mediapipe", mediapipeProvider({ runtime: loadTasksVision() }));
923
+
924
+ // each call loads its model on first use, runs it under the gpu lock, and releases it
925
+ const video = document.querySelector("video")!;
926
+ video.srcObject = await navigator.mediaDevices.getUserMedia({ video: true }); // the webcam
927
+ await video.play();
928
+ const map = await depth(hub, video); // Depth Anything V2 small, weights Apache-2.0
929
+ const boxes = await detect(hub, video, { scoreThreshold: 0.4 }); // MediaPipe EfficientDet lite0, Apache-2.0
930
+ const line = await caption(hub, video); // SmolVLM 256M, Apache-2.0
931
+ console.log(map.width, map.height, boxes.map((b) => b.label), line);
932
+ ```
933
+
934
+ ### from the concepts
935
+
936
+ ```ts
937
+ import { createHub, stubFactory } from "@hackbuild/models";
938
+ import { tjsProvider, loadTransformers } from "@hackbuild/devices";
939
+ import { attachVision, mediapipeProvider, loadTasksVision, visionStubs, depth, detect, landmarks, caption } from "@hackbuild/vision";
940
+
941
+ const tjs = tjsProvider({ runtime: loadTransformers() });
942
+ const hub = createHub({ env, stub: new URLSearchParams(location.search).has("stub") });
943
+ attachVision(hub, tjs); // records plus transformers.js loaders
944
+ hub.provide("tjs", tjs.factory);
945
+ hub.provide("mediapipe", mediapipeProvider({ runtime: loadTasksVision() }));
946
+ hub.provide("stub", stubFactory(visionStubs()));
947
+
948
+ const map = await depth(hub, imageOrCanvas); // 0 to 1, larger is nearer, plus the raw range
949
+ const boxes = await detect(hub, video, { scoreThreshold: 0.4 });
950
+ const face = await landmarks(hub, "face", video); // falls through the chain, face.failures says what failed
951
+ const line = await caption(hub, frame); // serialized on the vlm chain
952
+ ```
953
+
954
+ ### from the concepts
955
+
956
+ ```ts
957
+ hub.onBusy((n) => (pill.textContent = n ? "model busy" : ""));
958
+ await depth(hub, frame, { size: "tiny", schedule: { minIntervalMs: 1200, frameBudgetMs: 20, when: "skip" } });
959
+ ```
960
+
961
+ ## Mistakes to avoid
962
+
963
+ - You import `@huggingface/transformers` or `@mediapipe/tasks-vision` at the top of your file. Pass the loaders instead: `tjsProvider({ runtime: loadTransformers() })` from @hackbuild/devices and `mediapipeProvider({ runtime: loadTasksVision() })`, and each runtime loads at run time from its pinned URL.
964
+ - You call `attachVision(hub, tjs)` and expect models to load. It adds the records and the transformers.js loaders only; also call `hub.provide("tjs", tjs.factory)` and `hub.provide("mediapipe", mediapipeProvider(...))`.
965
+ - You expect MediaPipe weights to go through the weight store on their own. They load by URL from `MP_MODELS`; pass `store` to `mediapipeProvider` to read them through @hackbuild/weights with resume, sha-256 and the licence line.
966
+ - You expect YOLO or a model from `PICKER_RECORDS` to answer `detect` or a `model` id. None is registered by default; build YOLO with `yoloRecord({ url })` for an export you supply (licence AGPL-3.0 unless you pass `licence`) and add it, or any picker record, with `hub.registry.add`.
967
+ - You run `depth` on the main thread beside a render loop and trust `schedule` to keep the frames. Run `depthWorker({ urls: transformersUrls(), device })` instead; it loads only registered depth records and throws "is not a registered depth record" unless you pass `record` with its licence named.
968
+
969
+ ## Errors this package throws
970
+
971
+ - `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
972
+ - `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
973
+ - `cutoutRgba: image is W x H, mask W2 x H2` (image and mask differ in size): pass the mask made from this image
974
+ - `encodePng: N bytes for W x H x C` (data shorter than width times height times channels): pass the full buffer
975
+ - `maskFromRle: counts cover N pixels of M` (the run length does not match its size): check `size` is `[height, width]`
976
+ - `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
977
+ - `ID: no mediapipe task for CAPABILITY` (the record's capability has no MediaPipe task): use detect, segment.person or a landmarks capability
978
+ - `ID: a mediapipe record needs source.url` (the record names no model file): set `source.url`
979
+ - `the transformers.js module has none of NAMES` (the runtime lacks the model class): use the pinned transformers.js 4.3.2
980
+ - `depth pipeline returned neither predicted_depth nor depth` (the pipeline gave another output): use a depth-estimation model
981
+ - `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
982
+ - `depth worker is not loaded` / `no transformers.js url loaded` (the worker could not import transformers.js): check the `urls`; use `transformersUrls()`