Update app.py
Browse files
app.py
CHANGED
|
@@ -1,251 +1,407 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import sys
|
| 3 |
-
import tempfile
|
| 4 |
-
import shutil
|
| 5 |
import gradio as gr
|
|
|
|
| 6 |
import torch
|
| 7 |
import numpy as np
|
| 8 |
import open3d as o3d
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
# Add RigNet modules to path
|
| 12 |
-
sys.path.insert(0, 'Rignet')
|
| 13 |
-
|
| 14 |
-
from models.GCN import JOINTNET_MASKNET_MEANSHIFT as JOINTNET
|
| 15 |
-
from models.ROOT_GCN import ROOTNET
|
| 16 |
-
from models.PairCls_GCN import PairCls as BONENET
|
| 17 |
-
from models.SKINNING import SKINNET
|
| 18 |
-
from utils.rig_parser import Info
|
| 19 |
-
from gen_dataset import get_tpl_edges, get_geo_edges
|
| 20 |
from torch_geometric.data import Data
|
| 21 |
from torch_geometric.utils import add_self_loops
|
| 22 |
-
|
| 23 |
-
from geometric_proc.common_ops import calc_surface_geodesic, get_bones
|
| 24 |
-
from utils.io_utils import assemble_skel_skin
|
| 25 |
-
from run_skinning import post_filter
|
| 26 |
-
|
| 27 |
-
# Import helper functions from quick_start
|
| 28 |
-
from quick_start import (
|
| 29 |
-
normalize_obj, predict_joints, predict_skeleton,
|
| 30 |
-
predict_skinning, calc_geodesic_matrix
|
| 31 |
-
)
|
| 32 |
-
|
| 33 |
-
# Initialize device
|
| 34 |
-
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 35 |
-
|
| 36 |
-
# Load models globally
|
| 37 |
-
print("Loading neural networks...")
|
| 38 |
-
jointNet = JOINTNET()
|
| 39 |
-
jointNet.to(device)
|
| 40 |
-
jointNet.eval()
|
| 41 |
-
jointNet.load_state_dict(
|
| 42 |
-
torch.load('Rignet/checkpoints/gcn_meanshift/model_best.pth.tar',
|
| 43 |
-
map_location=device)['state_dict']
|
| 44 |
-
)
|
| 45 |
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
rootNet.eval()
|
| 49 |
-
rootNet.load_state_dict(
|
| 50 |
-
torch.load('Rignet/checkpoints/rootnet/model_best.pth.tar',
|
| 51 |
-
map_location=device)['state_dict']
|
| 52 |
-
)
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
)
|
| 69 |
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
def create_single_data(mesh_filename):
|
| 74 |
-
"""Create input data
|
| 75 |
mesh = o3d.io.read_triangle_mesh(mesh_filename)
|
| 76 |
mesh.compute_vertex_normals()
|
| 77 |
mesh_v = np.asarray(mesh.vertices)
|
| 78 |
mesh_vn = np.asarray(mesh.vertex_normals)
|
| 79 |
mesh_f = np.asarray(mesh.triangles)
|
| 80 |
|
| 81 |
-
|
| 82 |
-
mesh_v, translation, scale = normalize_obj(mesh_v)
|
| 83 |
mesh_normalized = o3d.geometry.TriangleMesh(
|
| 84 |
vertices=o3d.utility.Vector3dVector(mesh_v),
|
| 85 |
triangles=o3d.utility.Vector3iVector(mesh_f)
|
| 86 |
)
|
| 87 |
|
| 88 |
-
normalized_path = mesh_filename.replace(
|
| 89 |
o3d.io.write_triangle_mesh(normalized_path, mesh_normalized)
|
| 90 |
|
| 91 |
-
#
|
| 92 |
v = np.concatenate((mesh_v, mesh_vn), axis=1)
|
| 93 |
v = torch.from_numpy(v).float()
|
| 94 |
|
| 95 |
-
#
|
| 96 |
tpl_e = get_tpl_edges(mesh_v, mesh_f).T
|
| 97 |
tpl_e = torch.from_numpy(tpl_e).long()
|
| 98 |
tpl_e, _ = add_self_loops(tpl_e, num_nodes=v.size(0))
|
| 99 |
|
| 100 |
-
#
|
| 101 |
surface_geodesic = calc_surface_geodesic(mesh)
|
| 102 |
|
| 103 |
-
#
|
| 104 |
geo_e = get_geo_edges(surface_geodesic, mesh_v).T
|
| 105 |
geo_e = torch.from_numpy(geo_e).long()
|
| 106 |
geo_e, _ = add_self_loops(geo_e, num_nodes=v.size(0))
|
| 107 |
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
|
|
|
|
|
|
| 112 |
|
| 113 |
-
with open(
|
| 114 |
vox = binvox_rw.read_as_3d_array(fvox)
|
| 115 |
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
tpl_edge_index=tpl_e, geo_edge_index=geo_e, batch=batch)
|
| 119 |
|
| 120 |
-
return data, vox, surface_geodesic,
|
| 121 |
-
|
| 122 |
|
| 123 |
-
def
|
| 124 |
-
"""
|
| 125 |
-
Main processing function for RigNet inference
|
| 126 |
-
|
| 127 |
-
Args:
|
| 128 |
-
input_file: Uploaded OBJ file
|
| 129 |
-
bandwidth: Bandwidth parameter for joint clustering
|
| 130 |
-
threshold: Threshold for joint density filtering
|
| 131 |
-
|
| 132 |
-
Returns:
|
| 133 |
-
Path to generated rig txt file and status message
|
| 134 |
-
"""
|
| 135 |
try:
|
| 136 |
-
#
|
| 137 |
-
temp_dir =
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
-
# Copy
|
| 140 |
-
|
| 141 |
-
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
-
#
|
| 144 |
-
mesh_ori = o3d.io.read_triangle_mesh(
|
| 145 |
-
if len(np.asarray(mesh_ori.vertices)) > 5000:
|
| 146 |
mesh_remesh = mesh_ori.simplify_quadric_decimation(4000)
|
| 147 |
-
|
|
|
|
| 148 |
|
| 149 |
# Create data
|
| 150 |
-
print("Creating
|
| 151 |
-
data, vox, surface_geodesic,
|
| 152 |
data.to(device)
|
| 153 |
|
| 154 |
# Predict joints
|
| 155 |
print("Predicting joints...")
|
| 156 |
-
|
| 157 |
-
data = predict_joints(
|
| 158 |
-
data, vox, jointNet, threshold,
|
| 159 |
-
bandwidth=bandwidth,
|
| 160 |
-
mesh_filename=input_path.replace('.obj', '_normalized.obj')
|
| 161 |
-
)
|
| 162 |
data.to(device)
|
| 163 |
|
| 164 |
# Predict skeleton
|
| 165 |
-
print("Predicting skeleton
|
| 166 |
-
pred_skeleton = predict_skeleton(
|
| 167 |
-
data, vox, rootNet, boneNet,
|
| 168 |
-
mesh_filename=input_path.replace('.obj', '_normalized.obj')
|
| 169 |
-
)
|
| 170 |
|
| 171 |
# Predict skinning
|
| 172 |
-
print("Predicting skinning
|
| 173 |
-
pred_rig = predict_skinning(
|
| 174 |
-
|
| 175 |
-
input_path.replace('.obj', '_normalized.obj'),
|
| 176 |
-
subsampling=True
|
| 177 |
-
)
|
| 178 |
|
| 179 |
-
#
|
| 180 |
-
pred_rig.normalize(
|
| 181 |
|
| 182 |
# Save rig
|
| 183 |
-
|
| 184 |
-
pred_rig.save(
|
| 185 |
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
rig_content = f.read()
|
| 189 |
-
|
| 190 |
-
return output_path, f"✅ Rigging completed successfully!\n\nGenerated {len(pred_skeleton.joint_pos)} joints", rig_content
|
| 191 |
|
| 192 |
except Exception as e:
|
| 193 |
-
return
|
| 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 |
-
# Launch the app
|
| 250 |
if __name__ == "__main__":
|
| 251 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
import torch
|
| 4 |
import numpy as np
|
| 5 |
import open3d as o3d
|
| 6 |
+
import trimesh
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
from torch_geometric.data import Data
|
| 8 |
from torch_geometric.utils import add_self_loops
|
| 9 |
+
import sys
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
+
# Add rignet to path
|
| 12 |
+
sys.path.append('./rignet')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
from rignet.utils import binvox_rw
|
| 15 |
+
from rignet.utils.rig_parser import Info
|
| 16 |
+
from rignet.utils.io_utils import assemble_skel_skin
|
| 17 |
+
from rignet.utils.cluster_utils import meanshift_cluster, nms_meanshift
|
| 18 |
+
from rignet.utils.mst_utils import inside_check, flip, increase_cost_for_outside_bone, primMST_symmetry, loadSkel_recur
|
| 19 |
+
from rignet.geometric_proc.common_ops import get_bones, calc_surface_geodesic
|
| 20 |
+
from rignet.geometric_proc.compute_volumetric_geodesic import calc_pts2bone_visible_mat, pts2line
|
| 21 |
+
from rignet.gen_dataset import get_tpl_edges, get_geo_edges
|
| 22 |
+
from rignet.mst_generate import sample_on_bone, getInitId
|
| 23 |
+
from rignet.run_skinning import post_filter
|
| 24 |
+
from rignet.models.GCN import JOINTNET_MASKNET_MEANSHIFT as JOINTNET
|
| 25 |
+
from rignet.models.ROOT_GCN import ROOTNET
|
| 26 |
+
from rignet.models.PairCls_GCN import PairCls as BONENET
|
| 27 |
+
from rignet.models.SKINNING import SKINNET
|
| 28 |
|
| 29 |
+
# Global models
|
| 30 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 31 |
+
joint_net = None
|
| 32 |
+
root_net = None
|
| 33 |
+
bone_net = None
|
| 34 |
+
skin_net = None
|
|
|
|
| 35 |
|
| 36 |
+
def load_models():
|
| 37 |
+
"""Load all RigNet models"""
|
| 38 |
+
global joint_net, root_net, bone_net, skin_net
|
| 39 |
+
|
| 40 |
+
print("Loading models...")
|
| 41 |
+
|
| 42 |
+
# Joint prediction network
|
| 43 |
+
joint_net = JOINTNET()
|
| 44 |
+
joint_net.to(device)
|
| 45 |
+
joint_net.eval()
|
| 46 |
+
joint_checkpoint = torch.load('rignet/checkpoints/gcn_meanshift/model_best.pth.tar', map_location=device)
|
| 47 |
+
joint_net.load_state_dict(joint_checkpoint['state_dict'])
|
| 48 |
+
|
| 49 |
+
# Root prediction network
|
| 50 |
+
root_net = ROOTNET()
|
| 51 |
+
root_net.to(device)
|
| 52 |
+
root_net.eval()
|
| 53 |
+
root_checkpoint = torch.load('rignet/checkpoints/rootnet/model_best.pth.tar', map_location=device)
|
| 54 |
+
root_net.load_state_dict(root_checkpoint['state_dict'])
|
| 55 |
+
|
| 56 |
+
# Bone prediction network
|
| 57 |
+
bone_net = BONENET()
|
| 58 |
+
bone_net.to(device)
|
| 59 |
+
bone_net.eval()
|
| 60 |
+
bone_checkpoint = torch.load('rignet/checkpoints/bonenet/model_best.pth.tar', map_location=device)
|
| 61 |
+
bone_net.load_state_dict(bone_checkpoint['state_dict'])
|
| 62 |
+
|
| 63 |
+
# Skinning prediction network
|
| 64 |
+
skin_net = SKINNET(nearest_bone=5, use_Dg=True, use_Lf=True)
|
| 65 |
+
skin_checkpoint = torch.load('rignet/checkpoints/skinnet/model_best.pth.tar', map_location=device)
|
| 66 |
+
skin_net.load_state_dict(skin_checkpoint['state_dict'])
|
| 67 |
+
skin_net.to(device)
|
| 68 |
+
skin_net.eval()
|
| 69 |
+
|
| 70 |
+
print("All models loaded successfully!")
|
| 71 |
|
| 72 |
+
def normalize_obj(mesh_v):
|
| 73 |
+
"""Normalize mesh vertices"""
|
| 74 |
+
dims = [max(mesh_v[:, 0]) - min(mesh_v[:, 0]),
|
| 75 |
+
max(mesh_v[:, 1]) - min(mesh_v[:, 1]),
|
| 76 |
+
max(mesh_v[:, 2]) - min(mesh_v[:, 2])]
|
| 77 |
+
scale = 1.0 / max(dims)
|
| 78 |
+
pivot = np.array([(min(mesh_v[:, 0]) + max(mesh_v[:, 0])) / 2, min(mesh_v[:, 1]),
|
| 79 |
+
(min(mesh_v[:, 2]) + max(mesh_v[:, 2])) / 2])
|
| 80 |
+
mesh_v[:, 0] -= pivot[0]
|
| 81 |
+
mesh_v[:, 1] -= pivot[1]
|
| 82 |
+
mesh_v[:, 2] -= pivot[2]
|
| 83 |
+
mesh_v *= scale
|
| 84 |
+
return mesh_v, pivot, scale
|
| 85 |
|
| 86 |
def create_single_data(mesh_filename):
|
| 87 |
+
"""Create input data from mesh file"""
|
| 88 |
mesh = o3d.io.read_triangle_mesh(mesh_filename)
|
| 89 |
mesh.compute_vertex_normals()
|
| 90 |
mesh_v = np.asarray(mesh.vertices)
|
| 91 |
mesh_vn = np.asarray(mesh.vertex_normals)
|
| 92 |
mesh_f = np.asarray(mesh.triangles)
|
| 93 |
|
| 94 |
+
mesh_v, translation_normalize, scale_normalize = normalize_obj(mesh_v)
|
|
|
|
| 95 |
mesh_normalized = o3d.geometry.TriangleMesh(
|
| 96 |
vertices=o3d.utility.Vector3dVector(mesh_v),
|
| 97 |
triangles=o3d.utility.Vector3iVector(mesh_f)
|
| 98 |
)
|
| 99 |
|
| 100 |
+
normalized_path = mesh_filename.replace(".obj", "_normalized.obj")
|
| 101 |
o3d.io.write_triangle_mesh(normalized_path, mesh_normalized)
|
| 102 |
|
| 103 |
+
# vertices
|
| 104 |
v = np.concatenate((mesh_v, mesh_vn), axis=1)
|
| 105 |
v = torch.from_numpy(v).float()
|
| 106 |
|
| 107 |
+
# topology edges
|
| 108 |
tpl_e = get_tpl_edges(mesh_v, mesh_f).T
|
| 109 |
tpl_e = torch.from_numpy(tpl_e).long()
|
| 110 |
tpl_e, _ = add_self_loops(tpl_e, num_nodes=v.size(0))
|
| 111 |
|
| 112 |
+
# surface geodesic
|
| 113 |
surface_geodesic = calc_surface_geodesic(mesh)
|
| 114 |
|
| 115 |
+
# geodesic edges
|
| 116 |
geo_e = get_geo_edges(surface_geodesic, mesh_v).T
|
| 117 |
geo_e = torch.from_numpy(geo_e).long()
|
| 118 |
geo_e, _ = add_self_loops(geo_e, num_nodes=v.size(0))
|
| 119 |
|
| 120 |
+
batch = torch.zeros(len(v), dtype=torch.long)
|
| 121 |
+
|
| 122 |
+
# voxelization
|
| 123 |
+
binvox_path = mesh_filename.replace('.obj', '_normalized.binvox')
|
| 124 |
+
if not os.path.exists(binvox_path):
|
| 125 |
+
os.system(f"./binvox -d 88 -pb {normalized_path}")
|
| 126 |
|
| 127 |
+
with open(binvox_path, 'rb') as fvox:
|
| 128 |
vox = binvox_rw.read_as_3d_array(fvox)
|
| 129 |
|
| 130 |
+
data = Data(x=v[:, 3:6], pos=v[:, 0:3], tpl_edge_index=tpl_e,
|
| 131 |
+
geo_edge_index=geo_e, batch=batch)
|
|
|
|
| 132 |
|
| 133 |
+
return data, vox, surface_geodesic, translation_normalize, scale_normalize
|
|
|
|
| 134 |
|
| 135 |
+
def predict_rig(input_obj_file):
|
| 136 |
+
"""Main inference function"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
try:
|
| 138 |
+
# Save uploaded file
|
| 139 |
+
temp_dir = "/tmp/rignet_temp"
|
| 140 |
+
os.makedirs(temp_dir, exist_ok=True)
|
| 141 |
+
|
| 142 |
+
mesh_filename = os.path.join(temp_dir, "input_mesh.obj")
|
| 143 |
|
| 144 |
+
# Copy uploaded file
|
| 145 |
+
if isinstance(input_obj_file, str):
|
| 146 |
+
os.system(f"cp {input_obj_file} {mesh_filename}")
|
| 147 |
+
else:
|
| 148 |
+
with open(mesh_filename, 'wb') as f:
|
| 149 |
+
f.write(input_obj_file.read())
|
| 150 |
|
| 151 |
+
# Remesh if necessary
|
| 152 |
+
mesh_ori = o3d.io.read_triangle_mesh(mesh_filename)
|
| 153 |
+
if len(np.asarray(mesh_ori.vertices)) > 5000 or len(np.asarray(mesh_ori.vertices)) < 1000:
|
| 154 |
mesh_remesh = mesh_ori.simplify_quadric_decimation(4000)
|
| 155 |
+
mesh_filename = os.path.join(temp_dir, "input_mesh_remesh.obj")
|
| 156 |
+
o3d.io.write_triangle_mesh(mesh_filename, mesh_remesh)
|
| 157 |
|
| 158 |
# Create data
|
| 159 |
+
print("Creating input data...")
|
| 160 |
+
data, vox, surface_geodesic, translation_normalize, scale_normalize = create_single_data(mesh_filename)
|
| 161 |
data.to(device)
|
| 162 |
|
| 163 |
# Predict joints
|
| 164 |
print("Predicting joints...")
|
| 165 |
+
data = predict_joints(data, vox, joint_net, threshold=1e-5, bandwidth=0.0429)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
data.to(device)
|
| 167 |
|
| 168 |
# Predict skeleton
|
| 169 |
+
print("Predicting skeleton...")
|
| 170 |
+
pred_skeleton = predict_skeleton(data, vox, root_net, bone_net)
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
# Predict skinning
|
| 173 |
+
print("Predicting skinning...")
|
| 174 |
+
pred_rig = predict_skinning(data, pred_skeleton, skin_net, surface_geodesic,
|
| 175 |
+
mesh_filename.replace(".obj", "_normalized.obj"))
|
|
|
|
|
|
|
|
|
|
| 176 |
|
| 177 |
+
# Denormalize
|
| 178 |
+
pred_rig.normalize(scale_normalize, -translation_normalize)
|
| 179 |
|
| 180 |
# Save rig
|
| 181 |
+
output_rig_path = os.path.join(temp_dir, "output_rig.txt")
|
| 182 |
+
pred_rig.save(output_rig_path)
|
| 183 |
|
| 184 |
+
print("Rig generation completed!")
|
| 185 |
+
return output_rig_path
|
|
|
|
|
|
|
|
|
|
| 186 |
|
| 187 |
except Exception as e:
|
| 188 |
+
return f"Error: {str(e)}"
|
| 189 |
|
| 190 |
+
def predict_joints(input_data, vox, joint_pred_net, threshold, bandwidth=None):
|
| 191 |
+
"""Predict joint locations"""
|
| 192 |
+
import itertools as it
|
| 193 |
+
|
| 194 |
+
with torch.no_grad():
|
| 195 |
+
data_displacement, _, attn_pred, bandwidth_pred = joint_pred_net(input_data)
|
| 196 |
+
|
| 197 |
+
y_pred = data_displacement + input_data.pos
|
| 198 |
+
y_pred_np = y_pred.data.cpu().numpy()
|
| 199 |
+
attn_pred_np = attn_pred.data.cpu().numpy()
|
| 200 |
+
|
| 201 |
+
y_pred_np, index_inside = inside_check(y_pred_np, vox)
|
| 202 |
+
attn_pred_np = attn_pred_np[index_inside, :]
|
| 203 |
+
y_pred_np = y_pred_np[attn_pred_np.squeeze() > 1e-3]
|
| 204 |
+
attn_pred_np = attn_pred_np[attn_pred_np.squeeze() > 1e-3]
|
| 205 |
+
|
| 206 |
+
# symmetrize
|
| 207 |
+
y_pred_np_reflect = y_pred_np * np.array([[-1, 1, 1]])
|
| 208 |
+
y_pred_np = np.concatenate((y_pred_np, y_pred_np_reflect), axis=0)
|
| 209 |
+
attn_pred_np = np.tile(attn_pred_np, (2, 1))
|
| 210 |
+
|
| 211 |
+
if bandwidth is None:
|
| 212 |
+
bandwidth = bandwidth_pred.item()
|
| 213 |
+
|
| 214 |
+
y_pred_np = meanshift_cluster(y_pred_np, bandwidth, attn_pred_np, max_iter=40)
|
| 215 |
+
|
| 216 |
+
Y_dist = np.sum(((y_pred_np[np.newaxis, ...] - y_pred_np[:, np.newaxis, :]) ** 2), axis=2)
|
| 217 |
+
density = np.maximum(bandwidth ** 2 - Y_dist, np.zeros(Y_dist.shape))
|
| 218 |
+
density = np.sum(density, axis=0)
|
| 219 |
+
density_sum = np.sum(density)
|
| 220 |
+
|
| 221 |
+
y_pred_np = y_pred_np[density / density_sum > threshold]
|
| 222 |
+
attn_pred_np = attn_pred_np[density / density_sum > threshold][:, 0]
|
| 223 |
+
density = density[density / density_sum > threshold]
|
| 224 |
+
|
| 225 |
+
pred_joints = nms_meanshift(y_pred_np, density, bandwidth)
|
| 226 |
+
pred_joints, _ = flip(pred_joints)
|
| 227 |
+
|
| 228 |
+
# prepare bone pairs
|
| 229 |
+
pairs = list(it.combinations(range(pred_joints.shape[0]), 2))
|
| 230 |
+
pair_attr = []
|
| 231 |
+
for pr in pairs:
|
| 232 |
+
dist = np.linalg.norm(pred_joints[pr[0]] - pred_joints[pr[1]])
|
| 233 |
+
bone_samples = sample_on_bone(pred_joints[pr[0]], pred_joints[pr[1]])
|
| 234 |
+
bone_samples_inside, _ = inside_check(bone_samples, vox)
|
| 235 |
+
outside_proportion = len(bone_samples_inside) / (len(bone_samples) + 1e-10)
|
| 236 |
+
attr = np.array([dist, outside_proportion, 1])
|
| 237 |
+
pair_attr.append(attr)
|
| 238 |
+
|
| 239 |
+
pairs = np.array(pairs)
|
| 240 |
+
pair_attr = np.array(pair_attr)
|
| 241 |
+
pairs = torch.from_numpy(pairs).float()
|
| 242 |
+
pair_attr = torch.from_numpy(pair_attr).float()
|
| 243 |
+
pred_joints = torch.from_numpy(pred_joints).float()
|
| 244 |
+
|
| 245 |
+
input_data.joints = pred_joints
|
| 246 |
+
input_data.pairs = pairs
|
| 247 |
+
input_data.pair_attr = pair_attr
|
| 248 |
+
input_data.joints_batch = torch.zeros(len(pred_joints), dtype=torch.long)
|
| 249 |
+
input_data.pairs_batch = torch.zeros(len(pairs), dtype=torch.long)
|
| 250 |
+
|
| 251 |
+
return input_data
|
| 252 |
|
| 253 |
+
def predict_skeleton(input_data, vox, root_pred_net, bone_pred_net):
|
| 254 |
+
"""Predict skeleton connectivity"""
|
| 255 |
+
from rignet.utils.tree_utils import TreeNode
|
| 256 |
+
|
| 257 |
+
root_id = getInitId(input_data, root_pred_net)
|
| 258 |
+
pred_joints = input_data.joints.data.cpu().numpy()
|
| 259 |
+
|
| 260 |
+
with torch.no_grad():
|
| 261 |
+
connect_prob, _ = bone_pred_net(input_data, permute_joints=False)
|
| 262 |
+
connect_prob = torch.sigmoid(connect_prob)
|
| 263 |
+
|
| 264 |
+
pair_idx = input_data.pairs.long().data.cpu().numpy()
|
| 265 |
+
prob_matrix = np.zeros((len(input_data.joints), len(input_data.joints)))
|
| 266 |
+
prob_matrix[pair_idx[:, 0], pair_idx[:, 1]] = connect_prob.data.cpu().numpy().squeeze()
|
| 267 |
+
prob_matrix = prob_matrix + prob_matrix.transpose()
|
| 268 |
+
|
| 269 |
+
cost_matrix = -np.log(prob_matrix + 1e-10)
|
| 270 |
+
cost_matrix = increase_cost_for_outside_bone(cost_matrix, pred_joints, vox)
|
| 271 |
+
|
| 272 |
+
pred_skel = Info()
|
| 273 |
+
parent, key, root_id = primMST_symmetry(cost_matrix, root_id, pred_joints)
|
| 274 |
+
|
| 275 |
+
for i in range(len(parent)):
|
| 276 |
+
if parent[i] == -1:
|
| 277 |
+
pred_skel.root = TreeNode('root', tuple(pred_joints[i]))
|
| 278 |
+
break
|
| 279 |
+
|
| 280 |
+
loadSkel_recur(pred_skel.root, i, None, pred_joints, parent)
|
| 281 |
+
pred_skel.joint_pos = pred_skel.get_joint_dict()
|
| 282 |
+
|
| 283 |
+
return pred_skel
|
| 284 |
+
|
| 285 |
+
def predict_skinning(input_data, pred_skel, skin_pred_net, surface_geodesic, mesh_filename):
|
| 286 |
+
"""Predict skinning weights"""
|
| 287 |
+
num_nearest_bone = 5
|
| 288 |
+
bones, bone_names, bone_isleaf = get_bones(pred_skel)
|
| 289 |
+
mesh_v = input_data.pos.data.cpu().numpy()
|
| 290 |
+
|
| 291 |
+
# Calculate geodesic distance
|
| 292 |
+
geo_dist = calc_geodesic_matrix(bones, mesh_v, surface_geodesic, mesh_filename)
|
| 293 |
+
|
| 294 |
+
input_samples = []
|
| 295 |
+
loss_mask = []
|
| 296 |
+
skin_nn = []
|
| 297 |
+
|
| 298 |
+
for v_id in range(len(mesh_v)):
|
| 299 |
+
geo_dist_v = geo_dist[v_id]
|
| 300 |
+
bone_id_near_to_far = np.argsort(geo_dist_v)
|
| 301 |
+
this_sample = []
|
| 302 |
+
this_nn = []
|
| 303 |
+
this_mask = []
|
| 304 |
|
| 305 |
+
for i in range(num_nearest_bone):
|
| 306 |
+
if i >= len(bones):
|
| 307 |
+
this_sample += bones[bone_id_near_to_far[0]].tolist()
|
| 308 |
+
this_sample.append(1.0 / (geo_dist_v[bone_id_near_to_far[0]] + 1e-10))
|
| 309 |
+
this_sample.append(bone_isleaf[bone_id_near_to_far[0]])
|
| 310 |
+
this_nn.append(0)
|
| 311 |
+
this_mask.append(0)
|
| 312 |
+
else:
|
| 313 |
+
skel_bone_id = bone_id_near_to_far[i]
|
| 314 |
+
this_sample += bones[skel_bone_id].tolist()
|
| 315 |
+
this_sample.append(1.0 / (geo_dist_v[skel_bone_id] + 1e-10))
|
| 316 |
+
this_sample.append(bone_isleaf[skel_bone_id])
|
| 317 |
+
this_nn.append(skel_bone_id)
|
| 318 |
+
this_mask.append(1)
|
| 319 |
+
|
| 320 |
+
input_samples.append(np.array(this_sample)[np.newaxis, :])
|
| 321 |
+
skin_nn.append(np.array(this_nn)[np.newaxis, :])
|
| 322 |
+
loss_mask.append(np.array(this_mask)[np.newaxis, :])
|
| 323 |
+
|
| 324 |
+
skin_input = np.concatenate(input_samples, axis=0)
|
| 325 |
+
loss_mask = np.concatenate(loss_mask, axis=0)
|
| 326 |
+
skin_nn = np.concatenate(skin_nn, axis=0)
|
| 327 |
+
skin_input = torch.from_numpy(skin_input).float()
|
| 328 |
+
|
| 329 |
+
input_data.skin_input = skin_input
|
| 330 |
+
input_data.to(device)
|
| 331 |
+
|
| 332 |
+
with torch.no_grad():
|
| 333 |
+
skin_pred = skin_pred_net(input_data)
|
| 334 |
+
skin_pred = torch.softmax(skin_pred, dim=1)
|
| 335 |
+
|
| 336 |
+
skin_pred = skin_pred.data.cpu().numpy()
|
| 337 |
+
skin_pred = skin_pred * loss_mask
|
| 338 |
+
skin_nn = skin_nn[:, 0:num_nearest_bone]
|
| 339 |
+
|
| 340 |
+
skin_pred_full = np.zeros((len(skin_pred), len(bone_names)))
|
| 341 |
+
for v in range(len(skin_pred)):
|
| 342 |
+
for nn_id in range(len(skin_nn[v, :])):
|
| 343 |
+
skin_pred_full[v, skin_nn[v, nn_id]] = skin_pred[v, nn_id]
|
| 344 |
+
|
| 345 |
+
# Post-processing
|
| 346 |
+
tpl_e = input_data.tpl_edge_index.data.cpu().numpy()
|
| 347 |
+
skin_pred_full = post_filter(skin_pred_full, tpl_e, num_ring=1)
|
| 348 |
+
skin_pred_full[skin_pred_full < np.max(skin_pred_full, axis=1, keepdims=True) * 0.35] = 0.0
|
| 349 |
+
skin_pred_full = skin_pred_full / (skin_pred_full.sum(axis=1, keepdims=True) + 1e-10)
|
| 350 |
+
|
| 351 |
+
skel_res = assemble_skel_skin(pred_skel, skin_pred_full)
|
| 352 |
+
return skel_res
|
| 353 |
+
|
| 354 |
+
def calc_geodesic_matrix(bones, mesh_v, surface_geodesic, mesh_filename):
|
| 355 |
+
"""Calculate volumetric geodesic distance"""
|
| 356 |
+
mesh_trimesh = trimesh.load(mesh_filename)
|
| 357 |
+
subsamples = mesh_v
|
| 358 |
+
|
| 359 |
+
origins, ends, pts_bone_dist = pts2line(subsamples, bones)
|
| 360 |
+
pts_bone_visibility = calc_pts2bone_visible_mat(mesh_trimesh, origins, ends)
|
| 361 |
+
pts_bone_visibility = pts_bone_visibility.reshape(len(bones), len(subsamples)).transpose()
|
| 362 |
+
pts_bone_dist = pts_bone_dist.reshape(len(bones), len(subsamples)).transpose()
|
| 363 |
+
|
| 364 |
+
for b in range(pts_bone_visibility.shape[1]):
|
| 365 |
+
visible_pts = np.argwhere(pts_bone_visibility[:, b] == 1).squeeze(1)
|
| 366 |
+
if len(visible_pts) == 0:
|
| 367 |
+
continue
|
| 368 |
+
threshold_b = np.percentile(pts_bone_dist[visible_pts, b], 15)
|
| 369 |
+
pts_bone_visibility[pts_bone_dist[:, b] > 1.3 * threshold_b, b] = False
|
| 370 |
+
|
| 371 |
+
visible_matrix = np.zeros(pts_bone_visibility.shape)
|
| 372 |
+
visible_matrix[np.where(pts_bone_visibility == 1)] = pts_bone_dist[np.where(pts_bone_visibility == 1)]
|
| 373 |
+
|
| 374 |
+
for c in range(visible_matrix.shape[1]):
|
| 375 |
+
unvisible_pts = np.argwhere(pts_bone_visibility[:, c] == 0).squeeze(1)
|
| 376 |
+
visible_pts = np.argwhere(pts_bone_visibility[:, c] == 1).squeeze(1)
|
| 377 |
+
|
| 378 |
+
if len(visible_pts) == 0:
|
| 379 |
+
visible_matrix[:, c] = pts_bone_dist[:, c]
|
| 380 |
+
continue
|
| 381 |
+
|
| 382 |
+
for r in unvisible_pts:
|
| 383 |
+
dist1 = np.min(surface_geodesic[r, visible_pts])
|
| 384 |
+
nn_visible = visible_pts[np.argmin(surface_geodesic[r, visible_pts])]
|
| 385 |
+
if np.isinf(dist1):
|
| 386 |
+
visible_matrix[r, c] = 8.0 + pts_bone_dist[r, c]
|
| 387 |
+
else:
|
| 388 |
+
visible_matrix[r, c] = dist1 + visible_matrix[nn_visible, c]
|
| 389 |
+
|
| 390 |
+
return visible_matrix
|
| 391 |
+
|
| 392 |
+
# Load models at startup
|
| 393 |
+
load_models()
|
| 394 |
+
|
| 395 |
+
# Create Gradio interface
|
| 396 |
+
iface = gr.Interface(
|
| 397 |
+
fn=predict_rig,
|
| 398 |
+
inputs=gr.File(label="Upload OBJ File", file_types=[".obj"]),
|
| 399 |
+
outputs=gr.File(label="Download Rig TXT"),
|
| 400 |
+
title="RigNet: Automatic Character Rigging",
|
| 401 |
+
description="Upload a 3D character mesh in OBJ format to automatically generate a rig. The model will predict joints, skeleton hierarchy, and skinning weights. Best results with meshes containing 1K-5K vertices.",
|
| 402 |
+
examples=[],
|
| 403 |
+
cache_examples=False
|
| 404 |
+
)
|
| 405 |
|
|
|
|
| 406 |
if __name__ == "__main__":
|
| 407 |
+
iface.launch(server_name="0.0.0.0", server_port=7860)
|