Keltezaa commited on
Commit
d0beb15
·
verified ·
1 Parent(s): 8f10667

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -614
app.py DELETED
@@ -1,614 +0,0 @@
1
- import os
2
- import gradio as gr
3
- import json
4
- import logging
5
- import torch
6
- from PIL import Image
7
- import spaces
8
- from diffusers import DiffusionPipeline, AutoencoderTiny, AutoencoderKL, AutoPipelineForImage2Image
9
- from live_preview_helpers import calculate_shift, retrieve_timesteps, flux_pipe_call_that_returns_an_iterable_of_images
10
- from huggingface_hub import hf_hub_download, HfFileSystem, ModelCard, snapshot_download
11
- from transformers import AutoModelForCausalLM, CLIPTokenizer, CLIPProcessor, CLIPModel, LongformerTokenizer, LongformerModel
12
- import copy
13
- import random
14
- import time
15
- import requests
16
- import pandas as pd
17
-
18
- # Disable tokenizer parallelism
19
- os.environ["TOKENIZERS_PARALLELISM"] = "false"
20
-
21
- # Initialize the CLIP tokenizer and model
22
- clip_tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-base-patch16")
23
- clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch16")
24
- clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch16")
25
-
26
- # Initialize the Longformer tokenizer and model
27
- longformer_tokenizer = LongformerTokenizer.from_pretrained("allenai/longformer-base-4096")
28
- longformer_model = LongformerModel.from_pretrained("allenai/longformer-base-4096")
29
-
30
- #Load prompts for randomization
31
- df = pd.read_csv('prompts.csv', header=None)
32
- prompt_values = df.values.flatten()
33
-
34
- # Load LoRAs from JSON file
35
- with open('loras.json', 'r') as f:
36
- loras = json.load(f)
37
-
38
- # Initialize the base model
39
- dtype = torch.bfloat16
40
- device = "cuda" if torch.cuda.is_available() else "cpu"
41
- base_model = "black-forest-labs/FLUX.1-dev"
42
-
43
- taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device)
44
- good_vae = AutoencoderKL.from_pretrained(base_model, subfolder="vae", torch_dtype=dtype).to(device)
45
- pipe = DiffusionPipeline.from_pretrained(base_model, torch_dtype=dtype, vae=taef1).to(device)
46
- pipe_i2i = AutoPipelineForImage2Image.from_pretrained(
47
- base_model,
48
- vae=good_vae,
49
- transformer=pipe.transformer,
50
- text_encoder=pipe.text_encoder,
51
- tokenizer=pipe.tokenizer,
52
- text_encoder_2=pipe.text_encoder_2,
53
- tokenizer_2=pipe.tokenizer_2,
54
- torch_dtype=dtype
55
- )
56
- MAX_SEED = 2**32 - 1
57
-
58
- pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)
59
-
60
- def process_input(input_text):
61
- # Tokenize and truncate input
62
- #inputs = clip_processor(text=input_text, return_tensors="pt", padding=True, truncation=True, max_length=77)
63
- #return inputs
64
- #Change clip_processor to longformer
65
- inputs = longformer_tokenizer(input_text, return_tensors="pt", padding=True, truncation=True, max_length=4096)
66
- return inputs
67
-
68
- # Example usage
69
- input_text = "Your long prompt goes here..."
70
- inputs = process_input(input_text)
71
-
72
- class calculateDuration:
73
- def __init__(self, activity_name=""):
74
- self.activity_name = activity_name
75
-
76
- def __enter__(self):
77
- self.start_time = time.time()
78
- return self
79
-
80
- def __exit__(self, exc_type, exc_value, traceback):
81
- self.end_time = time.time()
82
- self.elapsed_time = self.end_time - self.start_time
83
- if self.activity_name:
84
- print(f"Elapsed time for {self.activity_name}: {self.elapsed_time:.6f} seconds")
85
- else:
86
- print(f"Elapsed time: {self.elapsed_time:.6f} seconds")
87
-
88
- def download_file(url, directory=None):
89
- if directory is None:
90
- directory = os.getcwd() # Use current working directory if not specified
91
-
92
- # Get the filename from the URL
93
- filename = url.split('/')[-1]
94
-
95
- # Full path for the downloaded file
96
- filepath = os.path.join(directory, filename)
97
-
98
- # Download the file
99
- response = requests.get(url)
100
- response.raise_for_status() # Raise an exception for bad status codes
101
-
102
- # Write the content to the file
103
- with open(filepath, 'wb') as file:
104
- file.write(response.content)
105
-
106
- return filepath
107
-
108
- def update_selection(evt: gr.SelectData, selected_indices, loras_state, width, height):
109
- selected_index = evt.index
110
- selected_indices = selected_indices or []
111
- if selected_index in selected_indices:
112
- selected_indices.remove(selected_index)
113
- else:
114
- if len(selected_indices) < 2:
115
- selected_indices.append(selected_index)
116
- else:
117
- gr.Warning("You can select up to 2 LoRAs, remove one to select a new one.")
118
- return gr.update(), gr.update(), gr.update(), selected_indices, gr.update(), gr.update(), width, height, gr.update(), gr.update()
119
-
120
- selected_info_1 = "Select a Celebrity as LoRA 1"
121
- selected_info_2 = "Select a LoRA 2"
122
- lora_scale_1 = 0.6
123
- lora_scale_2 = 1.15
124
- lora_image_1 = None
125
- lora_image_2 = None
126
- if len(selected_indices) >= 1:
127
- lora1 = loras_state[selected_indices[0]]
128
- selected_info_1 = f"### LoRA 1 Selected: [{lora1['title']}](https://huggingface.co/{lora1['repo']}) ✨"
129
- lora_image_1 = lora1['image']
130
- if len(selected_indices) >= 2:
131
- lora2 = loras_state[selected_indices[1]]
132
- selected_info_2 = f"### LoRA 2 Selected: [{lora2['title']}](https://huggingface.co/{lora2['repo']}) ✨"
133
- lora_image_2 = lora2['image']
134
-
135
- if selected_indices:
136
- last_selected_lora = loras_state[selected_indices[-1]]
137
- new_placeholder = f"Type a prompt for {last_selected_lora['title']}"
138
- else:
139
- new_placeholder = "Type a prompt after selecting a LoRA"
140
-
141
- return gr.update(placeholder=new_placeholder), selected_info_1, selected_info_2, selected_indices, lora_scale_1, lora_scale_2, width, height, lora_image_1, lora_image_2
142
-
143
- def remove_lora_1(selected_indices, loras_state):
144
- if len(selected_indices) >= 1:
145
- selected_indices.pop(0)
146
- selected_info_1 = "Select a Celebrity as LoRA 1"
147
- selected_info_2 = "Select a LoRA 2"
148
- lora_scale_1 = 0.6
149
- lora_scale_2 = 1.15
150
- lora_image_1 = None
151
- lora_image_2 = None
152
- if len(selected_indices) >= 1:
153
- lora1 = loras_state[selected_indices[0]]
154
- selected_info_1 = f"### LoRA 1 Selected: [{lora1['title']}]({lora1['repo']}) ✨"
155
- lora_image_1 = lora1['image']
156
- if len(selected_indices) >= 2:
157
- lora2 = loras_state[selected_indices[1]]
158
- selected_info_2 = f"### LoRA 2 Selected: [{lora2['title']}]({lora2['repo']}) ✨"
159
- lora_image_2 = lora2['image']
160
- return selected_info_1, selected_info_2, selected_indices, lora_scale_1, lora_scale_2, lora_image_1, lora_image_2
161
-
162
- def remove_lora_2(selected_indices, loras_state):
163
- if len(selected_indices) >= 2:
164
- selected_indices.pop(1)
165
- selected_info_1 = "Select a Celebrity as LoRA 1"
166
- selected_info_2 = "Select LoRA 2"
167
- lora_scale_1 = 0.6
168
- lora_scale_2 = 1.15
169
- lora_image_1 = None
170
- lora_image_2 = None
171
- if len(selected_indices) >= 1:
172
- lora1 = loras_state[selected_indices[0]]
173
- selected_info_1 = f"### LoRA 1 Selected: [{lora1['title']}]({lora1['repo']}) ✨"
174
- lora_image_1 = lora1['image']
175
- if len(selected_indices) >= 2:
176
- lora2 = loras_state[selected_indices[1]]
177
- selected_info_2 = f"### LoRA 2 Selected: [{lora2['title']}]({lora2['repo']}) ✨"
178
- lora_image_2 = lora2['image']
179
- return selected_info_1, selected_info_2, selected_indices, lora_scale_1, lora_scale_2, lora_image_1, lora_image_2
180
-
181
- def randomize_loras(selected_indices, loras_state):
182
- if len(loras_state) < 2:
183
- raise gr.Error("Not enough LoRAs to randomize.")
184
- selected_indices = random.sample(range(len(loras_state)), 2)
185
- lora1 = loras_state[selected_indices[0]]
186
- lora2 = loras_state[selected_indices[1]]
187
- selected_info_1 = f"### LoRA 1 Selected: [{lora1['title']}](https://huggingface.co/{lora1['repo']}) ✨"
188
- selected_info_2 = f"### LoRA 2 Selected: [{lora2['title']}](https://huggingface.co/{lora2['repo']}) ✨"
189
- lora_scale_1 = 1.15
190
- lora_scale_2 = 1.15
191
- lora_image_1 = lora1['image']
192
- lora_image_2 = lora2['image']
193
- random_prompt = random.choice(prompt_values)
194
- return selected_info_1, selected_info_2, selected_indices, lora_scale_1, lora_scale_2, lora_image_1, lora_image_2, random_prompt
195
-
196
- def add_custom_lora(custom_lora, selected_indices, current_loras, gallery):
197
- if custom_lora:
198
- try:
199
- title, repo, path, trigger_word, image = check_custom_model(custom_lora)
200
- print(f"Loaded custom LoRA: {repo}")
201
- existing_item_index = next((index for (index, item) in enumerate(current_loras) if item['repo'] == repo), None)
202
- if existing_item_index is None:
203
- if repo.endswith(".safetensors") and repo.startswith("http"):
204
- repo = download_file(repo)
205
- new_item = {
206
- "image": image if image else "/home/user/app/custom.png",
207
- "title": title,
208
- "repo": repo,
209
- "weights": path,
210
- "trigger_word": trigger_word
211
- }
212
- print(f"New LoRA: {new_item}")
213
- existing_item_index = len(current_loras)
214
- current_loras.append(new_item)
215
-
216
- # Update gallery
217
- gallery_items = [(item["image"], item["title"]) for item in current_loras]
218
- # Update selected_indices if there's room
219
- if len(selected_indices) < 2:
220
- selected_indices.append(existing_item_index)
221
- else:
222
- gr.Warning("You can select up to 2 LoRAs, remove one to select a new one.")
223
-
224
- # Update selected_info and images
225
- selected_info_1 = "Select a Celebrity as LoRA 1"
226
- selected_info_2 = "Select a LoRA 2"
227
- lora_scale_1 = 0.6
228
- lora_scale_2 = 1.15
229
- lora_image_1 = None
230
- lora_image_2 = None
231
- if len(selected_indices) >= 1:
232
- lora1 = current_loras[selected_indices[0]]
233
- selected_info_1 = f"### LoRA 1 Selected: {lora1['title']} ✨"
234
- lora_image_1 = lora1['image'] if lora1['image'] else None
235
- if len(selected_indices) >= 2:
236
- lora2 = current_loras[selected_indices[1]]
237
- selected_info_2 = f"### LoRA 2 Selected: {lora2['title']} ✨"
238
- lora_image_2 = lora2['image'] if lora2['image'] else None
239
- print("Finished adding custom LoRA")
240
- return (
241
- current_loras,
242
- gr.update(value=gallery_items),
243
- selected_info_1,
244
- selected_info_2,
245
- selected_indices,
246
- lora_scale_1,
247
- lora_scale_2,
248
- lora_image_1,
249
- lora_image_2
250
- )
251
- except Exception as e:
252
- print(e)
253
- gr.Warning(str(e))
254
- return current_loras, gr.update(), gr.update(), gr.update(), selected_indices, gr.update(), gr.update(), gr.update(), gr.update()
255
- else:
256
- return current_loras, gr.update(), gr.update(), gr.update(), selected_indices, gr.update(), gr.update(), gr.update(), gr.update()
257
-
258
- def remove_custom_lora(selected_indices, current_loras, gallery):
259
- if current_loras:
260
- custom_lora_repo = current_loras[-1]['repo']
261
- # Remove from loras list
262
- current_loras = current_loras[:-1]
263
- # Remove from selected_indices if selected
264
- custom_lora_index = len(current_loras)
265
- if custom_lora_index in selected_indices:
266
- selected_indices.remove(custom_lora_index)
267
- # Update gallery
268
- gallery_items = [(item["image"], item["title"]) for item in current_loras]
269
- # Update selected_info and images
270
- selected_info_1 = "Select a Celebrity as LoRA 1"
271
- selected_info_2 = "Select a LoRA 2"
272
- lora_scale_1 = 0.6
273
- lora_scale_2 = 1.15
274
- lora_image_1 = None
275
- lora_image_2 = None
276
- if len(selected_indices) >= 1:
277
- lora1 = current_loras[selected_indices[0]]
278
- selected_info_1 = f"### LoRA 1 Selected: [{lora1['title']}]({lora1['repo']}) ✨"
279
- lora_image_1 = lora1['image']
280
- if len(selected_indices) >= 2:
281
- lora2 = current_loras[selected_indices[1]]
282
- selected_info_2 = f"### LoRA 2 Selected: [{lora2['title']}]({lora2['repo']}) ✨"
283
- lora_image_2 = lora2['image']
284
- return (
285
- current_loras,
286
- gr.update(value=gallery_items),
287
- selected_info_1,
288
- selected_info_2,
289
- selected_indices,
290
- lora_scale_1,
291
- lora_scale_2,
292
- lora_image_1,
293
- lora_image_2
294
- )
295
-
296
- def generate_image(prompt_mash, steps, seed, cfg_scale, width, height, progress):
297
- print("Generating images...")
298
- pipe.to("cuda")
299
- generator = torch.Generator(device="cuda").manual_seed(seed)
300
- images = []
301
-
302
- with calculateDuration("Generating images"):
303
- try:
304
- for img in pipe.flux_pipe_call_that_returns_an_iterable_of_images(
305
- prompt=prompt_mash,
306
- num_inference_steps=steps,
307
- guidance_scale=cfg_scale,
308
- width=width,
309
- height=height,
310
- generator=generator,
311
- joint_attention_kwargs={"scale": 1.0},
312
- output_type="pil",
313
- good_vae=good_vae,
314
- ):
315
- images.append(img)
316
- progress(len(images) / 4 * 100) # Update progress as a percentage
317
- if len(images) == 4: # Collect exactly 4 images
318
- break
319
- except Exception as e:
320
- print(f"Error during image generation: {e}")
321
- raise
322
-
323
- if len(images) < 4:
324
- print("Fewer than 4 images generated. Padding with None.")
325
- while len(images) < 4:
326
- images.append(None)
327
-
328
- return images
329
-
330
- @spaces.GPU(duration=75)
331
- def run_lora(prompt, cfg_scale, steps, selected_indices, lora_scale_1, lora_scale_2, randomize_seed, seed, width, height, loras_state, progress=gr.Progress(track_tqdm=True)):
332
- if not selected_indices:
333
- raise gr.Error("You must select at least one LoRA before proceeding.")
334
-
335
- selected_loras = [loras_state[idx] for idx in selected_indices]
336
-
337
- # Build the prompt with trigger words
338
- prepends = []
339
- appends = []
340
- for lora in selected_loras:
341
- trigger_word = lora.get('trigger_word', '')
342
- if trigger_word:
343
- if lora.get("trigger_position") == "prepend":
344
- prepends.append(trigger_word)
345
- else:
346
- appends.append(trigger_word)
347
- prompt_mash = " ".join(prepends + [prompt] + appends)
348
- print("Prompt Mash: ", prompt_mash)
349
-
350
- # Unload previous LoRA weights
351
- with calculateDuration("Unloading LoRA"):
352
- pipe.unload_lora_weights()
353
-
354
- print(pipe.get_active_adapters())
355
-
356
- lora_names = []
357
- lora_weights = []
358
- with calculateDuration("Loading LoRA weights"):
359
- for idx, lora in enumerate(selected_loras):
360
- lora_name = f"lora_{idx}"
361
- lora_names.append(lora_name)
362
- print(f"Lora Name: {lora_name}")
363
- lora_weights.append(lora_scale_1 if idx == 0 else lora_scale_2)
364
- lora_path = lora['repo']
365
- weight_name = lora.get("weights")
366
- print(f"Lora Path: {lora_path}")
367
- pipe.load_lora_weights(
368
- lora_path,
369
- weight_name=weight_name if weight_name else None,
370
- low_cpu_mem_usage=True,
371
- adapter_name=lora_name
372
- )
373
-
374
- print("Loaded LoRAs:", lora_names)
375
- print("Adapter weights:", lora_weights)
376
-
377
- pipe.set_adapters(lora_names, adapter_weights=lora_weights)
378
-
379
- with calculateDuration("Randomizing seed"):
380
- if randomize_seed:
381
- seed = random.randint(0, MAX_SEED)
382
-
383
- images = generate_image(prompt_mash, steps, seed, cfg_scale, width, height, progress)
384
-
385
- return *images[:4], seed, gr.update(value="", visible=False)
386
-
387
- run_lora.zerogpu = True
388
-
389
- def get_huggingface_safetensors(link):
390
- split_link = link.split("/")
391
- if len(split_link) == 2:
392
- model_card = ModelCard.load(link)
393
- base_model = model_card.data.get("base_model")
394
- print(f"Base model: {base_model}")
395
- if base_model not in ["black-forest-labs/FLUX.1-dev", "black-forest-labs/FLUX.1-schnell"]:
396
- raise Exception("Not a FLUX LoRA!")
397
- image_path = model_card.data.get("widget", [{}])[0].get("output", {}).get("url", None)
398
- trigger_word = model_card.data.get("instance_prompt", "")
399
- image_url = f"https://huggingface.co/{link}/resolve/main/{image_path}" if image_path else None
400
- fs = HfFileSystem()
401
- safetensors_name = None
402
- try:
403
- list_of_files = fs.ls(link, detail=False)
404
- for file in list_of_files:
405
- if file.endswith(".safetensors"):
406
- safetensors_name = file.split("/")[-1]
407
- if not image_url and file.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
408
- image_elements = file.split("/")
409
- image_url = f"https://huggingface.co/{link}/resolve/main/{image_elements[-1]}"
410
- except Exception as e:
411
- print(e)
412
- raise gr.Error("Invalid Hugging Face repository with a *.safetensors LoRA")
413
- if not safetensors_name:
414
- raise gr.Error("No *.safetensors file found in the repository")
415
- return split_link[1], link, safetensors_name, trigger_word, image_url
416
- else:
417
- raise gr.Error("Invalid Hugging Face repository link")
418
-
419
- def check_custom_model(link):
420
- if link.endswith(".safetensors"):
421
- # Treat as direct link to the LoRA weights
422
- title = os.path.basename(link)
423
- repo = link
424
- path = None # No specific weight name
425
- trigger_word = ""
426
- image_url = None
427
- return title, repo, path, trigger_word, image_url
428
- elif link.startswith("https://"):
429
- if "huggingface.co" in link:
430
- link_split = link.split("huggingface.co/")
431
- return get_huggingface_safetensors(link_split[1])
432
- else:
433
- raise Exception("Unsupported URL")
434
- else:
435
- # Assume it's a Hugging Face model path
436
- return get_huggingface_safetensors(link)
437
-
438
- def update_history(new_image, history):
439
- """Updates the history gallery with the new image."""
440
- if history is None:
441
- history = []
442
- history.insert(0, new_image)
443
- return history
444
-
445
- css = '''
446
- #gen_btn{height: 100%}
447
- #title{text-align: center}
448
- #title h1{font-size: 3em; display:inline-flex; align-items:center}
449
- #title img{width: 100px; margin-right: 0.25em}
450
- #gallery .grid-wrap{height: 5vh}
451
- #lora_list{background: var(--block-background-fill);padding: 0 1em .3em; font-size: 90%}
452
- .custom_lora_card{margin-bottom: 1em}
453
- .card_internal{display: flex;height: 100px;margin-top: .5em}
454
- .card_internal img{margin-right: 1em}
455
- .styler{--form-gap-width: 0px !important}
456
- #progress{height:30px}
457
- #progress .generating{display:none}
458
- .progress-container {width: 100%;height: 30px;background-color: #f0f0f0;border-radius: 15px;overflow: hidden;margin-bottom: 20px}
459
- .progress-bar {height: 100%;background-color: #4f46e5;width: calc(var(--current) / var(--total) * 100%);transition: width 0.5s ease-in-out}
460
- #component-8, .button_total{height: 100%; align-self: stretch;}
461
- #loaded_loras [data-testid="block-info"]{font-size:80%}
462
- #custom_lora_structure{background: var(--block-background-fill)}
463
- #custom_lora_btn{margin-top: auto;margin-bottom: 11px}
464
- #random_btn{font-size: 300%}
465
- #component-11{align-self: stretch;}
466
- '''
467
-
468
- with gr.Blocks(css=css, delete_cache=(240, 240)) as app:
469
- title = gr.HTML(
470
- """<h1><img src="Keltezaa/Celebrity_LoRa_Mix" alt=" "> Celebrity LoRa Mix</h1><br><span style="
471
- margin-top: -25px !important;
472
- display: block;
473
- margin-left: 37px;
474
- ">SFW & NSFW FLUX LoRAs</span>""",
475
- elem_id="title",
476
- )
477
- loras_state = gr.State(loras)
478
- selected_indices = gr.State([])
479
- trigger_word_display = gr.Markdown("", elem_id="trigger_word")
480
-
481
- with gr.Row():
482
- with gr.Column(scale=3):
483
- prompt = gr.Textbox(label="Prompt", lines=1, placeholder="Type a prompt after selecting a LoRA")
484
-
485
- with gr.Row(elem_id="loaded_loras"):
486
-
487
- with gr.Column(scale=8):
488
- with gr.Row():
489
- with gr.Column(scale=0, min_width=50):
490
- lora_image_1 = gr.Image(label="LoRA 1 Image", interactive=False, width=50, show_label=False, show_share_button=False, show_download_button=False, show_fullscreen_button=False, height=50)
491
- with gr.Column(scale=3, min_width=100):
492
- selected_info_1 = gr.Markdown("Select a LoRA 1")
493
- with gr.Column(scale=5, min_width=50):
494
- lora_scale_1 = gr.Slider(label="LoRA 1 Scale", minimum=0, maximum=3, step=0.05, value=0.5)
495
- with gr.Row():
496
- remove_button_1 = gr.Button("Remove", size="sm")
497
-
498
- with gr.Column(scale=8):
499
- with gr.Row():
500
- with gr.Column(scale=0, min_width=50):
501
- lora_image_2 = gr.Image(label="LoRA 2 Image", interactive=False, width=50, show_label=False, show_share_button=False, show_download_button=False, show_fullscreen_button=False, height=50)
502
- with gr.Column(scale=3, min_width=100):
503
- selected_info_2 = gr.Markdown("Select a LoRA 2")
504
- with gr.Column(scale=5, min_width=50):
505
- lora_scale_2 = gr.Slider(label="LoRA 2 Scale", minimum=0, maximum=3, step=0.05, value=0.5)
506
- with gr.Row():
507
- remove_button_2 = gr.Button("Remove", size="sm")
508
-
509
- with gr.Column(scale=1,min_width=50):
510
- randomize_button = gr.Button("🎲", variant="secondary", scale=1, elem_id="random_btn")
511
-
512
- # with gr.Row(elem_id="loaded_loras"):
513
- # with gr.Column(scale=8):
514
- # with gr.Row():
515
- # with gr.Column(scale=0, min_width=50):
516
- # lora_image_3 = gr.Image(label="LoRA 3 Image", interactive=False, width=50, show_label=False, show_share_button=False, show_download_button=False, show_fullscreen_button=False, height=50)
517
- # with gr.Column(scale=3, min_width=100):
518
- # selected_info_3 = gr.Markdown("Select a LoRA 3")
519
- # with gr.Column(scale=5, min_width=50):
520
- # lora_scale_3 = gr.Slider(label="LoRA 3 Scale", minimum=0, maximum=3, step=0.05, value=0.5)
521
- # with gr.Row():
522
- # remove_button_3 = gr.Button("Remove", size="sm")
523
- # with gr.Column(scale=8):
524
- # with gr.Row():
525
- # with gr.Column(scale=0, min_width=50):
526
- # lora_image_4 = gr.Image(label="LoRA 4 Image", interactive=False, width=50, show_label=False, show_share_button=False, show_download_button=False, show_fullscreen_button=False, height=50)
527
- # with gr.Column(scale=3, min_width=100):
528
- # selected_info_4 = gr.Markdown("Select a LoRA 4")
529
- # with gr.Column(scale=5, min_width=150):
530
- # lora_scale_4 = gr.Slider(label="LoRA 4 Scale", minimum=0, maximum=3, step=0.05, value=0.5)
531
- # with gr.Row():
532
- # remove_button_4 = gr.Button("Remove", size="sm")
533
-
534
- with gr.Row():
535
- with gr.Accordion("Advanced Settings", open=True):
536
- #with gr.Row():
537
- # input_image = gr.Image(label="Input image", type="filepath", show_share_button=False)
538
- # 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)
539
- with gr.Column():
540
- with gr.Row():
541
- cfg_scale = gr.Slider(label="CFG Scale", minimum=1, maximum=20, step=0.5, value=7.5)
542
- steps = gr.Slider(label="Steps", minimum=1, maximum=50, step=1, value=28)
543
-
544
- with gr.Row():
545
- width = gr.Slider(label="Width", minimum=256, maximum=1536, step=64, value=768)
546
- height = gr.Slider(label="Height", minimum=256, maximum=1536, step=64, value=1024)
547
-
548
- with gr.Row():
549
- randomize_seed = gr.Checkbox(True, label="Randomize seed")
550
- seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0, randomize=True)
551
-
552
- with gr.Row():
553
- with gr.Column(scale=3):
554
- generate_button = gr.Button("Generate", variant="primary", elem_classes=["button_total"])
555
-
556
- with gr.Row():
557
- with gr.Column():
558
- with gr.Group():
559
- with gr.Row(elem_id="custom_lora_structure"):
560
- custom_lora = gr.Textbox(label="Custom LoRA", info="LoRA Hugging Face path or *.safetensors public URL", placeholder="multimodalart/vintage-ads-flux", scale=3, min_width=150)
561
- add_custom_lora_button = gr.Button("Add Custom LoRA", elem_id="custom_lora_btn", scale=2, min_width=150)
562
- remove_custom_lora_button = gr.Button("Remove Custom LoRA", visible=False)
563
- gr.Markdown("[Check the list of FLUX LoRAs](https://huggingface.co/models?other=base_model:adapter:black-forest-labs/FLUX.1-dev)", elem_id="lora_list")
564
- gallery = gr.Gallery(
565
- [(item["image"], item["title"]) for item in loras],
566
- label="Or pick from the gallery",
567
- allow_preview=False,
568
- columns=5,
569
- elem_id="gallery",
570
- show_share_button=False,
571
- interactive=False
572
- )
573
- with gr.Column():
574
- progress_bar = gr.Markdown(elem_id="progress", visible=False)
575
- results = [gr.Image(label=f"Image {i+1}", interactive=False, show_share_button=False) for i in range(4)]
576
-
577
- gallery.select(
578
- update_selection,
579
- inputs=[selected_indices, loras_state, width, height],
580
- outputs=[prompt, selected_info_1, selected_info_2, selected_indices, lora_scale_1, lora_scale_2, width, height, lora_image_1, lora_image_2])
581
- remove_button_1.click(
582
- remove_lora_1,
583
- inputs=[selected_indices, loras_state],
584
- outputs=[selected_info_1, selected_info_2, selected_indices, lora_scale_1, lora_scale_2, lora_image_1, lora_image_2]
585
- )
586
- remove_button_2.click(
587
- remove_lora_2,
588
- inputs=[selected_indices, loras_state],
589
- outputs=[selected_info_1, selected_info_2, selected_indices, lora_scale_1, lora_scale_2, lora_image_1, lora_image_2]
590
- )
591
- randomize_button.click(
592
- randomize_loras,
593
- inputs=[selected_indices, loras_state],
594
- outputs=[selected_info_1, selected_info_2, selected_indices, lora_scale_1, lora_scale_2, lora_image_1, lora_image_2, prompt]
595
- )
596
- add_custom_lora_button.click(
597
- add_custom_lora,
598
- inputs=[custom_lora, selected_indices, loras_state, gallery],
599
- outputs=[loras_state, gallery, selected_info_1, selected_info_2, selected_indices, lora_scale_1, lora_scale_2, lora_image_1, lora_image_2]
600
- )
601
- remove_custom_lora_button.click(
602
- remove_custom_lora,
603
- inputs=[selected_indices, loras_state, gallery],
604
- outputs=[loras_state, gallery, selected_info_1, selected_info_2, selected_indices, lora_scale_1, lora_scale_2, lora_image_1, lora_image_2]
605
- )
606
- gr.on(
607
- triggers=[generate_button.click, prompt.submit],
608
- fn=run_lora,
609
- inputs=[prompt, cfg_scale, steps, selected_indices, lora_scale_1, lora_scale_2, randomize_seed, seed, width, height, loras_state],
610
- outputs=[*results, seed, progress_bar]
611
- )
612
-
613
- app.queue()
614
- app.launch()