megalado commited on
Commit
891dfcb
·
1 Parent(s): 5ee9026

Create different animations based on input parameters

Browse files
Files changed (1) hide show
  1. app.py +120 -69
app.py CHANGED
@@ -9,33 +9,7 @@ import subprocess
9
  import glob
10
  import requests
11
  import time
12
-
13
- def download_checkpoint():
14
- """Download the recommended checkpoint if not present"""
15
- # Create checkpoints directory
16
- os.makedirs("checkpoints", exist_ok=True)
17
-
18
- # Define the target checkpoint path
19
- checkpoint_path = "checkpoints/humanml_trans_enc_512.pt"
20
-
21
- if not Path(checkpoint_path).exists():
22
- print(f"Downloading checkpoint to {checkpoint_path}...")
23
- # URL for the checkpoint from HuggingFace or direct link
24
- url = "https://huggingface.co/spaces/mohaed/testMDM/resolve/main/checkpoints/mld_humanml.pt"
25
-
26
- # Download the file
27
- response = requests.get(url, stream=True)
28
- response.raise_for_status()
29
-
30
- with open(checkpoint_path, 'wb') as f:
31
- for chunk in response.iter_content(chunk_size=8192):
32
- f.write(chunk)
33
-
34
- print(f"Checkpoint downloaded to {checkpoint_path}")
35
- else:
36
- print(f"Checkpoint already exists at {checkpoint_path}")
37
-
38
- return checkpoint_path
39
 
40
  def inspect_mdm_repo():
41
  """Check the structure of the MDM repository"""
@@ -45,54 +19,109 @@ def inspect_mdm_repo():
45
 
46
  print("Inspecting MDM repository structure:")
47
  # List top-level directories and files
48
- for item in sorted(os.listdir("motion-diffusion-model")):
49
  path = os.path.join("motion-diffusion-model", item)
50
  if os.path.isdir(path):
51
  print(f"Directory: {item}")
52
- # List files in the directory
53
- for subitem in sorted(os.listdir(path)):
54
  print(f" - {subitem}")
55
  else:
56
  print(f"File: {item}")
 
57
 
