@hackbuild/vision 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  // packages/models/src/record.ts
2
- /** The onnxruntime-web ladder the earlier transcription tool walks after one fetch: webgpu at basic, all, disabled, then wasm. */
2
+ /** The onnxruntime-web ladder to walk after one fetch: webgpu at basic, all, disabled, then wasm. */
3
3
  function ortLadder() {
4
4
  return [
5
5
  {
@@ -33,6 +33,7 @@ function ortLadder() {
33
33
  ];
34
34
  }
35
35
  // packages/models/src/pins.ts
36
+ /** Pinned commits and file hashes per Hugging Face repo, written by tools/pin-weights.mjs. */
36
37
  const PINS = {
37
38
  "HuggingFaceTB/SmolLM2-135M-Instruct": {
38
39
  "revision": "12fd25f77366fa6b3b4b768ec3050bf629380bac",
@@ -2881,6 +2882,7 @@ const PINS = {
2881
2882
  * added to a registry, so every loader resolves `resolve/<commit>/` URLs,
2882
2883
  * and pinnedSha gives the SHA-256 for such a URL.
2883
2884
  */
2885
+ /** The pin of a repo, or undefined when the repo is not pinned. */
2884
2886
  function pinOf(repo) {
2885
2887
  return repo && Object.hasOwn(PINS, repo) ? PINS[repo] : void 0;
2886
2888
  }
@@ -2919,25 +2921,25 @@ function tjsLadder(spec) {
2919
2921
  }
2920
2922
  return spec.wasmFirst ? [...cpu, ...gpu] : [...gpu, ...cpu];
2921
2923
  }
2922
- /** onnxruntime-web rungs: the earlier transcription tool walk, or wasm only when the graph is known to fail on webgpu. */
2924
+ /** onnxruntime-web rungs: webgpu then wasm, or wasm only when the graph is known to fail on webgpu. */
2923
2925
  function ortRungs(opts = {}) {
2924
2926
  const all = ortLadder();
2925
2927
  return opts.webgpu === false ? all.filter((r) => r.device === "wasm") : all;
2926
2928
  }
2927
- /** Ladders by name, from the builds. Each model record may copy one or write its own. */
2929
+ /** Ladders by name, one per model family. Each model record may copy one or write its own. */
2928
2930
  const LADDERS = {
2929
- /** an earlier relief bench runDepth. */
2931
+ /** Depth: fp16 then fp32 on webgpu, q8 then fp32 on wasm. */
2930
2932
  depth: () => tjsLadder({
2931
2933
  webgpu: ["fp16", "fp32"],
2932
2934
  wasm: ["q8", "fp32"]
2933
2935
  }),
2934
- /** earlier builds: perception models on cpu by default. */
2936
+ /** Perception models on cpu by default. */
2935
2937
  perceptionCpu: () => tjsLadder({
2936
2938
  webgpu: ["fp32"],
2937
2939
  wasm: ["q8", "fp32"],
2938
2940
  wasmFirst: true
2939
2941
  }),
2940
- /** whisper-large-v3-turbo (weights MIT), as the earlier transcription tool ran it. */
2942
+ /** whisper-large-v3-turbo (weights MIT). */
2941
2943
  whisperTurbo: () => tjsLadder({
2942
2944
  webgpu: [{
2943
2945
  encoder_model: "fp16",
@@ -2962,7 +2964,7 @@ const LADDERS = {
2962
2964
  decoder_model_merged: "q8"
2963
2965
  }]
2964
2966
  }),
2965
- /** SmolVLM (weights Apache-2.0): fp16 embed and vision, q4 decoder on webgpu; q8 vision on wasm, as earlier builds ran it. */
2967
+ /** SmolVLM (weights Apache-2.0): fp16 embed and vision, q4 decoder on webgpu; q8 vision on wasm. */
2966
2968
  smolvlm: () => tjsLadder({
2967
2969
  webgpu: [{
2968
2970
  embed_tokens: "fp32",
@@ -2980,11 +2982,12 @@ const LADDERS = {
2980
2982
  }],
2981
2983
  freshHeapRetry: true
2982
2984
  }),
2983
- /** earlier builds: q4f16 on webgpu only. */
2985
+ /** q4f16 on webgpu only. */
2984
2986
  vlmGpuOnly: () => tjsLadder({ webgpu: ["q4f16", "q4"] }),
2985
2987
  ort: ortRungs
2986
2988
  };
2987
2989
  // packages/ai-env/src/source.ts
2990
+ /** Applies string or RegExp rewrites to source text and reports each one that matched nothing. */
2988
2991
  function rewriteSource(src, rewrites) {
2989
2992
  let text = src;
2990
2993
  const missed = [];
@@ -3014,7 +3017,7 @@ function rewriteSource(src, rewrites) {
3014
3017
  const MODULE_WORKER = /new\s+Worker\(\s*([^,()]+(?:\([^()]*\))?[^,()]*)\s*,\s*\{([^{}]*)\}\s*\)/g;
3015
3018
  /**
3016
3019
  * Turn module workers into classic workers: Chrome refuses module workers
3017
- * from a file:// page (as earlier builds did). Other option keys
3020
+ * from a file:// page. Other option keys
3018
3021
  * are kept. Returns the text and how many constructors changed.
3019
3022
  */
3020
3023
  function toClassicWorker(src) {
@@ -3059,6 +3062,7 @@ function bytesToBase64(bytes) {
3059
3062
  }
3060
3063
  return parts.join("");
3061
3064
  }
3065
+ /** Encodes text as a base64 data: URL, JavaScript by default. */
3062
3066
  function textToDataUrl(text, mime = "text/javascript") {
3063
3067
  return `data:${mime};base64,${bytesToBase64(new TextEncoder().encode(text))}`;
3064
3068
  }
@@ -3068,7 +3072,7 @@ function textToDataUrl(text, mime = "text/javascript") {
3068
3072
  *
3069
3073
  * importEsm: plain import() first when nothing needs patching and the page
3070
3074
  * is served over http(s); else fetch the text, patch it, import it from a
3071
- * Blob URL, then from a base64 data: URL (as earlier builds did). Each URL in
3075
+ * Blob URL, then from a base64 data: URL. Each URL in
3072
3076
  * `urls` is tried in order, so a CDN fallback list is one call.
3073
3077
  *
3074
3078
  * spawnWorker: the worker ladder, written once. Rungs are module-blob,
@@ -3087,6 +3091,10 @@ async function sha256Text(text) {
3087
3091
  const d = new Uint8Array(await subtle.digest("SHA-256", new TextEncoder().encode(text)));
3088
3092
  return Array.from(d, (b) => b.toString(16).padStart(2, "0")).join("");
3089
3093
  }
3094
+ /**
3095
+ * The error importEsm and spawnWorker throw when every URL or rung failed, with one entry per
3096
+ * attempt in `attempts`.
3097
+ */
3090
3098
  var LoadError = class extends Error {
3091
3099
  attempts;
3092
3100
  constructor(message, attempts) {
@@ -3102,6 +3110,10 @@ const nativeImport = (s) => import(
3102
3110
  function errText(e) {
3103
3111
  return e instanceof Error ? `${e.name}: ${e.message}` : String(e);
3104
3112
  }
3113
+ /**
3114
+ * Imports an ES module from the first URL that loads, through plain import, then a patched Blob
3115
+ * URL, then a base64 data: URL, checking a SHA-256 when you give one.
3116
+ */
3105
3117
  async function importEsm(urls, opts = {}) {
3106
3118
  const list = typeof urls === "string" ? [urls] : urls;
3107
3119
  const importer = opts.importer ?? nativeImport;
@@ -3397,6 +3409,7 @@ async function spawnWorker(source, opts = {}) {
3397
3409
  * only for a URL the app supplies; YOLOv10 n, s and m, FastSAM and the face
3398
3410
  * swap set sit in PICKER_RECORDS.
3399
3411
  */
3412
+ /** The MediaPipe model storage base URL the MediaPipe records load from. */
3400
3413
  const MP_MODELS = "https://storage.googleapis.com/mediapipe-models/";
3401
3414
  /** MediaPipe ladder: GPU delegate (webgl), then the CPU delegate (wasm). */
3402
3415
  const mediapipeLadder = () => [{ device: "webgl" }, { device: "wasm" }];
@@ -3417,6 +3430,7 @@ const mp = (id, provides, path, sizeMB, label, verdict = "light, on the gpu", gr
3417
3430
  place: "main",
3418
3431
  runtime: "@mediapipe/tasks-vision@1.2.3"
3419
3432
  });
3433
+ /** The vision records registered by `attachVision`: Depth Anything V2 small, MediaPipe detection, segmentation and landmarks, SlimSAM, SmolVLM 256M and LFM2-VL 450M. */
3420
3434
  const VISION_RECORDS = [
3421
3435
  {
3422
3436
  id: "depth-anything-v2-small",
@@ -3434,7 +3448,7 @@ const VISION_RECORDS = [
3434
3448
  commercial: true,
3435
3449
  place: "cpu-worker",
3436
3450
  runtime: "@huggingface/transformers@4.3.2",
3437
- notes: ["earlier builds: fp16 on webgpu, fp32 on the same device after a failure"]
3451
+ notes: ["fp16 on webgpu, fp32 on the same device after a failure"]
3438
3452
  },
3439
3453
  mp("efficientdet-lite0", "detect", "object_detector/efficientdet_lite0/float16/1/efficientdet_lite0.tflite", 7, "mediapipe efficientdet lite0 (coco, 80 classes)", "light, 80 things"),
3440
3454
  mp("selfie-segmenter", "segment.person", "image_segmenter/selfie_segmenter/float16/latest/selfie_segmenter.tflite", 1, "mediapipe selfie segmenter"),
@@ -3466,7 +3480,7 @@ const VISION_RECORDS = [
3466
3480
  commercial: true,
3467
3481
  place: "cpu-worker",
3468
3482
  runtime: "@huggingface/transformers@4.3.2",
3469
- notes: ["earlier builds: one image embedding, then any number of point prompts"]
3483
+ notes: ["one image embedding, then any number of point prompts"]
3470
3484
  },
3471
3485
  {
3472
3486
  id: "smolvlm-256m-instruct",
@@ -3509,13 +3523,12 @@ const VISION_RECORDS = [
3509
3523
  commercial: "unknown",
3510
3524
  place: "gpu",
3511
3525
  runtime: "@huggingface/transformers@4.3.2",
3512
- notes: ["earlier builds: q4f16 on webgpu only; the licence limits commercial use by revenue, read it before shipping"]
3526
+ notes: ["q4f16 on webgpu only; the licence limits commercial use by revenue, read it before shipping"]
3513
3527
  }
3514
3528
  ];
3515
3529
  /**
3516
3530
  * Records listed for pickers and never registered by default, so a hub's
3517
- * routing by capability keeps its small defaults: larger alternates the
3518
- * earlier tools offered (smolvlm 500m and 2 video, gemma 4 e2b, two more
3531
+ * routing by capability keeps its small defaults: larger alternates (smolvlm 500m and 2 video, gemma 4 e2b, two more
3519
3532
  * depth models), and records under licences that limit use (YOLOv10 and
3520
3533
  * FastSAM are AGPL-3.0 upstream, Ultralytics; the face swap set is
3521
3534
  * InsightFace, non-commercial). A hub that runs one adds it itself. Sizes
@@ -3549,8 +3562,9 @@ const yolo10 = (size, mb, speed, verdict) => ({
3549
3562
  licence: "AGPL-3.0 (Ultralytics weights, the model card's licence field)",
3550
3563
  commercial: false,
3551
3564
  place: "gpu",
3552
- notes: ["output [1, 300, 6] after the model's own selection, so no nms pass (vendor, the yolov10 paper)", "an earlier room offered nano, small and medium"]
3565
+ notes: ["output [1, 300, 6] after the model's own selection, so no nms pass (vendor, the yolov10 paper)", "comes in nano, small and medium"]
3553
3566
  });
3567
+ /** Records listed for pickers and never registered by default: larger alternates, and records under licences that limit use (YOLOv10, FastSAM, the face swap set). */
3554
3568
  const PICKER_RECORDS = [
3555
3569
  {
3556
3570
  id: "smolvlm-500m-instruct",
@@ -3593,7 +3607,7 @@ const PICKER_RECORDS = [
3593
3607
  commercial: true,
3594
3608
  place: "cpu-worker",
3595
3609
  runtime: "@huggingface/transformers@4.3.2",
3596
- notes: ["an earlier room offered it beside smolvlm 256m and 500m"]
3610
+ notes: ["an option beside smolvlm 256m and 500m"]
3597
3611
  },
3598
3612
  {
3599
3613
  id: "depth-anything-v2-base",
@@ -3650,7 +3664,7 @@ const PICKER_RECORDS = [
3650
3664
  commercial: true,
3651
3665
  place: "gpu",
3652
3666
  runtime: "@huggingface/transformers@4.3.2",
3653
- notes: ["an earlier dog sim used it as the cortex at about 3.3 GB (vendor there)"]
3667
+ notes: ["about 3.3 GB (vendor)"]
3654
3668
  },
3655
3669
  yolo10("n", 9, "instant", "nano, quick"),
3656
3670
  yolo10("s", 28, "fast", "small, sharper"),
@@ -3679,7 +3693,7 @@ const PICKER_RECORDS = [
3679
3693
  licence: "AGPL-3.0 upstream (Ultralytics FastSAM); the export's card says apache-2.0",
3680
3694
  commercial: false,
3681
3695
  place: "cpu-worker",
3682
- notes: ["an earlier mask tool found every mask in one pass on onnxruntime-web (93 MB there, vendor)", "segment everything: prototype masks, nms, then a pick by click"]
3696
+ notes: ["finds every mask in one pass on onnxruntime-web (93 MB, vendor)", "segment everything: prototype masks, nms, then a pick by click"]
3683
3697
  },
3684
3698
  {
3685
3699
  id: "scrfd-10g",
@@ -3752,7 +3766,7 @@ const PICKER_RECORDS = [
3752
3766
  licence: "InsightFace: non-commercial research only; the mirror's card says gpl-3.0",
3753
3767
  commercial: false,
3754
3768
  place: "gpu",
3755
- notes: ["128 px faces; an earlier face swap tool pasted the result back with a feathered mask"]
3769
+ notes: ["128 px faces; paste the result back with a feathered mask"]
3756
3770
  }
3757
3771
  ];
3758
3772
  /** A face landmark fallback record over face-api.js tiny nets (code MIT; weights MIT from @vladmandic/face-api). */
@@ -3800,7 +3814,7 @@ function yoloRecord(o) {
3800
3814
  licence: o.licence ?? "AGPL-3.0 (Ultralytics YOLOv8 weights), supplied by the app",
3801
3815
  commercial: false,
3802
3816
  place: "gpu",
3803
- notes: ["earlier builds: 640 letterbox, per class nms at iou 0.45, at most 13 boxes"]
3817
+ notes: ["640 letterbox, per class nms at iou 0.45, at most 13 boxes"]
3804
3818
  };
3805
3819
  }
3806
3820
  // packages/vision/src/segment.ts
@@ -3885,7 +3899,7 @@ async function toRaw(tjs, img) {
3885
3899
  const R = tjs.RawImage;
3886
3900
  return R?.read ? R.read(img) : img;
3887
3901
  }
3888
- /** 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). */
3902
+ /** Normalize a depth pipeline result. predicted_depth keeps the raw range; depth is the 8 bit image. */
3889
3903
  function depthFromOutput(out) {
3890
3904
  const pd = out.predicted_depth;
3891
3905
  if (pd && pd.data && pd.dims?.length >= 2) {
@@ -3920,6 +3934,7 @@ function depthFromOutput(out) {
3920
3934
  range: [0, 255]
3921
3935
  };
3922
3936
  }
3937
+ /** The transformers.js loader for depth records: a depth-estimation pipeline wrapped as a {@link DepthModel}. */
3923
3938
  async function depthLoader(ctx) {
3924
3939
  const pipe = await ctx.tjs.pipeline("depth-estimation", ctx.record.source.modelId, ctx.options);
3925
3940
  return {
@@ -3927,6 +3942,7 @@ async function depthLoader(ctx) {
3927
3942
  dispose: () => pipe.dispose?.()
3928
3943
  };
3929
3944
  }
3945
+ /** The transformers.js loader for caption and question records: the VLM's processor and model wrapped as a {@link Vlm}. */
3930
3946
  async function vlmLoader(ctx) {
3931
3947
  const id = ctx.record.source.modelId;
3932
3948
  const processor = await cls(ctx.tjs, "AutoProcessor").from_pretrained(id);
@@ -4014,7 +4030,9 @@ async function samLoader(ctx) {
4014
4030
  });
4015
4031
  }
4016
4032
  // packages/vision/src/yolo.ts
4033
+ /** The 80 COCO class names, in YOLO class index order. */
4017
4034
  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,elephant,bear,zebra,giraffe,backpack,umbrella,handbag,tie,suitcase,frisbee,skis,snowboard,sports ball,kite,baseball bat,baseball glove,skateboard,surfboard,tennis racket,bottle,wine glass,cup,fork,knife,spoon,bowl,banana,apple,sandwich,orange,broccoli,carrot,hot dog,pizza,donut,cake,chair,couch,potted plant,bed,dining table,toilet,tv,laptop,mouse,remote,keyboard,cell phone,microwave,oven,toaster,sink,refrigerator,book,clock,vase,scissors,teddy bear,hair drier,toothbrush".split(",");
4035
+ /** The scale and padding that fit a `w` by `h` image into a `size` square (640 by default), centred. */
4018
4036
  function letterboxParams(w, h, size = 640) {
4019
4037
  const scale = Math.min(size / w, size / h);
4020
4038
  return {
@@ -4047,6 +4065,7 @@ function letterboxTensor(px, size = 640) {
4047
4065
  lb
4048
4066
  };
4049
4067
  }
4068
+ /** Intersection over union of two boxes, 0 to 1. */
4050
4069
  function iou(a, b) {
4051
4070
  const x1 = Math.max(a.x, b.x);
4052
4071
  const y1 = Math.max(a.y, b.y);
@@ -4130,7 +4149,7 @@ function yoloDetector(m, o = {}) {
4130
4149
  dispose: () => m.dispose()
4131
4150
  };
4132
4151
  }
4133
- /** Detection cadence as earlier builds ran it: wait max(0.45 s, 4 times the last latency) between runs. */
4152
+ /** Detection cadence: wait max(0.45 s, 4 times the last latency) between runs. */
4134
4153
  function detectCadenceMs(lastLatencyMs) {
4135
4154
  return Math.max(450, 4 * lastLatencyMs);
4136
4155
  }
@@ -4160,6 +4179,7 @@ async function withModel(hub, what, fn, o = {}) {
4160
4179
  }
4161
4180
  }
4162
4181
  const target = (cap, o) => o.model ? { id: o.model } : cap;
4182
+ /** A depth map of an image from the routed depth model (Depth Anything V2 small by default), loaded and released through the hub. */
4163
4183
  function depth(hub, image, o = {}) {
4164
4184
  return withModel(hub, target("depth", o), (m) => m.estimate(image), o);
4165
4185
  }
@@ -4167,6 +4187,7 @@ function asDetector(v, toPixels) {
4167
4187
  if (v && typeof v === "object" && "sessions" in v) return yoloDetector(v, toPixels ? { toPixels } : {});
4168
4188
  return v;
4169
4189
  }
4190
+ /** Objects in an image from the routed detector (MediaPipe EfficientDet by default, or a YOLO ort model), loaded and released through the hub. */
4170
4191
  function detect(hub, image, o = {}) {
4171
4192
  const opts = {};
4172
4193
  if (o.scoreThreshold !== void 0) opts.scoreThreshold = o.scoreThreshold;
@@ -4224,6 +4245,7 @@ async function landmarks(hub, kind, image, o = {}) {
4224
4245
  function caption(hub, image, o = {}) {
4225
4246
  return hub.chain("vlm")(() => withModel(hub, target("vision.caption", o), (m) => m.ask(image, void 0, o.maxTokens ? { maxTokens: o.maxTokens } : {}), o));
4226
4247
  }
4248
+ /** Answer a question about an image with the routed vision language model. VLM calls are serialized on one chain. */
4227
4249
  function ask(hub, image, question, o = {}) {
4228
4250
  return hub.chain("vlm")(() => withModel(hub, target("vision.ask", o), (m) => m.ask(image, question, o.maxTokens ? { maxTokens: o.maxTokens } : {}), o));
4229
4251
  }
@@ -4232,17 +4254,21 @@ function ask(hub, image, question, o = {}) {
4232
4254
  * A MediaPipe tasks-vision provider for the models hub. One wasm fileset
4233
4255
  * per page; one task per record, created with the GPU delegate on a
4234
4256
  * "webgl" rung and the CPU delegate on a "wasm" rung, so a failed GPU
4235
- * delegate falls to the CPU one (FaceSwap and an earlier scene app had no fallback).
4257
+ * delegate falls to the CPU one.
4236
4258
  * Results are turned into the package's Detector, Segmenter and
4237
4259
  * Landmarker shapes.
4238
4260
  */
4261
+ /** The pinned @mediapipe/tasks-vision version, 1.2.3. */
4239
4262
  const TASKS_VISION = "1.2.3";
4263
+ /** The URL @mediapipe/tasks-vision is imported from, on jsDelivr. */
4240
4264
  function tasksVisionUrls(version = TASKS_VISION) {
4241
4265
  return [`https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@${version}/vision_bundle.mjs`];
4242
4266
  }
4267
+ /** The directory of the tasks-vision wasm fileset, on jsDelivr. */
4243
4268
  function tasksVisionWasm(version = TASKS_VISION) {
4244
4269
  return `https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@${version}/wasm`;
4245
4270
  }
4271
+ /** A loader that imports the pinned @mediapipe/tasks-vision at run time; pass it as `runtime` to {@link mediapipeProvider}. */
4246
4272
  const loadTasksVision = (version = TASKS_VISION) => () => importEsm(tasksVisionUrls(version));
4247
4273
  const CLASS = {
4248
4274
  detect: "ObjectDetector",
@@ -4331,6 +4357,7 @@ function landmarker(t, kind, video, source) {
4331
4357
  dispose: () => call(t, "close")
4332
4358
  };
4333
4359
  }
4360
+ /** 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. */
4334
4361
  function mediapipeProvider(opts) {
4335
4362
  let fileset = null;
4336
4363
  return async ({ record, rung, signal }) => {
@@ -4368,6 +4395,7 @@ function mediapipeProvider(opts) {
4368
4395
  };
4369
4396
  }
4370
4397
  // packages/vision/src/faceapi.ts
4398
+ /** The face-api.js provider for the models hub: the tiny face detector and 68 point tiny landmark net, as a face {@link Landmarker}. */
4371
4399
  function faceApiProvider(opts) {
4372
4400
  return async ({ record }) => {
4373
4401
  const fa = await opts.runtime();
@@ -4387,6 +4415,7 @@ function faceApiProvider(opts) {
4387
4415
  };
4388
4416
  }
4389
4417
  // packages/vision/src/loop.ts
4418
+ /** Run a perception step beside a render loop, one at a time, each started no sooner than `interval(lastLatency)` after the previous one began. */
4390
4419
  function perceptionLoop(o) {
4391
4420
  const now = o.now ?? (() => globalThis.performance ? performance.now() : Date.now());
4392
4421
  const g = globalThis;
@@ -4480,7 +4509,7 @@ function readbackLoop(o) {
4480
4509
  }
4481
4510
  };
4482
4511
  }
4483
- /** A small LRU of results by key (an earlier relief bench keeps the depth map with the design so it never reruns). */
4512
+ /** A small LRU of results by key, so a depth map is computed once per image. */
4484
4513
  var ResultCache = class {
4485
4514
  max;
4486
4515
  m = /* @__PURE__ */ new Map();
@@ -4511,7 +4540,7 @@ var ResultCache = class {
4511
4540
  return this.m.size;
4512
4541
  }
4513
4542
  };
4514
- /** A depth map as an 8 bit grey RGBA buffer, for a canvas or a PNG (an earlier relief bench stores depth as a PNG data URL). */
4543
+ /** 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). */
4515
4544
  function depthToRgba(d) {
4516
4545
  const out = new Uint8ClampedArray(d.width * d.height * 4);
4517
4546
  for (let i = 0; i < d.width * d.height; i++) {
@@ -4521,7 +4550,7 @@ function depthToRgba(d) {
4521
4550
  }
4522
4551
  return out;
4523
4552
  }
4524
- /** Scale so the longest side is at most maxPx (as earlier builds did). */
4553
+ /** Scale so the longest side is at most maxPx. */
4525
4554
  function fitSize(w, h, maxPx = 1024) {
4526
4555
  const s = Math.min(1, maxPx / Math.max(w, h));
4527
4556
  return {
@@ -4663,6 +4692,7 @@ const dims = (img) => {
4663
4692
  height: o?.height ?? 48
4664
4693
  };
4665
4694
  };
4695
+ /** A stub depth model with no weights: a left to right ramp at the image's size. */
4666
4696
  function rampDepth() {
4667
4697
  return { async estimate(img) {
4668
4698
  const { width, height } = dims(img);
@@ -4676,6 +4706,7 @@ function rampDepth() {
4676
4706
  };
4677
4707
  } };
4678
4708
  }
4709
+ /** A stub detector with no weights: one centred box with the given label. */
4679
4710
  function centreDetector(label = "person") {
4680
4711
  return { async detect(img) {
4681
4712
  const { width, height } = dims(img);
@@ -4741,6 +4772,7 @@ const centreBox = (img) => {
4741
4772
  h: 2 * r
4742
4773
  };
4743
4774
  };
4775
+ /** A stub landmarker with no weights: one list of `count` fixed points. */
4744
4776
  function fixedLandmarker(count, source = "stub") {
4745
4777
  return { async detect() {
4746
4778
  return {
@@ -4753,6 +4785,7 @@ function fixedLandmarker(count, source = "stub") {
4753
4785
  };
4754
4786
  } };
4755
4787
  }
4788
+ /** A stub vision language model with no weights: a fixed caption, or a fixed answer that repeats the question. */
4756
4789
  function fixedVlm(text = "a stub caption.") {
4757
4790
  return { ask: async (_img, q) => q ? `stub answer to: ${q}` : text };
4758
4791
  }
@@ -4798,19 +4831,22 @@ function maskArea(m) {
4798
4831
  function maskThreshold(m, t = ON) {
4799
4832
  return make(m, m.data.map((v) => v >= t ? 255 : 0));
4800
4833
  }
4834
+ /** Pixels inside either mask, the larger value of each. Throws when the sizes differ. */
4801
4835
  function maskUnion(a, b) {
4802
4836
  same("maskUnion", a, b);
4803
4837
  return make(a, a.data.map((v, i) => Math.max(v, b.data[i])));
4804
4838
  }
4839
+ /** Pixels inside both masks, the smaller value of each. Throws when the sizes differ. */
4805
4840
  function maskIntersect(a, b) {
4806
4841
  same("maskIntersect", a, b);
4807
4842
  return make(a, a.data.map((v, i) => Math.min(v, b.data[i])));
4808
4843
  }
4809
- /** `a` with `b` taken out (shift with a selection tool in the earlier mask studio). */
4844
+ /** `a` with `b` taken out (shift with a selection tool in a mask editor). */
4810
4845
  function maskSubtract(a, b) {
4811
4846
  same("maskSubtract", a, b);
4812
4847
  return make(a, a.data.map((v, i) => Math.min(v, 255 - b.data[i])));
4813
4848
  }
4849
+ /** The mask with inside and outside swapped, 255 minus each value. */
4814
4850
  function maskInvert(m) {
4815
4851
  return make(m, m.data.map((v) => 255 - v));
4816
4852
  }
@@ -4864,7 +4900,7 @@ function maskErode(m, r) {
4864
4900
  const d = distance2((i) => m.data[i] < ON, m.width, m.height);
4865
4901
  return make(m, Uint8Array.from(d, (v) => v > r * r ? 255 : 0));
4866
4902
  }
4867
- /** Soft edges: a gaussian of radius `r` with sigma r / 2 (the earlier mask studio's smooth, before its rethreshold), edges clamped. */
4903
+ /** Soft edges: a gaussian of radius `r` with sigma r / 2 (a smooth without a rethreshold), edges clamped. */
4868
4904
  function maskFeather(m, r) {
4869
4905
  if (r <= 0) return make(m, m.data.slice());
4870
4906
  const { width: w, height: h } = m;
@@ -5105,6 +5141,7 @@ function maskToSvg(m, o = {}) {
5105
5141
  const d = maskOutline(m).map((l) => `M${l.map((p) => `${p[0]} ${p[1]}`).join("L")}Z`).join("");
5106
5142
  return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${m.width} ${m.height}" width="${m.width}" height="${m.height}"><path d="${d}" fill="${o.fill ?? "#000"}" fill-rule="evenodd"/></svg>`;
5107
5143
  }
5144
+ /** The mask as COCO style uncompressed run length, column major, 128 and up inside. */
5108
5145
  function maskToRle(m) {
5109
5146
  const { width: w, height: h } = m;
5110
5147
  const counts = [];
@@ -5125,6 +5162,7 @@ function maskToRle(m) {
5125
5162
  counts
5126
5163
  };
5127
5164
  }
5165
+ /** A mask from COCO style run length, inside 255. Throws when the counts do not cover the image. */
5128
5166
  function maskFromRle(r) {
5129
5167
  const [h, w] = r.size;
5130
5168
  const data = new Uint8Array(w * h);
@@ -5176,6 +5214,7 @@ const absent = () => ({
5176
5214
  frown: 0,
5177
5215
  gesture: null
5178
5216
  });
5217
+ /** Turns raw face and hand frames into steady signals and discrete events, smoothed or held so one noisy frame never fires a reaction. */
5179
5218
  var SignalTracker = class {
5180
5219
  p = absent();
5181
5220
  lastSeen = -Infinity;
@@ -5436,6 +5475,7 @@ var SeenNotes = class {
5436
5475
  };
5437
5476
  /** Questions that call for an on demand look rather than the steady signals. Replace it to suit a persona. */
5438
5477
  const LOOK_PATTERN = /\b(what (am i|is this|'?s this|do you see|can you see)|can you see|do you see|look at (this|me|my)|what('?s| is) in my hand|holding|wearing|show(ing)? you)\b/i;
5478
+ /** True when a message asks the character to look, by {@link LOOK_PATTERN} or the pattern you pass. */
5439
5479
  const wantsLook = (text, pattern = LOOK_PATTERN) => pattern.test(text);
5440
5480
  /** Default reactions (vendor): greet on arrival, smile back after 600 ms at 0.7 chance, answer waves and a few gestures. */
5441
5481
  const DEFAULT_REACTIONS = [
package/dist/stubs.d.ts CHANGED
@@ -6,7 +6,9 @@
6
6
  import type { ModelRecord } from "@hackbuild/models";
7
7
  import { type EmbeddingCache } from "./segment.js";
8
8
  import type { DepthModel, Detector, Landmarker, Segmenter, Vlm } from "./types.js";
9
+ /** A stub depth model with no weights: a left to right ramp at the image's size. */
9
10
  export declare function rampDepth(): DepthModel;
11
+ /** A stub detector with no weights: one centred box with the given label. */
10
12
  export declare function centreDetector(label?: string): Detector;
11
13
  /**
12
14
  * A disc at the first positive point, or in the middle of the box, with a
@@ -20,7 +22,9 @@ export declare function discSegmenter(): Segmenter & {
20
22
  }>;
21
23
  encodes: number;
22
24
  };
25
+ /** A stub landmarker with no weights: one list of `count` fixed points. */
23
26
  export declare function fixedLandmarker(count: number, source?: string): Landmarker;
27
+ /** A stub vision language model with no weights: a fixed caption, or a fixed answer that repeats the question. */
24
28
  export declare function fixedVlm(text?: string): Vlm;
25
29
  /** Stub builders to merge into `stubFactory({...})`. */
26
30
  export declare function visionStubs(): Record<string, (r: ModelRecord) => unknown>;
package/dist/stubs.js CHANGED
@@ -8,6 +8,7 @@ const dims = (img) => {
8
8
  const o = img;
9
9
  return { width: o?.width ?? 64, height: o?.height ?? 48 };
10
10
  };
11
+ /** A stub depth model with no weights: a left to right ramp at the image's size. */
11
12
  export function rampDepth() {
12
13
  return {
13
14
  async estimate(img) {
@@ -20,6 +21,7 @@ export function rampDepth() {
20
21
  },
21
22
  };
22
23
  }
24
+ /** A stub detector with no weights: one centred box with the given label. */
23
25
  export function centreDetector(label = "person") {
24
26
  return {
25
27
  async detect(img) {
@@ -65,6 +67,7 @@ const centreBox = (img) => {
65
67
  const r = Math.min(width, height) / 4;
66
68
  return { x: width / 2 - r, y: height / 2 - r, w: 2 * r, h: 2 * r };
67
69
  };
70
+ /** A stub landmarker with no weights: one list of `count` fixed points. */
68
71
  export function fixedLandmarker(count, source = "stub") {
69
72
  return {
70
73
  async detect() {
@@ -72,6 +75,7 @@ export function fixedLandmarker(count, source = "stub") {
72
75
  },
73
76
  };
74
77
  }
78
+ /** A stub vision language model with no weights: a fixed caption, or a fixed answer that repeats the question. */
75
79
  export function fixedVlm(text = "a stub caption.") {
76
80
  return { ask: async (_img, q) => (q ? `stub answer to: ${q}` : text) };
77
81
  }
package/dist/types.d.ts CHANGED
@@ -8,30 +8,35 @@ export interface Pixels {
8
8
  height: number;
9
9
  data: Uint8ClampedArray | Uint8Array;
10
10
  }
11
+ /** A depth map: width, height, 0 to 1 per pixel with larger nearer, and the raw output range. */
11
12
  export interface DepthMap {
12
13
  width: number;
13
14
  height: number;
14
15
  /** 0 to 1 per pixel, larger is nearer (Depth Anything is relative inverse depth). */
15
16
  data: Float32Array;
16
- /** The raw model output range before normalizing, for stable scale across frames (as earlier builds did). */
17
+ /** The raw model output range before normalizing, for stable scale across frames. */
17
18
  range: [min: number, max: number];
18
19
  }
20
+ /** A loaded depth model: `estimate` returns a {@link DepthMap} for an image. */
19
21
  export interface DepthModel {
20
22
  estimate(image: ImageInput): Promise<DepthMap>;
21
23
  dispose?(): unknown;
22
24
  }
25
+ /** A rectangle in image pixels: left, top, width and height. */
23
26
  export interface Box {
24
27
  x: number;
25
28
  y: number;
26
29
  w: number;
27
30
  h: number;
28
31
  }
32
+ /** One detected object: its label, score and box. */
29
33
  export interface Detection {
30
34
  label: string;
31
35
  score: number;
32
36
  /** Pixels of the input image. */
33
37
  box: Box;
34
38
  }
39
+ /** A loaded detector: `detect` returns the objects in an image. */
35
40
  export interface Detector {
36
41
  detect(image: ImageInput, opts?: {
37
42
  scoreThreshold?: number;
@@ -40,6 +45,7 @@ export interface Detector {
40
45
  }): Promise<Detection[]>;
41
46
  dispose?(): unknown;
42
47
  }
48
+ /** A mask the size of its image: 0 or 255 per pixel, or a confidence 0 to 255, with an optional score. */
43
49
  export interface Mask {
44
50
  width: number;
45
51
  height: number;
@@ -47,6 +53,7 @@ export interface Mask {
47
53
  data: Uint8Array;
48
54
  score?: number;
49
55
  }
56
+ /** What to cut out: points (object or background) and a box, in image pixels. */
50
57
  export interface SegmentPrompt {
51
58
  /** Points in image pixels; label 1 for object, 0 for background (a negative point). */
52
59
  points?: {
@@ -57,18 +64,21 @@ export interface SegmentPrompt {
57
64
  /** A box around the object, image pixels. */
58
65
  box?: Box;
59
66
  }
67
+ /** How a segmenter keeps image embeddings: a stable key for the image and the cache to keep them in. */
60
68
  export interface SegmentOptions {
61
69
  /** A stable key for the image, such as a hash; the image object itself when omitted. */
62
70
  key?: string;
63
71
  /** The caller's embedding cache; the segmenter's own when omitted. */
64
72
  cache?: EmbeddingCache<unknown>;
65
73
  }
74
+ /** A loaded segmenter: `segment` returns masks for an image and prompt, best first. */
66
75
  export interface Segmenter {
67
76
  segment(image: ImageInput, prompt?: SegmentPrompt, o?: SegmentOptions): Promise<Mask[]>;
68
77
  dispose?(): unknown;
69
78
  }
70
79
  /** "gesture" is hand landmarks plus a canned gesture label per hand (MediaPipe gesture recognizer). */
71
80
  export type LandmarkKind = "face" | "hand" | "pose" | "gesture";
81
+ /** Landmarks for each face, hand or body, with blendshapes, handedness and gestures where the model gives them, and the record that answered. */
72
82
  export interface Landmarks {
73
83
  /** One list per face, hand or body; x and y normalized 0 to 1, z relative. */
74
84
  points: [number, number, number][][];
@@ -84,12 +94,14 @@ export interface Landmarks {
84
94
  /** Which record produced this, for status lines after a fallback. */
85
95
  source: string;
86
96
  }
97
+ /** A loaded landmark model: `detect` returns {@link Landmarks} for an image. */
87
98
  export interface Landmarker {
88
99
  detect(image: ImageInput, opts?: {
89
100
  timestamp?: number;
90
101
  }): Promise<Landmarks>;
91
102
  dispose?(): unknown;
92
103
  }
104
+ /** A loaded vision language model: `ask` answers a question about an image, or captions it. */
93
105
  export interface Vlm {
94
106
  /** Answer a question about an image; caption when the question is omitted. */
95
107
  ask(image: ImageInput, question?: string, opts?: {
package/dist/worker.d.ts CHANGED
@@ -11,6 +11,7 @@
11
11
  import { type Spawned, type SpawnOptions } from "@hackbuild/ai-env";
12
12
  import type { DepthMap } from "./types.js";
13
13
  import { type ModelRecord } from "@hackbuild/models";
14
+ /** Options for {@link depthWorker}: the transformers.js URLs, the depth model or record, the licence callback, device, dtype and worker rungs. */
14
15
  export interface DepthWorkerOptions {
15
16
  /** transformers.js ESM URLs tried in order (transformersUrls() from @hackbuild/devices). */
16
17
  urls: readonly string[];
@@ -32,11 +33,13 @@ export interface DepthWorkerOptions {
32
33
  /** Worker rungs; module blob first by default. */
33
34
  spawn?: Pick<SpawnOptions, "prefer" | "Worker" | "createObjectURL" | "readyMs" | "prelude">;
34
35
  }
36
+ /** RGBA pixels the page sends to the depth worker: ImageData, or anything with width, height and data. */
35
37
  export interface Pixels {
36
38
  width: number;
37
39
  height: number;
38
40
  data: Uint8ClampedArray | Uint8Array;
39
41
  }
42
+ /** A depth model in a worker: the worker rung that started, the device, `estimate` and `dispose`. */
40
43
  export interface DepthWorker {
41
44
  /** The worker rung that started (module-blob, classic-blob or inline). */
42
45
  readonly rung: Spawned["rung"];
package/dist/yolo.d.ts CHANGED
@@ -7,19 +7,23 @@
7
7
  */
8
8
  import type { OrtModel } from "@hackbuild/devices";
9
9
  import type { Box, Detection, Detector, Pixels } from "./types.js";
10
+ /** The 80 COCO class names, in YOLO class index order. */
10
11
  export declare const COCO_LABELS: string[];
12
+ /** How an image was fitted into the square input: scale, left and top padding, and the square side. */
11
13
  export interface Letterbox {
12
14
  scale: number;
13
15
  padX: number;
14
16
  padY: number;
15
17
  size: number;
16
18
  }
19
+ /** The scale and padding that fit a `w` by `h` image into a `size` square (640 by default), centred. */
17
20
  export declare function letterboxParams(w: number, h: number, size?: number): Letterbox;
18
21
  /** RGBA pixels to a planar float tensor [1, 3, size, size] in 0 to 1, nearest neighbour, grey padding. */
19
22
  export declare function letterboxTensor(px: Pixels, size?: number): {
20
23
  data: Float32Array;
21
24
  lb: Letterbox;
22
25
  };
26
+ /** Intersection over union of two boxes, 0 to 1. */
23
27
  export declare function iou(a: Box, b: Box): number;
24
28
  /** Greedy NMS within each label, best first, then the top `max` overall. */
25
29
  export declare function nms(dets: Detection[], iouThreshold?: number, max?: number): Detection[];
@@ -39,5 +43,5 @@ export declare function yoloDetector(m: OrtModel, o?: {
39
43
  labels?: readonly string[];
40
44
  toPixels?: (img: unknown) => Pixels;
41
45
  }): Detector;
42
- /** Detection cadence as earlier builds ran it: wait max(0.45 s, 4 times the last latency) between runs. */
46
+ /** Detection cadence: wait max(0.45 s, 4 times the last latency) between runs. */
43
47
  export declare function detectCadenceMs(lastLatencyMs: number): number;