studio with gradio server and workflow

#1
by akhaliq HF Staff - opened
Files changed (4) hide show
  1. README.md +22 -1
  2. app.py +221 -76
  3. studio.html +781 -0
  4. workflow.json +210 -0
README.md CHANGED
@@ -4,12 +4,33 @@ emoji: 🖼️
4
  colorFrom: purple
5
  colorTo: indigo
6
  sdk: gradio
7
- sdk_version: 6.28.0
8
  python_version: "3.12"
9
  app_file: app.py
10
  pinned: false
11
  startup_duration_timeout: 1h
12
  short_description: Text-to-image and image editing, based on MiniMax-H3
 
 
13
  models:
14
  - PrunaAI/P-H3-Image
15
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  colorFrom: purple
5
  colorTo: indigo
6
  sdk: gradio
7
+ sdk_version: 6.30.0
8
  python_version: "3.12"
9
  app_file: app.py
10
  pinned: false
11
  startup_duration_timeout: 1h
12
  short_description: Text-to-image and image editing, based on MiniMax-H3
13
+ tags:
14
+ - ml-intern
15
  models:
16
  - PrunaAI/P-H3-Image
17
  ---
18
+
19
+ <a href="https://hf.co/chat?mode=ml-intern"><img src="https://huggingface.co/datasets/huggingface/badges/resolve/main/built-with-ml-intern-sm.svg" alt="Built with ML Intern" /></a>
20
+
21
+ P-H3-Image on ZeroGPU (`xlarge`: a full RTX PRO 6000 Blackwell, 96 GB) — now behind two bespoke
22
+ surfaces modeled on [briaai/Fibo-2.0-editing](https://huggingface.co/spaces/briaai/Fibo-2.0-editing),
23
+ with the backend (`p_h3_image_fast.py`, prompt upsampler, warmup) unchanged:
24
+
25
+ - **`/` — Studio** (`gr.Server` API + custom UI, Pruna design, dark and light themes): Generate
26
+ and Edit modes with prompt upsampling, aspect-ratio and resolution controls (4 / 8 / 16 MP
27
+ text-to-image, 4 / 8 MP edits at the source's aspect ratio), up to 8 reference images, seed
28
+ control, all of the original examples, before/after split view, run history with one-click
29
+ restore, and the upsampled prompt after each run. Both modes call the same `_render` as the
30
+ classic UI did.
31
+ - **`/workflow` — Workflow canvas** (`gr.Workflow`): node-based generate/edit pipelines you can
32
+ rewire and chain — text-to-image into chained edits, or your own source image. To change the
33
+ starter graph, edit `workflow.json` in the repo.
34
+
35
+ The classic two-tab form UI is replaced by the studio; `sdk_version` moves to 6.30.0 for
36
+ `gr.Server`/`gr.Workflow`.
app.py CHANGED
@@ -1,16 +1,24 @@
1
- """P-H3-Image on ZeroGPU (`xlarge`: a full RTX PRO 6000 Blackwell, 96 GB).
2
 
3
- The pipeline is loaded once at startup, one component at a time (the host has ~97 GB), and slimmed to fit the slice
4
- with p_h3_image_fast.py (kernels only, no torch.compile): AdaLN tables instead of the transformer's AdaLN projections,
5
- FP8 linears everywhere, fused Triton DiT blocks, batched VAE tiles, and for the prompt upsampler a weight-only FP8 GEMV,
6
- decode attention and speculative decoding with its MTP head in one CUDA graph per step.
 
 
 
 
 
7
  """
8
 
 
9
  import json
10
  import os
11
  import random
 
12
  import tempfile
13
  import time
 
14
 
15
  os.environ.setdefault("DIFFUSERS_TRUST_REMOTE_KERNELS", "true")
16
  os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
@@ -18,19 +26,23 @@ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
18
  import gradio as gr
19
  import spaces
20
  import torch
 
 
 
 
21
  from huggingface_hub import snapshot_download
22
  from PIL import Image, ImageOps
23
  from torchvision.io import encode_jpeg
24
 
25
  import p_h3_image_fast as fast
26
  from diffusers import ModularPipeline
27
- from examples import EXAMPLES
28
- from theme import CSS, HEAD, THEME, render_footer, render_header
29
 
30
  REPO, REVISION = "PrunaAI/P-H3-Image", "ee4a685de1fbd4337a50bcf9b3c407e4f8463d49"
 
31
  # Canvases (width, height), multiples of 32: 4 and 8 MP as tested, 16 MP from the same ratios.
32
  RATIOS = {"1:1": 1.0, "4:3": 4 / 3, "3:4": 3 / 4, "3:2": 3 / 2, "2:3": 2 / 3, "16:9": 16 / 9, "9:16": 9 / 16}
33
  T2I_RESOLUTIONS, EDIT_RESOLUTIONS = ["4 MP", "8 MP", "16 MP"], ["4 MP", "8 MP"]
 
34
 
35
 
36
  def _canvas(ratio: float, megapixels: int) -> tuple[int, int]:
@@ -52,7 +64,7 @@ REFERENCE_BUDGET = 8 * 1024**2
52
 
53
  def load_pipeline():
54
  path = snapshot_download(REPO, revision=REVISION, max_workers=16)
55
- with open(os.path.join(os.path.dirname(__file__), "adaln_calls.json")) as handle:
56
  calls = json.load(handle)
57
  pipe, mtp = fast.load_slim_pipeline(path, calls, log=lambda message: print(message, flush=True))
58
  # The same components without the prompt upsampler step, for requests that skip upsampling.
@@ -166,17 +178,6 @@ def _info(timing, size, seed):
166
  return f"{head} ({upsample:.1f} s prompt upsampling{rate}, {timing['total'] - upsample:.1f} s rendering)"
167
 
168
 
169
- def text_to_image(prompt, aspect, resolution, upsample):
170
- if not prompt or not prompt.strip():
171
- raise gr.Error("Write a prompt first.")
172
- seed = random.randint(0, 2**31 - 1)
173
- try:
174
- path, size, upsampled, timing = _render("t2i", prompt.strip(), [], aspect, resolution, upsample, seed)
175
- except RuntimeError as error:
176
- raise gr.Error(str(error).split("\n")[0])
177
- return path, upsampled, _info(timing, size, seed)
178
-
179
-
180
  def _fit(image: Image.Image, pixels: float) -> Image.Image:
181
  """Downscale to at most `pixels` (the pipeline keeps references at their own size, from 1 MP up)."""
182
  scale = (pixels / (image.width * image.height)) ** 0.5
@@ -185,63 +186,207 @@ def _fit(image: Image.Image, pixels: float) -> Image.Image:
185
  return image.resize((max(1, round(image.width * scale)), max(1, round(image.height * scale))), Image.LANCZOS)
186
 
187
 
188
- def edit(gallery, prompt, resolution, upsample):
189
- images = []
190
- for item in gallery or []:
191
- item = item[0] if isinstance(item, (tuple, list)) else item
192
- item = Image.open(item) if isinstance(item, str) else item
193
- images.append(ImageOps.exif_transpose(item).convert("RGB"))
194
- if not images:
195
- raise gr.Error("Add at least one image; the first one is edited.")
196
- if len(images) > MAX_IMAGES:
197
- raise gr.Error(f"At most {MAX_IMAGES} images.")
198
- if not prompt or not prompt.strip():
199
- raise gr.Error("Describe the edit first.")
200
- images = [_fit(image, REFERENCE_BUDGET / len(images)) for image in images]
201
- seed = random.randint(0, 2**31 - 1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  try:
203
- path, size, upsampled, timing = _render("edit", prompt.strip(), images, None, resolution, upsample, seed)
204
  except (RuntimeError, ValueError) as error:
205
  raise gr.Error(str(error).split("\n")[0])
206
- return path, upsampled, _info(timing, size, seed)
207
-
208
-
209
- with gr.Blocks(title="P-H3-Image", fill_width=True) as demo:
210
- render_header()
211
- with gr.Tabs(elem_classes="main-tabs"):
212
- with gr.Tab("Text to image"):
213
- with gr.Row():
214
- with gr.Column():
215
- t_prompt = gr.Textbox(label="Prompt", lines=4)
216
- with gr.Row():
217
- t_aspect = gr.Dropdown(list(RATIOS), value="4:3", label="Aspect ratio", filterable=False)
218
- t_resolution = gr.Radio(T2I_RESOLUTIONS, value="8 MP", label="Resolution")
219
- t_upsample = gr.Checkbox(value=True, label="Prompt upsampling")
220
- t_button = gr.Button("Generate", variant="primary")
221
- with gr.Column():
222
- t_image = gr.Image(label="Result", type="filepath")
223
- t_info = gr.Markdown()
224
- with gr.Accordion("Upsampled prompt", open=False):
225
- t_upsampled = gr.Textbox(show_label=False, lines=10)
226
- gr.Examples([[prompt, aspect] for _, aspect, prompt in EXAMPLES], inputs=[t_prompt, t_aspect],
227
- example_labels=[label for label, _, _ in EXAMPLES])
228
- t_button.click(text_to_image, [t_prompt, t_aspect, t_resolution, t_upsample], [t_image, t_upsampled, t_info])
229
- with gr.Tab("Edit"):
230
- with gr.Row():
231
- with gr.Column():
232
- e_images = gr.Gallery(label=f"Images (the first one is edited, up to {MAX_IMAGES})", type="pil",
233
- columns=4, height=260, interactive=True)
234
- e_prompt = gr.Textbox(label="Edit", lines=3, placeholder="e.g. put the fox from <Picture 2> on the bench")
235
- e_resolution = gr.Radio(EDIT_RESOLUTIONS, value="8 MP", label="Resolution",
236
- info="The first image's aspect ratio at this size.")
237
- e_upsample = gr.Checkbox(value=True, label="Prompt upsampling")
238
- e_button = gr.Button("Edit", variant="primary")
239
- with gr.Column():
240
- e_image = gr.Image(label="Result", type="filepath")
241
- e_info = gr.Markdown()
242
- with gr.Accordion("Upsampled prompt", open=False):
243
- e_upsampled = gr.Textbox(show_label=False, lines=10)
244
- e_button.click(edit, [e_images, e_prompt, e_resolution, e_upsample], [e_image, e_upsampled, e_info])
245
- render_footer()
246
-
247
- demo.queue(max_size=20).launch(theme=THEME, css=CSS, head=HEAD)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """P-H3-Image Studio — gr.Server studio + gr.Workflow canvas.
2
 
3
+ The bespoke studio at / replaces the classic form UI; the backend is unchanged from
4
+ PrunaAI/P-H3-Image: the pipeline is loaded once at startup, one component at a time (the host has
5
+ ~97 GB), and slimmed to fit the slice with p_h3_image_fast.py (kernels only, no torch.compile):
6
+ AdaLN tables instead of the transformer's AdaLN projections, FP8 linears everywhere, fused Triton
7
+ DiT blocks, batched VAE tiles, and for the prompt upsampler a weight-only FP8 GEMV, decode
8
+ attention and speculative decoding with its MTP head in one CUDA graph per step. The studio's
9
+ Generate/Edit calls and the workflow canvas at /workflow all run through the same _render.
10
+
11
+ Server + workflow structure adapted from https://huggingface.co/spaces/briaai/Fibo-2.0-editing.
12
  """
13
 
14
+ import base64
15
  import json
16
  import os
17
  import random
18
+ import shutil
19
  import tempfile
20
  import time
21
+ from urllib.parse import unquote, urlparse
22
 
23
  os.environ.setdefault("DIFFUSERS_TRUST_REMOTE_KERNELS", "true")
24
  os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
 
26
  import gradio as gr
27
  import spaces
28
  import torch
29
+ import uvicorn
30
+ from fastapi.responses import FileResponse, HTMLResponse
31
+ from gradio.utils import get_upload_folder
32
+ from gradio_client import utils as client_utils
33
  from huggingface_hub import snapshot_download
34
  from PIL import Image, ImageOps
35
  from torchvision.io import encode_jpeg
36
 
37
  import p_h3_image_fast as fast
38
  from diffusers import ModularPipeline
 
 
39
 
40
  REPO, REVISION = "PrunaAI/P-H3-Image", "ee4a685de1fbd4337a50bcf9b3c407e4f8463d49"
41
+ APP_DIR = os.path.dirname(os.path.abspath(__file__))
42
  # Canvases (width, height), multiples of 32: 4 and 8 MP as tested, 16 MP from the same ratios.
43
  RATIOS = {"1:1": 1.0, "4:3": 4 / 3, "3:4": 3 / 4, "3:2": 3 / 2, "2:3": 2 / 3, "16:9": 16 / 9, "9:16": 9 / 16}
44
  T2I_RESOLUTIONS, EDIT_RESOLUTIONS = ["4 MP", "8 MP", "16 MP"], ["4 MP", "8 MP"]
45
+ MAX_SEED = 2**31 - 1
46
 
47
 
48
  def _canvas(ratio: float, megapixels: int) -> tuple[int, int]:
 
64
 
65
  def load_pipeline():
66
  path = snapshot_download(REPO, revision=REVISION, max_workers=16)
67
+ with open(os.path.join(APP_DIR, "adaln_calls.json")) as handle:
68
  calls = json.load(handle)
69
  pipe, mtp = fast.load_slim_pipeline(path, calls, log=lambda message: print(message, flush=True))
70
  # The same components without the prompt upsampler step, for requests that skip upsampling.
 
178
  return f"{head} ({upsample:.1f} s prompt upsampling{rate}, {timing['total'] - upsample:.1f} s rendering)"
179
 
180
 
 
 
 
 
 
 
 
 
 
 
 
181
  def _fit(image: Image.Image, pixels: float) -> Image.Image:
182
  """Downscale to at most `pixels` (the pipeline keeps references at their own size, from 1 MP up)."""
183
  scale = (pixels / (image.width * image.height)) ** 0.5
 
186
  return image.resize((max(1, round(image.width * scale)), max(1, round(image.height * scale))), Image.LANCZOS)
187
 
188
 
189
+ # --------------------------------------------------------------------------- helpers
190
+
191
+
192
+ def _resolve_seed(seed, randomize) -> int:
193
+ return random.randint(0, MAX_SEED) if randomize else min(max(int(float(seed)), 0), MAX_SEED)
194
+
195
+
196
+ def _check_choice(value, choices, name):
197
+ if value not in choices:
198
+ raise gr.Error(f"{name} must be one of: {', '.join(choices)}.")
199
+ return value
200
+
201
+
202
+ def _as_data_uri(path: str) -> str:
203
+ """Inline a result image so the studio page never needs a file route."""
204
+ with open(path, "rb") as handle:
205
+ return "data:image/jpeg;base64," + base64.b64encode(handle.read()).decode()
206
+
207
+
208
+ def _requested_path(value) -> str:
209
+ """Turn whatever the canvas/API client sends into a path."""
210
+ if isinstance(value, str):
211
+ return value
212
+ if not isinstance(value, dict):
213
+ raise gr.Error(f"Expected an image, got {type(value).__name__}")
214
+ if path := value.get("path"):
215
+ return path
216
+ url = value.get("url") or ""
217
+ if "/gradio_api/file=" in url:
218
+ return unquote(url.split("/gradio_api/file=", 1)[1])
219
+ if url.startswith(("http://", "https://")):
220
+ raise gr.Error("Upload the image instead of passing a URL.")
221
+ return unquote(urlparse(url).path)
222
+
223
+
224
+ def _local_path(value) -> str:
225
+ """A path this process may open: only files inside gradio's upload folder,
226
+ where /gradio_api/upload puts uploads and _publish puts results."""
227
+ path = os.path.realpath(_requested_path(value))
228
+ folder = os.path.realpath(get_upload_folder())
229
+ if os.path.commonpath([path, folder]) != folder:
230
+ raise gr.Error("Upload the image first.")
231
+ return path
232
+
233
+
234
+ def _open_rgb(value) -> Image.Image:
235
+ return ImageOps.exif_transpose(Image.open(_local_path(value))).convert("RGB")
236
+
237
+
238
+ def _publish(path: str) -> str:
239
+ """Copy a result into gradio's upload folder, which it already serves, so the workflow canvas can render it."""
240
+ folder = get_upload_folder()
241
+ os.makedirs(folder, exist_ok=True)
242
+ out = os.path.join(folder, f"ph3_{os.urandom(8).hex()}.jpg")
243
+ shutil.copyfile(path, out)
244
+ return out
245
+
246
+
247
+ def _as_media(path: str) -> dict:
248
+ """The dict shape the workflow canvas renders media from."""
249
+ return {
250
+ "path": path,
251
+ "url": f"/gradio_api/file={client_utils.encode_file_path(path)}",
252
+ "is_file": True,
253
+ }
254
+
255
+
256
+ def _run(mode, prompt, images, aspect, resolution, upsample, seed):
257
+ """One _render call with the classic app's error surface: messages, not stack traces."""
258
  try:
259
+ return _render(mode, prompt, images, aspect, resolution, upsample, seed)
260
  except (RuntimeError, ValueError) as error:
261
  raise gr.Error(str(error).split("\n")[0])
262
+
263
+
264
+ # ------------------------------------------------------------------ workflow fns
265
+
266
+
267
+ def ph3_generate(prompt, aspect: str = "4:3", resolution: str = "8 MP", seed: str = "42") -> dict:
268
+ """Text-to-image with P-H3-Image (prompt upsampling on)."""
269
+ if not prompt or not str(prompt).strip():
270
+ raise gr.Error("Write a prompt first.")
271
+ _check_choice(aspect, RATIOS, "Aspect ratio")
272
+ _check_choice(resolution, T2I_RESOLUTIONS, "Resolution")
273
+ seed_value = min(max(int(float(seed)), 0), MAX_SEED)
274
+ path, _, _, _ = _run("t2i", str(prompt).strip(), [], aspect, resolution, True, seed_value)
275
+ return _as_media(_publish(path))
276
+
277
+
278
+ def ph3_edit(image, prompt, seed: str = "42") -> dict:
279
+ """Edit an image with P-H3-Image (prompt upsampling on, 8 MP at the image's aspect ratio)."""
280
+ if not prompt or not str(prompt).strip():
281
+ raise gr.Error("Describe the edit first.")
282
+ source = _fit(_open_rgb(image), REFERENCE_BUDGET)
283
+ seed_value = min(max(int(float(seed)), 0), MAX_SEED)
284
+ path, _, _, _ = _run("edit", str(prompt).strip(), [source], None, "8 MP", True, seed_value)
285
+ return _as_media(_publish(path))
286
+
287
+
288
+ # ------------------------------------------------------------------ studio server
289
+
290
+ server = gr.Server(title="P-H3-Image Studio")
291
+
292
+
293
+ @server.get("/", response_class=HTMLResponse)
294
+ def _studio_page():
295
+ with open(os.path.join(APP_DIR, "studio.html"), encoding="utf-8") as handle:
296
+ return handle.read()
297
+
298
+
299
+ @server.api(name="generate", concurrency_limit=1)
300
+ def api_generate(
301
+ prompt: str,
302
+ aspect: str = "4:3",
303
+ resolution: str = "8 MP",
304
+ upsample: bool = True,
305
+ seed: float = 42,
306
+ randomize: bool = True,
307
+ ) -> dict:
308
+ """Text-to-image with P-H3-Image."""
309
+ if not prompt or not prompt.strip():
310
+ raise gr.Error("Write a prompt first.")
311
+ _check_choice(aspect, RATIOS, "Aspect ratio")
312
+ _check_choice(resolution, T2I_RESOLUTIONS, "Resolution")
313
+ seed_value = _resolve_seed(seed, randomize)
314
+ path, size, upsampled, timing = _run("t2i", prompt.strip(), [], aspect, resolution, bool(upsample), seed_value)
315
+ return {"image_data": _as_data_uri(path), "seed": seed_value, "prompt": upsampled,
316
+ "info": _info(timing, size, seed_value)}
317
+
318
+
319
+ @server.api(name="edit", concurrency_limit=1)
320
+ def api_edit(
321
+ source: str,
322
+ instruction: str,
323
+ ref2: str | None = None,
324
+ ref3: str | None = None,
325
+ ref4: str | None = None,
326
+ ref5: str | None = None,
327
+ ref6: str | None = None,
328
+ ref7: str | None = None,
329
+ ref8: str | None = None,
330
+ resolution: str = "8 MP",
331
+ upsample: bool = True,
332
+ seed: float = 42,
333
+ randomize: bool = True,
334
+ ) -> dict:
335
+ """Edit the source (+ up to 7 extra references) with P-H3-Image."""
336
+ if source is None:
337
+ raise gr.Error("Upload a source image first.")
338
+ if not instruction or not instruction.strip():
339
+ raise gr.Error("Describe the edit first.")
340
+ _check_choice(resolution, EDIT_RESOLUTIONS, "Resolution")
341
+ images = [_open_rgb(path) for path in (source, ref2, ref3, ref4, ref5, ref6, ref7, ref8) if path]
342
+ if len(images) > MAX_IMAGES:
343
+ raise gr.Error(f"At most {MAX_IMAGES} images.")
344
+ images = [_fit(image, REFERENCE_BUDGET / len(images)) for image in images]
345
+ seed_value = _resolve_seed(seed, randomize)
346
+ path, size, upsampled, timing = _run("edit", instruction.strip(), images, None, resolution, bool(upsample),
347
+ seed_value)
348
+ return {"image_data": _as_data_uri(path), "seed": seed_value, "prompt": upsampled,
349
+ "info": _info(timing, size, seed_value)}
350
+
351
+
352
+ # The @server.api endpoints are deferred until Server.launch(), which also fires
353
+ # the ZeroGPU registration hook (pack weights + startup report) through the
354
+ # patched Blocks.launch path. Launch on a loopback port for registration, then
355
+ # serve the same app via uvicorn.
356
+ _port_env = os.environ.get("GRADIO_SERVER_PORT")
357
+ os.environ["GRADIO_SERVER_PORT"] = "7861"
358
+ try:
359
+ server.launch(
360
+ prevent_thread_lock=True,
361
+ server_name="127.0.0.1",
362
+ server_port=7861,
363
+ quiet=True,
364
+ show_error=False,
365
+ ssr_mode=False,
366
+ )
367
+ finally:
368
+ if _port_env is None:
369
+ del os.environ["GRADIO_SERVER_PORT"]
370
+ else:
371
+ os.environ["GRADIO_SERVER_PORT"] = _port_env
372
+
373
+ try:
374
+ server.close()
375
+ except Exception:
376
+ pass
377
+
378
+ # ------------------------------------------------------------------ workflow canvas
379
+ # Mounted only after the registration launch above. Mounting first starts the
380
+ # workflow's queue on the loopback server's event loop, and close() then strands
381
+ # it: jobs are accepted on port 7860 but never run.
382
+
383
+ workflow_demo = gr.Workflow(
384
+ graph="workflow.json",
385
+ bind={"ph3_generate": ph3_generate, "ph3_edit": ph3_edit},
386
+ )
387
+ workflow_demo.title = "P-H3-Image Workflow"
388
+
389
+ server = gr.mount_gradio_app(server, workflow_demo, path="/workflow", ssr_mode=False)
390
+
391
+ if __name__ == "__main__":
392
+ uvicorn.run(server, host="0.0.0.0", port=7860)
studio.html ADDED
@@ -0,0 +1,781 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>P-H3-Image Studio</title>
7
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
8
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
9
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500&display=swap" rel="stylesheet" />
10
+ <style>
11
+ :root {
12
+ --bg: #120b1b; --panel: #171021; --panel2: #1d1429; --raised: #251b34;
13
+ --border: rgba(74,57,98,0.75); --hairline: rgba(255,255,255,0.08);
14
+ --text: #fafafa; --muted: #a3a3a3; --dim: #71717a;
15
+ --accent: #9334e9; --accent2: #8f35ff; --accent-soft: rgba(147,52,233,0.14);
16
+ --lavender: #d8b4fe; --link: #bf8bff;
17
+ --glow: radial-gradient(ellipse 60% 35% at 50% -5%, rgba(147,52,233,0.18), transparent 55%);
18
+ --stage-base: #0e0a16; --stage-square: #171221; --thumb-bg: #120c1c;
19
+ --radius: 10px;
20
+ }
21
+ body.light {
22
+ --bg: #f6f3fa; --panel: #ffffff; --panel2: #f6f3fa; --raised: #f3eef8;
23
+ --border: rgba(126,34,206,0.16); --hairline: rgba(24,24,27,0.08);
24
+ --text: #18181b; --muted: #71717a; --dim: #a1a1aa;
25
+ --accent: #9334e9; --accent2: #7c22ce; --accent-soft: rgba(147,52,233,0.10);
26
+ --lavender: #7e22ce; --link: #6d28d9;
27
+ --glow: radial-gradient(ellipse 60% 35% at 50% -5%, rgba(147,52,233,0.10), transparent 55%);
28
+ --stage-base: #e9e4f2; --stage-square: #f8f5fc; --thumb-bg: #f3eef8;
29
+ }
30
+ * { margin: 0; padding: 0; box-sizing: border-box; }
31
+ [hidden] { display: none !important; }
32
+ body {
33
+ font-family: "Inter", ui-sans-serif, system-ui, sans-serif;
34
+ background: var(--bg); background-image: var(--glow); background-repeat: no-repeat;
35
+ background-attachment: fixed;
36
+ color: var(--text); height: 100vh;
37
+ display: flex; flex-direction: column; overflow: hidden;
38
+ font-size: 13px; -webkit-font-smoothing: antialiased;
39
+ }
40
+ .topbar {
41
+ display: flex; align-items: center; gap: 14px; padding: 8px 16px;
42
+ background: var(--panel); border-bottom: 1px solid var(--hairline); flex-shrink: 0;
43
+ }
44
+ .brand { font-weight: 700; font-size: 0.95rem; white-space: nowrap; letter-spacing: -0.02em; display: flex; align-items: center; }
45
+ .brand img { height: 26px; margin-right: 10px; }
46
+ .studio-badge {
47
+ font-size: 0.6rem; font-weight: 650; letter-spacing: 0.12em; text-transform: uppercase;
48
+ color: var(--lavender); border: 1px solid var(--border); border-radius: 999px;
49
+ padding: 2px 8px; margin-left: 10px; background: var(--accent-soft);
50
+ }
51
+ .mode-tabs { display: flex; gap: 2px; background: var(--panel2); border: 1px solid var(--border); border-radius: 9px; padding: 3px; }
52
+ .mode-tabs button {
53
+ border: none; border-radius: 7px; padding: 6px 16px; font-weight: 550; font-size: 0.82rem;
54
+ background: transparent; color: var(--muted); cursor: pointer; transition: color 0.15s, background 0.15s;
55
+ font-family: inherit;
56
+ }
57
+ .mode-tabs button:hover { color: var(--text); }
58
+ .mode-tabs button.active { background: var(--raised); color: var(--text); box-shadow: 0 1px 3px rgba(0,0,0,0.45); }
59
+ body.light .mode-tabs button.active { box-shadow: 0 1px 3px rgba(88,28,135,0.15); }
60
+ .spacer { flex: 1; }
61
+ .ml-badge { color: var(--muted); text-decoration: none; font-size: 0.8rem; font-weight: 500; transition: color 0.15s; white-space: nowrap; }
62
+ .ml-badge:hover { color: var(--text); }
63
+ .ml-badge-img { display: inline-flex; align-items: center; }
64
+ .ml-badge-img img { height: 20px; display: block; }
65
+ .ml-badge-img:hover { opacity: 0.85; }
66
+ .ml-cta {
67
+ color: var(--lavender); text-decoration: none; font-size: 0.8rem; font-weight: 600;
68
+ padding: 5px 13px; border: 1px solid var(--accent); border-radius: 999px;
69
+ background: var(--accent-soft); transition: filter 0.15s; white-space: nowrap;
70
+ }
71
+ .ml-cta:hover { filter: brightness(1.2); }
72
+ .theme-toggle {
73
+ width: 34px; height: 34px; border: 1px solid var(--border); border-radius: 9px;
74
+ background: transparent; color: var(--muted); cursor: pointer; flex-shrink: 0;
75
+ display: inline-flex; align-items: center; justify-content: center;
76
+ transition: color 0.15s, background 0.15s;
77
+ }
78
+ .theme-toggle:hover { color: var(--text); background: var(--panel2); }
79
+ .theme-toggle svg { width: 17px; height: 17px; }
80
+ .theme-toggle .theme-icon-moon { display: none; }
81
+ .theme-toggle[data-mode="light"] .theme-icon-sun { display: none; }
82
+ .theme-toggle[data-mode="light"] .theme-icon-moon { display: block; }
83
+ .main { display: flex; flex: 1; min-height: 0; }
84
+ .rail {
85
+ width: 52px; flex-shrink: 0; display: flex; flex-direction: column; align-items: center;
86
+ gap: 6px; padding: 10px 0; background: var(--panel); border-right: 1px solid var(--hairline);
87
+ }
88
+ .rail button {
89
+ width: 38px; height: 38px; border: 1px solid transparent; border-radius: 8px;
90
+ background: transparent; color: var(--muted); cursor: pointer;
91
+ display: flex; align-items: center; justify-content: center;
92
+ transition: color 0.15s, background 0.15s;
93
+ }
94
+ .rail button:hover { background: var(--panel2); color: var(--text); }
95
+ .rail button.active { color: var(--accent2); background: var(--accent-soft); }
96
+ .viewport { flex: 1; min-width: 0; display: flex; flex-direction: column; overflow: auto; position: relative; }
97
+ .workflow-view { position: absolute; inset: 0; padding: 12px; }
98
+ .workflow-view iframe { width: 100%; height: 100%; border: none; border-radius: 10px; background: var(--stage-base); }
99
+ .doc-grid { flex: 1; min-height: 0; display: flex; gap: 16px; width: 100%; align-items: stretch; justify-content: center; padding: 20px 20px 10px; }
100
+ .doc {
101
+ flex: 1; min-width: 0; max-width: 640px; display: flex; flex-direction: column;
102
+ background: var(--panel); border: 1px solid var(--border); border-radius: 10px; overflow: hidden;
103
+ }
104
+ .doc figcaption {
105
+ padding: 8px 12px; font-size: 0.62rem; font-weight: 650; letter-spacing: 0.12em;
106
+ color: var(--dim); border-bottom: 1px solid var(--hairline); text-transform: uppercase;
107
+ display: flex; align-items: center;
108
+ }
109
+ .doc .stage {
110
+ position: relative; flex: 1; min-height: 0; display: flex; align-items: center; justify-content: center;
111
+ overflow: hidden; background-color: var(--stage-base);
112
+ background-image:
113
+ linear-gradient(45deg, var(--stage-square) 25%, transparent 25%),
114
+ linear-gradient(-45deg, var(--stage-square) 25%, transparent 25%),
115
+ linear-gradient(45deg, transparent 75%, var(--stage-square) 75%),
116
+ linear-gradient(-45deg, transparent 75%, var(--stage-square) 75%);
117
+ background-size: 20px 20px;
118
+ background-position: 0 0, 0 10px, 10px -10px, -10px 0;
119
+ }
120
+ .doc img { max-width: 100%; max-height: 100%; object-fit: contain; display: block; }
121
+ .doc img.zoomed { max-width: none; max-height: none; }
122
+ .doc .stage.scrollable { overflow: auto; justify-content: flex-start; align-items: flex-start; }
123
+ .drop-hint { color: var(--dim); font-size: 0.85rem; text-align: center; padding: 20px; }
124
+ .drop-hint b { color: var(--muted); display: block; margin-bottom: 6px; }
125
+ .zoom-btn {
126
+ margin-left: auto; border: 1px solid var(--border); background: transparent; color: var(--muted);
127
+ border-radius: 5px; font-size: 0.62rem; padding: 2px 8px; cursor: pointer; letter-spacing: 0.08em;
128
+ font-family: inherit;
129
+ }
130
+ .zoom-btn:hover { color: var(--text); border-color: var(--accent); }
131
+ .doc-bar {
132
+ display: flex; align-items: center; gap: 10px; padding: 6px 12px;
133
+ border-top: 1px solid var(--hairline); background: var(--panel);
134
+ font-size: 0.72rem; color: var(--muted); flex-shrink: 0;
135
+ }
136
+ .doc-bar button {
137
+ border: 1px solid var(--border); background: transparent; color: var(--muted);
138
+ border-radius: 5px; padding: 3px 10px; font-size: 0.68rem; cursor: pointer; letter-spacing: 0.06em;
139
+ font-family: inherit;
140
+ }
141
+ .doc-bar button:hover, .doc-bar button.active { color: var(--text); border-color: var(--accent); }
142
+ .doc-bar button.active { background: var(--accent-soft); color: var(--lavender); }
143
+ .split-wrap { position: absolute; inset: 0; overflow: hidden; }
144
+ .split-wrap img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; }
145
+ .split-divider {
146
+ position: absolute; top: 0; bottom: 0; width: 3px; background: var(--accent);
147
+ cursor: ew-resize; z-index: 5; box-shadow: 0 0 8px rgba(147,52,233,0.6);
148
+ }
149
+ .split-divider::after {
150
+ content: "◂ ▸"; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%);
151
+ background: var(--accent); color: white; border-radius: 999px; padding: 4px 7px;
152
+ font-size: 0.6rem; white-space: nowrap;
153
+ }
154
+ .history-strip {
155
+ display: flex; gap: 8px; padding: 8px 12px; overflow-x: auto; flex-shrink: 0;
156
+ background: var(--panel); border-top: 1px solid var(--hairline); align-items: center;
157
+ }
158
+ .history-strip .hlabel { font-size: 0.62rem; font-weight: 650; letter-spacing: 0.14em; color: var(--dim); text-transform: uppercase; white-space: nowrap; }
159
+ .history-chip {
160
+ width: 52px; height: 52px; border-radius: 6px; border: 1px solid var(--border);
161
+ overflow: hidden; cursor: pointer; flex-shrink: 0; position: relative;
162
+ }
163
+ .history-chip:hover { border-color: var(--accent); }
164
+ .history-chip img { width: 100%; height: 100%; object-fit: cover; }
165
+ .history-chip .hseed {
166
+ position: absolute; bottom: 0; left: 0; right: 0; background: rgba(0,0,0,0.65);
167
+ color: #ddd; font-size: 0.52rem; padding: 1px 3px; text-align: center;
168
+ }
169
+ body.light .history-chip .hseed { background: rgba(255,255,255,0.78); color: #3f3f46; }
170
+ .panels {
171
+ width: 320px; flex-shrink: 0; display: flex; flex-direction: column; gap: 10px;
172
+ padding: 12px; overflow-y: auto; background: var(--panel); border-left: 1px solid var(--hairline);
173
+ }
174
+ .panel { background: var(--panel2); border: 1px solid var(--border); border-radius: var(--radius); padding: 12px; }
175
+ .panel-title { font-size: 0.62rem; font-weight: 650; letter-spacing: 0.12em; color: var(--dim); text-transform: uppercase; margin-bottom: 10px; cursor: pointer; user-select: none; display: flex; align-items: center; justify-content: space-between; }
176
+ .panel .panel-title::after { content: "▾"; font-size: 0.7rem; color: var(--dim); }
177
+ .panel.collapsed .panel-title::after { content: "▸"; }
178
+ .panel.collapsed .panel-body { display: none; }
179
+ .panel label { display: block; font-size: 0.72rem; font-weight: 550; color: var(--muted); margin: 10px 0 4px; }
180
+ .panel label:first-of-type { margin-top: 0; }
181
+ textarea, input[type="text"], input[type="number"], select {
182
+ width: 100%; background: var(--raised); color: var(--text); border: 1px solid var(--border);
183
+ border-radius: 7px; padding: 8px 10px; font-family: inherit; font-size: 0.83rem; resize: vertical;
184
+ transition: border-color 0.15s, box-shadow 0.15s;
185
+ }
186
+ select { appearance: none; background-image: linear-gradient(45deg, transparent 50%, var(--muted) 50%), linear-gradient(135deg, var(--muted) 50%, transparent 50%); background-position: calc(100% - 16px) 50%, calc(100% - 11px) 50%; background-size: 5px 5px; background-repeat: no-repeat; }
187
+ textarea:focus, input:focus, select:focus { outline: none; border-color: var(--accent2); box-shadow: 0 0 0 3px var(--accent-soft); }
188
+ textarea.code { font-family: "IBM Plex Mono", ui-monospace, monospace; font-size: 0.72rem; }
189
+ textarea[readonly] { color: var(--muted); }
190
+ .row { display: flex; gap: 8px; align-items: center; }
191
+ .row > * { flex: 1; }
192
+ .switch { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; }
193
+ .switch input { display: none; }
194
+ .switch .sw {
195
+ display: inline-block;
196
+ width: 34px; height: 20px; border-radius: 999px; background: var(--raised);
197
+ border: 1px solid var(--border); position: relative; flex-shrink: 0; transition: background 0.18s, border-color 0.18s;
198
+ }
199
+ .switch .sw::after {
200
+ content: ""; position: absolute; top: 2px; left: 2px; width: 14px; height: 14px;
201
+ border-radius: 50%; background: var(--muted); transition: transform 0.18s, background 0.18s;
202
+ }
203
+ .switch input:checked + .sw { background: var(--accent); border-color: var(--accent); }
204
+ .switch input:checked + .sw::after { transform: translateX(14px); background: #fff; }
205
+ .switch .sw-label { font-size: 0.75rem; color: var(--muted); }
206
+ .layer-row {
207
+ display: flex; align-items: center; gap: 10px; padding: 6px 8px;
208
+ border: 1px solid var(--border); border-radius: 6px; margin-top: 6px;
209
+ background: var(--raised);
210
+ }
211
+ .layer-row .thumb {
212
+ width: 40px; height: 40px; border-radius: 4px; object-fit: cover; flex-shrink: 0;
213
+ background: var(--thumb-bg); border: 1px solid var(--border);
214
+ display: flex; align-items: center; justify-content: center;
215
+ color: var(--dim); font-size: 0.65rem; text-align: center;
216
+ }
217
+ .layer-row .thumb img { width: 100%; height: 100%; object-fit: cover; border-radius: 3px; }
218
+ .layer-row .lname { flex: 1; font-size: 0.78rem; color: var(--text); }
219
+ .layer-row .lsub { font-size: 0.62rem; color: var(--dim); display: block; }
220
+ .ref-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-top: 8px; }
221
+ .ref-slot {
222
+ height: 64px; border: 1px dashed var(--border); border-radius: 6px;
223
+ display: flex; align-items: center; justify-content: center; cursor: pointer; overflow: hidden;
224
+ color: var(--dim); font-size: 0.68rem; background: var(--raised); text-align: center;
225
+ }
226
+ .ref-slot:hover { border-color: var(--accent); }
227
+ .ref-slot img { width: 100%; height: 100%; object-fit: cover; }
228
+ .hint { font-size: 0.68rem; color: var(--dim); margin-top: 8px; line-height: 1.4; }
229
+ #examples { display: flex; flex-direction: column; gap: 6px; max-height: 260px; overflow-y: auto; }
230
+ .ex-chip {
231
+ border: 1px solid var(--border); border-radius: 8px; cursor: pointer; flex-shrink: 0;
232
+ background: var(--raised); padding: 7px 10px; text-align: left;
233
+ display: flex; align-items: center; justify-content: space-between; gap: 8px;
234
+ transition: border-color 0.15s; font-family: inherit;
235
+ }
236
+ .ex-chip:hover { border-color: var(--accent); }
237
+ .ex-chip .ex-label { font-size: 0.75rem; color: var(--text); font-weight: 550; }
238
+ .ex-chip .ex-aspect { font-size: 0.62rem; color: var(--lavender); font-family: "IBM Plex Mono", ui-monospace, monospace; }
239
+ #run-btn {
240
+ margin-top: 4px; padding: 12px; border: 1px solid rgba(147,52,233,0.7); border-radius: 8px; cursor: pointer;
241
+ background: var(--accent); color: white; box-shadow: inset 0 1px rgba(255,255,255,0.2);
242
+ font-weight: 600; font-size: 0.9rem; letter-spacing: 0.01em; font-family: inherit;
243
+ transition: filter 0.15s, transform 0.05s;
244
+ }
245
+ #run-btn:hover { filter: brightness(1.12); }
246
+ #run-btn:active { transform: translateY(1px); }
247
+ #run-btn:disabled { opacity: 0.5; cursor: wait; }
248
+ .statusbar {
249
+ display: flex; align-items: center; gap: 16px; padding: 7px 16px; flex-shrink: 0;
250
+ background: var(--panel); border-top: 1px solid var(--hairline);
251
+ font-size: 0.75rem; color: var(--muted);
252
+ }
253
+ .statusbar .pulse { width: 8px; height: 8px; border-radius: 50%; background: #4fd1a5; }
254
+ .statusbar.busy .pulse { background: var(--accent2); animation: pulse 1s infinite alternate; }
255
+ @keyframes pulse { from { opacity: 0.4; } to { opacity: 1; } }
256
+ .foot-links { display: flex; gap: 12px; align-items: center; }
257
+ .foot-links a { color: var(--dim); text-decoration: none; font-size: 0.72rem; font-weight: 500; }
258
+ .foot-links a:hover { color: var(--lavender); }
259
+ #file-input { display: none; }
260
+ @media (max-width: 860px) {
261
+ html, body { height: auto !important; overflow: visible !important; }
262
+ body { display: block; }
263
+ .topbar { flex-wrap: wrap; gap: 8px; padding: 8px 12px; }
264
+ .brand { font-size: 0.88rem; }
265
+ .topbar .ml-badge, .topbar .ml-badge-img { display: none; }
266
+ .main { display: block; height: auto; min-height: 0; }
267
+ .rail {
268
+ flex-direction: row; width: 100%; justify-content: center; gap: 10px;
269
+ padding: 6px 10px; border-right: none; border-bottom: 1px solid var(--hairline);
270
+ }
271
+ .rail button { width: 44px; height: 44px; }
272
+ .viewport { display: block; padding: 10px; overflow: visible; }
273
+ .workflow-view { position: static; height: 78vh; padding: 0 0 10px; }
274
+ .doc-grid { flex-direction: column; align-items: stretch; height: auto; }
275
+ .doc { max-width: 100%; width: 100%; }
276
+ .doc .stage { min-height: 220px; }
277
+ .panels {
278
+ width: 100%; border-left: none; border-top: 1px solid var(--hairline);
279
+ padding: 10px 12px; overflow-y: visible;
280
+ }
281
+ .mode-tabs button { padding: 6px 13px; font-size: 0.8rem; }
282
+ .foot-links { display: none; }
283
+ .statusbar { position: sticky; bottom: 0; }
284
+ }
285
+ </style>
286
+ </head>
287
+ <body>
288
+ <header class="topbar">
289
+ <div class="brand"><img src="https://huggingface.co/spaces/PrunaAI/P-H3-Image/resolve/main/pruna-logo.png" alt="Pruna" />P-H3-Image<span class="studio-badge">Studio</span></div>
290
+ <div class="mode-tabs">
291
+ <button id="mode-generate" class="active">Generate</button>
292
+ <button id="mode-edit">Edit</button>
293
+ <button id="mode-workflow">Workflow</button>
294
+ </div>
295
+ <div class="spacer"></div>
296
+ <a class="ml-badge-img" href="https://hf.co/chat?mode=ml-intern" target="_blank" rel="noopener">
297
+ <img src="https://huggingface.co/datasets/huggingface/badges/resolve/main/built-with-ml-intern-md.svg" alt="Built with ML Intern" />
298
+ </a>
299
+ <a class="ml-cta" href="https://hf.co/chat?mode=ml-intern" target="_blank" rel="noopener">Build your own app here →</a>
300
+ <a class="ml-badge" href="https://huggingface.co/PrunaAI/P-H3-Image" target="_blank" rel="noopener">Model card</a>
301
+ <a class="ml-badge" href="https://www.pruna.ai/" target="_blank" rel="noopener">pruna.ai</a>
302
+ <button type="button" class="theme-toggle" id="theme-toggle" data-mode="dark" aria-label="Switch to light mode" title="Switch to light mode">
303
+ <svg class="theme-icon-sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
304
+ <circle cx="12" cy="12" r="4"></circle>
305
+ <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"></path>
306
+ </svg>
307
+ <svg class="theme-icon-moon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
308
+ <path d="M21 14.5A8.5 8.5 0 1 1 9.5 3 7 7 0 0 0 21 14.5z"></path>
309
+ </svg>
310
+ </button>
311
+ </header>
312
+
313
+ <div class="main">
314
+ <div class="rail">
315
+ <button id="tool-upload" title="Upload an image to edit"><svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg></button>
316
+ <button id="tool-clear-doc" title="Clear document"><svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg></button>
317
+ </div>
318
+
319
+ <div class="viewport">
320
+ <div class="workflow-view" id="workflow-view" hidden>
321
+ <iframe src="/workflow/?ui=canvas" title="Workflow canvas"></iframe>
322
+ </div>
323
+ <div class="doc-grid">
324
+ <figure class="doc" id="doc-before">
325
+ <figcaption id="before-caption">Source</figcaption>
326
+ <div class="stage" id="before-stage">
327
+ <img id="source-img" alt="" hidden />
328
+ <div class="drop-hint" id="source-hint"><b>No source image</b>Use the upload tool or drop a file here</div>
329
+ </div>
330
+ </figure>
331
+ <figure class="doc" id="doc-after">
332
+ <figcaption id="after-caption">Result</figcaption>
333
+ <div class="stage" id="after-stage">
334
+ <img id="result-img" alt="" hidden />
335
+ <div class="split-wrap" id="split-wrap" hidden>
336
+ <img id="split-source" alt="" style="clip-path: inset(0 50% 0 0)" />
337
+ <div class="split-divider" id="split-divider" style="left:50%"></div>
338
+ </div>
339
+ <div class="drop-hint" id="result-hint"><b>Nothing yet</b>Run to see the result</div>
340
+ </div>
341
+ <div class="doc-bar">
342
+ <span id="result-meta">—</span>
343
+ <div class="spacer"></div>
344
+ <button id="split-toggle" hidden>SPLIT</button>
345
+ </div>
346
+ </figure>
347
+ </div>
348
+ <div class="history-strip" id="history-strip"><span class="hlabel">History</span></div>
349
+ </div>
350
+
351
+ <aside class="panels">
352
+ <section class="panel">
353
+ <div class="panel-title">Examples</div>
354
+ <div id="examples"></div>
355
+ </section>
356
+ <section class="panel">
357
+ <div class="panel-title">Prompt</div>
358
+ <textarea id="prompt" rows="6" placeholder="Describe the image…"></textarea>
359
+ </section>
360
+ <section class="panel">
361
+ <div class="panel-title">Composition</div>
362
+ <div id="aspect-row">
363
+ <label for="aspect">Aspect ratio</label>
364
+ <select id="aspect">
365
+ <option>1:1</option>
366
+ <option selected>4:3</option>
367
+ <option>3:4</option>
368
+ <option>3:2</option>
369
+ <option>2:3</option>
370
+ <option>16:9</option>
371
+ <option>9:16</option>
372
+ </select>
373
+ </div>
374
+ <label for="resolution">Resolution</label>
375
+ <select id="resolution"></select>
376
+ <div class="row" style="margin-top:10px">
377
+ <label class="switch"><input type="checkbox" id="upsample" checked /><span class="sw"></span><span class="sw-label">Prompt upsampling</span></label>
378
+ </div>
379
+ </section>
380
+ <section class="panel" id="layers-panel" hidden>
381
+ <div class="panel-title">Layers</div>
382
+ <div class="layer-row" id="layer-source">
383
+ <div class="thumb" id="layer-source-thumb">BG</div>
384
+ <div class="lname">Background<span class="lsub">source image — this one is edited</span></div>
385
+ </div>
386
+ <div class="ref-grid">
387
+ <div class="ref-slot" data-ref="2">+ Ref 2</div>
388
+ <div class="ref-slot" data-ref="3">+ Ref 3</div>
389
+ <div class="ref-slot" data-ref="4">+ Ref 4</div>
390
+ <div class="ref-slot" data-ref="5">+ Ref 5</div>
391
+ <div class="ref-slot" data-ref="6">+ Ref 6</div>
392
+ <div class="ref-slot" data-ref="7">+ Ref 7</div>
393
+ <div class="ref-slot" data-ref="8">+ Ref 8</div>
394
+ </div>
395
+ <div class="hint">Reference extra images in the prompt as &lt;Picture 2&gt; … &lt;Picture 8&gt; (e.g. "put the fox from &lt;Picture 2&gt; on the bench").</div>
396
+ </section>
397
+ <section class="panel">
398
+ <div class="panel-title">Advanced</div>
399
+ <div class="row">
400
+ <div><label for="seed">Seed</label><input type="number" id="seed" value="42" min="0" /></div>
401
+ <label class="switch"><input type="checkbox" id="randomize" checked /><span class="sw"></span><span class="sw-label">Randomize</span></label>
402
+ </div>
403
+ </section>
404
+ <section class="panel">
405
+ <div class="panel-title">Upsampled prompt</div>
406
+ <textarea id="upsampled" class="code" rows="5" readonly placeholder="Filled in after a run with prompt upsampling on."></textarea>
407
+ </section>
408
+ <button id="run-btn">Generate</button>
409
+ </aside>
410
+ </div>
411
+
412
+ <footer class="statusbar" id="statusbar">
413
+ <div class="pulse"></div>
414
+ <span id="status">Idle</span>
415
+ <div class="spacer"></div>
416
+ <span class="foot-links">
417
+ <a href="https://github.com/PrunaAI/pruna" target="_blank" rel="noopener">GitHub</a>
418
+ <a href="https://discord.gg/JFQmtFKCjd" target="_blank" rel="noopener">Discord</a>
419
+ <a href="https://x.com/PrunaAI" target="_blank" rel="noopener">X</a>
420
+ </span>
421
+ <span id="seed-out"></span>
422
+ </footer>
423
+
424
+ <input type="file" id="file-input" accept="image/*" />
425
+
426
+ <script type="module">
427
+ import { client } from "https://cdn.jsdelivr.net/npm/@gradio/client@2.7.1/dist/index.min.js";
428
+
429
+ const $ = (id) => document.getElementById(id);
430
+ const state = { mode: "generate", sourcePath: null, refPaths: {}, app: null };
431
+ for (let i = 2; i <= 8; i++) state.refPaths[i] = null;
432
+ const docState = { source: null, result: null, history: [] };
433
+
434
+ const EXAMPLES = [
435
+ { label: "Negotiation in orbit", aspect: "16:9",
436
+ prompt: "Medium wide shot from a low angle across a long table, on a 35mm lens, with the window and far wall behind the figures. Five people sit in tense negotiation, leaning toward each other. Two humans in worn grey wool suits face three alien delegates. The first alien is tall and thin-limbed, with grey skin, long folded fingers and a robe of coarse woven fiber. The second is squat and heavy, its back plated with pale ridged shell, gripping a stylus in three thick fingers. The third has a dark mantle of fine filaments and wears a harness of dented brass clips. A cracked ceramic jug, scuffed data slates and curled paper printouts sit on the table. Earth fills the large curved window, a band of blue cloud over dark ocean. Ribbed steel girders frame the foreground. Cold sunlight rakes across the table while one amber lamp hangs overhead, casting soft shadows under the chins. Fine dust drifts in the light. Palette of slate, bone, rust and deep teal, natural film color, fine grain, shadows deep with detail kept." },
437
+ { label: "Astronaut in a flooded jungle", aspect: "16:9",
438
+ prompt: "A frame from a feature film: a wide establishing shot from a low angle, with a small astronaut standing waist-deep in a flooded jungle clearing, captured on a large-format digital cinema camera with a 35mm lens.\n\nThe astronaut wears a worn white spacesuit with grey mud on the knees, scuffed gloves, and a cracked visor that reflects the canopy. One hand grips a rusted machete while the other rests on a broken comms pack. The helmet is tilted toward a sound in the trees, caught mid-step as if listening for danger.\n\nBehind the figure, tangled roots and fallen trunks rise out of black water. A pale strangler fig wraps around a torn fragment of a landing hull. Farther back, ferns and mist-shrouded trunks fade into layers of blue-grey haze.\n\nThe light is a low, overcast sky above the canopy, a cold top light with a faint blue-white bounce off the water. A single battery lantern clipped to the pack casts a small warm pool across the suit.\n\nDrifting mist hangs between the trunks, and fine rain dimples the water surface. The palette is restrained: slate blue, steel grey, muted sage green and pale ivory, with film-like color and fine grain." },
439
+ { label: "Knight in a frozen forest", aspect: "3:2",
440
+ prompt: "A photograph by an experienced landscape photographer, shot at eye level from a low position with a 35mm lens at f/2.8, the knight placed in the middle distance on a narrow forest path.\n\nThe knight is a weathered man in his forties, his beard rimmed with frost and his brow tight as he scans the trees. His dented steel plate is dulled with grey scratches, a wool cloak hangs heavy and damp at his shoulders, and his right hand rests loosely on a sword hilt wrapped in worn leather. His breath drifts visibly in the cold air as he walks mid-stride, one boot sinking into the snow.\n\nBehind him, birch and pine trunks are coated in white frost, and fallen branches lie half-buried under drifts. Moonlight comes from high upper left, pale and cool, lifting the frost on the bark and the rim of his pauldron, while the forest floor falls into deep blue shadow where texture remains visible. The palette stays restrained: slate blue, grey-white snow, muted brown leather and tarnished steel, with neutral white balance and fine film grain." },
441
+ { label: "Anime sword duel", aspect: "16:9",
442
+ prompt: "A frame from a Japanese anime television series, hand-drawn cel animation over a painted background, widescreen composition. On a rocky mountaintop in a thunderstorm, a swordsman in a torn dark coat swings a massive broadsword that glows pale blue, its blade mid-arc and his teeth clenched. Opposite him, a slender fighter in a white scarf blurs into motion, leaving streaks of afterimage and a ring of cracked stone. Lightning forks across the sky behind them, rain slants through the frame, and bright white highlights gleam on wet rock." },
443
+ { label: "1970s sci-fi comic", aspect: "3:2",
444
+ prompt: "A gouache and ink illustration in the style of a 1970s European science-fiction comic, filling the whole picture edge to edge. A lone space traveler in a bulky white suit stands on a rocky ledge, helmet visor catching the faint light, gazing up at towering mushroom trees with broad caps and thick pale stalks. A dim violet sky stretches above, with a few pale spores drifting through the air. Flat violet and ochre color with visible brush texture and inked contour lines, shown in a wide landscape view from a low angle." },
445
+ { label: "Linen lookbook", aspect: "2:3",
446
+ prompt: "A lookbook photograph by an experienced fashion photographer: a woman in her late twenties stands full length in a pale sandy-linen dress, a loose sleeveless A-line with a square neckline, a gathered waist and a hem that falls just below the calf. The natural linen creases softly at the hips and lifts slightly as she shifts her weight onto one foot in a light breeze. Her chestnut hair is loosely tied back, she wears simple leather sandals and small gold hoops, and her expression is calm as she looks just past the camera. The location is a whitewashed plaster wall beside a weathered wooden door, with the shadow of a palm frond falling across the plaster. Late-afternoon sunlight from the left gives warm directional light with visible detail in the shadows. Shot at 85mm from a few steps back at standing eye height, shallow depth of field, true white balance, fine grain, restrained palette of cream, sand and sage. No text, no other objects." },
447
+ { label: "Risograph cyclist", aspect: "3:4",
448
+ prompt: "A two-color risograph print on cream paper, the artwork running edge to edge with no border or margin. A cyclist in a hooded jacket and helmet leans into a turn on a bicycle down a wide city avenue, seen from a low side angle. Behind them rise tall apartment blocks with rows of windows, a tram line curving into the distance, and a few parked cars. Only the cyclist, the buildings and the road are shown. The image uses fluorescent pink and deep blue inks, which overprint to a dark purple where they overlap. Visible halftone dots, grainy ink coverage, and slight misregistration between the two passes run across the whole sheet." },
449
+ { label: "Byzantine mosaic", aspect: "3:4",
450
+ prompt: "A Byzantine gold-ground mosaic panel, small glass and stone tesserae set in lime mortar, with the gold tiles catching light unevenly. A lighthouse keeper in a dark blue tunic and short cloak stands at the base of a tall white tower, one hand raised to shield his eyes as he looks out to sea. Behind him a lantern glows with a red-gold flame, and the water below is built in bands of teal and deep blue tesserae, with a small ship on the horizon. The gold ground fills the background, the figures are outlined in dark grey-brown tesserae, and the grout lines are slightly uneven. The mosaic fills the whole image edge to edge, with no frame or border." },
451
+ { label: "Kirchner street at night", aspect: "3:4",
452
+ prompt: "A German Expressionist oil painting on canvas in the manner of Ernst Ludwig Kirchner's Berlin street scenes. A narrow city street at night tilts sharply toward the viewer, its buildings leaning into angular, flattened planes. Gaunt figures in dark coats hurry past a gas lamp whose light is a thick yellow smear dragged across the wet paving. Heavy impasto brushstrokes and visible palette-knife edges, with raw cadmium yellow, cobalt blue and vermilion patches in the lit windows. The paint covers the canvas edge to edge, with no frame or border." },
453
+ ];
454
+
455
+ async function getApp() {
456
+ if (!state.app) state.app = await client(location.origin);
457
+ return state.app;
458
+ }
459
+
460
+ async function uploadFile(file) {
461
+ const form = new FormData();
462
+ form.append("files", file);
463
+ const resp = await fetch("/gradio_api/upload", { method: "POST", body: form });
464
+ if (!resp.ok) throw new Error(`Upload failed (${resp.status})`);
465
+ const paths = await resp.json();
466
+ return Array.isArray(paths) ? paths[0] : paths;
467
+ }
468
+
469
+ function setStatus(text, busy = false) {
470
+ $("status").textContent = text;
471
+ $("statusbar").classList.toggle("busy", busy);
472
+ $("run-btn").disabled = busy;
473
+ }
474
+
475
+ // ---------- theme ----------
476
+ const themeBtn = $("theme-toggle");
477
+ function applyTheme(mode) {
478
+ document.body.classList.toggle("light", mode === "light");
479
+ themeBtn.dataset.mode = mode;
480
+ const label = mode === "dark" ? "Switch to light mode" : "Switch to dark mode";
481
+ themeBtn.setAttribute("aria-label", label);
482
+ themeBtn.setAttribute("title", label);
483
+ try { localStorage.setItem("pruna-theme", mode); } catch (e) {}
484
+ }
485
+ themeBtn.onclick = () => applyTheme(document.body.classList.contains("light") ? "dark" : "light");
486
+ (function initTheme() {
487
+ let mode = "dark";
488
+ try { if (localStorage.getItem("pruna-theme") === "light") mode = "light"; } catch (e) {}
489
+ applyTheme(mode);
490
+ })();
491
+
492
+ function setResolutions(list) {
493
+ const sel = $("resolution");
494
+ const prev = sel.value;
495
+ sel.innerHTML = "";
496
+ for (const r of list) {
497
+ const opt = document.createElement("option");
498
+ opt.value = r;
499
+ opt.textContent = r;
500
+ sel.appendChild(opt);
501
+ }
502
+ sel.value = list.includes(prev) ? prev : "8 MP";
503
+ }
504
+
505
+ function setMode(mode) {
506
+ state.mode = mode;
507
+ for (const m of ["generate", "edit", "workflow"]) $(`mode-${m}`).classList.toggle("active", mode === m);
508
+ const workflow = mode === "workflow";
509
+ $("workflow-view").hidden = !workflow;
510
+ document.querySelector(".doc-grid").style.display = workflow ? "none" : "";
511
+ document.querySelector(".rail").style.display = workflow ? "none" : "";
512
+ document.querySelector(".panels").style.display = workflow ? "none" : "";
513
+ $("history-strip").style.display = workflow ? "none" : "";
514
+ if (!workflow) {
515
+ const edit = mode === "edit";
516
+ $("doc-before").style.display = edit ? "" : "none";
517
+ $("layers-panel").hidden = !edit;
518
+ $("aspect-row").style.display = edit ? "none" : "";
519
+ setResolutions(edit ? ["4 MP", "8 MP"] : ["4 MP", "8 MP", "16 MP"]);
520
+ $("run-btn").textContent = edit ? "Generate Edit" : "Generate";
521
+ $("prompt").placeholder = edit ? "e.g. put the fox from <Picture 2> on the bench" : "Describe the image…";
522
+ }
523
+ }
524
+ $("mode-generate").onclick = () => setMode("generate");
525
+ $("mode-edit").onclick = () => setMode("edit");
526
+ $("mode-workflow").onclick = () => setMode("workflow");
527
+
528
+ // ---------- uploads ----------
529
+ let uploadTarget = "source";
530
+ function pickFile(target) {
531
+ uploadTarget = target;
532
+ $("file-input").click();
533
+ }
534
+ $("tool-upload").onclick = () => { setMode("edit"); pickFile("source"); };
535
+ document.querySelectorAll(".ref-slot").forEach((slot) => {
536
+ slot.onclick = () => pickFile(slot.dataset.ref);
537
+ });
538
+ $("file-input").onchange = async (e) => {
539
+ const file = e.target.files[0];
540
+ e.target.value = "";
541
+ if (!file) return;
542
+ setStatus("Uploading…", true);
543
+ try {
544
+ const path = await uploadFile(file);
545
+ if (uploadTarget === "source") {
546
+ state.sourcePath = path;
547
+ showSource(file);
548
+ } else {
549
+ state.refPaths[uploadTarget] = path;
550
+ const slot = document.querySelector(`.ref-slot[data-ref="${uploadTarget}"]`);
551
+ slot.innerHTML = "";
552
+ const img = document.createElement("img");
553
+ img.src = URL.createObjectURL(file);
554
+ slot.appendChild(img);
555
+ }
556
+ setStatus("Idle");
557
+ } catch (err) {
558
+ setStatus(String(err));
559
+ }
560
+ };
561
+ $("before-stage").addEventListener("dragover", (e) => e.preventDefault());
562
+ $("before-stage").addEventListener("drop", async (e) => {
563
+ e.preventDefault();
564
+ const file = e.dataTransfer.files[0];
565
+ if (!file) return;
566
+ setStatus("Uploading…", true);
567
+ try {
568
+ state.sourcePath = await uploadFile(file);
569
+ showSource(file);
570
+ setStatus("Idle");
571
+ } catch (err) {
572
+ setStatus(String(err));
573
+ }
574
+ });
575
+
576
+ function showSource(file) {
577
+ const img = $("source-img");
578
+ img.src = URL.createObjectURL(file);
579
+ img.hidden = false;
580
+ $("source-hint").style.display = "none";
581
+ docState.source = img.src;
582
+ const st = $("layer-source-thumb");
583
+ st.innerHTML = "";
584
+ const stImg = document.createElement("img");
585
+ stImg.src = img.src;
586
+ st.appendChild(stImg);
587
+ setMode("edit");
588
+ }
589
+
590
+ $("tool-clear-doc").onclick = () => {
591
+ state.sourcePath = null;
592
+ for (let i = 2; i <= 8; i++) state.refPaths[i] = null;
593
+ docState.source = null;
594
+ docState.result = null;
595
+ $("source-img").hidden = true;
596
+ $("source-hint").style.display = "";
597
+ $("result-img").hidden = true;
598
+ $("result-hint").style.display = "";
599
+ $("result-meta").textContent = "—";
600
+ $("seed-out").textContent = "";
601
+ $("upsampled").value = "";
602
+ $("split-toggle").hidden = true;
603
+ $("split-wrap").hidden = true;
604
+ $("layer-source-thumb").textContent = "BG";
605
+ document.querySelectorAll(".ref-slot").forEach((slot) => {
606
+ slot.textContent = `+ Ref ${slot.dataset.ref}`;
607
+ });
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 || "";
618
+ const img = document.createElement("img");
619
+ img.src = h.uri;
620
+ const tag = document.createElement("div");
621
+ tag.className = "hseed";
622
+ tag.textContent = h.seed ?? "";
623
+ chip.appendChild(img);
624
+ chip.appendChild(tag);
625
+ chip.onclick = () => {
626
+ setMode(h.mode || "generate");
627
+ $("prompt").value = h.prompt;
628
+ $("seed").value = h.seed ?? 42;
629
+ $("randomize").checked = false;
630
+ docState.result = h.uri;
631
+ $("result-img").src = h.uri;
632
+ $("result-img").hidden = false;
633
+ $("result-hint").style.display = "none";
634
+ $("split-toggle").hidden = !(h.mode === "edit" && !$("source-img").hidden);
635
+ };
636
+ strip.appendChild(chip);
637
+ });
638
+ }
639
+ function pushHistory(uri, seed, prompt, mode) {
640
+ docState.history.unshift({ uri, seed, prompt, mode });
641
+ if (docState.history.length > 8) docState.history.pop();
642
+ renderHistory();
643
+ }
644
+
645
+ // ---------- before/after split view ----------
646
+ let splitOn = false;
647
+ $("split-toggle").onclick = () => {
648
+ if ($("result-img").hidden) return;
649
+ splitOn = !splitOn;
650
+ $("split-toggle").classList.toggle("active", splitOn);
651
+ $("split-wrap").hidden = !splitOn;
652
+ if (splitOn && !$("source-img").hidden) $("split-source").src = $("source-img").src;
653
+ };
654
+ (function () {
655
+ const divider = $("split-divider");
656
+ let dragging = false;
657
+ divider.addEventListener("pointerdown", (e) => { dragging = true; e.preventDefault(); });
658
+ window.addEventListener("pointermove", (e) => {
659
+ if (!dragging) return;
660
+ const stage = $("after-stage").getBoundingClientRect();
661
+ const pct = Math.min(97, Math.max(3, ((e.clientX - stage.left) / stage.width) * 100));
662
+ divider.style.left = pct + "%";
663
+ $("split-source").style.clipPath = `inset(0 ${100 - pct}% 0 0)`;
664
+ });
665
+ window.addEventListener("pointerup", () => { dragging = false; });
666
+ })();
667
+
668
+ // ---------- zoom ----------
669
+ document.querySelectorAll(".doc figcaption").forEach((caption) => {
670
+ const btn = document.createElement("button");
671
+ btn.className = "zoom-btn";
672
+ btn.textContent = "FIT";
673
+ btn.onclick = () => {
674
+ const img = caption.parentElement.querySelector("img");
675
+ const stage = caption.parentElement.querySelector(".stage");
676
+ const zoomed = img.classList.toggle("zoomed");
677
+ stage.classList.toggle("scrollable", zoomed);
678
+ btn.textContent = zoomed ? "1:1" : "FIT";
679
+ };
680
+ caption.appendChild(btn);
681
+ });
682
+
683
+ // ---------- collapsible panels ----------
684
+ document.querySelectorAll(".panel .panel-title").forEach((title) => {
685
+ const body = document.createElement("div");
686
+ body.className = "panel-body";
687
+ [...title.parentElement.children].forEach((child) => {
688
+ if (child !== title) body.appendChild(child);
689
+ });
690
+ title.parentElement.appendChild(body);
691
+ title.onclick = () => title.parentElement.classList.toggle("collapsed");
692
+ });
693
+
694
+ // ---------- examples ----------
695
+ const exRow = $("examples");
696
+ EXAMPLES.forEach((ex) => {
697
+ const chip = document.createElement("button");
698
+ chip.className = "ex-chip";
699
+ const label = document.createElement("span");
700
+ label.className = "ex-label";
701
+ label.textContent = ex.label;
702
+ const aspect = document.createElement("span");
703
+ aspect.className = "ex-aspect";
704
+ aspect.textContent = ex.aspect;
705
+ chip.appendChild(label);
706
+ chip.appendChild(aspect);
707
+ chip.onclick = () => {
708
+ setMode("generate");
709
+ $("prompt").value = ex.prompt;
710
+ $("aspect").value = ex.aspect;
711
+ setStatus("Example loaded — hit Generate");
712
+ };
713
+ exRow.appendChild(chip);
714
+ });
715
+
716
+ // ---------- result handling ----------
717
+ function unwrap(result) {
718
+ const data = Array.isArray(result?.data) ? result.data[0] : result?.data;
719
+ return data ?? {};
720
+ }
721
+ function showResult(result) {
722
+ const payload = unwrap(result);
723
+ const url = typeof payload.image_data === "string" ? payload.image_data : null;
724
+ if (!url) { setStatus("Run finished but no image came back (see console)."); return false; }
725
+ const img = $("result-img");
726
+ img.src = url;
727
+ img.hidden = false;
728
+ $("result-hint").style.display = "none";
729
+ docState.result = url;
730
+ if (payload.seed != null) $("seed-out").textContent = "seed " + payload.seed;
731
+ if (payload.prompt) $("upsampled").value = payload.prompt;
732
+ $("result-meta").textContent = payload.info || "Done";
733
+ $("split-toggle").hidden = !(state.mode === "edit" && !$("source-img").hidden);
734
+ pushHistory(url, payload.seed, $("prompt").value.trim(), state.mode);
735
+ return true;
736
+ }
737
+
738
+ $("run-btn").onclick = async () => {
739
+ const app = await getApp();
740
+ const prompt = $("prompt").value.trim();
741
+ const seed = parseInt($("seed").value, 10) || 0;
742
+ const randomize = $("randomize").checked;
743
+ const upsample = $("upsample").checked;
744
+ const resolution = $("resolution").value;
745
+ try {
746
+ let result;
747
+ if (state.mode === "edit") {
748
+ if (!state.sourcePath) { setStatus("Upload a source image first."); return; }
749
+ if (!prompt) { setStatus("Describe the edit first."); return; }
750
+ setStatus("Editing…", true);
751
+ result = await app.predict("/edit", {
752
+ source: state.sourcePath,
753
+ instruction: prompt,
754
+ ref2: state.refPaths[2],
755
+ ref3: state.refPaths[3],
756
+ ref4: state.refPaths[4],
757
+ ref5: state.refPaths[5],
758
+ ref6: state.refPaths[6],
759
+ ref7: state.refPaths[7],
760
+ ref8: state.refPaths[8],
761
+ resolution, upsample, seed, randomize,
762
+ });
763
+ } else {
764
+ if (!prompt) { setStatus("Write a prompt first."); return; }
765
+ setStatus(upsample ? "Upsampling the prompt, then rendering…" : "Rendering…", true);
766
+ result = await app.predict("/generate", {
767
+ prompt,
768
+ aspect: $("aspect").value,
769
+ resolution, upsample, seed, randomize,
770
+ });
771
+ }
772
+ if (showResult(result)) setStatus("Done");
773
+ } catch (err) {
774
+ setStatus(err?.message || String(err));
775
+ }
776
+ };
777
+
778
+ setMode("generate");
779
+ </script>
780
+ </body>
781
+ </html>
workflow.json ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "2",
3
+ "name": "P-H3-Image Workflow",
4
+ "references": [
5
+ {
6
+ "id": "ref_source",
7
+ "label": "Source Image",
8
+ "role": "reference",
9
+ "asset_type": "image",
10
+ "inputs": [{"id": "in", "label": "Image", "type": "image"}],
11
+ "outputs": [{"id": "out", "label": "Image", "type": "image"}],
12
+ "x": 40,
13
+ "y": 40,
14
+ "width": 220,
15
+ "height": 130,
16
+ "data": {}
17
+ },
18
+ {
19
+ "id": "ref_edit",
20
+ "label": "Edit Instruction",
21
+ "role": "reference",
22
+ "asset_type": "text",
23
+ "inputs": [{"id": "in", "label": "Text", "type": "text"}],
24
+ "outputs": [{"id": "out", "label": "Text", "type": "text"}],
25
+ "x": 300,
26
+ "y": 40,
27
+ "width": 280,
28
+ "height": 130,
29
+ "data": {"out": "make it night, with warm light glowing in the windows"}
30
+ },
31
+ {
32
+ "id": "ref_edit_2",
33
+ "label": "Second Edit Instruction",
34
+ "role": "reference",
35
+ "asset_type": "text",
36
+ "inputs": [{"id": "in", "label": "Text", "type": "text"}],
37
+ "outputs": [{"id": "out", "label": "Text", "type": "text"}],
38
+ "x": 620,
39
+ "y": 250,
40
+ "width": 280,
41
+ "height": 130,
42
+ "data": {"out": "add a small boat with a lantern on the water"}
43
+ },
44
+ {
45
+ "id": "ref_seed",
46
+ "label": "Seed",
47
+ "role": "reference",
48
+ "asset_type": "text",
49
+ "inputs": [{"id": "in", "label": "Text", "type": "text"}],
50
+ "outputs": [{"id": "out", "label": "Text", "type": "text"}],
51
+ "x": 300,
52
+ "y": 190,
53
+ "width": 130,
54
+ "height": 90,
55
+ "data": {"out": "42"}
56
+ },
57
+ {
58
+ "id": "ref_prompt",
59
+ "label": "Prompt",
60
+ "role": "reference",
61
+ "asset_type": "text",
62
+ "inputs": [{"id": "in", "label": "Text", "type": "text"}],
63
+ "outputs": [{"id": "out", "label": "Text", "type": "text"}],
64
+ "x": 40,
65
+ "y": 460,
66
+ "width": 300,
67
+ "height": 160,
68
+ "data": {"out": "A lighthouse on a cliff at dusk, film still, cold light raking across the rocks, fine grain, restrained palette of slate and amber."}
69
+ },
70
+ {
71
+ "id": "ref_aspect",
72
+ "label": "Aspect Ratio",
73
+ "role": "reference",
74
+ "asset_type": "text",
75
+ "inputs": [{"id": "in", "label": "Text", "type": "text"}],
76
+ "outputs": [{"id": "out", "label": "Text", "type": "text"}],
77
+ "x": 40,
78
+ "y": 640,
79
+ "width": 140,
80
+ "height": 90,
81
+ "data": {"out": "4:3"}
82
+ },
83
+ {
84
+ "id": "ref_resolution",
85
+ "label": "Resolution",
86
+ "role": "reference",
87
+ "asset_type": "text",
88
+ "inputs": [{"id": "in", "label": "Text", "type": "text"}],
89
+ "outputs": [{"id": "out", "label": "Text", "type": "text"}],
90
+ "x": 200,
91
+ "y": 640,
92
+ "width": 140,
93
+ "height": 90,
94
+ "data": {"out": "8 MP"}
95
+ }
96
+ ],
97
+ "operators": [
98
+ {
99
+ "id": "op_edit",
100
+ "label": "P-H3 Edit",
101
+ "role": "operator",
102
+ "kind": "fn",
103
+ "fn": "ph3_edit",
104
+ "inputs": [
105
+ {"id": "image", "label": "Image", "type": "image", "required": true},
106
+ {"id": "prompt", "label": "Edit Instruction", "type": "text", "required": true},
107
+ {"id": "seed", "label": "Seed", "type": "text"}
108
+ ],
109
+ "outputs": [{"id": "out_0", "label": "Image", "type": "image", "output_index": 0}],
110
+ "x": 620,
111
+ "y": 60,
112
+ "width": 230,
113
+ "height": 150,
114
+ "data": {}
115
+ },
116
+ {
117
+ "id": "op_edit_2",
118
+ "label": "P-H3 Edit (chained)",
119
+ "role": "operator",
120
+ "kind": "fn",
121
+ "fn": "ph3_edit",
122
+ "inputs": [
123
+ {"id": "image", "label": "Image", "type": "image", "required": true},
124
+ {"id": "prompt", "label": "Edit Instruction", "type": "text", "required": true},
125
+ {"id": "seed", "label": "Seed", "type": "text"}
126
+ ],
127
+ "outputs": [{"id": "out_0", "label": "Image", "type": "image", "output_index": 0}],
128
+ "x": 960,
129
+ "y": 260,
130
+ "width": 230,
131
+ "height": 150,
132
+ "data": {}
133
+ },
134
+ {
135
+ "id": "op_generate",
136
+ "label": "P-H3 Generate",
137
+ "role": "operator",
138
+ "kind": "fn",
139
+ "fn": "ph3_generate",
140
+ "inputs": [
141
+ {"id": "prompt", "label": "Prompt", "type": "text", "required": true},
142
+ {"id": "aspect", "label": "Aspect Ratio", "type": "text"},
143
+ {"id": "resolution", "label": "Resolution", "type": "text"},
144
+ {"id": "seed", "label": "Seed", "type": "text"}
145
+ ],
146
+ "outputs": [{"id": "out_0", "label": "Image", "type": "image", "output_index": 0}],
147
+ "x": 420,
148
+ "y": 480,
149
+ "width": 230,
150
+ "height": 170,
151
+ "data": {}
152
+ }
153
+ ],
154
+ "subjects": [
155
+ {
156
+ "id": "sub_edited",
157
+ "label": "Edited Image",
158
+ "role": "subject",
159
+ "asset_type": "image",
160
+ "inputs": [{"id": "in", "label": "Image", "type": "image"}],
161
+ "outputs": [{"id": "out", "label": "Image", "type": "image"}],
162
+ "x": 900,
163
+ "y": 70,
164
+ "width": 230,
165
+ "height": 110,
166
+ "data": {}
167
+ },
168
+ {
169
+ "id": "sub_final",
170
+ "label": "Final Image",
171
+ "role": "subject",
172
+ "asset_type": "image",
173
+ "inputs": [{"id": "in", "label": "Image", "type": "image"}],
174
+ "outputs": [{"id": "out", "label": "Image", "type": "image"}],
175
+ "x": 1240,
176
+ "y": 270,
177
+ "width": 230,
178
+ "height": 110,
179
+ "data": {}
180
+ },
181
+ {
182
+ "id": "sub_generated",
183
+ "label": "Generated Image",
184
+ "role": "subject",
185
+ "asset_type": "image",
186
+ "inputs": [{"id": "in", "label": "Image", "type": "image"}],
187
+ "outputs": [{"id": "out", "label": "Image", "type": "image"}],
188
+ "x": 710,
189
+ "y": 490,
190
+ "width": 230,
191
+ "height": 110,
192
+ "data": {}
193
+ }
194
+ ],
195
+ "edges": [
196
+ {"id": "e_source", "from_node_id": "ref_source", "from_port_id": "out", "to_node_id": "op_edit", "to_port_id": "image", "type": "image"},
197
+ {"id": "e_edit", "from_node_id": "ref_edit", "from_port_id": "out", "to_node_id": "op_edit", "to_port_id": "prompt", "type": "text"},
198
+ {"id": "e_seed", "from_node_id": "ref_seed", "from_port_id": "out", "to_node_id": "op_edit", "to_port_id": "seed", "type": "text"},
199
+ {"id": "e_out", "from_node_id": "op_edit", "from_port_id": "out_0", "to_node_id": "sub_edited", "to_port_id": "in", "type": "image"},
200
+ {"id": "e_chain", "from_node_id": "op_edit", "from_port_id": "out_0", "to_node_id": "op_edit_2", "to_port_id": "image", "type": "image"},
201
+ {"id": "e_edit_2", "from_node_id": "ref_edit_2", "from_port_id": "out", "to_node_id": "op_edit_2", "to_port_id": "prompt", "type": "text"},
202
+ {"id": "e_seed_2", "from_node_id": "ref_seed", "from_port_id": "out", "to_node_id": "op_edit_2", "to_port_id": "seed", "type": "text"},
203
+ {"id": "e_out_2", "from_node_id": "op_edit_2", "from_port_id": "out_0", "to_node_id": "sub_final", "to_port_id": "in", "type": "image"},
204
+ {"id": "e_prompt", "from_node_id": "ref_prompt", "from_port_id": "out", "to_node_id": "op_generate", "to_port_id": "prompt", "type": "text"},
205
+ {"id": "e_aspect", "from_node_id": "ref_aspect", "from_port_id": "out", "to_node_id": "op_generate", "to_port_id": "aspect", "type": "text"},
206
+ {"id": "e_resolution", "from_node_id": "ref_resolution", "from_port_id": "out", "to_node_id": "op_generate", "to_port_id": "resolution", "type": "text"},
207
+ {"id": "e_seed_g", "from_node_id": "ref_seed", "from_port_id": "out", "to_node_id": "op_generate", "to_port_id": "seed", "type": "text"},
208
+ {"id": "e_gen", "from_node_id": "op_generate", "from_port_id": "out_0", "to_node_id": "sub_generated", "to_port_id": "in", "type": "image"}
209
+ ]
210
+ }