File size: 30,660 Bytes
646cef1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
// LookAnything WebGPU, single-file build of pilresize.js + prep.js + infer.js + main.js (see build.py).
// Port of Pillow's 8-bit resampling (libImaging/Resample.c) for RGB images, so the
// detectors see the same pixels in the browser as in Python: Image.resize(size,
// BICUBIC | LANCZOS) with no box and reducing_gap=None. Separable, horizontal pass first,
// coefficients normalised in double and rounded to 22-bit fixed point, as in C.
const PRECISION_BITS = 22;
const ONE = 1 << PRECISION_BITS;

const FILTERS = {
  bicubic: { support: 2.0, f: (x) => {
    const a = -0.5;
    if (x < 0) x = -x;
    if (x < 1) return ((a + 2) * x - (a + 3)) * x * x + 1;
    if (x < 2) return (((x - 5) * x + 8) * x - 4) * a;
    return 0;
  } },
  lanczos: { support: 3.0, f: (x) => {
    const sinc = (v) => { if (v === 0) return 1; v *= Math.PI; return Math.sin(v) / v; };
    return (x >= -3 && x < 3) ? sinc(x) * sinc(x / 3) : 0;
  } },
};

function coeffs(inSize, outSize, filter) {
  const scale = inSize / outSize;
  const filterscale = scale < 1 ? 1 : scale;
  const support = filter.support * filterscale;
  const ksize = Math.ceil(support) * 2 + 1;
  const kk = new Int32Array(outSize * ksize), bounds = new Int32Array(outSize * 2);
  const pre = new Float64Array(ksize);
  for (let xx = 0; xx < outSize; xx++) {
    const center = (xx + 0.5) * scale, ss = 1 / filterscale;
    let xmin = Math.trunc(center - support + 0.5); if (xmin < 0) xmin = 0;
    let xmax = Math.trunc(center + support + 0.5); if (xmax > inSize) xmax = inSize;
    xmax -= xmin;
    let ww = 0;
    for (let x = 0; x < xmax; x++) { const w = filter.f((x + xmin - center + 0.5) * ss); pre[x] = w; ww += w; }
    for (let x = 0; x < xmax; x++) {
      const v = ww !== 0 ? pre[x] / ww : pre[x];
      kk[xx * ksize + x] = v < 0 ? Math.trunc(-0.5 + v * ONE) : Math.trunc(0.5 + v * ONE);
    }
    bounds[xx * 2] = xmin; bounds[xx * 2 + 1] = xmax;
  }
  return { kk, bounds, ksize };
}

const clip8 = (v) => (v >= (ONE * 256) ? 255 : v <= 0 ? 0 : Math.floor(v / ONE));

// img: { w, h, data: Uint8Array RGB } -> { w, h, data }
function resize(img, outW, outH, kind) {
  if (outW === img.w && outH === img.h) return { w: img.w, h: img.h, data: img.data.slice() };
  const filter = FILTERS[kind];
  const H = coeffs(img.w, outW, filter), V = coeffs(img.h, outH, filter);
  const needH = outW !== img.w, needV = outH !== img.h;
  const yFirst = V.bounds[0], yLast = V.bounds[(outH - 1) * 2] + V.bounds[(outH - 1) * 2 + 1];
  let src = img;
  if (needH) {
    const rows = yLast - yFirst, out = new Uint8Array(outW * rows * 3), d = img.data, W = img.w;
    for (let yy = 0; yy < rows; yy++) {
      const rowOff = (yy + yFirst) * W * 3;
      for (let xx = 0; xx < outW; xx++) {
        const xmin = H.bounds[xx * 2], xmax = H.bounds[xx * 2 + 1], k = xx * H.ksize;
        let s0 = ONE / 2, s1 = ONE / 2, s2 = ONE / 2;
        for (let x = 0; x < xmax; x++) {
          const c = H.kk[k + x], p = rowOff + (x + xmin) * 3;
          s0 += d[p] * c; s1 += d[p + 1] * c; s2 += d[p + 2] * c;
        }
        const o = (yy * outW + xx) * 3;
        out[o] = clip8(s0); out[o + 1] = clip8(s1); out[o + 2] = clip8(s2);
      }
    }
    src = { w: outW, h: rows, data: out };
  }
  if (!needV) return src;
  const shift = needH ? yFirst : 0, W = src.w, d = src.data, out = new Uint8Array(W * outH * 3);
  for (let yy = 0; yy < outH; yy++) {
    const ymin = V.bounds[yy * 2] - shift, ymax = V.bounds[yy * 2 + 1], k = yy * V.ksize;
    for (let xx = 0; xx < W; xx++) {
      let s0 = ONE / 2, s1 = ONE / 2, s2 = ONE / 2;
      for (let y = 0; y < ymax; y++) {
        const c = V.kk[k + y], p = ((y + ymin) * W + xx) * 3;
        s0 += d[p] * c; s1 += d[p + 1] * c; s2 += d[p + 2] * c;
      }
      const o = (yy * W + xx) * 3;
      out[o] = clip8(s0); out[o + 1] = clip8(s1); out[o + 2] = clip8(s2);
    }
  }
  return { w: W, h: outH, data: out };
}

