luizC commited on
Commit
c0bfc28
·
verified ·
1 Parent(s): accc4a0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +138 -94
app.py CHANGED
@@ -3,144 +3,188 @@ import onnxruntime as ort
3
  import numpy as np
4
  import torch
5
  from transformers import CLIPTokenizer, CLIPTextModel
6
- import mdm_manager
7
- import viz_utils
8
  import os
9
 
10
- # --- Globals ---
11
- ORT_SESSION = None
 
12
  CLIP_TOKENIZER = None
13
  CLIP_MODEL = None
14
 
15
- def init_inference_engine():
16
- global ORT_SESSION, CLIP_TOKENIZER, CLIP_MODEL
 
 
 
 
 
 
 
 
 
 
17
 
18
- if not os.path.exists("mdm.onnx"):
19
- return "Model 'mdm.onnx' not found. Please go to the Setup tab."
 
20
 
21
  try:
22
- # Load ONNX Runtime (CPU Optimized)
23
  opts = ort.SessionOptions()
24
  opts.intra_op_num_threads = 4
25
  opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
 
 
26
 
27
- ORT_SESSION = ort.InferenceSession("mdm.onnx", opts)
28
-
29
- # Load CLIP
30
- CLIP_TOKENIZER = CLIPTokenizer.from_pretrained("openai/clip-vit-base-patch32")
31
- CLIP_MODEL = CLIPTextModel.from_pretrained("openai/clip-vit-base-patch32")
32
-
33
- return "Engine Loaded Successfully. Ready to Generate."
34
  except Exception as e:
35
  return f"Error loading engine: {e}"
36
 
37
- def generate_motion(prompt, steps):
38
- if ORT_SESSION is None:
39
- init_inference_engine()
40
- if ORT_SESSION is None:
41
- return None, None, "Error: Engine not loaded."
42
 
43
- # 1. Text Embedding
44
  inputs = CLIP_TOKENIZER([prompt], padding="max_length", max_length=77, return_tensors="pt")
45
  with torch.no_grad():
46
  embeddings = CLIP_MODEL(**inputs).last_hidden_state
47
 
48
- context = embeddings.numpy().astype(np.float32) # [1, 77, 512]
49
- # Adjust shape based on specific MDM version (some take pooled, some sequence)
50
- # We will try passing the full sequence context. If MDM expects [1, 1, 512], slice it.
51
- # Assuming standard MDM: [1, 1, 512] usually implies pooled or first token.
52
- # For robustness, let's use the first token as context vector
53
- context = context[:, 0:1, :]
54
-
55
- # 2. Diffusion Loop (Simulated for Speed)
56
- # Real diffusion requires looping 'steps' times.
57
- # We initialize random noise
58
  batch = 1
59
  seq = 196
60
- feats = 263
61
- x = np.random.randn(batch, seq, feats).astype(np.float32)
62
 
63
- status = "Generating..."
 
64
 
65
- # Simple DDIM-like loop
66
- # We step backwards from Step T to 0
67
- step_history = list(reversed(range(0, 1000, int(1000/steps))))
68
 
69
- for i, t_val in enumerate(step_history):
70
  timesteps = np.array([t_val], dtype=np.int64)
71
 
72
- inputs = {
73
  "x": x,
74
  "timesteps": timesteps,
75
  "context": context
76
  }
77
 
78
- # Run ONNX (The Optimized C++ core)
79
- pred = ORT_SESSION.run(None, inputs)[0]
80
 
81
- # Update x (Simplified Update Rule)
82
- # In a real sampler, this math is specific to the scheduler.
83
- # Here we blend the prediction to denoised result.
84
- # This is a visual approximation for the demo.
85
- alpha = (i + 1) / len(step_history)
86
  x = x * (1 - alpha) + pred * alpha
87
 
