File size: 8,153 Bytes
732426d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
// Boxes: the objects you name, boxed live. Each object is one question, all of a frame's
// questions in one request, answered from one read of the picture: a `box` (one instance,
// "Where is the phone?") or, switched on per object, `boxes` (every instance in reading
// order, "Every hand."; one block of slots an instance, `max` of them, so several times a box's
// tokens). Any object can be asked for: typed at play time, nothing is trained per item. Shown only
// on a model with typed answers (d1-2B on).

import { el, section, kpis } from "./ui.js";
import { summary } from "./stream.js";

const START = [["face", false], ["hand", true], ["phone", false], ["cup or mug", false], ["bottle", false], ["book", false]];
const COLORS = ["#6c4fe0", "#cd82f0", "#2a9d8f", "#e09f3e", "#d1495b", "#3a86ff", "#8338ec", "#06a77d"];
const MAX = 8;
const EVERY = 8;  // the instances an "all" object reads: a block of about 26 tokens each; 16 without a max
const EASE = 0.5;  // a box moves this share of the way to each new answer

const name = (thing) => thing.replace(/^(a pair of|a set of|an|a|the) /, "").replace(/ or .*/, "");
const ask = (o) => (o.every ? `Every ${o.thing}.` : `Where is the ${o.thing}?`);

let alive = false, raf = 0, overlay = null;