58
- def create_simple_motion():
59
- """Create a simple motion animation as a fallback"""
60
- print("Creating a simple motion animation...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
  # Create a simple visualization script
63
- with open("simple_motion.py", "w") as f:
64
- f.write("""
65
  import numpy as np
66
  import matplotlib.pyplot as plt
67
  from matplotlib.animation import FuncAnimation
68
  import os
69
  from mpl_toolkits.mplot3d import Axes3D
 
70
 
71
- # Create a simple walking motion
72
- def generate_simple_motion(frames=90):
 
 
 
 
73
  joints = 16 # Number of joints in a simplified skeleton
74
  dims = 3 # x, y, z
75
 
76
  motion = np.zeros((frames, joints, dims))
77
 
78
- # Create a simple walking motion
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  for frame in range(frames):
80
  t = frame / frames
81
 
82
  # Basic forward motion
83
- motion[frame, :, 0] = t * 2 # Move forward on X axis
 
 
 
 
 
 
 
84
 
85
  # Root joint (pelvis)
86
- motion[frame, 0, 1] = 0 # Y position
87
- motion[frame, 0, 2] = np.sin(t * 2 * np.pi * 2) * 0.1 + 1 # Z position with slight bounce
 
 
 
 
 
 
88
 
89
  # Spine and head (joints 1, 2, 3)
90
  for i in range(1, 4):
91
- motion[frame, i, 1] = 0
92
  motion[frame, i, 2] = motion[frame, 0, 2] + i * 0.2 # Stack joints vertically
93
 
 
 
 
 
 
94
  # Left leg (joints 4, 5, 6)
95
- swing_leg_l = np.sin(t * 2 * np.pi * 2)
 
96
  motion[frame, 4, 1] = 0.2 # Left hip position
97
  motion[frame, 4, 2] = motion[frame, 0, 2] - 0.1
98
  motion[frame, 5, 1] = 0.2
@@ -101,7 +130,7 @@ def generate_simple_motion(frames=90):
101
  motion[frame, 6, 2] = motion[frame, 5, 2] - 0.5 + swing_leg_l * 0.3
102
 
103
  # Right leg (joints 7, 8, 9)
104
- swing_leg_r = np.sin(t * 2 * np.pi * 2 + np.pi) # Opposite phase
105
  motion[frame, 7, 1] = -0.2 # Right hip position
106
  motion[frame, 7, 2] = motion[frame, 0, 2] - 0.1
107
  motion[frame, 8, 1] = -0.2
@@ -110,17 +139,38 @@ def generate_simple_motion(frames=90):
110
  motion[frame, 9, 2] = motion[frame, 8, 2] - 0.5 + swing_leg_r * 0.3
111
 
112
  # Left arm (joints 10, 11, 12)
113
- swing_arm_l = np.sin(t * 2 * np.pi * 2 + np.pi) # Opposite to left leg
114
- motion[frame, 10, 1] = 0.3 # Left shoulder position
115
- motion[frame, 10, 2] = motion[frame, 3, 2] - 0.2
116
- motion[frame, 11, 1] = 0.3 + swing_arm_l * 0.2
117
- motion[frame, 11, 2] = motion[frame, 10, 2] - 0.4
118
- motion[frame, 12, 1] = 0.3 + swing_arm_l * 0.4
119
- motion[frame, 12, 2] = motion[frame, 11, 2] - 0.4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
  # Right arm (joints 13, 14, 15)
122
- swing_arm_r = np.sin(t * 2 * np.pi * 2) # Opposite to right leg
123
- motion[frame, 13, 1] = -0.3 # Right shoulder position
124
  motion[frame, 13, 2] = motion[frame, 3, 2] - 0.2
125
  motion[frame, 14, 1] = -0.3 + swing_arm_r * 0.2
126
  motion[frame, 14, 2] = motion[frame, 13, 2] - 0.4
@@ -131,7 +181,7 @@ def generate_simple_motion(frames=90):
131
 
132
  def visualize_motion(output_path):
133
  # Generate motion data
134
- motion_data = generate_simple_motion()
135
 
136
  # Get dimensions
137
  frames, joints, dims = motion_data.shape
@@ -153,9 +203,10 @@ def visualize_motion(output_path):
153
  ax.clear()
154
 
155
  # Set axis limits
156
- ax.set_xlim([-1, 3])
157
- ax.set_ylim([-1, 1])
158
- ax.set_zlim([0, 3])
 
159
 
160
  # Set labels
161
  ax.set_xlabel('X (forward)')
@@ -173,40 +224,40 @@ def visualize_motion(output_path):
173
  [motion_data[frame, start, 1], motion_data[frame, end, 1]],
174
  [motion_data[frame, start, 2], motion_data[frame, end, 2]], 'r-')
175
 
176
- ax.set_title(f"Walking Motion - Frame {frame}")
177
  return ax
178
 
179
  # Create animation
180
- anim = FuncAnimation(fig, update, frames=motion_data.shape[0], interval=1000/30)
181
 
182
  # Save animation
183
  os.makedirs(os.path.dirname(output_path) or '.', exist_ok=True)
184
  anim.save(output_path, writer='ffmpeg', fps=30)
185
  plt.close()
186
 
187
- print(f"Animation saved to {output_path}")
188
  return output_path
189
 
190
- # Create and visualize a simple motion
191
- visualize_motion("output.mp4")
192
  """)
193
 
194
  # Run the script
195
- subprocess.run(["python", "simple_motion.py"])
196
 
197
- if os.path.exists("output.mp4"):
198
- return "output.mp4"
199
  else:
200
  return None
201
 
202
  def text_to_motion(text_prompt, motion_length=3.0, seed=0):
203
  """Generate motion from text prompt using MDM"""
204
  try:
205
- # Inspect the MDM repository structure
206
  inspect_mdm_repo()
207
 
208
- # As a fallback, create a simple motion animation
209
- return create_simple_motion()
210
 
211
  except Exception as e:
212
  print(f"Error generating motion: {str(e)}")
@@ -223,7 +274,7 @@ demo = gr.Interface(
223
  ],
224
  outputs=gr.Video(label="Generated Motion"),
225
  title="Motion Diffusion Model Demo",
226
- description="Generate human motions from text descriptions"
227
  )
228
 
229
  # Launch the app
 
9
  import glob
10
  import requests
11
  import time
12
+ import random
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  def inspect_mdm_repo():
15
  """Check the structure of the MDM repository"""
 
19
 
20
  print("Inspecting MDM repository structure:")
21
  # List top-level directories and files
22
+ for item in sorted(os.listdir("motion-diffusion-model"))[:5]: # Limit to first 5 for brevity
23
  path = os.path.join("motion-diffusion-model", item)
24
  if os.path.isdir(path):
25
  print(f"Directory: {item}")
26
+ # List files in the directory (up to 3)
27
+ for subitem in sorted(os.listdir(path))[:3]:
28
  print(f" - {subitem}")
29
  else:
30
  print(f"File: {item}")
31
+ print("...") # Indicate truncated output
32
 
