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