Spaces:
Running
on
Zero
Running
on
Zero
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import torch
|
3 |
+
import trimesh
|
4 |
+
import os
|
5 |
+
import sys
|
6 |
+
import tempfile
|
7 |
+
import shutil
|
8 |
+
|
9 |
+
# Add UniRig source directory to Python path
|
10 |
+
# Assuming UniRig files are in a subdirectory named 'UniRig_src'
|
11 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), 'UniRig_src'))
|
12 |
+
|
13 |
+
# Conditional import for AutoRigger and setup_source_mesh
|
14 |
+
# This helps in providing a clearer error if UniRig_src is not found
|
15 |
+
try:
|
16 |
+
from autorig import AutoRigger
|
17 |
+
from utils import setup_source_mesh
|
18 |
+
except ImportError as e:
|
19 |
+
print("Error importing from UniRig_src. Make sure the UniRig source files are in the 'UniRig_src' directory.")
|
20 |
+
print(f"Details: {e}")
|
21 |
+
# Define dummy functions if import fails, so Gradio can still load with an error message
|
22 |
+
def AutoRigger(*args, **kwargs):
|
23 |
+
raise RuntimeError("UniRig AutoRigger could not be loaded. Check UniRig_src setup.")
|
24 |
+
def setup_source_mesh(mesh, *args, **kwargs):
|
25 |
+
raise RuntimeError("UniRig setup_source_mesh could not be loaded. Check UniRig_src setup.")
|
26 |
+
|
27 |
+
# --- Configuration ---
|
28 |
+
# Define paths to the UniRig model files
|
29 |
+
# These files should be placed in the 'model_files' directory in your Hugging Face Space
|
30 |
+
MODEL_DIR = os.path.join(os.path.dirname(__file__), "model_files")
|
31 |
+
SMPL_SKELETON_PATH = os.path.join(MODEL_DIR, "smpl_skeleton.pkl")
|
32 |
+
SKIN_KPS_PREDICTOR_PATH = os.path.join(MODEL_DIR, "skin_kps_predictor.pkl")
|
33 |
+
|
34 |
+
# Check if model files exist
|
35 |
+
if not os.path.exists(SMPL_SKELETON_PATH) or not os.path.exists(SKIN_KPS_PREDICTOR_PATH):
|
36 |
+
print(f"Warning: Model files not found at {MODEL_DIR}. Please ensure smpl_skeleton.pkl and skin_kps_predictor.pkl are present.")
|
37 |
+
|
38 |
+
# Determine processing device (CUDA if available, otherwise CPU)
|
39 |
+
# ZeroGPU on Hugging Face Spaces should provide CUDA
|
40 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
41 |
+
print(f"Using device: {DEVICE}")
|
42 |
+
if DEVICE.type == 'cuda':
|
43 |
+
print(f"CUDA Device Name: {torch.cuda.get_device_name(0)}")
|
44 |
+
print(f"CUDA Version: {torch.version.cuda}")
|
45 |
+
else:
|
46 |
+
print("CUDA not available, UniRig performance will be significantly slower on CPU.")
|
47 |
+
|
48 |
+
|
49 |
+
# --- Core Rigging Function ---
|
50 |
+
def rig_glb_mesh(input_glb_file):
|
51 |
+
"""
|
52 |
+
Takes an input GLB file, rigs it using UniRig, and returns the path to the rigged GLB file.
|
53 |
+
"""
|
54 |
+
if input_glb_file is None:
|
55 |
+
raise gr.Error("No input file provided. Please upload a .glb mesh.")
|
56 |
+
|
57 |
+
input_glb_path = input_glb_file.name # Get the path of the uploaded file
|
58 |
+
|
59 |
+
# Ensure UniRig components are loaded (they might be dummy if import failed)
|
60 |
+
if not callable(getattr(AutoRigger, '__init__', None)) or not callable(setup_source_mesh):
|
61 |
+
raise gr.Error("UniRig components are not correctly loaded. Please check the server logs and UniRig_src setup.")
|
62 |
+
|
63 |
+
try:
|
64 |
+
# Create a temporary directory for output
|
65 |
+
temp_dir = tempfile.mkdtemp()
|
66 |
+
output_glb_filename = "rigged_output.glb"
|
67 |
+
output_glb_path = os.path.join(temp_dir, output_glb_filename)
|
68 |
+
|
69 |
+
# 1. Load the mesh using trimesh
|
70 |
+
print(f"Loading mesh from: {input_glb_path}")
|
71 |
+
mesh = trimesh.load_mesh(input_glb_path, force='mesh', process=False)
|
72 |
+
|
73 |
+
if not isinstance(mesh, trimesh.Trimesh):
|
74 |
+
# If it's a Scene object, try to get a single geometry
|
75 |
+
if isinstance(mesh, trimesh.Scene):
|
76 |
+
if len(mesh.geometry) == 0:
|
77 |
+
raise gr.Error("Input GLB file contains no mesh geometry.")
|
78 |
+
# Concatenate all meshes in the scene into a single mesh
|
79 |
+
# This is a common approach, but might not be ideal for all GLB files
|
80 |
+
print(f"Input is a scene with {len(mesh.geometry)} geometries. Attempting to merge.")
|
81 |
+
mesh = trimesh.util.concatenate(list(mesh.geometry.values()))
|
82 |
+
if not isinstance(mesh, trimesh.Trimesh):
|
83 |
+
raise gr.Error(f"Could not extract a valid mesh from the GLB scene. Found type: {type(mesh)}")
|
84 |
+
else:
|
85 |
+
raise gr.Error(f"Failed to load a valid mesh from the input file. Loaded type: {type(mesh)}")
|
86 |
+
|
87 |
+
print("Mesh loaded successfully.")
|
88 |
+
|
89 |
+
# 2. Preprocess the mesh (as per UniRig's example)
|
90 |
+
# This step is crucial for UniRig to work correctly.
|
91 |
+
# It involves canonicalization and remeshing.
|
92 |
+
print("Preprocessing mesh...")
|
93 |
+
mesh = setup_source_mesh(mesh, device=DEVICE)
|
94 |
+
print("Mesh preprocessing complete.")
|
95 |
+
|
96 |
+
# 3. Initialize the AutoRigger
|
97 |
+
# Ensure model files are accessible
|
98 |
+
if not os.path.exists(SMPL_SKELETON_PATH) or not os.path.exists(SKIN_KPS_PREDICTOR_PATH):
|
99 |
+
raise gr.Error(f"UniRig model files not found. Searched in {MODEL_DIR}. Please check your Space's file structure.")
|
100 |
+
|
101 |
+
print("Initializing AutoRigger...")
|
102 |
+
autorigger = AutoRigger(SMPL_SKELETON_PATH, SKIN_KPS_PREDICTOR_PATH, device=DEVICE)
|
103 |
+
print("AutoRigger initialized.")
|
104 |
+
|
105 |
+
# 4. Perform rigging
|
106 |
+
print("Starting rigging process...")
|
107 |
+
# The `rig` method might require specific verts, faces, and normals if not handled by `setup_source_mesh`
|
108 |
+
# Assuming `setup_source_mesh` prepares it adequately.
|
109 |
+
output_dict = autorigger.rig(mesh)
|
110 |
+
print("Rigging process complete.")
|
111 |
+
|
112 |
+
# 5. Extract the rigged mesh
|
113 |
+
rigged_mesh = output_dict['rigged_mesh'] # This should be a trimesh.Trimesh object
|
114 |
+
print("Rigged mesh extracted.")
|
115 |
+
|
116 |
+
# 6. Export the rigged mesh to GLB format
|
117 |
+
print(f"Exporting rigged mesh to: {output_glb_path}")
|
118 |
+
rigged_mesh.export(output_glb_path)
|
119 |
+
print("Export complete.")
|
120 |
+
|
121 |
+
return output_glb_path
|
122 |
+
|
123 |
+
except Exception as e:
|
124 |
+
print(f"Error during rigging: {e}")
|
125 |
+
# Clean up temp dir in case of error
|
126 |
+
if 'temp_dir' in locals() and os.path.exists(temp_dir):
|
127 |
+
shutil.rmtree(temp_dir)
|
128 |
+
# Re-raise as Gradio error to display to user
|
129 |
+
raise gr.Error(f"An error occurred during processing: {str(e)}")
|
130 |
+
# No finally block for shutil.rmtree(temp_dir) here,
|
131 |
+
# because Gradio needs the file path to serve it.
|
132 |
+
# Gradio handles cleanup of temporary files created by gr.File.
|
133 |
+
|
134 |
+
# --- Gradio Interface ---
|
135 |
+
# Define a custom theme (Blue and Charcoal Gray)
|
136 |
+
# Using Soft theme with sky blue and slate gray
|
137 |
+
theme = gr.themes.Soft(
|
138 |
+
primary_hue=gr.themes.colors.sky, # A nice blue
|
139 |
+
secondary_hue=gr.themes.colors.blue, # Can be same as primary or a complementary blue
|
140 |
+
neutral_hue=gr.themes.colors.slate, # Charcoal gray
|
141 |
+
font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"],
|
142 |
+
).set(
|
143 |
+
# Further fine-tuning if needed
|
144 |
+
# button_primary_background_fill="*primary_500",
|
145 |
+
# button_primary_text_color="white",
|
146 |
+
)
|
147 |
+
|
148 |
+
# Interface definition
|
149 |
+
iface = gr.Interface(
|
150 |
+
fn=rig_glb_mesh,
|
151 |
+
inputs=gr.File(label="Upload .glb Mesh File", type="file"), # 'file' gives a NamedTemporaryFile object
|
152 |
+
outputs=gr.Model3D(label="Rigged 3D Model (.glb)", clear_color=[0.8, 0.8, 0.8, 1.0]), # Model3D can display .glb
|
153 |
+
title="UniRig Auto-Rigger for 3D Meshes",
|
154 |
+
description=(
|
155 |
+
"Upload a 3D mesh in `.glb` format. This application uses UniRig to automatically rig the mesh.\n"
|
156 |
+
"The process may take a few minutes, especially for complex meshes. Ensure your GLB has clean geometry.\n"
|
157 |
+
f"Running on: {str(DEVICE).upper()}. Model files expected in '{MODEL_DIR}'.\n"
|
158 |
+
f"UniRig Source: https://github.com/VAST-AI-Research/UniRig"
|
159 |
+
),
|
160 |
+
examples=[
|
161 |
+
# Add paths to example GLB files if you include them in your Space
|
162 |
+
# e.g., [os.path.join(os.path.dirname(__file__), "examples/sample_mesh.glb")]
|
163 |
+
],
|
164 |
+
cache_examples=False, # Set to True if you have static examples and want to pre-process them
|
165 |
+
theme=theme,
|
166 |
+
allow_flagging="never"
|
167 |
+
)
|
168 |
+
|
169 |
+
if __name__ == "__main__":
|
170 |
+
if not os.path.exists(os.path.join(os.path.dirname(__file__), 'UniRig_src')):
|
171 |
+
print("CRITICAL: 'UniRig_src' directory not found. Please ensure UniRig source files are correctly placed.")
|
172 |
+
iface.launch()
|