linoyts HF Staff commited on
Commit
8b506d7
·
verified ·
1 Parent(s): 0718f73

Live camera mode for style transfer

Browse files
Files changed (1) hide show
  1. index.html +46 -12
index.html CHANGED
@@ -92,6 +92,8 @@
92
  <input type="file" id="file" accept="image/*" class="sr-only">
93
  </label>
94
  <div class="thumbs" id="thumbs"></div>
 
 
95
  <label>Style</label>
96
  <div class="chips" id="styles"></div>
97
  </div>
@@ -146,24 +148,54 @@
146
  $("thumbs").append(b);
147
  }
148
 
149
- /** a picture -> 512 x 512 RGB (shorter side to 512, centre crop), shown in the drop zone and sent to the worker once */
150
- async function setPhoto(blob) {
151
- const bmp = await createImageBitmap(blob), s = 512 / Math.min(bmp.width, bmp.height);
152
- const w = Math.max(512, Math.round(bmp.width * s)), h = Math.max(512, Math.round(bmp.height * s));
153
- const ctx = $("src").getContext("2d"); ctx.imageSmoothingQuality = "high";
154
- ctx.drawImage(bmp, -Math.floor((w - 512) / 2), -Math.floor((h - 512) / 2), w, h);
 
155
  const px = ctx.getImageData(0, 0, 512, 512).data, rgb = new Uint8Array(512 * 512 * 3);
156
  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]; }
157
  worker.postMessage({ type: "image", data: { rgb, imageId: ++imageId } }, [rgb.buffer]);
158
- haveImage = true; live();
 
 
 
 
 
159
  }
160
  $("file").onchange = (e) => { if (e.target.files[0]) setPhoto(e.target.files[0]); e.target.value = ""; };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  $("drop").ondragover = (e) => { e.preventDefault(); $("drop").classList.add("over"); };
162
  $("drop").ondragleave = () => $("drop").classList.remove("over");
163
  $("drop").ondrop = (e) => { e.preventDefault(); $("drop").classList.remove("over"); if (e.dataTransfer.files[0]) setPhoto(e.dataTransfer.files[0]); };
164
 
165
  const setMode = (m) => {
166
- mode = m;
167
  $("tab-t2i").setAttribute("aria-selected", String(m === "t2i")); $("tab-i2i").setAttribute("aria-selected", String(m === "i2i"));
168
  $("t2i-panel").hidden = m !== "t2i"; $("i2i-panel").hidden = m !== "i2i";
169
  if (m === "i2i" && !haveImage) $("thumbs").children[0].click(); else live();
@@ -177,8 +209,9 @@
177
  const TOTAL = 7.55e9;
178
  let ready = false, reqId = 0;
179
  const sent = new Map(), frames = [];
180
- const request = () => {
181
  if (mode === "i2i" && !haveImage) return;
 
182
  const id = ++reqId; sent.set(id, performance.now());
183
  worker.postMessage({ type: "generate", data: { mode, prompt: $("prompt").value, task, seed: Number($("seed").value) || 0, id } });
184
  };
@@ -197,7 +230,7 @@
197
  $("bar").style.width = "100%";
198
  setStatus(`Ready (loaded in ${m.data.seconds.toFixed(1)} s).`);
199
  $("go").disabled = false; $("load").disabled = true; ready = true;
200
- if ($("live").checked) request();
201
  } else if (m.status === "image") {
202
  const { rgb, timings } = m.data, img = new ImageData(512, 512);
203
  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; }
@@ -210,11 +243,12 @@
210
  frames.push(now); while (frames.length && now - frames[0] > 5000) frames.shift();
211
  const fps = frames.length > 1 ? (frames.length - 1) / ((now - frames[0]) / 1000) : 0;
212
  setStatus(`Done in ${(timings.total / 1000).toFixed(2)} s.`);
213
- $("live-stats").textContent = `Latency from change to image: ${(latency / 1000).toFixed(2)} s` +
214
  (fps ? ` · ${fps.toFixed(1)} images/s` : "") + (m.data.skipped ? ` · ${m.data.skipped} stale requests skipped` : "");
215
  $("go").disabled = false;
 
216
  } else if (m.status === "error") {
217
- setStatus("Error: " + m.data, true); $("go").disabled = false;
218
  }
219
  };
220
  $("load").onclick = () => { $("load").disabled = true; setStatus("Starting..."); worker.postMessage({ type: "load" }); };
 
92
  <input type="file" id="file" accept="image/*" class="sr-only">
93
  </label>
94
  <div class="thumbs" id="thumbs"></div>
95
+ <button class="secondary" id="cam" type="button">Use camera (live)</button>
96
+ <video id="video" playsinline muted hidden></video>
97
  <label>Style</label>
98
  <div class="chips" id="styles"></div>
99
  </div>
 
148
  $("thumbs").append(b);
149
  }
150
 
151
+ /** a picture or video frame -> 512 x 512 RGB (shorter side to 512, centre crop; mirrored for the camera), drawn in the
152
+ * drop zone and sent to the worker */
153
+ function sendFrame(src, sw, sh, mirror = false) {
154
+ const s = 512 / Math.min(sw, sh), w = Math.max(512, Math.round(sw * s)), h = Math.max(512, Math.round(sh * s));
155
+ const ctx = $("src").getContext("2d", { willReadFrequently: true }); ctx.imageSmoothingQuality = "high";
156
+ ctx.save(); if (mirror) { ctx.translate(512, 0); ctx.scale(-1, 1); }
157
+ ctx.drawImage(src, -Math.floor((w - 512) / 2), -Math.floor((h - 512) / 2), w, h); ctx.restore();
158
  const px = ctx.getImageData(0, 0, 512, 512).data, rgb = new Uint8Array(512 * 512 * 3);
159
  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]; }