88
- # 3. Visualization
89
- fig, joints = viz_utils.visualize_motion(x[0])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
- # 4. Save
92
- file_path = viz_utils.save_bvh(x[0], "output_motion.xyz")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
- return fig, file_path, f"Done. Generated '{prompt}'"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
- # --- UI Definition ---
97
- with gr.Blocks(title="MDM ONNX Studio") as app:
98
- gr.Markdown("# 🏃 Motion Diffusion Model - CPU Optimized Studio")
99
- gr.Markdown("This Space allows you to clone the MDM repo, convert weights to ONNX, and generate 3D motion on CPU.")
 
100
 
101
  with gr.Tabs():
102
- # --- TAB 1: GENERATION ---
103
- with gr.Tab("1. Inference (Generate)"):
 
 
 
 
 
 
104
  with gr.Row():
105
- with gr.Column():
106
- prompt = gr.Textbox(label="Prompt", value="A person walking forward")
107
- steps = gr.Slider(10, 50, value=20, label="Diffusion Steps", step=1)
108
- gen_btn = gr.Button("Generate 3D Motion", variant="primary")
109
- status_lbl = gr.Label(value="Ready")
110
 
111
- with gr.Column():
112
- out_plot = gr.Plot(label="3D Preview")
113
- out_file = gr.File(label="Download Animation Data")
114
-
115
- gen_btn.click(generate_motion, inputs=[prompt, steps], outputs=[out_plot, out_file, status_lbl])
116
-
117
- # --- TAB 2: SETUP ---
118
- with gr.Tab("2. Setup & Conversion (Run First)"):
119
- gr.Markdown("If the model is not loaded, run these steps in order.")
120
 
 
 
 
 
 
121
  with gr.Row():
122
- with gr.Column():
123
- gr.Markdown("### Step A: Clone Repo")
124
- setup_btn = gr.Button("Clone MDM Repository")
125
- setup_log = gr.Textbox(label="Log")
126
- setup_btn.click(mdm_manager.setup_environment, outputs=setup_log)
127
-
128
- with gr.Column():
129
- gr.Markdown("### Step B: Download Weights")
130
- # Default link is HumanML3D sample
131
- url_in = gr.Textbox(label="Weights URL (GDrive or Direct)", value="https://huggingface.co/layers7/mdm_humanml3d/resolve/main/model000475000.pt")
132
- dl_btn = gr.Button("Download .pt Model")
133
- dl_log = gr.Textbox(label="Log")
134
- dl_btn.click(mdm_manager.download_weights, inputs=url_in, outputs=dl_log)
135
-
136
- with gr.Column():
137
- gr.Markdown("### Step C: Compile to ONNX")
138
- convert_btn = gr.Button("Convert to Optimized ONNX")
139
- convert_log = gr.Textbox(label="Log")
140
- convert_btn.click(
141
- fn=lambda: mdm_manager.convert_to_onnx("model.pt"),
142
- outputs=convert_log
143
- )
144
 
145
  if __name__ == "__main__":
146
  app.launch()
 
3
  import numpy as np
4
  import torch
5
  from transformers import CLIPTokenizer, CLIPTextModel
6
+ import mdm_tools
7
+ import plotly.graph_objects as go
8
  import os
9
 
10
+ # --- GLOBAL STATE ---
11
+ CURRENT_SESSION = None
12
+ CURRENT_MODEL_NAME = None
13
  CLIP_TOKENIZER = None
14
  CLIP_MODEL = None
15
 
16
+ # Kinematic Chain for Plotting (HumanML3D style)
17
+ CHAIN = [-1, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 12, 13, 14, 16, 17, 18, 19]
18
+
19
+ def init_clip():
20
+ global CLIP_TOKENIZER, CLIP_MODEL
21
+ if CLIP_TOKENIZER is None:
22
+ print("Loading CLIP...")
23
+ CLIP_TOKENIZER = CLIPTokenizer.from_pretrained("openai/clip-vit-base-patch32")
24
+ CLIP_MODEL = CLIPTextModel.from_pretrained("openai/clip-vit-base-patch32")
25
+
26
+ def load_engine(model_name):
27
+ global CURRENT_SESSION, CURRENT_MODEL_NAME
28
 