function crop(img, x, y, w, h) {
  const out = new Uint8Array(w * h * 3);
  for (let r = 0; r < h; r++) out.set(img.data.subarray(((y + r) * img.w + x) * 3, ((y + r) * img.w + x + w) * 3), r * w * 3);
  return { w, h, data: out };
}

// Python's round(): halves to even.
function pyRound(v) {
  const f = Math.floor(v), d = v - f;
  if (d > 0.5) return f + 1;
  if (d < 0.5) return f;
  return f % 2 === 0 ? f : f + 1;
}

// Everything LookAnything needs around its ONNX graphs, ported from transformers / the model repo:
// smart_resize + patchify (Qwen2VLImageProcessor), vision position tables, M-RoPE ids and tables,
// the query-group attention mask, and the input sequence (prompt, image tokens, 27 query tokens).
// Checked against numpy / PyTorch in tests (work/tables.py, work/ref_look.py).

const FACTOR = 32, PATCH = 16, MERGE = 2, NUM_GRID = 48;
const MIN_PIXELS = 12544, MAX_PIXELS = 451584;      // inference_config.json

// Qwen2-VL smart_resize: both sides multiples of 32, area inside [min, max] pixels.
function smartResize(h, w, minPixels = MIN_PIXELS, maxPixels = MAX_PIXELS) {
  let hb = pyRound(h / FACTOR) * FACTOR, wb = pyRound(w / FACTOR) * FACTOR;
  if (hb * wb > maxPixels) {
    const beta = Math.sqrt((h * w) / maxPixels);
    hb = Math.floor(h / beta / FACTOR) * FACTOR; wb = Math.floor(w / beta / FACTOR) * FACTOR;
  } else if (hb * wb < minPixels) {
    const beta = Math.sqrt(minPixels / (h * w));
    hb = Math.ceil((h * beta) / FACTOR) * FACTOR; wb = Math.ceil((w * beta) / FACTOR) * FACTOR;
  }
  return [Math.max(hb, FACTOR), Math.max(wb, FACTOR)];
}

// img { w, h, data: Uint8Array RGB } -> { patches: Float32Array [N,1536], gh, gw } (gh, gw in 16 px patches)
function patchify(img, minPixels, maxPixels) {
  const [H, W] = smartResize(img.h, img.w, minPixels, maxPixels);
  const r = resize(img, W, H, 'bicubic');
  const gh = H / PATCH, gw = W / PATCH, N = gh * gw, out = new Float32Array(N * 1536), d = r.data;
  // order: (gh/2, gw/2, 2, 2) patches; each patch is C x T(2, the image repeated) x 16 x 16
  let o = 0;
  for (let by = 0; by < gh / MERGE; by++) for (let bx = 0; bx < gw / MERGE; bx++)
    for (let my = 0; my < MERGE; my++) for (let mx = 0; mx < MERGE; mx++) {
      const y0 = (by * MERGE + my) * PATCH, x0 = (bx * MERGE + mx) * PATCH;
      for (let c = 0; c < 3; c++) for (let t = 0; t < 2; t++) for (let y = 0; y < PATCH; y++) {
        let p = ((y0 + y) * W + x0) * 3 + c;
        for (let x = 0; x < PATCH; x++, p += 3) out[o++] = (Math.fround(d[p] / 255) - 0.5) / 0.5;
      }
    }
  return { patches: out, gh, gw, width: W, height: H };
}

const linspace32 = (n, hi) => { const a = new Float32Array(n); for (let i = 0; i < n; i++) a[i] = n === 1 ? 0 : Math.fround(i * Math.fround(hi / (n - 1))); return a; };

