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