Live camera mode for style transfer
Browse files91 unmodified lines92939495969748 unmodified lines1461471481491501511521531541551561571581591601611621631641651661671681697 unmodified lines17717817918018118218318412 unmodified lines1971981992002012022036 unmodified lines21021121221321421521621721821922091 unmodified lines<input type="file" id="file" accept="image/*" class="sr-only"></label><div class="thumbs" id="thumbs"></div><label>Style</label><div class="chips" id="styles"></div></div>48 unmodified lines$("thumbs").append(b);}/** a picture -> 512 x 512 RGB (shorter side to 512, centre crop), shown in the drop zone and sent to the worker once */async function setPhoto(blob) {const bmp = await createImageBitmap(blob), s = 512 / Math.min(bmp.width, bmp.height);const w = Math.max(512, Math.round(bmp.width * s)), h = Math.max(512, Math.round(bmp.height * s));const ctx = $("src").getContext("2d"); ctx.imageSmoothingQuality = "high";ctx.drawImage(bmp, -Math.floor((w - 512) / 2), -Math.floor((h - 512) / 2), w, h);const px = ctx.getImageData(0, 0, 512, 512).data, rgb = new Uint8Array(512 * 512 * 3);for (let i = 0; i < 512 * 512; i++) { rgb[3 * i] = px[4 * i]; rgb[3 * i + 1] = px[4 * i + 1]; rgb[3 * i + 2] = px[4 * i + 2]; }worker.postMessage({ type: "image", data: { rgb, imageId: ++imageId } }, [rgb.buffer]);haveImage = true; live();}$("file").onchange = (e) => { if (e.target.files[0]) setPhoto(e.target.files[0]); e.target.value = ""; };$("drop").ondragover = (e) => { e.preventDefault(); $("drop").classList.add("over"); };$("drop").ondragleave = () => $("drop").classList.remove("over");$("drop").ondrop = (e) => { e.preventDefault(); $("drop").classList.remove("over"); if (e.dataTransfer.files[0]) setPhoto(e.dataTransfer.files[0]); };const setMode = (m) => {mode = m;$("tab-t2i").setAttribute("aria-selected", String(m === "t2i")); $("tab-i2i").setAttribute("aria-selected", String(m === "i2i"));$("t2i-panel").hidden = m !== "t2i"; $("i2i-panel").hidden = m !== "i2i";if (m === "i2i" && !haveImage) $("thumbs").children[0].click(); else live();7 unmodified linesconst TOTAL = 7.55e9;let ready = false, reqId = 0;const sent = new Map(), frames = [];const request = () => {if (mode === "i2i" && !haveImage) return;const id = ++reqId; sent.set(id, performance.now());worker.postMessage({ type: "generate", data: { mode, prompt: $("prompt").value, task, seed: Number($("seed").value) || 0, id } });};12 unmodified lines$("bar").style.width = "100%";setStatus(`Ready (loaded in ${m.data.seconds.toFixed(1)} s).`);$("go").disabled = false; $("load").disabled = true; ready = true;if ($("live").checked) request();} else if (m.status === "image") {const { rgb, timings } = m.data, img = new ImageData(512, 512);for (let i = 0; i < 512 * 512; i++) { img.data[4 * i] = rgb[3 * i]; img.data[4 * i + 1] = rgb[3 * i + 1]; img.data[4 * i + 2] = rgb[3 * i + 2]; img.data[4 * i + 3] = 255; }6 unmodified linesframes.push(now); while (frames.length && now - frames[0] > 5000) frames.shift();const fps = frames.length > 1 ? (frames.length - 1) / ((now - frames[0]) / 1000) : 0;setStatus(`Done in ${(timings.total / 1000).toFixed(2)} s.`);$("live-stats").textContent = `Latency from change to image: ${(latency / 1000).toFixed(2)} s` +(fps ? ` · ${fps.toFixed(1)} images/s` : "") + (m.data.skipped ? ` · ${m.data.skipped} stale requests skipped` : "");$("go").disabled = false;} else if (m.status === "error") {setStatus("Error: " + m.data, true); $("go").disabled = false;}};$("load").onclick = () => { $("load").disabled = true; setStatus("Starting..."); worker.postMessage({ type: "load" }); };91 unmodified lines929394959697989948 unmodified lines1481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002017 unmodified lines20921021121221321421521621712 unmodified lines2302312322332342352366 unmodified lines24324424524624724824925025125225325491 unmodified lines<input type="file" id="file" accept="image/*" class="sr-only"></label><div class="thumbs" id="thumbs"></div><button class="secondary" id="cam" type="button">Use camera (live)</button><video id="video" playsinline muted hidden></video><label>Style</label><div class="chips" id="styles"></div></div>48 unmodified lines$("thumbs").append(b);}/** a picture or video frame -> 512 x 512 RGB (shorter side to 512, centre crop; mirrored for the camera), drawn in the* drop zone and sent to the worker */function sendFrame(src, sw, sh, mirror = false) {const s = 512 / Math.min(sw, sh), w = Math.max(512, Math.round(sw * s)), h = Math.max(512, Math.round(sh * s));const ctx = $("src").getContext("2d", { willReadFrequently: true }); ctx.imageSmoothingQuality = "high";ctx.save(); if (mirror) { ctx.translate(512, 0); ctx.scale(-1, 1); }ctx.drawImage(src, -Math.floor((w - 512) / 2), -Math.floor((h - 512) / 2), w, h); ctx.restore();const px = ctx.getImageData(0, 0, 512, 512).data, rgb = new Uint8Array(512 * 512 * 3);for (let i = 0; i < 512 * 512; i++) { rgb[3 * i] = px[4 * i]; rgb[3 * i + 1] = px[4 * i + 1]; rgb[3 * i + 2] = px[4 * i + 2]; }worker.postMessage({ type: "image", data: { rgb, imageId: ++imageId } }, [rgb.buffer]);haveImage = true;}async function setPhoto(blob) {stopCamera();const bmp = await createImageBitmap(blob);sendFrame(bmp, bmp.width, bmp.height); live();}$("file").onchange = (e) => { if (e.target.files[0]) setPhoto(e.target.files[0]); e.target.value = ""; };// Camera: one frame in flight at a time. The next frame is grabbed when the previous image comes back, so the output// lags the camera by one generation, never more, and the seed (sampling noise) stays fixed for a steadier picture.let stream = null, camBusy = false;function camTick() {if (!stream || !ready || camBusy || mode !== "i2i") return;const v = $("video");if (v.readyState < 2) { requestAnimationFrame(camTick); return; }camBusy = true; sendFrame(v, v.videoWidth, v.videoHeight, true); request(true);}async function startCamera() {try {stream = await navigator.mediaDevices.getUserMedia({ video: { width: { ideal: 640 }, height: { ideal: 640 }, facingMode: "user" }, audio: false });} catch (e) { setStatus("Camera unavailable: " + (e.message || e), true); stream = null; return; }$("video").srcObject = stream; await $("video").play();$("cam").textContent = "Stop camera"; camBusy = false;if (!ready) setStatus("Camera on. Load the model to start."); camTick();}function stopCamera() {if (!stream) return;for (const t of stream.getTracks()) t.stop();stream = null; camBusy = false; $("video").srcObject = null; $("cam").textContent = "Use camera (live)";}$("cam").onclick = () => (stream ? stopCamera() : startCamera());$("drop").ondragover = (e) => { e.preventDefault(); $("drop").classList.add("over"); };$("drop").ondragleave = () => $("drop").classList.remove("over");$("drop").ondrop = (e) => { e.preventDefault(); $("drop").classList.remove("over"); if (e.dataTransfer.files[0]) setPhoto(e.dataTransfer.files[0]); };const setMode = (m) => {mode = m; if (m !== "i2i") stopCamera();$("tab-t2i").setAttribute("aria-selected", String(m === "t2i")); $("tab-i2i").setAttribute("aria-selected", String(m === "i2i"));$("t2i-panel").hidden = m !== "t2i"; $("i2i-panel").hidden = m !== "i2i";if (m === "i2i" && !haveImage) $("thumbs").children[0].click(); else live();7 unmodified linesconst TOTAL = 7.55e9;let ready = false, reqId = 0;const sent = new Map(), frames = [];const request = (fromCamera = false) => {if (mode === "i2i" && !haveImage) return;if (stream && !fromCamera) return; // the camera loop drives requests while it runsconst id = ++reqId; sent.set(id, performance.now());worker.postMessage({ type: "generate", data: { mode, prompt: $("prompt").value, task, seed: Number($("seed").value) || 0, id } });};12 unmodified lines$("bar").style.width = "100%";setStatus(`Ready (loaded in ${m.data.seconds.toFixed(1)} s).`);$("go").disabled = false; $("load").disabled = true; ready = true;if (stream) camTick(); else if ($("live").checked) request();} else if (m.status === "image") {const { rgb, timings } = m.data, img = new ImageData(512, 512);for (let i = 0; i < 512 * 512; i++) { img.data[4 * i] = rgb[3 * i]; img.data[4 * i + 1] = rgb[3 * i + 1]; img.data[4 * i + 2] = rgb[3 * i + 2]; img.data[4 * i + 3] = 255; }6 unmodified linesframes.push(now); while (frames.length && now - frames[0] > 5000) frames.shift();const fps = frames.length > 1 ? (frames.length - 1) / ((now - frames[0]) / 1000) : 0;setStatus(`Done in ${(timings.total / 1000).toFixed(2)} s.`);$("live-stats").textContent = `Latency ${stream ? "from camera frame" : "from change"} to image: ${(latency / 1000).toFixed(2)} s` +(fps ? ` · ${fps.toFixed(1)} images/s` : "") + (m.data.skipped ? ` · ${m.data.skipped} stale requests skipped` : "");$("go").disabled = false;if (stream) { camBusy = false; requestAnimationFrame(camTick); }} else if (m.status === "error") {setStatus("Error: " + m.data, true); $("go").disabled = false; camBusy = false;}};$("load").onclick = () => { $("load").disabled = true; setStatus("Starting..."); worker.postMessage({ type: "load" }); };
index.html+46-12