// bilinear position-embedding lookups + 2-D rotary cos/sin for a gh x gw patch grid, in merge order
function visionTables(gh, gw) {
  const N = gh * gw, idx = new BigInt64Array(4 * N), wt = new Float32Array(4 * N), cos = new Float32Array(N * 64), sin = new Float32Array(N * 64);
  const hs = linspace32(gh, NUM_GRID - 1), ws = linspace32(gw, NUM_GRID - 1);
  const inv = Float32Array.from({ length: 16 }, (_, i) => Math.fround(1 / Math.pow(10000, (2 * i) / 32)));
  let n = 0;
  for (let by = 0; by < gh / MERGE; by++) for (let bx = 0; bx < gw / MERGE; bx++)
    for (let my = 0; my < MERGE; my++) for (let mx = 0; mx < MERGE; mx++, n++) {
      const y = by * MERGE + my, x = bx * MERGE + mx;
      const hf = Math.trunc(hs[y]), wf = Math.trunc(ws[x]), hc = Math.min(hf + 1, NUM_GRID - 1), wc = Math.min(wf + 1, NUM_GRID - 1);
      const dh = Math.fround(hs[y] - hf), dw = Math.fround(ws[x] - wf);
      const ids = [hf * NUM_GRID + wf, hf * NUM_GRID + wc, hc * NUM_GRID + wf, hc * NUM_GRID + wc];
      const ww = [(1 - dh) * (1 - dw), (1 - dh) * dw, dh * (1 - dw), dh * dw];
      for (let k = 0; k < 4; k++) { idx[k * N + n] = BigInt(ids[k]); wt[k * N + n] = ww[k]; }
      for (let i = 0; i < 16; i++) {
        const a = Math.fround(y * inv[i]), b = Math.fround(x * inv[i]);
        for (const [off, v] of [[i, a], [16 + i, b], [32 + i, a], [48 + i, b]]) { cos[n * 64 + off] = Math.cos(v); sin[n * 64 + off] = Math.sin(v); }
      }
    }
  return { idx, wt, cos, sin };
}

// get_rope_index for [text x nBefore][image gh x gw merged tokens][text x nAfter] -> Int32Array [3*S]
function positions(nBefore, gh, gw, nAfter) {
  const S = nBefore + gh * gw + nAfter, p = new Int32Array(3 * S);
  for (let i = 0; i < nBefore; i++) p[i] = p[S + i] = p[2 * S + i] = i;
  for (let y = 0; y < gh; y++) for (let x = 0; x < gw; x++) { const i = nBefore + y * gw + x; p[i] = nBefore; p[S + i] = nBefore + y; p[2 * S + i] = nBefore + x; }
  const cur = nBefore + Math.max(gh, gw);
  for (let i = 0; i < nAfter; i++) { const j = nBefore + gh * gw + i; p[j] = p[S + j] = p[2 * S + j] = cur + i; }
  return p;
}

// cos/sin [S,128] with interleaved M-RoPE (theta 5e6, sections 24/20/20)
function textTables(pos, S) {
  const inv = Float32Array.from({ length: 64 }, (_, i) => Math.fround(1 / Math.pow(5e6, (2 * i) / 128)));
  const cos = new Float32Array(S * 128), sin = new Float32Array(S * 128), sect = [24, 20, 20];
  for (let s = 0; s < S; s++) for (let i = 0; i < 64; i++) {
    let axis = 0;
    if (i % 3 === 1 && i < sect[1] * 3) axis = 1; else if (i % 3 === 2 && i < sect[2] * 3) axis = 2;
    const f = Math.fround(pos[axis * S + s] * inv[i]), c = Math.cos(f), n = Math.sin(f);
    cos[s * 128 + i] = cos[s * 128 + 64 + i] = c; sin[s * 128 + i] = sin[s * 128 + 64 + i] = n;
  }
  return { cos, sin };
}

// additive mask [S,S]: causal; the three query groups of 9 cannot see each other
function queryMask(S, promptLen, nPer = 9, groups = 3) {
  const NEG = -3.4028234663852886e38, m = new Float32Array(S * S);
  for (let i = 0; i < S; i++) for (let j = i + 1; j < S; j++) m[i * S + j] = NEG;
  for (let a = 0; a < groups; a++) for (let b = 0; b < groups; b++) if (a !== b)
    for (let i = 0; i < nPer; i++) for (let j = 0; j < nPer; j++) m[(promptLen + a * nPer + i) * S + promptLen + b * nPer + j] = NEG;
  return m;
}

// bf16 bits (Uint16) -> float32, exact
function bf16rows(u16) { const u = new Uint32Array(u16.length); for (let i = 0; i < u16.length; i++) u[i] = u16[i] << 16; return new Float32Array(u.buffer); }

// token ids for the chosen prompt, with `nImg` image placeholders. pieces = prompt.json
function promptIds(pieces, imagePad, nImg, kind, box) {
  let mid = kind === 'b2p' ? pieces.b2p.mid.slice() : pieces[kind].slice();
  if (kind === 'b2p') for (const ch of box.join(',')) mid.push(ch === ',' ? pieces.comma : pieces.digits[+ch]);
  const tail = kind === 'b2p' ? pieces.b2p.tail : [];
  return { ids: [...pieces.head, ...new Array(nImg).fill(imagePad), ...mid, ...tail], first: pieces.head.length };
}

