Keltezaa commited on
Commit
c717eb7
·
verified ·
1 Parent(s): b329984

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -653
app.py DELETED
@@ -1,653 +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_images(prompt_mash, steps, seed, cfg_scale, width, height, progress):
297
- print("Generating multiple images...")
298
- pipe.to("cuda")
299
- images = []
300
- for _ in range(4): # Generate 4 images
301
- seed = random.randint(0, MAX_SEED)
302
- generator = torch.Generator(device="cuda").manual_seed(seed)
303
- with calculateDuration("Generating image"):
304
- img = next(
305
- pipe.flux_pipe_call_that_returns_an_iterable_of_images(
306
- prompt=prompt_mash,
307
- num_inference_steps=steps,
308
- guidance_scale=cfg_scale,
309
- width=width,
310
- height=height,
311
- generator=generator,
312
- joint_attention_kwargs={"scale": 1.0},
313
- output_type="pil",
314
- good_vae=good_vae,
315
- )
316
- )
317
- images.append((img, seed))
318
- return images
319
-
320
- #def generate_image_to_image(prompt_mash, image_input_path, image_strength, steps, cfg_scale, width, height, seed):
321
- # pipe_i2i.to("cuda")
322
- # generator = torch.Generator(device="cuda").manual_seed(seed)
323
- # image_input = load_image(image_input_path)
324
- # final_image = pipe_i2i(
325
- # prompt=prompt_mash,
326
- # image=image_input,
327
- # strength=image_strength,
328
- # num_inference_steps=steps,
329
- # guidance_scale=cfg_scale,
330
- # width=width,
331
- # height=height,
332
- # generator=generator,
333
- # joint_attention_kwargs={"scale": 1.0},
334
- # output_type="pil",
335
- # ).images[0]
336
- # return img
337
-
338
- @spaces.GPU(duration=75)
339
- def run_lora_multi(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)):
340
- if not selected_indices:
341
- raise gr.Error("You must select at least one LoRA before proceeding.")
342
-
343
- selected_loras = [loras_state[idx] for idx in selected_indices]
344
-
345
- # Build the prompt with trigger words
346
- prepends = []
347
- appends = []
348
- for lora in selected_loras:
349
- trigger_word = lora.get('trigger_word', '')
350
- if trigger_word:
351
- if lora.get("trigger_position") == "prepend":
352
- prepends.append(trigger_word)
353
- else:
354
- appends.append(trigger_word)
355
- prompt_mash = " ".join(prepends + [prompt] + appends)
356
- print("Prompt Mash: ", prompt_mash)
357
- print("seed: ", seed)
358
-
359
- # Unload previous LoRA weights
360
- with calculateDuration("Unloading LoRA"):
361
- pipe.unload_lora_weights()
362
- # pipe_i2i.unload_lora_weights()
363
-
364
- print(pipe.get_active_adapters())
365
- # Load LoRA weights with respective scales
366
- lora_names = []
367
- lora_weights = []
368
- with calculateDuration("Loading LoRA weights"):
369
- for idx, lora in enumerate(selected_loras):
370
- lora_name = f"lora_{idx}"
371
- lora_names.append(lora_name)
372
- print(f"Lora Name: {lora_name}")
373
- lora_weights.append(lora_scale_1 if idx == 0 else lora_scale_2)
374
- lora_path = lora['repo']
375
- weight_name = lora.get("weights")
376
- print(f"Lora Path: {lora_path}")
377
- pipe.load_lora_weights(
378
- lora_path,
379
- weight_name=weight_name if weight_name else None,
380
- low_cpu_mem_usage=True,
381
- adapter_name=lora_name
382
- )
383
- # if image_input is not None: pipe_i2i = pipe_to_use
384
- # else: pipe = pipe_to_use
385
- print("Loaded LoRAs:", lora_names)
386
- print("Adapter weights:", lora_weights)
387
- print("cfg_scale:", cfg_scale)
388
- print("steps:", steps)
389
- # if image_input is not None:
390
- # pipe_i2i.set_adapters(lora_names, adapter_weights=lora_weights)
391
- # else:
392
- pipe.set_adapters(lora_names, adapter_weights=lora_weights)
393
- # print(pipe.get_active_adapters())
394
- # Set random seed for reproducibility
395
- with calculateDuration("Randomizing seed"):
396
- if randomize_seed:
397
- seed = random.randint(0, MAX_SEED)
398
-
399
- # Generate image
400
- # if image_input is not None:
401
- # final_image = generate_image_to_image(prompt_mash, steps, cfg_scale, width, height, seed)
402
- # yield final_image, seed, gr.update(visible=False)
403
- # else:
404
- image_generator = generate_images(prompt_mash, steps, seed, cfg_scale, width, height, progress)
405
- return [(img, seed) for img, seed in images]
406
- # Consume the generator to get the final image
407
- # final_image = None
408
- step_counter = 0
409
- for image in image_generator:
410
- step_counter += 1
411
- final_image = images
412
- progress_bar = f'<div class="progress-container"><div class="progress-bar" style="--current: {step_counter}; --total: {steps};"></div></div>'
413
- yield images, seed, gr.update(value=progress_bar, visible=True)
414
- # yield final_image, seed, gr.update(value=progress_bar, visible=False)
415
-
416
- run_lora_multi.zerogpu = True
417
-
418
- def get_huggingface_safetensors(link):
419
- split_link = link.split("/")
420
- if len(split_link) == 2:
421
- model_card = ModelCard.load(link)
422
- base_model = model_card.data.get("base_model")
423
- print(f"Base model: {base_model}")
424
- if base_model not in ["black-forest-labs/FLUX.1-dev", "black-forest-labs/FLUX.1-schnell"]:
425
- raise Exception("Not a FLUX LoRA!")
426
- image_path = model_card.data.get("widget", [{}])[0].get("output", {}).get("url", None)
427
- trigger_word = model_card.data.get("instance_prompt", "")
428
- image_url = f"https://huggingface.co/{link}/resolve/main/{image_path}" if image_path else None
429
- fs = HfFileSystem()
430
- safetensors_name = None
431
- try:
432
- list_of_files = fs.ls(link, detail=False)
433
- for file in list_of_files:
434
- if file.endswith(".safetensors"):
435
- safetensors_name = file.split("/")[-1]
436
- if not image_url and file.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
437
- image_elements = file.split("/")
438
- image_url = f"https://huggingface.co/{link}/resolve/main/{image_elements[-1]}"
439
- except Exception as e:
440
- print(e)
441
- raise gr.Error("Invalid Hugging Face repository with a *.safetensors LoRA")
442
- if not safetensors_name:
443
- raise gr.Error("No *.safetensors file found in the repository")
444
- return split_link[1], link, safetensors_name, trigger_word, image_url
445
- else:
446
- raise gr.Error("Invalid Hugging Face repository link")
447
-
448
- def check_custom_model(link):
449
- if link.endswith(".safetensors"):
450
- # Treat as direct link to the LoRA weights
451
- title = os.path.basename(link)
452
- repo = link
453
- path = None # No specific weight name
454
- trigger_word = ""
455
- image_url = None
456
- return title, repo, path, trigger_word, image_url
457
- elif link.startswith("https://"):
458
- if "huggingface.co" in link:
459
- link_split = link.split("huggingface.co/")
460
- return get_huggingface_safetensors(link_split[1])
461
- else:
462
- raise Exception("Unsupported URL")
463
- else:
464
- # Assume it's a Hugging Face model path
465
- return get_huggingface_safetensors(link)
466
-
467
- def update_history(new_image, history):
468
- """Updates the history gallery with the new image."""
469
- if history is None:
470
- history = []
471
- history.insert(0, new_image)
472
- return history
473
-
474
- css = '''
475
- #gen_btn{height: 100%}
476
- #title{text-align: center}
477
- #title h1{font-size: 3em; display:inline-flex; align-items:center}
478
- #title img{width: 100px; margin-right: 0.25em}
479
- #gallery .grid-wrap{height: 5vh}
480
- #lora_list{background: var(--block-background-fill);padding: 0 1em .3em; font-size: 90%}
481
- .custom_lora_card{margin-bottom: 1em}
482
- .card_internal{display: flex;height: 100px;margin-top: .5em}
483
- .card_internal img{margin-right: 1em}
484
- .styler{--form-gap-width: 0px !important}
485
- #progress{height:30px}
486
- #progress .generating{display:none}
487
- .progress-container {width: 100%;height: 30px;background-color: #f0f0f0;border-radius: 15px;overflow: hidden;margin-bottom: 20px}
488
- .progress-bar {height: 100%;background-color: #4f46e5;width: calc(var(--current) / var(--total) * 100%);transition: width 0.5s ease-in-out}
489
- #component-8, .button_total{height: 100%; align-self: stretch;}
490
- #loaded_loras [data-testid="block-info"]{font-size:80%}
491
- #custom_lora_structure{background: var(--block-background-fill)}
492
- #custom_lora_btn{margin-top: auto;margin-bottom: 11px}
493
- #random_btn{font-size: 300%}
494
- #component-11{align-self: stretch;}
495
- '''
496
-
497
- with gr.Blocks(css=css, delete_cache=(240, 240)) as app:
498
- title = gr.HTML(
499
- """<h1><img src="Keltezaa/Celebrity_LoRa_Mix" alt=" "> Celebrity LoRa Mix</h1><br><span style="
500
- margin-top: -25px !important;
501
- display: block;
502
- margin-left: 37px;
503
- ">SFW & NSFW FLUX LoRAs</span>""",
504
- elem_id="title",
505
- )
506
- loras_state = gr.State(loras)
507
- selected_indices = gr.State([])
508
- trigger_word_display = gr.Markdown("", elem_id="trigger_word")
509
-
510
- with gr.Row():
511
- with gr.Column(scale=3):
512
- prompt = gr.Textbox(label="Prompt", lines=1, placeholder="Type a prompt after selecting a LoRA")
513
-
514
- with gr.Row(elem_id="loaded_loras"):
515
-
516
- with gr.Column(scale=8):
517
- with gr.Row():
518
- with gr.Column(scale=0, min_width=50):
519
- 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)
520
- with gr.Column(scale=3, min_width=100):
521
- selected_info_1 = gr.Markdown("Select a LoRA 1")
522
- with gr.Column(scale=5, min_width=50):
523
- lora_scale_1 = gr.Slider(label="LoRA 1 Scale", minimum=0, maximum=3, step=0.05, value=0.5)
524
- with gr.Row():
525
- remove_button_1 = gr.Button("Remove", size="sm")
526
-
527
- with gr.Column(scale=8):
528
- with gr.Row():
529
- with gr.Column(scale=0, min_width=50):
530
- 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)
531
- with gr.Column(scale=3, min_width=100):
532
- selected_info_2 = gr.Markdown("Select a LoRA 2")
533
- with gr.Column(scale=5, min_width=50):
534
- lora_scale_2 = gr.Slider(label="LoRA 2 Scale", minimum=0, maximum=3, step=0.05, value=0.5)
535
- with gr.Row():
536
- remove_button_2 = gr.Button("Remove", size="sm")
537
-
538
- with gr.Column(scale=1,min_width=50):
539
- randomize_button = gr.Button("🎲", variant="secondary", scale=1, elem_id="random_btn")
540
-
541
- # with gr.Row(elem_id="loaded_loras"):
542
- # with gr.Column(scale=8):
543
- # with gr.Row():
544
- # with gr.Column(scale=0, min_width=50):
545
- # 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)
546
- # with gr.Column(scale=3, min_width=100):
547
- # selected_info_3 = gr.Markdown("Select a LoRA 3")
548
- # with gr.Column(scale=5, min_width=50):
549
- # lora_scale_3 = gr.Slider(label="LoRA 3 Scale", minimum=0, maximum=3, step=0.05, value=0.5)
550
- # with gr.Row():
551
- # remove_button_3 = gr.Button("Remove", size="sm")
552
- # with gr.Column(scale=8):
553
- # with gr.Row():
554
- # with gr.Column(scale=0, min_width=50):
555
- # 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)
556
- # with gr.Column(scale=3, min_width=100):
557
- # selected_info_4 = gr.Markdown("Select a LoRA 4")
558
- # with gr.Column(scale=5, min_width=150):
559
- # lora_scale_4 = gr.Slider(label="LoRA 4 Scale", minimum=0, maximum=3, step=0.05, value=0.5)
560
- # with gr.Row():
561
- # remove_button_4 = gr.Button("Remove", size="sm")
562
-
563
- with gr.Row():
564
- with gr.Accordion("Advanced Settings", open=True):
565
- #with gr.Row():
566
- # input_image = gr.Image(label="Input image", type="filepath", show_share_button=False)
567
- # 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)
568
- with gr.Column():
569
- with gr.Row():
570
- cfg_scale = gr.Slider(label="CFG Scale", minimum=1, maximum=20, step=0.5, value=7.5)
571
- steps = gr.Slider(label="Steps", minimum=1, maximum=50, step=1, value=28)
572
-
573
- with gr.Row():
574
- width = gr.Slider(label="Width", minimum=256, maximum=1536, step=64, value=768)
575
- height = gr.Slider(label="Height", minimum=256, maximum=1536, step=64, value=1024)
576
-
577
- with gr.Row():
578
- randomize_seed = gr.Checkbox(True, label="Randomize seed")
579
- seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0, randomize=True)
580
-
581
- with gr.Row():
582
- with gr.Column(scale=3):
583
- generate_button = gr.Button("Generate", variant="primary", elem_classes=["button_total"])
584
-
585
- with gr.Row():
586
- with gr.Column():
587
- with gr.Group():
588
- with gr.Row(elem_id="custom_lora_structure"):
589
- 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)
590
- add_custom_lora_button = gr.Button("Add Custom LoRA", elem_id="custom_lora_btn", scale=2, min_width=150)
591
- remove_custom_lora_button = gr.Button("Remove Custom LoRA", visible=False)
592
- 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")
593
- gallery = gr.Gallery(
594
- [(item["image"], item["title"]) for item in loras],
595
- label="Or pick from the gallery",
596
- allow_preview=False,
597
- columns=5,
598
- elem_id="gallery",
599
- show_share_button=False,
600
- interactive=False
601
- )
602
- with gr.Column():
603
- progress_bar = gr.Markdown(elem_id="progress", visible=False)
604
- result = gr.Image(label="Generated Images", interactive=False, show_share_button=False)
605
- # with gr.Accordion("History", open=False):
606
- # history_gallery = gr.Gallery(label="History", columns=6, object_fit="contain", interactive=False)
607
-
608
- gallery.select(
609
- update_selection,
610
- inputs=[selected_indices, loras_state, width, height],
611
- outputs=[prompt, selected_info_1, selected_info_2, selected_indices, lora_scale_1, lora_scale_2, width, height, lora_image_1, lora_image_2])
612
- remove_button_1.click(
613
- remove_lora_1,
614
- inputs=[selected_indices, loras_state],
615
- outputs=[selected_info_1, selected_info_2, selected_indices, lora_scale_1, lora_scale_2, lora_image_1, lora_image_2]
616
- )
617
- remove_button_2.click(
618
- remove_lora_2,
619
- inputs=[selected_indices, loras_state],
620
- outputs=[selected_info_1, selected_info_2, selected_indices, lora_scale_1, lora_scale_2, lora_image_1, lora_image_2]
621
- )
622
- randomize_button.click(
623
- randomize_loras,
624
- inputs=[selected_indices, loras_state],
625
- outputs=[selected_info_1, selected_info_2, selected_indices, lora_scale_1, lora_scale_2, lora_image_1, lora_image_2, prompt]
626
- )
627
- add_custom_lora_button.click(
628
- add_custom_lora,
629
- inputs=[custom_lora, selected_indices, loras_state, gallery],
630
- outputs=[loras_state, gallery, selected_info_1, selected_info_2, selected_indices, lora_scale_1, lora_scale_2, lora_image_1, lora_image_2]
631
- )
632
- remove_custom_lora_button.click(
633
- remove_custom_lora,
634
- inputs=[selected_indices, loras_state, gallery],
635
- outputs=[loras_state, gallery, selected_info_1, selected_info_2, selected_indices, lora_scale_1, lora_scale_2, lora_image_1, lora_image_2]
636
- )
637
- gr.on(
638
- triggers=[generate_button.click, prompt.submit],
639
- fn=run_lora_multi,
640
- inputs=[prompt, cfg_scale, steps, selected_indices, lora_scale_1, lora_scale_2, randomize_seed, seed, width, height, loras_state],
641
- outputs=[
642
- result, seed, progress_bar,
643
- gr.Gallery(label="Generated Images"), # Display 4 images
644
- gr.Markdown(label="Seeds") # Display seeds used
645
- ]
646
- )#.then(
647
- # fn=lambda x, history: update_history(x, history),
648
- # inputs=[result, history_gallery],
649
- # outputs=history_gallery,
650
- #)
651
-
652
- app.queue()
653
- app.launch()