prithivMLmods commited on
Commit
a5410ca
·
verified ·
1 Parent(s): 207c80b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +531 -529
app.py CHANGED
@@ -1,530 +1,532 @@
1
- import spaces
2
- import gradio as gr
3
- import torch
4
- from PIL import Image
5
- from diffusers import DiffusionPipeline, AutoencoderTiny, AutoencoderKL
6
- import random
7
- import uuid
8
- from typing import Tuple, Union, List, Optional, Any, Dict
9
- import numpy as np
10
- import time
11
- import zipfile
12
- from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
13
-
14
- # Description for the app
15
- DESCRIPTION = """## flux comparator hpc/."""
16
-
17
- # Helper functions
18
- def save_image(img):
19
- unique_name = str(uuid.uuid4()) + ".png"
20
- img.save(unique_name)
21
- return unique_name
22
-
23
- def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
24
- if randomize_seed:
25
- seed = random.randint(0, MAX_SEED)
26
- return seed
27
-
28
- MAX_SEED = np.iinfo(np.int32).max
29
- MAX_IMAGE_SIZE = 2048
30
-
31
- # Load pipelines for both models
32
- # Flux.1-dev-realism
33
- base_model_dev = "black-forest-labs/FLUX.1-dev"
34
- pipe_dev = DiffusionPipeline.from_pretrained(base_model_dev, torch_dtype=torch.bfloat16)
35
- lora_repo = "strangerzonehf/Flux-Super-Realism-LoRA"
36
- trigger_word = "Super Realism"
37
- pipe_dev.load_lora_weights(lora_repo)
38
- pipe_dev.to("cuda")
39
-
40
- # Flux.1-krea
41
- dtype = torch.bfloat16
42
- device = "cuda" if torch.cuda.is_available() else "cpu"
43
- taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device)
44
- good_vae = AutoencoderKL.from_pretrained("prithivMLmods/Flux.1-Krea-Merged-Dev", subfolder="vae", torch_dtype=dtype).to(device)
45
- pipe_krea = DiffusionPipeline.from_pretrained("prithivMLmods/Flux.1-Krea-Merged-Dev", torch_dtype=dtype, vae=taef1).to(device)
46
-
47
- # Define the flux_pipe_call_that_returns_an_iterable_of_images for flux.1-krea
48
- @torch.inference_mode()
49
- def flux_pipe_call_that_returns_an_iterable_of_images(
50
- self,
51
- prompt: Union[str, List[str]] = None,
52
- prompt_2: Optional[Union[str, List[str]]] = None,
53
- height: Optional[int] = None,
54
- width: Optional[int] = None,
55
- num_inference_steps: int = 28,
56
- timesteps: List[int] = None,
57
- guidance_scale: float = 3.5,
58
- num_images_per_prompt: Optional[int] = 1,
59
- generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
60
- latents: Optional[torch.FloatTensor] = None,
61
- prompt_embeds: Optional[torch.FloatTensor] = None,
62
- pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
63
- output_type: Optional[str] = "pil",
64
- return_dict: bool = True,
65
- joint_attention_kwargs: Optional[Dict[str, Any]] = None,
66
- max_sequence_length: int = 512,
67
- good_vae: Optional[Any] = None,
68
- ):
69
- height = height or self.default_sample_size * self.vae_scale_factor
70
- width = width or self.default_sample_size * self.vae_scale_factor
71
-
72
- self.check_inputs(
73
- prompt,
74
- prompt_2,
75
- height,
76
- width,
77
- prompt_embeds=prompt_embeds,
78
- pooled_prompt_embeds=pooled_prompt_embeds,
79
- max_sequence_length=max_sequence_length,
80
- )
81
-
82
- self._guidance_scale = guidance_scale
83
- self._joint_attention_kwargs = joint_attention_kwargs
84
- self._interrupt = False
85
-
86
- batch_size = 1 if isinstance(prompt, str) else len(prompt)
87
- device = self._execution_device
88
-
89
- lora_scale = joint_attention_kwargs.get("scale", None) if joint_attention_kwargs is not None else None
90
- prompt_embeds, pooled_prompt_embeds, text_ids = self.encode_prompt(
91
- prompt=prompt,
92
- prompt_2=prompt_2,
93
- prompt_embeds=prompt_embeds,
94
- pooled_prompt_embeds=pooled_prompt_embeds,
95
- device=device,
96
- num_images_per_prompt=num_images_per_prompt,
97
- max_sequence_length=max_sequence_length,
98
- lora_scale=lora_scale,
99
- )
100
-
101
- num_channels_latents = self.transformer.config.in_channels // 4
102
- latents, latent_image_ids = self.prepare_latents(
103
- batch_size * num_images_per_prompt,
104
- num_channels_latents,
105
- height,
106
- width,
107
- prompt_embeds.dtype,
108
- device,
109
- generator,
110
- latents,
111
- )
112
-
113
- sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
114
- image_seq_len = latents.shape[1]
115
- mu = calculate_shift(
116
- image_seq_len,
117
- self.scheduler.config.base_image_seq_len,
118
- self.scheduler.config.max_image_seq_len,
119
- self.scheduler.config.base_shift,
120
- self.scheduler.config.max_shift,
121
- )
122
- timesteps, num_inference_steps = retrieve_timesteps(
123
- self.scheduler,
124
- num_inference_steps,
125
- device,
126
- timesteps,
127
- sigmas,
128
- mu=mu,
129
- )
130
- self._num_timesteps = len(timesteps)
131
-
132
- guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32).expand(latents.shape[0]) if self.transformer.config.guidance_embeds else None
133
-
134
- for i, t in enumerate(timesteps):
135
- if self.interrupt:
136
- continue
137
-
138
- timestep = t.expand(latents.shape[0]).to(latents.dtype)
139
-
140
- noise_pred = self.transformer(
141
- hidden_states=latents,
142
- timestep=timestep / 1000,
143
- guidance=guidance,
144
- pooled_projections=pooled_prompt_embeds,
145
- encoder_hidden_states=prompt_embeds,
146
- txt_ids=text_ids,
147
- img_ids=latent_image_ids,
148
- joint_attention_kwargs=self.joint_attention_kwargs,
149
- return_dict=False,
150
- )[0]
151
-
152
- latents_for_image = self._unpack_latents(latents, height, width, self.vae_scale_factor)
153
- latents_for_image = (latents_for_image / self.vae.config.scaling_factor) + self.vae.config.shift_factor
154
- image = self.vae.decode(latents_for_image, return_dict=False)[0]
155
- yield self.image_processor.postprocess(image, output_type=output_type)[0]
156
-
157
- latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
158
- torch.cuda.empty_cache()
159
-
160
- latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
161
- latents = (latents / good_vae.config.scaling_factor) + good_vae.config.shift_factor
162
- image = good_vae.decode(latents, return_dict=False)[0]
163
- self.maybe_free_model_hooks()
164
- torch.cuda.empty_cache()
165
- yield self.image_processor.postprocess(image, output_type=output_type)[0]
166
-
167
- pipe_krea.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe_krea)
168
-
169
- # Helper functions for flux.1-krea
170
- def calculate_shift(
171
- image_seq_len,
172
- base_seq_len: int = 256,
173
- max_seq_len: int = 4096,
174
- base_shift: float = 0.5,
175
- max_shift: float = 1.16,
176
- ):
177
- m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
178
- b = base_shift - m * base_seq_len
179
- mu = image_seq_len * m + b
180
- return mu
181
-
182
- def retrieve_timesteps(
183
- scheduler,
184
- num_inference_steps: Optional[int] = None,
185
- device: Optional[Union[str, torch.device]] = None,
186
- timesteps: Optional[List[int]] = None,
187
- sigmas: Optional[List[float]] = None,
188
- **kwargs,
189
- ):
190
- if timesteps is not None and sigmas is not None:
191
- raise ValueError("Only one of `timesteps` or `sigmas` can be passed.")
192
- if timesteps is not None:
193
- scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
194
- timesteps = scheduler.timesteps
195
- num_inference_steps = len(timesteps)
196
- elif sigmas is not None:
197
- scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
198
- timesteps = scheduler.timesteps
199
- num_inference_steps = len(timesteps)
200
- else:
201
- scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
202
- timesteps = scheduler.timesteps
203
- return timesteps, num_inference_steps
204
-
205
- # Styles for flux.1-dev-realism
206
- style_list = [
207
- {"name": "3840 x 2160", "prompt": "hyper-realistic 8K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic", "negative_prompt": ""},
208
- {"name": "2560 x 1440", "prompt": "hyper-realistic 4K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic", "negative_prompt": ""},
209
- {"name": "HD+", "prompt": "hyper-realistic 2K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic", "negative_prompt": ""},
210
- {"name": "Style Zero", "prompt": "{prompt}", "negative_prompt": ""},
211
- ]
212
-
213
- styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}
214
- DEFAULT_STYLE_NAME = "3840 x 2160"
215
- STYLE_NAMES = list(styles.keys())
216
-
217
- def apply_style(style_name: str, positive: str) -> Tuple[str, str]:
218
- p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
219
- return p.replace("{prompt}", positive), n
220
-
221
- # Generation function for flux.1-dev-realism
222
- @spaces.GPU
223
- def generate_dev(
224
- prompt: str,
225
- negative_prompt: str = "",
226
- use_negative_prompt: bool = False,
227
- seed: int = 0,
228
- width: int = 1024,
229
- height: int = 1024,
230
- guidance_scale: float = 3,
231
- randomize_seed: bool = False,
232
- style_name: str = DEFAULT_STYLE_NAME,
233
- num_inference_steps: int = 30,
234
- num_images: int = 1,
235
- zip_images: bool = False,
236
- progress=gr.Progress(track_tqdm=True),
237
- ):
238
- positive_prompt, style_negative_prompt = apply_style(style_name, prompt)
239
-
240
- if use_negative_prompt:
241
- final_negative_prompt = style_negative_prompt + " " + negative_prompt
242
- else:
243
- final_negative_prompt = style_negative_prompt
244
-
245
- final_negative_prompt = final_negative_prompt.strip()
246
-
247
- if trigger_word:
248
- positive_prompt = f"{trigger_word} {positive_prompt}"
249
-
250
- seed = int(randomize_seed_fn(seed, randomize_seed))
251
- generator = torch.Generator(device="cuda").manual_seed(seed)
252
-
253
- start_time = time.time()
254
-
255
- images = pipe_dev(
256
- prompt=positive_prompt,
257
- negative_prompt=final_negative_prompt if final_negative_prompt else None,
258
- width=width,
259
- height=height,
260
- guidance_scale=guidance_scale,
261
- num_inference_steps=num_inference_steps,
262
- num_images_per_prompt=num_images,
263
- generator=generator,
264
- output_type="pil",
265
- ).images
266
-
267
- end_time = time.time()
268
- duration = end_time - start_time
269
-
270
- image_paths = [save_image(img) for img in images]
271
-
272
- zip_path = None
273
- if zip_images:
274
- zip_name = str(uuid.uuid4()) + ".zip"
275
- with zipfile.ZipFile(zip_name, 'w') as zipf:
276
- for i, img_path in enumerate(image_paths):
277
- zipf.write(img_path, arcname=f"Img_{i}.png")
278
- zip_path = zip_name
279
-
280
- return image_paths, seed, f"{duration:.2f}", zip_path
281
-
282
- # Generation function for flux.1-krea
283
- @spaces.GPU
284
- def generate_krea(
285
- prompt: str,
286
- seed: int = 0,
287
- width: int = 1024,
288
- height: int = 1024,
289
- guidance_scale: float = 4.5,
290
- randomize_seed: bool = False,
291
- num_inference_steps: int = 28,
292
- num_images: int = 1,
293
- zip_images: bool = False,
294
- progress=gr.Progress(track_tqdm=True),
295
- ):
296
- if randomize_seed:
297
- seed = random.randint(0, MAX_SEED)
298
- generator = torch.Generator().manual_seed(seed)
299
-
300
- start_time = time.time()
301
-
302
- images = []
303
- for _ in range(num_images):
304
- final_img = list(pipe_krea.flux_pipe_call_that_returns_an_iterable_of_images(
305
- prompt=prompt,
306
- guidance_scale=guidance_scale,
307
- num_inference_steps=num_inference_steps,
308
- width=width,
309
- height=height,
310
- generator=generator,
311
- output_type="pil",
312
- good_vae=good_vae,
313
- ))[-1] # Take the final image only
314
- images.append(final_img)
315
-
316
- end_time = time.time()
317
- duration = end_time - start_time
318
-
319
- image_paths = [save_image(img) for img in images]
320
-
321
- zip_path = None
322
- if zip_images:
323
- zip_name = str(uuid.uuid4()) + ".zip"
324
- with zipfile.ZipFile(zip_name, 'w') as zipf:
325
- for i, img_path in enumerate(image_paths):
326
- zipf.write(img_path, arcname=f"Img_{i}.png")
327
- zip_path = zip_name
328
-
329
- return image_paths, seed, f"{duration:.2f}", zip_path
330
-
331
- # Main generation function to handle model choice
332
- @spaces.GPU
333
- def generate(
334
- model_choice: str,
335
- prompt: str,
336
- negative_prompt: str = "",
337
- use_negative_prompt: bool = False,
338
- seed: int = 0,
339
- width: int = 1024,
340
- height: int = 1024,
341
- guidance_scale: float = 3,
342
- randomize_seed: bool = False,
343
- style_name: str = DEFAULT_STYLE_NAME,
344
- num_inference_steps: int = 30,
345
- num_images: int = 1,
346
- zip_images: bool = False,
347
- progress=gr.Progress(track_tqdm=True),
348
- ):
349
- if model_choice == "flux.1-dev-realism":
350
- return generate_dev(
351
- prompt=prompt,
352
- negative_prompt=negative_prompt,
353
- use_negative_prompt=use_negative_prompt,
354
- seed=seed,
355
- width=width,
356
- height=height,
357
- guidance_scale=guidance_scale,
358
- randomize_seed=randomize_seed,
359
- style_name=style_name,
360
- num_inference_steps=num_inference_steps,
361
- num_images=num_images,
362
- zip_images=zip_images,
363
- progress=progress,
364
- )
365
- elif model_choice == "flux.1-krea-merged-dev":
366
- return generate_krea(
367
- prompt=prompt,
368
- seed=seed,
369
- width=width,
370
- height=height,
371
- guidance_scale=guidance_scale,
372
- randomize_seed=randomize_seed,
373
- num_inference_steps=num_inference_steps,
374
- num_images=num_images,
375
- zip_images=zip_images,
376
- progress=progress,
377
- )
378
- else:
379
- raise ValueError("Invalid model choice")
380
-
381
- # Examples (tailored for flux.1-dev-realism)
382
- examples = [
383
- "An attractive young woman with blue eyes lying face down on the bed, in the style of animated gifs, light white and light amber, jagged edges, the snapshot aesthetic, timeless beauty, goosepunk, sunrays shine upon it --no freckles --chaos 65 --ar 1:2 --profile yruxpc2 --stylize 750 --v 6.1",
384
- "Headshot of handsome young man, wearing dark gray sweater with buttons and big shawl collar, brown hair and short beard, serious look on his face, black background, soft studio lighting, portrait photography --ar 85:128 --v 6.0 --style",
385
- "Purple Dreamy, a medium-angle shot of a young woman with long brown hair, wearing a pair of eye-level glasses, stands in front of a backdrop of purple and white lights.",
386
- "High-resolution photograph, woman, UHD, photorealistic, shot on a Sony A7III --chaos 20 --ar 1:2 --style raw --stylize 250"
387
- ]
388
-
389
- css = '''
390
- .gradio-container {
391
- max-width: 590px !important;
392
- margin: 0 auto !important;
393
- }
394
- h1 {
395
- text-align: center;
396
- }
397
- footer {
398
- visibility: hidden;
399
- }
400
- '''
401
-
402
- # Gradio interface
403
- with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
404
- gr.Markdown(DESCRIPTION)
405
- with gr.Row():
406
- prompt = gr.Text(
407
- label="Prompt",
408
- show_label=False,
409
- max_lines=1,
410
- placeholder="Enter your prompt",
411
- container=False,
412
- )
413
- run_button = gr.Button("Run", scale=0, variant="primary")
414
- result = gr.Gallery(label="Result", columns=1, show_label=False, preview=True)
415
-
416
- with gr.Row():
417
- # Model choice radio button above additional options
418
- model_choice = gr.Radio(
419
- choices=["flux.1-krea-merged-dev", "flux.1-dev-realism"],
420
- label="Select Model",
421
- value="flux.1-krea-merged-dev"
422
- )
423
-
424
- with gr.Accordion("Additional Options", open=False):
425
- style_selection = gr.Dropdown(
426
- label="Quality Style (for flux.1-dev-realism only)",
427
- choices=STYLE_NAMES,
428
- value=DEFAULT_STYLE_NAME,
429
- interactive=True,
430
- )
431
- use_negative_prompt = gr.Checkbox(label="Use negative prompt (for flux.1-dev-realism only)", value=False)
432
- negative_prompt = gr.Text(
433
- label="Negative prompt",
434
- max_lines=1,
435
- placeholder="Enter a negative prompt",
436
- visible=False,
437
- )
438
- seed = gr.Slider(
439
- label="Seed",
440
- minimum=0,
441
- maximum=MAX_SEED,
442
- step=1,
443
- value=0,
444
- )
445
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
446
- with gr.Row():
447
- width = gr.Slider(
448
- label="Width",
449
- minimum=512,
450
- maximum=2048,
451
- step=64,
452
- value=1024,
453
- )
454
- height = gr.Slider(
455
- label="Height",
456
- minimum=512,
457
- maximum=2048,
458
- step=64,
459
- value=1024,
460
- )
461
- guidance_scale = gr.Slider(
462
- label="Guidance Scale",
463
- minimum=0.1,
464
- maximum=20.0,
465
- step=0.1,
466
- value=3.5,
467
- )
468
- num_inference_steps = gr.Slider(
469
- label="Number of inference steps",
470
- minimum=1,
471
- maximum=40,
472
- step=1,
473
- value=28,
474
- )
475
- num_images = gr.Slider(
476
- label="Number of images",
477
- minimum=1,
478
- maximum=5,
479
- step=1,
480
- value=1,
481
- )
482
- zip_images = gr.Checkbox(label="Zip generated images", value=False)
483
-
484
- gr.Markdown("### Output Information")
485
- seed_display = gr.Textbox(label="Seed used", interactive=False)
486
- generation_time = gr.Textbox(label="Generation time (seconds)", interactive=False)
487
- zip_file = gr.File(label="Download ZIP")
488
-
489
- gr.Examples(
490
- examples=examples,
491
- inputs=prompt,
492
- outputs=[result, seed_display, generation_time, zip_file],
493
- fn=generate,
494
- cache_examples=False,
495
- )
496
-
497
- use_negative_prompt.change(
498
- fn=lambda x: gr.update(visible=x),
499
- inputs=use_negative_prompt,
500
- outputs=negative_prompt,
501
- api_name=False,
502
- )
503
-
504
- gr.on(
505
- triggers=[
506
- prompt.submit,
507
- run_button.click,
508
- ],
509
- fn=generate,
510
- inputs=[
511
- model_choice,
512
- prompt,
513
- negative_prompt,
514
- use_negative_prompt,
515
- seed,
516
- width,
517
- height,
518
- guidance_scale,
519
- randomize_seed,
520
- style_selection,
521
- num_inference_steps,
522
- num_images,
523
- zip_images,
524
- ],
525
- outputs=[result, seed_display, generation_time, zip_file],
526
- api_name="run",
527
- )
528
-
529
- if __name__ == "__main__":
 
 
530
  demo.queue(max_size=30).launch(mcp_server=True, ssr_mode=False, show_error=True)
 
