prithivMLmods commited on
Commit
e0982a5
·
verified ·
1 Parent(s): fecf055

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -39
app.py CHANGED
@@ -1,3 +1,6 @@
 
 
 
1
  import os
2
  import gc
3
  import gradio as gr
@@ -5,10 +8,10 @@ import numpy as np
5
  import random
6
  import spaces
7
  import torch
 
8
  from diffusers import Flux2KleinPipeline, AutoencoderKLFlux2
9
  from PIL import Image
10
  from pathlib import Path
11
- import concurrent.futures
12
  import threading
13
  from typing import Iterable
14
  from gradio.themes import Soft
@@ -115,9 +118,6 @@ pipe_small_decoder = Flux2KleinPipeline.from_pretrained(
115
  )
116
  pipe_small_decoder.enable_model_cpu_offload()
117
 
118
- pipe_lock_standard = threading.Lock()
119
- pipe_lock_small = threading.Lock()
120
-
121
  # ── Helpers ───────────────────────────────────────────────────────────────────
122
 
123
  def update_dimensions_from_image(image_list):
@@ -168,18 +168,18 @@ def parse_input_images(input_images):
168
  return None
169
 
170
 
171
- # ── Per-pipeline worker ───────────────────────────────────────────────────────
172
-
173
- def run_pipeline(pipe, lock, kwargs, seed):
174
- with lock:
175
- gen = torch.Generator(device="cpu").manual_seed(seed)
176
- result = pipe(**kwargs, generator=gen).images[0]
177
- return result
178
 
179
 
180
  # ── Inference ─────────────────────────────────────────────────────────────────
181
 
182
- @spaces.GPU(duration=120)
183
  def infer(
184
  prompt,
185
  input_images=None,
@@ -212,28 +212,47 @@ def infer(
212
  if image_list is not None:
213
  shared_kwargs["image"] = image_list
214
 
215
- progress(0.05, desc="⚡ Launching both pipelines simultaneously...")
 
 
216
 
217
- with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
218
- future_std = executor.submit(run_pipeline, pipe_standard, pipe_lock_standard, shared_kwargs, seed)
219
- future_small = executor.submit(run_pipeline, pipe_small_decoder, pipe_lock_small, shared_kwargs, seed)
220
- concurrent.futures.wait(
221
- [future_std, future_small],
222
- return_when=concurrent.futures.ALL_COMPLETED,
223
- )
 
 
 
 
 
224
 
225
- progress(0.95, desc="✅ Both pipelines done!")
 
226
 
227
- out_standard = future_std.result()
228
- out_small = future_small.result()
 
 
 
 
 
 
 
229
 
230
  gc.collect()
231
  torch.cuda.empty_cache()
232
 
233
- return out_standard, out_small, seed
 
 
 
 
234
 
235
 
236
- @spaces.GPU(duration=120)
237
  def infer_example(images, prompt):
238
  if not images:
239
  images_list = None
@@ -241,8 +260,8 @@ def infer_example(images, prompt):
241
  images_list = [images]
242
  else:
243
  images_list = images
244
-
245
- out_std, out_small, seed_used = infer(
246
  prompt=prompt,
247
  input_images=images_list,
248
  seed=0,
@@ -252,7 +271,7 @@ def infer_example(images, prompt):
252
  num_inference_steps=4,
253
  guidance_scale=1.0,
254
  )
255
- return out_std, out_small, seed_used
256
 
257
 
258
  # ── CSS ───────────────────────────────────────────────────────────────────────
@@ -274,6 +293,16 @@ css = """
274
  display: block;
275
  margin-bottom: 6px;
276
  }
 
 
 
 
 
 
 
 
 
 
277
  """
278
 
279
  # ── UI ────────────────────────────────────────────────────────────────────────
@@ -287,8 +316,8 @@ with gr.Blocks() as demo:
287
  elem_id="main-title",
288
  )
289
  gr.Markdown(
290
- "Compare **FLUX.2-klein-4B** side-by-side with two VAE decoders — generated **simultaneously** from the **same seed**. \n"
291
- "🟦 **Standard VAE** vs 🟩 **Small Decoder VAE** ([FLUX.2-small-decoder](https://huggingface.co/black-forest-labs/FLUX.2-small-decoder)) · [[model](https://huggingface.co/black-forest-labs/FLUX.2-klein-4B)]"
292
  )
293
 
294
  # ── Main two-column row ───────────────────────────────────────────────
@@ -316,11 +345,12 @@ with gr.Blocks() as demo:
316
  # ── Right: outputs ────────────────────────────────────────────────
317
  with gr.Column():
318
  with gr.Row():
 
319
  with gr.Column():
320
  gr.HTML(
321
  '<span class="vae-badge" '
322
  'style="background:#FFE0CC;color:#CC3700;">'
323
- '🟦 Standard VAE</span>'
324
  )
325
  result_standard = gr.Image(
326
  label="Standard VAE",
@@ -329,12 +359,17 @@ with gr.Blocks() as demo:
329
  format="png",
330
  height=280,
331
  )
 
 
 
 
332
 
 
333
  with gr.Column():
334
  gr.HTML(
335
  '<span class="vae-badge" '
336
  'style="background:#FFF0E5;color:#E63E00;">'
337
- '🟩 Small Decoder VAE</span>'
338
  )
339
  result_small = gr.Image(
340
  label="Small Decoder VAE",
@@ -343,8 +378,12 @@ with gr.Blocks() as demo:
343
  format="png",
344
  height=280,
345
  )
 
 
 
 
346
 
347
- with gr.Accordion("Advanced Settings", open=False, visible=False):
348
  seed_output = gr.Number(label="Seed Used", precision=0)
349
  seed = gr.Slider(
350
  label="Seed",
@@ -387,19 +426,20 @@ with gr.Blocks() as demo:
387
  value=1.0,
388
  )
389
 
390
- # ── Standard App-Style Examples ───────────────────────────────────────
391
  gr.Examples(
392
  examples=[
393
  [["examples/1.jpg"], "Change the weather to stormy."],
394
  [["examples/2.jpg"], "Transform the scene into a snowy winter day while preserving the original subject identity, framing, and composition."],
395
  [["examples/3.jpg"], "Relight the image with soft golden sunset lighting while keeping all structures and subject details consistent."],
396
  [["examples/4.jpg"], "Make the texture high-resolution."],
 
397
  ],
398
  inputs=[input_images, prompt],
399
- outputs=[result_standard, result_small, seed_output],
400
  fn=infer_example,
401
  cache_examples=False,
402
- label="Examples"
403
  )
404
 
405
  gr.Markdown(
@@ -428,13 +468,12 @@ with gr.Blocks() as demo:
428
  num_inference_steps,
429
  guidance_scale,
430
  ],
431
- outputs=[result_standard, result_small, seed_output],
432
  )
