forked from Fannovel16/ComfyUI-MotionDiff
-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
328 lines (293 loc) · 12.2 KB
/
__init__.py
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
import torch
import os
import sys
from pathlib import Path
EXTENSION_PATH = Path(__file__).parent
sys.path.insert(0, str(EXTENSION_PATH.resolve()))
import custom_mmpkg.custom_mmcv as mmcv
import numpy as np
import torch
from motiondiff_modules.mogen.models import build_architecture
from custom_mmpkg.custom_mmcv.runner import load_checkpoint
from motiondiff_modules.mogen.utils.plot_utils import (
plot_3d_motion,
t2m_kinematic_chain
)
from comfy.model_management import get_torch_device
from .md_config import get_model_dataset_dict
from .utils import *
#from custom_mmpkg.custom_mmhuman3d.core.conventions.keypoints_mapping import convert_kps
#from custom_mmpkg.custom_mmhuman3d.core.visualization.visualize_keypoints3d import visualize_kp3d
from pathlib import Path
import importlib, traceback
def create_mdm_model(model_config):
cfg = mmcv.Config.fromstring(model_config.config_code, '.py')
mdm = build_architecture(cfg.model)
load_checkpoint(mdm, str(model_config.ckpt_path), map_location='cpu')
mdm.eval().cpu()
return mdm
class MotionDiffModelWrapper(torch.nn.Module): #Anything beside CLIP (mdm.model)
def __init__(self, mdm, dataset) -> None:
super(MotionDiffModelWrapper, self).__init__()
self.loss_recon=mdm.loss_recon
self.diffusion_train=mdm.diffusion_train
self.diffusion_test=mdm.diffusion_test
self.sampler=mdm.sampler
self.dataset = dataset
def forward(self, clip, cond_dict, **kwargs):
motion, motion_mask = kwargs['motion'].float(), kwargs['motion_mask'].float()
sample_idx = kwargs.get('sample_idx', None)
clip_feat = kwargs.get('clip_feat', None)
sampler = kwargs.get('sampler', 'ddpm')
seed = kwargs.get('seed', None)
B, T = motion.shape[:2]
dim_pose = kwargs['motion'].shape[-1]
model_kwargs = cond_dict
model_kwargs['motion_mask'] = motion_mask
model_kwargs['sample_idx'] = sample_idx
inference_kwargs = kwargs.get('inference_kwargs', {})
if sampler == 'ddpm':
output = self.diffusion_test.p_sample_loop(
clip,
(B, T, dim_pose),
clip_denoised=False,
progress=False,
model_kwargs=model_kwargs,
seed=seed,
**inference_kwargs
)
else:
output = self.diffusion_test.ddim_sample_loop(
clip,
(B, T, dim_pose),
clip_denoised=False,
progress=False,
model_kwargs=model_kwargs,
eta=0,
seed=seed,
**inference_kwargs
)
if getattr(clip, "post_process") is not None:
output = clip.post_process(output)
results = kwargs
results['pred_motion'] = output
results = self.split_results(results)
return results
def split_results(self, results):
B = results['motion'].shape[0]
output = []
for i in range(B):
batch_output = dict()
batch_output['motion'] = to_cpu(results['motion'][i])
batch_output['pred_motion'] = to_cpu(results['pred_motion'][i])
batch_output['motion_length'] = to_cpu(results['motion_length'][i])
batch_output['motion_mask'] = to_cpu(results['motion_mask'][i])
if 'pred_motion_length' in results.keys():
batch_output['pred_motion_length'] = to_cpu(results['pred_motion_length'][i])
else:
batch_output['pred_motion_length'] = to_cpu(results['motion_length'][i])
if 'pred_motion_mask' in results:
batch_output['pred_motion_mask'] = to_cpu(results['pred_motion_mask'][i])
else:
batch_output['pred_motion_mask'] = to_cpu(results['motion_mask'][i])
if 'motion_metas' in results.keys():
motion_metas = results['motion_metas'][i]
if 'text' in motion_metas.keys():
batch_output['text'] = motion_metas['text']
if 'token' in motion_metas.keys():
batch_output['token'] = motion_metas['token']
output.append(batch_output)
return output
class MotionDiffCLIPWrapper(torch.nn.Module):
def __init__(self, mdm):
super(MotionDiffCLIPWrapper, self).__init__()
self.model = mdm.model
def forward(self, text, motion_data):
self.model.to(get_torch_device())
B, T = motion_data["motion"].shape[:2]
texts = []
for _ in range(B):
texts.append(text)
out = self.model.get_precompute_condition(device=get_torch_device(), text=texts, **motion_data)
self.model.cpu()
return out
model_dataset_dict = None
class MotionDiffLoader:
@classmethod
def INPUT_TYPES(s):
global model_dataset_dict
model_dataset_dict = get_model_dataset_dict()
return {
"required": {
"model_dataset": (
list(model_dataset_dict.keys()),
{ "default": "-human_ml3d" }
)
},
}
RETURN_TYPES = ("MD_MODEL", "MD_CLIP")
CATEGORY = "MotionDiff"
FUNCTION = "load_mdm"
def load_mdm(self, model_dataset):
global model_dataset_dict
if model_dataset_dict is None:
model_dataset_dict = get_model_dataset_dict() #In case of API users
model_config = model_dataset_dict[model_dataset]()
mdm = create_mdm_model(model_config)
return (MotionDiffModelWrapper(mdm, dataset=model_config.dataset), MotionDiffCLIPWrapper(mdm))
class MotionCLIPTextEncode:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"md_clip": ("MD_CLIP", ),
"motion_data": ("MOTION_DATA", ),
"text": ("STRING", {"default": "a person performs a cartwheel" ,"multiline": True})
},
}
RETURN_TYPES = ("MD_CONDITIONING",)
CATEGORY = "MotionDiff"
FUNCTION = "encode_text"
def encode_text(self, md_clip, motion_data, text):
return (md_clip(text, motion_data), )
class EmptyMotionData:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"frames": ("INT", {"default": 196, "min": 1, "max": 196})
}
}
RETURN_TYPES = ("MOTION_DATA", )
CATEGORY = "MotionDiff"
FUNCTION = "encode_text"
def encode_text(self, frames):
return ({
'motion': torch.zeros(1, frames, 263),
'motion_mask': torch.ones(1, frames),
'motion_length': torch.Tensor([frames]).long(),
}, )
class MotionDiffSimpleSampler:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"sampler_name": (["ddpm", "ddim"], {"default": "ddim"}),
"md_model": ("MD_MODEL", ),
"md_clip": ("MD_CLIP", ),
"md_cond": ("MD_CONDITIONING", ),
"motion_data": ("MOTION_DATA",),
"seed": ("INT", {"default": 123,"min": 0, "max": 0xffffffffffffffff, "step": 1}),
}
}
RETURN_TYPES = ("MOTION_DATA",)
CATEGORY = "MotionDiff"
FUNCTION = "sample"
def sample(self, sampler_name, md_model: MotionDiffModelWrapper, md_clip, md_cond, motion_data, seed):
md_model.to(get_torch_device())
md_clip.to(get_torch_device())
for key in motion_data:
motion_data[key] = to_gpu(motion_data[key])
kwargs = {
**motion_data,
'inference_kwargs': {},
'sampler': sampler_name,
'seed': seed
}
with torch.no_grad():
output = md_model(md_clip.model, cond_dict=md_cond, **kwargs)[0]['pred_motion']
pred_motion = output * md_model.dataset.std + md_model.dataset.mean
pred_motion = pred_motion.cpu().detach()
md_model.cpu(), md_clip.cpu()
for key in motion_data:
motion_data[key] = to_cpu(motion_data[key])
return ({
'motion': pred_motion,
'motion_mask': motion_data['motion_mask'],
'motion_length': motion_data['motion_length'],
}, )
class MotionDataVisualizer:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"motion_data": ("MOTION_DATA", ),
"visualization": (["original", "pseudo-openpose"], {"default": "pseudo-openpose"}),
"distance": ("FLOAT", {"default": 7.0, "min": 0.0, "max": 10.0, "step": 0.1}),
"elevation": ("FLOAT", {"default": 120, "min": 0.0, "max": 300.0, "step": 0.1}),
"rotation": ("FLOAT", {"default": -90, "min": -180, "max": 180, "step": 1}),
"poselinewidth": ("FLOAT", {"default": 4, "min": 0, "max": 50, "step": 0.1}),
},
"optional": {
"opt_title": ("STRING", {"default": '' ,"multiline": False}),
}
}
RETURN_TYPES = ("IMAGE",)
CATEGORY = "MotionDiff"
FUNCTION = "visualize"
def visualize(self, motion_data, visualization, distance, elevation, rotation, poselinewidth, opt_title=None):
if "joints" in motion_data:
joints = motion_data["joints"]
else:
joints = motion_data_to_joints(motion_data["motion"])
pil_frames = plot_3d_motion(
None, t2m_kinematic_chain, joints, distance, elevation, rotation, poselinewidth,
title=opt_title if opt_title is not None else '',
fps=1, save_as_pil_lists=True, visualization=visualization
)
tensor_frames = []
for pil_image in pil_frames:
np_image = np.array(pil_image.convert("RGB")).astype(np.float32) / 255.0
tensor_frames.append(torch.from_numpy(np_image))
return (torch.stack(tensor_frames, dim=0), )
def load_nodes():
shorted_errors = []
full_error_messages = []
node_class_mappings = {}
node_display_name_mappings = {}
for filename in (Path(__file__).parent / "nodes").iterdir():
module_name = filename.stem
if module_name.startswith('.'): continue #Skip hidden files created by the OS (e.g. [.DS_Store](https://en.wikipedia.org/wiki/.DS_Store))
try:
module = importlib.import_module(f".nodes.{module_name}", package=__package__)
node_class_mappings.update(getattr(module, "NODE_CLASS_MAPPINGS"))
if hasattr(module, "NODE_DISPLAY_NAME_MAPPINGS"):
node_display_name_mappings.update(getattr(module, "NODE_DISPLAY_NAME_MAPPINGS"))
print(f"Imported {module_name} nodes")
except AttributeError:
pass # wip nodes
except Exception:
error_message = traceback.format_exc()
full_error_messages.append(error_message)
error_message = error_message.splitlines()[-1]
shorted_errors.append(
f"Failed to import module {module_name} because {error_message}"
)
if len(shorted_errors) > 0:
full_err_log = '\n\n'.join(full_error_messages)
print(f"\n\nFull error log from ComfyUI-MotionDiff: \n{full_err_log}\n\n")
print(
f"Some nodes failed to load:\n\t"
+ "\n\t".join(shorted_errors)
+ "\n\n"
+ "Check that you properly installed the dependencies.\n"
+ "If you think this is a bug, please report it on the github page (https://github.com/Fannovel16/ComfyUI-MotionDiff/issues)"
)
return node_class_mappings, node_display_name_mappings
AUX_NODE_MAPPINGS, AUX_DISPLAY_NAME_MAPPINGS = load_nodes()
NODE_CLASS_MAPPINGS = {
"MotionDiffLoader": MotionDiffLoader,
"MotionCLIPTextEncode": MotionCLIPTextEncode,
"MotionDiffSimpleSampler": MotionDiffSimpleSampler,
"EmptyMotionData": EmptyMotionData,
"MotionDataVisualizer": MotionDataVisualizer,
**AUX_NODE_MAPPINGS
}
NODE_DISPLAY_NAME_MAPPINGS = {
"MotionDiffLoader": "MotionDiff Loader",
"MotionCLIPTextEncode": "MotionCLIP Text Encode",
"MotionDiffSimpleSampler": "MotionDiff Simple Sampler",
"EmptyMotionData": "Empty Motion Data",
"MotionDataVisualizer": "Motion Data Visualizer",
**AUX_DISPLAY_NAME_MAPPINGS
}