real time and some fixes

#2
by akhaliq HF Staff - opened
Files changed (3) hide show
  1. README.md +9 -1
  2. app.py +267 -11
  3. studio.html +117 -10
README.md CHANGED
@@ -25,12 +25,20 @@ does text-to-image, image-to-image (structure to image, colorization, style tran
25
 
26
  The Space serves a project-page-inspired studio UI (`studio.html`) through a `gr.Server` app: a clean white layout,
27
  black typography and the red/green/blue Jeveration wordmark, plus an optional neutral dark theme. The studio includes
28
- Generate / Edit / Dense modes, a before/after split view, run history, per-run timing info, and all original examples.
 
 
 
 
29
 
30
  The **Workflow** tab opens a `gr.Workflow` canvas at `/workflow`, following the node-based workflow pattern from
31
  [PrunaAI/P-Image-OSS](https://huggingface.co/spaces/PrunaAI/P-Image-OSS). The starter graph chains Prompt → Generate →
32
  Style Edit → Dense, with generated and styled image previews plus segmentation, depth and surface-normal outputs.
33
  An optional source-image node can be wired into the edit node instead. Edit `workflow.json` to change the starter graph.
 
 
 
 
34
 
35
  - Paper: https://arxiv.org/abs/2611.24738
36
  - Code: https://github.com/Carol-lyh/Jeveration
 
25
 
26
  The Space serves a project-page-inspired studio UI (`studio.html`) through a `gr.Server` app: a clean white layout,
27
  black typography and the red/green/blue Jeveration wordmark, plus an optional neutral dark theme. The studio includes
28
+ Generate / Edit / Dense modes, a before/after split view, per-run timing info, and all original examples. Each tab keeps
29
+ its own history — a chip restores its run into its own tab only, so a Dense input never appears as an Edit source or a
30
+ Generate prompt. A **⚡ Live preview** toggle (Generate and Edit) holds the GPU for ~85 s and streams a fresh 512 × 512
31
+ frame whenever the prompt, task or source changes — the realtime pattern from
32
+ [akhaliq/p-h3-image-2step](https://huggingface.co/spaces/akhaliq/p-h3-image-2step).
33
 
34
  The **Workflow** tab opens a `gr.Workflow` canvas at `/workflow`, following the node-based workflow pattern from
35
  [PrunaAI/P-Image-OSS](https://huggingface.co/spaces/PrunaAI/P-Image-OSS). The starter graph chains Prompt → Generate →
36
  Style Edit → Dense, with generated and styled image previews plus segmentation, depth and surface-normal outputs.
37
  An optional source-image node can be wired into the edit node instead. Edit `workflow.json` to change the starter graph.
38
+ Canvas runs run on the visitor's own ZeroGPU quota: the studio page's client calls carry the visitor's `x-ip-token`,
39
+ which the app stashes per client IP and re-attaches to the canvas's GPU calls — the same pattern as
40
+ [akhaliq/idol-studio](https://huggingface.co/spaces/akhaliq/idol-studio), without which the canvas's iframe (which never
41
+ completes gradio's handshake with huggingface.co) bills the Space's anonymous allowance.
42
 
43
  - Paper: https://arxiv.org/abs/2611.24738
44
  - Code: https://github.com/Carol-lyh/Jeveration
app.py CHANGED
@@ -7,7 +7,10 @@ gr.Server API endpoints at / and a chainable gr.Workflow canvas at /workflow.
7
  """
8
  import base64
9
  import io
 
10
  import os
 
 
11
  import time
12
  from urllib.parse import unquote, urlparse
13
 
@@ -22,8 +25,10 @@ except ImportError:
22
 
23
  import gradio as gr
24
  from fastapi.responses import FileResponse, HTMLResponse
 
25
  from gradio.utils import get_upload_folder
26
  from gradio_client import utils as client_utils
 
27
 
28
  from jeveration import config
29
  from jeveration.dense import depth_view, normal_view, seg_view
@@ -224,7 +229,12 @@ def _run(fn, *args):
224
  try:
225
  return fn(*args)
226
  except (RuntimeError, ValueError) as error:
227
- raise gr.Error(str(error).split("\n")[0])
 
 
 
 
 
228
 
229
 
230
  @_gpu
@@ -242,28 +252,155 @@ def _dense(image):
242
  return _dense_run(image)
243
 
244
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  # ------------------------------------------------------------------ workflow fns
246
 
247
 
248
- def jeveration_generate(prompt, seed: str = "42") -> dict:
249
- """Generate one 512 x 512 image from text."""
 
 
 
 
 
 
250
  seed_value = min(max(int(float(seed)), 0), MAX_SEED)
251
- image, _ = _run(_generate, prompt, seed_value)
252
  return _as_media(_publish(image))
253
 
254
 
255
- def jeveration_edit(image, task: str = "anime", caption: str = "", seed: str = "42") -> dict:
 
256
  """Apply structure-to-image, colorization or style transfer to an image."""
257
  _check_choice(task, I2I_TASKS, "Task")
258
  source = _open_rgb(image)
259
  seed_value = min(max(int(float(seed)), 0), MAX_SEED)
260
- _, result, _ = _run(_edit, source, task, caption, False, seed_value)
261
  return _as_media(_publish(result))
262
 
263
 
264
- def jeveration_dense(image) -> tuple[dict, dict, dict]:
265
  """Return segmentation, depth and surface normals for an image."""
266
- seg, depth, normal, _ = _run(_dense, _open_rgb(image))
267
  return tuple(_as_media(_publish(result)) for result in (seg, depth, normal))
268
 
269
 
@@ -287,8 +424,10 @@ def _example_file(name: str):
287
 
288
 
289
  @server.api(name="generate", concurrency_limit=1)
290
- def api_generate(prompt: str, seed: float = 0, randomize: bool = True) -> dict:
 
291
  """Text-to-image with Jeveration (one 512 x 512 forward pass)."""
 
292
  seed_value = _resolve_seed(seed, randomize)
293
  image, note = _run(_generate, prompt, seed_value)
294
  return {"image_data": _to_png_uri(image), "seed": seed_value, "info": note}
@@ -296,8 +435,9 @@ def api_generate(prompt: str, seed: float = 0, randomize: bool = True) -> dict:
296
 
297
  @server.api(name="edit", concurrency_limit=1)
298
  def api_edit(source: str, task: str = "hed", caption: str = "", from_photo: bool = False,
299
- seed: float = 0, randomize: bool = True) -> dict:
300
  """Structure-to-image, colorization or style transfer with Jeveration."""
 
301
  _check_choice(task, I2I_TASKS, "Task")
302
  seed_value = _resolve_seed(seed, randomize)
303
  image = _open_rgb(source)
@@ -307,13 +447,129 @@ def api_edit(source: str, task: str = "hed", caption: str = "", from_photo: bool
307
 
308
 
309
  @server.api(name="dense", concurrency_limit=1)
310
- def api_dense(image: str) -> dict:
311
  """Segmentation (13 classes), depth and surface normals of a picture."""
 
312
  seg, depth, normal, note = _run(_dense, _open_rgb(image))
313
  return {"seg_data": _to_png_uri(seg), "depth_data": _to_png_uri(depth), "normal_data": _to_png_uri(normal),
314
  "info": note}
315
 
316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
317
  if spaces is None: # compile the kernels before the first visitor's request
318
  try:
319
  for _ in range(2):
 
7
  """
8
  import base64
9
  import io
10
+ import json
11
  import os
12
+ import tempfile
13
+ import threading
14
  import time
15
  from urllib.parse import unquote, urlparse
16
 
 
25
 
26
  import gradio as gr
27
  from fastapi.responses import FileResponse, HTMLResponse
28
+ from gradio.context import LocalContext
29
  from gradio.utils import get_upload_folder
30
  from gradio_client import utils as client_utils
31
+ from starlette.requests import Request as StarletteRequest
32
 
33
  from jeveration import config
34
  from jeveration.dense import depth_view, normal_view, seg_view
 
229
  try:
230
  return fn(*args)
231
  except (RuntimeError, ValueError) as error:
232
+ message = str(error).split("\n")[0]
233
+ if "ZeroGPU" in message and ("limit" in message or "quota" in message):
234
+ message += (" The run was billed anonymously: open the Space from its huggingface.co page "
235
+ "while signed in, so it uses your own ZeroGPU quota — the anonymous allowance "
236
+ "is tiny and shared.")
237
+ raise gr.Error(message)
238
 
239
 
240
  @_gpu
 
252
  return _dense_run(image)
253
 
254
 
255
+ # ---- ZeroGPU quota on the workflow canvas -----------------------------------
256
+ # The canvas is nested inside the studio iframe, so gradio's postMessage handshake with
257
+ # huggingface.co — which would attach the visitor's x-ip-token to the canvas's requests —
258
+ # never completes, and its @spaces.GPU calls bill the Space's anonymous allowance. The
259
+ # studio page's own @gradio/client calls do carry the header, so every studio API call
260
+ # stashes it per client IP, and workflow runs from the same IP re-attach it here.
261
+ # Pattern from akhaliq/idol-studio.
262
+ _TOKEN_TTL = 1800 # seconds
263
+ _tokens: dict[str, tuple[str, float]] = {}
264
+ _tokens_lock = threading.Lock()
265
+
266
+
267
+ def _token_claims(token: str) -> dict:
268
+ """The unverified JWT payload, to tell user-attributed tokens from anonymous ones."""
269
+ try:
270
+ payload = token.split(".")[1]
271
+ return json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
272
+ except Exception: # noqa: BLE001 - not a JWT
273
+ return {}
274
+
275
+
276
+ def _client_ip(request) -> str:
277
+ forwarded = (request.headers.get("x-forwarded-for") or "").split(",")[0].strip()
278
+ return forwarded or (request.client.host if request.client else "")
279
+
280
+
281
+ def _is_user_token(token: str) -> bool:
282
+ return bool(_token_claims(token).get("user"))
283
+
284
+
285
+ def _is_fresh_user_token(token: str) -> bool:
286
+ """User-attributed and not expiring in the next few seconds (proxy tokens live ~2-4 min)."""
287
+ claims = _token_claims(token)
288
+ return bool(claims.get("user")) and claims.get("exp", 0) > time.time() + 5
289
+
290
+
291
+ def _remember_token(request) -> None:
292
+ if request is None:
293
+ return
294
+ token = request.headers.get("x-ip-token")
295
+ if not token:
296
+ return
297
+ ip = _client_ip(request)
298
+ with _tokens_lock:
299
+ now = time.time()
300
+ for stale in [stale for stale, (_, at) in _tokens.items() if now - at > _TOKEN_TTL]:
301
+ del _tokens[stale]
302
+ existing = _tokens.get(ip)
303
+ # never downgrade: an anonymous edge token must not replace a usable user-attributed one
304
+ if existing and _is_fresh_user_token(existing[0]) and not _is_user_token(token):
305
+ return
306
+ _tokens[ip] = (token, now)
307
+
308
+
309
+ def _fake_starlette_request(token_or_headers) -> StarletteRequest:
310
+ """A real starlette request carrying just an x-ip-token (or a full header dict), so the
311
+ gradio Request built on top of it behaves like one served over HTTP."""
312
+ if isinstance(token_or_headers, str):
313
+ headers = {"x-ip-token": token_or_headers}
314
+ else:
315
+ headers = token_or_headers
316
+ scope = {
317
+ "type": "http",
318
+ "method": "GET",
319
+ "path": "/",
320
+ "scheme": "https",
321
+ "query_string": b"",
322
+ "headers": [(k.lower().encode("ascii"), str(v).encode("latin-1"))
323
+ for k, v in headers.items() if v is not None],
324
+ }
325
+ return StarletteRequest(scope)
326
+
327
+
328
+ def _as_gradio_request(request):
329
+ """A gradio Request with a live underlying starlette request — the shape spaces' ZeroGPU
330
+ hook expects in LocalContext (it reads `request.request`). The workflow runtime and some
331
+ Server-mode paths inject a raw starlette Request, and queue-created gradio Requests carry
332
+ no live one; both are wrapped so ZeroGPU can read the visitor's x-ip-token."""
333
+ if request is None:
334
+ return None
335
+ if isinstance(request, gr.Request):
336
+ if request.request is not None:
337
+ return request
338
+ return gr.Request(request=_fake_starlette_request(dict(getattr(request, "headers", {}) or {})))
339
+ if isinstance(request, StarletteRequest):
340
+ return gr.Request(request=request)
341
+ return gr.Request(request=_fake_starlette_request(str(request)))
342
+
343
+
344
+ def _zerogpu_request(request):
345
+ """The gradio Request to bind to LocalContext for the GPU call, or None to run anonymously.
346
+
347
+ The studio's handshaken token (stored per IP) wins over the injected request's own header:
348
+ that one may be an anonymous edge-minted token, which bills the Space's anonymous allowance."""
349
+ direct = request.headers.get("x-ip-token") if request is not None else None
350
+ ip = _client_ip(request) if request is not None else ""
351
+ with _tokens_lock:
352
+ hit = _tokens.get(ip)
353
+ stored = hit[0] if hit and time.time() - hit[1] <= _TOKEN_TTL else None
354
+ if stored and _is_user_token(stored) and not _is_fresh_user_token(stored):
355
+ stored = None # expired: the scheduler would reject it anyway
356
+ if stored and (_is_user_token(stored) or not direct):
357
+ return _as_gradio_request(stored)
358
+ if direct:
359
+ return _as_gradio_request(request)
360
+ return None
361
+
362
+
363
+ def _on_visitor_quota(request, fn, *args):
364
+ """Run one GPU call on the visitor's quota when their token is known, else anonymously."""
365
+ zerogpu_request = _zerogpu_request(request)
366
+ if zerogpu_request is None:
367
+ return _run(fn, *args)
368
+ reset = LocalContext.request.set(zerogpu_request)
369
+ try:
370
+ return _run(fn, *args)
371
+ finally:
372
+ LocalContext.request.reset(reset)
373
+
374
+
375
  # ------------------------------------------------------------------ workflow fns
376
 
377
 
378
+ def jeveration_generate(prompt, seed: str = "42", request: gr.Request = None) -> dict:
379
+ """Generate one 512 x 512 image from text.
380
+
381
+ `request` is injected by the workflow runtime and never appears as a canvas port. ZeroGPU
382
+ bills whoever owns the X-IP-Token header of the request in LocalContext; pointing the
383
+ contextvar at the visitor's request keeps the @spaces.GPU call on their quota instead of
384
+ the Space's anonymous allowance.
385
+ """
386
  seed_value = min(max(int(float(seed)), 0), MAX_SEED)
387
+ image, _ = _on_visitor_quota(request, _generate, prompt, seed_value)
388
  return _as_media(_publish(image))
389
 
390
 
391
+ def jeveration_edit(image, task: str = "anime", caption: str = "", seed: str = "42",
392
+ request: gr.Request = None) -> dict:
393
  """Apply structure-to-image, colorization or style transfer to an image."""
394
  _check_choice(task, I2I_TASKS, "Task")
395
  source = _open_rgb(image)
396
  seed_value = min(max(int(float(seed)), 0), MAX_SEED)
397
+ _, result, _ = _on_visitor_quota(request, _edit, source, task, caption, False, seed_value)
398
  return _as_media(_publish(result))
399
 
400
 
401
+ def jeveration_dense(image, request: gr.Request = None) -> tuple[dict, dict, dict]:
402
  """Return segmentation, depth and surface normals for an image."""
403
+ seg, depth, normal, _ = _on_visitor_quota(request, _dense, _open_rgb(image))
404
  return tuple(_as_media(_publish(result)) for result in (seg, depth, normal))
405
 
406
 
 
424
 
425
 
426
  @server.api(name="generate", concurrency_limit=1)
427
+ def api_generate(prompt: str, seed: float = 0, randomize: bool = True,
428
+ request: gr.Request = None) -> dict:
429
  """Text-to-image with Jeveration (one 512 x 512 forward pass)."""
430
+ _remember_token(request)
431
  seed_value = _resolve_seed(seed, randomize)
432
  image, note = _run(_generate, prompt, seed_value)
433
  return {"image_data": _to_png_uri(image), "seed": seed_value, "info": note}
 
435
 
436
  @server.api(name="edit", concurrency_limit=1)
437
  def api_edit(source: str, task: str = "hed", caption: str = "", from_photo: bool = False,
438
+ seed: float = 0, randomize: bool = True, request: gr.Request = None) -> dict:
439
  """Structure-to-image, colorization or style transfer with Jeveration."""
440
+ _remember_token(request)
441
  _check_choice(task, I2I_TASKS, "Task")
442
  seed_value = _resolve_seed(seed, randomize)
443
  image = _open_rgb(source)
 
447
 
448
 
449
  @server.api(name="dense", concurrency_limit=1)
450
+ def api_dense(image: str, request: gr.Request = None) -> dict:
451
  """Segmentation (13 classes), depth and surface normals of a picture."""
452
+ _remember_token(request)
453
  seg, depth, normal, note = _run(_dense, _open_rgb(image))
454
  return {"seg_data": _to_png_uri(seg), "depth_data": _to_png_uri(depth), "normal_data": _to_png_uri(normal),
455
  "info": note}
456
 
457
 
458
+ @server.api(name="handshake")
459
+ def api_handshake(request: gr.Request = None) -> dict:
460
+ """No-op the studio page calls on load and every minute; @gradio/client only attaches
461
+ the visitor's ZeroGPU user token to queued calls, which _remember_token then stashes
462
+ for the workflow canvas's runs (whose iframe never completes the handshake)."""
463
+ _remember_token(request)
464
+ return {"ok": True}
465
+
466
+
467
+ # ------------------------------------------------------------------ realtime edits
468
+ # The pattern from akhaliq/p-h3-image-2step (linoyts/qwen-image-2-1-realtime): a held-GPU
469
+ # @spaces.GPU generator polls a per-session JSON channel and renders a fresh 512 x 512 frame
470
+ # whenever the prompt, task, caption, source or seed changes, so live updates skip the
471
+ # per-call reservation. @spaces.GPU runs in a forked subprocess, so requests reach the
472
+ # running generator through the file, not a shared variable.
473
+
474
+ LIVE_DIR = os.path.join(tempfile.gettempdir(), "jeveration_live")
475
+ os.makedirs(LIVE_DIR, exist_ok=True)
476
+ RT_WINDOW = 85 # seconds of held GPU per realtime window (under the @spaces.GPU duration)
477
+ _gpu_live = spaces.GPU(duration=95) if spaces else (lambda fn: fn)
478
+
479
+
480
+ def _live_path(sid):
481
+ return os.path.join(LIVE_DIR, f"{sid}.json")
482
+
483
+
484
+ def push_live(prompt, task, caption, from_photo, seed, source, sid):
485
+ """Write the latest live request to the session's channel (no GPU). Bumps a version counter."""
486
+ if not sid:
487
+ return
488
+ path = _live_path(sid)
489
+ prev = 0
490
+ if os.path.exists(path):
491
+ try:
492
+ prev = int(json.load(open(path)).get("ver", 0))
493
+ except Exception: # noqa: BLE001
494
+ prev = 0
495
+ tmp = path + ".tmp"
496
+ with open(tmp, "w") as handle:
497
+ json.dump({"prompt": prompt or "", "task": task or "hed", "caption": caption or "",
498
+ "from_photo": bool(from_photo), "seed": int(seed), "source": source or None,
499
+ "ver": prev + 1}, handle)
500
+ os.replace(tmp, path)
501
+
502
+
503
+ def _render_live_frame(req):
504
+ """One live frame: an edit when a source is set, text-to-image otherwise. The model itself
505
+ is the fast tier — one 512 x 512 forward pass per frame."""
506
+ seed = int(req.get("seed", 0))
507
+ if req.get("source"):
508
+ image = _open_rgb(req["source"])
509
+ prepared, result, note = _edit_run(image, req.get("task", "hed"), req.get("caption", ""),
510
+ bool(req.get("from_photo")), seed)
511
+ return {"image_data": _to_png_uri(result), "source_data": _to_png_uri(prepared),
512
+ "seed": seed, "info": note}
513
+ result, note = _generate_run(req.get("prompt", ""), seed)
514
+ return {"image_data": _to_png_uri(result), "seed": seed, "info": note}
515
+
516
+
517
+ @_gpu_live
518
+ def _realtime_session(sid, realtime_on):
519
+ """Hold the GPU and yield a fresh frame whenever the session's request changes."""
520
+ if not realtime_on or not sid:
521
+ return
522
+ path = _live_path(sid)
523
+ deadline = time.time() + RT_WINDOW
524
+ last_ver = -1
525
+ while time.time() < deadline:
526
+ req = None
527
+ if os.path.exists(path):
528
+ try:
529
+ with open(path) as handle:
530
+ req = json.load(handle)
531
+ except Exception: # noqa: BLE001
532
+ req = None
533
+ if req and int(req.get("ver", -1)) != last_ver:
534
+ last_ver = int(req["ver"])
535
+ try:
536
+ yield _render_live_frame(req)
537
+ except Exception as error: # noqa: BLE001 - one bad frame should not end the session
538
+ print(f"[realtime] frame skipped: {error!r}", flush=True)
539
+ else:
540
+ time.sleep(0.05)
541
+
542
+
543
+ @server.api(name="live_push", concurrency_limit=8)
544
+ def api_live_push(prompt: str = "", task: str = "hed", caption: str = "", from_photo: bool = False,
545
+ seed: float = 0, source: str = "", sid: str = "") -> dict:
546
+ """Queue the newest live request for the held-GPU realtime session (no GPU call)."""
547
+ push_live(prompt, task, caption, bool(from_photo), int(seed), source or None, sid)
548
+ return {"ok": True}
549
+
550
+
551
+ @server.api(name="live_session", concurrency_limit=1)
552
+ def api_live_session(sid: str, realtime_on: bool = True, request: gr.Request = None) -> dict:
553
+ """Hold the GPU and stream a fresh 512 x 512 frame whenever the session's request changes.
554
+
555
+ The -> dict annotation is load-bearing: gr.api derives the endpoint's outputs from the
556
+ return annotation, and a generator without one registers ZERO outputs — the queue then
557
+ drops every streamed frame with a 'returned too many output values' warning.
558
+ """
559
+ _remember_token(request)
560
+ if not sid:
561
+ raise gr.Error("No realtime session id.")
562
+ zerogpu_request = _zerogpu_request(request)
563
+ if zerogpu_request is None:
564
+ yield from _realtime_session(sid, realtime_on)
565
+ return
566
+ reset = LocalContext.request.set(zerogpu_request)
567
+ try:
568
+ yield from _realtime_session(sid, realtime_on)
569
+ finally:
570
+ LocalContext.request.reset(reset)
571
+
572
+
573
  if spaces is None: # compile the kernels before the first visitor's request
574
  try:
575
  for _ in range(2):
studio.html CHANGED
@@ -367,6 +367,13 @@
367
  <div class="hint" id="task-hint"></div>
368
  </div>
369
  </section>
 
 
 
 
 
 
 
370
  <section class="panel">
371
  <div class="panel-title">Advanced</div>
372
  <div class="panel-body">
@@ -404,8 +411,9 @@
404
  import { client } from "https://cdn.jsdelivr.net/npm/@gradio/client@2.7.1/dist/index.min.js";
405
 
406
  const $ = (id) => document.getElementById(id);
407
- const state = { mode: "generate", sourcePath: null, app: null };
408
- const docState = { source: null, result: null, history: [] };
 
409
 
410
  const TASKS = ["hed", "depth", "colorize", "anime", "ghibli", "watercolor"];
411
  const TASK_HELP = {
@@ -512,12 +520,11 @@
512
  }
513
  const dense = mode === "dense";
514
  const edit = mode === "edit";
 
 
515
  $("doc-before").style.display = "";
516
  $("doc-after").style.display = dense ? "none" : "";
517
- for (const id of ["doc-seg", "doc-depth", "doc-normal"]) {
518
- $(id).hidden = !dense;
519
- $(id).style.display = "";
520
- }
521
  $("task-panel").hidden = !edit;
522
  $("prompt-title").textContent = edit ? "Caption" : "Prompt";
523
  $("prompt").placeholder = edit ? "Caption of the wanted image (hed / depth)" : "Describe the image…";
@@ -527,6 +534,7 @@
527
  $("run-btn").textContent = dense ? "Predict" : edit ? "Generate Edit" : "Generate";
528
  $("split-toggle").hidden = !(edit && !$("result-img").hidden && !$("source-img").hidden);
529
  renderExamples();
 
530
  }
531
  $("mode-generate").onclick = () => setMode("generate");
532
  $("mode-edit").onclick = () => setMode("edit");
@@ -544,6 +552,91 @@
544
  taskSel.value = "hed";
545
  taskSel.onchange = () => { $("task-hint").textContent = TASK_HELP[taskSel.value]; };
546
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
547
  // ---------- uploads ----------
548
  $("tool-upload").onclick = () => { $("file-input").click(); };
549
  $("file-input").onchange = async (e) => {
@@ -555,6 +648,7 @@
555
  state.sourcePath = await uploadFile(file);
556
  showLocalSource(file);
557
  if (state.mode === "generate") setMode("edit");
 
558
  setStatus("Idle");
559
  } catch (err) {
560
  setStatus(String(err));
@@ -570,6 +664,7 @@
570
  state.sourcePath = await uploadFile(file);
571
  showLocalSource(file);
572
  if (state.mode === "generate") setMode("edit");
 
573
  setStatus("Idle");
574
  } catch (err) {
575
  setStatus(String(err));
@@ -608,10 +703,12 @@
608
  };
609
 
610
  // ---------- history ----------
 
 
611
  function renderHistory() {
612
  const strip = $("history-strip");
613
  strip.innerHTML = '<span class="hlabel">History</span>';
614
- docState.history.forEach((h) => {
615
  const chip = document.createElement("div");
616
  chip.className = "history-chip";
617
  chip.title = h.prompt || h.info || "";
@@ -627,8 +724,9 @@
627
  });
628
  }
629
  function pushHistory(entry) {
630
- docState.history.unshift(entry);
631
- if (docState.history.length > 8) docState.history.pop();
 
632
  renderHistory();
633
  }
634
 
@@ -724,7 +822,15 @@
724
  chip.appendChild(label);
725
  chip.appendChild(tag);
726
  chip.onclick = () => {
727
- setMode("generate");
 
 
 
 
 
 
 
 
728
  $("prompt").value = prompt;
729
  setStatus("Example loaded — hit Generate");
730
  };
@@ -753,6 +859,7 @@
753
  state.sourcePath = await uploadExampleUrl(`/examples/${ex.file}`, ex.file);
754
  showSourceImage(`/examples/${ex.file}`);
755
  $("before-caption").textContent = "Source";
 
756
  setStatus("Example loaded — hit Generate Edit");
757
  } catch (err) {
758
  setStatus(String(err));
 
367
  <div class="hint" id="task-hint"></div>
368
  </div>
369
  </section>
370
+ <section class="panel" id="live-panel">
371
+ <div class="panel-title">Realtime</div>
372
+ <div class="panel-body">
373
+ <label class="switch"><input type="checkbox" id="live-toggle" /><span class="sw"></span><span class="sw-label">⚡ Live preview</span></label>
374
+ <div class="hint" id="live-hint">Holds the GPU for ~85 s and re-renders as you type — a fresh 512 × 512 frame whenever the prompt, task or source changes. Full-quality runs queue behind the window; toggle Live off for those.</div>
375
+ </div>
376
+ </section>
377
  <section class="panel">
378
  <div class="panel-title">Advanced</div>
379
  <div class="panel-body">
 
411
  import { client } from "https://cdn.jsdelivr.net/npm/@gradio/client@2.7.1/dist/index.min.js";
412
 
413
  const $ = (id) => document.getElementById(id);
414
+ const state = { mode: "generate", sourcePath: null, app: null, sid: null, liveJob: null, liveOn: false, liveFrames: 0 };
415
+ const docState = { source: null, result: null };
416
+ const histories = { generate: [], edit: [], dense: [] }; // one history per tab, app-side
417
 
418
  const TASKS = ["hed", "depth", "colorize", "anime", "ghibli", "watercolor"];
419
  const TASK_HELP = {
 
520
  }
521
  const dense = mode === "dense";
522
  const edit = mode === "edit";
523
+ if ((dense || mode === "workflow") && state.liveOn) setLive(false); // live preview is a generate/edit tool
524
+ $("live-panel").hidden = dense || mode === "workflow";
525
  $("doc-before").style.display = "";
526
  $("doc-after").style.display = dense ? "none" : "";
527
+ for (const id of ["doc-seg", "doc-depth", "doc-normal"]) $(id).style.display = dense ? "" : "none";
 
 
 
528
  $("task-panel").hidden = !edit;
529
  $("prompt-title").textContent = edit ? "Caption" : "Prompt";
530
  $("prompt").placeholder = edit ? "Caption of the wanted image (hed / depth)" : "Describe the image…";
 
534
  $("run-btn").textContent = dense ? "Predict" : edit ? "Generate Edit" : "Generate";
535
  $("split-toggle").hidden = !(edit && !$("result-img").hidden && !$("source-img").hidden);
536
  renderExamples();
537
+ renderHistory();
538
  }
539
  $("mode-generate").onclick = () => setMode("generate");
540
  $("mode-edit").onclick = () => setMode("edit");
 
552
  taskSel.value = "hed";
553
  taskSel.onchange = () => { $("task-hint").textContent = TASK_HELP[taskSel.value]; };
554
 
555
+ // ---------- realtime live preview ----------
556
+ // The pattern from akhaliq/p-h3-image-2step: a held-GPU session on the app streams a fresh
557
+ // frame whenever the session's request changes; edits here just rewrite the request channel
558
+ // (/live_push, no GPU). The window starts only when the toggle flips — never on page load.
559
+ function getSid() {
560
+ if (!state.sid) state.sid = (crypto.randomUUID ? crypto.randomUUID()
561
+ : String(Math.random()).slice(2) + Date.now());
562
+ return state.sid;
563
+ }
564
+ let livePushTimer = null;
565
+ async function pushLive() {
566
+ if (!state.liveOn) return;
567
+ try {
568
+ const app = await getApp();
569
+ await app.predict("/live_push", {
570
+ prompt: $("prompt").value.trim(),
571
+ task: taskSel.value,
572
+ caption: $("prompt").value.trim(),
573
+ from_photo: $("from-photo").checked,
574
+ seed: parseInt($("seed").value, 10) || 0,
575
+ source: state.sourcePath || "",
576
+ sid: getSid(),
577
+ });
578
+ } catch (err) { /* the next change retries */ }
579
+ }
580
+ function queueLivePush() {
581
+ if (!state.liveOn) return;
582
+ clearTimeout(livePushTimer);
583
+ livePushTimer = setTimeout(pushLive, 300);
584
+ }
585
+ function applyLiveFrame(payload) {
586
+ if (typeof payload.image_data === "string") {
587
+ const img = $("result-img");
588
+ img.src = payload.image_data;
589
+ img.hidden = false;
590
+ $("result-hint").style.display = "none";
591
+ docState.result = payload.image_data;
592
+ }
593
+ if (typeof payload.source_data === "string" && state.mode === "edit") {
594
+ showSourceImage(payload.source_data);
595
+ $("before-caption").textContent = "Input as the model reads it (512 × 512)";
596
+ }
597
+ if (payload.seed != null) $("seed-out").textContent = "seed " + payload.seed;
598
+ $("result-meta").textContent = (payload.info || "") + " · live";
599
+ $("run-info").value = payload.info || "";
600
+ state.liveFrames += 1;
601
+ setStatus(`Live · ${state.liveFrames} frame${state.liveFrames === 1 ? "" : "s"} this window`, true);
602
+ }
603
+ async function setLive(on) {
604
+ state.liveOn = on;
605
+ $("live-toggle").checked = on;
606
+ if (on) {
607
+ if (state.mode !== "generate" && state.mode !== "edit") return;
608
+ state.liveFrames = 0;
609
+ setStatus("Starting the live window���", true);
610
+ await pushLive();
611
+ try {
612
+ const app = await getApp();
613
+ const job = app.submit("/live_session", { sid: getSid(), realtime_on: true });
614
+ state.liveJob = job;
615
+ for await (const msg of job) {
616
+ const payload = Array.isArray(msg?.data) ? msg.data[0] : msg?.data;
617
+ if (payload && typeof payload === "object" && payload.image_data) applyLiveFrame(payload);
618
+ }
619
+ state.liveOn = false;
620
+ $("live-toggle").checked = false;
621
+ setStatus(`Live window ended after ${state.liveFrames} frame${state.liveFrames === 1 ? "" : "s"} — toggle Live again for a new one`);
622
+ } catch (err) {
623
+ if (state.liveOn) setStatus(err?.message || String(err));
624
+ } finally {
625
+ state.liveJob = null;
626
+ }
627
+ } else {
628
+ clearTimeout(livePushTimer);
629
+ try { await state.liveJob?.cancel?.(); } catch (e) {}
630
+ state.liveJob = null;
631
+ setStatus("Idle");
632
+ }
633
+ }
634
+ $("live-toggle").onchange = () => setLive($("live-toggle").checked);
635
+ $("prompt").addEventListener("input", queueLivePush);
636
+ taskSel.addEventListener("change", queueLivePush);
637
+ $("from-photo").addEventListener("change", queueLivePush);
638
+ $("seed").addEventListener("input", queueLivePush);
639
+
640
  // ---------- uploads ----------
641
  $("tool-upload").onclick = () => { $("file-input").click(); };
642
  $("file-input").onchange = async (e) => {
 
648
  state.sourcePath = await uploadFile(file);
649
  showLocalSource(file);
650
  if (state.mode === "generate") setMode("edit");
651
+ queueLivePush();
652
  setStatus("Idle");
653
  } catch (err) {
654
  setStatus(String(err));
 
664
  state.sourcePath = await uploadFile(file);
665
  showLocalSource(file);
666
  if (state.mode === "generate") setMode("edit");
667
+ queueLivePush();
668
  setStatus("Idle");
669
  } catch (err) {
670
  setStatus(String(err));
 
703
  };
704
 
705
  // ---------- history ----------
706
+ // Each tab renders only its own history: a chip restores its run into its own tab only,
707
+ // so a Dense input never shows up as an Edit source or a Generate prompt.
708
  function renderHistory() {
709
  const strip = $("history-strip");
710
  strip.innerHTML = '<span class="hlabel">History</span>';
711
+ (histories[state.mode] || []).forEach((h) => {
712
  const chip = document.createElement("div");
713
  chip.className = "history-chip";
714
  chip.title = h.prompt || h.info || "";
 
724
  });
725
  }
726
  function pushHistory(entry) {
727
+ const list = histories[entry.mode] || (histories[entry.mode] = []);
728
+ list.unshift(entry);
729
+ if (list.length > 8) list.pop();
730
  renderHistory();
731
  }
732
 
 
822
  chip.appendChild(label);
823
  chip.appendChild(tag);
824
  chip.onclick = () => {
825
+ // ---------- ZeroGPU quota handshake for the workflow canvas ----------
826
+ // The canvas iframe can't complete gradio's postMessage handshake with huggingface.co, so its
827
+ // GPU calls would bill the Space's anonymous allowance (the quota error on the Workflow tab).
828
+ // The studio page's own @gradio/client calls carry the visitor's x-ip-token; /handshake
829
+ // stashes it server-side per client IP for the canvas's runs to re-attach.
830
+ getApp().then((app) => app.predict("/handshake", {})).catch(() => {});
831
+ setInterval(() => { getApp().then((app) => app.predict("/handshake", {})).catch(() => {}); }, 60000);
832
+
833
+ setMode("generate");
834
  $("prompt").value = prompt;
835
  setStatus("Example loaded — hit Generate");
836
  };
 
859
  state.sourcePath = await uploadExampleUrl(`/examples/${ex.file}`, ex.file);
860
  showSourceImage(`/examples/${ex.file}`);
861
  $("before-caption").textContent = "Source";
862
+ queueLivePush();
863
  setStatus("Example loaded — hit Generate Edit");
864
  } catch (err) {
865
  setStatus(String(err));