Keltezaa commited on
Commit
41e3236
·
verified ·
1 Parent(s): a066858

Upload app.py

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