@hackbuild/vision 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Stub models for `?stub` pages and tests: no weights, fixed shapes. Depth
3
+ * is a left to right ramp, detection one centred box, segmentation a
4
+ * centred disc, landmarks a fixed set, captions a fixed line.
5
+ */
6
+ import type { ModelRecord } from "@hackbuild/models";
7
+ import { type EmbeddingCache } from "./segment.js";
8
+ import type { DepthModel, Detector, Landmarker, Segmenter, Vlm } from "./types.js";
9
+ export declare function rampDepth(): DepthModel;
10
+ export declare function centreDetector(label?: string): Detector;
11
+ /**
12
+ * A disc at the first positive point, or in the middle of the box, with a
13
+ * hole at each negative point. The stub encoder counts its runs on
14
+ * `encodes`, so tests can see the embedding cache work.
15
+ */
16
+ export declare function discSegmenter(): Segmenter & {
17
+ cache: EmbeddingCache<{
18
+ width: number;
19
+ height: number;
20
+ }>;
21
+ encodes: number;
22
+ };
23
+ export declare function fixedLandmarker(count: number, source?: string): Landmarker;
24
+ export declare function fixedVlm(text?: string): Vlm;
25
+ /** Stub builders to merge into `stubFactory({...})`. */
26
+ export declare function visionStubs(): Record<string, (r: ModelRecord) => unknown>;
package/dist/stubs.js ADDED
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Stub models for `?stub` pages and tests: no weights, fixed shapes. Depth
3
+ * is a left to right ramp, detection one centred box, segmentation a
4
+ * centred disc, landmarks a fixed set, captions a fixed line.
5
+ */
6
+ import { promptSegmenter } from "./segment.js";
7
+ const dims = (img) => {
8
+ const o = img;
9
+ return { width: o?.width ?? 64, height: o?.height ?? 48 };
10
+ };
11
+ export function rampDepth() {
12
+ return {
13
+ async estimate(img) {
14
+ const { width, height } = dims(img);
15
+ const data = new Float32Array(width * height);
16
+ for (let y = 0; y < height; y++)
17
+ for (let x = 0; x < width; x++)
18
+ data[y * width + x] = width > 1 ? x / (width - 1) : 0;
19
+ return { width, height, data, range: [0, 1] };
20
+ },
21
+ };
22
+ }
23
+ export function centreDetector(label = "person") {
24
+ return {
25
+ async detect(img) {
26
+ const { width, height } = dims(img);
27
+ return [{ label, score: 0.9, box: { x: width / 4, y: height / 4, w: width / 2, h: height / 2 } }];
28
+ },
29
+ };
30
+ }
31
+ /**
32
+ * A disc at the first positive point, or in the middle of the box, with a
33
+ * hole at each negative point. The stub encoder counts its runs on
34
+ * `encodes`, so tests can see the embedding cache work.
35
+ */
36
+ export function discSegmenter() {
37
+ const seg = Object.assign(promptSegmenter({
38
+ encode: async (img) => {
39
+ seg.encodes++;
40
+ return dims(img);
41
+ },
42
+ async decode({ width, height }, prompt) {
43
+ const b = prompt.box;
44
+ const pos = prompt.points?.find((p) => (p.label ?? 1) === 1);
45
+ const c = pos ?? (b ? { x: b.x + b.w / 2, y: b.y + b.h / 2 } : { x: width / 2, y: height / 2 });
46
+ const r = b ? Math.min(b.w, b.h) / 2 : Math.min(width, height) / 4;
47
+ const neg = (prompt.points ?? []).filter((p) => p.label === 0);
48
+ const data = new Uint8Array(width * height);
49
+ for (let y = 0; y < height; y++)
50
+ for (let x = 0; x < width; x++) {
51
+ const inside = (x - c.x) ** 2 + (y - c.y) ** 2 <= r * r;
52
+ const cut = neg.some((p) => (x - p.x) ** 2 + (y - p.y) ** 2 <= (r * r) / 4);
53
+ data[y * width + x] = inside && !cut ? 255 : 0;
54
+ }
55
+ return [{ width, height, data, score: 1 }];
56
+ },
57
+ }), { encodes: 0 });
58
+ const person = seg.segment;
59
+ // the person capability takes no prompt: a centred disc
60
+ seg.segment = (img, prompt, o) => person(img, prompt && (prompt.points?.length || prompt.box) ? prompt : { box: centreBox(img) }, o);
61
+ return seg;
62
+ }
63
+ const centreBox = (img) => {
64
+ const { width, height } = dims(img);
65
+ const r = Math.min(width, height) / 4;
66
+ return { x: width / 2 - r, y: height / 2 - r, w: 2 * r, h: 2 * r };
67
+ };
68
+ export function fixedLandmarker(count, source = "stub") {
69
+ return {
70
+ async detect() {
71
+ return { points: [Array.from({ length: count }, (_, i) => [i / count, 0.5, 0])], source };
72
+ },
73
+ };
74
+ }
75
+ export function fixedVlm(text = "a stub caption.") {
76
+ return { ask: async (_img, q) => (q ? `stub answer to: ${q}` : text) };
77
+ }
78
+ /** Stub builders to merge into `stubFactory({...})`. */
79
+ export function visionStubs() {
80
+ return {
81
+ depth: () => rampDepth(),
82
+ detect: () => centreDetector(),
83
+ segment: () => discSegmenter(),
84
+ "segment.person": () => discSegmenter(),
85
+ "landmarks.face": () => fixedLandmarker(478),
86
+ "landmarks.hand": () => fixedLandmarker(21),
87
+ "landmarks.pose": () => fixedLandmarker(33),
88
+ "vision.caption": () => fixedVlm(),
89
+ "vision.ask": () => fixedVlm(),
90
+ };
91
+ }
@@ -0,0 +1,100 @@
1
+ /** Shapes every vision provider returns, so stubs, MediaPipe, transformers.js and onnxruntime models are interchangeable. */
2
+ import type { EmbeddingCache } from "./segment.js";
3
+ /** Anything the runtimes accept: an image, canvas, video frame, bitmap, URL or data URL. */
4
+ export type ImageInput = unknown;
5
+ /** RGBA pixels, as ImageData has them. */
6
+ export interface Pixels {
7
+ width: number;
8
+ height: number;
9
+ data: Uint8ClampedArray | Uint8Array;
10
+ }
11
+ export interface DepthMap {
12
+ width: number;
13
+ height: number;
14
+ /** 0 to 1 per pixel, larger is nearer (Depth Anything is relative inverse depth). */
15
+ data: Float32Array;
16
+ /** The raw model output range before normalizing, for stable scale across frames (as earlier builds did). */
17
+ range: [min: number, max: number];
18
+ }
19
+ export interface DepthModel {
20
+ estimate(image: ImageInput): Promise<DepthMap>;
21
+ dispose?(): unknown;
22
+ }
23
+ export interface Box {
24
+ x: number;
25
+ y: number;
26
+ w: number;
27
+ h: number;
28
+ }
29
+ export interface Detection {
30
+ label: string;
31
+ score: number;
32
+ /** Pixels of the input image. */
33
+ box: Box;
34
+ }
35
+ export interface Detector {
36
+ detect(image: ImageInput, opts?: {
37
+ scoreThreshold?: number;
38
+ maxResults?: number;
39
+ timestamp?: number;
40
+ }): Promise<Detection[]>;
41
+ dispose?(): unknown;
42
+ }
43
+ export interface Mask {
44
+ width: number;
45
+ height: number;
46
+ /** 0 or 255 per pixel, or a confidence 0 to 255. */
47
+ data: Uint8Array;
48
+ score?: number;
49
+ }
50
+ export interface SegmentPrompt {
51
+ /** Points in image pixels; label 1 for object, 0 for background (a negative point). */
52
+ points?: {
53
+ x: number;
54
+ y: number;
55
+ label?: 0 | 1;
56
+ }[];
57
+ /** A box around the object, image pixels. */
58
+ box?: Box;
59
+ }
60
+ export interface SegmentOptions {
61
+ /** A stable key for the image, such as a hash; the image object itself when omitted. */
62
+ key?: string;
63
+ /** The caller's embedding cache; the segmenter's own when omitted. */
64
+ cache?: EmbeddingCache<unknown>;
65
+ }
66
+ export interface Segmenter {
67
+ segment(image: ImageInput, prompt?: SegmentPrompt, o?: SegmentOptions): Promise<Mask[]>;
68
+ dispose?(): unknown;
69
+ }
70
+ /** "gesture" is hand landmarks plus a canned gesture label per hand (MediaPipe gesture recognizer). */
71
+ export type LandmarkKind = "face" | "hand" | "pose" | "gesture";
72
+ export interface Landmarks {
73
+ /** One list per face, hand or body; x and y normalized 0 to 1, z relative. */
74
+ points: [number, number, number][][];
75
+ /** Face blendshapes by name, per face. */
76
+ blendshapes?: Record<string, number>[];
77
+ /** Hand labels, per hand. */
78
+ handedness?: string[];
79
+ /** Top canned gesture per hand ("Open_Palm", "Thumb_Up" and so on), null for "None". */
80
+ gestures?: ({
81
+ name: string;
82
+ score: number;
83
+ } | null)[];
84
+ /** Which record produced this, for status lines after a fallback. */
85
+ source: string;
86
+ }
87
+ export interface Landmarker {
88
+ detect(image: ImageInput, opts?: {
89
+ timestamp?: number;
90
+ }): Promise<Landmarks>;
91
+ dispose?(): unknown;
92
+ }
93
+ export interface Vlm {
94
+ /** Answer a question about an image; caption when the question is omitted. */
95
+ ask(image: ImageInput, question?: string, opts?: {
96
+ maxTokens?: number;
97
+ signal?: AbortSignal;
98
+ }): Promise<string>;
99
+ dispose?(): unknown;
100
+ }
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ /** Shapes every vision provider returns, so stubs, MediaPipe, transformers.js and onnxruntime models are interchangeable. */
2
+ export {};
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Depth Anything in a dedicated worker: transformers.js, the model, its
3
+ * pre and post processing and the normalization all run off the main
4
+ * thread, so a three.js scene keeps its frames while depth runs. The page
5
+ * sends RGBA pixels (ImageData, or anything with width, height and data)
6
+ * and gets a DepthMap back, both buffers transferred.
7
+ *
8
+ * Weights: Depth Anything V2 small, Apache-2.0, fetched by transformers.js
9
+ * from Hugging Face in the worker; nothing is bundled.
10
+ */
11
+ import { type Spawned, type SpawnOptions } from "@hackbuild/ai-env";
12
+ import type { DepthMap } from "./types.js";
13
+ import { type ModelRecord } from "@hackbuild/models";
14
+ export interface DepthWorkerOptions {
15
+ /** transformers.js ESM URLs tried in order (transformersUrls() from @hackbuild/devices). */
16
+ urls: readonly string[];
17
+ /**
18
+ * Default onnx-community/depth-anything-v2-small. Only models of the
19
+ * registered depth records load, at their pinned commit, since Depth
20
+ * Anything base and large carry CC-BY-NC-4.0 weights; pass `record` for
21
+ * another model with its licence named.
22
+ */
23
+ modelId?: string;
24
+ /** A depth record of your own: its modelId, revision and licence are used instead of the built in list. */
25
+ record?: ModelRecord;
26
+ /** Called once with the weight licence line before the model loads. Default console.info. */
27
+ onLicence?: (line: string) => void;
28
+ /** Default "webgpu". */
29
+ device?: "webgpu" | "wasm";
30
+ /** Default "fp16" on webgpu, "q8" on wasm. */
31
+ dtype?: string;
32
+ /** Worker rungs; module blob first by default. */
33
+ spawn?: Pick<SpawnOptions, "prefer" | "Worker" | "createObjectURL" | "readyMs" | "prelude">;
34
+ }
35
+ export interface Pixels {
36
+ width: number;
37
+ height: number;
38
+ data: Uint8ClampedArray | Uint8Array;
39
+ }
40
+ export interface DepthWorker {
41
+ /** The worker rung that started (module-blob, classic-blob or inline). */
42
+ readonly rung: Spawned["rung"];
43
+ readonly device: "webgpu" | "wasm";
44
+ estimate(image: Pixels): Promise<DepthMap>;
45
+ dispose(): void;
46
+ }
47
+ /** The worker's source. It imports transformers.js at load and answers run messages. */
48
+ export declare 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";
49
+ /** Spawns the worker and loads the model in it. */
50
+ export declare function depthWorker(o: DepthWorkerOptions): Promise<DepthWorker>;
package/dist/worker.js ADDED
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Depth Anything in a dedicated worker: transformers.js, the model, its
3
+ * pre and post processing and the normalization all run off the main
4
+ * thread, so a three.js scene keeps its frames while depth runs. The page
5
+ * sends RGBA pixels (ImageData, or anything with width, height and data)
6
+ * and gets a DepthMap back, both buffers transferred.
7
+ *
8
+ * Weights: Depth Anything V2 small, Apache-2.0, fetched by transformers.js
9
+ * from Hugging Face in the worker; nothing is bundled.
10
+ */
11
+ import { spawnWorker } from "@hackbuild/ai-env";
12
+ import { withPin } from "@hackbuild/models";
13
+ import { VISION_RECORDS } from "./records.js";
14
+ /** The worker's source. It imports transformers.js at load and answers run messages. */
15
+ export const DEPTH_WORKER_SOURCE = `
16
+ let pipe = null;
17
+ let RawImage = null;
18
+ const norm = (out) => {
19
+ const pd = out.predicted_depth;
20
+ if (pd && pd.data && pd.dims && pd.dims.length >= 2) {
21
+ const h = pd.dims[pd.dims.length - 2], w = pd.dims[pd.dims.length - 1];
22
+ let mn = Infinity, mx = -Infinity;
23
+ for (let i = 0; i < w * h; i++) { const v = pd.data[i]; if (v < mn) mn = v; if (v > mx) mx = v; }
24
+ const inv = mx > mn ? 1 / (mx - mn) : 0;
25
+ const data = new Float32Array(w * h);
26
+ for (let i = 0; i < w * h; i++) data[i] = (pd.data[i] - mn) * inv;
27
+ return { width: w, height: h, data, range: [mn, mx] };
28
+ }
29
+ const d = out.depth;
30
+ if (!d) throw new Error("depth pipeline returned neither predicted_depth nor depth");
31
+ const ch = d.channels || 1;
32
+ const data = new Float32Array(d.width * d.height);
33
+ for (let i = 0; i < data.length; i++) data[i] = d.data[i * ch] / 255;
34
+ return { width: d.width, height: d.height, data, range: [0, 255] };
35
+ };
36
+ self.onmessage = async (ev) => {
37
+ const m = ev.data;
38
+ if (!m || typeof m !== "object" || !("op" in m)) return;
39
+ try {
40
+ if (m.op === "load") {
41
+ let tjs = null, err = null;
42
+ const load = self.__import || ((u) => import(u));
43
+ for (const u of m.urls) { try { tjs = await load(u); break; } catch (e) { err = e; } }
44
+ if (!tjs) throw err || new Error("no transformers.js url loaded");
45
+ RawImage = tjs.RawImage;
46
+ pipe = await tjs.pipeline("depth-estimation", m.modelId, { device: m.device, dtype: m.dtype, revision: m.revision });
47
+ self.postMessage({ id: m.id, ok: true });
48
+ } else if (m.op === "run") {
49
+ if (!pipe) throw new Error("depth worker is not loaded");
50
+ const img = new RawImage(new Uint8ClampedArray(m.data), m.width, m.height, 4);
51
+ const d = norm(await pipe(img));
52
+ self.postMessage({ id: m.id, ok: true, depth: d }, [d.data.buffer]);
53
+ }
54
+ } catch (e) {
55
+ self.postMessage({ id: m.id, ok: false, error: String((e && e.message) || e) });
56
+ }
57
+ };
58
+ `;
59
+ /** Spawns the worker and loads the model in it. */
60
+ export async function depthWorker(o) {
61
+ const device = o.device ?? "webgpu";
62
+ const { worker, rung } = await spawnWorker(DEPTH_WORKER_SOURCE, { prefer: ["module-blob", "classic-blob"], ...o.spawn });
63
+ let next = 1;
64
+ const waiting = new Map();
65
+ worker.addEventListener("message", (ev) => {
66
+ const d = ev.data;
67
+ if (!d || typeof d.id !== "number")
68
+ return;
69
+ const w = waiting.get(d.id);
70
+ if (!w)
71
+ return;
72
+ waiting.delete(d.id);
73
+ if (d.ok)
74
+ w.resolve(d.depth);
75
+ else
76
+ w.reject(new Error(`depth worker: ${d.error ?? "error"}`));
77
+ });
78
+ // a worker that dies after startup rejects what is waiting instead of leaving estimate() pending
79
+ worker.addEventListener("error", (ev) => {
80
+ for (const w of waiting.values())
81
+ w.reject(new Error(`depth worker crashed: ${ev.message ?? "error event"}`));
82
+ waiting.clear();
83
+ });
84
+ const call = (msg, transfer = []) => new Promise((resolve, reject) => {
85
+ const id = next++;
86
+ waiting.set(id, { resolve, reject });
87
+ worker.postMessage({ ...msg, id }, transfer);
88
+ });
89
+ try {
90
+ const rec = o.record ?? VISION_RECORDS.find((r) => r.provides.includes("depth") && r.source.modelId === (o.modelId ?? "onnx-community/depth-anything-v2-small"));
91
+ if (!rec?.source.modelId)
92
+ throw new Error(`depth worker: ${o.modelId} is not a registered depth record; pass record with its licence named`);
93
+ const pinned = withPin(rec);
94
+ (o.onLicence ?? ((l) => console.info(l)))(`model ${pinned.id}: weight licence ${pinned.licence}. the weights are not part of this library.`);
95
+ await call({
96
+ op: "load",
97
+ urls: [...o.urls],
98
+ modelId: pinned.source.modelId,
99
+ revision: pinned.source.revision ?? "main",
100
+ device,
101
+ dtype: o.dtype ?? (device === "webgpu" ? "fp16" : "q8"),
102
+ });
103
+ }
104
+ catch (e) {
105
+ worker.terminate();
106
+ throw e;
107
+ }
108
+ return {
109
+ rung,
110
+ device,
111
+ async estimate(image) {
112
+ const copy = new Uint8ClampedArray(image.data);
113
+ return (await call({ op: "run", width: image.width, height: image.height, data: copy.buffer }, [copy.buffer]));
114
+ },
115
+ dispose() {
116
+ for (const w of waiting.values())
117
+ w.reject(new Error("depth worker disposed"));
118
+ waiting.clear();
119
+ worker.terminate();
120
+ },
121
+ };
122
+ }
package/dist/yolo.d.ts ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * A detector over a YOLOv8 style ONNX export: a square letterbox (640 by
3
+ * default, grey 114 padding), one [1, 4 + classes, anchors] output read as
4
+ * centre x, centre y, width, height and class scores, then non maximum
5
+ * suppression per class. Written from the published output layout; the
6
+ * weights are external and AGPL-3.0.
7
+ */
8
+ import type { OrtModel } from "@hackbuild/devices";
9
+ import type { Box, Detection, Detector, Pixels } from "./types.js";
10
+ export declare const COCO_LABELS: string[];
11
+ export interface Letterbox {
12
+ scale: number;
13
+ padX: number;
14
+ padY: number;
15
+ size: number;
16
+ }
17
+ export declare function letterboxParams(w: number, h: number, size?: number): Letterbox;
18
+ /** RGBA pixels to a planar float tensor [1, 3, size, size] in 0 to 1, nearest neighbour, grey padding. */
19
+ export declare function letterboxTensor(px: Pixels, size?: number): {
20
+ data: Float32Array;
21
+ lb: Letterbox;
22
+ };
23
+ export declare function iou(a: Box, b: Box): number;
24
+ /** Greedy NMS within each label, best first, then the top `max` overall. */
25
+ export declare function nms(dets: Detection[], iouThreshold?: number, max?: number): Detection[];
26
+ /** Decode a [4 + classes, anchors] output (batch 1) into boxes in source pixels. */
27
+ export declare function decodeYolo(out: ArrayLike<number>, dims: readonly number[], lb: Letterbox, src: {
28
+ width: number;
29
+ height: number;
30
+ }, o?: {
31
+ scoreThreshold?: number;
32
+ iou?: number;
33
+ max?: number;
34
+ labels?: readonly string[];
35
+ }): Detection[];
36
+ /** Wrap an ort model as a Detector. Images must be Pixels, or `toPixels` must turn them into Pixels. */
37
+ export declare function yoloDetector(m: OrtModel, o?: {
38
+ size?: number;
39
+ labels?: readonly string[];
40
+ toPixels?: (img: unknown) => Pixels;
41
+ }): Detector;
42
+ /** Detection cadence as earlier builds ran it: wait max(0.45 s, 4 times the last latency) between runs. */
43
+ export declare function detectCadenceMs(lastLatencyMs: number): number;
package/dist/yolo.js ADDED
@@ -0,0 +1,113 @@
1
+ /**
2
+ * A detector over a YOLOv8 style ONNX export: a square letterbox (640 by
3
+ * default, grey 114 padding), one [1, 4 + classes, anchors] output read as
4
+ * centre x, centre y, width, height and class scores, then non maximum
5
+ * suppression per class. Written from the published output layout; the
6
+ * weights are external and AGPL-3.0.
7
+ */
8
+ export const COCO_LABELS = ("person,bicycle,car,motorcycle,airplane,bus,train,truck,boat,traffic light,fire hydrant,stop sign,parking meter,bench,bird,cat,dog,horse,sheep,cow," +
9
+ "elephant,bear,zebra,giraffe,backpack,umbrella,handbag,tie,suitcase,frisbee,skis,snowboard,sports ball,kite,baseball bat,baseball glove,skateboard," +
10
+ "surfboard,tennis racket,bottle,wine glass,cup,fork,knife,spoon,bowl,banana,apple,sandwich,orange,broccoli,carrot,hot dog,pizza,donut,cake,chair,couch," +
11
+ "potted plant,bed,dining table,toilet,tv,laptop,mouse,remote,keyboard,cell phone,microwave,oven,toaster,sink,refrigerator,book,clock,vase,scissors," +
12
+ "teddy bear,hair drier,toothbrush").split(",");
13
+ export function letterboxParams(w, h, size = 640) {
14
+ const scale = Math.min(size / w, size / h);
15
+ return { scale, padX: Math.floor((size - Math.round(w * scale)) / 2), padY: Math.floor((size - Math.round(h * scale)) / 2), size };
16
+ }
17
+ /** RGBA pixels to a planar float tensor [1, 3, size, size] in 0 to 1, nearest neighbour, grey padding. */
18
+ export function letterboxTensor(px, size = 640) {
19
+ const lb = letterboxParams(px.width, px.height, size);
20
+ const plane = size * size;
21
+ const data = new Float32Array(3 * plane).fill(114 / 255);
22
+ const w = Math.round(px.width * lb.scale);
23
+ const h = Math.round(px.height * lb.scale);
24
+ for (let y = 0; y < h; y++) {
25
+ const sy = Math.min(px.height - 1, Math.floor(y / lb.scale));
26
+ for (let x = 0; x < w; x++) {
27
+ const sx = Math.min(px.width - 1, Math.floor(x / lb.scale));
28
+ const s = (sy * px.width + sx) * 4;
29
+ const d = (y + lb.padY) * size + x + lb.padX;
30
+ data[d] = px.data[s] / 255;
31
+ data[plane + d] = px.data[s + 1] / 255;
32
+ data[2 * plane + d] = px.data[s + 2] / 255;
33
+ }
34
+ }
35
+ return { data, lb };
36
+ }
37
+ export function iou(a, b) {
38
+ const x1 = Math.max(a.x, b.x);
39
+ const y1 = Math.max(a.y, b.y);
40
+ const x2 = Math.min(a.x + a.w, b.x + b.w);
41
+ const y2 = Math.min(a.y + a.h, b.y + b.h);
42
+ const inter = Math.max(0, x2 - x1) * Math.max(0, y2 - y1);
43
+ const u = a.w * a.h + b.w * b.h - inter;
44
+ return u > 0 ? inter / u : 0;
45
+ }
46
+ /** Greedy NMS within each label, best first, then the top `max` overall. */
47
+ export function nms(dets, iouThreshold = 0.45, max = 13) {
48
+ const sorted = [...dets].sort((a, b) => b.score - a.score);
49
+ const keep = [];
50
+ for (const d of sorted) {
51
+ if (keep.some((k) => k.label === d.label && iou(k.box, d.box) > iouThreshold))
52
+ continue;
53
+ keep.push(d);
54
+ if (keep.length >= max)
55
+ break;
56
+ }
57
+ return keep;
58
+ }
59
+ /** Decode a [4 + classes, anchors] output (batch 1) into boxes in source pixels. */
60
+ export function decodeYolo(out, dims, lb, src, o = {}) {
61
+ const rows = dims[dims.length - 2];
62
+ const n = dims[dims.length - 1];
63
+ const classes = rows - 4;
64
+ const thr = o.scoreThreshold ?? 0.25;
65
+ const labels = o.labels ?? COCO_LABELS;
66
+ const dets = [];
67
+ for (let a = 0; a < n; a++) {
68
+ let best = -1;
69
+ let score = thr;
70
+ for (let c = 0; c < classes; c++) {
71
+ const s = out[(4 + c) * n + a];
72
+ if (s > score) {
73
+ score = s;
74
+ best = c;
75
+ }
76
+ }
77
+ if (best < 0)
78
+ continue;
79
+ const cx = out[a];
80
+ const cy = out[n + a];
81
+ const w = out[2 * n + a];
82
+ const h = out[3 * n + a];
83
+ const x0 = Math.max(0, (cx - w / 2 - lb.padX) / lb.scale);
84
+ const y0 = Math.max(0, (cy - h / 2 - lb.padY) / lb.scale);
85
+ const x1 = Math.min(src.width, (cx + w / 2 - lb.padX) / lb.scale);
86
+ const y1 = Math.min(src.height, (cy + h / 2 - lb.padY) / lb.scale);
87
+ dets.push({ label: labels[best] ?? String(best), score, box: { x: x0, y: y0, w: x1 - x0, h: y1 - y0 } });
88
+ }
89
+ return nms(dets, o.iou ?? 0.45, o.max ?? 13);
90
+ }
91
+ /** Wrap an ort model as a Detector. Images must be Pixels, or `toPixels` must turn them into Pixels. */
92
+ export function yoloDetector(m, o = {}) {
93
+ const size = o.size ?? 640;
94
+ return {
95
+ async detect(image, opts = {}) {
96
+ const px = o.toPixels ? o.toPixels(image) : image;
97
+ const { data, lb } = letterboxTensor(px, size);
98
+ const feeds = { [m.session.inputNames[0]]: new m.ort.Tensor("float32", data, [1, 3, size, size]) };
99
+ const res = await m.session.run(feeds);
100
+ const t = res[m.session.outputNames[0]];
101
+ return decodeYolo(t.data, t.dims, lb, px, {
102
+ ...(opts.scoreThreshold !== undefined ? { scoreThreshold: opts.scoreThreshold } : {}),
103
+ ...(opts.maxResults !== undefined ? { max: opts.maxResults } : {}),
104
+ ...(o.labels ? { labels: o.labels } : {}),
105
+ });
106
+ },
107
+ dispose: () => m.dispose(),
108
+ };
109
+ }
110
+ /** Detection cadence as earlier builds ran it: wait max(0.45 s, 4 times the last latency) between runs. */
111
+ export function detectCadenceMs(lastLatencyMs) {
112
+ return Math.max(450, 4 * lastLatencyMs);
113
+ }
package/how.ts ADDED
@@ -0,0 +1,32 @@
1
+ // how this works: the fold of the package page and of the suite tool. Plain data, no imports;
2
+ // checked by tsconfig.how.json, shipped in the tarball, never imported by the runtime entry.
3
+ const how: HowDoc = {
4
+ packages: ["@hackbuild/vision"],
5
+ what: `perception through the \`@hackbuild/models\` hub: depth, detection, segmentation, face, hand and pose landmarks with a fallback chain, and captions and questions through small vlms, plus a webcam loop helper and a result cache.`,
6
+ how: [
7
+ `every task is a capability on the \`@hackbuild/models\` hub with a fallback chain of records, so a call names what it wants (depth, detect, segment, face, hand, pose, caption) and the hub picks a model this device can run.`,
8
+ `every call takes \`schedule\` (passed to \`hub.run\`: \`minIntervalMs\`, \`idleOnly\`, \`frameBudgetMs\`) and \`size\` or \`maxMB\` to route to a smaller model, so a rendering page keeps its frames.`,
9
+ `\`depthWorker\` runs depth anything v2 small (apache-2.0) in a dedicated worker, so pre and post processing and the readback leave the page thread. the yolo decoder is written from the published output layout and is never registered by default.`,
10
+ ],
11
+ install: "npm install @hackbuild/vision",
12
+ today: `git clone https://github.com/hackbuild/hackbuild-browser-ai
13
+ cd hackbuild-browser-ai && npm ci && npm run build
14
+ npm pack -w @hackbuild/vision`,
15
+ code: `import { createHub, stubFactory } from "@hackbuild/models";
16
+ import { tjsProvider, loadTransformers } from "@hackbuild/devices";
17
+ import { attachVision, mediapipeProvider, loadTasksVision, visionStubs, depth, detect, landmarks, caption } from "@hackbuild/vision";
18
+
19
+ const tjs = tjsProvider({ runtime: loadTransformers() });
20
+ const hub = createHub({ env, stub: new URLSearchParams(location.search).has("stub") });
21
+ attachVision(hub, tjs); // records plus transformers.js loaders
22
+ hub.provide("tjs", tjs.factory);
23
+ hub.provide("mediapipe", mediapipeProvider({ runtime: loadTasksVision() }));
24
+ hub.provide("stub", stubFactory(visionStubs()));
25
+
26
+ const map = await depth(hub, imageOrCanvas); // 0 to 1, larger is nearer, plus the raw range
27
+ const boxes = await detect(hub, video, { scoreThreshold: 0.4 });
28
+ const face = await landmarks(hub, "face", video); // falls through the chain, face.failures says what failed
29
+ const line = await caption(hub, frame); // serialized on the vlm chain`,
30
+ links: { page: "https://hackbuild.github.io/hackbuild-browser-ai/vision/", source: "https://github.com/hackbuild/hackbuild-browser-ai/tree/main/packages/vision" },
31
+ };
32
+ export default how;
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@hackbuild/vision",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Perception through the models hub: depth (Depth Anything V2 small), detection (MediaPipe EfficientDet, YOLO as an optional external model), segmentation, face, hand and pose landmarks with a fallback chain, captions and questions through small VLMs, a webcam loop helper and a result cache.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Moheeb Zara <hackbuildvideo@gmail.com>",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/hackbuild/hackbuild-browser-ai.git",
11
+ "directory": "packages/vision"
12
+ },
13
+ "engines": {
14
+ "node": "^22.18.0 || >=24.11.0"
15
+ },
16
+ "sideEffects": false,
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js"
21
+ }
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "how.ts",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "unpkg": "./dist/single/index.iife.js",
30
+ "jsdelivr": "./dist/single/index.iife.js",
31
+ "scripts": {
32
+ "build": "tsc -b"
33
+ },
34
+ "dependencies": {
35
+ "@hackbuild/ai-env": "0.1.1",
36
+ "@hackbuild/models": "0.1.1",
37
+ "@hackbuild/devices": "0.1.1",
38
+ "@hackbuild/weights": "0.1.1"
39
+ }
40
+ }