29
+ onnx_file = mdm_tools.MODELS_CONFIG[model_name]['onnx_file']
30
+ if not os.path.exists(onnx_file):
31
+ return f"ONNX file {onnx_file} not found. Please convert it in the Setup tab."
32
 
33
  try:
 
34
  opts = ort.SessionOptions()
35
  opts.intra_op_num_threads = 4
36
  opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
37
+ CURRENT_SESSION = ort.InferenceSession(onnx_file, opts)
38
+ CURRENT_MODEL_NAME = model_name
39
 
40
+ init_clip()
41
+ return f"Loaded {model_name} Engine Successfully."
 
 
 
 
 
42
  except Exception as e:
43
  return f"Error loading engine: {e}"
44
 
45
+ def generate_animation(model_name, prompt, steps):
46
+ # 1. Ensure Engine Loaded
47
+ if CURRENT_SESSION is None or CURRENT_MODEL_NAME != model_name:
48
+ status = load_engine(model_name)
49
+ if "Error" in status: return None, None, status
50
 
51
+ # 2. Text Embeddings
52
  inputs = CLIP_TOKENIZER([prompt], padding="max_length", max_length=77, return_tensors="pt")
53
  with torch.no_grad():
54
  embeddings = CLIP_MODEL(**inputs).last_hidden_state
55
 
56
+ # Context handling (Slice to [1, 1, 512] for standard MDM inference)
57
+ context = embeddings.numpy().astype(np.float32)[:, 0:1, :]
58
+
59
+ # 3. Diffusion Loop (Simulated for Speed/Demo)
60
+ cfg = mdm_tools.MODELS_CONFIG[model_name]
 
 
 
 
 
61
  batch = 1
62
  seq = 196
63
+ feats = cfg['feats']
 
64
 
65
+ # Initialize pure noise
66
+ x = np.random.randn(batch, seq, feats).astype(np.float32)
67
 
68
+ # Steps list (Reverse from 1000 to 0)
69
+ # We take 'steps' amount of jumps
70
+ step_vals = list(reversed(range(0, 1000, int(1000/steps))))
71
 
72
+ for i, t_val in enumerate(step_vals):
73
  timesteps = np.array([t_val], dtype=np.int64)
74
 
75
+ ort_inputs = {
76
  "x": x,
77
  "timesteps": timesteps,
78
  "context": context
79
  }
80
 
81
+ # ONNX Inference
82
+ pred = CURRENT_SESSION.run(None, ort_inputs)[0]
83
 
84
+ # Simple Denoising blending (Approximation of DDIM for demo)
85
+ # Real sampling requires complex variance schedule code
86
+ alpha = 1.0 / (len(step_vals) - i)
 
 
87
  x = x * (1 - alpha) + pred * alpha
88
 
89
+ # 4. Recover 3D Positions (Using Repo Logic)
90
+ xyz_data = mdm_tools.recover_motion_to_xyz(x, model_name) # [Seq, Joints, 3]
91
+
92
+ # 5. Visualization
93
+ fig = plot_skeleton(xyz_data)
94
+
95
+ # 6. Save for Blender
96
+ filename = f"mdm_{model_name}_output.bvh"
97
+ mdm_tools.export_to_bvh_blender(xyz_data, filename)
98
+
99
+ return fig, filename, "Generation Complete."
100
+
101
+ def plot_skeleton(xyz_data):
102
+ """Draws stick figure animation."""
103
+ # Downsample
104
+ xyz = xyz_data[::5] # 196 -> ~40 frames
105
 
