vumichien commited on
Commit
8770e77
1 Parent(s): 74c3c5d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +288 -0
app.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ import OpenGL.GL as gl
4
+ os.environ["PYOPENGL_PLATFORM"] = "egl"
5
+ sys.argv = ['VQ-Trans/GPT_eval_multi.py']
6
+ os.makedirs('output', exist_ok=True)
7
+ os.chdir('VQ-Trans')
8
+ os.makedirs('checkpoints', exist_ok=True)
9
+ os.system('gdown --fuzzy https://drive.google.com/file/d/1o7RTDQcToJjTm9_mNWTyzvZvjTWpZfug/view -O checkpoints')
10
+ os.system('gdown --fuzzy https://drive.google.com/file/d/1tX79xk0fflp07EZ660Xz1RAFE33iEyJR/view -O checkpoints')
11
+ os.system('unzip checkpoints/t2m.zip')
12
+ os.system('unzip checkpoints/kit.zip')
13
+ os.system('rm checkpoints/t2m.zip')
14
+ os.system('rm checkpoints/kit.zip')
15
+ sys.path.append('/home/user/app/VQ-Trans')
16
+
17
+ import options.option_transformer as option_trans
18
+ from huggingface_hub import snapshot_download
19
+ model_path = snapshot_download(repo_id="vumichien/T2M-GPT")
20
+
21
+ args = option_trans.get_args_parser()
22
+
23
+ args.dataname = 't2m'
24
+ args.resume_pth = f'{model_path}/VQVAE/net_last.pth'
25
+ args.resume_trans = f'{model_path}/VQTransformer_corruption05/net_best_fid.pth'
26
+ args.down_t = 2
27
+ args.depth = 3
28
+ args.block_size = 51
29
+
30
+ import clip
31
+ import torch
32
+ import numpy as np
33
+ import models.vqvae as vqvae
34
+ import models.t2m_trans as trans
35
+ from utils.motion_process import recover_from_ric
36
+ import visualization.plot_3d_global as plot_3d
37
+ from models.rotation2xyz import Rotation2xyz
38
+ import numpy as np
39
+ from trimesh import Trimesh
40
+ import gc
41
+
42
+ import torch
43
+ from visualize.simplify_loc2rot import joints2smpl
44
+ import pyrender
45
+ # import matplotlib.pyplot as plt
46
+
47
+ import io
48
+ import imageio
49
+ from shapely import geometry
50
+ import trimesh
51
+ from pyrender.constants import RenderFlags
52
+ import math
53
+ # import ffmpeg
54
+ # from PIL import Image
55
+ import hashlib
56
+ import gradio as gr
57
+
58
+ ## load clip model and datasets
59
+ is_cuda = torch.cuda.is_available()
60
+ device = torch.device("cuda" if is_cuda else "cpu")
61
+ print(device)
62
+ clip_model, clip_preprocess = clip.load("ViT-B/32", device=device, jit=False, download_root='./') # Must set jit=False for training
63
+ clip.model.convert_weights(clip_model) # Actually this line is unnecessary since clip by default already on float16
64
+ clip_model.eval()
65
+ for p in clip_model.parameters():
66
+ p.requires_grad = False
67
+
68
+ net = vqvae.HumanVQVAE(args, ## use args to define different parameters in different quantizers
69
+ args.nb_code,
70
+ args.code_dim,
71
+ args.output_emb_width,
72
+ args.down_t,
73
+ args.stride_t,
74
+ args.width,
75
+ args.depth,
76
+ args.dilation_growth_rate)
77
+
78
+
79
+ trans_encoder = trans.Text2Motion_Transformer(num_vq=args.nb_code,
80
+ embed_dim=1024,
81
+ clip_dim=args.clip_dim,
82
+ block_size=args.block_size,
83
+ num_layers=9,
84
+ n_head=16,
85
+ drop_out_rate=args.drop_out_rate,
86
+ fc_rate=args.ff_rate)
87
+
88
+
89
+ print('loading checkpoint from {}'.format(args.resume_pth))
90
+ ckpt = torch.load(args.resume_pth, map_location='cpu')
91
+ net.load_state_dict(ckpt['net'], strict=True)
92
+ net.eval()
93
+
94
+ print('loading transformer checkpoint from {}'.format(args.resume_trans))
95
+ ckpt = torch.load(args.resume_trans, map_location='cpu')
96
+ trans_encoder.load_state_dict(ckpt['trans'], strict=True)
97
+ trans_encoder.eval()
98
+ mean = torch.from_numpy(np.load('./checkpoints/t2m/VQVAEV3_CB1024_CMT_H1024_NRES3/meta/mean.npy'))
99
+ std = torch.from_numpy(np.load('./checkpoints/t2m/VQVAEV3_CB1024_CMT_H1024_NRES3/meta/std.npy'))
100
+ if is_cuda:
101
+ net.cuda()
102
+ trans_encoder.cuda()
103
+ mean = mean.cuda()
104
+ std = std.cuda()
105
+
106
+
107
+ def render(motions, device_id=0, name='test_vis'):
108
+ frames, njoints, nfeats = motions.shape
109
+ MINS = motions.min(axis=0).min(axis=0)
110
+ MAXS = motions.max(axis=0).max(axis=0)
111
+
112
+ height_offset = MINS[1]
113
+ motions[:, :, 1] -= height_offset
114
+ trajec = motions[:, 0, [0, 2]]
115
+ is_cuda = torch.cuda.is_available()
116
+ # device = torch.device("cuda" if is_cuda else "cpu")
117
+ j2s = joints2smpl(num_frames=frames, device_id=0, cuda=is_cuda)
118
+ rot2xyz = Rotation2xyz(device=device)
119
+ faces = rot2xyz.smpl_model.faces
120
+
121
+ if not os.path.exists(f'output/{name}_pred.pt'):
122
+ print(f'Running SMPLify, it may take a few minutes.')
123
+ motion_tensor, opt_dict = j2s.joint2smpl(motions) # [nframes, njoints, 3]
124
+
125
+ vertices = rot2xyz(torch.tensor(motion_tensor).clone(), mask=None,
126
+ pose_rep='rot6d', translation=True, glob=True,
127
+ jointstype='vertices',
128
+ vertstrans=True)
129
+ vertices = vertices.detach().cpu()
130
+ torch.save(vertices, f'output/{name}_pred.pt')
131
+ else:
132
+ vertices = torch.load(f'output/{name}_pred.pt')
133
+ frames = vertices.shape[3] # shape: 1, nb_frames, 3, nb_joints
134
+ print(vertices.shape)
135
+ MINS = torch.min(torch.min(vertices[0], axis=0)[0], axis=1)[0]
136
+ MAXS = torch.max(torch.max(vertices[0], axis=0)[0], axis=1)[0]
137
+
138
+ out_list = []
139
+
140
+ minx = MINS[0] - 0.5
141
+ maxx = MAXS[0] + 0.5
142
+ minz = MINS[2] - 0.5
143
+ maxz = MAXS[2] + 0.5
144
+ polygon = geometry.Polygon([[minx, minz], [minx, maxz], [maxx, maxz], [maxx, minz]])
145
+ polygon_mesh = trimesh.creation.extrude_polygon(polygon, 1e-5)
146
+
147
+ vid = []
148
+ for i in range(frames):
149
+ if i % 10 == 0:
150
+ print(i)
151
+
152
+ mesh = Trimesh(vertices=vertices[0, :, :, i].squeeze().tolist(), faces=faces)
153
+
154
+ base_color = (0.11, 0.53, 0.8, 0.5)
155
+ ## OPAQUE rendering without alpha
156
+ ## BLEND rendering consider alpha
157
+ material = pyrender.MetallicRoughnessMaterial(
158
+ metallicFactor=0.7,
159
+ alphaMode='OPAQUE',
160
+ baseColorFactor=base_color
161
+ )
162
+
163
+
164
+ mesh = pyrender.Mesh.from_trimesh(mesh, material=material)
165
+
166
+ polygon_mesh.visual.face_colors = [0, 0, 0, 0.21]
167
+ polygon_render = pyrender.Mesh.from_trimesh(polygon_mesh, smooth=False)
168
+
169
+ bg_color = [1, 1, 1, 0.8]
170
+ scene = pyrender.Scene(bg_color=bg_color, ambient_light=(0.4, 0.4, 0.4))
171
+
172
+ sx, sy, tx, ty = [0.75, 0.75, 0, 0.10]
173
+
174
+ camera = pyrender.PerspectiveCamera(yfov=(np.pi / 3.0))
175
+
176
+ light = pyrender.DirectionalLight(color=[1,1,1], intensity=300)
177
+
178
+ scene.add(mesh)
179
+
180
+ c = np.pi / 2
181
+
182
+ scene.add(polygon_render, pose=np.array([[ 1, 0, 0, 0],
183
+
184
+ [ 0, np.cos(c), -np.sin(c), MINS[1].cpu().numpy()],
185
+
186
+ [ 0, np.sin(c), np.cos(c), 0],
187
+
188
+ [ 0, 0, 0, 1]]))
189
+
190
+ light_pose = np.eye(4)
191
+ light_pose[:3, 3] = [0, -1, 1]
192
+ scene.add(light, pose=light_pose.copy())
193
+
194
+ light_pose[:3, 3] = [0, 1, 1]
195
+ scene.add(light, pose=light_pose.copy())
196
+
197
+ light_pose[:3, 3] = [1, 1, 2]
198
+ scene.add(light, pose=light_pose.copy())
199
+
200
+
201
+ c = -np.pi / 6
202
+
203
+ scene.add(camera, pose=[[ 1, 0, 0, (minx+maxx).cpu().numpy()/2],
204
+
205
+ [ 0, np.cos(c), -np.sin(c), 1.5],
206
+
207
+ [ 0, np.sin(c), np.cos(c), max(4, minz.cpu().numpy()+(1.5-MINS[1].cpu().numpy())*2, (maxx-minx).cpu().numpy())],
208
+
209
+ [ 0, 0, 0, 1]
210
+ ])
211
+
212
+ # render scene
213
+ r = pyrender.OffscreenRenderer(960, 960)
214
+
215
+ color, _ = r.render(scene, flags=RenderFlags.RGBA)
216
+ # Image.fromarray(color).save(outdir+'/'+name+'_'+str(i)+'.png')
217
+
218
+ vid.append(color)
219
+
220
+ r.delete()
221
+
222
+ out = np.stack(vid, axis=0)
223
+ imageio.mimwrite(f'output/results.gif', out, fps=20)
224
+ del out, vertices
225
+ return f'output/results.gif'
226
+
227
+ def predict(clip_text, method='fast'):
228
+ gc.collect()
229
+ if torch.cuda.is_available():
230
+ text = clip.tokenize([clip_text], truncate=True).cuda()
231
+ else:
232
+ text = clip.tokenize([clip_text], truncate=True)
233
+ feat_clip_text = clip_model.encode_text(text).float()
234
+ index_motion = trans_encoder.sample(feat_clip_text[0:1], False)
235
+ pred_pose = net.forward_decoder(index_motion)
236
+ pred_xyz = recover_from_ric((pred_pose*std+mean).float(), 22)
237
+ output_name = hashlib.md5(clip_text.encode()).hexdigest()
238
+ if method == 'fast':
239
+ xyz = pred_xyz.reshape(1, -1, 22, 3)
240
+ pose_vis = plot_3d.draw_to_batch(xyz.detach().cpu().numpy(), title_batch=None, outname=[f'output/results.gif'])
241
+ return f'output/results.gif'
242
+ elif method == 'slow':
243
+ output_path = render(pred_xyz.detach().cpu().numpy().squeeze(axis=0), device_id=0, name=output_name)
244
+ return output_path
245
+
246
+
247
+ # ---- Gradio Layout -----
248
+ text_prompt = gr.Textbox(label="Text prompt", lines=1, interactive=True)
249
+ video_out = gr.Video(label="Motion", mirror_webcam=False, interactive=False)
250
+ demo = gr.Blocks()
251
+ demo.encrypt = False
252
+
253
+ with demo:
254
+ gr.Markdown('''
255
+ <div>
256
+ <h1 style='text-align: center'>Generating Human Motion from Textual Descriptions with Discrete Representations (T2M-GPT)</h1>
257
+ 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🤗
258
+ </div>
259
+ ''')
260
+ with gr.Row():
261
+ gr.Markdown('''
262
+ ### Generate human motion by **T2M-GPT**
263
+ ##### Step 1. Give prompt text describing human motion
264
+ ##### Step 2. Choice method to generate output (Fast: Sketch skeleton; Slow: SMPL mesh)
265
+ ##### Step 3. Generate output and enjoy
266
+ ''')
267
+ with gr.Row():
268
+ gr.Markdown('''
269
+ ### You can test by following examples:
270
+ ''')
271
+ examples = gr.Examples(examples=
272
+ [ "a person jogs in place, slowly at first, then increases speed. they then back up and squat down.",
273
+ "a man steps forward and does a handstand",
274
+ "a man rises from the ground, walks in a circle and sits back down on the ground"],
275
+ label="Examples", inputs=[text_prompt])
276
+
277
+ with gr.Column():
278
+ with gr.Row():
279
+ text_prompt.render()
280
+ method = gr.Dropdown(["slow", "fast"], label="Method", value="fast")
281
+ with gr.Row():
282
+ generate_btn = gr.Button("Generate")
283
+ generate_btn.click(predict, [text_prompt, method], [video_out])
284
+ print(video_out)
285
+ with gr.Row():
286
+ video_out.render()
287
+
288
+ demo.launch(debug=True)