seawolf2357 commited on
Commit
dc266dd
โ€ข
1 Parent(s): 4b2c9a4

Create app-backup.py

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