File size: 71,510 Bytes
d0ffe9c |
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 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 |
import glob
import logging
import os
import re
from functools import partial
from itertools import chain
from os import PathLike
from pathlib import Path
from typing import Any, Callable, Dict, List, Union
import numpy as np
import torch
from controlnet_aux import LineartAnimeDetector
from controlnet_aux.processor import MODELS
from controlnet_aux.processor import Processor as ControlnetPreProcessor
from controlnet_aux.util import HWC3, ade_palette
from controlnet_aux.util import resize_image as aux_resize_image
from diffusers import (AutoencoderKL, ControlNetModel, DiffusionPipeline,
EulerDiscreteScheduler,
StableDiffusionControlNetImg2ImgPipeline,
StableDiffusionPipeline, StableDiffusionXLPipeline)
from PIL import Image
from torchvision.datasets.folder import IMG_EXTENSIONS
from tqdm.rich import tqdm
from transformers import (AutoImageProcessor, CLIPImageProcessor,
CLIPTextConfig, CLIPTextModel,
CLIPTextModelWithProjection, CLIPTokenizer,
UperNetForSemanticSegmentation)
from animatediff import get_dir
from animatediff.dwpose import DWposeDetector
from animatediff.models.clip import CLIPSkipTextModel
from animatediff.models.unet import UNet3DConditionModel
from animatediff.pipelines import AnimationPipeline, load_text_embeddings
from animatediff.pipelines.lora import load_lcm_lora, load_lora_map
from animatediff.pipelines.pipeline_controlnet_img2img_reference import \
StableDiffusionControlNetImg2ImgReferencePipeline
from animatediff.schedulers import DiffusionScheduler, get_scheduler
from animatediff.settings import InferenceConfig, ModelConfig
from animatediff.utils.control_net_lllite import (ControlNetLLLite,
load_controlnet_lllite)
from animatediff.utils.convert_from_ckpt import convert_ldm_vae_checkpoint
from animatediff.utils.convert_lora_safetensor_to_diffusers import convert_lora
from animatediff.utils.model import (ensure_motion_modules,
get_checkpoint_weights,
get_checkpoint_weights_sdxl)
from animatediff.utils.util import (get_resized_image, get_resized_image2,
get_resized_images,
get_tensor_interpolation_method,
prepare_dwpose, prepare_extra_controlnet,
prepare_ip_adapter,
prepare_ip_adapter_sdxl, prepare_lcm_lora,
prepare_lllite, prepare_motion_module,
save_frames, save_imgs, save_video)
controlnet_address_table={
"controlnet_tile" : ['lllyasviel/control_v11f1e_sd15_tile'],
"controlnet_lineart_anime" : ['lllyasviel/control_v11p_sd15s2_lineart_anime'],
"controlnet_ip2p" : ['lllyasviel/control_v11e_sd15_ip2p'],
"controlnet_openpose" : ['lllyasviel/control_v11p_sd15_openpose'],
"controlnet_softedge" : ['lllyasviel/control_v11p_sd15_softedge'],
"controlnet_shuffle" : ['lllyasviel/control_v11e_sd15_shuffle'],
"controlnet_depth" : ['lllyasviel/control_v11f1p_sd15_depth'],
"controlnet_canny" : ['lllyasviel/control_v11p_sd15_canny'],
"controlnet_inpaint" : ['lllyasviel/control_v11p_sd15_inpaint'],
"controlnet_lineart" : ['lllyasviel/control_v11p_sd15_lineart'],
"controlnet_mlsd" : ['lllyasviel/control_v11p_sd15_mlsd'],
"controlnet_normalbae" : ['lllyasviel/control_v11p_sd15_normalbae'],
"controlnet_scribble" : ['lllyasviel/control_v11p_sd15_scribble'],
"controlnet_seg" : ['lllyasviel/control_v11p_sd15_seg'],
"qr_code_monster_v1" : ['monster-labs/control_v1p_sd15_qrcode_monster'],
"qr_code_monster_v2" : ['monster-labs/control_v1p_sd15_qrcode_monster', 'v2'],
"controlnet_mediapipe_face" : ['CrucibleAI/ControlNetMediaPipeFace', "diffusion_sd15"],
"animatediff_controlnet" : [None, "data/models/controlnet/animatediff_controlnet/controlnet_checkpoint.ckpt"]
}
# Edit this table if you want to change to another controlnet checkpoint
controlnet_address_table_sdxl={
# "controlnet_openpose" : ['thibaud/controlnet-openpose-sdxl-1.0'],
# "controlnet_softedge" : ['SargeZT/controlnet-sd-xl-1.0-softedge-dexined'],
# "controlnet_depth" : ['diffusers/controlnet-depth-sdxl-1.0-small'],
# "controlnet_canny" : ['diffusers/controlnet-canny-sdxl-1.0-small'],
# "controlnet_seg" : ['SargeZT/sdxl-controlnet-seg'],
"qr_code_monster_v1" : ['monster-labs/control_v1p_sdxl_qrcode_monster'],
}
# Edit this table if you want to change to another lllite checkpoint
lllite_address_table_sdxl={
"controlnet_tile" : ['models/lllite/bdsqlsz_controlllite_xl_tile_anime_β.safetensors'],
"controlnet_lineart_anime" : ['models/lllite/bdsqlsz_controlllite_xl_lineart_anime_denoise.safetensors'],
# "controlnet_ip2p" : ('lllyasviel/control_v11e_sd15_ip2p'),
"controlnet_openpose" : ['models/lllite/bdsqlsz_controlllite_xl_dw_openpose.safetensors'],
# "controlnet_openpose" : ['models/lllite/controllllite_v01032064e_sdxl_pose_anime.safetensors'],
"controlnet_softedge" : ['models/lllite/bdsqlsz_controlllite_xl_softedge.safetensors'],
"controlnet_shuffle" : ['models/lllite/bdsqlsz_controlllite_xl_t2i-adapter_color_shuffle.safetensors'],
"controlnet_depth" : ['models/lllite/bdsqlsz_controlllite_xl_depth.safetensors'],
"controlnet_canny" : ['models/lllite/bdsqlsz_controlllite_xl_canny.safetensors'],
# "controlnet_canny" : ['models/lllite/controllllite_v01032064e_sdxl_canny.safetensors'],
# "controlnet_inpaint" : ('lllyasviel/control_v11p_sd15_inpaint'),
# "controlnet_lineart" : ('lllyasviel/control_v11p_sd15_lineart'),
"controlnet_mlsd" : ['models/lllite/bdsqlsz_controlllite_xl_mlsd_V2.safetensors'],
"controlnet_normalbae" : ['models/lllite/bdsqlsz_controlllite_xl_normal.safetensors'],
"controlnet_scribble" : ['models/lllite/bdsqlsz_controlllite_xl_sketch.safetensors'],
"controlnet_seg" : ['models/lllite/bdsqlsz_controlllite_xl_segment_animeface_V2.safetensors'],
# "qr_code_monster_v1" : ['monster-labs/control_v1p_sdxl_qrcode_monster'],
# "qr_code_monster_v2" : ('monster-labs/control_v1p_sd15_qrcode_monster', 'v2'),
# "controlnet_mediapipe_face" : ('CrucibleAI/ControlNetMediaPipeFace', "diffusion_sd15"),
}
try:
import onnxruntime
onnxruntime_installed = True
except:
onnxruntime_installed = False
logger = logging.getLogger(__name__)
data_dir = get_dir("data")
default_base_path = data_dir.joinpath("models/huggingface/stable-diffusion-v1-5")
re_clean_prompt = re.compile(r"[^\w\-, ]")
controlnet_preprocessor = {}
def load_safetensors_lora(text_encoder, unet, lora_path, alpha=0.75, is_animatediff=True):
from safetensors.torch import load_file
from animatediff.utils.lora_diffusers import (LoRANetwork,
create_network_from_weights)
sd = load_file(lora_path)
print(f"create LoRA network")
lora_network: LoRANetwork = create_network_from_weights(text_encoder, unet, sd, multiplier=alpha, is_animatediff=is_animatediff)
print(f"load LoRA network weights")
lora_network.load_state_dict(sd, False)
#lora_network.merge_to(alpha)
lora_network.apply_to(alpha)
return lora_network
def load_safetensors_lora2(text_encoder, unet, lora_path, alpha=0.75, is_animatediff=True):
from safetensors.torch import load_file
from animatediff.utils.lora_diffusers import (LoRANetwork,
create_network_from_weights)
sd = load_file(lora_path)
print(f"create LoRA network")
lora_network: LoRANetwork = create_network_from_weights(text_encoder, unet, sd, multiplier=alpha, is_animatediff=is_animatediff)
print(f"load LoRA network weights")
lora_network.load_state_dict(sd, False)
lora_network.merge_to(alpha)
def load_tensors(path:Path,framework="pt",device="cpu"):
tensors = {}
if path.suffix == ".safetensors":
from safetensors import safe_open
with safe_open(path, framework=framework, device=device) as f:
for k in f.keys():
tensors[k] = f.get_tensor(k) # loads the full tensor given a key
else:
from torch import load
tensors = load(path, device)
if "state_dict" in tensors:
tensors = tensors["state_dict"]
return tensors
def load_motion_lora(unet, lora_path:Path, alpha=1.0):
state_dict = load_tensors(lora_path)
# directly update weight in diffusers model
for key in state_dict:
# only process lora down key
if "up." in key: continue
up_key = key.replace(".down.", ".up.")
model_key = key.replace("processor.", "").replace("_lora", "").replace("down.", "").replace("up.", "")
model_key = model_key.replace("to_out.", "to_out.0.")
layer_infos = model_key.split(".")[:-1]
curr_layer = unet
try:
while len(layer_infos) > 0:
temp_name = layer_infos.pop(0)
curr_layer = curr_layer.__getattr__(temp_name)
except:
logger.info(f"{model_key} not found")
continue
weight_down = state_dict[key]
weight_up = state_dict[up_key]
curr_layer.weight.data += alpha * torch.mm(weight_up, weight_down).to(curr_layer.weight.data.device)
class SegPreProcessor:
def __init__(self):
self.image_processor = AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-small")
self.processor = UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-small")
def __call__(self, input_image, detect_resolution=512, image_resolution=512, output_type="pil", **kwargs):
input_array = np.array(input_image, dtype=np.uint8)
input_array = HWC3(input_array)
input_array = aux_resize_image(input_array, detect_resolution)
pixel_values = self.image_processor(input_array, return_tensors="pt").pixel_values
with torch.no_grad():
outputs = self.processor(pixel_values.to(self.processor.device))
outputs.loss = outputs.loss.to("cpu") if outputs.loss is not None else outputs.loss
outputs.logits = outputs.logits.to("cpu") if outputs.logits is not None else outputs.logits
outputs.hidden_states = outputs.hidden_states.to("cpu") if outputs.hidden_states is not None else outputs.hidden_states
outputs.attentions = outputs.attentions.to("cpu") if outputs.attentions is not None else outputs.attentions
seg = self.image_processor.post_process_semantic_segmentation(outputs, target_sizes=[input_image.size[::-1]])[0]
color_seg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype=np.uint8) # height, width, 3
for label, color in enumerate(ade_palette()):
color_seg[seg == label, :] = color
color_seg = color_seg.astype(np.uint8)
color_seg = aux_resize_image(color_seg, image_resolution)
color_seg = Image.fromarray(color_seg)
return color_seg
class NullPreProcessor:
def __call__(self, input_image, **kwargs):
return input_image
class BlurPreProcessor:
def __call__(self, input_image, sigma=5.0, **kwargs):
import cv2
input_array = np.array(input_image, dtype=np.uint8)
input_array = HWC3(input_array)
dst = cv2.GaussianBlur(input_array, (0, 0), sigma)
return Image.fromarray(dst)
class TileResamplePreProcessor:
def resize(self, input_image, resolution):
import cv2
H, W, C = input_image.shape
H = float(H)
W = float(W)
k = float(resolution) / min(H, W)
H *= k
W *= k
img = cv2.resize(input_image, (int(W), int(H)), interpolation=cv2.INTER_LANCZOS4 if k > 1 else cv2.INTER_AREA)
return img
def __call__(self, input_image, down_sampling_rate = 1.0, **kwargs):
input_array = np.array(input_image, dtype=np.uint8)
input_array = HWC3(input_array)
H, W, C = input_array.shape
target_res = min(H,W) / down_sampling_rate
dst = self.resize(input_array, target_res)
return Image.fromarray(dst)
def is_valid_controlnet_type(type_str, is_sdxl):
if not is_sdxl:
return type_str in controlnet_address_table
else:
return (type_str in controlnet_address_table_sdxl) or (type_str in lllite_address_table_sdxl)
def load_controlnet_from_file(file_path, torch_dtype):
from safetensors.torch import load_file
prepare_extra_controlnet()
file_path = Path(file_path)
if file_path.exists() and file_path.is_file():
if file_path.suffix.lower() in [".pth", ".pt", ".ckpt"]:
controlnet_state_dict = torch.load(file_path, map_location="cpu", weights_only=True)
elif file_path.suffix.lower() == ".safetensors":
controlnet_state_dict = load_file(file_path, device="cpu")
else:
raise RuntimeError(
f"unknown file format for controlnet weights: {file_path.suffix}"
)
else:
raise FileNotFoundError(f"no controlnet weights found in {file_path}")
if file_path.parent.name == "animatediff_controlnet":
model = ControlNetModel(cross_attention_dim=768)
else:
model = ControlNetModel()
missing, _ = model.load_state_dict(controlnet_state_dict["state_dict"], strict=False)
if len(missing) > 0:
logger.info(f"ControlNetModel has missing keys: {missing}")
return model.to(dtype=torch_dtype)
def create_controlnet_model(pipe, type_str, is_sdxl):
if not is_sdxl:
if type_str in controlnet_address_table:
addr = controlnet_address_table[type_str]
if addr[0] != None:
if len(addr) == 1:
return ControlNetModel.from_pretrained(addr[0], torch_dtype=torch.float16)
else:
return ControlNetModel.from_pretrained(addr[0], subfolder=addr[1], torch_dtype=torch.float16)
else:
return load_controlnet_from_file(addr[1],torch_dtype=torch.float16)
else:
raise ValueError(f"unknown controlnet type {type_str}")
else:
if type_str in controlnet_address_table_sdxl:
addr = controlnet_address_table_sdxl[type_str]
if len(addr) == 1:
return ControlNetModel.from_pretrained(addr[0], torch_dtype=torch.float16)
else:
return ControlNetModel.from_pretrained(addr[0], subfolder=addr[1], torch_dtype=torch.float16)
elif type_str in lllite_address_table_sdxl:
addr = lllite_address_table_sdxl[type_str]
model_path = data_dir.joinpath(addr[0])
return load_controlnet_lllite(model_path, pipe, torch_dtype=torch.float16)
else:
raise ValueError(f"unknown controlnet type {type_str}")
default_preprocessor_table={
"controlnet_lineart_anime":"lineart_anime",
"controlnet_openpose": "openpose_full" if onnxruntime_installed==False else "dwpose",
"controlnet_softedge":"softedge_hedsafe",
"controlnet_shuffle":"shuffle",
"controlnet_depth":"depth_midas",
"controlnet_canny":"canny",
"controlnet_lineart":"lineart_realistic",
"controlnet_mlsd":"mlsd",
"controlnet_normalbae":"normal_bae",
"controlnet_scribble":"scribble_pidsafe",
"controlnet_seg":"upernet_seg",
"controlnet_mediapipe_face":"mediapipe_face",
"qr_code_monster_v1":"depth_midas",
"qr_code_monster_v2":"depth_midas",
}
def create_preprocessor_from_name(pre_type):
if pre_type == "dwpose":
prepare_dwpose()
return DWposeDetector()
elif pre_type == "upernet_seg":
return SegPreProcessor()
elif pre_type == "blur":
return BlurPreProcessor()
elif pre_type == "tile_resample":
return TileResamplePreProcessor()
elif pre_type == "none":
return NullPreProcessor()
elif pre_type in MODELS:
return ControlnetPreProcessor(pre_type)
else:
raise ValueError(f"unknown controlnet preprocessor type {pre_type}")
def create_default_preprocessor(type_str):
if type_str in default_preprocessor_table:
pre_type = default_preprocessor_table[type_str]
else:
pre_type = "none"
return create_preprocessor_from_name(pre_type)
def get_preprocessor(type_str, device_str, preprocessor_map):
if type_str not in controlnet_preprocessor:
if preprocessor_map:
controlnet_preprocessor[type_str] = create_preprocessor_from_name(preprocessor_map["type"])
if type_str not in controlnet_preprocessor:
controlnet_preprocessor[type_str] = create_default_preprocessor(type_str)
if hasattr(controlnet_preprocessor[type_str], "processor"):
if hasattr(controlnet_preprocessor[type_str].processor, "to"):
if device_str:
controlnet_preprocessor[type_str].processor.to(device_str)
elif hasattr(controlnet_preprocessor[type_str], "to"):
if device_str:
controlnet_preprocessor[type_str].to(device_str)
return controlnet_preprocessor[type_str]
def clear_controlnet_preprocessor(type_str = None):
global controlnet_preprocessor
if type_str == None:
for t in controlnet_preprocessor:
controlnet_preprocessor[t] = None
controlnet_preprocessor={}
torch.cuda.empty_cache()
else:
controlnet_preprocessor[type_str] = None
torch.cuda.empty_cache()
def get_preprocessed_img(type_str, img, use_preprocessor, device_str, preprocessor_map):
if use_preprocessor:
param = {}
if preprocessor_map:
param = preprocessor_map["param"] if "param" in preprocessor_map else {}
return get_preprocessor(type_str, device_str, preprocessor_map)(img, **param)
else:
return img
def create_pipeline_sdxl(
base_model: Union[str, PathLike] = default_base_path,
model_config: ModelConfig = ...,
infer_config: InferenceConfig = ...,
use_xformers: bool = True,
video_length: int = 16,
motion_module_path = ...,
):
from animatediff.pipelines.sdxl_animation import AnimationPipeline
from animatediff.sdxl_models.unet import UNet3DConditionModel
logger.info("Loading tokenizer...")
tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained(base_model, subfolder="tokenizer")
logger.info("Loading text encoder...")
text_encoder: CLIPTextModel = CLIPTextModel.from_pretrained(base_model, subfolder="text_encoder", torch_dtype=torch.float16)
logger.info("Loading VAE...")
vae: AutoencoderKL = AutoencoderKL.from_pretrained(base_model, subfolder="vae")
logger.info("Loading tokenizer two...")
tokenizer_two = CLIPTokenizer.from_pretrained(base_model, subfolder="tokenizer_2")
logger.info("Loading text encoder two...")
text_encoder_two = CLIPTextModelWithProjection.from_pretrained(base_model, subfolder="text_encoder_2", torch_dtype=torch.float16)
logger.info("Loading UNet...")
unet: UNet3DConditionModel = UNet3DConditionModel.from_pretrained_2d(
pretrained_model_path=base_model,
motion_module_path=motion_module_path,
subfolder="unet",
unet_additional_kwargs=infer_config.unet_additional_kwargs,
)
# set up scheduler
sched_kwargs = infer_config.noise_scheduler_kwargs
scheduler = get_scheduler(model_config.scheduler, sched_kwargs)
logger.info(f'Using scheduler "{model_config.scheduler}" ({scheduler.__class__.__name__})')
if model_config.gradual_latent_hires_fix_map:
if "enable" in model_config.gradual_latent_hires_fix_map:
if model_config.gradual_latent_hires_fix_map["enable"]:
if model_config.scheduler not in (DiffusionScheduler.euler_a, DiffusionScheduler.lcm):
logger.warn("gradual_latent_hires_fix enable")
logger.warn(f"{model_config.scheduler=}")
logger.warn("If you are forced to exit with an error, change to euler_a or lcm")
# Load the checkpoint weights into the pipeline
if model_config.path is not None:
model_path = data_dir.joinpath(model_config.path)
logger.info(f"Loading weights from {model_path}")
if model_path.is_file():
logger.debug("Loading from single checkpoint file")
unet_state_dict, tenc_state_dict, tenc2_state_dict, vae_state_dict = get_checkpoint_weights_sdxl(model_path)
elif model_path.is_dir():
logger.debug("Loading from Diffusers model directory")
temp_pipeline = StableDiffusionXLPipeline.from_pretrained(model_path)
unet_state_dict, tenc_state_dict, tenc2_state_dict, vae_state_dict = (
temp_pipeline.unet.state_dict(),
temp_pipeline.text_encoder.state_dict(),
temp_pipeline.text_encoder_2.state_dict(),
temp_pipeline.vae.state_dict(),
)
del temp_pipeline
else:
raise FileNotFoundError(f"model_path {model_path} is not a file or directory")
# Load into the unet, TE, and VAE
logger.info("Merging weights into UNet...")
_, unet_unex = unet.load_state_dict(unet_state_dict, strict=False)
if len(unet_unex) > 0:
raise ValueError(f"UNet has unexpected keys: {unet_unex}")
tenc_missing, _ = text_encoder.load_state_dict(tenc_state_dict, strict=False)
if len(tenc_missing) > 0:
raise ValueError(f"TextEncoder has missing keys: {tenc_missing}")
tenc2_missing, _ = text_encoder_two.load_state_dict(tenc2_state_dict, strict=False)
if len(tenc2_missing) > 0:
raise ValueError(f"TextEncoder2 has missing keys: {tenc2_missing}")
vae_missing, _ = vae.load_state_dict(vae_state_dict, strict=False)
if len(vae_missing) > 0:
raise ValueError(f"VAE has missing keys: {vae_missing}")
else:
logger.info("Using base model weights (no checkpoint/LoRA)")
if model_config.vae_path:
vae_path = data_dir.joinpath(model_config.vae_path)
logger.info(f"Loading vae from {vae_path}")
if vae_path.is_dir():
vae = AutoencoderKL.from_pretrained(vae_path)
else:
tensors = load_tensors(vae_path)
tensors = convert_ldm_vae_checkpoint(tensors, vae.config)
vae.load_state_dict(tensors)
unet.to(torch.float16)
text_encoder.to(torch.float16)
text_encoder_two.to(torch.float16)
del unet_state_dict
del tenc_state_dict
del tenc2_state_dict
del vae_state_dict
# enable xformers if available
if use_xformers:
logger.info("Enabling xformers memory-efficient attention")
unet.enable_xformers_memory_efficient_attention()
# motion lora
for l in model_config.motion_lora_map:
lora_path = data_dir.joinpath(l)
logger.info(f"loading motion lora {lora_path=}")
if lora_path.is_file():
logger.info(f"Loading motion lora {lora_path}")
logger.info(f"alpha = {model_config.motion_lora_map[l]}")
load_motion_lora(unet, lora_path, alpha=model_config.motion_lora_map[l])
else:
raise ValueError(f"{lora_path=} not found")
logger.info("Creating AnimationPipeline...")
pipeline = AnimationPipeline(
vae=vae,
text_encoder=text_encoder,
text_encoder_2=text_encoder_two,
tokenizer=tokenizer,
tokenizer_2=tokenizer_two,
unet=unet,
scheduler=scheduler,
controlnet_map=None,
)
del vae
del text_encoder
del text_encoder_two
del tokenizer
del tokenizer_two
del unet
torch.cuda.empty_cache()
pipeline.lcm = None
if model_config.lcm_map:
if model_config.lcm_map["enable"]:
prepare_lcm_lora()
load_lcm_lora(pipeline, model_config.lcm_map, is_sdxl=True)
load_lora_map(pipeline, model_config.lora_map, video_length, is_sdxl=True)
pipeline.unet = pipeline.unet.half()
pipeline.text_encoder = pipeline.text_encoder.half()
pipeline.text_encoder_2 = pipeline.text_encoder_2.half()
# Load TI embeddings
pipeline.text_encoder = pipeline.text_encoder.to("cuda")
pipeline.text_encoder_2 = pipeline.text_encoder_2.to("cuda")
load_text_embeddings(pipeline, is_sdxl=True)
pipeline.text_encoder = pipeline.text_encoder.to("cpu")
pipeline.text_encoder_2 = pipeline.text_encoder_2.to("cpu")
return pipeline
def create_pipeline(
base_model: Union[str, PathLike] = default_base_path,
model_config: ModelConfig = ...,
infer_config: InferenceConfig = ...,
use_xformers: bool = True,
video_length: int = 16,
is_sdxl:bool = False,
) -> DiffusionPipeline:
"""Create an AnimationPipeline from a pretrained model.
Uses the base_model argument to load or download the pretrained reference pipeline model."""
# make sure motion_module is a Path and exists
logger.info("Checking motion module...")
motion_module = data_dir.joinpath(model_config.motion_module)
if not (motion_module.exists() and motion_module.is_file()):
prepare_motion_module()
if not (motion_module.exists() and motion_module.is_file()):
# check for safetensors version
motion_module = motion_module.with_suffix(".safetensors")
if not (motion_module.exists() and motion_module.is_file()):
# download from HuggingFace Hub if not found
ensure_motion_modules()
if not (motion_module.exists() and motion_module.is_file()):
# this should never happen, but just in case...
raise FileNotFoundError(f"Motion module {motion_module} does not exist or is not a file!")
if is_sdxl:
return create_pipeline_sdxl(
base_model=base_model,
model_config=model_config,
infer_config=infer_config,
use_xformers=use_xformers,
video_length=video_length,
motion_module_path=motion_module,
)
logger.info("Loading tokenizer...")
tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained(base_model, subfolder="tokenizer")
logger.info("Loading text encoder...")
text_encoder: CLIPSkipTextModel = CLIPSkipTextModel.from_pretrained(base_model, subfolder="text_encoder")
logger.info("Loading VAE...")
vae: AutoencoderKL = AutoencoderKL.from_pretrained(base_model, subfolder="vae")
logger.info("Loading UNet...")
unet: UNet3DConditionModel = UNet3DConditionModel.from_pretrained_2d(
pretrained_model_path=base_model,
motion_module_path=motion_module,
subfolder="unet",
unet_additional_kwargs=infer_config.unet_additional_kwargs,
)
feature_extractor = CLIPImageProcessor.from_pretrained(base_model, subfolder="feature_extractor")
# set up scheduler
if model_config.gradual_latent_hires_fix_map:
if "enable" in model_config.gradual_latent_hires_fix_map:
if model_config.gradual_latent_hires_fix_map["enable"]:
if model_config.scheduler not in (DiffusionScheduler.euler_a, DiffusionScheduler.lcm):
logger.warn("gradual_latent_hires_fix enable")
logger.warn(f"{model_config.scheduler=}")
logger.warn("If you are forced to exit with an error, change to euler_a or lcm")
sched_kwargs = infer_config.noise_scheduler_kwargs
scheduler = get_scheduler(model_config.scheduler, sched_kwargs)
logger.info(f'Using scheduler "{model_config.scheduler}" ({scheduler.__class__.__name__})')
# Load the checkpoint weights into the pipeline
if model_config.path is not None:
model_path = data_dir.joinpath(model_config.path)
logger.info(f"Loading weights from {model_path}")
if model_path.is_file():
logger.debug("Loading from single checkpoint file")
unet_state_dict, tenc_state_dict, vae_state_dict = get_checkpoint_weights(model_path)
elif model_path.is_dir():
logger.debug("Loading from Diffusers model directory")
temp_pipeline = StableDiffusionPipeline.from_pretrained(model_path)
unet_state_dict, tenc_state_dict, vae_state_dict = (
temp_pipeline.unet.state_dict(),
temp_pipeline.text_encoder.state_dict(),
temp_pipeline.vae.state_dict(),
)
del temp_pipeline
else:
raise FileNotFoundError(f"model_path {model_path} is not a file or directory")
# Load into the unet, TE, and VAE
logger.info("Merging weights into UNet...")
_, unet_unex = unet.load_state_dict(unet_state_dict, strict=False)
if len(unet_unex) > 0:
raise ValueError(f"UNet has unexpected keys: {unet_unex}")
tenc_missing, _ = text_encoder.load_state_dict(tenc_state_dict, strict=False)
if len(tenc_missing) > 0:
raise ValueError(f"TextEncoder has missing keys: {tenc_missing}")
vae_missing, _ = vae.load_state_dict(vae_state_dict, strict=False)
if len(vae_missing) > 0:
raise ValueError(f"VAE has missing keys: {vae_missing}")
else:
logger.info("Using base model weights (no checkpoint/LoRA)")
if model_config.vae_path:
vae_path = data_dir.joinpath(model_config.vae_path)
logger.info(f"Loading vae from {vae_path}")
if vae_path.is_dir():
vae = AutoencoderKL.from_pretrained(vae_path)
else:
tensors = load_tensors(vae_path)
tensors = convert_ldm_vae_checkpoint(tensors, vae.config)
vae.load_state_dict(tensors)
# enable xformers if available
if use_xformers:
logger.info("Enabling xformers memory-efficient attention")
unet.enable_xformers_memory_efficient_attention()
if False:
# lora
for l in model_config.lora_map:
lora_path = data_dir.joinpath(l)
if lora_path.is_file():
logger.info(f"Loading lora {lora_path}")
logger.info(f"alpha = {model_config.lora_map[l]}")
load_safetensors_lora(text_encoder, unet, lora_path, alpha=model_config.lora_map[l])
# motion lora
for l in model_config.motion_lora_map:
lora_path = data_dir.joinpath(l)
logger.info(f"loading motion lora {lora_path=}")
if lora_path.is_file():
logger.info(f"Loading motion lora {lora_path}")
logger.info(f"alpha = {model_config.motion_lora_map[l]}")
load_motion_lora(unet, lora_path, alpha=model_config.motion_lora_map[l])
else:
raise ValueError(f"{lora_path=} not found")
logger.info("Creating AnimationPipeline...")
pipeline = AnimationPipeline(
vae=vae,
text_encoder=text_encoder,
tokenizer=tokenizer,
unet=unet,
scheduler=scheduler,
feature_extractor=feature_extractor,
controlnet_map=None,
)
pipeline.lcm = None
if model_config.lcm_map:
if model_config.lcm_map["enable"]:
prepare_lcm_lora()
load_lcm_lora(pipeline, model_config.lcm_map, is_sdxl=False)
load_lora_map(pipeline, model_config.lora_map, video_length)
# Load TI embeddings
pipeline.unet = pipeline.unet.half()
pipeline.text_encoder = pipeline.text_encoder.half()
pipeline.text_encoder = pipeline.text_encoder.to("cuda")
load_text_embeddings(pipeline)
pipeline.text_encoder = pipeline.text_encoder.to("cpu")
return pipeline
def load_controlnet_models(pipe: DiffusionPipeline, model_config: ModelConfig = ..., is_sdxl:bool = False):
# controlnet
if is_sdxl:
prepare_lllite()
controlnet_map={}
if model_config.controlnet_map:
c_image_dir = data_dir.joinpath( model_config.controlnet_map["input_image_dir"] )
for c in model_config.controlnet_map:
item = model_config.controlnet_map[c]
if type(item) is dict:
if item["enable"] == True:
if is_valid_controlnet_type(c, is_sdxl):
img_dir = c_image_dir.joinpath( c )
cond_imgs = sorted(glob.glob( os.path.join(img_dir, "[0-9]*.png"), recursive=False))
if len(cond_imgs) > 0:
logger.info(f"loading {c=} model")
controlnet_map[c] = create_controlnet_model(pipe, c , is_sdxl)
else:
logger.info(f"invalid controlnet type for {'sdxl' if is_sdxl else 'sd15'} : {c}")
if not controlnet_map:
controlnet_map = None
pipe.controlnet_map = controlnet_map
def unload_controlnet_models(pipe: AnimationPipeline):
from animatediff.utils.util import show_gpu
if pipe.controlnet_map:
for c in pipe.controlnet_map:
controlnet = pipe.controlnet_map[c]
if isinstance(controlnet, ControlNetLLLite):
controlnet.unapply_to()
del controlnet
#show_gpu("before uload controlnet")
pipe.controlnet_map = None
torch.cuda.empty_cache()
#show_gpu("after unload controlnet")
def create_us_pipeline(
model_config: ModelConfig = ...,
infer_config: InferenceConfig = ...,
use_xformers: bool = True,
use_controlnet_ref: bool = False,
use_controlnet_tile: bool = False,
use_controlnet_line_anime: bool = False,
use_controlnet_ip2p: bool = False,
) -> DiffusionPipeline:
# set up scheduler
sched_kwargs = infer_config.noise_scheduler_kwargs
scheduler = get_scheduler(model_config.scheduler, sched_kwargs)
logger.info(f'Using scheduler "{model_config.scheduler}" ({scheduler.__class__.__name__})')
controlnet = []
if use_controlnet_tile:
controlnet.append( ControlNetModel.from_pretrained('lllyasviel/control_v11f1e_sd15_tile') )
if use_controlnet_line_anime:
controlnet.append( ControlNetModel.from_pretrained('lllyasviel/control_v11p_sd15s2_lineart_anime') )
if use_controlnet_ip2p:
controlnet.append( ControlNetModel.from_pretrained('lllyasviel/control_v11e_sd15_ip2p') )
if len(controlnet) == 1:
controlnet = controlnet[0]
elif len(controlnet) == 0:
controlnet = None
# Load the checkpoint weights into the pipeline
pipeline:DiffusionPipeline
if model_config.path is not None:
model_path = data_dir.joinpath(model_config.path)
logger.info(f"Loading weights from {model_path}")
if model_path.is_file():
def is_empty_dir(path):
import os
return len(os.listdir(path)) == 0
save_path = data_dir.joinpath("models/huggingface/" + model_path.stem + "_" + str(model_path.stat().st_size))
save_path.mkdir(exist_ok=True)
if save_path.is_dir() and is_empty_dir(save_path):
# StableDiffusionControlNetImg2ImgPipeline.from_single_file does not exist in version 18.2
logger.debug("Loading from single checkpoint file")
tmp_pipeline = StableDiffusionPipeline.from_single_file(
pretrained_model_link_or_path=str(model_path.absolute())
)
tmp_pipeline.save_pretrained(save_path, safe_serialization=True)
del tmp_pipeline
if use_controlnet_ref:
pipeline = StableDiffusionControlNetImg2ImgReferencePipeline.from_pretrained(
save_path,
controlnet=controlnet,
local_files_only=False,
load_safety_checker=False,
safety_checker=None,
)
else:
pipeline = StableDiffusionControlNetImg2ImgPipeline.from_pretrained(
save_path,
controlnet=controlnet,
local_files_only=False,
load_safety_checker=False,
safety_checker=None,
)
elif model_path.is_dir():
logger.debug("Loading from Diffusers model directory")
if use_controlnet_ref:
pipeline = StableDiffusionControlNetImg2ImgReferencePipeline.from_pretrained(
model_path,
controlnet=controlnet,
local_files_only=True,
load_safety_checker=False,
safety_checker=None,
)
else:
pipeline = StableDiffusionControlNetImg2ImgPipeline.from_pretrained(
model_path,
controlnet=controlnet,
local_files_only=True,
load_safety_checker=False,
safety_checker=None,
)
else:
raise FileNotFoundError(f"model_path {model_path} is not a file or directory")
else:
raise ValueError("model_config.path is invalid")
pipeline.scheduler = scheduler
# enable xformers if available
if use_xformers:
logger.info("Enabling xformers memory-efficient attention")
pipeline.enable_xformers_memory_efficient_attention()
# lora
for l in model_config.lora_map:
lora_path = data_dir.joinpath(l)
if lora_path.is_file():
alpha = model_config.lora_map[l]
if isinstance(alpha, dict):
alpha = 0.75
logger.info(f"Loading lora {lora_path}")
logger.info(f"alpha = {alpha}")
load_safetensors_lora2(pipeline.text_encoder, pipeline.unet, lora_path, alpha=alpha,is_animatediff=False)
# Load TI embeddings
pipeline.unet = pipeline.unet.half()
pipeline.text_encoder = pipeline.text_encoder.half()
pipeline.text_encoder = pipeline.text_encoder.to("cuda")
load_text_embeddings(pipeline)
pipeline.text_encoder = pipeline.text_encoder.to("cpu")
return pipeline
def seed_everything(seed):
import random
import numpy as np
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed % (2**32))
random.seed(seed)
def controlnet_preprocess(
controlnet_map: Dict[str, Any] = None,
width: int = 512,
height: int = 512,
duration: int = 16,
out_dir: PathLike = ...,
device_str:str=None,
is_sdxl:bool = False,
):
if not controlnet_map:
return None, None, None, None
out_dir = Path(out_dir) # ensure out_dir is a Path
# { 0 : { "type_str" : IMAGE, "type_str2" : IMAGE } }
controlnet_image_map={}
controlnet_type_map={}
c_image_dir = data_dir.joinpath( controlnet_map["input_image_dir"] )
save_detectmap = controlnet_map["save_detectmap"] if "save_detectmap" in controlnet_map else True
preprocess_on_gpu = controlnet_map["preprocess_on_gpu"] if "preprocess_on_gpu" in controlnet_map else True
device_str = device_str if preprocess_on_gpu else None
for c in controlnet_map:
if c == "controlnet_ref":
continue
item = controlnet_map[c]
processed = False
if type(item) is dict:
if item["enable"] == True:
if is_valid_controlnet_type(c, is_sdxl):
preprocessor_map = item["preprocessor"] if "preprocessor" in item else {}
img_dir = c_image_dir.joinpath( c )
cond_imgs = sorted(glob.glob( os.path.join(img_dir, "[0-9]*.png"), recursive=False))
if len(cond_imgs) > 0:
controlnet_type_map[c] = {
"controlnet_conditioning_scale" : item["controlnet_conditioning_scale"],
"control_guidance_start" : item["control_guidance_start"],
"control_guidance_end" : item["control_guidance_end"],
"control_scale_list" : item["control_scale_list"],
"guess_mode" : item["guess_mode"] if "guess_mode" in item else False,
"control_region_list" : item["control_region_list"] if "control_region_list" in item else []
}
use_preprocessor = item["use_preprocessor"] if "use_preprocessor" in item else True
for img_path in tqdm(cond_imgs, desc=f"Preprocessing images ({c})"):
frame_no = int(Path(img_path).stem)
if frame_no < duration:
if frame_no not in controlnet_image_map:
controlnet_image_map[frame_no] = {}
controlnet_image_map[frame_no][c] = get_preprocessed_img( c, get_resized_image2(img_path, 512) , use_preprocessor, device_str, preprocessor_map)
processed = True
else:
logger.info(f"invalid controlnet type for {'sdxl' if is_sdxl else 'sd15'} : {c}")
if save_detectmap and processed:
det_dir = out_dir.joinpath(f"{0:02d}_detectmap/{c}")
det_dir.mkdir(parents=True, exist_ok=True)
for frame_no in tqdm(controlnet_image_map, desc=f"Saving Preprocessed images ({c})"):
save_path = det_dir.joinpath(f"{frame_no:08d}.png")
if c in controlnet_image_map[frame_no]:
controlnet_image_map[frame_no][c].save(save_path)
clear_controlnet_preprocessor(c)
clear_controlnet_preprocessor()
controlnet_ref_map = None
if "controlnet_ref" in controlnet_map:
r = controlnet_map["controlnet_ref"]
if r["enable"] == True:
org_name = data_dir.joinpath( r["ref_image"]).stem
# ref_image = get_resized_image( data_dir.joinpath( r["ref_image"] ) , width, height)
ref_image = get_resized_image2( data_dir.joinpath( r["ref_image"] ) , 512)
if ref_image is not None:
controlnet_ref_map = {
"ref_image" : ref_image,
"style_fidelity" : r["style_fidelity"],
"attention_auto_machine_weight" : r["attention_auto_machine_weight"],
"gn_auto_machine_weight" : r["gn_auto_machine_weight"],
"reference_attn" : r["reference_attn"],
"reference_adain" : r["reference_adain"],
"scale_pattern" : r["scale_pattern"]
}
if save_detectmap:
det_dir = out_dir.joinpath(f"{0:02d}_detectmap/controlnet_ref")
det_dir.mkdir(parents=True, exist_ok=True)
save_path = det_dir.joinpath(f"{org_name}.png")
ref_image.save(save_path)
controlnet_no_shrink = ["controlnet_tile","animatediff_controlnet","controlnet_canny","controlnet_normalbae","controlnet_depth","controlnet_lineart","controlnet_lineart_anime","controlnet_scribble","controlnet_seg","controlnet_softedge","controlnet_mlsd"]
if "no_shrink_list" in controlnet_map:
controlnet_no_shrink = controlnet_map["no_shrink_list"]
return controlnet_image_map, controlnet_type_map, controlnet_ref_map, controlnet_no_shrink
def ip_adapter_preprocess(
ip_adapter_config_map: Dict[str, Any] = None,
width: int = 512,
height: int = 512,
duration: int = 16,
out_dir: PathLike = ...,
is_sdxl: bool = False,
):
ip_adapter_map={}
processed = False
if ip_adapter_config_map:
if ip_adapter_config_map["enable"] == True:
resized_to_square = ip_adapter_config_map["resized_to_square"] if "resized_to_square" in ip_adapter_config_map else False
image_dir = data_dir.joinpath( ip_adapter_config_map["input_image_dir"] )
imgs = sorted(chain.from_iterable([glob.glob(os.path.join(image_dir, f"[0-9]*{ext}")) for ext in IMG_EXTENSIONS]))
if len(imgs) > 0:
prepare_ip_adapter_sdxl() if is_sdxl else prepare_ip_adapter()
ip_adapter_map["images"] = {}
for img_path in tqdm(imgs, desc=f"Preprocessing images (ip_adapter)"):
frame_no = int(Path(img_path).stem)
if frame_no < duration:
if resized_to_square:
ip_adapter_map["images"][frame_no] = get_resized_image(img_path, 256, 256)
else:
ip_adapter_map["images"][frame_no] = get_resized_image2(img_path, 256)
processed = True
if processed:
ip_adapter_config_map["prompt_fixed_ratio"] = max(min(1.0, ip_adapter_config_map["prompt_fixed_ratio"]),0)
prompt_fixed_ratio = ip_adapter_config_map["prompt_fixed_ratio"]
prompt_map = ip_adapter_map["images"]
prompt_map = dict(sorted(prompt_map.items()))
key_list = list(prompt_map.keys())
for k0,k1 in zip(key_list,key_list[1:]+[duration]):
k05 = k0 + round((k1-k0) * prompt_fixed_ratio)
if k05 == k1:
k05 -= 1
if k05 != k0:
prompt_map[k05] = prompt_map[k0]
ip_adapter_map["images"] = prompt_map
if (ip_adapter_config_map["save_input_image"] == True) and processed:
det_dir = out_dir.joinpath(f"{0:02d}_ip_adapter/")
det_dir.mkdir(parents=True, exist_ok=True)
for frame_no in tqdm(ip_adapter_map["images"], desc=f"Saving Preprocessed images (ip_adapter)"):
save_path = det_dir.joinpath(f"{frame_no:08d}.png")
ip_adapter_map["images"][frame_no].save(save_path)
return ip_adapter_map if processed else None
def prompt_preprocess(
prompt_config_map: Dict[str, Any],
head_prompt: str,
tail_prompt: str,
prompt_fixed_ratio: float,
video_length: int,
):
prompt_map = {}
for k in prompt_config_map.keys():
if int(k) < video_length:
pr = prompt_config_map[k]
if head_prompt:
pr = head_prompt + "," + pr
if tail_prompt:
pr = pr + "," + tail_prompt
prompt_map[int(k)]=pr
prompt_map = dict(sorted(prompt_map.items()))
key_list = list(prompt_map.keys())
for k0,k1 in zip(key_list,key_list[1:]+[video_length]):
k05 = k0 + round((k1-k0) * prompt_fixed_ratio)
if k05 == k1:
k05 -= 1
if k05 != k0:
prompt_map[k05] = prompt_map[k0]
return prompt_map
def region_preprocess(
model_config: ModelConfig = ...,
width: int = 512,
height: int = 512,
duration: int = 16,
out_dir: PathLike = ...,
is_init_img_exist: bool = False,
is_sdxl:bool = False,
):
is_bg_init_img = False
if is_init_img_exist:
if model_config.region_map:
if "background" in model_config.region_map:
is_bg_init_img = model_config.region_map["background"]["is_init_img"]
region_condi_list=[]
region2index={}
condi_index = 0
prev_ip_map = None
if not is_bg_init_img:
ip_map = ip_adapter_preprocess(
model_config.ip_adapter_map,
width,
height,
duration,
out_dir,
is_sdxl
)
if ip_map:
prev_ip_map = ip_map
condition_map = {
"prompt_map": prompt_preprocess(
model_config.prompt_map,
model_config.head_prompt,
model_config.tail_prompt,
model_config.prompt_fixed_ratio,
duration
),
"ip_adapter_map": ip_map
}
region_condi_list.append( condition_map )
bg_src = condi_index
condi_index += 1
else:
bg_src = -1
region_list=[
{
"mask_images": None,
"src" : bg_src,
"crop_generation_rate" : 0
}
]
region2index["background"]=bg_src
if model_config.region_map:
for r in model_config.region_map:
if r == "background":
continue
if model_config.region_map[r]["enable"] != True:
continue
region_dir = out_dir.joinpath(f"region_{int(r):05d}/")
region_dir.mkdir(parents=True, exist_ok=True)
mask_map = mask_preprocess(
model_config.region_map[r],
width,
height,
duration,
region_dir
)
if not mask_map:
continue
if model_config.region_map[r]["is_init_img"] == False:
ip_map = ip_adapter_preprocess(
model_config.region_map[r]["condition"]["ip_adapter_map"],
width,
height,
duration,
region_dir,
is_sdxl
)
if ip_map:
prev_ip_map = ip_map
condition_map={
"prompt_map": prompt_preprocess(
model_config.region_map[r]["condition"]["prompt_map"],
model_config.region_map[r]["condition"]["head_prompt"],
model_config.region_map[r]["condition"]["tail_prompt"],
model_config.region_map[r]["condition"]["prompt_fixed_ratio"],
duration
),
"ip_adapter_map": ip_map
}
region_condi_list.append( condition_map )
src = condi_index
condi_index += 1
else:
if is_init_img_exist == False:
logger.warn("'is_init_img' : true / BUT init_img is not exist -> ignore region")
continue
src = -1
region_list.append(
{
"mask_images": mask_map,
"src" : src,
"crop_generation_rate" : model_config.region_map[r]["crop_generation_rate"] if "crop_generation_rate" in model_config.region_map[r] else 0
}
)
region2index[r]=src
ip_adapter_config_map = None
if prev_ip_map is not None:
ip_adapter_config_map={}
ip_adapter_config_map["scale"] = model_config.ip_adapter_map["scale"]
ip_adapter_config_map["is_plus"] = model_config.ip_adapter_map["is_plus"]
ip_adapter_config_map["is_plus_face"] = model_config.ip_adapter_map["is_plus_face"] if "is_plus_face" in model_config.ip_adapter_map else False
ip_adapter_config_map["is_light"] = model_config.ip_adapter_map["is_light"] if "is_light" in model_config.ip_adapter_map else False
ip_adapter_config_map["is_full_face"] = model_config.ip_adapter_map["is_full_face"] if "is_full_face" in model_config.ip_adapter_map else False
for c in region_condi_list:
if c["ip_adapter_map"] == None:
logger.info(f"fill map")
c["ip_adapter_map"] = prev_ip_map
#for c in region_condi_list:
# logger.info(f"{c['prompt_map']=}")
if not region_condi_list:
raise ValueError("erro! There is not a single valid region")
return region_condi_list, region_list, ip_adapter_config_map, region2index
def img2img_preprocess(
img2img_config_map: Dict[str, Any] = None,
width: int = 512,
height: int = 512,
duration: int = 16,
out_dir: PathLike = ...,
):
img2img_map={}
processed = False
if img2img_config_map:
if img2img_config_map["enable"] == True:
image_dir = data_dir.joinpath( img2img_config_map["init_img_dir"] )
imgs = sorted(glob.glob( os.path.join(image_dir, "[0-9]*.png"), recursive=False))
if len(imgs) > 0:
img2img_map["images"] = {}
img2img_map["denoising_strength"] = img2img_config_map["denoising_strength"]
for img_path in tqdm(imgs, desc=f"Preprocessing images (img2img)"):
frame_no = int(Path(img_path).stem)
if frame_no < duration:
img2img_map["images"][frame_no] = get_resized_image(img_path, width, height)
processed = True
if (img2img_config_map["save_init_image"] == True) and processed:
det_dir = out_dir.joinpath(f"{0:02d}_img2img_init_img/")
det_dir.mkdir(parents=True, exist_ok=True)
for frame_no in tqdm(img2img_map["images"], desc=f"Saving Preprocessed images (img2img)"):
save_path = det_dir.joinpath(f"{frame_no:08d}.png")
img2img_map["images"][frame_no].save(save_path)
return img2img_map if processed else None
def mask_preprocess(
region_config_map: Dict[str, Any] = None,
width: int = 512,
height: int = 512,
duration: int = 16,
out_dir: PathLike = ...,
):
mask_map={}
processed = False
size = None
mode = None
if region_config_map:
image_dir = data_dir.joinpath( region_config_map["mask_dir"] )
imgs = sorted(glob.glob( os.path.join(image_dir, "[0-9]*.png"), recursive=False))
if len(imgs) > 0:
for img_path in tqdm(imgs, desc=f"Preprocessing images (mask)"):
frame_no = int(Path(img_path).stem)
if frame_no < duration:
mask_map[frame_no] = get_resized_image(img_path, width, height)
if size is None:
size = mask_map[frame_no].size
mode = mask_map[frame_no].mode
processed = True
if processed:
if 0 in mask_map:
prev_img = mask_map[0]
else:
prev_img = Image.new(mode, size, color=0)
for i in range(duration):
if i in mask_map:
prev_img = mask_map[i]
else:
mask_map[i] = prev_img
if (region_config_map["save_mask"] == True) and processed:
det_dir = out_dir.joinpath(f"mask/")
det_dir.mkdir(parents=True, exist_ok=True)
for frame_no in tqdm(mask_map, desc=f"Saving Preprocessed images (mask)"):
save_path = det_dir.joinpath(f"{frame_no:08d}.png")
mask_map[frame_no].save(save_path)
return mask_map if processed else None
def wild_card_conversion(model_config: ModelConfig = ...,):
from animatediff.utils.wild_card import replace_wild_card
wild_card_dir = get_dir("wildcards")
for k in model_config.prompt_map.keys():
model_config.prompt_map[k] = replace_wild_card(model_config.prompt_map[k], wild_card_dir)
if model_config.head_prompt:
model_config.head_prompt = replace_wild_card(model_config.head_prompt, wild_card_dir)
if model_config.tail_prompt:
model_config.tail_prompt = replace_wild_card(model_config.tail_prompt, wild_card_dir)
model_config.prompt_fixed_ratio = max(min(1.0, model_config.prompt_fixed_ratio),0)
if model_config.region_map:
for r in model_config.region_map:
if r == "background":
continue
if "condition" in model_config.region_map[r]:
c = model_config.region_map[r]["condition"]
for k in c["prompt_map"].keys():
c["prompt_map"][k] = replace_wild_card(c["prompt_map"][k], wild_card_dir)
if "head_prompt" in c:
c["head_prompt"] = replace_wild_card(c["head_prompt"], wild_card_dir)
if "tail_prompt" in c:
c["tail_prompt"] = replace_wild_card(c["tail_prompt"], wild_card_dir)
if "prompt_fixed_ratio" in c:
c["prompt_fixed_ratio"] = max(min(1.0, c["prompt_fixed_ratio"]),0)
def save_output(
pipeline_output,
frame_dir:str,
out_file:str,
output_map : Dict[str,Any] = {},
no_frames : bool = False,
save_frames=save_frames,
save_video=None,
):
output_format = "gif"
output_fps = 8
if output_map:
output_format = output_map["format"] if "format" in output_map else output_format
output_fps = output_map["fps"] if "fps" in output_map else output_fps
if output_format == "mp4":
output_format = "h264"
if output_format == "gif":
out_file = out_file.with_suffix(".gif")
if no_frames is not True:
if save_frames:
save_frames(pipeline_output,frame_dir)
# generate the output filename and save the video
if save_video:
save_video(pipeline_output, out_file, output_fps)
else:
pipeline_output[0].save(
fp=out_file, format="GIF", append_images=pipeline_output[1:], save_all=True, duration=(1 / output_fps * 1000), loop=0
)
else:
if save_frames:
save_frames(pipeline_output,frame_dir)
from animatediff.rife.ffmpeg import (FfmpegEncoder, VideoCodec,
codec_extn)
out_file = out_file.with_suffix( f".{codec_extn(output_format)}" )
logger.info("Creating ffmpeg encoder...")
encoder = FfmpegEncoder(
frames_dir=frame_dir,
out_file=out_file,
codec=output_format,
in_fps=output_fps,
out_fps=output_fps,
lossless=False,
param= output_map["encode_param"] if "encode_param" in output_map else {}
)
logger.info("Encoding interpolated frames with ffmpeg...")
result = encoder.encode()
logger.debug(f"ffmpeg result: {result}")
def run_inference(
pipeline: DiffusionPipeline,
n_prompt: str = ...,
seed: int = -1,
steps: int = 25,
guidance_scale: float = 7.5,
unet_batch_size: int = 1,
width: int = 512,
height: int = 512,
duration: int = 16,
idx: int = 0,
out_dir: PathLike = ...,
context_frames: int = -1,
context_stride: int = 3,
context_overlap: int = 4,
context_schedule: str = "uniform",
clip_skip: int = 1,
controlnet_map: Dict[str, Any] = None,
controlnet_image_map: Dict[str,Any] = None,
controlnet_type_map: Dict[str,Any] = None,
controlnet_ref_map: Dict[str,Any] = None,
controlnet_no_shrink:List[str]=None,
no_frames :bool = False,
img2img_map: Dict[str,Any] = None,
ip_adapter_config_map: Dict[str,Any] = None,
region_list: List[Any] = None,
region_condi_list: List[Any] = None,
output_map: Dict[str,Any] = None,
is_single_prompt_mode: bool = False,
is_sdxl:bool=False,
apply_lcm_lora:bool=False,
gradual_latent_map: Dict[str,Any] = None,
):
out_dir = Path(out_dir) # ensure out_dir is a Path
# Trim and clean up the prompt for filename use
prompt_map = region_condi_list[0]["prompt_map"]
prompt_tags = [re_clean_prompt.sub("", tag).strip().replace(" ", "-") for tag in prompt_map[list(prompt_map.keys())[0]].split(",")]
prompt_str = "_".join((prompt_tags[:6]))[:50]
frame_dir = out_dir.joinpath(f"{idx:02d}-{seed}")
out_file = out_dir.joinpath(f"{idx:02d}_{seed}_{prompt_str}")
def preview_callback(i: int, video: torch.Tensor, save_fn: Callable[[torch.Tensor], None], out_file: str) -> None:
save_fn(video, out_file=Path(f"{out_file}_preview@{i}"))
save_fn = partial(
save_output,
frame_dir=frame_dir,
output_map=output_map,
no_frames=no_frames,
save_frames=partial(save_frames, show_progress=False),
save_video=save_video
)
callback = partial(preview_callback, save_fn=save_fn, out_file=out_file)
seed_everything(seed)
logger.info(f"{len( region_condi_list )=}")
logger.info(f"{len( region_list )=}")
pipeline_output = pipeline(
negative_prompt=n_prompt,
num_inference_steps=steps,
guidance_scale=guidance_scale,
unet_batch_size=unet_batch_size,
width=width,
height=height,
video_length=duration,
return_dict=False,
context_frames=context_frames,
context_stride=context_stride + 1,
context_overlap=context_overlap,
context_schedule=context_schedule,
clip_skip=clip_skip,
controlnet_type_map=controlnet_type_map,
controlnet_image_map=controlnet_image_map,
controlnet_ref_map=controlnet_ref_map,
controlnet_no_shrink=controlnet_no_shrink,
controlnet_max_samples_on_vram=controlnet_map["max_samples_on_vram"] if "max_samples_on_vram" in controlnet_map else 999,
controlnet_max_models_on_vram=controlnet_map["max_models_on_vram"] if "max_models_on_vram" in controlnet_map else 99,
controlnet_is_loop = controlnet_map["is_loop"] if "is_loop" in controlnet_map else True,
img2img_map=img2img_map,
ip_adapter_config_map=ip_adapter_config_map,
region_list=region_list,
region_condi_list=region_condi_list,
interpolation_factor=1,
is_single_prompt_mode=is_single_prompt_mode,
apply_lcm_lora=apply_lcm_lora,
gradual_latent_map=gradual_latent_map,
callback=callback,
callback_steps=output_map.get("preview_steps"),
)
logger.info("Generation complete, saving...")
save_fn(pipeline_output, out_file=out_file)
logger.info(f"Saved sample to {out_file}")
return pipeline_output
def run_upscale(
org_imgs: List[str],
pipeline: DiffusionPipeline,
prompt_map: Dict[int, str] = None,
n_prompt: str = ...,
seed: int = -1,
steps: int = 25,
strength: float = 0.5,
guidance_scale: float = 7.5,
clip_skip: int = 1,
us_width: int = 512,
us_height: int = 512,
idx: int = 0,
out_dir: PathLike = ...,
upscale_config:Dict[str, Any]=None,
use_controlnet_ref: bool = False,
use_controlnet_tile: bool = False,
use_controlnet_line_anime: bool = False,
use_controlnet_ip2p: bool = False,
no_frames:bool = False,
output_map: Dict[str,Any] = None,
):
from animatediff.utils.lpw_stable_diffusion import lpw_encode_prompt
pipeline.set_progress_bar_config(disable=True)
images = get_resized_images(org_imgs, us_width, us_height)
steps = steps if "steps" not in upscale_config else upscale_config["steps"]
scheduler = scheduler if "scheduler" not in upscale_config else upscale_config["scheduler"]
guidance_scale = guidance_scale if "guidance_scale" not in upscale_config else upscale_config["guidance_scale"]
clip_skip = clip_skip if "clip_skip" not in upscale_config else upscale_config["clip_skip"]
strength = strength if "strength" not in upscale_config else upscale_config["strength"]
controlnet_conditioning_scale = []
guess_mode = []
control_guidance_start = []
control_guidance_end = []
# for controlnet tile
if use_controlnet_tile:
controlnet_conditioning_scale.append(upscale_config["controlnet_tile"]["controlnet_conditioning_scale"])
guess_mode.append(upscale_config["controlnet_tile"]["guess_mode"])
control_guidance_start.append(upscale_config["controlnet_tile"]["control_guidance_start"])
control_guidance_end.append(upscale_config["controlnet_tile"]["control_guidance_end"])
# for controlnet line_anime
if use_controlnet_line_anime:
controlnet_conditioning_scale.append(upscale_config["controlnet_line_anime"]["controlnet_conditioning_scale"])
guess_mode.append(upscale_config["controlnet_line_anime"]["guess_mode"])
control_guidance_start.append(upscale_config["controlnet_line_anime"]["control_guidance_start"])
control_guidance_end.append(upscale_config["controlnet_line_anime"]["control_guidance_end"])
# for controlnet ip2p
if use_controlnet_ip2p:
controlnet_conditioning_scale.append(upscale_config["controlnet_ip2p"]["controlnet_conditioning_scale"])
guess_mode.append(upscale_config["controlnet_ip2p"]["guess_mode"])
control_guidance_start.append(upscale_config["controlnet_ip2p"]["control_guidance_start"])
control_guidance_end.append(upscale_config["controlnet_ip2p"]["control_guidance_end"])
# for controlnet ref
ref_image = None
if use_controlnet_ref:
if not upscale_config["controlnet_ref"]["use_frame_as_ref_image"] and not upscale_config["controlnet_ref"]["use_1st_frame_as_ref_image"]:
ref_image = get_resized_images([ data_dir.joinpath( upscale_config["controlnet_ref"]["ref_image"] ) ], us_width, us_height)[0]
generator = torch.manual_seed(seed)
seed_everything(seed)
prompt_embeds_map = {}
prompt_map = dict(sorted(prompt_map.items()))
negative = None
do_classifier_free_guidance=guidance_scale > 1.0
prompt_list = [prompt_map[key_frame] for key_frame in prompt_map.keys()]
prompt_embeds,neg_embeds = lpw_encode_prompt(
pipe=pipeline,
prompt=prompt_list,
do_classifier_free_guidance=do_classifier_free_guidance,
negative_prompt=n_prompt,
)
if do_classifier_free_guidance:
negative = neg_embeds.chunk(neg_embeds.shape[0], 0)
positive = prompt_embeds.chunk(prompt_embeds.shape[0], 0)
else:
negative = [None]
positive = prompt_embeds.chunk(prompt_embeds.shape[0], 0)
for i, key_frame in enumerate(prompt_map):
prompt_embeds_map[key_frame] = positive[i]
key_first =list(prompt_map.keys())[0]
key_last =list(prompt_map.keys())[-1]
def get_current_prompt_embeds(
center_frame: int = 0,
video_length : int = 0
):
key_prev = key_last
key_next = key_first
for p in prompt_map.keys():
if p > center_frame:
key_next = p
break
key_prev = p
dist_prev = center_frame - key_prev
if dist_prev < 0:
dist_prev += video_length
dist_next = key_next - center_frame
if dist_next < 0:
dist_next += video_length
if key_prev == key_next or dist_prev + dist_next == 0:
return prompt_embeds_map[key_prev]
rate = dist_prev / (dist_prev + dist_next)
return get_tensor_interpolation_method()(prompt_embeds_map[key_prev],prompt_embeds_map[key_next], rate)
line_anime_processor = LineartAnimeDetector.from_pretrained("lllyasviel/Annotators")
out_images=[]
logger.info(f"{use_controlnet_tile=}")
logger.info(f"{use_controlnet_line_anime=}")
logger.info(f"{use_controlnet_ip2p=}")
logger.info(f"{controlnet_conditioning_scale=}")
logger.info(f"{guess_mode=}")
logger.info(f"{control_guidance_start=}")
logger.info(f"{control_guidance_end=}")
for i, org_image in enumerate(tqdm(images, desc=f"Upscaling...")):
cur_positive = get_current_prompt_embeds(i, len(images))
# logger.info(f"w {condition_image.size[0]}")
# logger.info(f"h {condition_image.size[1]}")
condition_image = []
if use_controlnet_tile:
condition_image.append( org_image )
if use_controlnet_line_anime:
condition_image.append( line_anime_processor(org_image) )
if use_controlnet_ip2p:
condition_image.append( org_image )
if not use_controlnet_ref:
out_image = pipeline(
prompt_embeds=cur_positive,
negative_prompt_embeds=negative[0],
image=org_image,
control_image=condition_image,
width=org_image.size[0],
height=org_image.size[1],
strength=strength,
num_inference_steps=steps,
guidance_scale=guidance_scale,
generator=generator,
controlnet_conditioning_scale= controlnet_conditioning_scale if len(controlnet_conditioning_scale) > 1 else controlnet_conditioning_scale[0],
guess_mode= guess_mode[0],
control_guidance_start= control_guidance_start if len(control_guidance_start) > 1 else control_guidance_start[0],
control_guidance_end= control_guidance_end if len(control_guidance_end) > 1 else control_guidance_end[0],
).images[0]
else:
if upscale_config["controlnet_ref"]["use_1st_frame_as_ref_image"]:
if i == 0:
ref_image = org_image
elif upscale_config["controlnet_ref"]["use_frame_as_ref_image"]:
ref_image = org_image
out_image = pipeline(
prompt_embeds=cur_positive,
negative_prompt_embeds=negative[0],
image=org_image,
control_image=condition_image,
width=org_image.size[0],
height=org_image.size[1],
strength=strength,
num_inference_steps=steps,
guidance_scale=guidance_scale,
generator=generator,
controlnet_conditioning_scale= controlnet_conditioning_scale if len(controlnet_conditioning_scale) > 1 else controlnet_conditioning_scale[0],
guess_mode= guess_mode[0],
# control_guidance_start= control_guidance_start,
# control_guidance_end= control_guidance_end,
### for controlnet ref
ref_image=ref_image,
attention_auto_machine_weight = upscale_config["controlnet_ref"]["attention_auto_machine_weight"],
gn_auto_machine_weight = upscale_config["controlnet_ref"]["gn_auto_machine_weight"],
style_fidelity = upscale_config["controlnet_ref"]["style_fidelity"],
reference_attn= upscale_config["controlnet_ref"]["reference_attn"],
reference_adain= upscale_config["controlnet_ref"]["reference_adain"],
).images[0]
out_images.append(out_image)
# Trim and clean up the prompt for filename use
prompt_tags = [re_clean_prompt.sub("", tag).strip().replace(" ", "-") for tag in prompt_map[list(prompt_map.keys())[0]].split(",")]
prompt_str = "_".join((prompt_tags[:6]))[:50]
# generate the output filename and save the video
out_file = out_dir.joinpath(f"{idx:02d}_{seed}_{prompt_str}")
frame_dir = out_dir.joinpath(f"{idx:02d}-{seed}-upscaled")
save_output( out_images, frame_dir, out_file, output_map, no_frames, save_imgs, None )
logger.info(f"Saved sample to {out_file}")
return out_images
|