Keltezaa commited on
Commit
b44a250
·
verified ·
1 Parent(s): e043aa2

Delete app.py

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