Sirapatrwan commited on
Commit
5e13238
·
verified ·
1 Parent(s): d7612ee

Create app.py

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