Spaces:
Running
on
Zero
Running
on
Zero
vincenthugging
commited on
Commit
•
ad8f2a1
1
Parent(s):
ab8b4ee
feat: add model select area
Browse files- app.py +317 -4
- flux_lora.png +0 -0
- live_preview_helpers.py +166 -0
- loras.json +54 -0
- requirements.txt +6 -0
app.py
CHANGED
@@ -1,7 +1,320 @@
|
|
|
|
1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
-
|
4 |
-
|
|
|
|
|
5 |
|
6 |
-
|
7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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,login
|
12 |
+
import copy
|
13 |
+
import random
|
14 |
+
import time
|
15 |
|
16 |
+
|
17 |
+
# get access token
|
18 |
+
access_token = os.environ.get("ACCESS_TOKEN")
|
19 |
+
# login with access token
|
20 |
+
if access_token:
|
21 |
+
login(token=access_token)
|
22 |
+
else:
|
23 |
+
print("warning: no access token found")
|
24 |
+
|
25 |
+
|
26 |
+
# Load LoRAs from JSON file
|
27 |
+
with open('loras.json', 'r') as f:
|
28 |
+
loras = json.load(f)
|
29 |
+
|
30 |
+
# Initialize the base model
|
31 |
+
dtype = torch.bfloat16
|
32 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
33 |
+
base_model = "black-forest-labs/FLUX.1-dev"
|
34 |
+
|
35 |
+
taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device)
|
36 |
+
good_vae = AutoencoderKL.from_pretrained(base_model, subfolder="vae", torch_dtype=dtype).to(device)
|
37 |
+
pipe = DiffusionPipeline.from_pretrained(base_model, torch_dtype=dtype, vae=taef1).to(device)
|
38 |
+
|
39 |
+
MAX_SEED = 2**32-1
|
40 |
+
|
41 |
+
pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)
|
42 |
+
|
43 |
+
class calculateDuration:
|
44 |
+
def __init__(self, activity_name=""):
|
45 |
+
self.activity_name = activity_name
|
46 |
+
|
47 |
+
def __enter__(self):
|
48 |
+
self.start_time = time.time()
|
49 |
+
return self
|
50 |
+
|
51 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
52 |
+
self.end_time = time.time()
|
53 |
+
self.elapsed_time = self.end_time - self.start_time
|
54 |
+
if self.activity_name:
|
55 |
+
print(f"Elapsed time for {self.activity_name}: {self.elapsed_time:.6f} seconds")
|
56 |
+
else:
|
57 |
+
print(f"Elapsed time: {self.elapsed_time:.6f} seconds")
|
58 |
+
|
59 |
+
def update_selection(evt: gr.SelectData, width, height):
|
60 |
+
selected_lora = loras[evt.index]
|
61 |
+
|
62 |
+
new_placeholder = selected_lora.get('placeholder', f"Type a prompt for {selected_lora['title']}")
|
63 |
+
example_prompt = selected_lora.get('example_prompt', '')
|
64 |
+
lora_repo = selected_lora["repo"]
|
65 |
+
updated_text = f"### Selected: [{lora_repo}](https://huggingface.co/{lora_repo}) ✨"
|
66 |
+
|
67 |
+
# 分辨率切换
|
68 |
+
if "aspect" in selected_lora:
|
69 |
+
if selected_lora["aspect"] == "portrait":
|
70 |
+
width = 768
|
71 |
+
height = 1024
|
72 |
+
elif selected_lora["aspect"] == "landscape":
|
73 |
+
width = 1024
|
74 |
+
height = 768
|
75 |
+
else:
|
76 |
+
width = 1024
|
77 |
+
height = 1024
|
78 |
+
|
79 |
+
gr.Info("LoRA selection updated") # 添加这行来触发 UI 刷新
|
80 |
+
|
81 |
+
return (
|
82 |
+
gr.update(placeholder=new_placeholder, value=example_prompt),
|
83 |
+
updated_text,
|
84 |
+
evt.index,
|
85 |
+
width,
|
86 |
+
height,
|
87 |
+
)
|
88 |
+
|
89 |
+
@spaces.GPU(duration=70)
|
90 |
+
def generate_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, progress):
|
91 |
+
pipe.to("cuda")
|
92 |
+
generator = torch.Generator(device="cuda").manual_seed(seed)
|
93 |
+
with calculateDuration("Generating image"):
|
94 |
+
# Generate image
|
95 |
+
for img in pipe.flux_pipe_call_that_returns_an_iterable_of_images(
|
96 |
+
prompt=prompt_mash,
|
97 |
+
num_inference_steps=steps,
|
98 |
+
guidance_scale=cfg_scale,
|
99 |
+
width=width,
|
100 |
+
height=height,
|
101 |
+
generator=generator,
|
102 |
+
joint_attention_kwargs={"scale": lora_scale},
|
103 |
+
output_type="pil",
|
104 |
+
good_vae=good_vae,
|
105 |
+
):
|
106 |
+
yield img
|
107 |
+
|
108 |
+
# 执行 run
|
109 |
+
def run_lora(prompt, cfg_scale, steps, selected_index, randomize_seed, seed, width, height, lora_scale, progress=gr.Progress(track_tqdm=True)):
|
110 |
+
if selected_index is None:
|
111 |
+
raise gr.Error("You must select a LoRA before proceeding.")
|
112 |
+
selected_lora = loras[selected_index]
|
113 |
+
|
114 |
+
lora_path = selected_lora["repo"]
|
115 |
+
trigger_word = selected_lora["trigger_word"]
|
116 |
+
|
117 |
+
if(trigger_word):
|
118 |
+
if "trigger_position" in selected_lora:
|
119 |
+
if selected_lora["trigger_position"] == "prepend":
|
120 |
+
prompt_mash = f"{trigger_word} {prompt}"
|
121 |
+
else:
|
122 |
+
prompt_mash = f"{prompt} {trigger_word}"
|
123 |
+
else:
|
124 |
+
prompt_mash = f"{trigger_word} {prompt}"
|
125 |
+
else:
|
126 |
+
prompt_mash = prompt
|
127 |
+
|
128 |
+
with calculateDuration("Unloading LoRA"):
|
129 |
+
pipe.unload_lora_weights()
|
130 |
+
|
131 |
+
# Load LoRA weights
|
132 |
+
with calculateDuration(f"Loading LoRA weights for {selected_lora['title']}"):
|
133 |
+
if "weights" in selected_lora:
|
134 |
+
pipe.load_lora_weights(lora_path, weight_name=selected_lora["weights"])
|
135 |
+
else:
|
136 |
+
pipe.load_lora_weights(lora_path)
|
137 |
+
|
138 |
+
# Set random seed for reproducibility
|
139 |
+
with calculateDuration("Randomizing seed"):
|
140 |
+
if randomize_seed:
|
141 |
+
seed = random.randint(0, MAX_SEED)
|
142 |
+
|
143 |
+
image_generator = generate_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, progress)
|
144 |
+
|
145 |
+
# Consume the generator to get the final image
|
146 |
+
final_image = None
|
147 |
+
step_counter = 0
|
148 |
+
for image in image_generator:
|
149 |
+
step_counter+=1
|
150 |
+
final_image = image
|
151 |
+
progress_bar = f'<div class="progress-container"><div class="progress-bar" style="--current: {step_counter}; --total: {steps};"></div></div>'
|
152 |
+
yield image, seed, gr.update(value=progress_bar, visible=True)
|
153 |
+
|
154 |
+
yield final_image, seed, gr.update(value=progress_bar, visible=False)
|
155 |
+
|
156 |
+
def get_huggingface_safetensors(link):
|
157 |
+
split_link = link.split("/")
|
158 |
+
if(len(split_link) == 2):
|
159 |
+
model_card = ModelCard.load(link)
|
160 |
+
base_model = model_card.data.get("base_model")
|
161 |
+
print(base_model)
|
162 |
+
if((base_model != "black-forest-labs/FLUX.1-dev") and (base_model != "black-forest-labs/FLUX.1-schnell")):
|
163 |
+
raise Exception("Not a FLUX LoRA!")
|
164 |
+
image_path = model_card.data.get("widget", [{}])[0].get("output", {}).get("url", None)
|
165 |
+
trigger_word = model_card.data.get("instance_prompt", "")
|
166 |
+
image_url = f"https://huggingface.co/{link}/resolve/main/{image_path}" if image_path else None
|
167 |
+
fs = HfFileSystem()
|
168 |
+
try:
|
169 |
+
list_of_files = fs.ls(link, detail=False)
|
170 |
+
for file in list_of_files:
|
171 |
+
if(file.endswith(".safetensors")):
|
172 |
+
safetensors_name = file.split("/")[-1]
|
173 |
+
if (not image_url and file.lower().endswith((".jpg", ".jpeg", ".png", ".webp"))):
|
174 |
+
image_elements = file.split("/")
|
175 |
+
image_url = f"https://huggingface.co/{link}/resolve/main/{image_elements[-1]}"
|
176 |
+
except Exception as e:
|
177 |
+
print(e)
|
178 |
+
gr.Warning(f"You didn't include a link neither a valid Hugging Face repository with a *.safetensors LoRA")
|
179 |
+
raise Exception(f"You didn't include a link neither a valid Hugging Face repository with a *.safetensors LoRA")
|
180 |
+
return split_link[1], link, safetensors_name, trigger_word, image_url
|
181 |
+
|
182 |
+
def check_custom_model(link):
|
183 |
+
if(link.startswith("https://")):
|
184 |
+
if(link.startswith("https://huggingface.co") or link.startswith("https://www.huggingface.co")):
|
185 |
+
link_split = link.split("huggingface.co/")
|
186 |
+
return get_huggingface_safetensors(link_split[1])
|
187 |
+
else:
|
188 |
+
return get_huggingface_safetensors(link)
|
189 |
+
|
190 |
+
def add_custom_lora(custom_lora):
|
191 |
+
global loras
|
192 |
+
if(custom_lora):
|
193 |
+
try:
|
194 |
+
title, repo, path, trigger_word, image = check_custom_model(custom_lora)
|
195 |
+
print(f"Loaded custom LoRA: {repo}")
|
196 |
+
card = f'''
|
197 |
+
<div class="custom_lora_card">
|
198 |
+
<span>Loaded custom LoRA:</span>
|
199 |
+
<div class="card_internal">
|
200 |
+
<img src="{image}" />
|
201 |
+
<div>
|
202 |
+
<h3>{title}</h3>
|
203 |
+
<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>
|
204 |
+
</div>
|
205 |
+
</div>
|
206 |
+
</div>
|
207 |
+
'''
|
208 |
+
existing_item_index = next((index for (index, item) in enumerate(loras) if item['repo'] == repo), None)
|
209 |
+
if(not existing_item_index):
|
210 |
+
new_item = {
|
211 |
+
"image": image,
|
212 |
+
"title": title,
|
213 |
+
"repo": repo,
|
214 |
+
"weights": path,
|
215 |
+
"trigger_word": trigger_word
|
216 |
+
}
|
217 |
+
print(new_item)
|
218 |
+
existing_item_index = len(loras)
|
219 |
+
loras.append(new_item)
|
220 |
+
|
221 |
+
return gr.update(visible=True, value=card), gr.update(visible=True), gr.Gallery(selected_index=None), f"Custom: {path}", existing_item_index, trigger_word
|
222 |
+
except Exception as e:
|
223 |
+
gr.Warning(f"Invalid LoRA: either you entered an invalid link, or a non-FLUX LoRA")
|
224 |
+
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, ""
|
225 |
+
else:
|
226 |
+
return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
|
227 |
+
|
228 |
+
def remove_custom_lora():
|
229 |
+
return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
|
230 |
+
|
231 |
+
run_lora.zerogpu = True
|
232 |
+
|
233 |
+
css = '''
|
234 |
+
#gen_btn{height: 100%}
|
235 |
+
#title{text-align: center}
|
236 |
+
#title h1{font-size: 3em; display:inline-flex; align-items:center}
|
237 |
+
#title img{width: 100px; margin-right: 0.5em}
|
238 |
+
#gallery .grid-wrap{height: 10vh}
|
239 |
+
#lora_list{background: var(--block-background-fill);padding: 0 1em .3em; font-size: 90%}
|
240 |
+
.card_internal{display: flex;height: 100px;margin-top: .5em}
|
241 |
+
.card_internal img{margin-right: 1em}
|
242 |
+
.styler{--form-gap-width: 0px !important}
|
243 |
+
#progress{height:30px}
|
244 |
+
#progress .generating{display:none}
|
245 |
+
.progress-container {width: 100%;height: 30px;background-color: #f0f0f0;border-radius: 15px;overflow: hidden;margin-bottom: 20px}
|
246 |
+
.progress-bar {height: 100%;background-color: #4f46e5;width: calc(var(--current) / var(--total) * 100%);transition: width 0.5s ease-in-out}
|
247 |
+
'''
|
248 |
+
with gr.Blocks(theme=gr.themes.Soft(), css=css) as app:
|
249 |
+
title = gr.HTML(
|
250 |
+
"""<h1><img src="https://huggingface.co/spaces/multimodalart/flux-lora-the-explorer/resolve/main/flux_lora.png" alt="LoRA"> FLUX LoRA the Explorer</h1>""",
|
251 |
+
elem_id="title",
|
252 |
+
)
|
253 |
+
selected_index = gr.State(None)
|
254 |
+
|
255 |
+
with gr.Row():
|
256 |
+
with gr.Column(scale=3):
|
257 |
+
prompt = gr.Textbox(label="Prompt", lines=1, placeholder="Type a prompt after selecting a LoRA")
|
258 |
+
with gr.Column(scale=1, elem_id="gen_column"):
|
259 |
+
generate_button = gr.Button("Generate", variant="primary", elem_id="gen_btn")
|
260 |
+
|
261 |
+
with gr.Row():
|
262 |
+
with gr.Column():
|
263 |
+
selected_info = gr.Markdown("")
|
264 |
+
gallery = gr.Gallery(
|
265 |
+
[(item["image"], item["title"]) for item in loras],
|
266 |
+
label="LoRA Gallery",
|
267 |
+
allow_preview=False,
|
268 |
+
columns=3,
|
269 |
+
elem_id="gallery"
|
270 |
+
)
|
271 |
+
with gr.Group():
|
272 |
+
custom_lora = gr.Textbox(label="Custom LoRA", info="LoRA Hugging Face path", placeholder="XLabs-AI/flux-RealismLora")
|
273 |
+
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")
|
274 |
+
custom_lora_info = gr.HTML(visible=False)
|
275 |
+
custom_lora_button = gr.Button("Remove custom LoRA", visible=False)
|
276 |
+
|
277 |
+
with gr.Accordion("Advanced Settings", open=False):
|
278 |
+
with gr.Row():
|
279 |
+
cfg_scale = gr.Slider(label="CFG Scale", minimum=1, maximum=20, step=0.5, value=3.5)
|
280 |
+
steps = gr.Slider(label="Steps", minimum=1, maximum=50, step=1, value=28)
|
281 |
+
|
282 |
+
with gr.Row():
|
283 |
+
width = gr.Slider(label="Width", minimum=256, maximum=1536, step=64, value=1024)
|
284 |
+
height = gr.Slider(label="Height", minimum=256, maximum=1536, step=64, value=1024)
|
285 |
+
|
286 |
+
with gr.Row():
|
287 |
+
randomize_seed = gr.Checkbox(True, label="Randomize seed")
|
288 |
+
seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0, randomize=True)
|
289 |
+
lora_scale = gr.Slider(label="LoRA Scale", minimum=0, maximum=3, step=0.01, value=0.95)
|
290 |
+
|
291 |
+
with gr.Column():
|
292 |
+
progress_bar = gr.Markdown(elem_id="progress",visible=False)
|
293 |
+
result = gr.Image(label="Generated Image")
|
294 |
+
|
295 |
+
|
296 |
+
|
297 |
+
|
298 |
+
gallery.select(
|
299 |
+
update_selection,
|
300 |
+
inputs=[width, height],
|
301 |
+
outputs=[prompt, selected_info, selected_index, width, height]
|
302 |
+
)
|
303 |
+
custom_lora.input(
|
304 |
+
add_custom_lora,
|
305 |
+
inputs=[custom_lora],
|
306 |
+
outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, prompt]
|
307 |
+
)
|
308 |
+
custom_lora_button.click(
|
309 |
+
remove_custom_lora,
|
310 |
+
outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, custom_lora]
|
311 |
+
)
|
312 |
+
gr.on(
|
313 |
+
triggers=[generate_button.click, prompt.submit],
|
314 |
+
fn=run_lora,
|
315 |
+
inputs=[prompt, cfg_scale, steps, selected_index, randomize_seed, seed, width, height, lora_scale],
|
316 |
+
outputs=[result, seed, progress_bar]
|
317 |
+
)
|
318 |
+
|
319 |
+
app.queue()
|
320 |
+
app.launch()
|
flux_lora.png
ADDED
live_preview_helpers.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import numpy as np
|
3 |
+
from diffusers import FluxPipeline, AutoencoderTiny, FlowMatchEulerDiscreteScheduler
|
4 |
+
from typing import Any, Dict, List, Optional, Union
|
5 |
+
|
6 |
+
# Helper functions
|
7 |
+
def calculate_shift(
|
8 |
+
image_seq_len,
|
9 |
+
base_seq_len: int = 256,
|
10 |
+
max_seq_len: int = 4096,
|
11 |
+
base_shift: float = 0.5,
|
12 |
+
max_shift: float = 1.16,
|
13 |
+
):
|
14 |
+
m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
|
15 |
+
b = base_shift - m * base_seq_len
|
16 |
+
mu = image_seq_len * m + b
|
17 |
+
return mu
|
18 |
+
|
19 |
+
def retrieve_timesteps(
|
20 |
+
scheduler,
|
21 |
+
num_inference_steps: Optional[int] = None,
|
22 |
+
device: Optional[Union[str, torch.device]] = None,
|
23 |
+
timesteps: Optional[List[int]] = None,
|
24 |
+
sigmas: Optional[List[float]] = None,
|
25 |
+
**kwargs,
|
26 |
+
):
|
27 |
+
if timesteps is not None and sigmas is not None:
|
28 |
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
29 |
+
if timesteps is not None:
|
30 |
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
31 |
+
timesteps = scheduler.timesteps
|
32 |
+
num_inference_steps = len(timesteps)
|
33 |
+
elif sigmas is not None:
|
34 |
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
35 |
+
timesteps = scheduler.timesteps
|
36 |
+
num_inference_steps = len(timesteps)
|
37 |
+
else:
|
38 |
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
39 |
+
timesteps = scheduler.timesteps
|
40 |
+
return timesteps, num_inference_steps
|
41 |
+
|
42 |
+
# FLUX pipeline function
|
43 |
+
@torch.inference_mode()
|
44 |
+
def flux_pipe_call_that_returns_an_iterable_of_images(
|
45 |
+
self,
|
46 |
+
prompt: Union[str, List[str]] = None,
|
47 |
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
48 |
+
height: Optional[int] = None,
|
49 |
+
width: Optional[int] = None,
|
50 |
+
num_inference_steps: int = 28,
|
51 |
+
timesteps: List[int] = None,
|
52 |
+
guidance_scale: float = 3.5,
|
53 |
+
num_images_per_prompt: Optional[int] = 1,
|
54 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
55 |
+
latents: Optional[torch.FloatTensor] = None,
|
56 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
57 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
58 |
+
output_type: Optional[str] = "pil",
|
59 |
+
return_dict: bool = True,
|
60 |
+
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
|
61 |
+
max_sequence_length: int = 512,
|
62 |
+
good_vae: Optional[Any] = None,
|
63 |
+
):
|
64 |
+
height = height or self.default_sample_size * self.vae_scale_factor
|
65 |
+
width = width or self.default_sample_size * self.vae_scale_factor
|
66 |
+
|
67 |
+
# 1. Check inputs
|
68 |
+
self.check_inputs(
|
69 |
+
prompt,
|
70 |
+
prompt_2,
|
71 |
+
height,
|
72 |
+
width,
|
73 |
+
prompt_embeds=prompt_embeds,
|
74 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
75 |
+
max_sequence_length=max_sequence_length,
|
76 |
+
)
|
77 |
+
|
78 |
+
self._guidance_scale = guidance_scale
|
79 |
+
self._joint_attention_kwargs = joint_attention_kwargs
|
80 |
+
self._interrupt = False
|
81 |
+
|
82 |
+
# 2. Define call parameters
|
83 |
+
batch_size = 1 if isinstance(prompt, str) else len(prompt)
|
84 |
+
device = self._execution_device
|
85 |
+
|
86 |
+
# 3. Encode prompt
|
87 |
+
lora_scale = joint_attention_kwargs.get("scale", None) if joint_attention_kwargs is not None else None
|
88 |
+
prompt_embeds, pooled_prompt_embeds, text_ids = self.encode_prompt(
|
89 |
+
prompt=prompt,
|
90 |
+
prompt_2=prompt_2,
|
91 |
+
prompt_embeds=prompt_embeds,
|
92 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
93 |
+
device=device,
|
94 |
+
num_images_per_prompt=num_images_per_prompt,
|
95 |
+
max_sequence_length=max_sequence_length,
|
96 |
+
lora_scale=lora_scale,
|
97 |
+
)
|
98 |
+
# 4. Prepare latent variables
|
99 |
+
num_channels_latents = self.transformer.config.in_channels // 4
|
100 |
+
latents, latent_image_ids = self.prepare_latents(
|
101 |
+
batch_size * num_images_per_prompt,
|
102 |
+
num_channels_latents,
|
103 |
+
height,
|
104 |
+
width,
|
105 |
+
prompt_embeds.dtype,
|
106 |
+
device,
|
107 |
+
generator,
|
108 |
+
latents,
|
109 |
+
)
|
110 |
+
# 5. Prepare timesteps
|
111 |
+
sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
|
112 |
+
image_seq_len = latents.shape[1]
|
113 |
+
mu = calculate_shift(
|
114 |
+
image_seq_len,
|
115 |
+
self.scheduler.config.base_image_seq_len,
|
116 |
+
self.scheduler.config.max_image_seq_len,
|
117 |
+
self.scheduler.config.base_shift,
|
118 |
+
self.scheduler.config.max_shift,
|
119 |
+
)
|
120 |
+
timesteps, num_inference_steps = retrieve_timesteps(
|
121 |
+
self.scheduler,
|
122 |
+
num_inference_steps,
|
123 |
+
device,
|
124 |
+
timesteps,
|
125 |
+
sigmas,
|
126 |
+
mu=mu,
|
127 |
+
)
|
128 |
+
self._num_timesteps = len(timesteps)
|
129 |
+
|
130 |
+
# Handle guidance
|
131 |
+
guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32).expand(latents.shape[0]) if self.transformer.config.guidance_embeds else None
|
132 |
+
|
133 |
+
# 6. Denoising loop
|
134 |
+
for i, t in enumerate(timesteps):
|
135 |
+
if self.interrupt:
|
136 |
+
continue
|
137 |
+
|
138 |
+
timestep = t.expand(latents.shape[0]).to(latents.dtype)
|
139 |
+
|
140 |
+
noise_pred = self.transformer(
|
141 |
+
hidden_states=latents,
|
142 |
+
timestep=timestep / 1000,
|
143 |
+
guidance=guidance,
|
144 |
+
pooled_projections=pooled_prompt_embeds,
|
145 |
+
encoder_hidden_states=prompt_embeds,
|
146 |
+
txt_ids=text_ids,
|
147 |
+
img_ids=latent_image_ids,
|
148 |
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
149 |
+
return_dict=False,
|
150 |
+
)[0]
|
151 |
+
# Yield intermediate result
|
152 |
+
latents_for_image = self._unpack_latents(latents, height, width, self.vae_scale_factor)
|
153 |
+
latents_for_image = (latents_for_image / self.vae.config.scaling_factor) + self.vae.config.shift_factor
|
154 |
+
image = self.vae.decode(latents_for_image, return_dict=False)[0]
|
155 |
+
yield self.image_processor.postprocess(image, output_type=output_type)[0]
|
156 |
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
157 |
+
torch.cuda.empty_cache()
|
158 |
+
|
159 |
+
|
160 |
+
# Final image using good_vae
|
161 |
+
latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
|
162 |
+
latents = (latents / good_vae.config.scaling_factor) + good_vae.config.shift_factor
|
163 |
+
image = good_vae.decode(latents, return_dict=False)[0]
|
164 |
+
self.maybe_free_model_hooks()
|
165 |
+
torch.cuda.empty_cache()
|
166 |
+
yield self.image_processor.postprocess(image, output_type=output_type)[0]
|
loras.json
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[
|
2 |
+
{
|
3 |
+
"image": "https://cdn-uploads.huggingface.co/production/uploads/6413514705147e9f74df6fec/HOki0-bZbfVsmZ06vYQ3p.jpeg",
|
4 |
+
"title": "GYY",
|
5 |
+
"repo": "vincenthugging/flux-dev-lora-gyy",
|
6 |
+
"trigger_word": "gyy",
|
7 |
+
"example_prompt": "A photo of gyy,holding a sign that says 'Love is Love'",
|
8 |
+
"placeholder": "Trigger word: gyy",
|
9 |
+
"aspect": "portrait"
|
10 |
+
},
|
11 |
+
{
|
12 |
+
"image": "https://cdn-uploads.huggingface.co/production/uploads/6413514705147e9f74df6fec/bui1QnJKX0xv76ThfP-1d.png",
|
13 |
+
"title": "Leijun",
|
14 |
+
"repo": "vincenthugging/flux-lora-leijun",
|
15 |
+
"trigger_word": "leijun",
|
16 |
+
"example_prompt": "A photo of leijun, about 50 years old, at a product launch event",
|
17 |
+
"placeholder": "Trigger word: leijun",
|
18 |
+
"aspect": "portrait"
|
19 |
+
},
|
20 |
+
{
|
21 |
+
"image": "https://cdn-uploads.huggingface.co/production/uploads/6413514705147e9f74df6fec/iNzpVNTfg4HJ_PCtgdl-_.jpeg",
|
22 |
+
"title": "Ayaka miyoshi",
|
23 |
+
"repo": "vincenthugging/flux-dev-lora-miyoshi",
|
24 |
+
"trigger_word": "miyoshi",
|
25 |
+
"example_prompt": "A glamorous shot of miyoshi on the red carpet",
|
26 |
+
"placeholder": "Trigger word: miyoshi",
|
27 |
+
"aspect": "portrait"
|
28 |
+
},
|
29 |
+
{
|
30 |
+
"image": "https://cdn-uploads.huggingface.co/production/uploads/6413514705147e9f74df6fec/NmBmH6VZ0HV2OrCdeg18L.jpeg",
|
31 |
+
"title": "Liuyifei",
|
32 |
+
"repo": "vincenthugging/flux-dev-lora-lyf",
|
33 |
+
"trigger_word": "lyf",
|
34 |
+
"example_prompt": "A close-up portrait of lyf in a traditional Chinese outfit",
|
35 |
+
"placeholder": "Trigger word: lyf",
|
36 |
+
"aspect": "portrait"
|
37 |
+
},
|
38 |
+
{
|
39 |
+
"image": "https://cdn-uploads.huggingface.co/production/uploads/6413514705147e9f74df6fec/4sVKcWUlZ2oglX-8oFWKV.png",
|
40 |
+
"title": "Vincentyang ",
|
41 |
+
"repo": "vincenthugging/flux-dev-lora-vincentyang",
|
42 |
+
"trigger_word": "vincentyang",
|
43 |
+
"example_prompt": "Photo of vincentyang,young and handsome",
|
44 |
+
"placeholder": "Trigger word: vincentyang"
|
45 |
+
},
|
46 |
+
|
47 |
+
{
|
48 |
+
"image": "https://huggingface.co/Shakker-Labs/AWPortrait-FL/resolve/main/cover.jpeg",
|
49 |
+
"title": "AWPortrait FL",
|
50 |
+
"repo": "Shakker-Labs/AWPortrait-FL",
|
51 |
+
"weights": "AWPortrait-FL-lora.safetensors",
|
52 |
+
"trigger_word": ""
|
53 |
+
}
|
54 |
+
]
|
requirements.txt
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
torch
|
2 |
+
git+https://github.com/huggingface/diffusers@3b604e8c384631e1f66a4fd9076ed5e7e2b08686
|
3 |
+
spaces
|
4 |
+
transformers
|
5 |
+
peft
|
6 |
+
sentencepiece
|