106
+ # Center
107
+ xyz = xyz - xyz[0:1, 0:1, :]
108
+
109
+ frames = []
110
+ for k in range(len(xyz)):
111
+ x_p, y_p, z_p = [], [], []
112
+ for child, parent in enumerate(CHAIN):
113
+ if parent == -1 or child >= xyz.shape[1] or parent >= xyz.shape[1]: continue
114
+ # Lines
115
+ x_p.extend([xyz[k, parent, 0], xyz[k, child, 0], None])
116
+ # Y-Z Swap for standard plotting tools often helps
117
+ y_p.extend([xyz[k, parent, 2], xyz[k, child, 2], None])
118
+ z_p.extend([xyz[k, parent, 1], xyz[k, child, 1], None])
119
+
120
+ frames.append(go.Frame(data=[go.Scatter3d(
121
+ x=x_p, y=y_p, z=z_p, mode='lines+markers',
122
+ marker=dict(size=3, color='red'), line=dict(color='blue', width=4)
123
+ )]))
124
 
125
+ fig = go.Figure(
126
+ data=frames[0].data,
127
+ layout=go.Layout(
128
+ title="Motion Preview",
129
+ scene=dict(
130
+ xaxis=dict(range=[-2, 2], autorange=False),
131
+ yaxis=dict(range=[-2, 2], autorange=False),
132
+ zaxis=dict(range=[-0, 2], autorange=False),
133
+ aspectmode='cube'
134
+ ),
135
+ updatemenus=[dict(type="buttons", buttons=[dict(label="Play", method="animate", args=[None])])]
136
+ ),
137
+ frames=frames
138
+ )
139
+ return fig
140
 
141
+ # --- GRADIO UI ---
142
+
143
+ with gr.Blocks(title="MDM Ultimate Studio") as app:
144
+ gr.Markdown("# 🕺 Motion Diffusion Model - ONNX Runtime Studio")
145
+ gr.Markdown("Fully autonomous environment: Clone repo, Download Weights, Compile to ONNX, and Generate.")
146
 
147
  with gr.Tabs():
148
+ # --- TAB 1: SETUP ---
149
+ with gr.Tab("1. Setup & Config"):
150
+ gr.Markdown("### Step 1: Initialize Environment")
151
+ setup_btn = gr.Button("Clone Repository & Setup Dependencies")
152
+ setup_log = gr.Textbox(label="Status")
153
+ setup_btn.click(lambda: "Done" if mdm_tools.setup_environment() else "Failed", outputs=setup_log)
154
+
155
+ gr.Markdown("### Step 2: Manage Models")
156
  with gr.Row():
157
+ model_sel = gr.Dropdown(choices=["HumanML3D", "KIT"], value="HumanML3D", label="Select Model")
158
+ dl_source = gr.Checkbox(label="Use GDrive (Uncheck for Mirror)", value=False)
 
 
 
159
 
160
+ with gr.Row():
161
+ dl_btn = gr.Button("Download Weights")
162
+ conv_btn = gr.Button("Convert to ONNX")
163
+
164
+ m_log = gr.Textbox(label="Model Log")
 
 
 
 
165
 
166
+ dl_btn.click(mdm_tools.download_model, inputs=[model_sel, dl_source], outputs=m_log)
167
+ conv_btn.click(mdm_tools.export_onnx, inputs=[model_sel], outputs=m_log)
168
+
169
+ # --- TAB 2: INFERENCE ---
170
+ with gr.Tab("2. Generate Animation"):
171
  with gr.Row():
172
+ with gr.Column(scale=1):
173
+ i_model = gr.Dropdown(choices=["HumanML3D", "KIT"], value="HumanML3D", label="Active Model")
174
+ i_prompt = gr.Textbox(label="Prompt", value="A person dancing happily")
175
+ i_steps = gr.Slider(10, 50, value=20, label="Steps", step=1)
176
+ i_btn = gr.Button("Generate", variant="primary")
177
+ i_status = gr.Label(value="Idle")
178
+
179
+ with gr.Column(scale=2):
180
+ out_viz = gr.Plot(label="3D Skeleton")
181
+ out_file = gr.File(label="Download for Blender (.bvh)")
182
+
183
+ i_btn.click(
184
+ generate_animation,
185
+ inputs=[i_model, i_prompt, i_steps],
186
+ outputs=[out_viz, out_file, i_status]
187
+ )
 
 
 
 
 
 
188
 
189
  if __name__ == "__main__":
190
  app.launch()