// One forward pass of LookAnything: vision tower, 28 language layers over [prompt + image tokens + 27 gaze queries],
// then the heads. m = { ort, sess, pieces, imagePad, rows, query, run } (run wraps every ONNX Runtime call).

const D = 2048, NQ = 27;
async function lookOnce(m, img, { maxPixels, kind, box }) {
  const { ort, sess } = m, gpu = m.run;
  const t0 = performance.now();
  const { patches, gh, gw } = patchify(img, undefined, maxPixels);
  const N = gh * gw, gm = gh / 2, gwm = gw / 2, nImg = gm * gwm;
  const { ids, first } = promptIds(m.pieces, m.imagePad, nImg, kind, box);
  const P = ids.length, S = P + NQ;
  const vt = visionTables(gh, gw);
  const T = (type, data, dims) => new ort.Tensor(type, data, dims);
  const a = await gpu(() => sess.vis_a.run({ patches: T('float32', patches, [N, 1536]), pos_idx: T('int64', vt.idx, [4, N]), pos_w: T('float32', vt.wt, [4, N]),
    cos: T('float32', vt.cos, [N, 64]), sin: T('float32', vt.sin, [N, 64]) }));
  const b = await gpu(() => sess.vis_b.run({ x: a.x, cos: T('float32', vt.cos, [N, 64]), sin: T('float32', vt.sin, [N, 64]) }));
  const tVis = performance.now();
  // sequence: prompt tokens (image placeholders replaced by the image embeddings), then the 27 gaze-query tokens
  const hidden = new Float32Array(S * D), ds = new Float32Array(3 * S * D);
  const imgE = b.img.data, d3 = [a.ds0.data, a.ds1.data, b.ds2.data];
  for (let t = 0; t < P; t++) {
    const id = ids[t];
    if (id === m.imagePad) hidden.set(imgE.subarray((t - first) * D, (t - first + 1) * D), t * D);
    else { const r = m.rows.get(id); if (!r) throw new Error(`no embedding for token ${id}`); hidden.set(r, t * D); }
  }
  hidden.set(m.query, P * D);
  for (let k = 0; k < 3; k++) ds.set(d3[k], k * S * D + first * D);
  const pos = positions(first, gm, gwm, S - first - nImg), tt = textTables(pos, S), mask = queryMask(S, P);
  let h = T('float32', hidden, [1, S, D]);
  const cos = T('float32', tt.cos, [S, 128]), sin = T('float32', tt.sin, [S, 128]), mk = T('float32', mask, [S, S]);
  for (const name of ['lm_1', 'lm_2', 'lm_3', 'lm_4']) {
    const feed = { hidden: h, cos, sin, mask: mk };
    if (name === 'lm_1') feed.ds = T('float32', ds, [3, S, D]);
    h = (await gpu(() => sess[name].run(feed))).out;
  }
  const H = h.data, tLm = performance.now();
  const rowsOf = (from, n) => H.slice(from * D, (from + n) * D);
  const out = await gpu(() => sess.heads.run({ gaze: T('float32', rowsOf(P + 18, 9), [1, 9, D]), head: T('float32', rowsOf(P + 9, 9), [1, 9, D]),
    vis: T('float32', rowsOf(first, nImg), [1, gm, gwm, D]) }));
  const t1 = performance.now();
  return { point: Array.from(out.point.data), box: Array.from(out.box.data), heat: out.heatmap.data, mask: out.head_mask.data, ms: t1 - t0, msVision: tVis - t0, msLm: tLm - tVis, tokens: S };
}



const q = new URLSearchParams(location.search);
// Test hooks: same-origin paths only, so a crafted link cannot load someone else's code or weights.
const local = (v) => (v && v.startsWith('/') && !v.startsWith('//') ? v : null);
const REPO = 'WeReCooking/LookAnything-ONNX-WebGPU';
const BASE = local(q.get('model')) || `https://huggingface.co/${REPO}/resolve/main`;
const ORT_URL = local(q.get('ort')) || 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/ort.webgpu.min.mjs';
const CACHE = 'look-anything-v1';
const LIVE_PIXELS = 200704, LIVE_SIDE = 640, STILL_SIDE = 1536;
const EXAMPLES = [
  ['zoo-lion.jpg', 'Children watching a lion, by Stephen H', 'https://unsplash.com/photos/WqEFya48Iig'],
  ['mountain.jpg', 'A man looking at a snowy mountain, by Hunter Bryant', 'https://unsplash.com/photos/iVEWLe-GidE'],
  ['woman-dog.jpg', 'A woman with her dog, by Manuel Meza', 'https://unsplash.com/photos/KvKop_a_EXw'],
  ['phone.jpg', 'A man looking at his phone in the snow, by Erik Mclean', 'https://unsplash.com/photos/aZpiH4HkZ3Y'],
  ['high-five.jpg', 'A woman and her dog on a railway track, by Richard Brutyo', 'https://unsplash.com/photos/xvYxGcwFvuE'],
  ['spyglass.jpg', 'A girl with a spyglass in a tree house, by Kelly Sikkema', 'https://unsplash.com/photos/lgMXYafVFiU'],
];

