jojosims4557 commited on
Commit
917f044
1 Parent(s): 5c8e6d7

create app.py

Browse files
Files changed (1) hide show
  1. app.py +340 -0
app.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 diffusers.utils import load_image
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
+ pipe_i2i = AutoPipelineForImage2Image.from_pretrained(base_model,
29
+ vae=good_vae,
30
+ transformer=pipe.transformer,
31
+ text_encoder=pipe.text_encoder,
32
+ tokenizer=pipe.tokenizer,
33
+ text_encoder_2=pipe.text_encoder_2,
34
+ tokenizer_2=pipe.tokenizer_2,
35
+ torch_dtype=dtype
36
+ )
37
+
38
+ MAX_SEED = 2**32-1
39
+
40
+ pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)
41
+
42
+ class calculateDuration:
43
+ def __init__(self, activity_name=""):
44
+ self.activity_name = activity_name
45
+
46
+ def __enter__(self):
47
+ self.start_time = time.time()
48
+ return self
49
+
50
+ def __exit__(self, exc_type, exc_value, traceback):
51
+ self.end_time = time.time()
52
+ self.elapsed_time = self.end_time - self.start_time
53
+ if self.activity_name:
54
+ print(f"Elapsed time for {self.activity_name}: {self.elapsed_time:.6f} seconds")
55
+ else:
56
+ print(f"Elapsed time: {self.elapsed_time:.6f} seconds")
57
+
58
+ def update_selection(evt: gr.SelectData, width, height):
59
+ selected_lora = loras[evt.index]
60
+ new_placeholder = f"Type a prompt for {selected_lora['title']}"
61
+ lora_repo = selected_lora["repo"]
62
+ updated_text = f"### Selected: [{lora_repo}](https://huggingface.co/{lora_repo}) ✨"
63
+ if "aspect" in selected_lora:
64
+ if selected_lora["aspect"] == "portrait":
65
+ width = 768
66
+ height = 1024
67
+ elif selected_lora["aspect"] == "landscape":
68
+ width = 1024
69
+ height = 768
70
+ else:
71
+ width = 1024
72
+ height = 1024
73
+ return (
74
+ gr.update(placeholder=new_placeholder),
75
+ updated_text,
76
+ evt.index,
77
+ width,
78
+ height,
79
+ )
80
+
81
+ @spaces.GPU(duration=70)
82
+ def generate_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, progress):
83
+ pipe.to("cuda")
84
+ generator = torch.Generator(device="cuda").manual_seed(seed)
85
+ with calculateDuration("Generating image"):
86
+ # Generate image
87
+ for img in pipe.flux_pipe_call_that_returns_an_iterable_of_images(
88
+ prompt=prompt_mash,
89
+ num_inference_steps=steps,
90
+ guidance_scale=cfg_scale,
91
+ width=width,
92
+ height=height,
93
+ generator=generator,
94
+ joint_attention_kwargs={"scale": lora_scale},
95
+ output_type="pil",
96
+ good_vae=good_vae,
97
+ ):
98
+ yield img
99
+
100
+ def generate_image_to_image(prompt_mash, image_input_path, image_strength, steps, cfg_scale, width, height, lora_scale, seed):
101
+ generator = torch.Generator(device="cuda").manual_seed(seed)
102
+ pipe_i2i.to("cuda")
103
+ image_input = load_image(image_input_path)
104
+ final_image = pipe_i2i(
105
+ prompt=prompt_mash,
106
+ image=image_input,
107
+ strength=image_strength,
108
+ num_inference_steps=steps,
109
+ guidance_scale=cfg_scale,
110
+ width=width,
111
+ height=height,
112
+ generator=generator,
113
+ joint_attention_kwargs={"scale": lora_scale},
114
+ output_type="pil",
115
+ ).images[0]
116
+ return final_image
117
+
118
+ @spaces.GPU(duration=70)
119
+ def run_lora(prompt, image_input, image_strength, cfg_scale, steps, selected_index, randomize_seed, seed, width, height, lora_scale, progress=gr.Progress(track_tqdm=True)):
120
+ if selected_index is None:
121
+ raise gr.Error("You must select a LoRA before proceeding.")
122
+ selected_lora = loras[selected_index]
123
+ lora_path = selected_lora["repo"]
124
+ trigger_word = selected_lora["trigger_word"]
125
+ if(trigger_word):
126
+ if "trigger_position" in selected_lora:
127
+ if selected_lora["trigger_position"] == "prepend":
128
+ prompt_mash = f"{trigger_word} {prompt}"
129
+ else:
130
+ prompt_mash = f"{prompt} {trigger_word}"
131
+ else:
132
+ prompt_mash = f"{trigger_word} {prompt}"
133
+ else:
134
+ prompt_mash = prompt
135
+
136
+ with calculateDuration("Unloading LoRA"):
137
+ pipe.unload_lora_weights()
138
+ pipe_i2i.unload_lora_weights()
139
+
140
+ # Load LoRA weights
141
+ with calculateDuration(f"Loading LoRA weights for {selected_lora['title']}"):
142
+ pipe_to_use = pipe_i2i if image_input is not None else pipe
143
+ weight_name = selected_lora.get("weights", None)
144
+
145
+ pipe_to_use.load_lora_weights(
146
+ lora_path,
147
+ weight_name=weight_name,
148
+ low_cpu_mem_usage=True
149
+ )
150
+
151
+ # Set random seed for reproducibility
152
+ with calculateDuration("Randomizing seed"):
153
+ if randomize_seed:
154
+ seed = random.randint(0, MAX_SEED)
155
+
156
+ if(image_input is not None):
157
+
158
+ final_image = generate_image_to_image(prompt_mash, image_input, image_strength, steps, cfg_scale, width, height, lora_scale, seed)
159
+ yield final_image, seed, gr.update(visible=False)
160
+ else:
161
+ image_generator = generate_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, progress)
162
+
163
+ # Consume the generator to get the final image
164
+ final_image = None
165
+ step_counter = 0
166
+ for image in image_generator:
167
+ step_counter+=1
168
+ final_image = image
169
+ progress_bar = f'<div class="progress-container"><div class="progress-bar" style="--current: {step_counter}; --total: {steps};"></div></div>'
170
+ yield image, seed, gr.update(value=progress_bar, visible=True)
171
+
172
+ yield final_image, seed, gr.update(value=progress_bar, visible=False)
173
+
174
+ def get_huggingface_safetensors(link):
175
+ split_link = link.split("/")
176
+ if(len(split_link) == 2):
177
+ model_card = ModelCard.load(link)
178
+ base_model = model_card.data.get("base_model")
179
+ print(base_model)
180
+ if((base_model != "black-forest-labs/FLUX.1-dev") and (base_model != "black-forest-labs/FLUX.1-schnell")):
181
+ raise Exception("Not a FLUX LoRA!")
182
+ image_path = model_card.data.get("widget", [{}])[0].get("output", {}).get("url", None)
183
+ trigger_word = model_card.data.get("instance_prompt", "")
184
+ image_url = f"https://huggingface.co/{link}/resolve/main/{image_path}" if image_path else None
185
+ fs = HfFileSystem()
186
+ try:
187
+ list_of_files = fs.ls(link, detail=False)
188
+ for file in list_of_files:
189
+ if(file.endswith(".safetensors")):
190
+ safetensors_name = file.split("/")[-1]
191
+ if (not image_url and file.lower().endswith((".jpg", ".jpeg", ".png", ".webp"))):
192
+ image_elements = file.split("/")
193
+ image_url = f"https://huggingface.co/{link}/resolve/main/{image_elements[-1]}"
194
+ except Exception as e:
195
+ print(e)
196
+ gr.Warning(f"You didn't include a link neither a valid Hugging Face repository with a *.safetensors LoRA")
197
+ raise Exception(f"You didn't include a link neither a valid Hugging Face repository with a *.safetensors LoRA")
198
+ return split_link[1], link, safetensors_name, trigger_word, image_url
199
+
200
+ def check_custom_model(link):
201
+ if(link.startswith("https://")):
202
+ if(link.startswith("https://huggingface.co") or link.startswith("https://www.huggingface.co")):
203
+ link_split = link.split("huggingface.co/")
204
+ return get_huggingface_safetensors(link_split[1])
205
+ else:
206
+ return get_huggingface_safetensors(link)
207
+
208
+ def add_custom_lora(custom_lora):
209
+ global loras
210
+ if(custom_lora):
211
+ try:
212
+ title, repo, path, trigger_word, image = check_custom_model(custom_lora)
213
+ print(f"Loaded custom LoRA: {repo}")
214
+ card = f'''
215
+ <div class="custom_lora_card">
216
+ <span>Loaded custom LoRA:</span>
217
+ <div class="card_internal">
218
+ <img src="{image}" />
219
+ <div>
220
+ <h3>{title}</h3>
221
+ <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>
222
+ </div>
223
+ </div>
224
+ </div>
225
+ '''
226
+ existing_item_index = next((index for (index, item) in enumerate(loras) if item['repo'] == repo), None)
227
+ if(not existing_item_index):
228
+ new_item = {
229
+ "image": image,
230
+ "title": title,
231
+ "repo": repo,
232
+ "weights": path,
233
+ "trigger_word": trigger_word
234
+ }
235
+ print(new_item)
236
+ existing_item_index = len(loras)
237
+ loras.append(new_item)
238
+
239
+ return gr.update(visible=True, value=card), gr.update(visible=True), gr.Gallery(selected_index=None), f"Custom: {path}", existing_item_index, trigger_word
240
+ except Exception as e:
241
+ gr.Warning(f"Invalid LoRA: either you entered an invalid link, or a non-FLUX LoRA")
242
+ 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, ""
243
+ else:
244
+ return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
245
+
246
+ def remove_custom_lora():
247
+ return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
248
+
249
+ run_lora.zerogpu = True
250
+
251
+ css = '''
252
+ #gen_btn{height: 100%}
253
+ #gen_column{align-self: stretch}
254
+ #title{text-align: center}
255
+ #title h1{font-size: 3em; display:inline-flex; align-items:center}
256
+ #title img{width: 100px; margin-right: 0.5em}
257
+ #gallery .grid-wrap{height: 10vh}
258
+ #lora_list{background: var(--block-background-fill);padding: 0 1em .3em; font-size: 90%}
259
+ .card_internal{display: flex;height: 100px;margin-top: .5em}
260
+ .card_internal img{margin-right: 1em}
261
+ .styler{--form-gap-width: 0px !important}
262
+ #progress{height:30px}
263
+ #progress .generating{display:none}
264
+ .progress-container {width: 100%;height: 30px;background-color: #f0f0f0;border-radius: 15px;overflow: hidden;margin-bottom: 20px}
265
+ .progress-bar {height: 100%;background-color: #4f46e5;width: calc(var(--current) / var(--total) * 100%);transition: width 0.5s ease-in-out}
266
+ '''
267
+ font=[gr.themes.GoogleFont("Source Sans Pro"), "Arial", "sans-serif"]
268
+ with gr.Blocks(theme=gr.themes.Soft(font=font), css=css, delete_cache=(60, 60)) as app:
269
+ title = gr.HTML(
270
+ """<h1><img src="https://huggingface.co/spaces/multimodalart/flux-lora-the-explorer/resolve/main/flux_lora.png" alt="LoRA"> FLUX LoRA the Explorer</h1>""",
271
+ elem_id="title",
272
+ )
273
+ selected_index = gr.State(None)
274
+ with gr.Row():
275
+ with gr.Column(scale=3):
276
+ prompt = gr.Textbox(label="Prompt", lines=1, placeholder="Type a prompt after selecting a LoRA")
277
+ with gr.Column(scale=1, elem_id="gen_column"):
278
+ generate_button = gr.Button("Generate", variant="primary", elem_id="gen_btn")
279
+ with gr.Row():
280
+ with gr.Column():
281
+ selected_info = gr.Markdown("")
282
+ gallery = gr.Gallery(
283
+ [(item["image"], item["title"]) for item in loras],
284
+ label="LoRA Gallery",
285
+ allow_preview=False,
286
+ columns=3,
287
+ elem_id="gallery",
288
+ show_share_button=False
289
+ )
290
+ with gr.Group():
291
+ custom_lora = gr.Textbox(label="Custom LoRA", info="LoRA Hugging Face path", placeholder="multimodalart/vintage-ads-flux")
292
+ 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")
293
+ custom_lora_info = gr.HTML(visible=False)
294
+ custom_lora_button = gr.Button("Remove custom LoRA", visible=False)
295
+ with gr.Column():
296
+ progress_bar = gr.Markdown(elem_id="progress",visible=False)
297
+ result = gr.Image(label="Generated Image")
298
+
299
+ with gr.Row():
300
+ with gr.Accordion("Advanced Settings", open=False):
301
+ with gr.Row():
302
+ input_image = gr.Image(label="Input image", type="filepath")
303
+ 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)
304
+ with gr.Column():
305
+ with gr.Row():
306
+ cfg_scale = gr.Slider(label="CFG Scale", minimum=1, maximum=20, step=0.5, value=3.5)
307
+ steps = gr.Slider(label="Steps", minimum=1, maximum=50, step=1, value=28)
308
+
309
+ with gr.Row():
310
+ width = gr.Slider(label="Width", minimum=256, maximum=1536, step=64, value=1024)
311
+ height = gr.Slider(label="Height", minimum=256, maximum=1536, step=64, value=1024)
312
+
313
+ with gr.Row():
314
+ randomize_seed = gr.Checkbox(True, label="Randomize seed")
315
+ seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0, randomize=True)
316
+ lora_scale = gr.Slider(label="LoRA Scale", minimum=0, maximum=3, step=0.01, value=0.95)
317
+
318
+ gallery.select(
319
+ update_selection,
320
+ inputs=[width, height],
321
+ outputs=[prompt, selected_info, selected_index, width, height]
322
+ )
323
+ custom_lora.input(
324
+ add_custom_lora,
325
+ inputs=[custom_lora],
326
+ outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, prompt]
327
+ )
328
+ custom_lora_button.click(
329
+ remove_custom_lora,
330
+ outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, custom_lora]
331
+ )
332
+ gr.on(
333
+ triggers=[generate_button.click, prompt.submit],
334
+ fn=run_lora,
335
+ inputs=[prompt, input_image, image_strength, cfg_scale, steps, selected_index, randomize_seed, seed, width, height, lora_scale],
336
+ outputs=[result, seed, progress_bar]
337
+ )
338
+
339
+ app.queue()
340
+ app.launch()