ruslanmv commited on
Commit
cdbc5ce
·
verified ·
1 Parent(s): 2f46b7a

Create app-v1-working.py

Browse files
Files changed (1) hide show
  1. app-v1-working.py +515 -0
app-v1-working.py ADDED
@@ -0,0 +1,515 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import copy
4
+ import time
5
+ import random
6
+ import logging
7
+ import numpy as np
8
+ from typing import Any, Dict, List, Optional, Union
9
+
10
+ import torch
11
+ from PIL import Image
12
+ import gradio as gr
13
+
14
+ from diffusers import (
15
+ DiffusionPipeline,
16
+ AutoencoderTiny,
17
+ AutoencoderKL,
18
+ AutoPipelineForImage2Image,
19
+ FluxPipeline,
20
+ FlowMatchEulerDiscreteScheduler
21
+ )
22
+
23
+ from huggingface_hub import (
24
+ hf_hub_download,
25
+ HfFileSystem,
26
+ ModelCard,
27
+ snapshot_download
28
+ )
29
+
30
+ from diffusers.utils import load_image
31
+
32
+ import spaces
33
+
34
+ # Attempt to import loras from lora.py; otherwise use a default placeholder.
35
+ try:
36
+ from lora import loras
37
+ except ImportError:
38
+ loras = [
39
+ {"image": "placeholder.jpg", "title": "Placeholder LoRA", "repo": "placeholder/repo", "weights": None, "trigger_word": ""}
40
+ ]
41
+
42
+ #---if workspace = local or colab---
43
+ # (Optional: add Hugging Face login code here)
44
+
45
+ def calculate_shift(
46
+ image_seq_len,
47
+ base_seq_len: int = 256,
48
+ max_seq_len: int = 4096,
49
+ base_shift: float = 0.5,
50
+ max_shift: float = 1.16,
51
+ ):
52
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
53
+ b = base_shift - m * base_seq_len
54
+ mu = image_seq_len * m + b
55
+ return mu
56
+
57
+ def retrieve_timesteps(
58
+ scheduler,
59
+ num_inference_steps: Optional[int] = None,
60
+ device: Optional[Union[str, torch.device]] = None,
61
+ timesteps: Optional[List[int]] = None,
62
+ sigmas: Optional[List[float]] = None,
63
+ **kwargs,
64
+ ):
65
+ if timesteps is not None and sigmas is not None:
66
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
67
+ if timesteps is not None:
68
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
69
+ timesteps = scheduler.timesteps
70
+ num_inference_steps = len(timesteps)
71
+ elif sigmas is not None:
72
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
73
+ timesteps = scheduler.timesteps
74
+ num_inference_steps = len(timesteps)
75
+ else:
76
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
77
+ timesteps = scheduler.timesteps
78
+ return timesteps, num_inference_steps
79
+
80
+ # FLUX pipeline
81
+ @torch.inference_mode()
82
+ def flux_pipe_call_that_returns_an_iterable_of_images(
83
+ self,
84
+ prompt: Union[str, List[str]] = None,
85
+ prompt_2: Optional[Union[str, List[str]]] = None,
86
+ height: Optional[int] = None,
87
+ width: Optional[int] = None,
88
+ num_inference_steps: int = 28,
89
+ timesteps: List[int] = None,
90
+ guidance_scale: float = 3.5,
91
+ num_images_per_prompt: Optional[int] = 1,
92
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
93
+ latents: Optional[torch.FloatTensor] = None,
94
+ prompt_embeds: Optional[torch.FloatTensor] = None,
95
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
96
+ output_type: Optional[str] = "pil",
97
+ return_dict: bool = True,
98
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
99
+ max_sequence_length: int = 512,
100
+ good_vae: Optional[Any] = None,
101
+ ):
102
+ height = height or self.default_sample_size * self.vae_scale_factor
103
+ width = width or self.default_sample_size * self.vae_scale_factor
104
+
105
+ self.check_inputs(
106
+ prompt,
107
+ prompt_2,
108
+ height,
109
+ width,
110
+ prompt_embeds=prompt_embeds,
111
+ pooled_prompt_embeds=pooled_prompt_embeds,
112
+ max_sequence_length=max_sequence_length,
113
+ )
114
+
115
+ self._guidance_scale = guidance_scale
116
+ self._joint_attention_kwargs = joint_attention_kwargs
117
+ self._interrupt = False
118
+
119
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
120
+ device = self._execution_device
121
+
122
+ lora_scale = joint_attention_kwargs.get("scale", None) if joint_attention_kwargs is not None else None
123
+ prompt_embeds, pooled_prompt_embeds, text_ids = self.encode_prompt(
124
+ prompt=prompt,
125
+ prompt_2=prompt_2,
126
+ prompt_embeds=prompt_embeds,
127
+ pooled_prompt_embeds=pooled_prompt_embeds,
128
+ device=device,
129
+ num_images_per_prompt=num_images_per_prompt,
130
+ max_sequence_length=max_sequence_length,
131
+ lora_scale=lora_scale,
132
+ )
133
+
134
+ num_channels_latents = self.transformer.config.in_channels // 4
135
+ latents, latent_image_ids = self.prepare_latents(
136
+ batch_size * num_images_per_prompt,
137
+ num_channels_latents,
138
+ height,
139
+ width,
140
+ prompt_embeds.dtype,
141
+ device,
142
+ generator,
143
+ latents,
144
+ )
145
+
146
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
147
+ image_seq_len = latents.shape[1]
148
+ mu = calculate_shift(
149
+ image_seq_len,
150
+ self.scheduler.config.base_image_seq_len,
151
+ self.scheduler.config.max_image_seq_len,
152
+ self.scheduler.config.base_shift,
153
+ self.scheduler.config.max_shift,
154
+ )
155
+ timesteps, num_inference_steps = retrieve_timesteps(
156
+ self.scheduler,
157
+ num_inference_steps,
158
+ device,
159
+ timesteps,
160
+ sigmas,
161
+ mu=mu,
162
+ )
163
+ self._num_timesteps = len(timesteps)
164
+
165
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32).expand(latents.shape[0]) if self.transformer.config.guidance_embeds else None
166
+
167
+ for i, t in enumerate(timesteps):
168
+ if self.interrupt:
169
+ continue
170
+
171
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
172
+
173
+ noise_pred = self.transformer(
174
+ hidden_states=latents,
175
+ timestep=timestep / 1000,
176
+ guidance=guidance,
177
+ pooled_projections=pooled_prompt_embeds,
178
+ encoder_hidden_states=prompt_embeds,
179
+ txt_ids=text_ids,
180
+ img_ids=latent_image_ids,
181
+ joint_attention_kwargs=self.joint_attention_kwargs,
182
+ return_dict=False,
183
+ )[0]
184
+
185
+ latents_for_image = self._unpack_latents(latents, height, width, self.vae_scale_factor)
186
+ latents_for_image = (latents_for_image / self.vae.config.scaling_factor) + self.vae.config.shift_factor
187
+ image = self.vae.decode(latents_for_image, return_dict=False)[0]
188
+ yield self.image_processor.postprocess(image, output_type=output_type)[0]
189
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
190
+ torch.cuda.empty_cache()
191
+
192
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
193
+ latents = (latents / good_vae.config.scaling_factor) + good_vae.config.shift_factor
194
+ image = good_vae.decode(latents, return_dict=False)[0]
195
+ self.maybe_free_model_hooks()
196
+ torch.cuda.empty_cache()
197
+ yield self.image_processor.postprocess(image, output_type=output_type)[0]
198
+
199
+ #--------------------------------------------------Model Initialization-----------------------------------------------------------------------------------------#
200
+ dtype = torch.bfloat16
201
+ device = "cuda" if torch.cuda.is_available() else "cpu"
202
+ base_model = "black-forest-labs/FLUX.1-dev"
203
+
204
+ # TAEF1 is a very tiny autoencoder which uses the same "latent API" as FLUX.1's VAE.
205
+ taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device)
206
+ good_vae = AutoencoderKL.from_pretrained(base_model, subfolder="vae", torch_dtype=dtype).to(device)
207
+ pipe = DiffusionPipeline.from_pretrained(base_model, torch_dtype=dtype, vae=taef1).to(device)
208
+ pipe_i2i = AutoPipelineForImage2Image.from_pretrained(base_model,
209
+ vae=good_vae,
210
+ transformer=pipe.transformer,
211
+ text_encoder=pipe.text_encoder,
212
+ tokenizer=pipe.tokenizer,
213
+ text_encoder_2=pipe.text_encoder_2,
214
+ tokenizer_2=pipe.tokenizer_2,
215
+ torch_dtype=dtype
216
+ )
217
+ MAX_SEED = 2**32-1
218
+
219
+ pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)
220
+
221
+ class calculateDuration:
222
+ def __init__(self, activity_name=""):
223
+ self.activity_name = activity_name
224
+ def __enter__(self):
225
+ self.start_time = time.time()
226
+ return self
227
+ def __exit__(self, exc_type, exc_value, traceback):
228
+ self.end_time = time.time()
229
+ self.elapsed_time = self.end_time - self.start_time
230
+ if self.activity_name:
231
+ print(f"Elapsed time for {self.activity_name}: {self.elapsed_time:.6f} seconds")
232
+ else:
233
+ print(f"Elapsed time: {self.elapsed_time:.6f} seconds")
234
+
235
+ def update_selection(evt: gr.SelectData, width, height):
236
+ selected_lora = loras[evt.index]
237
+ new_placeholder = f"Type a prompt for {selected_lora['title']}"
238
+ lora_repo = selected_lora["repo"]
239
+ updated_text = f"### Selected: [{lora_repo}](https://huggingface.co/{lora_repo}) ✅"
240
+ if "aspect" in selected_lora:
241
+ if selected_lora["aspect"] == "portrait":
242
+ width = 768
243
+ height = 1024
244
+ elif selected_lora["aspect"] == "landscape":
245
+ width = 1024
246
+ height = 768
247
+ else:
248
+ width = 1024
249
+ height = 1024
250
+ return (
251
+ gr.update(placeholder=new_placeholder),
252
+ updated_text,
253
+ evt.index,
254
+ width,
255
+ height,
256
+ )
257
+
258
+ @spaces.GPU(duration=100)
259
+ def generate_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, progress):
260
+ pipe.to("cuda")
261
+ generator = torch.Generator(device="cuda").manual_seed(seed)
262
+ with calculateDuration("Generating image"):
263
+ for img in pipe.flux_pipe_call_that_returns_an_iterable_of_images(
264
+ prompt=prompt_mash,
265
+ num_inference_steps=steps,
266
+ guidance_scale=cfg_scale,
267
+ width=width,
268
+ height=height,
269
+ generator=generator,
270
+ joint_attention_kwargs={"scale": lora_scale},
271
+ output_type="pil",
272
+ good_vae=good_vae,
273
+ ):
274
+ yield img
275
+
276
+ def generate_image_to_image(prompt_mash, image_input_path, image_strength, steps, cfg_scale, width, height, lora_scale, seed):
277
+ generator = torch.Generator(device="cuda").manual_seed(seed)
278
+ pipe_i2i.to("cuda")
279
+ image_input = load_image(image_input_path)
280
+ final_image = pipe_i2i(
281
+ prompt=prompt_mash,
282
+ image=image_input,
283
+ strength=image_strength,
284
+ num_inference_steps=steps,
285
+ guidance_scale=cfg_scale,
286
+ width=width,
287
+ height=height,
288
+ generator=generator,
289
+ joint_attention_kwargs={"scale": lora_scale},
290
+ output_type="pil",
291
+ ).images[0]
292
+ return final_image
293
+
294
+ @spaces.GPU(duration=100)
295
+ def run_lora(prompt, image_input, image_strength, cfg_scale, steps, selected_index, randomize_seed, seed, width, height, lora_scale, progress=gr.Progress(track_tqdm=True)):
296
+ if selected_index is None:
297
+ raise gr.Error("You must select a LoRA before proceeding.🧨")
298
+ selected_lora = loras[selected_index]
299
+ lora_path = selected_lora["repo"]
300
+ trigger_word = selected_lora["trigger_word"]
301
+ if(trigger_word):
302
+ if "trigger_position" in selected_lora:
303
+ if selected_lora["trigger_position"] == "prepend":
304
+ prompt_mash = f"{trigger_word} {prompt}"
305
+ else:
306
+ prompt_mash = f"{prompt} {trigger_word}"
307
+ else:
308
+ prompt_mash = f"{trigger_word} {prompt}"
309
+ else:
310
+ prompt_mash = prompt
311
+
312
+ with calculateDuration("Unloading LoRA"):
313
+ pipe.unload_lora_weights()
314
+ pipe_i2i.unload_lora_weights()
315
+
316
+ with calculateDuration(f"Loading LoRA weights for {selected_lora['title']}"):
317
+ pipe_to_use = pipe_i2i if image_input is not None else pipe
318
+ weight_name = selected_lora.get("weights", None)
319
+ pipe_to_use.load_lora_weights(
320
+ lora_path,
321
+ weight_name=weight_name,
322
+ low_cpu_mem_usage=True
323
+ )
324
+
325
+ with calculateDuration("Randomizing seed"):
326
+ if randomize_seed:
327
+ seed = random.randint(0, MAX_SEED)
328
+
329
+ if(image_input is not None):
330
+ final_image = generate_image_to_image(prompt_mash, image_input, image_strength, steps, cfg_scale, width, height, lora_scale, seed)
331
+ yield final_image, seed, gr.update(visible=False)
332
+ else:
333
+ image_generator = generate_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, progress)
334
+ final_image = None
335
+ step_counter = 0
336
+ for image in image_generator:
337
+ step_counter += 1
338
+ final_image = image
339
+ progress_bar = f'<div class="progress-container"><div class="progress-bar" style="--current: {step_counter}; --total: {steps};"></div></div>'
340
+ yield image, seed, gr.update(value=progress_bar, visible=True)
341
+ yield final_image, seed, gr.update(value=progress_bar, visible=False)
342
+
343
+ def get_huggingface_safetensors(link):
344
+ split_link = link.split("/")
345
+ if(len(split_link) == 2):
346
+ model_card = ModelCard.load(link)
347
+ base_model = model_card.data.get("base_model")
348
+ print(base_model)
349
+ if((base_model != "black-forest-labs/FLUX.1-dev") and (base_model != "black-forest-labs/FLUX.1-schnell")):
350
+ raise Exception("Flux LoRA Not Found!")
351
+ image_path = model_card.data.get("widget", [{}])[0].get("output", {}).get("url", None)
352
+ trigger_word = model_card.data.get("instance_prompt", "")
353
+ image_url = f"https://huggingface.co/{link}/resolve/main/{image_path}" if image_path else None
354
+ fs = HfFileSystem()
355
+ try:
356
+ list_of_files = fs.ls(link, detail=False)
357
+ for file in list_of_files:
358
+ if(file.endswith(".safetensors")):
359
+ safetensors_name = file.split("/")[-1]
360
+ if (not image_url and file.lower().endswith((".jpg", ".jpeg", ".png", ".webp"))):
361
+ image_elements = file.split("/")
362
+ image_url = f"https://huggingface.co/{link}/resolve/main/{image_elements[-1]}"
363
+ except Exception as e:
364
+ print(e)
365
+ gr.Warning(f"You didn't include a link neither a valid Hugging Face repository with a *.safetensors LoRA")
366
+ raise Exception(f"You didn't include a link neither a valid Hugging Face repository with a *.safetensors LoRA")
367
+ return split_link[1], link, safetensors_name, trigger_word, image_url
368
+ else:
369
+ raise Exception("Invalid LoRA link format")
370
+
371
+ def check_custom_model(link):
372
+ if(link.startswith("https://")):
373
+ if(link.startswith("https://huggingface.co") or link.startswith("https://www.huggingface.co")):
374
+ link_split = link.split("huggingface.co/")
375
+ return get_huggingface_safetensors(link_split[1])
376
+ else:
377
+ return get_huggingface_safetensors(link)
378
+
379
+ def add_custom_lora(custom_lora):
380
+ global loras
381
+ if(custom_lora):
382
+ try:
383
+ title, repo, path, trigger_word, image = check_custom_model(custom_lora)
384
+ print(f"Loaded custom LoRA: {repo}")
385
+ card = f'''
386
+ <div class="custom_lora_card">
387
+ <span>Loaded custom LoRA:</span>
388
+ <div class="card_internal">
389
+ <img src="{image}" />
390
+ <div>
391
+ <h3>{title}</h3>
392
+ <small>{"Using: <code><b>"+trigger_word+"</code></b> as the trigger word" if trigger_word else "No trigger word found. If there's a trigger word, include it in your prompt"}<br></small>
393
+ </div>
394
+ </div>
395
+ </div>
396
+ '''
397
+ existing_item_index = next((index for (index, item) in enumerate(loras) if item['repo'] == repo), None)
398
+ if(not existing_item_index):
399
+ new_item = {
400
+ "image": image,
401
+ "title": title,
402
+ "repo": repo,
403
+ "weights": path,
404
+ "trigger_word": trigger_word
405
+ }
406
+ print(new_item)
407
+ existing_item_index = len(loras)
408
+ loras.append(new_item)
409
+
410
+ return gr.update(visible=True, value=card), gr.update(visible=True), gr.Gallery(selected_index=None), f"Custom: {path}", existing_item_index, trigger_word
411
+ except Exception as e:
412
+ gr.Warning(f"Invalid LoRA: either you entered an invalid link, or a non-FLUX LoRA")
413
+ return gr.update(visible=True, value=f"Invalid LoRA: either you entered an invalid link, a non-FLUX LoRA"), gr.update(visible=False), gr.update(), "", None, ""
414
+ else:
415
+ return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
416
+
417
+ def remove_custom_lora():
418
+ return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
419
+
420
+ run_lora.zerogpu = True
421
+
422
+ css = '''
423
+ #gen_btn{height: 100%}
424
+ #gen_column{align-self: stretch}
425
+ #title{text-align: center}
426
+ #title h1{font-size: 3em; display:inline-flex; align-items:center}
427
+ #title img{width: 100px; margin-right: 0.5em}
428
+ #gallery .grid-wrap{height: 10vh}
429
+ #lora_list{background: var(--block-background-fill);padding: 0 1em .3em; font-size: 90%}
430
+ .card_internal{display: flex;height: 100px;margin-top: .5em}
431
+ .card_internal img{margin-right: 1em}
432
+ .styler{--form-gap-width: 0px !important}
433
+ #progress{height:30px}
434
+ #progress .generating{display:none}
435
+ .progress-container {width: 100%;height: 30px;background-color: #f0f0f0;border-radius: 15px;overflow: hidden;margin-bottom: 20px}
436
+ .progress-bar {height: 100%;background-color: #4f46e5;width: calc(var(--current) / var(--total) * 100%);transition: width 0.5s ease-in-out}
437
+ '''
438
+
439
+ with gr.Blocks(theme="YTheme/Minecraft", css=css, delete_cache=(60, 60)) as app:
440
+ title = gr.HTML(
441
+ """<h1>FLUX LoRA DLC🥳</h1>""",
442
+ elem_id="title",
443
+ )
444
+ selected_index = gr.State(None)
445
+ with gr.Row():
446
+ with gr.Column(scale=3):
447
+ prompt = gr.Textbox(label="Prompt", lines=1, placeholder=":/ choose the LoRA and type the prompt ")
448
+ with gr.Column(scale=1, elem_id="gen_column"):
449
+ generate_button = gr.Button("Generate", variant="primary", elem_id="gen_btn")
450
+ with gr.Row():
451
+ with gr.Column():
452
+ selected_info = gr.Markdown("")
453
+ gallery = gr.Gallery(
454
+ [(item["image"], item["title"]) for item in loras],
455
+ label="LoRA DLC's",
456
+ allow_preview=False,
457
+ columns=3,
458
+ elem_id="gallery",
459
+ show_share_button=False
460
+ )
461
+ with gr.Group():
462
+ custom_lora = gr.Textbox(label="Enter Custom LoRA", placeholder="prithivMLmods/Canopus-LoRA-Flux-Anime")
463
+ gr.Markdown("[Check the list of FLUX LoRA's](https://huggingface.co/models?other=base_model:adapter:black-forest-labs/FLUX.1-dev)", elem_id="lora_list")
464
+ custom_lora_info = gr.HTML(visible=False)
465
+ custom_lora_button = gr.Button("Remove custom LoRA", visible=False)
466
+ with gr.Column():
467
+ progress_bar = gr.Markdown(elem_id="progress",visible=False)
468
+ result = gr.Image(label="Generated Image")
469
+ with gr.Row():
470
+ with gr.Accordion("Advanced Settings", open=False):
471
+ with gr.Row():
472
+ input_image = gr.Image(label="Input image", type="filepath")
473
+ image_strength = gr.Slider(label="Denoise Strength", info="Lower means more image influence", minimum=0.1, maximum=1.0, step=0.01, value=0.75)
474
+ with gr.Column():
475
+ with gr.Row():
476
+ cfg_scale = gr.Slider(label="CFG Scale", minimum=1, maximum=20, step=0.5, value=3.5)
477
+ steps = gr.Slider(label="Steps", minimum=1, maximum=50, step=1, value=28)
478
+ with gr.Row():
479
+ width = gr.Slider(label="Width", minimum=256, maximum=1536, step=64, value=1024)
480
+ height = gr.Slider(label="Height", minimum=256, maximum=1536, step=64, value=1024)
481
+ with gr.Row():
482
+ randomize_seed = gr.Checkbox(True, label="Randomize seed")
483
+ seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0, randomize=True)
484
+ lora_scale = gr.Slider(label="LoRA Scale", minimum=0, maximum=3, step=0.01, value=0.95)
485
+ with gr.Row():
486
+ use_enhancer = gr.Checkbox(value=False, label="Use Prompt Enhancer")
487
+ show_enhanced_prompt = gr.Checkbox(value=False, label="Display Enhanced Prompt")
488
+ enhanced_prompt_box = gr.Textbox(label="Enhanced Prompt", visible=False)
489
+ # Add the change event so that the enhanced prompt box visibility toggles.
490
+ show_enhanced_prompt.change(fn=lambda show: gr.update(visible=show),
491
+ inputs=show_enhanced_prompt,
492
+ outputs=enhanced_prompt_box)
493
+ gallery.select(
494
+ update_selection,
495
+ inputs=[width, height],
496
+ outputs=[prompt, selected_info, selected_index, width, height]
497
+ )
498
+ custom_lora.input(
499
+ add_custom_lora,
500
+ inputs=[custom_lora],
501
+ outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, prompt]
502
+ )
503
+ custom_lora_button.click(
504
+ remove_custom_lora,
505
+ outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, custom_lora]
506
+ )
507
+ gr.on(
508
+ triggers=[generate_button.click, prompt.submit],
509
+ fn=run_lora,
510
+ inputs=[prompt, input_image, image_strength, cfg_scale, steps, selected_index, randomize_seed, seed, width, height, lora_scale],
511
+ outputs=[result, seed, progress_bar]
512
+ )
513
+
514
+ app.queue()
515
+ app.launch(debug=True)