const $ = (id) => document.getElementById(id);
const ui = { box: $('stagebox'), stage: $('stage'), pick: $('pick'), cam: $('cam'), stop: $('stop'), file: $('file'), status: $('status'),
  bar: $('bar').firstElementChild, hint: $('hint'), thumbs: $('thumbs'), store: $('store'), wipe: $('wipe') };
const ctx = ui.stage.getContext('2d', { willReadFrequently: true });
const tick = () => new Promise((r) => setTimeout(r, 0));
const mb = (b) => `${Math.round(b / 1e6)} MB`;
const store = { get: (k) => { try { return sessionStorage.getItem(k); } catch { return null; } } };

function status(text, frac = null, bad = false) {
  ui.status.textContent = text; ui.status.classList.toggle('bad', bad);
  if (frac !== null) ui.bar.style.width = `${Math.round(Math.max(0, Math.min(1, frac)) * 100)}%`;
}

// ---------------------------------------------------------------- downloads (Cache API, once)
async function openCache() { try { return await caches.open(CACHE); } catch { return null; } }
async function fetchBytes(url, onBytes) {
  const cache = await openCache();
  const hit = cache && await cache.match(url);
  if (hit) { const b = new Uint8Array(await hit.arrayBuffer()); onBytes?.(b.length); return b; }
  const resp = await fetch(url);
  if (!resp.ok) throw new Error(`HTTP ${resp.status} for ${url.split('/').pop()}`);
  const total = Number(resp.headers.get('content-length')) || 0, reader = resp.body.getReader();
  let bytes = new Uint8Array(total || 1 << 20), got = 0;
  for (;;) {     // one preallocated buffer: no Blob, no second copy
    const { done, value } = await reader.read();
    if (done) break;
    if (got + value.length > bytes.length) { const g = new Uint8Array(Math.max(bytes.length * 2, got + value.length)); g.set(bytes.subarray(0, got)); bytes = g; }
    bytes.set(value, got); got += value.length; onBytes?.(got);
  }
  if (got !== bytes.length) bytes = bytes.slice(0, got);
  if (cache) { try { await cache.put(url, new Response(bytes)); } catch (e) { console.warn(`not stored (${e.name}): ${url}`); } }
  return bytes;
}

// ---------------------------------------------------------------- model
let ortP = null, modelP = null;
const getOrt = () => (ortP ||= (async () => {
  if (!navigator.gpu || !(await navigator.gpu.requestAdapter())) throw new Error('This browser has no WebGPU. Use Chrome or Edge 121+, Android 12+ or Safari 26.');
  const ort = await import(ORT_URL);
  ort.env.logLevel = 'error';
  return ort;
})());
let gpuQ = Promise.resolve();      // one ONNX Runtime call at a time: creating a session while another runs corrupts memory
const gpu = (fn) => { const p = gpuQ.then(fn); gpuQ = p.catch(() => {}); return p; };

const loadModel = () => (modelP ||= (async () => {
  const ort = await getOrt();
  const man = await (await fetch(`${BASE}/manifest.json`)).json();
  const total = man.total_bytes + Object.values(man.data).reduce((a, f) => a + f.bytes, 0);
  let done = 0;
  const get = async (f, label) => {
    const b = await fetchBytes(`${BASE}/${f.path}`, (got) => status(`${label}: ${mb(done + got)} of ${mb(total)}, first time only`, (done + got) / total));
    done += f.bytes; return b;
  };
  const data = {};
  for (const k of Object.keys(man.data)) data[k] = await get(man.data[k], 'Downloading');
  const sess = {};
  for (const name of man.order) {
    const bytes = await get(man.files[name], 'Downloading');
    status(`Starting ${name} on your GPU (${Object.keys(sess).length + 1} of ${man.order.length})…`, done / total);
    sess[name] = await gpu(() => ort.InferenceSession.create(bytes, { executionProviders: ['webgpu'], logSeverityLevel: 3 }));
  }
  const pieces = JSON.parse(new TextDecoder().decode(data['prompt.json']));
  const ids = JSON.parse(new TextDecoder().decode(data['ids.json']));
  const rowsF = bf16rows(new Uint16Array(data['prompt_rows.bf16'].buffer.slice(data['prompt_rows.bf16'].byteOffset, data['prompt_rows.bf16'].byteOffset + data['prompt_rows.bf16'].byteLength)));
  const rows = new Map(pieces.row_ids.map((id, i) => [id, rowsF.subarray(i * 2048, (i + 1) * 2048)]));
  const qb = data['query_tokens.f32'];
  const query = new Float32Array(qb.buffer.slice(qb.byteOffset, qb.byteOffset + qb.byteLength));
  status('Model ready.', 1);
  return { ort, sess, pieces, imagePad: ids.image_pad, rows, query };
})());

