File size: 19,940 Bytes
b213d84 8fdc0c8 b213d84 24e151d 7778e32 afadbd4 80cec7b 99686f2 8fdc0c8 501340d af38e9b 189dd29 b600457 189dd29 b600457 83b8d5b 189dd29 83b8d5b 189dd29 235a7ab 189dd29 235a7ab 9fbd4b4 189dd29 8fdc0c8 1f17448 189dd29 83b8d5b f7aa706 83b8d5b f7aa706 1f17448 501340d 1f17448 f7aa706 83b8d5b f7aa706 189dd29 f7aa706 189dd29 f7aa706 26d2e48 f7aa706 83b8d5b 26d2e48 f7aa706 83b8d5b f7aa706 189dd29 1f17448 189dd29 7ac3a5d 7778e32 dcb1878 189dd29 dcb1878 7ac3a5d dcb1878 7ac3a5d 189dd29 dcb1878 189dd29 5999e9b 7ac3a5d 5999e9b 7ac3a5d 5999e9b 7ac3a5d 189dd29 dcb1878 189dd29 dcb1878 7ac3a5d dcb1878 189dd29 7ac3a5d dcb1878 7ac3a5d dcb1878 189dd29 7ac3a5d af38e9b 2a0877a 189dd29 2a0877a af38e9b 2a0877a af38e9b 2a0877a 501340d 2a0877a 26d2e48 2a0877a 501340d 2a0877a 501340d 2a0877a 26d2e48 2a0877a 26d2e48 2a0877a 26d2e48 2a0877a af38e9b 189dd29 af38e9b 26d2e48 24e151d 26d2e48 24e151d 6fca6aa 2a0877a 6fca6aa 2a0877a 189dd29 501340d 12cd271 83b8d5b 12cd271 4076ac2 12cd271 24e151d 12cd271 24e151d 12cd271 24e151d 12cd271 24e151d 12cd271 24e151d 12cd271 24e151d 12cd271 67d988e 12cd271 24e151d 12cd271 67d988e 12cd271 24e151d 12cd271 83b8d5b 12cd271 235a7ab 6fca6aa 235a7ab e696492 12cd271 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 |
import numpy as np
from PIL import Image
from huggingface_hub import snapshot_download, login
from leffa.transform import LeffaTransform
from leffa.model import LeffaModel
from leffa.inference import LeffaInference
from utils.garment_agnostic_mask_predictor import AutoMasker
from utils.densepose_predictor import DensePosePredictor
from utils.utils import resize_and_center
import spaces
import torch
from diffusers import DiffusionPipeline
from transformers import pipeline
import gradio as gr
import os
import random
import gc
from contextlib import contextmanager
# ์์ ์ ์
MAX_SEED = 2**32 - 1
BASE_MODEL = "black-forest-labs/FLUX.1-dev"
MODEL_LORA_REPO = "Motas/Flux_Fashion_Photography_Style"
CLOTHES_LORA_REPO = "prithivMLmods/Canopus-Clothing-Flux-LoRA"
# ๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ๋ฅผ ์ํ ๋ฐ์ฝ๋ ์ดํฐ
def safe_model_call(func):
def wrapper(*args, **kwargs):
try:
clear_memory()
result = func(*args, **kwargs)
clear_memory()
return result
except Exception as e:
clear_memory()
print(f"Error in {func.__name__}: {str(e)}")
raise
return wrapper
# ๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ๋ฅผ ์ํ ์ปจํ
์คํธ ๋งค๋์
@contextmanager
def torch_gc():
try:
yield
finally:
gc.collect()
if torch.cuda.is_available() and torch.cuda.current_device() >= 0:
with torch.cuda.device('cuda'):
torch.cuda.empty_cache()
def clear_memory():
gc.collect()
def setup_environment():
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'max_split_size_mb:128'
HF_TOKEN = os.getenv("HF_TOKEN")
if not HF_TOKEN:
raise ValueError("HF_TOKEN not found in environment variables")
login(token=HF_TOKEN)
return HF_TOKEN
def contains_korean(text):
return any(ord('๊ฐ') <= ord(char) <= ord('ํฃ') for char in text)
@spaces.GPU()
def get_translator():
return pipeline("translation", model="Helsinki-NLP/opus-mt-ko-en", device="cuda")
# ํ๊ฒฝ ์ค์ ์คํ
setup_environment()
@spaces.GPU()
def initialize_fashion_pipe():
with torch_gc():
pipe = DiffusionPipeline.from_pretrained(
BASE_MODEL,
torch_dtype=torch.float16,
)
return pipe.to("cuda")
def setup():
# Leffa ์ฒดํฌํฌ์ธํธ ๋ค์ด๋ก๋๋ง ์ํ
snapshot_download(repo_id="franciszzj/Leffa", local_dir="./ckpts")
@spaces.GPU()
def get_translator():
with torch_gc():
return pipeline("translation",
model="Helsinki-NLP/opus-mt-ko-en",
device="cuda")
@safe_model_call
def get_mask_predictor():
global mask_predictor
if mask_predictor is None:
mask_predictor = AutoMasker(
densepose_path="./ckpts/densepose",
schp_path="./ckpts/schp",
)
return mask_predictor
@safe_model_call
def get_densepose_predictor():
global densepose_predictor
if densepose_predictor is None:
densepose_predictor = DensePosePredictor(
config_path="./ckpts/densepose/densepose_rcnn_R_50_FPN_s1x.yaml",
weights_path="./ckpts/densepose/model_final_162be9.pkl",
)
return densepose_predictor
@spaces.GPU()
def get_vt_model():
with torch_gc():
model = LeffaModel(
pretrained_model_name_or_path="./ckpts/stable-diffusion-inpainting",
pretrained_model="./ckpts/virtual_tryon.pth"
)
model = model.half()
return model.to("cuda"), LeffaInference(model=model)
def load_lora(pipe, lora_path):
try:
pipe.unload_lora_weights()
except:
pass
try:
pipe.load_lora_weights(lora_path)
return pipe
except Exception as e:
print(f"Warning: Failed to load LoRA weights from {lora_path}: {e}")
return pipe
@spaces.GPU()
def get_mask_predictor():
global mask_predictor
if mask_predictor is None:
mask_predictor = AutoMasker(
densepose_path="./ckpts/densepose",
schp_path="./ckpts/schp",
)
return mask_predictor
# ๋ชจ๋ธ ์ด๊ธฐํ ํจ์ ์์
@spaces.GPU()
def initialize_fashion_pipe():
try:
pipe = DiffusionPipeline.from_pretrained(
BASE_MODEL,
torch_dtype=torch.float16,
safety_checker=None,
requires_safety_checker=False
).to("cuda")
pipe.enable_model_cpu_offload()
return pipe
except Exception as e:
print(f"Error initializing fashion pipe: {e}")
raise
@spaces.GPU()
def generate_fashion(prompt, mode, cfg_scale, steps, randomize_seed, seed, width, height, lora_scale, progress=gr.Progress(track_tqdm=True)):
try:
# ํ๊ธ ์ฒ๋ฆฌ
if contains_korean(prompt):
with torch.inference_mode():
translator = get_translator()
translated = translator(prompt)[0]['translation_text']
actual_prompt = translated
else:
actual_prompt = prompt
# ํ์ดํ๋ผ์ธ ์ด๊ธฐํ
pipe = initialize_fashion_pipe()
# LoRA ์ค์
if mode == "Generate Model":
pipe.load_lora_weights(MODEL_LORA_REPO)
trigger_word = "fashion photography, professional model"
else:
pipe.load_lora_weights(CLOTHES_LORA_REPO)
trigger_word = "upper clothing, fashion item"
# ํ๋ผ๋ฏธํฐ ์ ํ
width = min(width, 768)
height = min(height, 768)
steps = min(steps, 30)
# ์๋ ์ค์
if randomize_seed:
seed = random.randint(0, MAX_SEED)
generator = torch.Generator("cuda").manual_seed(seed)
# ์ด๋ฏธ์ง ์์ฑ
with torch.inference_mode():
output = pipe(
prompt=f"{actual_prompt} {trigger_word}",
num_inference_steps=steps,
guidance_scale=cfg_scale,
width=width,
height=height,
generator=generator,
cross_attention_kwargs={"scale": lora_scale},
)
image = output.images[0]
# ๋ฉ๋ชจ๋ฆฌ ์ ๋ฆฌ
del pipe
torch.cuda.empty_cache()
gc.collect()
return image, seed
except Exception as e:
print(f"Error in generate_fashion: {str(e)}")
raise gr.Error(f"Generation failed: {str(e)}")
class ModelManager:
def __init__(self):
self.mask_predictor = None
self.densepose_predictor = None
self.translator = None
@spaces.GPU()
def get_mask_predictor(self):
if self.mask_predictor is None:
self.mask_predictor = AutoMasker(
densepose_path="./ckpts/densepose",
schp_path="./ckpts/schp",
)
return self.mask_predictor
@spaces.GPU()
def get_densepose_predictor(self):
if self.densepose_predictor is None:
self.densepose_predictor = DensePosePredictor(
config_path="./ckpts/densepose/densepose_rcnn_R_50_FPN_s1x.yaml",
weights_path="./ckpts/densepose/model_final_162be9.pkl",
)
return self.densepose_predictor
@spaces.GPU()
def get_translator(self):
if self.translator is None:
self.translator = pipeline("translation",
model="Helsinki-NLP/opus-mt-ko-en",
device="cuda")
return self.translator
# ๋ชจ๋ธ ๋งค๋์ ์ธ์คํด์ค ์์ฑ
model_manager = ModelManager()
@spaces.GPU()
def leffa_predict(src_image_path, ref_image_path, control_type):
try:
with torch_gc():
# ๋ชจ๋ธ ์ด๊ธฐํ
model, inference = get_vt_model()
# ์ด๋ฏธ์ง ์ฒ๋ฆฌ
src_image = Image.open(src_image_path)
ref_image = Image.open(ref_image_path)
src_image = resize_and_center(src_image, 768, 1024)
ref_image = resize_and_center(ref_image, 768, 1024)
src_image_array = np.array(src_image)
ref_image_array = np.array(ref_image)
# Mask ๋ฐ DensePose ์ฒ๋ฆฌ
with torch.inference_mode():
src_image = src_image.convert("RGB")
mask_pred = model_manager.get_mask_predictor()
mask = mask_pred(src_image, "upper")["mask"]
dense_pred = model_manager.get_densepose_predictor()
src_image_seg_array = dense_pred.predict_seg(src_image_array)
densepose = Image.fromarray(src_image_seg_array)
# Leffa ๋ณํ ๋ฐ ์ถ๋ก
transform = LeffaTransform()
data = {
"src_image": [src_image],
"ref_image": [ref_image],
"mask": [mask],
"densepose": [densepose],
}
data = transform(data)
with torch.inference_mode():
output = inference(data)
# ๋ฉ๋ชจ๋ฆฌ ์ ๋ฆฌ
del model
del inference
torch.cuda.empty_cache()
gc.collect()
return np.array(output["generated_image"][0])
except Exception as e:
print(f"Error in leffa_predict: {str(e)}")
raise
@spaces.GPU()
def leffa_predict_vt(src_image_path, ref_image_path):
try:
return leffa_predict(src_image_path, ref_image_path, "virtual_tryon")
except Exception as e:
print(f"Error in leffa_predict_vt: {str(e)}")
raise
@spaces.GPU()
def generate_image(prompt, mode, cfg_scale=7.0, steps=30, seed=None, width=512, height=768, lora_scale=0.85):
try:
with torch_gc():
# ํ๊ธ ์ฒ๋ฆฌ
if contains_korean(prompt):
translator = model_manager.get_translator()
with torch.inference_mode():
translated = translator(prompt)[0]['translation_text']
actual_prompt = translated
else:
actual_prompt = prompt
# ํ์ดํ๋ผ์ธ ์ด๊ธฐํ
pipe = DiffusionPipeline.from_pretrained(
BASE_MODEL,
torch_dtype=torch.float16,
)
pipe = pipe.to("cuda")
# LoRA ์ค์
if mode == "Generate Model":
pipe.load_lora_weights(MODEL_LORA_REPO)
trigger_word = "fashion photography, professional model"
else:
pipe.load_lora_weights(CLOTHES_LORA_REPO)
trigger_word = "upper clothing, fashion item"
# ์ด๋ฏธ์ง ์์ฑ
with torch.inference_mode():
result = pipe(
prompt=f"{actual_prompt} {trigger_word}",
num_inference_steps=steps,
guidance_scale=cfg_scale,
width=width,
height=height,
generator=torch.Generator("cuda").manual_seed(
seed if seed is not None else torch.randint(0, 2**32 - 1, (1,)).item()
),
joint_attention_kwargs={"scale": lora_scale},
).images[0]
# ๋ฉ๋ชจ๋ฆฌ ์ ๋ฆฌ
del pipe
return result, seed
except Exception as e:
raise gr.Error(f"Generation failed: {str(e)}")
# ์ด๊ธฐ ์ค์ ์คํ
setup()
def create_interface():
with gr.Blocks(theme="Yntec/HaleyCH_Theme_Orange") as demo:
gr.Markdown("# ๐ญ FitGen:Fashion Studio & Virtual Try-on")
with gr.Tabs():
# ํจ์
์์ฑ ํญ
with gr.Tab("Fashion Generation"):
with gr.Column():
mode = gr.Radio(
choices=["Generate Model", "Generate Clothes"],
label="Generation Mode",
value="Generate Model"
)
# ์์ ํ๋กฌํํธ ์ค์
example_model_prompts = [
"professional fashion model, full body shot, standing pose, natural lighting, studio background, high fashion, elegant pose",
"fashion model portrait, upper body, confident pose, fashion photography, neutral background, professional lighting",
"stylish fashion model, three-quarter view, editorial pose, high-end fashion magazine style, minimal background"
]
example_clothes_prompts = [
"luxury designer sweater, cashmere material, cream color, cable knit pattern, high-end fashion, product photography",
"elegant business blazer, tailored fit, charcoal grey, premium wool fabric, professional wear",
"modern streetwear hoodie, oversized fit, minimalist design, premium cotton, urban style"
]
prompt = gr.TextArea(
label="Fashion Description (ํ๊ธ ๋๋ ์์ด)",
placeholder="ํจ์
๋ชจ๋ธ์ด๋ ์๋ฅ๋ฅผ ์ค๋ช
ํ์ธ์..."
)
# ์์ ์น์
์ถ๊ฐ
gr.Examples(
examples=example_model_prompts + example_clothes_prompts,
inputs=prompt,
label="Example Prompts"
)
with gr.Row():
with gr.Column():
result = gr.Image(label="Generated Result")
generate_button = gr.Button("Generate Fashion")
with gr.Accordion("Advanced Options", open=False):
with gr.Group():
with gr.Row():
with gr.Column():
cfg_scale = gr.Slider(
label="CFG Scale",
minimum=1,
maximum=20,
step=0.5,
value=7.0
)
steps = gr.Slider(
label="Steps",
minimum=1,
maximum=30,
step=1,
value=30
)
lora_scale = gr.Slider(
label="LoRA Scale",
minimum=0,
maximum=1,
step=0.01,
value=0.85
)
with gr.Row():
width = gr.Slider(
label="Width",
minimum=256,
maximum=768,
step=64,
value=512
)
height = gr.Slider(
label="Height",
minimum=256,
maximum=768,
step=64,
value=768
)
with gr.Row():
randomize_seed = gr.Checkbox(
True,
label="Randomize seed"
)
seed = gr.Slider(
label="Seed",
minimum=0,
maximum=2**32-1,
step=1,
value=42
)
# ๊ฐ์ ํผํ
ํญ
with gr.Tab("Virtual Try-on"):
with gr.Row():
with gr.Column():
gr.Markdown("#### Person Image")
vt_src_image = gr.Image(
sources=["upload"],
type="filepath",
label="Person Image",
width=512,
height=512,
)
gr.Examples(
inputs=vt_src_image,
examples_per_page=5,
examples=["a1.webp",
"a2.webp",
"a3.webp",
"a4.webp",
"a5.webp"]
)
with gr.Column():
gr.Markdown("#### Garment Image")
vt_ref_image = gr.Image(
sources=["upload"],
type="filepath",
label="Garment Image",
width=512,
height=512,
)
gr.Examples(
inputs=vt_ref_image,
examples_per_page=5,
examples=["b1.webp",
"b2.webp",
"b3.webp",
"b4.webp",
"c1.png",
"c2.png",
"c3.png",
"c4.png",
"c5.png",
"c6.png",
"c7.png",
"c8.png",
"c9.png",
"c10.png",
"c11.png",
"c12.png",
"c13.png",
"c14.png",
"c15.png",
"c16.png",
"b5.webp"]
)
with gr.Column():
gr.Markdown("#### Generated Image")
vt_gen_image = gr.Image(
label="Generated Image",
width=512,
height=512,
)
vt_gen_button = gr.Button("Try-on")
vt_gen_button.click(
fn=leffa_predict_vt,
inputs=[vt_src_image, vt_ref_image],
outputs=[vt_gen_image]
)
generate_button.click(
fn=generate_image,
inputs=[prompt, mode, cfg_scale, steps, seed, width, height, lora_scale],
outputs=[result, seed]
).success(
fn=lambda: gc.collect(), # ์ฑ๊ณต ํ ๋ฉ๋ชจ๋ฆฌ ์ ๋ฆฌ
inputs=None,
outputs=None
)
return demo
if __name__ == "__main__":
setup_environment()
demo = create_interface()
demo.queue()
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=False
) |