Spaces:
Running
Running
LookAnything WebGPU: photo, video and webcam gaze following
Browse filesFiles changed (17)
- .gitattributes+6
- README.md+23-3
- app.jsAdded+532
- examples/high-five.jpgAdded
- examples/mountain.jpgAdded
- examples/phone.jpgAdded
- examples/spyglass.jpgAdded
- examples/thumb/high-five.jpgAdded
- examples/thumb/mountain.jpgAdded
- examples/thumb/phone.jpgAdded
- examples/thumb/spyglass.jpgAdded
- examples/thumb/woman-dog.jpgAdded
- examples/thumb/zoo-lion.jpgAdded
- examples/woman-dog.jpgAdded
- examples/zoo-lion.jpgAdded
- index.html+51-17
- style.css+47-23
32 unmodified lines33343536373839404132 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textexamples/high-five.jpg filter=lfs diff=lfs merge=lfs -textexamples/mountain.jpg filter=lfs diff=lfs merge=lfs -textexamples/phone.jpg filter=lfs diff=lfs merge=lfs -textexamples/spyglass.jpg filter=lfs diff=lfs merge=lfs -textexamples/woman-dog.jpg filter=lfs diff=lfs merge=lfs -textexamples/zoo-lion.jpg filter=lfs diff=lfs merge=lfs -text1234345678910111213141516171819102021222324252627282930---title: LookAnything WebGPUemoji: 😻colorFrom: yellowemoji: 👀colorFrom: graycolorTo: redsdk: staticapp_file: index.htmlpinned: falselicense: apache-2.0short_description: Where is everyone looking? Gaze following in your browsermodels: - JYT4chenxiyuxi/LookAnything - WeReCooking/LookAnything-ONNX-WebGPUtags: - webgpu - onnxruntime-web - gaze-following---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-referenceDrop a photo or a video, paste one, or turn on the webcam: [LookAnything](https://huggingface.co/JYT4chenxiyuxi/LookAnything)(Qwen3-VL-2B with learned gaze queries) shows where the people in it are looking, on your own GPU with ONNX Runtime Web.Nothing is uploaded. The arrow runs from the head to the gaze point; the orange glow is the heatmap and the dashed box thegaze box. Drag a box around a head to pick one person in a crowd.
The model (8-bit ONNX, 2.26 GB) comes from [WeReCooking/LookAnything-ONNX-WebGPU](https://huggingface.co/WeReCooking/LookAnything-ONNX-WebGPU)and downloads once into the browser. It needs WebGPU and about 3 GB of free GPU memory; expect seconds per frame on mostGPUs, so webcam and video are near-live rather than video speed. Only the one-pass heads (point, box, heatmap, head mask)are included, not the text answers.
Example photos: Unsplash, by Stephen H, Hunter Bryant, Manuel Meza, Erik Mclean, Richard Brutyo and Kelly Sikkema (Unsplash License).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532// 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 orderfunction 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 otherfunction 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, exactfunction 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.jsonfunction 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;}
// ---------------------------------------------------------------- modellet 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 memoryconst 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);
// ---------------------------------------------------------------- drawingconst 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, webcamconst 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 picturelet 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 boxui.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 hook123456789101112131415161718234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253<!doctype html><html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>My static Space</title> <link rel="stylesheet" href="style.css" /> </head> <body> <div class="card"> <h1>Welcome to your static Space!</h1> <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p> <p> Also don't forget to check the <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>. </p> </div> </body><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>LookAnything WebGPU</title><meta name="description" content="Where is everyone looking? LookAnything gaze following on your own GPU with ONNX Runtime Web, for photos, videos and your webcam."><link rel="icon" href="data:,"><link rel="stylesheet" href="style.css"></head><body><main> <p id="line"><b><a href="https://huggingface.co/JYT4chenxiyuxi/LookAnything" target="_blank" rel="noopener">LookAnything</a></b> shows where the people in a photo, a video or your webcam are looking. It runs on your own GPU and nothing is uploaded.</p>
<section id="stagebox"> <canvas id="stage" width="640" height="420" aria-label="Photo or video with the predicted gaze"></canvas> <div id="ask"><span>Drop a photo or video here, paste one,<br>or use the buttons below</span></div> <div id="tools"> <button id="pick" type="button" title="Pick a photo or video" aria-label="Pick a photo or video"> <svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/></svg> </button> <button id="cam" type="button" title="Use the webcam" aria-label="Use the webcam"> <svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true"><path d="M4 8a2 2 0 0 1 2-2h1.5l1.2-1.6h6.6L16.5 6H18a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/><circle cx="12" cy="12.5" r="3.4" fill="none" stroke="currentColor" stroke-width="1.8"/></svg> </button> <button id="stop" type="button" hidden title="Stop" aria-label="Stop the video or webcam"> <svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true"><rect x="6" y="6" width="12" height="12" rx="1.5" fill="currentColor"/></svg> </button> <input id="file" type="file" accept="image/*,video/*" class="sr"> </div> </section>
<p id="status" role="status" aria-live="polite">Ready. The model (2.3 GB) downloads once, when you first pick something.</p> <div id="bar"><i></i></div> <p id="hint" hidden>Drag a box around a head to choose one person. Click the picture to clear the box.</p>
<section id="examples"><div id="thumbs"></div></section>
<details id="more"> <summary>About, storage and credits</summary> <p>LookAnything (A Foundation Model for Holistic Gaze Following, Apache-2.0) by Jiayu Tang, Yuchen Zhou et al. is a Qwen3-VL-2B model with learned gaze queries. This page runs its one-pass heads: the gaze point (the arrow tip), the gaze box, the heatmap and the head mask (the arrow start), from a single forward pass, no text generation. The ONNX conversion (8-bit weights, vision LoRA merged) is in <a id="repo" target="_blank" rel="noopener">the model repo</a>.</p> <p>Photos and video use the full 451,584-pixel budget of the original demo settings for stills and about 200,000 pixels live, which is roughly twice as fast and moves the point by a few percent of the image. Needs WebGPU (Chrome or Edge 121+, Android 12+, Safari 26) and about 3 GB of free GPU memory. Expect seconds per frame, not video speed, except on a fast desktop GPU.</p> <p id="store"></p> <button id="wipe" type="button">Delete downloaded model</button> <p id="credits"></p> </details></main><script type="module" src="app.js"></script></body></html>12312345567867891011121314151617111213141516181920212223242526272829303132181920212223243334353637382627283940414243444546474849505152body { padding: 2rem; font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif;:root { --bg: #f4f2ee; --panel: #ffffff; --ink: #1d1c1a; --muted: #6b6760; --line: #d8d4cc; --accent: #b4441b; --accent-ink: #ffffff; --bad: #a3261b; color-scheme: light dark;}
h1 { font-size: 16px; margin-top: 0;@media (prefers-color-scheme: dark) { :root { --bg: #151413; --panel: #1f1d1b; --ink: #ece8e1; --muted: #a29d94; --line: #3a3732; --accent: #e0703f; --accent-ink: #151413; --bad: #ff8a7a; }}* { box-sizing: border-box; }html, body { margin: 0; background: var(--bg); color: var(--ink); font: 15px/1.4 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }main { display: grid; gap: 8px; padding: 8px 12px 16px; max-width: 1100px; margin: 0 auto; grid-template-columns: minmax(0, 1fr); }#line { margin: 0; font-size: 14px; color: var(--muted); }#line b { color: var(--ink); font-weight: 600; font-size: 15px; }#line a { color: inherit; }
p { color: rgb(107, 114, 128); font-size: 15px; margin-bottom: 10px; margin-top: 5px;}#stagebox { position: relative; background: var(--panel); border: 1.5px dashed var(--line); border-radius: 6px; overflow: hidden; display: grid; place-items: center; min-height: 240px; }#stagebox.has { border-style: solid; background: #000; }#stagebox.over { border-color: var(--accent); }#stage { display: block; width: 100%; height: auto; max-height: 72vh; object-fit: contain; touch-action: pan-y; cursor: crosshair; }#stagebox:not(.has) #stage { display: none; }#ask { position: absolute; inset: 0; display: grid; place-items: center; text-align: center; padding: 24px 24px 64px; color: var(--muted); pointer-events: none; }#stagebox.has #ask { display: none; }#tools { position: absolute; left: 8px; bottom: 8px; display: flex; gap: 8px; }#tools button { width: 42px; height: 42px; display: grid; place-items: center; padding: 0; cursor: pointer; color: var(--ink); background: color-mix(in srgb, var(--panel) 88%, transparent); border: 1px solid var(--line); border-radius: 50%; }#tools button:hover { border-color: var(--accent); color: var(--accent); }#tools button[hidden] { display: none; }#tools button.on { color: var(--accent-ink); background: var(--accent); border-color: var(--accent); }
.card { max-width: 620px; margin: 0 auto; padding: 16px; border: 1px solid lightgray; border-radius: 16px;}#status { margin: 0; min-height: 1.4em; font-size: 13px; color: var(--muted); font-variant-numeric: tabular-nums; }#status.bad { color: var(--bad); }#bar { height: 4px; background: var(--line); border-radius: 2px; overflow: hidden; margin-top: -4px; }#bar i { display: block; height: 100%; width: 0; background: var(--accent); transition: width .2s; }#hint { margin: 0; font-size: 12px; color: var(--muted); }
.card p:last-child { margin-bottom: 0;}#thumbs { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 6px; }@media (max-width: 480px) { #thumbs { grid-template-columns: repeat(3, minmax(0, 1fr)); } }#thumbs button { padding: 0; border: 2px solid transparent; border-radius: 5px; background: none; cursor: pointer; aspect-ratio: 1; overflow: hidden; }#thumbs button.on { border-color: var(--accent); }#thumbs img { width: 100%; height: 100%; object-fit: cover; display: block; border-radius: 3px; }
#more { color: var(--muted); font-size: 13px; }#more p { margin: 6px 0; }summary { cursor: pointer; }#wipe { font: inherit; min-height: 30px; padding: 0 12px; cursor: pointer; color: var(--ink); background: transparent; border: 1px solid var(--line); border-radius: 4px; }a { color: var(--accent); }.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }:where(button, input, summary, a, [tabindex]):focus-visible { outline: 2px solid var(--accent) !important; outline-offset: 2px; }@media (prefers-reduced-motion: reduce) { *, *::before, *::after { transition-duration: 0.01ms !important; } }.gitattributes+6
README.md+23-3
app.jsAdded+532
examples/high-five.jpgAdded

Large File Pointer Details
- SHA256: 3ae1a4dda0ca937da85cea929b189fdbcadc9b26999522fb7750613a45509928
- Pointer size: 131 Bytes
- Size of remote file: 193 kB
examples/mountain.jpgAdded

Large File Pointer Details
- SHA256: 871a67bf014634af309fa3fdc1d6b657542defda026c2e8dabe1b442c387fdfb
- Pointer size: 131 Bytes
- Size of remote file: 192 kB
examples/phone.jpgAdded

Large File Pointer Details
- SHA256: fdc091c1a4337bee05e6b9952aefa064e2d2e2320dfd00b8ad24180d01a1ea66
- Pointer size: 131 Bytes
- Size of remote file: 190 kB
examples/spyglass.jpgAdded

Large File Pointer Details
- SHA256: d778f4a19f7083014d7ab6436060074f6d548ac894a5ba32baf05d97d9874a51
- Pointer size: 131 Bytes
- Size of remote file: 257 kB
examples/thumb/high-five.jpgAdded
examples/thumb/mountain.jpgAdded
examples/thumb/phone.jpgAdded
examples/thumb/spyglass.jpgAdded
examples/thumb/woman-dog.jpgAdded
examples/thumb/zoo-lion.jpgAdded
examples/woman-dog.jpgAdded

Large File Pointer Details
- SHA256: 5a653d3f343367f059688c72406ed9273d1b586d106f13e462e6dd3d8a44c8d3
- Pointer size: 131 Bytes
- Size of remote file: 180 kB
examples/zoo-lion.jpgAdded

Large File Pointer Details
- SHA256: 217e710b6755ef1be25400ef793feb697048d85ad608cd9ffe0497b6057d934d
- Pointer size: 131 Bytes
- Size of remote file: 334 kB
index.html+51-17
style.css+47-23