const infer = async (img, opts) => lookOnce({ ...(await loadModel()), run: gpu }, img, opts);

// ---------------------------------------------------------------- drawing
const sigmoid = (v) => 1 / (1 + Math.exp(-v));
function headOf(maskLogits) {                       // bbox and centroid of the head mask (64 x 64, normalized to the picture)
  let x0 = 64, y0 = 64, x1 = -1, y1 = -1, sx = 0, sy = 0, n = 0;
  for (let y = 0; y < 64; y++) for (let x = 0; x < 64; x++) if (maskLogits[y * 64 + x] > 0) { x0 = Math.min(x0, x); x1 = Math.max(x1, x); y0 = Math.min(y0, y); y1 = Math.max(y1, y); sx += x + 0.5; sy += y + 0.5; n++; }
  return n >= 3 ? { box: [x0 / 64, y0 / 64, (x1 + 1) / 64, (y1 + 1) / 64], c: [sx / n / 64, sy / n / 64] } : null;
}
const heatCanvas = Object.assign(document.createElement('canvas'), { width: 64, height: 64 });
function draw(frame, r, pick) {
  const W = ui.stage.width, H = ui.stage.height;
  ctx.drawImage(frame, 0, 0, W, H);
  if (r) {
    const accent = getComputedStyle(document.documentElement).getPropertyValue('--accent').trim() || '#e0703f';
    // heatmap: softmax over the 64 x 64 logits, scaled to its peak ('legacy' mode: cell i sits at i / 63)
    let mx = -Infinity; for (let i = 0; i < 4096; i++) mx = Math.max(mx, r.heat[i]);
    const hd = heatCanvas.getContext('2d').createImageData(64, 64);
    for (let i = 0; i < 4096; i++) { const p = Math.exp(r.heat[i] - mx); hd.data.set([255, 150, 40, Math.round(190 * p ** 0.7)], i * 4); }
    heatCanvas.getContext('2d').putImageData(hd, 0, 0);
    ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = 'high';
    ctx.drawImage(heatCanvas, 0, 0, W, H);
    const head = headOf(r.mask), px = r.point[0] * W, py = r.point[1] * H, lw = Math.max(2, W / 320);
    ctx.lineWidth = lw; ctx.strokeStyle = '#fff'; ctx.fillStyle = accent;
    if (head) {
      const [a, b, c, d] = head.box; ctx.strokeRect(a * W, b * H, (c - a) * W, (d - b) * H);
      const hx = head.c[0] * W, hy = head.c[1] * H, ang = Math.atan2(py - hy, px - hx), L = Math.hypot(px - hx, py - hy), ah = Math.min(18, L * 0.4) + lw * 2;
      ctx.strokeStyle = accent; ctx.lineWidth = lw * 1.6; ctx.beginPath(); ctx.moveTo(hx, hy); ctx.lineTo(px - Math.cos(ang) * ah * 0.6, py - Math.sin(ang) * ah * 0.6); ctx.stroke();
      ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(px - Math.cos(ang - 0.45) * ah, py - Math.sin(ang - 0.45) * ah); ctx.lineTo(px - Math.cos(ang + 0.45) * ah, py - Math.sin(ang + 0.45) * ah); ctx.closePath(); ctx.fill();
    } else { ctx.beginPath(); ctx.arc(px, py, lw * 3, 0, 7); ctx.fill(); }
    ctx.setLineDash([lw * 3, lw * 2]); ctx.strokeStyle = '#fff'; ctx.lineWidth = lw * 0.8;
    ctx.strokeRect(r.box[0] * W, r.box[1] * H, (r.box[2] - r.box[0]) * W, (r.box[3] - r.box[1]) * H); ctx.setLineDash([]);
  }
  if (pick) { ctx.setLineDash([6, 4]); ctx.lineWidth = 2; ctx.strokeStyle = '#4dd2ff'; ctx.strokeRect(pick[0] * W, pick[1] * H, (pick[2] - pick[0]) * W, (pick[3] - pick[1]) * H); ctx.setLineDash([]); }
}