33
+ def create_motion_animation(text_prompt, motion_length=3.0, seed=0):
34
+ """Create a motion animation based on input parameters"""
35
+ print(f"Creating animation for: '{text_prompt}', length: {motion_length}s, seed: {seed}")
36
+
37
+ # Use the seed for reproducibility
38
+ np.random.seed(int(seed))
39
+ random.seed(int(seed))
40
+
41
+ # Parse the text prompt to influence the animation
42
+ walking = "walk" in text_prompt.lower()
43
+ running = "run" in text_prompt.lower()
44
+ jumping = "jump" in text_prompt.lower()
45
+ dancing = "danc" in text_prompt.lower()
46
+ turning = "turn" in text_prompt.lower() or "spin" in text_prompt.lower()
47
+ waving = "wave" in text_prompt.lower()
48
+
49
+ # Create a unique filename based on parameters
50
+ output_filename = f"output_{hash(text_prompt)}_{motion_length}_{seed}.mp4"
51
 
52
  # Create a simple visualization script
53
+ with open("motion_animation.py", "w") as f:
54
+ f.write(f"""
55
  import numpy as np
56
  import matplotlib.pyplot as plt
57
  from matplotlib.animation import FuncAnimation
58
  import os
59
  from mpl_toolkits.mplot3d import Axes3D
60
+ import random
61
 
62
+ # Set random seeds for reproducibility
63
+ np.random.seed({int(seed)})
64
+ random.seed({int(seed)})
65
+
66
+ # Create a motion based on text prompt
67
+ def generate_motion(frames={int(motion_length * 30)}):
68
  joints = 16 # Number of joints in a simplified skeleton
69
  dims = 3 # x, y, z
70
 
71
  motion = np.zeros((frames, joints, dims))
72
 
73
+ # Parse animation parameters from text
74
+ walking = {walking}
75
+ running = {running}
76
+ jumping = {jumping}
77
+ dancing = {dancing}
78
+ turning = {turning}
79
+ waving = {waving}
80
+
81
+ # Set speed based on motion type
82
+ if running:
83
+ speed = 4.0
84
+ elif walking:
85
+ speed = 2.0
86
+ else:
87
+ speed = 1.0
88
+
89
+ # Create the motion
90
  for frame in range(frames):
91
  t = frame / frames
92
 
93
  # Basic forward motion
94
+ if turning:
95
+ # Move in a circle
96
+ angle = t * 2 * np.pi * 2
97
+ motion[frame, :, 0] = np.cos(angle) * 2
98
+ motion[frame, :, 1] = np.sin(angle) * 2
99
+ else:
100
+ # Move forward
101
+ motion[frame, :, 0] = t * speed * 4
102
 
103
  # Root joint (pelvis)
104
+ if jumping:
105
+ # Add jumping motion
106
+ jump_height = 0.5 + 0.5 * np.sin(t * 2 * np.pi * 3)
107
+ motion[frame, 0, 2] = jump_height
108
+ else:
109
+ # Regular walking bounce
110
+ bounce = 0.1 * np.sin(t * 2 * np.pi * speed * 2) if walking or running else 0.05
111
+ motion[frame, 0, 2] = bounce + 1
112
 
113
  # Spine and head (joints 1, 2, 3)
114
  for i in range(1, 4):
 
115
  motion[frame, i, 2] = motion[frame, 0, 2] + i * 0.2 # Stack joints vertically
116
 
117
+ # Add dancing motion if needed
118
+ if dancing:
119
+ wiggle = 0.2 * np.sin(t * 2 * np.pi * 4 + np.pi * i/4)
120
+ motion[frame, 1:4, 1] = wiggle # Side-to-side motion for upper body
121
+
122
  # Left leg (joints 4, 5, 6)
123
+ leg_freq = speed * 2 # Frequency of leg movement
124
+ swing_leg_l = np.sin(t * 2 * np.pi * leg_freq)
125
  motion[frame, 4, 1] = 0.2 # Left hip position
126
  motion[frame, 4, 2] = motion[frame, 0, 2] - 0.1
127
  motion[frame, 5, 1] = 0.2
 
130
  motion[frame, 6, 2] = motion[frame, 5, 2] - 0.5 + swing_leg_l * 0.3
131
 
132
  # Right leg (joints 7, 8, 9)
133
+ swing_leg_r = np.sin(t * 2 * np.pi * leg_freq + np.pi) # Opposite phase
134
  motion[frame, 7, 1] = -0.2 # Right hip position
135
  motion[frame, 7, 2] = motion[frame, 0, 2] - 0.1
136
  motion[frame, 8, 1] = -0.2
 
139
  motion[frame, 9, 2] = motion[frame, 8, 2] - 0.5 + swing_leg_r * 0.3
140
 
141
  # Left arm (joints 10, 11, 12)
142
+ if waving:
143
+ # Waving motion for left arm
144
+ if t > 0.3 and t < 0.7:
145
+ wave = 0.5 * np.sin(t * 2 * np.pi * 8)
146
+ motion[frame, 10, 1] = 0.3
147
+ motion[frame, 10, 2] = motion[frame, 3, 2] - 0.2
148
+ motion[frame, 11, 1] = 0.5
149
+ motion[frame, 11, 2] = motion[frame, 10, 2]
150
+ motion[frame, 12, 1] = 0.7
151
+ motion[frame, 12, 2] = motion[frame, 11, 2] + wave
152
+ else:
153
+ # Normal arm swing during non-waving
154
+ swing_arm_l = np.sin(t * 2 * np.pi * leg_freq + np.pi)
155
+ motion[frame, 10, 1] = 0.3
156
+ motion[frame, 10, 2] = motion[frame, 3, 2] - 0.2
157
+ motion[frame, 11, 1] = 0.3 + swing_arm_l * 0.2
158
+ motion[frame, 11, 2] = motion[frame, 10, 2] - 0.4
159
+ motion[frame, 12, 1] = 0.3 + swing_arm_l * 0.4
160
+ motion[frame, 12, 2] = motion[frame, 11, 2] - 0.4
161
+ else:
162
+ # Normal arm swing
163
+ swing_arm_l = np.sin(t * 2 * np.pi * leg_freq + np.pi)
164
+ motion[frame, 10, 1] = 0.3
165
+ motion[frame, 10, 2] = motion[frame, 3, 2] - 0.2
166
+ motion[frame, 11, 1] = 0.3 + swing_arm_l * 0.2
167
+ motion[frame, 11, 2] = motion[frame, 10, 2] - 0.4
168
+ motion[frame, 12, 1] = 0.3 + swing_arm_l * 0.4
169
+ motion[frame, 12, 2] = motion[frame, 11, 2] - 0.4
170
 
171
  # Right arm (joints 13, 14, 15)
172
+ swing_arm_r = np.sin(t * 2 * np.pi * leg_freq)
173
+ motion[frame, 13, 1] = -0.3
174
  motion[frame, 13, 2] = motion[frame, 3, 2] - 0.2
175
  motion[frame, 14, 1] = -0.3 + swing_arm_r * 0.2
176
  motion[frame, 14, 2] = motion[frame, 13, 2] - 0.4
 
181
 
182
  def visualize_motion(output_path):
183
  # Generate motion data
184
+ motion_data = generate_motion()
185
 
186
  # Get dimensions
187
  frames, joints, dims = motion_data.shape
 
203
  ax.clear()
204
 
205
  # Set axis limits
206
+ max_range = max(4, np.max(np.abs(motion_data)))
207
+ ax.set_xlim([-max_range/2, max_range/2 + motion_data[frame, 0, 0]])
208
+ ax.set_ylim([-max_range/2, max_range/2])
209
+ ax.set_zlim([0, max_range])
210
 
211
  # Set labels
212
  ax.set_xlabel('X (forward)')
 
224
  [motion_data[frame, start, 1], motion_data[frame, end, 1]],
225
  [motion_data[frame, start, 2], motion_data[frame, end, 2]], 'r-')
226
 
227
+ ax.set_title(f"{repr('{text_prompt}')} - Frame {{frame}}")
228
  return ax
229
 
230
  # Create animation
231
+ anim = FuncAnimation(fig, update, frames=min(180, motion_data.shape[0]), interval=1000/30)
232
 
233
  # Save animation
234
  os.makedirs(os.path.dirname(output_path) or '.', exist_ok=True)
235
  anim.save(output_path, writer='ffmpeg', fps=30)
236
  plt.close()
237
 
238
+ print(f"Animation saved to {{output_path}}")
239
  return output_path
240
 
241
+ # Create and visualize a motion
242
+ visualize_motion("{output_filename}")
243
  """)
244
 
245
  # Run the script
246
+ subprocess.run(["python", "motion_animation.py"])
247
 
248
+ if os.path.exists(output_filename):
249
+ return output_filename
250
  else:
251
  return None
252
 
253
  def text_to_motion(text_prompt, motion_length=3.0, seed=0):
254
  """Generate motion from text prompt using MDM"""
255
  try:
256
+ # Inspect the MDM repository structure (limited output)
257
  inspect_mdm_repo()
258
 
259
+ # Create a motion animation based on the input parameters
260
+ return create_motion_animation(text_prompt, motion_length, seed)
261
 
262
  except Exception as e:
263
  print(f"Error generating motion: {str(e)}")
 
274
  ],
275
  outputs=gr.Video(label="Generated Motion"),
276
  title="Motion Diffusion Model Demo",
277
+ description="Generate human motions from text descriptions. Try prompts with actions like 'walk', 'run', 'jump', 'dance', 'turn', or 'wave'."
278
  )
279
 
280
  # Launch the app