433
 
434
  if __name__ == "__main__":
435
  demo.queue(max_size=20).launch(
436
- css=css,
437
- theme=orange_red_theme,
438
  ssr_mode=False,
439
  show_error=True,
440
  )
 
1
+ Here's the updated code with sequential generation and individual timing:
2
+
3
+ ```python
4
  import os
5
  import gc
6
  import gradio as gr
 
8
  import random
9
  import spaces
10
  import torch
11
+ import time
12
  from diffusers import Flux2KleinPipeline, AutoencoderKLFlux2
13
  from PIL import Image
14
  from pathlib import Path
 
15
  import threading
16
  from typing import Iterable
17
  from gradio.themes import Soft
 
118
  )
119
  pipe_small_decoder.enable_model_cpu_offload()
120
 
 
 
 
121
  # ── Helpers ───────────────────────────────────────────────────────────────────
122
 
123
  def update_dimensions_from_image(image_list):
 
168
  return None
169
 
170
 
171
+ def format_time(seconds: float) -> str:
172
+ """Format seconds into a human-readable string."""
173
+ if seconds < 60:
174
+ return f"{seconds:.2f}s"
175
+ minutes = int(seconds // 60)
176
+ secs = seconds % 60
177
+ return f"{minutes}m {secs:.2f}s"
178
 
179
 
180
  # ── Inference ─────────────────────────────────────────────────────────────────
181
 
182
+ @spaces.GPU(duration=240)
183
  def infer(
184
  prompt,
185
  input_images=None,
 
212
  if image_list is not None:
213
  shared_kwargs["image"] = image_list
214
 
215
+ # ── Step 1: Standard VAE ──────────────────────────────────────────────────
216
+ progress(0.05, desc="🟦 Running Standard VAE generation...")
217
+ print("Starting Standard VAE generation...")
218
 
219
+ t0_std = time.perf_counter()
220
+ gen_std = torch.Generator(device="cpu").manual_seed(seed)
221
+ out_standard = pipe_standard(**shared_kwargs, generator=gen_std).images[0]
222
+ t1_std = time.perf_counter()
223
+ time_std = t1_std - t0_std
224
+ time_std_str = format_time(time_std)
225
+
226
+ print(f"Standard VAE done in {time_std_str}")
227
+ progress(0.55, desc=f"🟦 Standard VAE done in {time_std_str} — now running 🟩 Small Decoder VAE...")
228
+
229
+ gc.collect()
230
+ torch.cuda.empty_cache()
231
 
232
+ # ── Step 2: Small Decoder VAE ─────────────────────────────────────────────
233
+ print("Starting Small Decoder VAE generation...")
234
 
235
+ t0_small = time.perf_counter()
236
+ gen_small = torch.Generator(device="cpu").manual_seed(seed)
237
+ out_small = pipe_small_decoder(**shared_kwargs, generator=gen_small).images[0]
238
+ t1_small = time.perf_counter()
239
+ time_small = t1_small - t0_small
240
+ time_small_str = format_time(time_small)
241
+
242
+ print(f"Small Decoder VAE done in {time_small_str}")
243
+ progress(1.0, desc=f"✅ Both done! Standard: {time_std_str} | Small Decoder: {time_small_str}")
244
 
245
  gc.collect()
246
  torch.cuda.empty_cache()
247
 
248
+ # ── Build timing label strings ────────────────────────────────────────────
249
+ label_std = f"🟦 Standard VAE — ⏱ {time_std_str}"
250
+ label_small = f"🟩 Small Decoder VAE — ⏱ {time_small_str}"
251
+
252
+ return out_standard, out_small, seed, label_std, label_small
253
 
254
 
255
+ @spaces.GPU(duration=240)
256
  def infer_example(images, prompt):
257
  if not images:
258
  images_list = None
 
260
  images_list = [images]
261
  else:
262
  images_list = images
263
+
264
+ out_std, out_small, seed_used, label_std, label_small = infer(
265
  prompt=prompt,
266
  input_images=images_list,
267
  seed=0,
 
271
  num_inference_steps=4,
272
  guidance_scale=1.0,
273
  )
274
+ return out_std, out_small, seed_used, label_std, label_small
275
 
276
 
277
  # ── CSS ───────────────────────────────────────────────────────────────────────
 
293
  display: block;
294
  margin-bottom: 6px;
295
  }
296
+ .timing-label {
297
+ text-align: center;
298
+ font-size: 0.92em;
299
+ font-weight: 600;
300
+ color: #555;
301
+ margin-top: 4px;
302
+ padding: 3px 10px;
303
+ border-radius: 12px;
304
+ background: rgba(255,255,255,0.6);
305
+ }
306
  """
307
 
308
  # ── UI ────────────────────────────────────────────────────────────────────────
 
316
  elem_id="main-title",
317
  )
318
  gr.Markdown(
319
+ "Compare **FLUX.2-klein-4B** side-by-side with two VAE decoders — generated **sequentially** from the **same seed**. \n"
320
+ "🟦 **Standard VAE** (generated first) → 🟩 **Small Decoder VAE** ([FLUX.2-small-decoder](https://huggingface.co/black-forest-labs/FLUX.2-small-decoder)) · [[model](https://huggingface.co/black-forest-labs/FLUX.2-klein-4B)]"
321
  )
322
 
323
  # ── Main two-column row ───────────────────────────────────────────────
 
345
  # ── Right: outputs ────────────────────────────────────────────────
346
  with gr.Column():
347
  with gr.Row():
348
+ # Standard VAE output
349
  with gr.Column():
350
  gr.HTML(
351
  '<span class="vae-badge" '
352
  'style="background:#FFE0CC;color:#CC3700;">'
353
+ '🟦 Standard VAE &nbsp;·&nbsp; Generated First</span>'
354
  )
355
  result_standard = gr.Image(
356
  label="Standard VAE",
 
359
  format="png",
360
  height=280,
361
  )
362
+ timing_standard = gr.Markdown(
363
+ value="⏱ Waiting...",
364
+ elem_classes=["timing-label"],
365
+ )
366
 
367
+ # Small Decoder VAE output
368
  with gr.Column():
369
  gr.HTML(
370
  '<span class="vae-badge" '
371
  'style="background:#FFF0E5;color:#E63E00;">'
372
+ '🟩 Small Decoder VAE &nbsp;·&nbsp; Generated Second</span>'
373
  )
374
  result_small = gr.Image(
375
  label="Small Decoder VAE",
 
378
  format="png",
379
  height=280,
380
  )
381
+ timing_small = gr.Markdown(
382
+ value="⏱ Waiting...",
383
+ elem_classes=["timing-label"],
384
+ )
385
 
386
+ with gr.Accordion("Advanced Settings", open=False):
387
  seed_output = gr.Number(label="Seed Used", precision=0)
388
  seed = gr.Slider(
389
  label="Seed",
 
426
  value=1.0,
427
  )
428
 
429
+ # ── Examples ──────────────────────────────────────────────────────────
430
  gr.Examples(
431
  examples=[
432
  [["examples/1.jpg"], "Change the weather to stormy."],
433
  [["examples/2.jpg"], "Transform the scene into a snowy winter day while preserving the original subject identity, framing, and composition."],
434
  [["examples/3.jpg"], "Relight the image with soft golden sunset lighting while keeping all structures and subject details consistent."],
435
  [["examples/4.jpg"], "Make the texture high-resolution."],
436
+ [None, "A beautiful cyberpunk cityscape at night, neon lights, highly detailed."],
437
  ],
438
  inputs=[input_images, prompt],
439
+ outputs=[result_standard, result_small, seed_output, timing_standard, timing_small],
440
  fn=infer_example,
441
  cache_examples=False,
442
+ label="Examples",
443
  )
444
 
445
  gr.Markdown(
 
468
  num_inference_steps,
469
  guidance_scale,
470
  ],
471
+ outputs=[result_standard, result_small, seed_output, timing_standard, timing_small],
472
  )
473
 
474
  if __name__ == "__main__":
475
  demo.queue(max_size=20).launch(
476
+ css=css, theme=orange_red_theme,
 
477
  ssr_mode=False,
478
  show_error=True,
479
  )