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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
|
9 |
+
from live_preview_helpers import calculate_shift, retrieve_timesteps, flux_pipe_call_that_returns_an_iterable_of_images
|
10 |
+
|
11 |
+
from huggingface_hub import hf_hub_download, HfFileSystem, ModelCard, snapshot_download
|
12 |
+
import copy
|
13 |
+
import random
|
14 |
+
import time
|
15 |
+
|
16 |
+
# Load LoRAs from JSON file
|
17 |
+
with open('loras.json', 'r') as f:
|
18 |
+
loras = json.load(f)
|
19 |
+
|
20 |
+
# Initialize the base model
|
21 |
+
dtype = torch.bfloat16
|
22 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
23 |
+
base_model = "black-forest-labs/FLUX.1-dev"
|
24 |
+
|
25 |
+
taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device)
|
26 |
+
good_vae = AutoencoderKL.from_pretrained(base_model, subfolder="vae", torch_dtype=dtype).to(device)
|
27 |
+
pipe = DiffusionPipeline.from_pretrained(base_model, torch_dtype=dtype, vae=taef1).to(device)
|
28 |
+
|
29 |
+
MAX_SEED = 2**32-1
|
30 |
+
|
31 |
+
pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)
|
32 |
+
|
33 |
+
class calculateDuration:
|
34 |
+
def __init__(self, activity_name=""):
|
35 |
+
self.activity_name = activity_name
|
36 |
+
|
37 |
+
def __enter__(self):
|
38 |
+
self.start_time = time.time()
|
39 |
+
return self
|
40 |
+
|
41 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
42 |
+
self.end_time = time.time()
|
43 |
+
self.elapsed_time = self.end_time - self.start_time
|
44 |
+
if self.activity_name:
|
45 |
+
print(f"Elapsed time for {self.activity_name}: {self.elapsed_time:.6f} seconds")
|
46 |
+
else:
|
47 |
+
print(f"Elapsed time: {self.elapsed_time:.6f} seconds")
|
48 |
+
|
49 |
+
def update_selection(evt: gr.SelectData, width, height):
|
50 |
+
selected_lora = loras[evt.index]
|
51 |
+
new_placeholder = f"Type a prompt for {selected_lora['title']}"
|
52 |
+
lora_repo = selected_lora["repo"]
|
53 |
+
updated_text = f"### Selected: [{lora_repo}](https://huggingface.co/{lora_repo}) ✨"
|
54 |
+
if "aspect" in selected_lora:
|
55 |
+
if selected_lora["aspect"] == "portrait":
|
56 |
+
width = 768
|
57 |
+
height = 1024
|
58 |
+
elif selected_lora["aspect"] == "landscape":
|
59 |
+
width = 1024
|
60 |
+
height = 768
|
61 |
+
else:
|
62 |
+
width = 1024
|
63 |
+
height = 1024
|
64 |
+
return (
|
65 |
+
gr.update(placeholder=new_placeholder),
|
66 |
+
updated_text,
|
67 |
+
evt.index,
|
68 |
+
width,
|
69 |
+
height,
|
70 |
+
)
|
71 |
+
|
72 |
+
@spaces.GPU(duration=70)
|
73 |
+
def generate_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, progress):
|
74 |
+
pipe.to("cuda")
|
75 |
+
generator = torch.Generator(device="cuda").manual_seed(seed)
|
76 |
+
with calculateDuration("Generating image"):
|
77 |
+
# Generate image
|
78 |
+
for img in pipe.flux_pipe_call_that_returns_an_iterable_of_images(
|
79 |
+
prompt=prompt_mash,
|
80 |
+
num_inference_steps=steps,
|
81 |
+
guidance_scale=cfg_scale,
|
82 |
+
width=width,
|
83 |
+
height=height,
|
84 |
+
generator=generator,
|
85 |
+
joint_attention_kwargs={"scale": lora_scale},
|
86 |
+
output_type="pil",
|
87 |
+
good_vae=good_vae,
|
88 |
+
):
|
89 |
+
yield img
|
90 |
+
|
91 |
+
def run_lora(prompt, cfg_scale, steps, selected_index, randomize_seed, seed, width, height, lora_scale, progress=gr.Progress(track_tqdm=True)):
|
92 |
+
if selected_index is None:
|
93 |
+
raise gr.Error("You must select a LoRA before proceeding.")
|
94 |
+
selected_lora = loras[selected_index]
|
95 |
+
lora_path = selected_lora["repo"]
|
96 |
+
trigger_word = selected_lora["trigger_word"]
|
97 |
+
if(trigger_word):
|
98 |
+
if "trigger_position" in selected_lora:
|
99 |
+
if selected_lora["trigger_position"] == "prepend":
|
100 |
+
prompt_mash = f"{trigger_word} {prompt}"
|
101 |
+
else:
|
102 |
+
prompt_mash = f"{prompt} {trigger_word}"
|
103 |
+
else:
|
104 |
+
prompt_mash = f"{trigger_word} {prompt}"
|
105 |
+
else:
|
106 |
+
prompt_mash = prompt
|
107 |
+
|
108 |
+
with calculateDuration("Unloading LoRA"):
|
109 |
+
pipe.unload_lora_weights()
|
110 |
+
|
111 |
+
# Load LoRA weights
|
112 |
+
with calculateDuration(f"Loading LoRA weights for {selected_lora['title']}"):
|
113 |
+
if "weights" in selected_lora:
|
114 |
+
pipe.load_lora_weights(lora_path, weight_name=selected_lora["weights"])
|
115 |
+
else:
|
116 |
+
pipe.load_lora_weights(lora_path)
|
117 |
+
|
118 |
+
# Set random seed for reproducibility
|
119 |
+
with calculateDuration("Randomizing seed"):
|
120 |
+
if randomize_seed:
|
121 |
+
seed = random.randint(0, MAX_SEED)
|
122 |
+
|
123 |
+
image_generator = generate_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, progress)
|
124 |
+
|
125 |
+
# Consume the generator to get the final image
|
126 |
+
final_image = None
|
127 |
+
step_counter = 0
|
128 |
+
for image in image_generator:
|
129 |
+
step_counter+=1
|
130 |
+
final_image = image
|
131 |
+
progress_bar = f'<div class="progress-container"><div class="progress-bar" style="--current: {step_counter}; --total: {steps};"></div></div>'
|
132 |
+
yield image, seed, gr.update(value=progress_bar, visible=True)
|
133 |
+
|
134 |
+
yield final_image, seed, gr.update(value=progress_bar, visible=False)
|
135 |
+
|
136 |
+
def get_huggingface_safetensors(link):
|
137 |
+
split_link = link.split("/")
|
138 |
+
if(len(split_link) == 2):
|
139 |
+
model_card = ModelCard.load(link)
|
140 |
+
base_model = model_card.data.get("base_model")
|
141 |
+
print(base_model)
|
142 |
+
if((base_model != "black-forest-labs/FLUX.1-dev") and (base_model != "black-forest-labs/FLUX.1-schnell")):
|
143 |
+
raise Exception("Not a FLUX LoRA!")
|
144 |
+
image_path = model_card.data.get("widget", [{}])[0].get("output", {}).get("url", None)
|
145 |
+
trigger_word = model_card.data.get("instance_prompt", "")
|
146 |
+
image_url = f"https://huggingface.co/{link}/resolve/main/{image_path}" if image_path else None
|
147 |
+
fs = HfFileSystem()
|
148 |
+
try:
|
149 |
+
list_of_files = fs.ls(link, detail=False)
|
150 |
+
for file in list_of_files:
|
151 |
+
if(file.endswith(".safetensors")):
|
152 |
+
safetensors_name = file.split("/")[-1]
|
153 |
+
if (not image_url and file.lower().endswith((".jpg", ".jpeg", ".png", ".webp"))):
|
154 |
+
image_elements = file.split("/")
|
155 |
+
image_url = f"https://huggingface.co/{link}/resolve/main/{image_elements[-1]}"
|
156 |
+
except Exception as e:
|
157 |
+
print(e)
|
158 |
+
gr.Warning(f"You didn't include a link neither a valid Hugging Face repository with a *.safetensors LoRA")
|
159 |
+
raise Exception(f"You didn't include a link neither a valid Hugging Face repository with a *.safetensors LoRA")
|
160 |
+
return split_link[1], link, safetensors_name, trigger_word, image_url
|
161 |
+
|
162 |
+
def check_custom_model(link):
|
163 |
+
if(link.startswith("https://")):
|
164 |
+
if(link.startswith("https://huggingface.co") or link.startswith("https://www.huggingface.co")):
|
165 |
+
link_split = link.split("huggingface.co/")
|
166 |
+
return get_huggingface_safetensors(link_split[1])
|
167 |
+
else:
|
168 |
+
return get_huggingface_safetensors(link)
|
169 |
+
|
170 |
+
def add_custom_lora(custom_lora):
|
171 |
+
global loras
|
172 |
+
if(custom_lora):
|
173 |
+
try:
|
174 |
+
title, repo, path, trigger_word, image = check_custom_model(custom_lora)
|
175 |
+
print(f"Loaded custom LoRA: {repo}")
|
176 |
+
card = f'''
|
177 |
+
<div class="custom_lora_card">
|
178 |
+
<span>Loaded custom LoRA:</span>
|
179 |
+
<div class="card_internal">
|
180 |
+
<img src="{image}" />
|
181 |
+
<div>
|
182 |
+
<h3>{title}</h3>
|
183 |
+
<small>{"Using: <code><b>"+trigger_word+"</code></b> as the trigger word" if trigger_word else "No trigger word found. If there's a trigger word, include it in your prompt"}<br></small>
|
184 |
+
</div>
|
185 |
+
</div>
|
186 |
+
</div>
|
187 |
+
'''
|
188 |
+
existing_item_index = next((index for (index, item) in enumerate(loras) if item['repo'] == repo), None)
|
189 |
+
if(not existing_item_index):
|
190 |
+
new_item = {
|
191 |
+
"image": image,
|
192 |
+
"title": title,
|
193 |
+
"repo": repo,
|
194 |
+
"weights": path,
|
195 |
+
"trigger_word": trigger_word
|
196 |
+
}
|
197 |
+
print(new_item)
|
198 |
+
existing_item_index = len(loras)
|
199 |
+
loras.append(new_item)
|
200 |
+
|
201 |
+
return gr.update(visible=True, value=card), gr.update(visible=True), gr.Gallery(selected_index=None), f"Custom: {path}", existing_item_index, trigger_word
|
202 |
+
except Exception as e:
|
203 |
+
gr.Warning(f"Invalid LoRA: either you entered an invalid link, or a non-FLUX LoRA")
|
204 |
+
return gr.update(visible=True, value=f"Invalid LoRA: either you entered an invalid link, a non-FLUX LoRA"), gr.update(visible=True), gr.update(), "", None, ""
|
205 |
+
else:
|
206 |
+
return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
|
207 |
+
|
208 |
+
def remove_custom_lora():
|
209 |
+
return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
|
210 |
+
|
211 |
+
run_lora.zerogpu = True
|
212 |
+
|
213 |
+
css = """
|
214 |
+
footer {
|
215 |
+
visibility: hidden;
|
216 |
+
}
|
217 |
+
"""
|
218 |
+
|
219 |
+
with gr.Blocks(theme="Nymbo/Nymbo_Theme", css=css) as app:
|
220 |
+
|
221 |
+
selected_index = gr.State(None)
|
222 |
+
with gr.Row():
|
223 |
+
with gr.Column(scale=3):
|
224 |
+
prompt = gr.Textbox(label="Prompt", lines=1, placeholder="Type a prompt after selecting a LoRA")
|
225 |
+
with gr.Column(scale=1, elem_id="gen_column"):
|
226 |
+
generate_button = gr.Button("Generate", variant="primary", elem_id="gen_btn")
|
227 |
+
with gr.Row():
|
228 |
+
with gr.Column():
|
229 |
+
selected_info = gr.Markdown("")
|
230 |
+
gallery = gr.Gallery(
|
231 |
+
[(item["image"], item["title"]) for item in loras],
|
232 |
+
label="LoRA Gallery",
|
233 |
+
allow_preview=False,
|
234 |
+
columns=3,
|
235 |
+
elem_id="gallery"
|
236 |
+
)
|
237 |
+
with gr.Group():
|
238 |
+
custom_lora = gr.Textbox(label="Custom LoRA", info="LoRA Hugging Face path", placeholder="multimodalart/vintage-ads-flux")
|
239 |
+
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")
|
240 |
+
custom_lora_info = gr.HTML(visible=False)
|
241 |
+
custom_lora_button = gr.Button("Remove custom LoRA", visible=False)
|
242 |
+
with gr.Column():
|
243 |
+
progress_bar = gr.Markdown(elem_id="progress",visible=False)
|
244 |
+
result = gr.Image(label="Generated Image")
|
245 |
+
|
246 |
+
with gr.Row():
|
247 |
+
with gr.Accordion("Advanced Settings", open=False):
|
248 |
+
with gr.Column():
|
249 |
+
with gr.Row():
|
250 |
+
cfg_scale = gr.Slider(label="CFG Scale", minimum=1, maximum=20, step=0.5, value=3.5)
|
251 |
+
steps = gr.Slider(label="Steps", minimum=1, maximum=50, step=1, value=28)
|
252 |
+
|
253 |
+
with gr.Row():
|
254 |
+
width = gr.Slider(label="Width", minimum=256, maximum=1536, step=64, value=1024)
|
255 |
+
height = gr.Slider(label="Height", minimum=256, maximum=1536, step=64, value=1024)
|
256 |
+
|
257 |
+
with gr.Row():
|
258 |
+
randomize_seed = gr.Checkbox(True, label="Randomize seed")
|
259 |
+
seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0, randomize=True)
|
260 |
+
lora_scale = gr.Slider(label="LoRA Scale", minimum=0, maximum=3, step=0.01, value=0.95)
|
261 |
+
|
262 |
+
gallery.select(
|
263 |
+
update_selection,
|
264 |
+
inputs=[width, height],
|
265 |
+
outputs=[prompt, selected_info, selected_index, width, height]
|
266 |
+
)
|
267 |
+
custom_lora.input(
|
268 |
+
add_custom_lora,
|
269 |
+
inputs=[custom_lora],
|
270 |
+
outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, prompt]
|
271 |
+
)
|
272 |
+
custom_lora_button.click(
|
273 |
+
remove_custom_lora,
|
274 |
+
outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, custom_lora]
|
275 |
+
)
|
276 |
+
gr.on(
|
277 |
+
triggers=[generate_button.click, prompt.submit],
|
278 |
+
fn=run_lora,
|
279 |
+
inputs=[prompt, cfg_scale, steps, selected_index, randomize_seed, seed, width, height, lora_scale],
|
280 |
+
outputs=[result, seed, progress_bar]
|
281 |
+
)
|
282 |
+
|
283 |
+
app.queue()
|
284 |
+
app.launch()
|