Spaces:
Runtime error
Runtime error
File size: 37,055 Bytes
cd25265 a71f5d3 460d058 b7b1936 ef9ea85 177badc b7b1936 3ec1fb0 1d8d0a5 55004dd c8c91af 051efbb 1d8d0a5 2eb05f5 6ee559d 1d8d0a5 b7b1936 460d058 b7b1936 177badc a854895 460d058 b7b1936 460d058 b7b1936 cb3d765 460d058 b7b1936 abdaa5a 460d058 b7b1936 460d058 b7b1936 460d058 b7b1936 04519b1 b7b1936 0fa9e72 b7b1936 0fa9e72 b7b1936 b20f839 177badc 460d058 b20f839 460d058 177badc 460d058 6d0fa70 460d058 6d0fa70 460d058 a88c73f 460d058 a71f5d3 b7b1936 6ee559d b7b1936 fde2175 88d7d46 fde2175 177badc 6554c65 177badc 22b7bf5 a88c73f 6554c65 a88c73f 2f2566e a88c73f b7b1936 177badc 74ccd9d 460d058 62ccd4d a30cb7d 17c0d68 460d058 17c0d68 6554c65 460d058 ccce1ea 460d058 113326d 460d058 74ccd9d 460d058 74ccd9d 460d058 74ccd9d 460d058 74ccd9d 460d058 74ccd9d 460d058 74ccd9d 460d058 1b3ed30 d92b3ae 460d058 d92b3ae 460d058 177badc 460d058 74ccd9d 6ee559d 74ccd9d a2e1901 460d058 74ccd9d 177badc 460d058 17c0d68 460d058 17c0d68 6554c65 460d058 e7563df 460d058 d92b3ae 460d058 d92b3ae 460d058 6ee559d 460d058 a2e1901 460d058 17c0d68 460d058 17c0d68 d92b3ae 460d058 e7563df 460d058 0b9adc4 e9e6a73 0b9adc4 460d058 42c9642 84d010d 460d058 6ee559d 460d058 a2e1901 460d058 52a262a 50761b6 460d058 62ccd4d 43d6947 458f652 460d058 458f652 6554c65 460d058 ccce1ea 460d058 6ee559d 460d058 458f652 460d058 458f652 6554c65 ccce1ea e7563df 460d058 6ee559d 460d058 b65dcf6 460d058 34eb952 460d058 9757d1a 460d058 9757d1a 460d058 6ee559d 460d058 458f652 460d058 458f652 6554c65 460d058 ccce1ea e7563df 460d058 6ee559d 460d058 b65dcf6 460d058 ccce1ea 460d058 74ccd9d 460d058 74ccd9d 460d058 74ccd9d ca9db04 d2faec8 a71f5d3 9738dce f82fd7b 854eb45 460d058 34eb952 4162f6b 50761b6 6725272 9738dce d85e2cb 460d058 50761b6 9738dce a71f5d3 d4bbfb5 d2faec8 735e830 86e6a95 9f58901 b7b1936 2eb05f5 9f58901 b7b1936 9f58901 ef9ea85 b872418 ef9ea85 b872418 b7b1936 a20297c 504c283 a20297c b872418 ef9ea85 b7b1936 e6ca5c2 504c283 a20297c ef9ea85 7d4603f a20297c 9738dce b7b1936 b872418 ef9ea85 b7b1936 ef9ea85 3b0e749 ef9ea85 fde2175 b7b1936 2d9fb2b d4bbfb5 a71f5d3 ef9ea85 a71f5d3 ef9ea85 a71f5d3 ef9ea85 a71f5d3 d2faec8 abdaa5a 9e23671 47b5782 504c283 53cda62 47b5782 570499e abdaa5a 504c283 53cda62 abdaa5a 47b5782 abdaa5a f5f499a 051efbb abdaa5a f889121 abdaa5a 22b7bf5 177badc 4d649f7 abdaa5a f4bcc02 abdaa5a 9e23671 abdaa5a d2faec8 22b7bf5 48cd46c 22b7bf5 504c283 53cda62 22b7bf5 a3b5493 22b7bf5 504c283 53cda62 22b7bf5 a2e1901 36b0b46 a2e1901 5ecd99a 051efbb 50761b6 5ecd99a 22b7bf5 5ecd99a 22b7bf5 f4bcc02 22b7bf5 d2faec8 22b7bf5 a3b5493 9738dce ef9ea85 90b30ce 2d9fb2b a71f5d3 6ee559d a71f5d3 ef9ea85 b7b1936 6554c65 113326d 6554c65 113326d a88c73f 6554c65 a88c73f 2f2566e a88c73f a71f5d3 6b9434e a71f5d3 |
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 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 |
import gradio as gr
import numpy as np
import torch
from diffusers import (
StableDiffusionPipeline,
ControlNetModel,
StableDiffusionControlNetPipeline,
StableDiffusionControlNetImg2ImgPipeline,
AutoPipelineForImage2Image,
DDIMScheduler,
UniPCMultistepScheduler)
from transformers import pipeline
from diffusers.utils import load_image, make_image_grid
from peft import PeftModel, LoraConfig
import os
from PIL import Image
MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 1024
IP_ADAPTER = 'h94/IP-Adapter'
WEIGHT_NAME = "ip-adapter_sd15.bin"
WEIGHT_NAME_plus = "ip-adapter-plus_sd15.bin"
WEIGHT_NAME_face = "ip-adapter-full-face_sd15.bin"
model_default = "stable-diffusion-v1-5/stable-diffusion-v1-5"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
def get_lora_sd_pipeline(
lora_dir='lora_man_animestyle',
base_model_name_or_path=None,
dtype=torch.float16,
adapter_name="default"
):
unet_sub_dir = os.path.join(lora_dir, "unet")
text_encoder_sub_dir = os.path.join(lora_dir, "text_encoder")
if os.path.exists(text_encoder_sub_dir) and base_model_name_or_path is None:
config = LoraConfig.from_pretrained(text_encoder_sub_dir)
base_model_name_or_path = config.base_model_name_or_path
if base_model_name_or_path is None:
raise ValueError("Укажите название базовой модели или путь к ней")
pipe = StableDiffusionPipeline.from_pretrained(base_model_name_or_path, torch_dtype=dtype)
before_params = pipe.unet.parameters()
pipe.unet = PeftModel.from_pretrained(pipe.unet, unet_sub_dir, adapter_name=adapter_name)
pipe.unet.set_adapter(adapter_name)
after_params = pipe.unet.parameters()
if os.path.exists(text_encoder_sub_dir):
pipe.text_encoder = PeftModel.from_pretrained(pipe.text_encoder, text_encoder_sub_dir, adapter_name=adapter_name)
if dtype in (torch.float16, torch.bfloat16):
pipe.unet.half()
pipe.text_encoder.half()
return pipe
def long_prompt_encoder(prompt, tokenizer, text_encoder, max_length=77):
tokens = tokenizer(prompt, truncation=False, return_tensors="pt")["input_ids"]
part_s = [tokens[:, i:i + max_length] for i in range(0, tokens.shape[1], max_length)]
with torch.no_grad():
embeds = [text_encoder(part.to(text_encoder.device))[0] for part in part_s]
return torch.cat(embeds, dim=1)
def align_embeddings(prompt_embeds, negative_prompt_embeds):
max_length = max(prompt_embeds.shape[1], negative_prompt_embeds.shape[1])
return torch.nn.functional.pad(prompt_embeds, (0, 0, 0, max_length - prompt_embeds.shape[1])), \
torch.nn.functional.pad(negative_prompt_embeds, (0, 0, 0, max_length - negative_prompt_embeds.shape[1]))
def preprocess_image(image, target_width, target_height, resize_to_224=False):
if isinstance(image, np.ndarray):
image = Image.fromarray(image)
# Если resize_to_224=True, изменяем размер до 224x224
if resize_to_224:
image = image.resize((224, 224), Image.LANCZOS)
else:
image = image.resize((target_width, target_height), Image.LANCZOS)
image = np.array(image).astype(np.float32) / 255.0 # Нормализация [0, 1]
image = image[None].transpose(0, 3, 1, 2) # Преобразуем в (batch, channels, height, width)
image = torch.from_numpy(image).to(device)
return image
def get_depth_map(image, depth_estimator):
# Преобразуем изображение в PIL, если это необходимо
if isinstance(image, np.ndarray):
image = Image.fromarray(image)
elif isinstance(image, torch.Tensor):
image = Image.fromarray(image.cpu().numpy())
# Получаем карту глубины
depth_map = depth_estimator(image)["depth"]
depth_map = np.array(depth_map)
depth_map = depth_map[:, :, None] # Добавляем третье измерение
depth_map = np.concatenate([depth_map, depth_map, depth_map], axis=2) # Преобразуем в 3 канала
depth_map = torch.from_numpy(depth_map).float() / 255.0 # Нормализация [0, 1]
depth_map = depth_map.permute(2, 0, 1) # Меняем порядок осей (C, H, W)
return depth_map
pipe_default = get_lora_sd_pipeline(lora_dir='lora_man_animestyle', base_model_name_or_path=model_default, dtype=torch_dtype).to(device)
# ----------------------------------------------------------------------------------------------------------------------------------------------------
def infer(
prompt,
negative_prompt,
model=model_default,
width=512,
height=512,
num_inference_steps=50,
seed=4,
guidance_scale=7.5,
lora_scale=0.7,
use_control_net=False, # Параметр для включения ControlNet
control_mode=None, # Параметр для выбора режима ControlNet
strength_cn=0.5, # Коэфф. зашумления ControlNet
control_strength=0.5, # Сила влияния ControlNet
cn_source_image=None, # Исходное изображение ControlNet
control_image=None, # Контрольное изображение ControlNet
use_ip_adapter=False, # Параметр для включения IP_adapter
ip_adapter_mode=None, # Параметр для выбора режима IP_adapter
strength_ip=0.5, # Коэфф. зашумления IP_adapter
ip_adapter_strength=0.5,# Сила влияния IP_adapter
controlnet_conditioning_scale=0.5, # Сила влияния ControlNet
ip_source_image=None, # Исходное изображение IP_adapter
ip_adapter_image=None, # Контрольное изображение IP_adapter
progress=gr.Progress(track_tqdm=True)
):
# Генерация изображений с Ip_Adapter ------------------------------------------------------------------------------------------------------------------
if use_ip_adapter and ip_source_image is not None and ip_adapter_image is not None:
if ip_adapter_mode == "pose_estimation":
print('ip_adapter_mode = ', ip_adapter_mode)
# Инициализация ControlNet
controlnet_model_path = "lllyasviel/sd-controlnet-openpose"
controlnet = ControlNetModel.from_pretrained(controlnet_model_path, torch_dtype=torch_dtype)
generator = torch.Generator(device).manual_seed(seed)
pipe_ip_adapter = StableDiffusionControlNetPipeline.from_pretrained(
model_default,
controlnet=controlnet,
torch_dtype=torch_dtype
).to(device)
# Загрузка IP-Adapter
pipe_ip_adapter.load_ip_adapter(IP_ADAPTER, subfolder="models", weight_name=WEIGHT_NAME_plus)
pipe_ip_adapter.set_ip_adapter_scale(ip_adapter_strength)
# Преобразование изображений для IP-Adapter (размер 224x224)
ip_source_image = preprocess_image(ip_source_image, width, height, resize_to_224=True)
ip_adapter_image = preprocess_image(ip_adapter_image, width, height, resize_to_224=True)
# Создаём пайплайн IP_adapter с LoRA, если он ещё не создан
if not hasattr(pipe_ip_adapter, 'lora_loaded') or not pipe_ip_adapter.lora_loaded:
# Загружаем LoRA для UNet
pipe_ip_adapter.unet = PeftModel.from_pretrained(
pipe_ip_adapter.unet,
'lora_man_animestyle/unet',
adapter_name="default"
)
pipe_ip_adapter.unet.set_adapter("default")
# Загружаем LoRA для Text Encoder, если она существует
text_encoder_lora_path = 'lora_man_animestyle/text_encoder'
if os.path.exists(text_encoder_lora_path):
pipe_ip_adapter.text_encoder = PeftModel.from_pretrained(
pipe_ip_adapter.text_encoder,
text_encoder_lora_path,
adapter_name="default"
)
pipe_ip_adapter.text_encoder.set_adapter("default")
# Объединяем LoRA с основной моделью
pipe_ip_adapter.fuse_lora(lora_scale=lora_scale)
pipe_ip_adapter.lora_loaded = True # Помечаем, что LoRA загружена
# Убедимся, что параметры имеют тип float
ip_adapter_strength = float(ip_adapter_strength)
controlnet_conditioning_scale = float(controlnet_conditioning_scale)
# Используем IP-Adapter с LoRA
prompt_embeds = long_prompt_encoder(prompt, pipe_ip_adapter.tokenizer, pipe_ip_adapter.text_encoder)
negative_prompt_embeds = long_prompt_encoder(negative_prompt, pipe_ip_adapter.tokenizer, pipe_ip_adapter.text_encoder)
prompt_embeds, negative_prompt_embeds = align_embeddings(prompt_embeds, negative_prompt_embeds)
image = pipe_ip_adapter(
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_prompt_embeds,
image=ip_adapter_image,
ip_adapter_image=ip_source_image,
strength=strength_ip,
width=width,
height=height,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
controlnet_conditioning_scale=controlnet_conditioning_scale,
generator=generator,
).images[0]
else:
if ip_adapter_mode == "edge_detection":
print('ip_adapter_mode = ', ip_adapter_mode)
# Инициализация ControlNet
controlnet_model_path = "lllyasviel/control_v11f1p_sd15_depth"
controlnet = ControlNetModel.from_pretrained(controlnet_model_path, torch_dtype=torch_dtype)
generator = torch.Generator(device).manual_seed(seed)
pipe_ip_adapter = StableDiffusionControlNetPipeline.from_pretrained(
model_default,
controlnet=controlnet,
torch_dtype=torch_dtype
).to(device)
# Загрузка IP-Adapter
#pipe_ip_adapter.load_ip_adapter(IP_ADAPTER, subfolder="models", weight_name=WEIGHT_NAME_face)
pipe_ip_adapter.load_ip_adapter(IP_ADAPTER, subfolder="models", weight_name=WEIGHT_NAME_plus)
pipe_ip_adapter.set_ip_adapter_scale(ip_adapter_strength)
# Преобразование изображений для IP-Adapter (размер 224x224)
ip_source_image = preprocess_image(ip_source_image, width, height, resize_to_224=True)
ip_adapter_image = preprocess_image(ip_adapter_image, width, height, resize_to_224=True)
# Создаём пайплайн IP_adapter с LoRA, если он ещё не создан
if not hasattr(pipe_ip_adapter, 'lora_loaded') or not pipe_ip_adapter.lora_loaded:
# Загружаем LoRA для UNet
pipe_ip_adapter.unet = PeftModel.from_pretrained(
pipe_ip_adapter.unet,
'lora_man_animestyle/unet',
adapter_name="default"
)
pipe_ip_adapter.unet.set_adapter("default")
# Загружаем LoRA для Text Encoder, если она существует
text_encoder_lora_path = 'lora_man_animestyle/text_encoder'
if os.path.exists(text_encoder_lora_path):
pipe_ip_adapter.text_encoder = PeftModel.from_pretrained(
pipe_ip_adapter.text_encoder,
text_encoder_lora_path,
adapter_name="default"
)
pipe_ip_adapter.text_encoder.set_adapter("default")
# Объединяем LoRA с основной моделью
pipe_ip_adapter.fuse_lora(lora_scale=lora_scale)
pipe_ip_adapter.lora_loaded = True # Помечаем, что LoRA загружена
# Убедимся, что параметры имеют тип float
ip_adapter_strength = float(ip_adapter_strength)
controlnet_conditioning_scale = float(controlnet_conditioning_scale)
# Используем IP-Adapter с LoRA
prompt_embeds = long_prompt_encoder(prompt, pipe_ip_adapter.tokenizer, pipe_ip_adapter.text_encoder)
negative_prompt_embeds = long_prompt_encoder(negative_prompt, pipe_ip_adapter.tokenizer, pipe_ip_adapter.text_encoder)
prompt_embeds, negative_prompt_embeds = align_embeddings(prompt_embeds, negative_prompt_embeds)
# scale = { # по умолчанию в остальных блоках везде 0.
# "down": {
# "block_0": [0.0, 1.0],
# "block_1": [0.0, 1.0],
# },
# "up": {
# "block_0": [0.0, 1.0, 0.0],
# "block_1": [0.0, 1.0, 0.0],
# },
# }
# scale = {
# "down": {"block_2": [0.0, 1.0]},
# "up": {"block_0": [0.0, 1.0, 0.0]},
# }
# pipe_ip_adapter.set_ip_adapter_scale(scale)
image = pipe_ip_adapter(
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_prompt_embeds,
image=ip_adapter_image,
ip_adapter_image=ip_source_image,
strength=strength_ip,
width=width,
height=height,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
controlnet_conditioning_scale=controlnet_conditioning_scale,
generator=generator,
).images[0]
else:
if ip_adapter_mode == "depth_map":
print('ip_adapter_mode = ', ip_adapter_mode)
# Убедимся, что параметры имеют тип float
controlnet_conditioning_scale = float(controlnet_conditioning_scale)
# Инициализация ControlNet
controlnet_model_path = "lllyasviel/control_v11f1p_sd15_depth"
controlnet = ControlNetModel.from_pretrained(controlnet_model_path, torch_dtype=torch_dtype)
generator = torch.Generator(device).manual_seed(seed)
# Преобразование изображений для IP-Adapter (размер 224x224)
ip_source_image = preprocess_image(ip_source_image, width, height, resize_to_224=True)
ip_adapter_image = preprocess_image(ip_adapter_image, width, height, resize_to_224=True)
pipe_ip_adapter = StableDiffusionControlNetPipeline.from_pretrained(
model_default,
controlnet=controlnet,
torch_dtype=torch_dtype
).to(device)
pipe_ip_adapter.load_ip_adapter(IP_ADAPTER, subfolder="models", weight_name=WEIGHT_NAME)
pipe_ip_adapter.set_ip_adapter_scale(ip_adapter_strength)
image = pipe_ip_adapter(
prompt=prompt,
negative_prompt=negative_prompt,
image=ip_source_image,
width=width,
height=height,
ip_adapter_image=ip_adapter_image,
num_inference_steps=num_inference_steps,
strength=strength_ip,
guidance_scale=guidance_scale,
controlnet_conditioning_scale=controlnet_conditioning_scale,
generator=generator,
).images[0]
else:
if ip_adapter_mode == "face_model":
print('ip_adapter_mode = ', ip_adapter_mode)
# Преобразование изображений для IP-Adapter (размер 224x224)
ip_source_image = preprocess_image(ip_source_image, width, height, resize_to_224=True)
ip_adapter_image = preprocess_image(ip_adapter_image, width, height, resize_to_224=True)
pipe_ip_adapter = StableDiffusionPipeline.from_pretrained(
model_default,
torch_dtype=torch_dtype,
).to(device)
pipe_ip_adapter.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
pipe_ip_adapter.load_ip_adapter(IP_ADAPTER, subfolder="models", weight_name=WEIGHT_NAME_face)
generator = torch.Generator(device).manual_seed(seed)
pipe_ip_adapter.set_ip_adapter_scale(ip_adapter_strength)
image = pipe_ip_adapter(
prompt=prompt,
negative_prompt=negative_prompt,
ip_adapter_image=ip_adapter_image,
width=width,
height=height,
guidance_scale=guidance_scale,
num_inference_steps=num_inference_steps,
generator=generator,
).images[0]
else:
# Генерация изображений с ControlNet ----------------------------------------------------------------------------------------------------------------
if use_control_net and control_image is not None and cn_source_image is not None:
if control_mode == "pose_estimation":
print('control_mode = ', control_mode)
# Инициализация ControlNet
controlnet_model_path = "lllyasviel/sd-controlnet-openpose"
controlnet = ControlNetModel.from_pretrained(controlnet_model_path, torch_dtype=torch_dtype)
generator = torch.Generator(device).manual_seed(seed)
pipe_controlnet = StableDiffusionControlNetImg2ImgPipeline.from_pretrained(
model_default,
controlnet=controlnet,
torch_dtype=torch_dtype
).to(device)
# Преобразуем изображения
cn_source_image = preprocess_image(cn_source_image, width, height)
control_image = preprocess_image(control_image, width, height)
# Создаём пайплайн ControlNet с LoRA, если он ещё не создан
if not hasattr(pipe_controlnet, 'lora_loaded') or not pipe_controlnet.lora_loaded:
# Загружаем LoRA для UNet
pipe_controlnet.unet = PeftModel.from_pretrained(
pipe_controlnet.unet,
'lora_man_animestyle/unet',
adapter_name="default"
)
pipe_controlnet.unet.set_adapter("default")
# Загружаем LoRA для Text Encoder, если она существует
text_encoder_lora_path = 'lora_man_animestyle/text_encoder'
if os.path.exists(text_encoder_lora_path):
pipe_controlnet.text_encoder = PeftModel.from_pretrained(
pipe_controlnet.text_encoder,
text_encoder_lora_path,
adapter_name="default"
)
pipe_controlnet.text_encoder.set_adapter("default")
# Объединяем LoRA с основной моделью
pipe_controlnet.fuse_lora(lora_scale=lora_scale)
pipe_controlnet.lora_loaded = True # Помечаем, что LoRA загружена
# Убедимся, что control_strength имеет тип float
control_strength = float(control_strength)
#strength_sn = float(strength_sn)
# Используем ControlNet с LoRA
prompt_embeds = long_prompt_encoder(prompt, pipe_controlnet.tokenizer, pipe_controlnet.text_encoder)
negative_prompt_embeds = long_prompt_encoder(negative_prompt, pipe_controlnet.tokenizer, pipe_controlnet.text_encoder)
prompt_embeds, negative_prompt_embeds = align_embeddings(prompt_embeds, negative_prompt_embeds)
image = pipe_controlnet(
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_prompt_embeds,
image=cn_source_image,
control_image=control_image,
strength=strength_cn,
width=width,
height=height,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
controlnet_conditioning_scale=control_strength,
generator=generator
).images[0]
else:
if control_mode == "edge_detection":
print('control_mode = ', control_mode)
controlnet_model_path = "lllyasviel/sd-controlnet-canny"
controlnet = ControlNetModel.from_pretrained(controlnet_model_path, torch_dtype=torch_dtype, use_safetensors=True)
generator = torch.Generator(device).manual_seed(seed)
pipe_controlnet = StableDiffusionControlNetPipeline.from_pretrained(
model_default,
controlnet=controlnet,
torch_dtype=torch_dtype,
use_safetensors=True
).to(device)
pipe_controlnet.scheduler = UniPCMultistepScheduler.from_config(pipe_controlnet.scheduler.config)
# Преобразуем изображения
cn_source_image = preprocess_image(cn_source_image, width, height)
control_image = preprocess_image(control_image, width, height)
image = pipe_controlnet(
prompt=prompt,
negative_prompt=negative_prompt,
image=cn_source_image,
control_image=control_image,
strength=strength_cn,
width=width,
height=height,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
controlnet_conditioning_scale=control_strength,
generator=generator
).images[0]
else:
if control_mode == "depth_map":
print('control_mode = ', control_mode)
depth_estimator = pipeline("depth-estimation")
depth_map = get_depth_map(control_image, depth_estimator).unsqueeze(0).half().to(device)
controlnet_model_path = "lllyasviel/control_v11f1p_sd15_depth"
controlnet = ControlNetModel.from_pretrained(controlnet_model_path, torch_dtype=torch_dtype, use_safetensors=True)
generator = torch.Generator(device).manual_seed(seed)
pipe_controlnet = StableDiffusionControlNetImg2ImgPipeline.from_pretrained(
model_default,
controlnet=controlnet,
torch_dtype=torch_dtype,
use_safetensors=True
).to(device)
pipe_controlnet.scheduler = UniPCMultistepScheduler.from_config(pipe_controlnet.scheduler.config)
image = pipe_controlnet(
prompt=prompt,
negative_prompt=negative_prompt,
image=control_image,
control_image=depth_map,
width=width,
height=height,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
generator=generator
).images[0]
else:
# Генерация изображений с LORA без ControlNet и IP_Adapter ---------------------------------------------------------------------------------------------
# Инициализация ControlNet
controlnet_model_path = "lllyasviel/sd-controlnet-openpose"
controlnet = ControlNetModel.from_pretrained(controlnet_model_path, torch_dtype=torch_dtype)
generator = torch.Generator(device).manual_seed(seed)
if model != model_default:
pipe = StableDiffusionPipeline.from_pretrained(model, torch_dtype=torch_dtype).to(device)
prompt_embeds = long_prompt_encoder(prompt, pipe.tokenizer, pipe.text_encoder)
negative_prompt_embeds = long_prompt_encoder(negative_prompt, pipe.tokenizer, pipe.text_encoder)
prompt_embeds, negative_prompt_embeds = align_embeddings(prompt_embeds, negative_prompt_embeds)
else:
pipe = pipe_default
prompt_embeds = long_prompt_encoder(prompt, pipe.tokenizer, pipe.text_encoder)
negative_prompt_embeds = long_prompt_encoder(negative_prompt, pipe.tokenizer, pipe.text_encoder)
prompt_embeds, negative_prompt_embeds = align_embeddings(prompt_embeds, negative_prompt_embeds)
pipe.fuse_lora(lora_scale=lora_scale)
params = {
'prompt_embeds': prompt_embeds,
'negative_prompt_embeds': negative_prompt_embeds,
'guidance_scale': guidance_scale,
'num_inference_steps': num_inference_steps,
'width': width,
'height': height,
'generator': generator,
}
image = pipe(**params).images[0]
return image
# ---------------------------------------------------------------------------------------------------------------------------------------------
examples = [
"A young man in anime style. The image is characterized by high definition and resolution. Handsome, thoughtful man, attentive eyes. The man is depicted in the foreground, close-up or in the middle. High-quality images of the face, eyes, nose, lips, hands and clothes. The background and background are blurred and indistinct. The play of light and shadow is visible on the face and clothes.",
"A man runs through the park against the background of trees. The man's entire figure, face, arms and legs are visible. Anime style. The best quality.",
"The smiling man. His face and hands are visible. Anime style. The best quality.",
"The smiling girl. Anime style. Best quality, high quality.",
"lego batman and robin. Rich and vibrant colors.",
"Photo of Pushkin as a hockey player in uniform with a stick, playing hockey on the ice arena in the NHL.",
]
examples_negative = [
"Blurred details, low resolution, bad anatomy, no face visible, poor image of a man's face, poor quality, artifacts, black and white image.",
"Monochrome, lowres, bad anatomy, worst quality, low quality",
"lowres, bad anatomy, worst quality, low quality, black and white image.",
]
css = """
#col-container {
margin: 0 auto;
max-width: 640px;
}
"""
available_models = [
"stable-diffusion-v1-5/stable-diffusion-v1-5",
"CompVis/stable-diffusion-v1-4",
]
# -------------------------------------------------------------------------------------------------------------------------------------------------
with gr.Blocks(css=css) as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown(" # Text-to-Image Gradio Template from V. Gorsky")
with gr.Row():
model = gr.Dropdown(
label="Model Selection",
choices=available_models,
value="stable-diffusion-v1-5/stable-diffusion-v1-5",
interactive=True
)
prompt = gr.Textbox(
label="Prompt",
max_lines=1,
placeholder="Enter your prompt",
)
negative_prompt = gr.Textbox(
label="Negative prompt",
max_lines=1,
placeholder="Enter a negative prompt",
)
with gr.Row():
lora_scale = gr.Slider(
label="LoRA scale",
minimum=0.0,
maximum=1.0,
step=0.01,
value=0.7,
)
with gr.Row():
guidance_scale = gr.Slider(
label="Guidance scale",
minimum=0.0,
maximum=10.0,
step=0.01,
value=7.5,
)
with gr.Row():
seed = gr.Slider(
label="Seed",
minimum=0,
maximum=MAX_SEED,
step=1,
value=4,
)
with gr.Row():
num_inference_steps = gr.Slider(
label="Number of inference steps",
minimum=1,
maximum=100,
step=1,
value=50,
)
with gr.Accordion("Advanced Settings", open=False):
with gr.Row():
width = gr.Slider(
label="Width",
minimum=256,
maximum=MAX_IMAGE_SIZE,
step=32,
value=512,
)
with gr.Row():
height = gr.Slider(
label="Height",
minimum=256,
maximum=MAX_IMAGE_SIZE,
step=32,
value=512,
)
# ControlNet -----------------------------------------------------------------------------------------------
with gr.Blocks():
with gr.Row():
use_control_net = gr.Checkbox(
label="Use ControlNet",
value=False,
)
with gr.Column(visible=False) as control_net_options:
strength_cn = gr.Slider(
label="Strength",
minimum=0.0,
maximum=1.0,
value=0.5,
step=0.01,
interactive=True,
)
control_strength = gr.Slider(
label="Control Strength",
minimum=0.0,
maximum=1.0,
value=0.5,
step=0.01,
interactive=True,
)
control_mode = gr.Dropdown(
label="Control Mode",
choices=[
"pose_estimation",
"edge_detection",
"depth_map",
],
value="pose_estimation",
interactive=True,
)
cn_source_image = gr.Image(label="Upload Source Image")
control_image = gr.Image(label="Upload Control Net Image")
use_control_net.change(
fn=lambda x: gr.update(visible=x),
inputs=use_control_net,
outputs=control_net_options
)
# IP_Adapter ------------------------------------------------------------------------------------------------
with gr.Blocks():
with gr.Row():
use_ip_adapter = gr.Checkbox(
label="Use IP_Adapter",
value=False,
)
with gr.Column(visible=False) as ip_adapter_options:
strength_ip = gr.Slider(
label="Strength",
minimum=0.0,
maximum=1.0,
value=0.5,
step=0.01,
interactive=True,
)
ip_adapter_strength = gr.Slider(
label="IP_Adapter Strength",
minimum=0.0,
maximum=1.0,
value=0.5,
step=0.01,
interactive=True,
)
controlnet_conditioning_scale = gr.Slider(
label="Controlnet conditioning scale",
minimum=0.0,
maximum=1.0,
value=0.5,
step=0.01,
interactive=True,
)
ip_adapter_mode = gr.Dropdown(
label="Ip_Adapter Mode",
choices=[
"pose_estimation",
"edge_detection",
"depth_map",
"face_model"
],
value="pose_estimation",
interactive=True,
)
ip_source_image = gr.Image(label="Upload Source Image")
ip_adapter_image = gr.Image(label="Upload IP_Adapter Image")
use_ip_adapter.change(
fn=lambda x: gr.update(visible=x),
inputs=use_ip_adapter,
outputs=ip_adapter_options
)
# ---------------------------------------------------------------------------------------------------------
gr.Examples(examples=examples, inputs=[prompt], label="Examples for prompt:")
gr.Examples(examples=examples_negative, inputs=[negative_prompt], label="Examples for negative prompt:")
run_button = gr.Button("Run", scale=1, variant="primary")
result = gr.Image(label="Result", show_label=False)
gr.on(
triggers=[run_button.click, prompt.submit],
fn=infer,
inputs=[
prompt,
negative_prompt,
model,
width,
height,
num_inference_steps,
seed,
guidance_scale,
lora_scale,
use_control_net, # Параметр для включения ControlNet
control_mode, # Параметр для выбора режима ControlNet
strength_cn, # Коэфф. зашумления ControlNet
control_strength, # Сила влияния ControlNet
cn_source_image, # Исходное изображение ControlNet
control_image, # Контрольное изображение ControlNet
use_ip_adapter, # Параметр для включения IP_adapter
ip_adapter_mode, # Параметр для выбора режима IP_adapter
strength_ip, # Коэфф. зашумления IP_adapter
ip_adapter_strength,# Сила влияния IP_adapter
controlnet_conditioning_scale, # Сила влияния ControlNet
ip_source_image, # Исходное изображение IP_adapter
ip_adapter_image, # Контрольное изображение IP_adapter
],
outputs=[result],
)
if __name__ == "__main__":
demo.launch()
|