160
  worker.postMessage({ type: "image", data: { rgb, imageId: ++imageId } }, [rgb.buffer]);
161
+ haveImage = true;
162
+ }
163
+ async function setPhoto(blob) {
164
+ stopCamera();
165
+ const bmp = await createImageBitmap(blob);
166
+ sendFrame(bmp, bmp.width, bmp.height); live();
167
  }
168
  $("file").onchange = (e) => { if (e.target.files[0]) setPhoto(e.target.files[0]); e.target.value = ""; };
169
+
170
+ // Camera: one frame in flight at a time. The next frame is grabbed when the previous image comes back, so the output
171
+ // lags the camera by one generation, never more, and the seed (sampling noise) stays fixed for a steadier picture.
172
+ let stream = null, camBusy = false;
173
+ function camTick() {
174
+ if (!stream || !ready || camBusy || mode !== "i2i") return;
175
+ const v = $("video");
176
+ if (v.readyState < 2) { requestAnimationFrame(camTick); return; }
177
+ camBusy = true; sendFrame(v, v.videoWidth, v.videoHeight, true); request(true);
178
+ }
179
+ async function startCamera() {
180
+ try {
181
+ stream = await navigator.mediaDevices.getUserMedia({ video: { width: { ideal: 640 }, height: { ideal: 640 }, facingMode: "user" }, audio: false });
182
+ } catch (e) { setStatus("Camera unavailable: " + (e.message || e), true); stream = null; return; }
183
+ $("video").srcObject = stream; await $("video").play();
184
+ $("cam").textContent = "Stop camera"; camBusy = false;
185
+ if (!ready) setStatus("Camera on. Load the model to start."); camTick();
186
+ }
187
+ function stopCamera() {
188
+ if (!stream) return;
189
+ for (const t of stream.getTracks()) t.stop();
190
+ stream = null; camBusy = false; $("video").srcObject = null; $("cam").textContent = "Use camera (live)";
191
+ }
192
+ $("cam").onclick = () => (stream ? stopCamera() : startCamera());
193
  $("drop").ondragover = (e) => { e.preventDefault(); $("drop").classList.add("over"); };
194
  $("drop").ondragleave = () => $("drop").classList.remove("over");
195
  $("drop").ondrop = (e) => { e.preventDefault(); $("drop").classList.remove("over"); if (e.dataTransfer.files[0]) setPhoto(e.dataTransfer.files[0]); };
196
 
197
  const setMode = (m) => {
198
+ mode = m; if (m !== "i2i") stopCamera();
199
  $("tab-t2i").setAttribute("aria-selected", String(m === "t2i")); $("tab-i2i").setAttribute("aria-selected", String(m === "i2i"));
200
  $("t2i-panel").hidden = m !== "t2i"; $("i2i-panel").hidden = m !== "i2i";
201
  if (m === "i2i" && !haveImage) $("thumbs").children[0].click(); else live();
 
209
  const TOTAL = 7.55e9;
210
  let ready = false, reqId = 0;
211
  const sent = new Map(), frames = [];
212
+ const request = (fromCamera = false) => {
213
  if (mode === "i2i" && !haveImage) return;
214
+ if (stream && !fromCamera) return; // the camera loop drives requests while it runs
215
  const id = ++reqId; sent.set(id, performance.now());
216
  worker.postMessage({ type: "generate", data: { mode, prompt: $("prompt").value, task, seed: Number($("seed").value) || 0, id } });
217
  };
 
230
  $("bar").style.width = "100%";
231
  setStatus(`Ready (loaded in ${m.data.seconds.toFixed(1)} s).`);
232
  $("go").disabled = false; $("load").disabled = true; ready = true;
233
+ if (stream) camTick(); else if ($("live").checked) request();
234
  } else if (m.status === "image") {
235
  const { rgb, timings } = m.data, img = new ImageData(512, 512);
236
  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; }
 
243
  frames.push(now); while (frames.length && now - frames[0] > 5000) frames.shift();
244
  const fps = frames.length > 1 ? (frames.length - 1) / ((now - frames[0]) / 1000) : 0;
245
  setStatus(`Done in ${(timings.total / 1000).toFixed(2)} s.`);
246
+ $("live-stats").textContent = `Latency ${stream ? "from camera frame" : "from change"} to image: ${(latency / 1000).toFixed(2)} s` +
247
  (fps ? ` · ${fps.toFixed(1)} images/s` : "") + (m.data.skipped ? ` · ${m.data.skipped} stale requests skipped` : "");
248
  $("go").disabled = false;
249
+ if (stream) { camBusy = false; requestAnimationFrame(camTick); }
250
  } else if (m.status === "error") {
251
+ setStatus("Error: " + m.data, true); $("go").disabled = false; camBusy = false;
252
  }
253
  };
254
  $("load").onclick = () => { $("load").disabled = true; setStatus("Starting..."); worker.postMessage({ type: "load" }); };