-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathmodel_loader_utils.py
More file actions
3064 lines (2627 loc) · 142 KB
/
model_loader_utils.py
File metadata and controls
3064 lines (2627 loc) · 142 KB
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
# !/usr/bin/env python
# -*- coding: UTF-8 -*-
import logging
import os
import re
import random
import torch
import gc
from omegaconf import OmegaConf
from PIL import Image
import numpy as np
import cv2
from diffusers import ( DDIMScheduler,
KDPM2AncestralDiscreteScheduler, LMSDiscreteScheduler,
DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler,
EulerDiscreteScheduler, HeunDiscreteScheduler,
KDPM2DiscreteScheduler,
EulerAncestralDiscreteScheduler, UniPCMultistepScheduler,
DDPMScheduler, LCMScheduler)
from .msdiffusion.models.projection import Resampler
from .msdiffusion.models.modelWrapper import MSAdapter as MSAdapterWarpper
from .utils.style_template import styles
from .utils.load_models_utils import get_lora_dict
from .PuLID.pulid.utils import resize_numpy_image_long
from transformers import AutoModel, AutoTokenizer
from comfy.utils import common_upscale,ProgressBar
import folder_paths
from comfy.clip_vision import load as clip_load
from .utils.gradio_utils import process_original_text,character_to_dict
import json
cur_path = os.path.dirname(os.path.abspath(__file__))
photomaker_dir=os.path.join(folder_paths.models_dir, "photomaker")
base_pt = os.path.join(photomaker_dir,"pt")
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
lora_get = get_lora_dict()
lora_lightning_list = lora_get["lightning_xl_lora"]
SAMPLER_NAMES = ["euler", "euler_cfg_pp", "euler_ancestral", "euler_ancestral_cfg_pp", "heun", "heunpp2","dpm_2", "dpm_2_ancestral",
"lms", "dpm_fast", "dpm_adaptive", "dpmpp_2s_ancestral", "dpmpp_2s_ancestral_cfg_pp", "dpmpp_sde", "dpmpp_sde_gpu",
"dpmpp_2m", "dpmpp_2m_sde", "dpmpp_2m_sde_gpu", "dpmpp_3m_sde", "dpmpp_3m_sde_gpu", "ddpm", "lcm",
"ipndm", "ipndm_v", "deis","ddim", "uni_pc", "uni_pc_bh2"]
SCHEDULER_NAMES = ["normal", "karras", "exponential", "sgm_uniform", "simple", "ddim_uniform", "beta"]
def gc_cleanup():
gc.collect()
torch.cuda.empty_cache()
def get_scheduler(name,scheduler_):
scheduler = False
if name == "euler" or name =="euler_cfg_pp":
scheduler = EulerDiscreteScheduler()
elif name == "euler_ancestral" or name =="euler_ancestral_cfg_pp":
scheduler = EulerAncestralDiscreteScheduler()
elif name == "ddim":
scheduler = DDIMScheduler()
elif name == "ddpm":
scheduler = DDPMScheduler()
elif name == "dpmpp_2m":
scheduler = DPMSolverMultistepScheduler()
elif name == "dpmpp_2m" and scheduler_=="karras":
scheduler = DPMSolverMultistepScheduler(use_karras_sigmas=True)
elif name == "dpmpp_2m_sde":
scheduler = DPMSolverMultistepScheduler(algorithm_type="sde-dpmsolver++")
elif name == "dpmpp_2m" and scheduler_=="karras":
scheduler = DPMSolverMultistepScheduler(use_karras_sigmas=True, algorithm_type="sde-dpmsolver++")
elif name == "dpmpp_sde" or name == "dpmpp_sde_gpu":
scheduler = DPMSolverSinglestepScheduler()
elif (name == "dpmpp_sde" or name == "dpmpp_sde_gpu") and scheduler_=="karras":
scheduler = DPMSolverSinglestepScheduler(use_karras_sigmas=True)
elif name == "dpm_2":
scheduler = KDPM2DiscreteScheduler()
elif name == "dpm_2" and scheduler_=="karras":
scheduler = KDPM2DiscreteScheduler(use_karras_sigmas=True)
elif name == "dpm_2_ancestral":
scheduler = KDPM2AncestralDiscreteScheduler()
elif name == "dpm_2_ancestral" and scheduler_=="karras":
scheduler = KDPM2AncestralDiscreteScheduler(use_karras_sigmas=True)
elif name == "heun":
scheduler = HeunDiscreteScheduler()
elif name == "lcm":
scheduler = LCMScheduler()
elif name == "lms":
scheduler = LMSDiscreteScheduler()
elif name == "lms" and scheduler_=="karras":
scheduler = LMSDiscreteScheduler(use_karras_sigmas=True)
elif name == "uni_pc":
scheduler = UniPCMultistepScheduler()
else:
scheduler = EulerDiscreteScheduler()
return scheduler
def get_extra_function(extra_function,extra_param,photomake_ckpt_path,image,infer_mode):
auraface=False
use_photov2=False
cached=False
inject=False
onnx_provider="gpu"
img2img_mode = True if isinstance(image, torch.Tensor) else False
trigger_words_dual="best"
dual_lora_scale=1.0
dreamo_mode="ip"
if extra_function:
extra_function = extra_function.strip().lower()
if "auraface" in extra_function:
auraface=True
if extra_param:
extra_param = extra_param.strip().lower()
if "cache" in extra_param:
cached=True
if "inject" in extra_param:
inject=True
if "cpu" in extra_param:
onnx_provider="cpu"
if "id" in extra_param:
dreamo_mode="id"
elif "style" in extra_param:
dreamo_mode="style"
if "[" in extra_param:
trigger_words_param=extra_param.split("[")[1].split("]")[0]
trigger_words_dual=trigger_words_param.split(",")[0]
dual_lora_scale=float(trigger_words_param.split(",")[1])
if isinstance(photomake_ckpt_path, str) and img2img_mode:
use_photov2 = True if "v2" in photomake_ckpt_path else False
return auraface,use_photov2,img2img_mode,cached,inject,onnx_provider,dreamo_mode,trigger_words_dual,dual_lora_scale
def extract_content_from_brackets(text):
# 正则表达式匹配多对方括号内的内容
return re.findall(r'\[(.*?)\]', text)
def phi2narry(img):
img = torch.from_numpy(np.array(img).astype(np.float32) / 255.0).unsqueeze(0)
return img
def tensor_to_image(tensor):
image_np = tensor.squeeze().mul(255).clamp(0, 255).byte().numpy()
image = Image.fromarray(image_np, mode='RGB')
return image
def tensortopil_list(tensor_in):
d1, _, _, _ = tensor_in.size()
if d1 == 1:
img_list = [tensor_to_image(tensor_in)]
else:
tensor_list = torch.chunk(tensor_in, chunks=d1)
img_list=[tensor_to_image(i) for i in tensor_list]
return img_list
def tensortopil_list_upscale(tensor_in,width,height):
d1, _, _, _ = tensor_in.size()
if d1 == 1:
img_list = [nomarl_upscale(tensor_in,width,height)]
else:
tensor_list = torch.chunk(tensor_in, chunks=d1)
img_list=[nomarl_upscale(i,width,height) for i in tensor_list]
return img_list
def tensortolist(tensor_in,width,height):
if tensor_in is None:
return None
d1, _, _, _ = tensor_in.size()
if d1 == 1:
tensor_list = [nomarl_tensor_upscale(tensor_in,width,height)]
else:
tensor_list_ = torch.chunk(tensor_in, chunks=d1)
tensor_list=[nomarl_tensor_upscale(i,width,height) for i in tensor_list_]
return tensor_list
def nomarl_tensor_upscale(tensor, width, height):
samples = tensor.movedim(-1, 1)
samples = common_upscale(samples, width, height, "nearest-exact", "center")
samples = samples.movedim(1, -1)
return samples
def nomarl_upscale(img, width, height):
samples = img.movedim(-1, 1)
img = common_upscale(samples, width, height, "nearest-exact", "center")
samples = img.movedim(1, -1)
img = tensor_to_image(samples)
return img
def nomarl_upscale_tensor(img, width, height):
samples = img.movedim(-1, 1)
img = common_upscale(samples, width, height, "nearest-exact", "center")
samples = img.movedim(1, -1)
return samples
def center_crop(img):
width, height = img.size
square = min(width, height)
left = (width - square) / 2
top = (height - square) / 2
right = (width + square) / 2
bottom = (height + square) / 2
return img.crop((left, top, right, bottom))
def center_crop_s(img, new_width, new_height):
width, height = img.size
left = (width - new_width) / 2
top = (height - new_height) / 2
right = (width + new_width) / 2
bottom = (height + new_height) / 2
return img.crop((left, top, right, bottom))
def contains_brackets(s):
return '[' in s or ']' in s
def has_parentheses(s):
return bool(re.search(r'\(.*?\)', s))
def extract_content_from_brackets_(text):
# 正则表达式匹配多对圆括号内的内容
return re.findall(r'\((.*?)\)', text)
def narry_list(list_in):
for i in range(len(list_in)):
value = list_in[i]
modified_value = phi2narry(value)
list_in[i] = modified_value
return list_in
def remove_punctuation_from_strings(lst):
pattern = r"[\W]+$" # 匹配字符串末尾的所有非单词字符
return [re.sub(pattern, '', s) for s in lst]
def phi_list(list_in):
for i in range(len(list_in)):
value = list_in[i]
list_in[i] = value
return list_in
def narry_list_pil(list_in):
for i in range(len(list_in)):
value = list_in[i]
modified_value = tensor_to_image(value)
list_in[i] = modified_value
return list_in
def setup_seed(seed):
torch.manual_seed(seed)
if device == "cuda":
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
def apply_style_positive(style_name: str, positive: str):
p, n = styles.get(style_name, styles[style_name])
#print(p, "test0", n)
return p.replace("{prompt}", positive),n
def apply_style(style_name: str, positives: list, negative: str = ""):
p, n = styles.get(style_name, styles[style_name])
#print(p,"test1",n)
return [
p.replace("{prompt}", positive) for positive in positives
], n + " " + negative
def face_bbox_to_square(bbox):
## l, t, r, b to square l, t, r, b
l,t,r,b = bbox
cent_x = (l + r) / 2
cent_y = (t + b) / 2
w, h = r - l, b - t
r = max(w, h) / 2
l0 = cent_x - r
r0 = cent_x + r
t0 = cent_y - r
b0 = cent_y + r
return [l0, t0, r0, b0]
def insight_face_loader(infer_mode,use_photov2,auraface,onnx_provider="cpu",mask_repo="briaai/RMBG-1.4"):
insightface_root_path= folder_paths.base_path
if infer_mode=="story" and use_photov2:
from .utils.insightface_package import FaceAnalysis2
if auraface:
from huggingface_hub import snapshot_download
snapshot_download(
"fal/AuraFace-v1",
local_dir="models/auraface",
)
app_face = FaceAnalysis2(name="auraface",
providers=["CUDAExecutionProvider", "CPUExecutionProvider"], root=insightface_root_path,
allowed_modules=['detection', 'recognition'])
else:
app_face = FaceAnalysis2(providers=['CUDAExecutionProvider'],
allowed_modules=['detection', 'recognition'])
app_face.prepare(ctx_id=0, det_size=(640, 640))
pipeline_mask = None
app_face_ = None
elif infer_mode=="kolor_face" :
from .kolors.models.sample_ipadapter_faceid_plus import FaceInfoGenerator
from huggingface_hub import snapshot_download
snapshot_download(
'DIAMONIK7777/antelopev2',
local_dir='models/antelopev2',
)
app_face = FaceInfoGenerator(root_dir=insightface_root_path)
pipeline_mask = None
app_face_ = None
elif infer_mode=="story_maker":
from insightface.app import FaceAnalysis
from transformers import pipeline
pipeline_mask = pipeline("image-segmentation", model=mask_repo,
trust_remote_code=True)
app_face = FaceAnalysis(name='buffalo_l', root=insightface_root_path,
providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
app_face.prepare(ctx_id=0, det_size=(640, 640))
app_face_ = None
elif infer_mode=="story_and_maker":
from insightface.app import FaceAnalysis
from transformers import pipeline
pipeline_mask = pipeline("image-segmentation", model=mask_repo,
trust_remote_code=True)
if use_photov2:
from .utils.insightface_package import FaceAnalysis2
if auraface:
from huggingface_hub import snapshot_download
snapshot_download(
"fal/AuraFace-v1",
local_dir="models/auraface",
)
app_face = FaceAnalysis2(name="auraface",
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
root=insightface_root_path,
allowed_modules=['detection', 'recognition'])
else:
app_face = FaceAnalysis2(providers=['CUDAExecutionProvider'],
allowed_modules=['detection', 'recognition'])
app_face.prepare(ctx_id=0, det_size=(640, 640))
app_face_ = FaceAnalysis(name='buffalo_l', root=insightface_root_path,
providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
app_face_.prepare(ctx_id=0, det_size=(640, 640))
else:
app_face = FaceAnalysis(name='buffalo_l', root=insightface_root_path,
providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
app_face.prepare(ctx_id=0, det_size=(640, 640))
app_face_ = None
elif infer_mode=="flux_pulid":
import insightface
from facexlib.parsing import init_parsing_model
from facexlib.utils.face_restoration_helper import FaceRestoreHelper
from insightface.app import FaceAnalysis
from huggingface_hub import snapshot_download
# antelopev2
snapshot_download('DIAMONIK7777/antelopev2', local_dir='models/antelopev2')
providers = ['CPUExecutionProvider'] if onnx_provider == 'cpu' else ['CUDAExecutionProvider', 'CPUExecutionProvider']
app_face = FaceAnalysis(name='antelopev2', root=insightface_root_path, providers=providers)
app_face.prepare(ctx_id=0, det_size=(640, 640))
# face_helper
face_helper = FaceRestoreHelper(
upscale_factor=1,
face_size=512,
crop_ratio=(1, 1),
det_model='retinaface_resnet50',
save_ext='png',
device=device,)
face_helper.face_parse = None
face_helper.face_parse = init_parsing_model(model_name='bisenet', device=device)
app_face_ = face_helper
handler_ante = insightface.model_zoo.get_model('models/antelopev2/glintr100.onnx',providers=providers)
handler_ante.prepare(ctx_id=0)
pipeline_mask = handler_ante
elif infer_mode=="infiniteyou":
from facexlib.recognition import init_recognition_model
from insightface.app import FaceAnalysis
# Load face encoder
app_face = FaceAnalysis(name='antelopev2',
root=insightface_root_path, providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
app_face.prepare(ctx_id=0, det_size=(640, 640))
app_face_ = init_recognition_model('arcface', device='cuda')
pipeline_mask = None
else:
app_face = None
pipeline_mask = None
app_face_ = None
return app_face,pipeline_mask,app_face_
def get_float(str_in):
list_str=str_in.split(",")
float_box=[float(x) for x in list_str]
return float_box
def adjust_indices(original_indices, deleted_indices):
"""根据删除的索引列表调整原索引"""
# 处理删除列表为空的特殊情况
if not deleted_indices:
return original_indices.copy() # 直接返回原索引,无需调整
deleted_sorted = sorted(deleted_indices)
adjusted = []
for idx in original_indices:
# 计算偏移量:有多少个删除索引 < 当前索引
offset = sum(1 for d in deleted_sorted if d < idx)
new_idx = idx - offset
# 如果原索引未被删除,则保留
if idx not in deleted_sorted:
adjusted.append(new_idx)
else:
adjusted.append(-1) # 标记为无效
return adjusted
def get_insight_dict(app_face,app_face_,pipeline_mask,infer_mode,use_photov2,image_list,
character_list_,condition_image,width, height,model=None,image_proj_model=None):
input_id_emb_s_dict = {}
input_id_img_s_dict = {}
input_id_emb_un_dict = {}
for ind, img in enumerate(image_list): # 最大只有2个ID
if infer_mode == "story" and use_photov2:
from .utils.insightface_package import analyze_faces
img_ = np.array(img)
img_ = cv2.cvtColor(img_, cv2.COLOR_RGB2BGR)
faces = analyze_faces(app_face, img_, )
id_embed_list = torch.from_numpy((faces[0]['embedding']))
crop_image = img_
uncond_id_embeddings = None
elif infer_mode == "kolor_face":
device = (
"cuda"
if torch.cuda.is_available()
else "mps" if torch.backends.mps.is_available() else "cpu"
)
face_info = app_face.get_faceinfo_one_img(img)
face_bbox_square = face_bbox_to_square(face_info["bbox"])
crop_image = img.crop(face_bbox_square)
crop_image = crop_image.resize((336, 336))
face_embeds = torch.from_numpy(np.array([face_info["embedding"]]))
id_embed_list = face_embeds.to(device, dtype=torch.float16)
uncond_id_embeddings = None
elif infer_mode=="story_maker":
crop_image = pipeline_mask(img, return_mask=True).convert('RGB') # outputs a pillow mask
# timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
# crop_image.copy().save(os.path.join(folder_paths.get_output_directory(),f"{timestamp}_mask.png"))
face_info = app_face.get(cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR))
id_embed_list = sorted(face_info,key=lambda x: (x['bbox'][2] - x['bbox'][0]) * (x['bbox'][3] - x['bbox'][1]))[-1] # only use the maximum face
uncond_id_embeddings = img
elif infer_mode=="story_and_maker":
if use_photov2:
from .utils.insightface_package import analyze_faces
img = np.array(img)
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
faces = analyze_faces(app_face, img, )
id_embed_list = torch.from_numpy((faces[0]['embedding']))
crop_image = pipeline_mask(img, return_mask=True).convert(
'RGB') # outputs a pillow mask
face_info = app_face_.get(cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR))
uncond_id_embeddings = sorted(face_info,key=lambda x: (x['bbox'][2] - x['bbox'][0]) * (x['bbox'][3] - x['bbox'][1]))[-1] # only use the maximum face
#photomake_mode = "v2"
# make+v2模式下,emb存v2的向量,corp 和 unemb 存make的向量
else: # V1不需要调用emb
crop_image = pipeline_mask(img, return_mask=True).convert(
'RGB') # outputs a pillow mask
face_info = app_face.get(cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR))
id_embed_list = sorted(face_info,key=lambda x: (x['bbox'][2] - x['bbox'][0]) * (x['bbox'][3] - x['bbox'][1]))[-1] # only use the maximum face
uncond_id_embeddings = img
elif infer_mode=="flux_pulid":
id_image = resize_numpy_image_long(img, 1024)
use_true_cfg = abs(1.0 - 1.0) > 1e-2
id_embed_list, uncond_id_embeddings=model.pulid_model.get_id_embedding_( id_image,app_face_,app_face,pipeline_mask,cal_uncond=use_true_cfg)
#id_embed_list, uncond_id_embeddings = pipe.pulid_model.get_id_embedding(id_image,cal_uncond=use_true_cfg)
crop_image = img
elif infer_mode=="infiniteyou":
def _detect_face(app_face, id_image_cv2):
face_info = app_face.get(id_image_cv2)
if face_info:
return face_info
else:
print("No face detected in the input ID image")
return []
from .pipelines.pipeline_infu_flux import extract_arcface_bgr_embedding,resize_and_pad_image,draw_kps
# Extract ID embeddings
print('Preparing ID embeddings')
id_image_cv2 = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
face_info = _detect_face(app_face,id_image_cv2)
if len(face_info) == 0:
raise ValueError('No face detected in the input ID image')
face_info = sorted(face_info, key=lambda x:(x['bbox'][2]-x['bbox'][0])*(x['bbox'][3]-x['bbox'][1]))[-1] # only use the maximum face
landmark = face_info['kps']
id_embed = extract_arcface_bgr_embedding(id_image_cv2, landmark, app_face_)
id_embed = id_embed.clone().unsqueeze(0).float().cuda()
id_embed = id_embed.reshape([1, -1, 512])
id_embed = id_embed.to(device='cuda', dtype=torch.bfloat16)
with torch.no_grad():
id_embed = image_proj_model(id_embed)
bs_embed, seq_len, _ = id_embed.shape
id_embed = id_embed.repeat(1, 1, 1)
id_embed = id_embed.view(bs_embed * 1, seq_len, -1)
id_embed = id_embed.to(device='cuda', dtype=torch.bfloat16)
# Load control image
print('Preparing the control image')
if isinstance(condition_image, torch.Tensor):
e1, _, _, _ = condition_image.size()
if e1 == 1:
cn_image_load = [nomarl_upscale(condition_image, width, height)]
else:
img_list = list(torch.chunk(condition_image, chunks=e1))
cn_image_load = [nomarl_upscale(img, width, height) for img in img_list]
# control_image = control_image.convert("RGB")
# control_image = resize_and_pad_image(control_image, (width, height))
control_image=[] #如果是单人多张控制图,可能导致失序,所以统一改成列表,并在采样的时候依次调用
for img in cn_image_load:
face_info = _detect_face(app_face,cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR))
if len(face_info) == 0:
print('No face detected in the control image,use empty image,无法识别到面部,加载全黑图片替代.') #卡通人物很难识别,所以避免反复加载, 直接用黑图
face_cn=Image.fromarray(np.zeros([height, width, 3]).astype(np.uint8))
else:
face_info = sorted(face_info, key=lambda x:(x['bbox'][2]-x['bbox'][0])*(x['bbox'][3]-x['bbox'][1]))[-1] # only use the maximum face
face_cn = draw_kps(img, face_info['kps'])
control_image.append(face_cn)
else:
out_img = np.zeros([height, width, 3])
control_image = Image.fromarray(out_img.astype(np.uint8))
id_embed_list=id_embed
crop_image = control_image # inf use crop to control img
uncond_id_embeddings = None
else:
id_embed_list = None
uncond_id_embeddings = None
crop_image = None
input_id_img_s_dict[character_list_[ind]] = [crop_image]
input_id_emb_s_dict[character_list_[ind]] = [id_embed_list]
input_id_emb_un_dict[character_list_[ind]] = [uncond_id_embeddings]
app_face = None
app_face_= None
pipeline_mask =None
gc_cleanup()
if isinstance(condition_image, torch.Tensor) and infer_mode=="story_maker":
e1, _, _, _ = condition_image.size()
if e1 == 1:
cn_image_load = [nomarl_upscale(condition_image, width, height)]
else:
img_list = list(torch.chunk(condition_image, chunks=e1))
cn_image_load = [nomarl_upscale(img, width, height) for img in img_list]
input_id_cloth_dict = {}
if len(cn_image_load)>2:
cn_image_load_role=cn_image_load[0:2]
else:
cn_image_load_role=cn_image_load
for ind, img in enumerate(cn_image_load_role):
input_id_cloth_dict[character_list_[ind]] = [img]
if len(cn_image_load)>2: #处理多张control img
my_list=cn_image_load[2:]
for ind,img in enumerate(my_list):
input_id_cloth_dict[f"dual{ind}"] = [img]
else:
input_id_cloth_dict = {}
return input_id_emb_s_dict,input_id_img_s_dict,input_id_emb_un_dict,input_id_cloth_dict
def load_model_tag(repo,device,select_method):
if "flor" in select_method.lower():#"thwri/CogFlorence-2-Large-Freeze"
#pip install flash_attn
from transformers import AutoModelForCausalLM, AutoProcessor, AutoConfig
model = AutoModelForCausalLM.from_pretrained(repo, trust_remote_code=True).to(
device)
processor = AutoProcessor.from_pretrained(repo, trust_remote_code=True)
else:
model = AutoModel.from_pretrained(repo, trust_remote_code=True)
processor = AutoTokenizer.from_pretrained(repo, trust_remote_code=True)#tokenizer
model.eval()
return model,processor
class StoryLiteTag:
def __init__(self, device,temperature,select_method,repo="pzc163/MiniCPMv2_6-prompt-generator",):
self.device = device
self.repo = repo
self.select_method=select_method
self.model, self.processor=load_model_tag(self.repo, self.device,self.select_method)
self.temperature=temperature
def run_tag(self,image):
if "flor" in self.select_method.lower():
inputs = self.processor(text="<MORE_DETAILED_CAPTION>" , images=image, return_tensors="pt").to(device)
generated_ids = self.model.generate(
input_ids=inputs["input_ids"],
pixel_values=inputs["pixel_values"],
max_new_tokens=1024,
num_beams=3,
do_sample=True
)
generated_text = self.processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
parsed_answer = self.processor.post_process_generation(generated_text, task="<MORE_DETAILED_CAPTION>" ,
image_size=(image.width, image.height))
res=parsed_answer["<MORE_DETAILED_CAPTION>"]
else:
question = 'Provide a detailed description of the details and content contained in the image, and generate a short prompt that can be used for image generation tasks in Stable Diffusion,remind you only need respons prompt itself and no other information.'
msgs = [{'role': 'user', 'content': [image, question]}]
res = self.model.chat(
image=None,
msgs=msgs,
tokenizer=self.processor,# tokenizer
temperature=self.temperature
)
res=res.split(":",1)[1].strip('"')
s=res.strip()
res=re.sub(r'^\n+|\n+$', '', s)
res.strip("'")
logging.info(f"{res}")
return res
def images_generator(img_list: list, ):
# get img size
sizes = {}
for image_ in img_list:
if isinstance(image_, Image.Image):
count = sizes.get(image_.size, 0)
sizes[image_.size] = count + 1
elif isinstance(image_, np.ndarray):
count = sizes.get(image_.shape[:2][::-1], 0)
sizes[image_.shape[:2][::-1]] = count + 1
else:
raise "unsupport image list,must be pil or cv2!!!"
size = max(sizes.items(), key=lambda x: x[1])[0]
yield size[0], size[1]
# any to tensor
def load_image(img_in):
if isinstance(img_in, Image.Image):
img_in = img_in.convert("RGB")
i = np.array(img_in, dtype=np.float32)
i = torch.from_numpy(i).div_(255)
if i.shape[0] != size[1] or i.shape[1] != size[0]:
i = torch.from_numpy(i).movedim(-1, 0).unsqueeze(0)
i = common_upscale(i, size[0], size[1], "lanczos", "center")
i = i.squeeze(0).movedim(0, -1).numpy()
return i
elif isinstance(img_in, np.ndarray):
i = cv2.cvtColor(img_in, cv2.COLOR_BGR2RGB).astype(np.float32)
i = torch.from_numpy(i).div_(255)
print(i.shape)
return i
else:
raise "unsupport image list,must be pil,cv2 or tensor!!!"
total_images = len(img_list)
processed_images = 0
pbar = ProgressBar(total_images)
images = map(load_image, img_list)
try:
prev_image = next(images)
while True:
next_image = next(images)
yield prev_image
processed_images += 1
pbar.update_absolute(processed_images, total_images)
prev_image = next_image
except StopIteration:
pass
if prev_image is not None:
yield prev_image
def load_images_list(img_list: list, ):
gen = images_generator(img_list)
(width, height) = next(gen)
images = torch.from_numpy(np.fromiter(gen, np.dtype((np.float32, (height, width, 3)))))
if len(images) == 0:
raise FileNotFoundError(f"No images could be loaded .")
return images
def fitter_cf_model_type(model):
VALUE_=model.model.model_type.value
if VALUE_ == 8:
cf_model_type = "FLUX"
elif VALUE_ == 4:
cf_model_type = "CASCADE"
elif VALUE_ == 6:
cf_model_type = "FLOW"
elif VALUE_ == 5:
cf_model_type = "EDM"
elif VALUE_ == 1:
cf_model_type = "EPS"
elif VALUE_ == 2:
cf_model_type = "V_PREDICTION"
elif VALUE_ == 3:
cf_model_type = "V_PREDICTION_EDM"
elif VALUE_ == 7:
cf_model_type = "PREDICTION_CONTINUOUS"
else:
raise "unsupport checkpoints"
return cf_model_type
def pre_text2infer(role_text,scene_text,lora_trigger_words,use_lora,tag_list):
'''
Args:
role_index_dict: {'[Taylor]': [0, 1], '[Lecun]': [2, 3]}
invert_role_index_dict{0: ['[Taylor]'], 1: ['[Taylor]'], 2: ['[Lecun]'], 3: ['[Lecun]']}
ref_role_index_dict {'[Taylor]': [0, 1], '[Lecun]': [2, 3]}
ref_role_totals[0, 1, 2, 3]
role_list ['[Taylor]', '[Lecun]']
role_dict {'[Taylor]': ' a woman img, wearing a white T-shirt, blue loose hair.', '[Lecun]': ' a man img,wearing a suit,black hair.'}
nc_txt_list [' a panda']
nc_indexs[4]
positions_index_dual[]
positions_index_char_1 0 2
positions_index_char_2 []
prompts_dual[] #['[A] play whith [B] in the garden']
index_char_1_list [0, 1]
index_char_2_list[2, 3]
Returns:
character_index_dict:{'[Taylor]': [0, 3], '[sam]': [1, 2]},if 1 role {'[Taylor]': [0, 1, 2]}
'''
add_trigger_words = " " + lora_trigger_words + " style "
# pre role_text
role_dict, role_list = character_to_dict(role_text, use_lora, add_trigger_words)
id_len=len(role_dict)
#pre scene_text
scene_text_origin = [i.strip() for i in scene_text.splitlines()]
scene_text_origin = [i for i in scene_text_origin if '[' in i] # 删除空行
prompt_sence = [i for i in scene_text_origin if not len(extract_content_from_brackets(i)) >= 2] # 剔除双角色的场景词
positions_index_dual = [index for index, prompt in enumerate(scene_text_origin) if
len(extract_content_from_brackets(prompt)) >= 2] #获取双角色出现的位置
prompts_dual = [prompt for prompt in scene_text_origin if len(extract_content_from_brackets(prompt)) >= 2] # 改成单句中双方括号方法,利于MS组句,[A]... [B]...[C]
#print(id_len,role_list)
if id_len == 2:
index_char_1_list=[index for index, prompt in enumerate(scene_text_origin) if role_list[0] in prompt]
positions_index_char_1 = index_char_1_list[0] # 获取角色出现的索引列表,并获取首次出现的位置
index_char_2_list=[index for index, prompt in enumerate(scene_text_origin) if role_list[1] in prompt]
positions_index_char_2 = index_char_2_list[0] # 获取角色出现的索引列表,并获取首次出现的位置
# print(positions_index_char_1, positions_index_char_2) #0,2
else:
index_char_1_list=[index for index, prompt in enumerate(scene_text_origin) if role_list[0] in prompt]
index_char_2_list=[]
positions_index_char_1=[]
positions_index_char_2=[]
if index_char_1_list and index_char_2_list: #dual 情况下,该列表有误,须排除重复元素
common_ = set(index_char_1_list) & set(index_char_2_list)
if common_:
index_char_1_list=[x for x in index_char_1_list if x not in common_]
index_char_2_list = [x for x in index_char_2_list if x not in common_]
clipped_prompts = prompt_sence[:] # copy
nc_indexs = []
for ind, prompt in enumerate(clipped_prompts): #获取NC的index
if "[NC]" in prompt:
nc_indexs.append(ind)
if ind < id_len:
raise f"The first [role] row need be a id prompts, cannot use [NC]!"
prompts = [
i if "[NC]" not in i else i.replace("[NC]", "") for i in clipped_prompts]
#去除#
prompts = [prompt.rpartition("#")[0] if "#" in prompt else prompt for prompt in prompts]
# character_dict:{'[Taylor]': ' a woman img, wearing a white T-shirt, blue loose hair.'},character_list:['[Taylor]'] 1role
#character_dict:{'[Taylor]': ' a woman img, wearing a white T-shirt, blue loose hair.', '[Lecun]': ' a man img,wearing a suit,black hair.'},character_list:['[Taylor]', '[Lecun]'] 2 role
#获取字典,实际用词等
role_index_dict, invert_role_index_dict, replace_prompts, ref_role_index_dict, ref_role_totals= process_original_text(role_dict, prompts)
if tag_list: #tag方法
if len(tag_list) < len(replace_prompts):
raise "The number of input condition images is less than the number of scene prompts!"
replace_prompts = [prompt + " " + tag_list[i] for i, prompt in enumerate(replace_prompts)]
if nc_indexs:
for x in nc_indexs: # 获取NC列表
nc_txt_list = [item for i, item in enumerate(replace_prompts) if i == x]
for x in nc_indexs: # 去除NC列表
replace_prompts = [item for i, item in enumerate(replace_prompts) if i != x]
else:
nc_txt_list = []
replace_prompts=[i for i in replace_prompts]
return replace_prompts,role_index_dict,invert_role_index_dict,ref_role_index_dict,ref_role_totals,role_list,role_dict,nc_txt_list,nc_indexs,positions_index_char_1,positions_index_char_2,positions_index_dual,prompts_dual,index_char_1_list,index_char_2_list
def convert_cf2diffuser(model):
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import convert_ldm_unet_checkpoint
from diffusers import UNet2DConditionModel
config_file = os.path.join(cur_path,"local_repo/unet/config.json")
cf_state_dict = model.diffusion_model.state_dict()
unet_state_dict = model.model_config.process_unet_state_dict_for_saving(cf_state_dict)
unet_config = UNet2DConditionModel.load_config(config_file)
Unet = UNet2DConditionModel.from_config(unet_config).to(device, torch.float16)
cf_state_dict = convert_ldm_unet_checkpoint(unet_state_dict, Unet.config)
Unet.load_state_dict(cf_state_dict, strict=False)
del cf_state_dict,unet_state_dict
gc.collect()
torch.cuda.empty_cache()
return Unet
def cf_clip(txt_list, clip, infer_mode,role_list,input_split=True):
if infer_mode == "classic":
input_split= False
if len(role_list)==1:
input_split= False
if input_split:
role_emb_dict={}
for role,role_text_list in zip(role_list,txt_list):
pos_cond_list=[]
for j in role_text_list:
tokens_p = clip.tokenize(j)
output_p = clip.encode_from_tokens(tokens_p, return_dict=True) # {"pooled_output":tensor}
cond_p = output_p.pop("cond")
if cond_p.shape[1] / 77 > 1 and infer_mode != "classic":
# logging.warning("prompt'tokens length is abvoe 77,split it")
cond_p = torch.chunk(cond_p, cond_p.shape[1] // 77, dim=1)[0]
positive = [cond_p, output_p]
pos_cond_list.append(positive)
role_emb_dict[role]=pos_cond_list
return role_emb_dict
pos_cond_list = []
for i in txt_list[0]:
tokens_p = clip.tokenize(i)
output_p = clip.encode_from_tokens(tokens_p, return_dict=True) # {"pooled_output":tensor}
cond_p = output_p.pop("cond")
if cond_p.shape[1] / 77 > 1 and infer_mode != "classic":
# logging.warning("prompt'tokens length is abvoe 77,split it")
cond_p = torch.chunk(cond_p, cond_p.shape[1] // 77, dim=1)[0]
if infer_mode == "classic":
positive = [[cond_p, output_p]]
else:
positive = [cond_p, output_p]
# logging.info(f"sampler text is {i}")
pos_cond_list.append(positive)
return pos_cond_list
def get_eot_idx_cf(tokenizer, prompt):
words = prompt.split()
start = 1
for w in words:
start += len(tokenizer.encode(w)) - 2
return start
def get_phrase_idx_cf(tokenizer, phrase, prompt, get_last_word=False, num=0):
def is_equal_words(pr_words, ph_words):
if len(pr_words) != len(ph_words):
return False
for pr_word, ph_word in zip(pr_words, ph_words):
if "-"+ph_word not in pr_word and ph_word != re.sub(r'[.!?,:]$', '', pr_word):
return False
return True
phrase_words = phrase.split()
if len(phrase_words) == 0:
return [0, 0], None
if get_last_word:
phrase_words = phrase_words[-1:]
# prompt_words = re.findall(r'\b[\w\'-]+\b', prompt)
prompt_words = prompt.split()
start = 1
end = 0
res_words = phrase_words
for i in range(len(prompt_words)):
if is_equal_words(prompt_words[i:i+len(phrase_words)], phrase_words):
if num != 0:
# skip this one
num -= 1
continue
end = start
res_words = prompt_words[i:i+len(phrase_words)]
res_words = [re.sub(r'[.!?,:]$', '', w) for w in res_words]
prompt_words[i+len(phrase_words)-1] = res_words[-1] # remove the last punctuation
for j in range(i, i+len(phrase_words)):
end += len(tokenizer.encode(prompt_words[j])) - 2
break
else:
start += len(tokenizer.encode(prompt_words[i])) - 2
if end == 0:
return [0, 0], None
return [start, end], res_words
def get_phrases_idx_cf(tokenizer, phrases, prompt):
res = []
phrase_cnt = {}
for phrase in phrases:
if phrase in phrase_cnt:
cur_cnt = phrase_cnt[phrase]
phrase_cnt[phrase] += 1
else:
cur_cnt = 0
phrase_cnt[phrase] = 1
res.append(get_phrase_idx_cf(tokenizer, phrase, prompt, num=cur_cnt)[0])
return res
def replicate_data_by_indices(data_list, index_list1, index_list2):
# 确定新列表的长度
max_index = max(max(index_list1), max(index_list2)) if (index_list1 and index_list2) else 0
new_list = [None] * (max_index + 1)
# 根据索引填充数据
for idx in index_list1:
new_list[idx] = data_list[0]
for idx in index_list2:
new_list[idx] = data_list[1]
return new_list
def get_ms_phrase_emb(boxes, device, weight_dtype, drop_grounding_tokens, bsz, phrase_idxes,
num_samples, eot_idxes,phrases,clip,tokenizer):
cross_attention_kwargs = None
grounding_kwargs = None
if boxes is not None:
boxes = torch.tensor(boxes).to(device, weight_dtype) #torch.Size([1, 2, 4])
if phrases is not None:
drop_grounding_tokens = drop_grounding_tokens if drop_grounding_tokens is not None else [0] * bsz
batch_boxes = boxes.view(bsz * boxes.shape[1], -1).to(device)
phrase_input_ids=[]
for phrase in phrases:
phrase_input_id = tokenizer(phrase, max_length=tokenizer.model_max_length,
padding="max_length", truncation=True,
return_tensors="pt").input_ids
int_list = phrase_input_id.tolist()[0]
clean_input_ids_1=[(i,1.0) for i in int_list]
clean_input_ids_2=[(i,1.0) for i in int_list if i==int_list[0] or i==49407 ]
clean_input_ids_2=clean_input_ids_2[:77] if len(clean_input_ids_2) >=77 else clean_input_ids_2 + [(0,1.0)]*(77 - len(clean_input_ids_2))
phrase_input_ids.append([clean_input_ids_1,clean_input_ids_2])
phrase_embeds_list = []
for i in phrase_input_ids:
_, pooled_prompt_embed_= clip.cond_stage_model.clip_l.encode_token_weights(i)
pooled_prompt_embed_= pooled_prompt_embed_.to(device,dtype=weight_dtype)
phrase_embeds_list.append(pooled_prompt_embed_)
#phrase_input_id = clip.tokenize(phrase, return_word_ids=False)["l"]
#output_=clip.cond_stage_model.clip_l.encode_token_weights(phrase_input_id)[1]
phrase_embeds=torch.cat(phrase_embeds_list,dim=0)
#print(phrase_embeds.shape,phrase_embeds.is_cuda,batch_boxes.shape,batch_boxes.is_cuda)#torch.Size([2, 768]) torch.Size([2 4])
grounding_kwargs = {"boxes": batch_boxes, "phrase_embeds": phrase_embeds,"drop_grounding_tokens": drop_grounding_tokens}
else:
grounding_kwargs = None
boxes = torch.repeat_interleave(boxes, repeats=num_samples, dim=0)
uncond_boxes = torch.zeros_like(boxes)
boxes = torch.cat([uncond_boxes, boxes], dim=0)
cross_attention_kwargs = {"boxes": boxes}
if phrase_idxes is not None:
# phrase_idxes = torch.tensor(phrase_idxes).to(device, torch.int)
# eot_idxes = torch.tensor(eot_idxes).to(device, torch.int)
phrase_idxes = torch.tensor(phrase_idxes).to(device, weight_dtype)
eot_idxes = torch.tensor(eot_idxes).to(device, weight_dtype)
phrase_idxes = torch.repeat_interleave(phrase_idxes, repeats=num_samples, dim=0)
eot_idxes = torch.repeat_interleave(eot_idxes, repeats=num_samples, dim=0)
uncond_phrase_idxes = torch.zeros_like(phrase_idxes)
uncond_eot_idxes = torch.zeros_like(eot_idxes)
phrase_idxes = torch.cat([uncond_phrase_idxes, phrase_idxes], dim=0)