export default {
  id: "boxes",
  title: "Boxes",
  blurb: "Show the camera anything: every object you name is boxed live, all at once.",
  tags: ["open vocabulary", "camera", "boxes"],
  camera: true,
  typed: true,

  start({ panel, view, video, stream, say }) {
    alive = true;
    const objects = [];  // {thing, every, color, boxes: [{x0, x1, y0, y1, p}]}
    const board = kpis([["objects", "0", true], ["in view", "0"], ["frames / s", "–"], ["round trip", "–"]]);
    const chips = el("div", { class: "row" });
    const input = el("input", { type: "text", placeholder: "add an object: a pen, keys, glasses…", maxlength: 40 });
    const render = () => {
      chips.replaceChildren(...objects.map((o, i) => {
        const mode = el("button", { class: "btn chip on", style: `--c:${o.color}`, title: "one, or every instance" },
          `${name(o.thing)}${o.every ? " · all" : ""}`);
        mode.onclick = () => { o.every = !o.every; o.boxes = []; render(); };
        const x = el("button", { class: "btn chip", title: "remove" }, "×");
        x.onclick = () => { objects.splice(i, 1); render(); };
        return el("span", { class: "row" }, mode, x);
      }));
      board.set("objects", String(objects.length));
    };
    const add = (thing, every = false) => {
      thing = thing.trim().toLowerCase();
      if (!thing || objects.length >= MAX || objects.some((o) => o.thing === thing)) return;
      const used = new Set(objects.map((o) => o.color));
      objects.push({ thing, every, color: COLORS.find((c) => !used.has(c)) ?? COLORS[0], boxes: [] });
      render();
    };
    START.forEach(([thing, every]) => add(thing, every));
    const seen = el("canvas", { class: "seen" });
    const seenCtx = seen.getContext("2d");
    const still = new Image();
    input.onkeydown = (e) => { if (e.key === "Enter") { add(name(input.value.trim().toLowerCase()), false); input.value = ""; } };
    panel.append(
      section("objects", chips, input),
      section("rate", board.node),
      section("what the model sees", seen, el("p", { class: "note" },
        "The frame sent, unmirrored, with the boxes of its own answer: no smoothing, no screen geometry.")),
      section("", el("p", { class: "note" },
        "One question an object, all in one request: the model reads the picture once. Click an object to box "
        + "every instance of it (\u201c\u00b7 all\u201d) or just one.")));

    overlay = el("canvas", { class: "boxes-overlay" });
    view.append(overlay);
    const ctx = overlay.getContext("2d");

    const questions = () => objects.map((o) => (o.every ? { text: ask(o), boxes: true, max: EVERY } : { text: ask(o), box: true }));
    // 512 px frames. d1-2B on pasted squares, 4 scenes: one box at IoU 0.90-0.98 (0.97-1.00 at 1280 px), every
    // instance 9/10 at IoU >= 0.5 (7/10 at 1280 px), counts 3/4 at both; a quarter of the bytes to send. 384 px saves
    // little (six questions on an M5 Pro 177 -> 162 ms): the questions cost, not the picture. Frames in flight: the
    // stream's default, one on this machine, where a second only waits in line.
    stream.start({ questions, side: 512 }, (answer) => {
      // each question's object (none if removed since the frame left) and its instances, a `box` answer as a list of one
      const owners = answer.questions.map((q) => objects.find((o) => ask(o) === q.text));
      const found = answer.probs.map((a) => a.boxes ?? (a.box ? [{ box: a.box, found: a.found }] : []));
      owners.forEach((o, i) => {
        if (!o) return;
        const next = found[i].map((b) => ({ x0: b.box.left, x1: b.box.right, y0: b.box.top, y1: b.box.bottom, p: b.found }));
        // the same instances in reading order: each box eases toward its new place; a new count starts afresh
        o.boxes = next.length === o.boxes.length
          ? next.map((n, k) => ({ ...Object.fromEntries(["x0", "x1", "y0", "y1"].map((e) => [e, o.boxes[k][e] + EASE * (n[e] - o.boxes[k][e])])), p: n.p }))
          : next;
      });
      board.set("in view", String(objects.reduce((n, o) => n + o.boxes.length, 0)));
      still.onload = () => {  // the frame as sent and this answer's raw boxes, in the frame's own pixels
        seen.width = still.width; seen.height = still.height;
        seenCtx.drawImage(still, 0, 0);
        seenCtx.lineWidth = Math.max(2, still.width / 320);
        owners.forEach((o, i) => {
          if (!o) return;
          seenCtx.strokeStyle = o.color;
          for (const { box: b } of found[i]) {
            seenCtx.strokeRect(b.left * still.width, b.top * still.height, (b.right - b.left) * still.width,
              (b.bottom - b.top) * still.height);
          }
        });
      };
      still.src = answer.frame;
      const r = summary();
      board.set("frames / s", r.rate.toFixed(1));
      board.set("round trip", `${r.latency.toFixed(0)} ms`);
    });

    // The boxes over the camera, which the page shows mirrored and letterboxed (`object-fit: contain`): the canvas
    // sits exactly on the video element, at the screen's pixel density, and the picture's rectangle is found inside.
    const draw = () => {
      if (!alive) return;
      const v = video.getBoundingClientRect(), r = view.getBoundingClientRect(), dpr = devicePixelRatio || 1;
      Object.assign(overlay.style, { left: `${v.left - r.left}px`, top: `${v.top - r.top}px`, width: `${v.width}px`,
                                     height: `${v.height}px` });
      const W = v.width, H = v.height;
      if (overlay.width !== Math.round(W * dpr) || overlay.height !== Math.round(H * dpr)) {
        overlay.width = Math.round(W * dpr); overlay.height = Math.round(H * dpr);
      }
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      ctx.clearRect(0, 0, W, H);
      const vw = video.videoWidth, vh = video.videoHeight;
      if (vw) {
        const scale = Math.min(W / vw, H / vh), dw = vw * scale, dh = vh * scale, ox = (W - dw) / 2, oy = (H - dh) / 2;
        ctx.font = "600 14px Inter, sans-serif";
        for (const o of objects) {
          for (const b of o.boxes) {
            const x = ox + (1 - b.x1) * dw, y = oy + b.y0 * dh, w = (b.x1 - b.x0) * dw, h = (b.y1 - b.y0) * dh;
            ctx.lineWidth = 3; ctx.strokeStyle = o.color;
            ctx.beginPath(); ctx.roundRect(x, y, w, h, 10); ctx.stroke();
            const tag = `${name(o.thing)} ${Math.round(100 * b.p)}%`, tw = ctx.measureText(tag).width + 14;
            ctx.fillStyle = o.color;
            ctx.beginPath(); ctx.roundRect(x, Math.max(0, y - 24), tw, 22, 6); ctx.fill();
            ctx.fillStyle = "#fff"; ctx.fillText(tag, x + 7, Math.max(0, y - 24) + 15);
          }
        }
      }
      raf = requestAnimationFrame(draw);
    };
    raf = requestAnimationFrame(draw);
    say("");
  },

  stop() {
    alive = false;
    cancelAnimationFrame(raf);
    overlay?.remove();
    overlay = null;
  },
};