1
+ import spaces
2
+ import gradio as gr
3
+ import torch
4
+ from PIL import Image
5
+ from diffusers import DiffusionPipeline, AutoencoderTiny, AutoencoderKL
6
+ import random
7
+ import uuid
8
+ from typing import Tuple, Union, List, Optional, Any, Dict
9
+ import numpy as np
10
+ import time
11
+ import zipfile
12
+ from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
13
+
14
+ # Description for the app
15
+ DESCRIPTION = """## flux comparator hpc/."""
16
+
17
+ # Helper functions
18
+ def save_image(img):
19
+ unique_name = str(uuid.uuid4()) + ".png"
20
+ img.save(unique_name)
21
+ return unique_name
22
+
23
+ def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
24
+ if randomize_seed:
25
+ seed = random.randint(0, MAX_SEED)
26
+ return seed
27
+
28
+ MAX_SEED = np.iinfo(np.int32).max
29
+ MAX_IMAGE_SIZE = 2048
30
+
31
+ # Load pipelines for both models
32
+ # Flux.1-dev-realism
33
+ base_model_dev = "prithivMLmods/Flux.1-Merged" # Merge of (black-forest-labs/FLUX.1-dev + black-forest-labs/FLUX.1-schnell)
34
+ pipe_dev = DiffusionPipeline.from_pretrained(base_model_dev, torch_dtype=torch.bfloat16)
35
+ lora_repo = "strangerzonehf/Flux-Super-Realism-LoRA"
36
+ trigger_word = "Super Realism"
37
+ pipe_dev.load_lora_weights(lora_repo)
38
+ pipe_dev.to("cuda")
39
+
40
+ # Flux.1-krea
41
+ dtype = torch.bfloat16
42
+ device = "cuda" if torch.cuda.is_available() else "cpu"
43
+ taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device)
44
+ # Merge of (black-forest-labs/FLUX.1-dev + https://huggingface.co/black-forest-labs/FLUX.1-Krea-dev)
45
+ good_vae = AutoencoderKL.from_pretrained("prithivMLmods/Flux.1-Krea-Merged-Dev", subfolder="vae", torch_dtype=dtype).to(device)
46
+ pipe_krea = DiffusionPipeline.from_pretrained("prithivMLmods/Flux.1-Krea-Merged-Dev", torch_dtype=dtype, vae=taef1).to(device)
47
+
48
+ # Define the flux_pipe_call_that_returns_an_iterable_of_images for flux.1-krea
49
+ @torch.inference_mode()
50
+ def flux_pipe_call_that_returns_an_iterable_of_images(
51
+ self,
52
+ prompt: Union[str, List[str]] = None,
53
+ prompt_2: Optional[Union[str, List[str]]] = None,
54
+ height: Optional[int] = None,
55
+ width: Optional[int] = None,
56
+ num_inference_steps: int = 28,
57
+ timesteps: List[int] = None,
58
+ guidance_scale: float = 3.5,
59
+ num_images_per_prompt: Optional[int] = 1,
60
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
61
+ latents: Optional[torch.FloatTensor] = None,
62
+ prompt_embeds: Optional[torch.FloatTensor] = None,
63
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
64
+ output_type: Optional[str] = "pil",
65
+ return_dict: bool = True,
66
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
67
+ max_sequence_length: int = 512,
68
+ good_vae: Optional[Any] = None,
69
+ ):
70
+ height = height or self.default_sample_size * self.vae_scale_factor
71
+ width = width or self.default_sample_size * self.vae_scale_factor
72
+
73
+ self.check_inputs(
74
+ prompt,
75
+ prompt_2,
76
+ height,
77
+ width,
78
+ prompt_embeds=prompt_embeds,
79
+ pooled_prompt_embeds=pooled_prompt_embeds,
80
+ max_sequence_length=max_sequence_length,
81
+ )
82
+
83
+ self._guidance_scale = guidance_scale
84
+ self._joint_attention_kwargs = joint_attention_kwargs
85
+ self._interrupt = False
86
+
87
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
88
+ device = self._execution_device
89
+
90
+ lora_scale = joint_attention_kwargs.get("scale", None) if joint_attention_kwargs is not None else None
91
+ prompt_embeds, pooled_prompt_embeds, text_ids = self.encode_prompt(
92
+ prompt=prompt,
93
+ prompt_2=prompt_2,
94
+ prompt_embeds=prompt_embeds,
95
+ pooled_prompt_embeds=pooled_prompt_embeds,
96
+ device=device,
97
+ num_images_per_prompt=num_images_per_prompt,
98
+ max_sequence_length=max_sequence_length,
99
+ lora_scale=lora_scale,
100
+ )
101
+
102
+ num_channels_latents = self.transformer.config.in_channels // 4
103
+ latents, latent_image_ids = self.prepare_latents(
104
+ batch_size * num_images_per_prompt,
105
+ num_channels_latents,
106
+ height,
107
+ width,
108
+ prompt_embeds.dtype,
109
+ device,
110
+ generator,
111
+ latents,
112
+ )
113
+
114
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
115
+ image_seq_len = latents.shape[1]
116
+ mu = calculate_shift(
117
+ image_seq_len,
118
+ self.scheduler.config.base_image_seq_len,
119
+ self.scheduler.config.max_image_seq_len,
120
+ self.scheduler.config.base_shift,
121
+ self.scheduler.config.max_shift,
122
+ )
123
+ timesteps, num_inference_steps = retrieve_timesteps(
124
+ self.scheduler,
125
+ num_inference_steps,
126
+ device,
127
+ timesteps,
128
+ sigmas,
129
+ mu=mu,
130
+ )
131
+ self._num_timesteps = len(timesteps)
132
+
133
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32).expand(latents.shape[0]) if self.transformer.config.guidance_embeds else None
134
+
135
+ for i, t in enumerate(timesteps):
136
+ if self.interrupt:
137
+ continue
138
+
139
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
140
+
141
+ noise_pred = self.transformer(
142
+ hidden_states=latents,
143
+ timestep=timestep / 1000,
144
+ guidance=guidance,
145
+ pooled_projections=pooled_prompt_embeds,
146
+ encoder_hidden_states=prompt_embeds,
147
+ txt_ids=text_ids,
148
+ img_ids=latent_image_ids,
149
+ joint_attention_kwargs=self.joint_attention_kwargs,
150
+ return_dict=False,
151
+ )[0]
152
+
153
+ latents_for_image = self._unpack_latents(latents, height, width, self.vae_scale_factor)
154
+ latents_for_image = (latents_for_image / self.vae.config.scaling_factor) + self.vae.config.shift_factor
155
+ image = self.vae.decode(latents_for_image, return_dict=False)[0]
156
+ yield self.image_processor.postprocess(image, output_type=output_type)[0]
157
+
158
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
159
+ torch.cuda.empty_cache()
160
+
161
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
162
+ latents = (latents / good_vae.config.scaling_factor) + good_vae.config.shift_factor
163
+ image = good_vae.decode(latents, return_dict=False)[0]
164
+ self.maybe_free_model_hooks()
165
+ torch.cuda.empty_cache()
166
+ yield self.image_processor.postprocess(image, output_type=output_type)[0]
167
+
168
+ pipe_krea.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe_krea)
169
+
170
+ # Helper functions for flux.1-krea
171
+ def calculate_shift(
172
+ image_seq_len,
173
+ base_seq_len: int = 256,
174
+ max_seq_len: int = 4096,
175
+ base_shift: float = 0.5,
176
+ max_shift: float = 1.16,
177
+ ):
178
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
179
+ b = base_shift - m * base_seq_len
180
+ mu = image_seq_len * m + b
181
+ return mu
182
+
183
+ def retrieve_timesteps(
184
+ scheduler,
185
+ num_inference_steps: Optional[int] = None,
186
+ device: Optional[Union[str, torch.device]] = None,
187
+ timesteps: Optional[List[int]] = None,
188
+ sigmas: Optional[List[float]] = None,
189
+ **kwargs,
190
+ ):
191
+ if timesteps is not None and sigmas is not None:
192
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed.")
193
+ if timesteps is not None:
194
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
195
+ timesteps = scheduler.timesteps
196
+ num_inference_steps = len(timesteps)
197
+ elif sigmas is not None:
198
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
199
+ timesteps = scheduler.timesteps
200
+ num_inference_steps = len(timesteps)
201
+ else:
202
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
203
+ timesteps = scheduler.timesteps
204
+ return timesteps, num_inference_steps
205
+
206
+ # Styles for flux.1-dev-realism
207
+ style_list = [
208
+ {"name": "3840 x 2160", "prompt": "hyper-realistic 8K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic", "negative_prompt": ""},
209
+ {"name": "2560 x 1440", "prompt": "hyper-realistic 4K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic", "negative_prompt": ""},
210
+ {"name": "HD+", "prompt": "hyper-realistic 2K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic", "negative_prompt": ""},
211
+ {"name": "Style Zero", "prompt": "{prompt}", "negative_prompt": ""},
212
+ ]
213
+
214
+ styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}
215
+ DEFAULT_STYLE_NAME = "Style Zero"
216
+ STYLE_NAMES = list(styles.keys())
217
+
218
+ def apply_style(style_name: str, positive: str) -> Tuple[str, str]:
219
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
220
+ return p.replace("{prompt}", positive), n
221
+
222
+ # Generation function for flux.1-dev-realism
223
+ @spaces.GPU
224
+ def generate_dev(
225
+ prompt: str,
226
+ negative_prompt: str = "",
227
+ use_negative_prompt: bool = False,
228
+ seed: int = 0,
229
+ width: int = 1024,
230
+ height: int = 1024,
231
+ guidance_scale: float = 3,
232
+ randomize_seed: bool = False,
233
+ style_name: str = DEFAULT_STYLE_NAME,
234
+ num_inference_steps: int = 30,
235
+ num_images: int = 1,
236
+ zip_images: bool = False,
237
+ progress=gr.Progress(track_tqdm=True),
238
+ ):
239
+ positive_prompt, style_negative_prompt = apply_style(style_name, prompt)
240
+
241
+ if use_negative_prompt:
242
+ final_negative_prompt = style_negative_prompt + " " + negative_prompt
243
+ else:
244
+ final_negative_prompt = style_negative_prompt
245
+
246
+ final_negative_prompt = final_negative_prompt.strip()
247
+
248
+ if trigger_word:
249
+ positive_prompt = f"{trigger_word} {positive_prompt}"
250
+
251
+ seed = int(randomize_seed_fn(seed, randomize_seed))
252
+ generator = torch.Generator(device="cuda").manual_seed(seed)
253
+
254
+ start_time = time.time()
255
+
256
+ images = pipe_dev(
257
+ prompt=positive_prompt,
258
+ negative_prompt=final_negative_prompt if final_negative_prompt else None,
259
+ width=width,
260
+ height=height,
261
+ guidance_scale=guidance_scale,
262
+ num_inference_steps=num_inference_steps,
263
+ num_images_per_prompt=num_images,
264
+ generator=generator,
265
+ output_type="pil",
266
+ ).images
267
+
268
+ end_time = time.time()
269
+ duration = end_time - start_time
270
+
271
+ image_paths = [save_image(img) for img in images]
272
+
273
+ zip_path = None
274
+ if zip_images:
275
+ zip_name = str(uuid.uuid4()) + ".zip"
276
+ with zipfile.ZipFile(zip_name, 'w') as zipf:
277
+ for i, img_path in enumerate(image_paths):
278
+ zipf.write(img_path, arcname=f"Img_{i}.png")
279
+ zip_path = zip_name
280
+
281
+ return image_paths, seed, f"{duration:.2f}", zip_path
282
+
283
+ # Generation function for flux.1-krea
284
+ @spaces.GPU
285
+ def generate_krea(
286
+ prompt: str,
287
+ seed: int = 0,
288
+ width: int = 1024,
289
+ height: int = 1024,
290
+ guidance_scale: float = 4.5,
291
+ randomize_seed: bool = False,
292
+ num_inference_steps: int = 28,
293
+ num_images: int = 1,
294
+ zip_images: bool = False,
295
+ progress=gr.Progress(track_tqdm=True),
296
+ ):
297
+ if randomize_seed:
298
+ seed = random.randint(0, MAX_SEED)
299
+ generator = torch.Generator().manual_seed(seed)
300
+
301
+ start_time = time.time()
302
+
303
+ images = []
304
+ for _ in range(num_images):
305
+ final_img = list(pipe_krea.flux_pipe_call_that_returns_an_iterable_of_images(
306
+ prompt=prompt,
307
+ guidance_scale=guidance_scale,
308
+ num_inference_steps=num_inference_steps,
309
+ width=width,
310
+ height=height,
311
+ generator=generator,
312
+ output_type="pil",
313
+ good_vae=good_vae,
314
+ ))[-1] # Take the final image only
315
+ images.append(final_img)
316
+
317
+ end_time = time.time()
318
+ duration = end_time - start_time
319
+
320
+ image_paths = [save_image(img) for img in images]
321
+
322
+ zip_path = None
323
+ if zip_images:
324
+ zip_name = str(uuid.uuid4()) + ".zip"
325
+ with zipfile.ZipFile(zip_name, 'w') as zipf:
326
+ for i, img_path in enumerate(image_paths):
327
+ zipf.write(img_path, arcname=f"Img_{i}.png")
328
+ zip_path = zip_name
329
+
330
+ return image_paths, seed, f"{duration:.2f}", zip_path
331
+
332
+ # Main generation function to handle model choice
333
+ @spaces.GPU
334
+ def generate(
335
+ model_choice: str,
336
+ prompt: str,
337
+ negative_prompt: str = "",
338
+ use_negative_prompt: bool = False,
339
+ seed: int = 0,
340
+ width: int = 1024,
341
+ height: int = 1024,
342
+ guidance_scale: float = 3,
343
+ randomize_seed: bool = False,
344
+ style_name: str = DEFAULT_STYLE_NAME,
345
+ num_inference_steps: int = 30,
346
+ num_images: int = 1,
347
+ zip_images: bool = False,
348
+ progress=gr.Progress(track_tqdm=True),
349
+ ):
350
+ if model_choice == "flux.1-dev-merged":
351
+ return generate_dev(
352
+ prompt=prompt,
353
+ negative_prompt=negative_prompt,
354
+ use_negative_prompt=use_negative_prompt,
355
+ seed=seed,
356
+ width=width,
357
+ height=height,
358
+ guidance_scale=guidance_scale,
359
+ randomize_seed=randomize_seed,
360
+ style_name=style_name,
361
+ num_inference_steps=num_inference_steps,
362
+ num_images=num_images,
363
+ zip_images=zip_images,
364
+ progress=progress,
365
+ )
366
+ elif model_choice == "flux.1-krea-merged-dev":
367
+ return generate_krea(
368
+ prompt=prompt,
369
+ seed=seed,
370
+ width=width,
371
+ height=height,
372
+ guidance_scale=guidance_scale,
373
+ randomize_seed=randomize_seed,
374
+ num_inference_steps=num_inference_steps,
375
+ num_images=num_images,
376
+ zip_images=zip_images,
377
+ progress=progress,
378
+ )
379
+ else:
380
+ raise ValueError("Invalid model choice")
381
+
382
+ # Examples (tailored for flux.1-dev-realism)
383
+ examples = [
384
+ "cinematic close-up of a mysterious man in a black leather jacket, wet city streets glowing with neon lights in the background, raindrops visible on his hair, moody cyberpunk vibe --ar 16:9 --chaos 30 --stylize 600 --v 6.1",
385
+ "elegant portrait of a young woman wearing a flowing red silk gown, standing on marble stairs inside a grand palace, chandelier light casting golden highlights, fashion photography style --ar 3:4 --stylize 500 --v 6.0",
386
+ "vibrant outdoor shot of a teenage skateboarder mid-jump, urban graffiti walls behind him, bright sunlight with dynamic motion blur, sports action shot --ar 21:9 --chaos 40 --stylize 700 --v 6.1",
387
+ "softly lit, intimate headshot of an elderly woman with silver hair tied in a bun, wearing a knitted cardigan, warm tones and shallow depth of field, fine art photography --ar 4:5 --style raw --stylize 300 --v 6.0"
388
+ ]
389
+
390
+
391
+ css = '''
392
+ .gradio-container {
393
+ max-width: 590px !important;
394
+ margin: 0 auto !important;
395
+ }
396
+ h1 {
397
+ text-align: center;
398
+ }
399
+ footer {
400
+ visibility: hidden;
401
+ }
402
+ '''
403
+
404
+ # Gradio interface
405
+ with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
406
+ gr.Markdown(DESCRIPTION)
407
+ with gr.Row():
408
+ prompt = gr.Text(
409
+ label="Prompt",
410
+ show_label=False,
411
+ max_lines=1,
412
+ placeholder="Enter your prompt",
413
+ container=False,
414
+ )
415
+ run_button = gr.Button("Run", scale=0, variant="primary")
416
+ result = gr.Gallery(label="Result", columns=1, show_label=False, preview=True)
417
+
418
+ with gr.Row():
419
+ # Model choice radio button above additional options
420
+ model_choice = gr.Radio(
421
+ choices=["flux.1-krea-merged-dev", "flux.1-dev-merged"],
422
+ label="Select Model",
423
+ value="flux.1-krea-merged-dev"
424
+ )
425
+
426
+ with gr.Accordion("Additional Options", open=False):
427
+ style_selection = gr.Dropdown(
428
+ label="Quality Style (for flux.1-dev-realism only)",
429
+ choices=STYLE_NAMES,
430
+ value=DEFAULT_STYLE_NAME,
431
+ interactive=True,
432
+ )
433
+ use_negative_prompt = gr.Checkbox(label="Use negative prompt (for flux.1-dev-realism only)", value=False)
434
+ negative_prompt = gr.Text(
435
+ label="Negative prompt",
436
+ max_lines=1,
437
+ placeholder="Enter a negative prompt",
438
+ visible=False,
439
+ )
440
+ seed = gr.Slider(
441
+ label="Seed",
442
+ minimum=0,
443
+ maximum=MAX_SEED,
444
+ step=1,
445
+ value=0,
446
+ )
447
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
448
+ with gr.Row():
449
+ width = gr.Slider(
450
+ label="Width",
451
+ minimum=512,
452
+ maximum=2048,
453
+ step=64,
454
+ value=1024,
455
+ )
456
+ height = gr.Slider(
457
+ label="Height",
458
+ minimum=512,
459
+ maximum=2048,
460
+ step=64,
461
+ value=1024,
462
+ )
463
+ guidance_scale = gr.Slider(
464
+ label="Guidance Scale",
465
+ minimum=0.1,
466
+ maximum=20.0,
467
+ step=0.1,
468
+ value=3.5,
469
+ )
470
+ num_inference_steps = gr.Slider(
471
+ label="Number of inference steps",
472
+ minimum=1,
473
+ maximum=40,
474
+ step=1,
475
+ value=28,
476
+ )
477
+ num_images = gr.Slider(
478
+ label="Number of images",
479
+ minimum=1,
480
+ maximum=5,
481
+ step=1,
482
+ value=1,
483
+ )
484
+ zip_images = gr.Checkbox(label="Zip generated images", value=False)
485
+
486
+ gr.Markdown("### Output Information")
487
+ seed_display = gr.Textbox(label="Seed used", interactive=False)
488
+ generation_time = gr.Textbox(label="Generation time (seconds)", interactive=False)
489
+ zip_file = gr.File(label="Download ZIP")
490
+
491
+ gr.Examples(
492
+ examples=examples,
493
+ inputs=prompt,
494
+ outputs=[result, seed_display, generation_time, zip_file],
495
+ fn=generate,
496
+ cache_examples=False,
497
+ )
498
+
499
+ use_negative_prompt.change(
500
+ fn=lambda x: gr.update(visible=x),
501
+ inputs=use_negative_prompt,
502
+ outputs=negative_prompt,
503
+ api_name=False,
504
+ )
505
+
506
+ gr.on(
507
+ triggers=[
508
+ prompt.submit,
509
+ run_button.click,
510
+ ],
511
+ fn=generate,
512
+ inputs=[
513
+ model_choice,
514
+ prompt,
515
+ negative_prompt,
516
+ use_negative_prompt,
517
+ seed,
518
+ width,
519
+ height,
520
+ guidance_scale,
521
+ randomize_seed,
522
+ style_selection,
523
+ num_inference_steps,
524
+ num_images,
525
+ zip_images,
526
+ ],
527
+ outputs=[result, seed_display, generation_time, zip_file],
528
+ api_name="run",
529
+ )
530
+
531
+ if __name__ == "__main__":
532
  demo.queue(max_size=30).launch(mcp_server=True, ssr_mode=False, show_error=True)