Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,21 +1,9 @@
|
|
1 |
import os
|
2 |
import gradio as gr
|
3 |
-
import json
|
4 |
-
import logging
|
5 |
import torch
|
6 |
-
from
|
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
|
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
|
@@ -23,274 +11,62 @@ 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 |
-
|
|
|
|
|
32 |
|
33 |
-
|
34 |
-
|
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(
|
74 |
-
|
|
|
|
|
|
|
|
|
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 |
-
#
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
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
|
|
|
212 |
|
213 |
-
|
214 |
-
|
215 |
-
#
|
216 |
-
|
217 |
-
#title img{width: 100px; margin-right: 0.5em}
|
218 |
-
#gallery .grid-wrap{height: 10vh}
|
219 |
-
#lora_list{background: var(--block-background-fill);padding: 0 1em .3em; font-size: 90%}
|
220 |
-
.card_internal{display: flex;height: 100px;margin-top: .5em}
|
221 |
-
.card_internal img{margin-right: 1em}
|
222 |
-
.styler{--form-gap-width: 0px !important}
|
223 |
-
#progress{height:30px}
|
224 |
-
#progress .generating{display:none}
|
225 |
-
.progress-container {width: 100%;height: 30px;background-color: #f0f0f0;border-radius: 15px;overflow: hidden;margin-bottom: 20px}
|
226 |
-
.progress-bar {height: 100%;background-color: #4f46e5;width: calc(var(--current) / var(--total) * 100%);transition: width 0.5s ease-in-out}
|
227 |
-
'''
|
228 |
-
with gr.Blocks(theme=gr.themes.Soft(), css=css) as app:
|
229 |
-
title = gr.HTML(
|
230 |
-
"""<h1><img src="https://huggingface.co/spaces/multimodalart/flux-lora-the-explorer/resolve/main/flux_lora.png" alt="LoRA"> FLUX LoRA the Explorer</h1>""",
|
231 |
-
elem_id="title",
|
232 |
-
)
|
233 |
-
selected_index = gr.State(None)
|
234 |
-
with gr.Row():
|
235 |
-
with gr.Column(scale=3):
|
236 |
-
prompt = gr.Textbox(label="Prompt", lines=1, placeholder="Type a prompt after selecting a LoRA")
|
237 |
-
with gr.Column(scale=1, elem_id="gen_column"):
|
238 |
-
generate_button = gr.Button("Generate", variant="primary", elem_id="gen_btn")
|
239 |
with gr.Row():
|
240 |
-
|
241 |
-
|
242 |
-
gallery = gr.Gallery(
|
243 |
-
[(item["image"], item["title"]) for item in loras],
|
244 |
-
label="LoRA Gallery",
|
245 |
-
allow_preview=False,
|
246 |
-
columns=3,
|
247 |
-
elem_id="gallery"
|
248 |
-
)
|
249 |
-
with gr.Group():
|
250 |
-
custom_lora = gr.Textbox(label="Custom LoRA", info="LoRA Hugging Face path", placeholder="multimodalart/vintage-ads-flux")
|
251 |
-
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")
|
252 |
-
custom_lora_info = gr.HTML(visible=False)
|
253 |
-
custom_lora_button = gr.Button("Remove custom LoRA", visible=False)
|
254 |
-
with gr.Column():
|
255 |
-
progress_bar = gr.Markdown(elem_id="progress",visible=False)
|
256 |
-
result = gr.Image(label="Generated Image")
|
257 |
-
|
258 |
with gr.Row():
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
height = gr.Slider(label="Height", minimum=256, maximum=1536, step=64, value=1024)
|
268 |
-
|
269 |
-
with gr.Row():
|
270 |
-
randomize_seed = gr.Checkbox(True, label="Randomize seed")
|
271 |
-
seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0, randomize=True)
|
272 |
-
lora_scale = gr.Slider(label="LoRA Scale", minimum=0, maximum=3, step=0.01, value=0.95)
|
273 |
-
|
274 |
-
gallery.select(
|
275 |
-
update_selection,
|
276 |
-
inputs=[width, height],
|
277 |
-
outputs=[prompt, selected_info, selected_index, width, height]
|
278 |
-
)
|
279 |
-
custom_lora.input(
|
280 |
-
add_custom_lora,
|
281 |
-
inputs=[custom_lora],
|
282 |
-
outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, prompt]
|
283 |
-
)
|
284 |
-
custom_lora_button.click(
|
285 |
-
remove_custom_lora,
|
286 |
-
outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, custom_lora]
|
287 |
-
)
|
288 |
-
gr.on(
|
289 |
-
triggers=[generate_button.click, prompt.submit],
|
290 |
fn=run_lora,
|
291 |
-
inputs=[prompt,
|
292 |
-
outputs=[
|
293 |
)
|
294 |
|
295 |
-
|
296 |
-
app.
|
|
|
|
1 |
import os
|
2 |
import gradio as gr
|
|
|
|
|
3 |
import torch
|
4 |
+
from diffusers import DiffusionPipeline, AutoencoderTiny
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
import random
|
6 |
+
import spaces
|
|
|
|
|
|
|
|
|
7 |
|
8 |
# Initialize the base model
|
9 |
dtype = torch.bfloat16
|
|
|
11 |
base_model = "black-forest-labs/FLUX.1-dev"
|
12 |
|
13 |
taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device)
|
|
|
14 |
pipe = DiffusionPipeline.from_pretrained(base_model, torch_dtype=dtype, vae=taef1).to(device)
|
15 |
|
16 |
MAX_SEED = 2**32-1
|
17 |
|
18 |
+
# Hidden variables (you would set these based on your specific LoRA)
|
19 |
+
LORA_PATH = "path/to/your/lora"
|
20 |
+
TRIGGER_WORD = "your_trigger_word"
|
21 |
|
22 |
+
# Load LoRA weights (do this once at startup)
|
23 |
+
pipe.load_lora_weights(LORA_PATH)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
|
25 |
@spaces.GPU(duration=70)
|
26 |
+
def generate_image(prompt, width, height):
|
27 |
+
# Combine prompt with trigger word
|
28 |
+
full_prompt = f"{TRIGGER_WORD} {prompt}"
|
29 |
+
|
30 |
+
# Set up generation parameters
|
31 |
+
seed = random.randint(0, MAX_SEED)
|
32 |
generator = torch.Generator(device="cuda").manual_seed(seed)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
|
34 |
+
# Generate image
|
35 |
+
image = pipe(
|
36 |
+
prompt=full_prompt,
|
37 |
+
num_inference_steps=28,
|
38 |
+
guidance_scale=3.5,
|
39 |
+
width=width,
|
40 |
+
height=height,
|
41 |
+
generator=generator,
|
42 |
+
).images[0]
|
43 |
+
|
44 |
+
return image
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
|
46 |
+
def run_lora(prompt, width, height):
|
47 |
+
return generate_image(prompt, width, height)
|
48 |
|
49 |
+
# Set up the Gradio interface
|
50 |
+
with gr.Blocks() as app:
|
51 |
+
gr.Markdown("# LoRA Image Generator")
|
52 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
with gr.Row():
|
54 |
+
prompt = gr.Textbox(label="Prompt", lines=3, placeholder="Enter your prompt here")
|
55 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
with gr.Row():
|
57 |
+
width = gr.Slider(label="Width", minimum=256, maximum=1024, step=64, value=512)
|
58 |
+
height = gr.Slider(label="Height", minimum=256, maximum=1024, step=64, value=512)
|
59 |
+
|
60 |
+
generate_button = gr.Button("Generate Image")
|
61 |
+
|
62 |
+
output_image = gr.Image(label="Generated Image")
|
63 |
+
|
64 |
+
generate_button.click(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
fn=run_lora,
|
66 |
+
inputs=[prompt, width, height],
|
67 |
+
outputs=[output_image]
|
68 |
)
|
69 |
|
70 |
+
if __name__ == "__main__":
|
71 |
+
app.queue()
|
72 |
+
app.launch()
|