File size: 18,910 Bytes
8d5568e | 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 | import sys
import os
import OpenGL.GL as gl
# os.environ["PYOPENGL_PLATFORM"] = "egl"
os.environ["MESA_GL_VERSION_OVERRIDE"] = "4.1"
# os.system('pip install /home/user/app/pyrender')
sys.argv = ['VQ-Trans/GPT_eval_multi.py']
os.chdir('VQ-Trans')
sys.path.append('./VQ-Trans')
sys.path.append('./pyrender')
import options.option_transformer as option_trans
from huggingface_hub import snapshot_download
model_path = snapshot_download(repo_id="vumichien/T2M-GPT")
args = option_trans.get_args_parser()
args.dataname = 't2m'
args.resume_pth = f'{model_path}/VQVAE/net_last.pth'
args.resume_trans = f'{model_path}/VQTransformer_corruption05/net_best_fid.pth'
args.down_t = 2
args.depth = 3
args.block_size = 51
import clip
import torch
import numpy as np
import models.vqvae as vqvae
import models.t2m_trans as trans
from utils.motion_process import recover_from_ric
import visualization.plot_3d_global as plot_3d
from models.rotation2xyz import Rotation2xyz
import numpy as np
from trimesh import Trimesh
import gc
import torch
from visualize.simplify_loc2rot import joints2smpl
import pyrender
# import matplotlib.pyplot as plt
import io
import imageio
from shapely import geometry
import trimesh
from pyrender.constants import RenderFlags
import math
# import ffmpeg
# from PIL import Image
import hashlib
import gradio as gr
import moviepy.editor as mp
from datetime import datetime
## load clip model and datasets
is_cuda = torch.cuda.is_available()
device = torch.device("cuda" if is_cuda else "cpu")
print(device)
clip_model, clip_preprocess = clip.load("ViT-B/32", device=device, jit=False, download_root='./') # Must set jit=False for training
if is_cuda:
clip.model.convert_weights(clip_model)
clip_model.eval()
for p in clip_model.parameters():
p.requires_grad = False
net = vqvae.HumanVQVAE(args, ## use args to define different parameters in different quantizers
args.nb_code,
args.code_dim,
args.output_emb_width,
args.down_t,
args.stride_t,
args.width,
args.depth,
args.dilation_growth_rate)
trans_encoder = trans.Text2Motion_Transformer(num_vq=args.nb_code,
embed_dim=1024,
clip_dim=args.clip_dim,
block_size=args.block_size,
num_layers=9,
n_head=16,
drop_out_rate=args.drop_out_rate,
fc_rate=args.ff_rate)
print('loading checkpoint from {}'.format(args.resume_pth))
ckpt = torch.load(args.resume_pth, map_location='cpu')
net.load_state_dict(ckpt['net'], strict=True)
net.eval()
print('loading transformer checkpoint from {}'.format(args.resume_trans))
ckpt = torch.load(args.resume_trans, map_location='cpu')
trans_encoder.load_state_dict(ckpt['trans'], strict=True)
trans_encoder.eval()
mean = torch.from_numpy(np.load(f'{model_path}/meta/mean.npy'))
std = torch.from_numpy(np.load(f'{model_path}/meta/std.npy'))
if is_cuda:
net.cuda()
trans_encoder.cuda()
mean = mean.cuda()
std = std.cuda()
def ensure_directory(path):
"""Tạo thư mục nếu chưa tồn tại"""
if not os.path.exists(path):
os.makedirs(path)
print(f"Created directory: {path}")
def get_output_path(output_dir, filename, extension):
"""Tạo đường dẫn đầy đủ cho file output"""
ensure_directory(output_dir)
if not filename.endswith(extension):
filename += extension
return os.path.join(output_dir, filename)
def render(motions, output_dir='output', filename='results', device_id=0):
"""
Render motion với tùy chọn thư mục và tên file
Args:
motions: Motion data
output_dir: Thư mục lưu kết quả (mặc định: 'output')
filename: Tên file không có extension (mặc định: 'results')
device_id: GPU device ID
"""
try:
frames, njoints, nfeats = motions.shape
MINS = motions.min(axis=0).min(axis=0)
MAXS = motions.max(axis=0).max(axis=0)
height_offset = MINS[1]
motions[:, :, 1] -= height_offset
trajec = motions[:, 0, [0, 2]]
is_cuda = torch.cuda.is_available()
j2s = joints2smpl(num_frames=frames, device_id=0, cuda=is_cuda)
rot2xyz = Rotation2xyz(device=device)
faces = rot2xyz.smpl_model.faces
# Tạo đường dẫn cho file .pt
pt_path = get_output_path(output_dir, f'{filename}_pred', '.pt')
if not os.path.exists(pt_path):
print(f'Running SMPLify, it may take a few minutes.')
motion_tensor, opt_dict = j2s.joint2smpl(motions)
vertices = rot2xyz(torch.tensor(motion_tensor).clone(), mask=None,
pose_rep='rot6d', translation=True, glob=True,
jointstype='vertices',
vertstrans=True)
vertices = vertices.detach().cpu()
torch.save(vertices, pt_path)
else:
vertices = torch.load(pt_path)
frames = vertices.shape[3]
print(f"Vertices shape: {vertices.shape}")
MINS = torch.min(torch.min(vertices[0], axis=0)[0], axis=1)[0]
MAXS = torch.max(torch.max(vertices[0], axis=0)[0], axis=1)[0]
out_list = []
minx = MINS[0] - 0.5
maxx = MAXS[0] + 0.5
minz = MINS[2] - 0.5
maxz = MAXS[2] + 0.5
polygon = geometry.Polygon([[minx, minz], [minx, maxz], [maxx, maxz], [maxx, minz]])
polygon_mesh = trimesh.creation.extrude_polygon(polygon, 1e-5)
vid = []
for i in range(frames):
if i % 10 == 0:
print(f"Processing frame {i}/{frames}")
try:
mesh = Trimesh(vertices=vertices[0, :, :, i].squeeze().tolist(), faces=faces)
base_color = (0.11, 0.53, 0.8, 0.5)
material = pyrender.MetallicRoughnessMaterial(
metallicFactor=0.7,
alphaMode='OPAQUE',
baseColorFactor=base_color
)
mesh = pyrender.Mesh.from_trimesh(mesh, material=material)
polygon_mesh.visual.face_colors = [0, 0, 0, 0.21]
polygon_render = pyrender.Mesh.from_trimesh(polygon_mesh, smooth=False)
bg_color = [1, 1, 1, 0.8]
scene = pyrender.Scene(bg_color=bg_color, ambient_light=(0.4, 0.4, 0.4))
sx, sy, tx, ty = [0.75, 0.75, 0, 0.10]
camera = pyrender.PerspectiveCamera(yfov=(np.pi / 3.0))
light = pyrender.DirectionalLight(color=[1,1,1], intensity=300)
scene.add(mesh)
c = np.pi / 2
scene.add(polygon_render, pose=np.array([
[1, 0, 0, 0],
[0, np.cos(c), -np.sin(c), MINS[1].cpu().numpy()],
[0, np.sin(c), np.cos(c), 0],
[0, 0, 0, 1]
]))
light_pose = np.eye(4)
light_pose[:3, 3] = [0, -1, 1]
scene.add(light, pose=light_pose.copy())
light_pose[:3, 3] = [0, 1, 1]
scene.add(light, pose=light_pose.copy())
light_pose[:3, 3] = [1, 1, 2]
scene.add(light, pose=light_pose.copy())
c = -np.pi / 6
scene.add(camera, pose=np.array([
[1, 0, 0, (minx+maxx).cpu().numpy()/2],
[0, np.cos(c), -np.sin(c), 1.5],
[0, np.sin(c), np.cos(c), max(4, minz.cpu().numpy()+(1.5-MINS[1].cpu().numpy())*2, (maxx-minx).cpu().numpy())],
[0, 0, 0, 1]
]))
r = pyrender.OffscreenRenderer(960, 960)
color, _ = r.render(scene, flags=RenderFlags.RGBA)
vid.append(color)
r.delete()
except Exception as e:
print(f"Error processing frame {i}: {str(e)}")
continue
if not vid:
raise Exception("No frames were successfully processed")
out = np.stack(vid, axis=0)
# Tạo đường dẫn cho file GIF và MP4
gif_path = get_output_path(output_dir, filename, '.gif')
mp4_path = get_output_path(output_dir, filename, '.mp4')
imageio.mimwrite(gif_path, out, duration=50)
out_video = mp.VideoFileClip(gif_path)
out_video.write_videofile(mp4_path)
# Set file permissions để đảm bảo file có thể được truy cập
try:
os.chmod(gif_path, 0o644)
os.chmod(mp4_path, 0o644)
except Exception as e:
print(f"Warning: Could not set file permissions: {str(e)}")
print(f"Results saved to: {mp4_path}")
del out, vertices
return mp4_path
except Exception as e:
print(f"Error in render function: {str(e)}")
# Fallback to fast rendering if slow rendering fails
print("Falling back to fast rendering...")
return None
def predict(clip_text, method='fast', output_dir='output', filename=''):
"""
Predict motion with custom output settings
Args:
clip_text: Text prompt
method: 'fast' or 'slow'
output_dir: Output directory
filename: Custom filename (if empty, will use hash or timestamp)
Returns:
tuple: (video_path, download_path) để hiển thị và download
"""
gc.collect()
print('prompt text instruction: {}'.format(clip_text))
# Đảm bảo output_dir là absolute path và trong thư mục hiện tại
if not os.path.isabs(output_dir):
output_dir = os.path.abspath(output_dir)
# Tạo tên file nếu không được cung cấp
if not filename.strip():
if method == 'fast':
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"motion_{timestamp}"
else:
filename = hashlib.md5(clip_text.encode()).hexdigest()
# Xử lý text với CLIP
if torch.cuda.is_available():
text = clip.tokenize([clip_text], truncate=True).cuda()
else:
text = clip.tokenize([clip_text], truncate=True)
feat_clip_text = clip_model.encode_text(text).float()
index_motion = trans_encoder.sample(feat_clip_text[0:1], False)
pred_pose = net.forward_decoder(index_motion)
pred_xyz = recover_from_ric((pred_pose*std+mean).float(), 22)
if method == 'fast':
xyz = pred_xyz.reshape(1, -1, 22, 3)
# Tạo đường dẫn cho fast method
gif_path = get_output_path(output_dir, filename, '.gif')
mp4_path = get_output_path(output_dir, filename, '.mp4')
pose_vis = plot_3d.draw_to_batch(xyz.detach().cpu().numpy(), title_batch=None, outname=[gif_path])
out_video = mp.VideoFileClip(gif_path)
out_video.write_videofile(mp4_path)
# Set file permissions để đảm bảo file có thể được truy cập
os.chmod(mp4_path, 0o644)
print(f"Fast render results saved to: {mp4_path}")
return mp4_path, mp4_path # Return both for display and download
elif method == 'slow':
try:
output_path = render(pred_xyz.detach().cpu().numpy().squeeze(axis=0),
output_dir=output_dir,
filename=filename,
device_id=0)
if output_path is None:
# Fallback to fast rendering if slow rendering fails
print("Slow rendering failed, using fast rendering instead...")
xyz = pred_xyz.reshape(1, -1, 22, 3)
gif_path = get_output_path(output_dir, filename, '.gif')
mp4_path = get_output_path(output_dir, filename, '.mp4')
pose_vis = plot_3d.draw_to_batch(xyz.detach().cpu().numpy(), title_batch=None, outname=[gif_path])
out_video = mp.VideoFileClip(gif_path)
out_video.write_videofile(mp4_path)
# Set file permissions
try:
os.chmod(mp4_path, 0o644)
except:
pass
return mp4_path, mp4_path
# Set file permissions để đảm bảo file có thể được truy cập
try:
os.chmod(output_path, 0o644)
except Exception as e:
print(f"Warning: Could not set file permissions: {str(e)}")
return output_path, output_path # Return both for display and download
except Exception as e:
print(f"Error in slow rendering: {str(e)}")
# Fallback to fast rendering
print("Falling back to fast rendering...")
xyz = pred_xyz.reshape(1, -1, 22, 3)
gif_path = get_output_path(output_dir, filename, '.gif')
mp4_path = get_output_path(output_dir, filename, '.mp4')
pose_vis = plot_3d.draw_to_batch(xyz.detach().cpu().numpy(), title_batch=None, outname=[gif_path])
out_video = mp.VideoFileClip(gif_path)
out_video.write_videofile(mp4_path)
# Set file permissions
try:
os.chmod(mp4_path, 0o644)
except:
pass
return mp4_path, mp4_path
# ---- Gradio Layout -----
video_out = gr.Video(label="Motion", mirror_webcam=False, interactive=False)
download_file = gr.File(label="Download Video", visible=False)
demo = gr.Blocks()
demo.encrypt = False
with demo:
gr.Markdown('''
<div>
<h1 style='text-align: center'>Generating Human Motion from Textual Descriptions (T2M-GPT)</h1>
This space uses <a href='https://mael-zys.github.io/T2M-GPT/' target='_blank'><b>T2M-GPT models</b></a> based on Vector Quantised-Variational AutoEncoder (VQ-VAE) and Generative Pre-trained Transformer (GPT) for human motion generation from textural descriptions🤗
</div>
''')
with gr.Row():
with gr.Column():
gr.Markdown('''
<figure>
<img src="https://huggingface.co/vumichien/T2M-GPT/resolve/main/demo_slow1.gif" alt="Demo Slow", width="425", height=480/>
<figcaption> a man starts off in an up right position with botg arms extended out by his sides, he then brings his arms down to his body and claps his hands together. after this he wals down amd the the left where he proceeds to sit on a seat
</figcaption>
</figure>
''')
with gr.Column():
gr.Markdown('''
<figure>
<img src="https://huggingface.co/vumichien/T2M-GPT/resolve/main/demo_slow2.gif" alt="Demo Slow 2", width="425", height=480/>
<figcaption> a person puts their hands together, leans forwards slightly then swings the arms from right to left
</figcaption>
</figure>
''')
with gr.Column():
gr.Markdown('''
<figure>
<img src="https://huggingface.co/vumichien/T2M-GPT/resolve/main/demo_slow3.gif" alt="Demo Slow 3", width="425", height=480/>
<figcaption> a man is practicing the waltz with a partner
</figcaption>
</figure>
''')
with gr.Row():
with gr.Column():
gr.Markdown('''
### Generate human motion by **T2M-GPT**
##### Step 1. Give prompt text describing human motion
##### Step 2. Choose method to render output (Fast: Sketch skeleton; Slow: SMPL mesh)
##### Step 3. Specify output directory and filename (optional)
##### Step 4. Generate output and enjoy
##### Step 5. Download your video using the download button below
''')
with gr.Column():
with gr.Row():
text_prompt = gr.Textbox(label="Text prompt", lines=1, interactive=True)
method = gr.Dropdown(["slow", "fast"], label="Method", value="slow")
with gr.Row():
output_dir = gr.Textbox(label="Output Directory", value="output", interactive=True)
filename = gr.Textbox(label="Filename (without extension)", placeholder="Leave empty for auto-generated name", interactive=True)
with gr.Row():
generate_btn = gr.Button("Generate")
with gr.Row():
video_out.render()
with gr.Row():
download_file.render()
# Kết nối button với function và output
generate_btn.click(
predict,
[text_prompt, method, output_dir, filename],
[video_out, download_file],
api_name="generate"
)
with gr.Row():
gr.Markdown('''
### You can test by following examples:
''')
examples = gr.Examples(
examples=[
["a person jogs in place, slowly at first, then increases speed. they then back up and squat down.", "slow", "output", "jogging_motion"],
["a man steps forward and does a handstand", "slow", "output", "handstand_motion"],
["a man rises from the ground, walks in a circle and sits back down on the ground", "slow", "output", "circle_walk"],
["a man starts off in an up right position with botg arms extended out by his sides, he then brings his arms down to his body and claps his hands together. after this he wals down amd the the left where he proceeds to sit on a seat", "slow", "output", "clap_and_sit"],
["a person puts their hands together, leans forwards slightly then swings the arms from right to left","slow", "output", "swing_arms"],
["a man is practicing the waltz with a partner","slow", "output", "waltz_dance"],
],
label="Examples",
inputs=[text_prompt, method, output_dir, filename],
outputs=[video_out, download_file],
fn=predict,
cache_examples=True,
)
demo.launch(debug=True, server_name="0.0.0.0", server_port=8000, inbrowser=True, share=True,
allowed_paths=[os.path.abspath("output"), os.path.abspath("./")]) |