// ---------------------------------------------------------------- sources: photo, video file, webcam
const grab = document.createElement('canvas'), gctx = grab.getContext('2d', { willReadFrequently: true });
let source = null;          // { type: 'image'|'video', el, mirror }
let pickBox = null;         // head box [x1,y1,x2,y2] as 0..1 fractions of the picture
let live = 0, lastResult = null, stillToken = 0, stream = null, fpsText = '';

function capture(side) {    // draw the current picture into the grab canvas (long side <= side), return RGB
  const el = source.el, sw = el.videoWidth || el.naturalWidth || el.width, sh = el.videoHeight || el.naturalHeight || el.height;
  const s = Math.min(1, side / Math.max(sw, sh)), w = Math.max(1, Math.round(sw * s)), h = Math.max(1, Math.round(sh * s));
  grab.width = w; grab.height = h;
  gctx.imageSmoothingEnabled = true; gctx.imageSmoothingQuality = 'high';
  if (source.mirror) { gctx.save(); gctx.translate(w, 0); gctx.scale(-1, 1); }
  gctx.drawImage(el, 0, 0, w, h);
  if (source.mirror) gctx.restore();
  const px = gctx.getImageData(0, 0, w, h).data, rgb = new Uint8Array(w * h * 3);
  for (let i = 0, o = 0; i < px.length; i += 4, o += 3) { rgb[o] = px[i]; rgb[o + 1] = px[i + 1]; rgb[o + 2] = px[i + 2]; }
  if (ui.stage.width !== w || ui.stage.height !== h) { ui.stage.width = w; ui.stage.height = h; }
  return { w, h, data: rgb };
}

const boxArgs = () => (pickBox ? { kind: 'b2p', box: pickBox.map((v) => Math.max(0, Math.min(999, Math.round(v * 1000)))) } : { kind: 'point', box: null });

function show(r, ms) {
  lastResult = r;
  const where = `looking at (${Math.round(r.point[0] * 100)}%, ${Math.round(r.point[1] * 100)}%)`;
  status(`${where} · ${(r.ms / 1000).toFixed(1)} s (vision ${(r.msVision / 1000).toFixed(1)}, language ${(r.msLm / 1000).toFixed(1)}) · ${r.tokens} tokens${pickBox ? ' · chosen head' : ''}${fpsText}`);
  ui.hint.hidden = false;
}

async function runStill() {
  const token = ++stillToken;
  if (!source || source.type !== 'image') return;
  try {
    status('Reading the picture…', 0);
    const frame = capture(STILL_SIDE); draw(grab, null, pickBox);
    await tick();
    const r = await infer(frame, { maxPixels: MAX_PIXELS, ...boxArgs() });
    if (token !== stillToken) return;
    draw(grab, r, pickBox); show(r);
  } catch (e) { fail(e); }
}

async function liveLoop(my) {
  let frames = 0, tStart = 0;
  while (live === my && source) {
    try {
      const frame = capture(LIVE_SIDE);
      const r = await infer(frame, { maxPixels: LIVE_PIXELS, ...boxArgs() });
      if (live !== my) break;
      draw(grab, r, pickBox); show(r);
      frames++;
      if (frames >= 2) fpsText = ` · ${((frames - 1) * 1000 / (performance.now() - tStart)).toFixed(2)} frames/s`; else tStart = performance.now();
    } catch (e) { fail(e); break; }
    await new Promise((r) => requestAnimationFrame(r));
  }
}

function fail(e) { console.error(e); status(e?.message || String(e), null, true); }
function stopSource() {
  live++; stillToken++;
  if (stream) { stream.getTracks().forEach((t) => t.stop()); stream = null; }
  if (source?.type === 'video') { source.el.pause(); source.el.removeAttribute('src'); source.el.srcObject = null; }
  ui.stop.hidden = true; ui.cam.classList.remove('on');
}
function setSource(next) {
  source = next; pickBox = null; lastResult = null; fpsText = '';
  ui.box.classList.add('has'); ui.hint.hidden = true;
}

