Spaces:
Runtime error
Runtime error
Delete oldbackups
Browse files- oldbackups +0 -303
oldbackups
DELETED
|
@@ -1,303 +0,0 @@
|
|
| 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 |
-
from huggingface_hub import hf_hub_download, HfFileSystem, ModelCard, snapshot_download
|
| 11 |
-
import copy
|
| 12 |
-
import random
|
| 13 |
-
import time
|
| 14 |
-
from transformers import pipeline
|
| 15 |
-
|
| 16 |
-
# 번역 모델 초기화
|
| 17 |
-
translator = pipeline("translation", model="Helsinki-NLP/opus-mt-ko-en")
|
| 18 |
-
|
| 19 |
-
# 프롬프트 처리 함수 추가
|
| 20 |
-
def process_prompt(prompt):
|
| 21 |
-
if any('\u3131' <= char <= '\u3163' or '\uac00' <= char <= '\ud7a3' for char in prompt):
|
| 22 |
-
translated = translator(prompt)[0]['translation_text']
|
| 23 |
-
return prompt, translated
|
| 24 |
-
return prompt, prompt
|
| 25 |
-
|
| 26 |
-
KEY_JSON = os.getenv("KEY_JSON")
|
| 27 |
-
with open(KEY_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 |
-
new_placeholder = f"{selected_lora['title']}를 위한 프롬프트를 입력하세요"
|
| 62 |
-
lora_repo = selected_lora["repo"]
|
| 63 |
-
updated_text = f"### 선택됨: [{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("이미지 생성"):
|
| 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 run_lora(prompt, cfg_scale, steps, selected_index, randomize_seed, seed, width, height, lora_scale, progress=gr.Progress(track_tqdm=True)):
|
| 102 |
-
if selected_index is None:
|
| 103 |
-
raise gr.Error("진행하기 전에 LoRA를 선택해야 합니다.")
|
| 104 |
-
|
| 105 |
-
original_prompt, english_prompt = process_prompt(prompt)
|
| 106 |
-
|
| 107 |
-
selected_lora = loras[selected_index]
|
| 108 |
-
lora_path = selected_lora["repo"]
|
| 109 |
-
trigger_word = selected_lora["trigger_word"]
|
| 110 |
-
if(trigger_word):
|
| 111 |
-
if "trigger_position" in selected_lora:
|
| 112 |
-
if selected_lora["trigger_position"] == "prepend":
|
| 113 |
-
prompt_mash = f"{trigger_word} {english_prompt}"
|
| 114 |
-
else:
|
| 115 |
-
prompt_mash = f"{english_prompt} {trigger_word}"
|
| 116 |
-
else:
|
| 117 |
-
prompt_mash = f"{trigger_word} {english_prompt}"
|
| 118 |
-
else:
|
| 119 |
-
prompt_mash = english_prompt
|
| 120 |
-
|
| 121 |
-
with calculateDuration("LoRA 언로드"):
|
| 122 |
-
pipe.unload_lora_weights()
|
| 123 |
-
|
| 124 |
-
# Load LoRA weights
|
| 125 |
-
with calculateDuration(f"{selected_lora['title']}의 LoRA 가중치 로드"):
|
| 126 |
-
if "weights" in selected_lora:
|
| 127 |
-
pipe.load_lora_weights(lora_path, weight_name=selected_lora["weights"])
|
| 128 |
-
else:
|
| 129 |
-
pipe.load_lora_weights(lora_path)
|
| 130 |
-
|
| 131 |
-
# Set random seed for reproducibility
|
| 132 |
-
with calculateDuration("시드 무작위화"):
|
| 133 |
-
if randomize_seed:
|
| 134 |
-
seed = random.randint(0, MAX_SEED)
|
| 135 |
-
|
| 136 |
-
image_generator = generate_image(prompt_mash, steps, seed, cfg_scale, width, height, lora_scale, progress)
|
| 137 |
-
|
| 138 |
-
# Consume the generator to get the final image
|
| 139 |
-
final_image = None
|
| 140 |
-
step_counter = 0
|
| 141 |
-
for image in image_generator:
|
| 142 |
-
step_counter+=1
|
| 143 |
-
final_image = image
|
| 144 |
-
progress_bar = f'<div class="progress-container"><div class="progress-bar" style="--current: {step_counter}; --total: {steps};"></div></div>'
|
| 145 |
-
yield image, seed, gr.update(value=progress_bar, visible=True), original_prompt, english_prompt
|
| 146 |
-
|
| 147 |
-
yield final_image, seed, gr.update(value=progress_bar, visible=False), original_prompt, english_prompt
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
def get_huggingface_safetensors(link):
|
| 151 |
-
split_link = link.split("/")
|
| 152 |
-
if(len(split_link) == 2):
|
| 153 |
-
model_card = ModelCard.load(link)
|
| 154 |
-
base_model = model_card.data.get("base_model")
|
| 155 |
-
print(base_model)
|
| 156 |
-
if((base_model != "black-forest-labs/FLUX.1-dev") and (base_model != "black-forest-labs/FLUX.1-schnell")):
|
| 157 |
-
raise Exception("Not a FLUX LoRA!")
|
| 158 |
-
image_path = model_card.data.get("widget", [{}])[0].get("output", {}).get("url", None)
|
| 159 |
-
trigger_word = model_card.data.get("instance_prompt", "")
|
| 160 |
-
image_url = f"https://huggingface.co/{link}/resolve/main/{image_path}" if image_path else None
|
| 161 |
-
fs = HfFileSystem()
|
| 162 |
-
try:
|
| 163 |
-
list_of_files = fs.ls(link, detail=False)
|
| 164 |
-
for file in list_of_files:
|
| 165 |
-
if(file.endswith(".safetensors")):
|
| 166 |
-
safetensors_name = file.split("/")[-1]
|
| 167 |
-
if (not image_url and file.lower().endswith((".jpg", ".jpeg", ".png", ".webp"))):
|
| 168 |
-
image_elements = file.split("/")
|
| 169 |
-
image_url = f"https://huggingface.co/{link}/resolve/main/{image_elements[-1]}"
|
| 170 |
-
except Exception as e:
|
| 171 |
-
print(e)
|
| 172 |
-
gr.Warning(f"You didn't include a link neither a valid Hugging Face repository with a *.safetensors LoRA")
|
| 173 |
-
raise Exception(f"You didn't include a link neither a valid Hugging Face repository with a *.safetensors LoRA")
|
| 174 |
-
return split_link[1], link, safetensors_name, trigger_word, image_url
|
| 175 |
-
|
| 176 |
-
def check_custom_model(link):
|
| 177 |
-
if(link.startswith("https://")):
|
| 178 |
-
if(link.startswith("https://huggingface.co") or link.startswith("https://www.huggingface.co")):
|
| 179 |
-
link_split = link.split("huggingface.co/")
|
| 180 |
-
return get_huggingface_safetensors(link_split[1])
|
| 181 |
-
else:
|
| 182 |
-
return get_huggingface_safetensors(link)
|
| 183 |
-
|
| 184 |
-
def add_custom_lora(custom_lora):
|
| 185 |
-
global loras
|
| 186 |
-
if(custom_lora):
|
| 187 |
-
try:
|
| 188 |
-
title, repo, path, trigger_word, image = check_custom_model(custom_lora)
|
| 189 |
-
print(f"Loaded custom LoRA: {repo}")
|
| 190 |
-
card = f'''
|
| 191 |
-
<div class="custom_lora_card">
|
| 192 |
-
<span>Loaded custom LoRA:</span>
|
| 193 |
-
<div class="card_internal">
|
| 194 |
-
<img src="{image}" />
|
| 195 |
-
<div>
|
| 196 |
-
<h3>{title}</h3>
|
| 197 |
-
<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>
|
| 198 |
-
</div>
|
| 199 |
-
</div>
|
| 200 |
-
</div>
|
| 201 |
-
'''
|
| 202 |
-
existing_item_index = next((index for (index, item) in enumerate(loras) if item['repo'] == repo), None)
|
| 203 |
-
if(not existing_item_index):
|
| 204 |
-
new_item = {
|
| 205 |
-
"image": image,
|
| 206 |
-
"title": title,
|
| 207 |
-
"repo": repo,
|
| 208 |
-
"weights": path,
|
| 209 |
-
"trigger_word": trigger_word
|
| 210 |
-
}
|
| 211 |
-
print(new_item)
|
| 212 |
-
existing_item_index = len(loras)
|
| 213 |
-
loras.append(new_item)
|
| 214 |
-
|
| 215 |
-
return gr.update(visible=True, value=card), gr.update(visible=True), gr.Gallery(selected_index=None), f"Custom: {path}", existing_item_index, trigger_word
|
| 216 |
-
except Exception as e:
|
| 217 |
-
gr.Warning(f"Invalid LoRA: either you entered an invalid link, or a non-FLUX LoRA")
|
| 218 |
-
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, ""
|
| 219 |
-
else:
|
| 220 |
-
return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
|
| 221 |
-
|
| 222 |
-
def remove_custom_lora():
|
| 223 |
-
return gr.update(visible=False), gr.update(visible=False), gr.update(), "", None, ""
|
| 224 |
-
|
| 225 |
-
run_lora.zerogpu = True
|
| 226 |
-
|
| 227 |
-
css = """
|
| 228 |
-
footer {
|
| 229 |
-
visibility: hidden;
|
| 230 |
-
}
|
| 231 |
-
"""
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
with gr.Blocks(theme="Nymbo/Nymbo_Theme", css=css) as app:
|
| 235 |
-
|
| 236 |
-
selected_index = gr.State(None)
|
| 237 |
-
with gr.Row():
|
| 238 |
-
with gr.Column(scale=3):
|
| 239 |
-
prompt = gr.Textbox(label="프롬프트", lines=1, placeholder="LoRA를 선택한 후 프롬프트를 입력하세요 (한글 또는 영어)")
|
| 240 |
-
with gr.Column(scale=1, elem_id="gen_column"):
|
| 241 |
-
generate_button = gr.Button("생성", variant="primary", elem_id="gen_btn")
|
| 242 |
-
with gr.Row():
|
| 243 |
-
with gr.Column():
|
| 244 |
-
selected_info = gr.Markdown("")
|
| 245 |
-
gallery = gr.Gallery(
|
| 246 |
-
[(item["image"], item["title"]) for item in loras],
|
| 247 |
-
label="LoRA 갤러리",
|
| 248 |
-
allow_preview=False,
|
| 249 |
-
columns=3,
|
| 250 |
-
elem_id="gallery"
|
| 251 |
-
)
|
| 252 |
-
with gr.Group():
|
| 253 |
-
custom_lora = gr.Textbox(label="커스텀 LoRA", info="LoRA Hugging Face 경로", placeholder="multimodalart/vintage-ads-flux")
|
| 254 |
-
gr.Markdown("[FLUX LoRA 목록 확인](https://huggingface.co/models?other=base_model:adapter:black-forest-labs/FLUX.1-dev)", elem_id="lora_list")
|
| 255 |
-
custom_lora_info = gr.HTML(visible=False)
|
| 256 |
-
custom_lora_button = gr.Button("커스텀 LoRA 제거", visible=False)
|
| 257 |
-
with gr.Column():
|
| 258 |
-
progress_bar = gr.Markdown(elem_id="progress",visible=False)
|
| 259 |
-
result = gr.Image(label="생성된 이미지")
|
| 260 |
-
original_prompt_display = gr.Textbox(label="원본 프롬프트")
|
| 261 |
-
english_prompt_display = gr.Textbox(label="영어 프롬프트")
|
| 262 |
-
|
| 263 |
-
with gr.Row():
|
| 264 |
-
with gr.Accordion("고급 설정", open=False):
|
| 265 |
-
with gr.Column():
|
| 266 |
-
with gr.Row():
|
| 267 |
-
cfg_scale = gr.Slider(label="CFG 스케일", minimum=1, maximum=20, step=0.5, value=3.5)
|
| 268 |
-
steps = gr.Slider(label="스텝", minimum=1, maximum=50, step=1, value=28)
|
| 269 |
-
|
| 270 |
-
with gr.Row():
|
| 271 |
-
width = gr.Slider(label="너비", minimum=256, maximum=1536, step=64, value=1024)
|
| 272 |
-
height = gr.Slider(label="높이", minimum=256, maximum=1536, step=64, value=1024)
|
| 273 |
-
|
| 274 |
-
with gr.Row():
|
| 275 |
-
randomize_seed = gr.Checkbox(True, label="시드 무작위화")
|
| 276 |
-
seed = gr.Slider(label="시드", minimum=0, maximum=MAX_SEED, step=1, value=0, randomize=True)
|
| 277 |
-
lora_scale = gr.Slider(label="LoRA 스케일", minimum=0, maximum=3, step=0.01, value=0.95)
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
gallery.select(
|
| 281 |
-
update_selection,
|
| 282 |
-
inputs=[width, height],
|
| 283 |
-
outputs=[prompt, selected_info, selected_index, width, height]
|
| 284 |
-
)
|
| 285 |
-
custom_lora.input(
|
| 286 |
-
add_custom_lora,
|
| 287 |
-
inputs=[custom_lora],
|
| 288 |
-
outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, prompt]
|
| 289 |
-
)
|
| 290 |
-
custom_lora_button.click(
|
| 291 |
-
remove_custom_lora,
|
| 292 |
-
outputs=[custom_lora_info, custom_lora_button, gallery, selected_info, selected_index, custom_lora]
|
| 293 |
-
)
|
| 294 |
-
|
| 295 |
-
gr.on(
|
| 296 |
-
triggers=[generate_button.click, prompt.submit],
|
| 297 |
-
fn=run_lora,
|
| 298 |
-
inputs=[prompt, cfg_scale, steps, selected_index, randomize_seed, seed, width, height, lora_scale],
|
| 299 |
-
outputs=[result, seed, progress_bar, original_prompt_display, english_prompt_display]
|
| 300 |
-
)
|
| 301 |
-
|
| 302 |
-
app.queue()
|
| 303 |
-
app.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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