Keltezaa commited on
Commit
d51b973
·
verified ·
1 Parent(s): aa0f9fe

Delete app.py

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