Spaces:
No application file
No application file
Update app.py
Browse files
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
|
| 7 |
-
import
|
| 8 |
import os
|
| 9 |
|
| 10 |
-
# ---
|
| 11 |
-
|
|
|
|
| 12 |
CLIP_TOKENIZER = None
|
| 13 |
CLIP_MODEL = None
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
|
|
|
| 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 |
-
|
| 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
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
|
| 43 |
-
#
|
| 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 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
#
|
| 52 |
-
|
| 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 =
|
| 61 |
-
x = np.random.randn(batch, seq, feats).astype(np.float32)
|
| 62 |
|
| 63 |
-
|
|
|
|
| 64 |
|
| 65 |
-
#
|
| 66 |
-
# We
|
| 67 |
-
|
| 68 |
|
| 69 |
-
for i, t_val in enumerate(
|
| 70 |
timesteps = np.array([t_val], dtype=np.int64)
|
| 71 |
|
| 72 |
-
|
| 73 |
"x": x,
|
| 74 |
"timesteps": timesteps,
|
| 75 |
"context": context
|
| 76 |
}
|
| 77 |
|
| 78 |
-
#
|
| 79 |
-
pred =
|
| 80 |
|
| 81 |
-
#
|
| 82 |
-
#
|
| 83 |
-
|
| 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 |
-
#
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
-
#
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
-
# --- UI
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
gr.Markdown("
|
|
|
|
| 100 |
|
| 101 |
with gr.Tabs():
|
| 102 |
-
# --- TAB 1:
|
| 103 |
-
with gr.Tab("1.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
with gr.Row():
|
| 105 |
-
|
| 106 |
-
|
| 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 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 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.
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 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()
|