async function useImage(blob, from = null) {
  const url = URL.createObjectURL(blob);
  try {
    const el = new Image(); el.src = url; await el.decode();
    stopSource(); setSource({ type: 'image', el, mirror: false });
    for (const b of ui.thumbs.children) b.classList.toggle('on', b === from);
    runStill();
  } catch { status('Cannot read this image.', null, true); }
  finally { setTimeout(() => URL.revokeObjectURL(url), 60000); }
}
async function useVideo(blob) {
  const el = Object.assign(document.createElement('video'), { muted: true, loop: true, playsInline: true, src: URL.createObjectURL(blob) });
  try { await el.play(); } catch { status('Cannot play this video.', null, true); return; }
  stopSource(); setSource({ type: 'video', el, mirror: false });
  ui.stop.hidden = false; for (const b of ui.thumbs.children) b.classList.remove('on');
  liveLoop(++live);
}
async function useWebcam() {
  stopSource();
  try {
    if (!navigator.mediaDevices?.getUserMedia) throw new Error('The webcam needs a secure (https) page.');
    stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user', width: { ideal: 640 }, height: { ideal: 480 } }, audio: false });
    const el = Object.assign(document.createElement('video'), { muted: true, playsInline: true, srcObject: stream });
    await el.play();
    setSource({ type: 'video', el, mirror: true });
    ui.stop.hidden = false; ui.cam.classList.add('on'); for (const b of ui.thumbs.children) b.classList.remove('on');
    liveLoop(++live);
  } catch (e) { status(e.name === 'NotAllowedError' ? 'Webcam access was refused.' : (e.message || 'No webcam found.'), null, true); }
}
function useFile(f) {
  if (!f) return;
  if (f.type.startsWith('video/')) useVideo(f); else if (f.type.startsWith('image/') || !f.type) useImage(f);
}

// ---------------------------------------------------------------- input: drop, paste, pick, webcam, head box
ui.pick.addEventListener('click', () => ui.file.click());
ui.file.addEventListener('change', () => { useFile(ui.file.files[0]); ui.file.value = ''; });
ui.cam.addEventListener('click', () => (stream ? stopSource() : useWebcam()));
ui.stop.addEventListener('click', () => { stopSource(); status('Stopped.'); });
addEventListener('paste', (e) => { const f = [...(e.clipboardData?.files || [])][0]; if (f) { e.preventDefault(); useFile(f); } });
addEventListener('dragover', (e) => { e.preventDefault(); ui.box.classList.add('over'); });
addEventListener('dragleave', (e) => { if (!e.relatedTarget) ui.box.classList.remove('over'); });
addEventListener('drop', (e) => { e.preventDefault(); ui.box.classList.remove('over'); useFile(e.dataTransfer?.files?.[0]); });

let drag = null;
const frac = (e) => { const r = ui.stage.getBoundingClientRect(); return [Math.max(0, Math.min(1, (e.clientX - r.left) / r.width)), Math.max(0, Math.min(1, (e.clientY - r.top) / r.height))]; };
ui.stage.addEventListener('pointerdown', (e) => { if (!source) return; ui.stage.setPointerCapture(e.pointerId); drag = frac(e); });
ui.stage.addEventListener('pointermove', (e) => {
  if (!drag) return;
  const [x, y] = frac(e), box = [Math.min(drag[0], x), Math.min(drag[1], y), Math.max(drag[0], x), Math.max(drag[1], y)];
  if (source.type === 'image') draw(grab, lastResult, box); else pickBox = box;
});
ui.stage.addEventListener('pointerup', (e) => {
  if (!drag) return;
  const [x, y] = frac(e), box = [Math.min(drag[0], x), Math.min(drag[1], y), Math.max(drag[0], x), Math.max(drag[1], y)];
  drag = null;
  const small = (box[2] - box[0]) * ui.stage.width < 14 || (box[3] - box[1]) * ui.stage.height < 14;
  pickBox = small ? null : box;
  if (source.type === 'image') runStill();
});
addEventListener('keydown', (e) => { if (e.key === 'Escape' && pickBox) { pickBox = null; if (source?.type === 'image') runStill(); } });

for (const [file, alt] of EXAMPLES) {
  const b = document.createElement('button');
  b.type = 'button'; b.title = alt;
  b.innerHTML = `<img src="examples/thumb/${file}" alt="${alt}" loading="lazy">`;
  b.addEventListener('click', async () => {
    try {
      const r = await fetch(`examples/${file}`);
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      useImage(new Blob([await r.arrayBuffer()], { type: 'image/jpeg' }), b);
    } catch (e) { fail(e); }
  });
  ui.thumbs.append(b);
}
$('credits').innerHTML = 'Photos on Unsplash (Unsplash License): ' + EXAMPLES.map(([, alt, link]) => `<a href="${link}" target="_blank" rel="noopener">${alt}</a>`).join('; ') + '.';
$('repo').href = `https://huggingface.co/${REPO}`; $('repo').textContent = REPO;

async function storage() {
  try { const e = await navigator.storage.estimate(); ui.store.textContent = `This site stores ${mb(e.usage || 0)} in this browser.`; } catch { ui.store.textContent = ''; }
}
ui.wipe.addEventListener('click', async () => { await caches.delete(CACHE).catch(() => {}); modelP = null; ui.store.textContent = 'Deleted. The model downloads again next time.'; });
storage();
window.__look = { infer, loadModel, draw, grab, ui };      // test hook