Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,32 +5,27 @@ import sys
|
|
| 5 |
import tempfile
|
| 6 |
import shutil
|
| 7 |
import subprocess
|
| 8 |
-
import spaces
|
| 9 |
-
from typing import Any, Dict,
|
| 10 |
|
| 11 |
# --- Configuration ---
|
| 12 |
UNIRIG_REPO_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "UniRig"))
|
| 13 |
-
BLENDER_INSTALL_DIR = "/opt/blender-4.2.0-linux-x64"
|
| 14 |
-
BLENDER_PYTHON_VERSION_DIR = "4.2"
|
| 15 |
-
BLENDER_PYTHON_VERSION = "python3.11"
|
| 16 |
|
| 17 |
# Construct paths
|
| 18 |
BLENDER_PYTHON_DIR = os.path.join(BLENDER_INSTALL_DIR, BLENDER_PYTHON_VERSION_DIR, "python")
|
| 19 |
BLENDER_PYTHON_BIN_DIR = os.path.join(BLENDER_PYTHON_DIR, "bin")
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
BLENDER_PYTHON_SITE_PACKAGES = os.path.join(BLENDER_PYTHON_LIB_PATH, "site-packages")
|
| 23 |
-
# Path to the main blender executable (assuming symlink exists or using direct path)
|
| 24 |
-
BLENDER_EXEC = os.path.join(BLENDER_INSTALL_DIR, "blender") # Use direct path first
|
| 25 |
BLENDER_EXEC_SYMLINK = "/usr/local/bin/blender" # Fallback symlink
|
| 26 |
|
| 27 |
SETUP_SCRIPT = os.path.join(os.path.dirname(__file__), "setup_blender.sh")
|
| 28 |
|
| 29 |
-
# --- Initial Checks ---
|
| 30 |
print("--- Environment Checks ---")
|
| 31 |
-
|
| 32 |
-
# Check if main Blender executable exists
|
| 33 |
-
blender_executable_to_use = None
|
| 34 |
if os.path.exists(BLENDER_EXEC):
|
| 35 |
print(f"Blender executable found at direct path: {BLENDER_EXEC}")
|
| 36 |
blender_executable_to_use = BLENDER_EXEC
|
|
@@ -38,7 +33,6 @@ elif os.path.exists(BLENDER_EXEC_SYMLINK):
|
|
| 38 |
print(f"Blender executable found via symlink: {BLENDER_EXEC_SYMLINK}")
|
| 39 |
blender_executable_to_use = BLENDER_EXEC_SYMLINK
|
| 40 |
else:
|
| 41 |
-
# Try running setup if Blender executable is missing
|
| 42 |
print(f"Blender executable not found at {BLENDER_EXEC} or {BLENDER_EXEC_SYMLINK}. Running setup script...")
|
| 43 |
if os.path.exists(SETUP_SCRIPT):
|
| 44 |
try:
|
|
@@ -50,30 +44,25 @@ else:
|
|
| 50 |
# Re-check for executable
|
| 51 |
if os.path.exists(BLENDER_EXEC):
|
| 52 |
blender_executable_to_use = BLENDER_EXEC
|
|
|
|
| 53 |
elif os.path.exists(BLENDER_EXEC_SYMLINK):
|
| 54 |
-
|
|
|
|
| 55 |
|
| 56 |
if not blender_executable_to_use:
|
| 57 |
raise RuntimeError(f"Setup script ran but Blender executable still not found at {BLENDER_EXEC} or {BLENDER_EXEC_SYMLINK}.")
|
| 58 |
|
| 59 |
except subprocess.CalledProcessError as e:
|
| 60 |
-
|
| 61 |
-
|
| 62 |
except Exception as e:
|
| 63 |
-
|
| 64 |
else:
|
| 65 |
raise gr.Error(f"Blender executable not found and setup script missing: {SETUP_SCRIPT}")
|
| 66 |
|
| 67 |
-
#
|
| 68 |
-
if not os.path.exists(BLENDER_PYTHON_EXEC):
|
| 69 |
-
print(f"WARNING: Blender Python executable not found at {BLENDER_PYTHON_EXEC}, though main executable exists.")
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
# Verify Blender Python site-packages path and attempt bpy import test
|
| 73 |
bpy_import_ok = False
|
| 74 |
-
if
|
| 75 |
-
print(f"Blender Python site-packages found at: {BLENDER_PYTHON_SITE_PACKAGES}")
|
| 76 |
-
# Try importing bpy using blender --background --python
|
| 77 |
try:
|
| 78 |
test_script_content = "import bpy; print('bpy imported successfully')"
|
| 79 |
test_result = subprocess.run(
|
|
@@ -87,14 +76,13 @@ if os.path.exists(BLENDER_PYTHON_SITE_PACKAGES):
|
|
| 87 |
print(f"WARNING: 'bpy' import test via Blender returned unexpected output:\nSTDOUT:{test_result.stdout}\nSTDERR:{test_result.stderr}")
|
| 88 |
|
| 89 |
except subprocess.TimeoutExpired:
|
| 90 |
-
|
| 91 |
except subprocess.CalledProcessError as e:
|
| 92 |
print(f"WARNING: Failed to import 'bpy' using Blender executable:\nSTDOUT:{e.stdout}\nSTDERR:{e.stderr}")
|
| 93 |
except Exception as e:
|
| 94 |
print(f"WARNING: Unexpected error during 'bpy' import test: {e}")
|
| 95 |
-
|
| 96 |
else:
|
| 97 |
-
|
| 98 |
|
| 99 |
|
| 100 |
# Check for UniRig repository
|
|
@@ -102,14 +90,21 @@ if not os.path.isdir(UNIRIG_REPO_DIR):
|
|
| 102 |
raise gr.Error(f"UniRig repository missing at: {UNIRIG_REPO_DIR}. Ensure it's cloned correctly.")
|
| 103 |
else:
|
| 104 |
print(f"UniRig repository found at: {UNIRIG_REPO_DIR}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
-
|
|
|
|
| 107 |
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 108 |
print(f"Gradio environment using device: {DEVICE}")
|
| 109 |
if DEVICE.type == 'cuda':
|
| 110 |
try:
|
| 111 |
print(f"Gradio CUDA Device Name: {torch.cuda.get_device_name(0)}")
|
| 112 |
-
|
|
|
|
|
|
|
| 113 |
except Exception as e:
|
| 114 |
print(f"Could not get CUDA device details: {e}")
|
| 115 |
else:
|
|
@@ -117,8 +112,7 @@ else:
|
|
| 117 |
|
| 118 |
print("--- End Environment Checks ---")
|
| 119 |
|
| 120 |
-
# --- Helper Functions ---
|
| 121 |
-
|
| 122 |
def patch_asset_py():
|
| 123 |
"""Temporary patch to fix type hinting error in UniRig's asset.py"""
|
| 124 |
asset_py_path = os.path.join(UNIRIG_REPO_DIR, "src", "data", "asset.py")
|
|
@@ -128,106 +122,150 @@ def patch_asset_py():
|
|
| 128 |
return
|
| 129 |
|
| 130 |
with open(asset_py_path, "r") as f: content = f.read()
|
|
|
|
| 131 |
problematic_line = "meta: Union[Dict[str, ...], None]=None"
|
| 132 |
-
corrected_line = "meta: Union[Dict[str, Any], None]=None"
|
| 133 |
typing_import = "from typing import Any"
|
| 134 |
|
| 135 |
if corrected_line in content:
|
| 136 |
print("Patch already applied to asset.py"); return
|
| 137 |
if problematic_line not in content:
|
| 138 |
-
|
| 139 |
|
| 140 |
print("Applying patch to asset.py...")
|
| 141 |
content = content.replace(problematic_line, corrected_line)
|
|
|
|
| 142 |
if typing_import not in content:
|
| 143 |
-
if "from typing import" in content:
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
with open(asset_py_path, "w") as f: f.write(content)
|
| 146 |
print("Successfully patched asset.py")
|
| 147 |
|
| 148 |
except Exception as e:
|
| 149 |
print(f"ERROR: Failed to patch asset.py: {e}. Proceeding cautiously.")
|
|
|
|
| 150 |
|
|
|
|
|
|
|
| 151 |
@spaces.GPU
|
| 152 |
-
def run_unirig_command(
|
| 153 |
"""
|
| 154 |
Runs a specific UniRig PYTHON script (.py) using the Blender executable
|
| 155 |
in background mode (`blender --background --python script.py -- args`).
|
| 156 |
|
| 157 |
Args:
|
| 158 |
-
|
| 159 |
script_args: A list of command-line arguments FOR THE PYTHON SCRIPT.
|
| 160 |
step_name: Name of the step for logging.
|
| 161 |
"""
|
| 162 |
if not blender_executable_to_use:
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
# Command structure: blender --background --python script.py -- script_arg1 script_arg2 ...
|
| 166 |
-
cmd = [
|
| 167 |
-
blender_executable_to_use,
|
| 168 |
-
"--background",
|
| 169 |
-
"--python", python_script_path,
|
| 170 |
-
"--" # Separator for script arguments
|
| 171 |
-
] + script_args
|
| 172 |
|
| 173 |
-
|
| 174 |
-
print(f"Command: {' '.join(cmd)}") # Note: Simple join for logging
|
| 175 |
-
|
| 176 |
-
# Environment variables might still be useful if the script imports other non-blender libs
|
| 177 |
process_env = os.environ.copy()
|
| 178 |
-
unirig_src_dir = os.path.join(UNIRIG_REPO_DIR, "src")
|
| 179 |
|
| 180 |
-
#
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
UNIRIG_REPO_DIR,
|
| 184 |
-
'.' # Add current working directory explicitly
|
| 185 |
-
]
|
| 186 |
existing_pythonpath = process_env.get('PYTHONPATH', '')
|
| 187 |
if existing_pythonpath:
|
| 188 |
pythonpath_parts.append(existing_pythonpath)
|
| 189 |
process_env["PYTHONPATH"] = os.pathsep.join(filter(None, pythonpath_parts))
|
| 190 |
print(f"Subprocess PYTHONPATH: {process_env['PYTHONPATH']}")
|
| 191 |
|
| 192 |
-
# LD_LIBRARY_PATH
|
| 193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
existing_ld_path = process_env.get('LD_LIBRARY_PATH', '')
|
| 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 |
try:
|
| 222 |
# Execute Blender with the Python script.
|
| 223 |
-
# cwd=UNIRIG_REPO_DIR ensures script runs relative to repo root.
|
| 224 |
result = subprocess.run(
|
| 225 |
cmd,
|
| 226 |
cwd=UNIRIG_REPO_DIR, # CWD is set to UniRig repo root
|
| 227 |
capture_output=True,
|
| 228 |
text=True,
|
| 229 |
check=True, # Raises CalledProcessError on non-zero exit codes
|
| 230 |
-
env=process_env # Pass the modified environment
|
|
|
|
| 231 |
)
|
| 232 |
print(f"{step_name} STDOUT:\n{result.stdout}")
|
| 233 |
# Blender often prints info/warnings to stderr even on success
|
|
@@ -235,9 +273,14 @@ def run_unirig_command(python_script_path: str, script_args: List[str], step_nam
|
|
| 235 |
print(f"{step_name} STDERR (Info/Warnings):\n{result.stderr}")
|
| 236 |
# Check stderr for common Blender errors even if exit code was 0
|
| 237 |
if "Error: Cannot read file" in result.stderr:
|
| 238 |
-
|
|
|
|
|
|
|
| 239 |
# Add other specific Blender error checks if needed
|
| 240 |
|
|
|
|
|
|
|
|
|
|
| 241 |
except subprocess.CalledProcessError as e:
|
| 242 |
print(f"ERROR during {step_name}: Subprocess failed!")
|
| 243 |
print(f"Command: {' '.join(e.cmd)}")
|
|
@@ -245,20 +288,33 @@ def run_unirig_command(python_script_path: str, script_args: List[str], step_nam
|
|
| 245 |
print(f"--- {step_name} STDOUT ---:\n{e.stdout}")
|
| 246 |
print(f"--- {step_name} STDERR ---:\n{e.stderr}")
|
| 247 |
error_summary = e.stderr.strip().splitlines()
|
| 248 |
-
last_lines = "\n".join(error_summary[-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
elif "
|
| 255 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
else:
|
| 257 |
-
|
|
|
|
| 258 |
|
| 259 |
except FileNotFoundError:
|
| 260 |
# This error means blender executable or the python script wasn't found
|
| 261 |
-
print(f"ERROR: Could not find Blender executable '{blender_executable_to_use}' or script '{
|
| 262 |
print(f"Attempted command: {' '.join(cmd)}")
|
| 263 |
raise gr.Error(f"Setup error for UniRig '{step_name}'. Blender or Python script not found.")
|
| 264 |
|
|
@@ -275,16 +331,27 @@ def run_unirig_command(python_script_path: str, script_args: List[str], step_nam
|
|
| 275 |
def rig_glb_mesh_multistep(input_glb_file_obj):
|
| 276 |
"""
|
| 277 |
Main Gradio function to rig a GLB mesh using UniRig's multi-step process.
|
| 278 |
-
Orchestrates calls to run_unirig_command for each step, executing .py
|
| 279 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
try:
|
| 281 |
-
patch_asset_py() #
|
| 282 |
except Exception as e:
|
| 283 |
-
|
| 284 |
|
| 285 |
# --- Input Validation ---
|
| 286 |
-
if input_glb_file_obj is None:
|
| 287 |
-
|
|
|
|
|
|
|
| 288 |
print(f"Input GLB path received: {input_glb_path}")
|
| 289 |
if not os.path.exists(input_glb_path): raise gr.Error(f"Input file path does not exist: {input_glb_path}")
|
| 290 |
if not input_glb_path.lower().endswith(".glb"): raise gr.Error("Invalid file type. Please upload a .glb file.")
|
|
@@ -296,76 +363,92 @@ def rig_glb_mesh_multistep(input_glb_file_obj):
|
|
| 296 |
try:
|
| 297 |
# --- Define File Paths ---
|
| 298 |
base_name = os.path.splitext(os.path.basename(input_glb_path))[0]
|
|
|
|
| 299 |
abs_input_glb_path = os.path.abspath(input_glb_path)
|
| 300 |
abs_skeleton_output_path = os.path.join(processing_temp_dir, f"{base_name}_skeleton.fbx")
|
| 301 |
abs_skin_output_path = os.path.join(processing_temp_dir, f"{base_name}_skin.fbx")
|
| 302 |
abs_final_rigged_glb_path = os.path.join(processing_temp_dir, f"{base_name}_rigged_final.glb")
|
| 303 |
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
|
| 308 |
-
# --- Execute UniRig Steps ---
|
|
|
|
| 309 |
|
| 310 |
# Step 1: Skeleton Prediction
|
| 311 |
print("\nStarting Step 1: Predicting Skeleton...")
|
| 312 |
-
# Arguments for the run.py script for skeleton task
|
| 313 |
-
# ** These are GUESSES - VERIFY from UniRig code / shell scripts **
|
| 314 |
skeleton_args = [
|
| 315 |
-
|
| 316 |
-
"
|
| 317 |
-
"
|
|
|
|
|
|
|
|
|
|
| 318 |
]
|
| 319 |
-
|
| 320 |
-
raise gr.Error(f"UniRig main script not found at: {run_script_path}")
|
| 321 |
-
run_unirig_command(run_script_path, skeleton_args, "Skeleton Prediction")
|
| 322 |
if not os.path.exists(abs_skeleton_output_path):
|
| 323 |
raise gr.Error("Skeleton prediction failed. Output file not created. Check logs.")
|
| 324 |
print("Step 1: Skeleton Prediction completed.")
|
| 325 |
|
| 326 |
# Step 2: Skinning Weight Prediction
|
| 327 |
print("\nStarting Step 2: Predicting Skinning Weights...")
|
| 328 |
-
# Arguments for the run.py script for skinning task
|
| 329 |
-
# ** GUESSES - VERIFY **
|
| 330 |
skin_args = [
|
| 331 |
-
|
| 332 |
-
"
|
| 333 |
-
"
|
| 334 |
-
|
|
|
|
|
|
|
| 335 |
]
|
| 336 |
-
run_unirig_command(
|
| 337 |
if not os.path.exists(abs_skin_output_path):
|
| 338 |
raise gr.Error("Skinning prediction failed. Output file not created. Check logs.")
|
| 339 |
print("Step 2: Skinning Prediction completed.")
|
| 340 |
|
| 341 |
-
# Step 3: Merge
|
| 342 |
print("\nStarting Step 3: Merging Results...")
|
| 343 |
-
# Arguments for the run.py script for merging task
|
| 344 |
-
# ** GUESSES - VERIFY **
|
| 345 |
merge_args = [
|
| 346 |
-
|
| 347 |
-
"
|
| 348 |
-
"
|
| 349 |
-
"
|
|
|
|
|
|
|
|
|
|
| 350 |
]
|
| 351 |
-
run_unirig_command(
|
| 352 |
if not os.path.exists(abs_final_rigged_glb_path):
|
| 353 |
raise gr.Error("Merging process failed. Final rigged GLB file not created. Check logs.")
|
| 354 |
print("Step 3: Merging completed.")
|
| 355 |
|
| 356 |
# --- Return Result ---
|
| 357 |
print(f"Successfully generated rigged model: {abs_final_rigged_glb_path}")
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 364 |
except Exception as e:
|
| 365 |
print(f"An unexpected error occurred in rig_glb_mesh_multistep: {e}")
|
| 366 |
import traceback; traceback.print_exc()
|
| 367 |
-
|
| 368 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 369 |
|
| 370 |
|
| 371 |
# --- Gradio Interface Definition ---
|
|
@@ -376,36 +459,64 @@ theme = gr.themes.Soft(
|
|
| 376 |
font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"],
|
| 377 |
)
|
| 378 |
|
| 379 |
-
# Check
|
| 380 |
-
|
|
|
|
|
|
|
|
|
|
| 381 |
startup_error_message = (f"CRITICAL STARTUP ERROR: UniRig repository not found at {UNIRIG_REPO_DIR}.")
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 388 |
else:
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 403 |
|
| 404 |
# --- Launch the Application ---
|
| 405 |
if __name__ == "__main__":
|
| 406 |
if 'iface' in locals():
|
| 407 |
print("Launching Gradio interface...")
|
| 408 |
-
|
|
|
|
| 409 |
else:
|
| 410 |
print("ERROR: Gradio interface not created due to startup errors.")
|
| 411 |
|
|
|
|
| 5 |
import tempfile
|
| 6 |
import shutil
|
| 7 |
import subprocess
|
| 8 |
+
import spaces # Keep this if you use @spaces.GPU
|
| 9 |
+
from typing import Any, Dict, List, Union # Added Union
|
| 10 |
|
| 11 |
# --- Configuration ---
|
| 12 |
UNIRIG_REPO_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "UniRig"))
|
| 13 |
+
BLENDER_INSTALL_DIR = "/opt/blender-4.2.0-linux-x64" # From your setup_blender.sh
|
| 14 |
+
BLENDER_PYTHON_VERSION_DIR = "4.2" # From your app.py
|
| 15 |
+
BLENDER_PYTHON_VERSION = "python3.11" # From your app.py and UniRig
|
| 16 |
|
| 17 |
# Construct paths
|
| 18 |
BLENDER_PYTHON_DIR = os.path.join(BLENDER_INSTALL_DIR, BLENDER_PYTHON_VERSION_DIR, "python")
|
| 19 |
BLENDER_PYTHON_BIN_DIR = os.path.join(BLENDER_PYTHON_DIR, "bin")
|
| 20 |
+
# Use Blender's main executable to run Python scripts via --python flag
|
| 21 |
+
BLENDER_EXEC = os.path.join(BLENDER_INSTALL_DIR, "blender")
|
|
|
|
|
|
|
|
|
|
| 22 |
BLENDER_EXEC_SYMLINK = "/usr/local/bin/blender" # Fallback symlink
|
| 23 |
|
| 24 |
SETUP_SCRIPT = os.path.join(os.path.dirname(__file__), "setup_blender.sh")
|
| 25 |
|
| 26 |
+
# --- Initial Checks (adapted from your script) ---
|
| 27 |
print("--- Environment Checks ---")
|
| 28 |
+
blender_executable_to_use = None # Use the main blender executable
|
|
|
|
|
|
|
| 29 |
if os.path.exists(BLENDER_EXEC):
|
| 30 |
print(f"Blender executable found at direct path: {BLENDER_EXEC}")
|
| 31 |
blender_executable_to_use = BLENDER_EXEC
|
|
|
|
| 33 |
print(f"Blender executable found via symlink: {BLENDER_EXEC_SYMLINK}")
|
| 34 |
blender_executable_to_use = BLENDER_EXEC_SYMLINK
|
| 35 |
else:
|
|
|
|
| 36 |
print(f"Blender executable not found at {BLENDER_EXEC} or {BLENDER_EXEC_SYMLINK}. Running setup script...")
|
| 37 |
if os.path.exists(SETUP_SCRIPT):
|
| 38 |
try:
|
|
|
|
| 44 |
# Re-check for executable
|
| 45 |
if os.path.exists(BLENDER_EXEC):
|
| 46 |
blender_executable_to_use = BLENDER_EXEC
|
| 47 |
+
print(f"Blender executable now found at: {BLENDER_EXEC}")
|
| 48 |
elif os.path.exists(BLENDER_EXEC_SYMLINK):
|
| 49 |
+
blender_executable_to_use = BLENDER_EXEC_SYMLINK
|
| 50 |
+
print(f"Blender executable now found via symlink: {BLENDER_EXEC_SYMLINK}")
|
| 51 |
|
| 52 |
if not blender_executable_to_use:
|
| 53 |
raise RuntimeError(f"Setup script ran but Blender executable still not found at {BLENDER_EXEC} or {BLENDER_EXEC_SYMLINK}.")
|
| 54 |
|
| 55 |
except subprocess.CalledProcessError as e:
|
| 56 |
+
print(f"ERROR running setup script: {SETUP_SCRIPT}\nStderr: {e.stderr}")
|
| 57 |
+
raise gr.Error(f"Failed to execute setup script. Check logs. Stderr: {e.stderr[-500:]}")
|
| 58 |
except Exception as e:
|
| 59 |
+
raise gr.Error(f"Unexpected error running setup script '{SETUP_SCRIPT}': {e}")
|
| 60 |
else:
|
| 61 |
raise gr.Error(f"Blender executable not found and setup script missing: {SETUP_SCRIPT}")
|
| 62 |
|
| 63 |
+
# Verify bpy import using the found Blender executable
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
bpy_import_ok = False
|
| 65 |
+
if blender_executable_to_use:
|
|
|
|
|
|
|
| 66 |
try:
|
| 67 |
test_script_content = "import bpy; print('bpy imported successfully')"
|
| 68 |
test_result = subprocess.run(
|
|
|
|
| 76 |
print(f"WARNING: 'bpy' import test via Blender returned unexpected output:\nSTDOUT:{test_result.stdout}\nSTDERR:{test_result.stderr}")
|
| 77 |
|
| 78 |
except subprocess.TimeoutExpired:
|
| 79 |
+
print("WARNING: 'bpy' import test via Blender timed out.")
|
| 80 |
except subprocess.CalledProcessError as e:
|
| 81 |
print(f"WARNING: Failed to import 'bpy' using Blender executable:\nSTDOUT:{e.stdout}\nSTDERR:{e.stderr}")
|
| 82 |
except Exception as e:
|
| 83 |
print(f"WARNING: Unexpected error during 'bpy' import test: {e}")
|
|
|
|
| 84 |
else:
|
| 85 |
+
print("WARNING: Cannot test bpy import as Blender executable was not found.")
|
| 86 |
|
| 87 |
|
| 88 |
# Check for UniRig repository
|
|
|
|
| 90 |
raise gr.Error(f"UniRig repository missing at: {UNIRIG_REPO_DIR}. Ensure it's cloned correctly.")
|
| 91 |
else:
|
| 92 |
print(f"UniRig repository found at: {UNIRIG_REPO_DIR}")
|
| 93 |
+
# Check for UniRig's run.py
|
| 94 |
+
UNIRIG_RUN_PY = os.path.join(UNIRIG_REPO_DIR, "run.py")
|
| 95 |
+
if not os.path.exists(UNIRIG_RUN_PY):
|
| 96 |
+
raise gr.Error(f"UniRig's run.py not found at {UNIRIG_RUN_PY}. Check UniRig clone.")
|
| 97 |
|
| 98 |
+
|
| 99 |
+
# Check PyTorch and CUDA for Gradio environment
|
| 100 |
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 101 |
print(f"Gradio environment using device: {DEVICE}")
|
| 102 |
if DEVICE.type == 'cuda':
|
| 103 |
try:
|
| 104 |
print(f"Gradio CUDA Device Name: {torch.cuda.get_device_name(0)}")
|
| 105 |
+
# Note: torch.version.cuda might show the version PyTorch was *built* with,
|
| 106 |
+
# not necessarily the runtime driver version. Check nvidia-smi in Space terminal if needed.
|
| 107 |
+
print(f"Gradio PyTorch CUDA Built Version: {torch.version.cuda}")
|
| 108 |
except Exception as e:
|
| 109 |
print(f"Could not get CUDA device details: {e}")
|
| 110 |
else:
|
|
|
|
| 112 |
|
| 113 |
print("--- End Environment Checks ---")
|
| 114 |
|
| 115 |
+
# --- Helper Functions (Keep patch_asset_py if needed) ---
|
|
|
|
| 116 |
def patch_asset_py():
|
| 117 |
"""Temporary patch to fix type hinting error in UniRig's asset.py"""
|
| 118 |
asset_py_path = os.path.join(UNIRIG_REPO_DIR, "src", "data", "asset.py")
|
|
|
|
| 122 |
return
|
| 123 |
|
| 124 |
with open(asset_py_path, "r") as f: content = f.read()
|
| 125 |
+
# Adjust problematic/corrected lines if UniRig code changes
|
| 126 |
problematic_line = "meta: Union[Dict[str, ...], None]=None"
|
| 127 |
+
corrected_line = "meta: Union[Dict[str, Any], None]=None" # Requires `from typing import Any`
|
| 128 |
typing_import = "from typing import Any"
|
| 129 |
|
| 130 |
if corrected_line in content:
|
| 131 |
print("Patch already applied to asset.py"); return
|
| 132 |
if problematic_line not in content:
|
| 133 |
+
print("Problematic line not found in asset.py, patch might be unnecessary or file changed."); return
|
| 134 |
|
| 135 |
print("Applying patch to asset.py...")
|
| 136 |
content = content.replace(problematic_line, corrected_line)
|
| 137 |
+
# Ensure 'Any' is imported
|
| 138 |
if typing_import not in content:
|
| 139 |
+
if "from typing import" in content:
|
| 140 |
+
# Add 'Any' to an existing import line
|
| 141 |
+
content = content.replace("from typing import", f"{typing_import}\nfrom typing import", 1)
|
| 142 |
+
else:
|
| 143 |
+
# Add the import line at the top
|
| 144 |
+
content = f"{typing_import}\n{content}"
|
| 145 |
+
|
| 146 |
with open(asset_py_path, "w") as f: f.write(content)
|
| 147 |
print("Successfully patched asset.py")
|
| 148 |
|
| 149 |
except Exception as e:
|
| 150 |
print(f"ERROR: Failed to patch asset.py: {e}. Proceeding cautiously.")
|
| 151 |
+
# --- End Helper Functions ---
|
| 152 |
|
| 153 |
+
|
| 154 |
+
# Decorator for ZeroGPU if needed
|
| 155 |
@spaces.GPU
|
| 156 |
+
def run_unirig_command(unirig_run_script_path: str, script_args: List[str], step_name: str):
|
| 157 |
"""
|
| 158 |
Runs a specific UniRig PYTHON script (.py) using the Blender executable
|
| 159 |
in background mode (`blender --background --python script.py -- args`).
|
| 160 |
|
| 161 |
Args:
|
| 162 |
+
unirig_run_script_path: Absolute path to the UniRig run.py script.
|
| 163 |
script_args: A list of command-line arguments FOR THE PYTHON SCRIPT.
|
| 164 |
step_name: Name of the step for logging.
|
| 165 |
"""
|
| 166 |
if not blender_executable_to_use:
|
| 167 |
+
raise gr.Error("Blender executable path could not be determined. Cannot run UniRig step.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
| 169 |
+
# --- Environment Setup for Subprocess ---
|
|
|
|
|
|
|
|
|
|
| 170 |
process_env = os.environ.copy()
|
|
|
|
| 171 |
|
| 172 |
+
# PYTHONPATH: Only need UniRig's root directory. Python automatically checks CWD.
|
| 173 |
+
# Add UniRig root to the start of PYTHONPATH.
|
| 174 |
+
pythonpath_parts = [UNIRIG_REPO_DIR]
|
|
|
|
|
|
|
|
|
|
| 175 |
existing_pythonpath = process_env.get('PYTHONPATH', '')
|
| 176 |
if existing_pythonpath:
|
| 177 |
pythonpath_parts.append(existing_pythonpath)
|
| 178 |
process_env["PYTHONPATH"] = os.pathsep.join(filter(None, pythonpath_parts))
|
| 179 |
print(f"Subprocess PYTHONPATH: {process_env['PYTHONPATH']}")
|
| 180 |
|
| 181 |
+
# LD_LIBRARY_PATH: Inherit system path (for CUDA) and add Blender's libraries.
|
| 182 |
+
blender_main_lib_path = os.path.join(BLENDER_INSTALL_DIR, "lib")
|
| 183 |
+
blender_python_lib_path = os.path.join(BLENDER_PYTHON_DIR, "lib") # Libs for the interpreter itself
|
| 184 |
+
ld_path_parts = []
|
| 185 |
+
# Add Blender's libs first so they are preferred if needed
|
| 186 |
+
if os.path.exists(blender_main_lib_path): ld_path_parts.append(blender_main_lib_path)
|
| 187 |
+
if os.path.exists(blender_python_lib_path): ld_path_parts.append(blender_python_lib_path)
|
| 188 |
+
# Inherit existing LD_LIBRARY_PATH (should include CUDA from ZeroGPU)
|
| 189 |
existing_ld_path = process_env.get('LD_LIBRARY_PATH', '')
|
| 190 |
+
if existing_ld_path: ld_path_parts.append(existing_ld_path)
|
| 191 |
+
|
| 192 |
+
if ld_path_parts:
|
| 193 |
+
process_env["LD_LIBRARY_PATH"] = os.pathsep.join(filter(None, ld_path_parts))
|
| 194 |
+
print(f"Subprocess LD_LIBRARY_PATH: {process_env.get('LD_LIBRARY_PATH', 'Not set')}")
|
| 195 |
+
|
| 196 |
+
# --- Test Import of 'src' module ---
|
| 197 |
+
# *** FIX: Use '--python-expr' which is equivalent to '--python -c' but safer with args ***
|
| 198 |
+
test_cmd = [
|
| 199 |
+
blender_executable_to_use,
|
| 200 |
+
"--background",
|
| 201 |
+
"--python-expr", "import src; print('src module imported successfully')" # Use --python-expr
|
| 202 |
+
]
|
| 203 |
+
print(f"Running test import command: {' '.join(test_cmd)}")
|
| 204 |
+
try:
|
| 205 |
+
test_result = subprocess.run(
|
| 206 |
+
test_cmd,
|
| 207 |
+
cwd=UNIRIG_REPO_DIR, # Run test from UniRig root
|
| 208 |
+
capture_output=True,
|
| 209 |
+
text=True,
|
| 210 |
+
check=True, # Raise error on non-zero exit
|
| 211 |
+
env=process_env,
|
| 212 |
+
timeout=30
|
| 213 |
+
)
|
| 214 |
+
if "src module imported successfully" not in test_result.stdout:
|
| 215 |
+
print(f"Test import of 'src' did not produce expected output.")
|
| 216 |
+
print(f"Test STDOUT: {test_result.stdout}")
|
| 217 |
+
print(f"Test STDERR: {test_result.stderr}")
|
| 218 |
+
# Don't raise here, maybe it prints elsewhere, but log warning
|
| 219 |
+
print("WARNING: Unexpected output from 'src' import test. Proceeding with main command.")
|
| 220 |
+
else:
|
| 221 |
+
print("Test import of 'src' succeeded.")
|
| 222 |
+
|
| 223 |
+
except subprocess.TimeoutExpired:
|
| 224 |
+
print("ERROR: Test import of 'src' timed out.")
|
| 225 |
+
raise gr.Error("Failed to verify 'src' module import within Blender environment (timeout). Check setup.")
|
| 226 |
+
except subprocess.CalledProcessError as e:
|
| 227 |
+
print(f"Test import of 'src' failed with return code {e.returncode}")
|
| 228 |
+
print(f"Test Command: {' '.join(e.cmd)}")
|
| 229 |
+
print(f"Test CWD: {UNIRIG_REPO_DIR}")
|
| 230 |
+
print(f"Test STDOUT: {e.stdout}")
|
| 231 |
+
print(f"Test STDERR: {e.stderr}")
|
| 232 |
+
# Check common errors
|
| 233 |
+
if "ModuleNotFoundError: No module named 'src'" in e.stderr:
|
| 234 |
+
error_msg = "Failed to import 'src' module in Blender environment. Check PYTHONPATH and that UniRig repo structure is correct."
|
| 235 |
+
elif "could not get a list of mounted file-systems" in e.stderr:
|
| 236 |
+
error_msg = "Blender environment issue ('could not get mounted file-systems'). Check Space permissions or Blender compatibility."
|
| 237 |
+
else:
|
| 238 |
+
error_msg = f"Failed to import 'src' module in Blender environment. Error: {e.stderr[:500]}"
|
| 239 |
+
raise gr.Error(error_msg)
|
| 240 |
+
except Exception as e_test:
|
| 241 |
+
print(f"Unexpected error during test import: {e_test}")
|
| 242 |
+
raise gr.Error(f"Unexpected error during 'src' import test: {str(e_test)[:500]}")
|
| 243 |
+
|
| 244 |
+
# --- Execute Main UniRig Command ---
|
| 245 |
+
# Command structure: blender --background --python script.py -- script_arg1 script_arg2 ...
|
| 246 |
+
# Note: UniRig's run.py uses Hydra, which parses args differently. It doesn't need '--'.
|
| 247 |
+
# The arguments are passed directly after the script name.
|
| 248 |
+
cmd = [
|
| 249 |
+
blender_executable_to_use,
|
| 250 |
+
"--background",
|
| 251 |
+
"--python", unirig_run_script_path,
|
| 252 |
+
# "--" # REMOVED: Hydra parses args directly after script name
|
| 253 |
+
] + script_args
|
| 254 |
+
|
| 255 |
+
print(f"\n--- Running UniRig Step: {step_name} ---")
|
| 256 |
+
print(f"Command: {' '.join(cmd)}") # Log the actual command
|
| 257 |
|
| 258 |
try:
|
| 259 |
# Execute Blender with the Python script.
|
| 260 |
+
# cwd=UNIRIG_REPO_DIR ensures script runs relative to repo root and finds configs.
|
| 261 |
result = subprocess.run(
|
| 262 |
cmd,
|
| 263 |
cwd=UNIRIG_REPO_DIR, # CWD is set to UniRig repo root
|
| 264 |
capture_output=True,
|
| 265 |
text=True,
|
| 266 |
check=True, # Raises CalledProcessError on non-zero exit codes
|
| 267 |
+
env=process_env, # Pass the modified environment
|
| 268 |
+
timeout=1800 # 30 minutes timeout, adjust as needed
|
| 269 |
)
|
| 270 |
print(f"{step_name} STDOUT:\n{result.stdout}")
|
| 271 |
# Blender often prints info/warnings to stderr even on success
|
|
|
|
| 273 |
print(f"{step_name} STDERR (Info/Warnings):\n{result.stderr}")
|
| 274 |
# Check stderr for common Blender errors even if exit code was 0
|
| 275 |
if "Error: Cannot read file" in result.stderr:
|
| 276 |
+
raise gr.Error(f"Blender reported an error reading an input file during {step_name}. Check paths and file integrity.")
|
| 277 |
+
elif "Error:" in result.stderr: # Catch generic Blender errors
|
| 278 |
+
print(f"WARNING: Potential Blender error message found in STDERR for {step_name} despite success exit code.")
|
| 279 |
# Add other specific Blender error checks if needed
|
| 280 |
|
| 281 |
+
except subprocess.TimeoutExpired:
|
| 282 |
+
print(f"ERROR: {step_name} timed out after 30 minutes.")
|
| 283 |
+
raise gr.Error(f"Processing step '{step_name}' timed out. Please try with a simpler model or check logs.")
|
| 284 |
except subprocess.CalledProcessError as e:
|
| 285 |
print(f"ERROR during {step_name}: Subprocess failed!")
|
| 286 |
print(f"Command: {' '.join(e.cmd)}")
|
|
|
|
| 288 |
print(f"--- {step_name} STDOUT ---:\n{e.stdout}")
|
| 289 |
print(f"--- {step_name} STDERR ---:\n{e.stderr}")
|
| 290 |
error_summary = e.stderr.strip().splitlines()
|
| 291 |
+
last_lines = "\n".join(error_summary[-15:]) if error_summary else "No stderr output."
|
| 292 |
+
|
| 293 |
+
specific_error = "Unknown error."
|
| 294 |
+
# Check common Python/PyTorch/Blender errors in stderr
|
| 295 |
+
if "ModuleNotFoundError: No module named 'bpy'" in e.stderr:
|
| 296 |
+
specific_error = "The 'bpy' module could not be imported by the script. Check installation in Blender's Python (via setup_blender.sh)."
|
| 297 |
+
elif "ModuleNotFoundError: No module named 'flash_attn'" in e.stderr:
|
| 298 |
+
specific_error = "The 'flash_attn' module is missing or failed to import. It might have failed during installation. Check setup_blender.sh logs."
|
| 299 |
+
elif "ModuleNotFoundError: No module named 'src'" in e.stderr:
|
| 300 |
+
specific_error = "UniRig script failed to import its own 'src' module. Check PYTHONPATH and CWD for the subprocess."
|
| 301 |
+
elif "ModuleNotFoundError" in e.stderr or "ImportError" in e.stderr:
|
| 302 |
+
specific_error = f"An import error occurred. Check library installations. Details: {last_lines}"
|
| 303 |
+
elif "OutOfMemoryError" in e.stderr or "CUDA out of memory" in e.stderr:
|
| 304 |
+
specific_error = "CUDA out of memory. Try a smaller model or a Space with more GPU RAM."
|
| 305 |
+
elif "hydra.errors.ConfigCompositionException" in e.stderr:
|
| 306 |
+
specific_error = f"Hydra configuration error. Check the arguments passed to run.py: {script_args}. Details: {last_lines}"
|
| 307 |
+
elif "Error: Cannot read file" in e.stderr:
|
| 308 |
+
specific_error = f"Blender could not read an input file. Check paths: {last_lines}"
|
| 309 |
+
elif "Error:" in e.stderr: # Generic Blender error
|
| 310 |
+
specific_error = f"Blender reported an error. Details: {last_lines}"
|
| 311 |
else:
|
| 312 |
+
specific_error = f"Check logs. Last error lines:\n{last_lines}"
|
| 313 |
+
raise gr.Error(f"Error in UniRig '{step_name}'. {specific_error}")
|
| 314 |
|
| 315 |
except FileNotFoundError:
|
| 316 |
# This error means blender executable or the python script wasn't found
|
| 317 |
+
print(f"ERROR: Could not find Blender executable '{blender_executable_to_use}' or script '{unirig_run_script_path}' for {step_name}.")
|
| 318 |
print(f"Attempted command: {' '.join(cmd)}")
|
| 319 |
raise gr.Error(f"Setup error for UniRig '{step_name}'. Blender or Python script not found.")
|
| 320 |
|
|
|
|
| 331 |
def rig_glb_mesh_multistep(input_glb_file_obj):
|
| 332 |
"""
|
| 333 |
Main Gradio function to rig a GLB mesh using UniRig's multi-step process.
|
| 334 |
+
Orchestrates calls to run_unirig_command for each step, executing run.py via Blender's Python.
|
| 335 |
"""
|
| 336 |
+
# Check readiness before proceeding
|
| 337 |
+
if not blender_executable_to_use:
|
| 338 |
+
# Use gr.Warning or gr.Info for non-blocking user feedback
|
| 339 |
+
gr.Info("System setup might still be in progress (Blender not found yet). Please wait a moment or check logs if this persists.")
|
| 340 |
+
return None # Return None for the output component
|
| 341 |
+
if not bpy_import_ok:
|
| 342 |
+
gr.Info("System setup might still be in progress (bpy import test failed). Please wait or check logs.")
|
| 343 |
+
return None
|
| 344 |
+
|
| 345 |
try:
|
| 346 |
+
patch_asset_py() # If still needed
|
| 347 |
except Exception as e:
|
| 348 |
+
print(f"Ignoring patch error: {e}")
|
| 349 |
|
| 350 |
# --- Input Validation ---
|
| 351 |
+
if input_glb_file_obj is None:
|
| 352 |
+
gr.Warning("No input file provided.")
|
| 353 |
+
return None # Return None for the output component
|
| 354 |
+
input_glb_path = input_glb_file_obj # Gradio File(type="filepath") gives path string
|
| 355 |
print(f"Input GLB path received: {input_glb_path}")
|
| 356 |
if not os.path.exists(input_glb_path): raise gr.Error(f"Input file path does not exist: {input_glb_path}")
|
| 357 |
if not input_glb_path.lower().endswith(".glb"): raise gr.Error("Invalid file type. Please upload a .glb file.")
|
|
|
|
| 363 |
try:
|
| 364 |
# --- Define File Paths ---
|
| 365 |
base_name = os.path.splitext(os.path.basename(input_glb_path))[0]
|
| 366 |
+
# Ensure paths are absolute for the subprocess
|
| 367 |
abs_input_glb_path = os.path.abspath(input_glb_path)
|
| 368 |
abs_skeleton_output_path = os.path.join(processing_temp_dir, f"{base_name}_skeleton.fbx")
|
| 369 |
abs_skin_output_path = os.path.join(processing_temp_dir, f"{base_name}_skin.fbx")
|
| 370 |
abs_final_rigged_glb_path = os.path.join(processing_temp_dir, f"{base_name}_rigged_final.glb")
|
| 371 |
|
| 372 |
+
unirig_script_to_run = UNIRIG_RUN_PY # Path to UniRig/run.py
|
| 373 |
+
|
| 374 |
+
# --- Determine Device for UniRig ---
|
| 375 |
+
# Use CUDA if available in the Gradio env, otherwise CPU. Pass explicitly.
|
| 376 |
+
unirig_device_arg = "device=cpu"
|
| 377 |
+
if DEVICE.type == 'cuda':
|
| 378 |
+
# UniRig examples often use cuda:0 explicitly for Hydra config
|
| 379 |
+
unirig_device_arg = "device=cuda:0"
|
| 380 |
+
print(f"UniRig steps will attempt to use device argument: {unirig_device_arg}")
|
| 381 |
|
| 382 |
+
# --- Execute UniRig Steps using Hydra format ---
|
| 383 |
+
# UniRig uses Hydra (run.py --config-name=X with key=value ...)
|
| 384 |
|
| 385 |
# Step 1: Skeleton Prediction
|
| 386 |
print("\nStarting Step 1: Predicting Skeleton...")
|
|
|
|
|
|
|
| 387 |
skeleton_args = [
|
| 388 |
+
"--config-name", "skeleton_config", "with", # Hydra syntax
|
| 389 |
+
f"input={abs_input_glb_path}",
|
| 390 |
+
f"output={abs_skeleton_output_path}",
|
| 391 |
+
unirig_device_arg
|
| 392 |
+
# Add other optional args from generate_skeleton.sh if needed, e.g.:
|
| 393 |
+
# "seed=42", "verbose=True"
|
| 394 |
]
|
| 395 |
+
run_unirig_command(unirig_script_to_run, skeleton_args, "Skeleton Prediction")
|
|
|
|
|
|
|
| 396 |
if not os.path.exists(abs_skeleton_output_path):
|
| 397 |
raise gr.Error("Skeleton prediction failed. Output file not created. Check logs.")
|
| 398 |
print("Step 1: Skeleton Prediction completed.")
|
| 399 |
|
| 400 |
# Step 2: Skinning Weight Prediction
|
| 401 |
print("\nStarting Step 2: Predicting Skinning Weights...")
|
|
|
|
|
|
|
| 402 |
skin_args = [
|
| 403 |
+
"--config-name", "skin_config", "with", # Hydra syntax
|
| 404 |
+
f"input={abs_skeleton_output_path}", # Uses the skeleton from previous step
|
| 405 |
+
f"output={abs_skin_output_path}",
|
| 406 |
+
unirig_device_arg
|
| 407 |
+
# Add other optional args from generate_skin.sh if needed, e.g.:
|
| 408 |
+
# "verbose=True"
|
| 409 |
]
|
| 410 |
+
run_unirig_command(unirig_script_to_run, skin_args, "Skinning Prediction")
|
| 411 |
if not os.path.exists(abs_skin_output_path):
|
| 412 |
raise gr.Error("Skinning prediction failed. Output file not created. Check logs.")
|
| 413 |
print("Step 2: Skinning Prediction completed.")
|
| 414 |
|
| 415 |
+
# Step 3: Merge Results
|
| 416 |
print("\nStarting Step 3: Merging Results...")
|
|
|
|
|
|
|
| 417 |
merge_args = [
|
| 418 |
+
"--config-name", "merge_config", "with", # Hydra syntax
|
| 419 |
+
f"source_path={abs_skin_output_path}", # Rigged data (skeleton + skin)
|
| 420 |
+
f"target_path={abs_input_glb_path}", # Original mesh (for attributes, reference)
|
| 421 |
+
f"output_path={abs_final_rigged_glb_path}",
|
| 422 |
+
"mode=skin", # Explicitly set based on typical workflow
|
| 423 |
+
unirig_device_arg
|
| 424 |
+
# Add other optional args from merge.sh if needed
|
| 425 |
]
|
| 426 |
+
run_unirig_command(unirig_script_to_run, merge_args, "Merging Results")
|
| 427 |
if not os.path.exists(abs_final_rigged_glb_path):
|
| 428 |
raise gr.Error("Merging process failed. Final rigged GLB file not created. Check logs.")
|
| 429 |
print("Step 3: Merging completed.")
|
| 430 |
|
| 431 |
# --- Return Result ---
|
| 432 |
print(f"Successfully generated rigged model: {abs_final_rigged_glb_path}")
|
| 433 |
+
# Use gr.update to explicitly update the Model3D component
|
| 434 |
+
return gr.update(value=abs_final_rigged_glb_path)
|
| 435 |
+
|
| 436 |
+
except gr.Error as e: # Catch Gradio errors specifically to re-raise
|
| 437 |
+
print(f"A Gradio Error occurred: {e}")
|
| 438 |
+
# Cleanup temp dir before re-raising
|
| 439 |
+
if os.path.exists(processing_temp_dir):
|
| 440 |
+
shutil.rmtree(processing_temp_dir)
|
| 441 |
+
print(f"Cleaned up temp dir: {processing_temp_dir}")
|
| 442 |
+
raise e # Re-raise the Gradio error
|
| 443 |
except Exception as e:
|
| 444 |
print(f"An unexpected error occurred in rig_glb_mesh_multistep: {e}")
|
| 445 |
import traceback; traceback.print_exc()
|
| 446 |
+
# Cleanup temp dir before raising Gradio error
|
| 447 |
+
if os.path.exists(processing_temp_dir):
|
| 448 |
+
shutil.rmtree(processing_temp_dir)
|
| 449 |
+
print(f"Cleaned up temp dir: {processing_temp_dir}")
|
| 450 |
+
raise gr.Error(f"An unexpected error occurred: {str(e)[:500]}. Check logs for details.")
|
| 451 |
+
# finally: # Cleanup is handled within except blocks to ensure it happens before raising
|
| 452 |
|
| 453 |
|
| 454 |
# --- Gradio Interface Definition ---
|
|
|
|
| 459 |
font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"],
|
| 460 |
)
|
| 461 |
|
| 462 |
+
# Check critical components before building the interface
|
| 463 |
+
startup_error_message = None
|
| 464 |
+
if not blender_executable_to_use:
|
| 465 |
+
startup_error_message = (f"CRITICAL STARTUP ERROR: Blender executable could not be located or setup failed. Check logs.")
|
| 466 |
+
elif not os.path.isdir(UNIRIG_REPO_DIR):
|
| 467 |
startup_error_message = (f"CRITICAL STARTUP ERROR: UniRig repository not found at {UNIRIG_REPO_DIR}.")
|
| 468 |
+
elif not os.path.exists(UNIRIG_RUN_PY):
|
| 469 |
+
startup_error_message = (f"CRITICAL STARTUP ERROR: UniRig run.py not found at {UNIRIG_RUN_PY}.")
|
| 470 |
+
# Add bpy_import_ok check? Maybe too strict for startup, handle in rig_glb_mesh_multistep
|
| 471 |
+
# elif not bpy_import_ok:
|
| 472 |
+
# startup_error_message = (f"CRITICAL STARTUP ERROR: Failed initial 'bpy' import test using Blender.")
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
if startup_error_message:
|
| 476 |
+
print(startup_error_message)
|
| 477 |
+
with gr.Blocks(theme=theme) as iface:
|
| 478 |
+
gr.Markdown(f"# Application Startup Error\n\n{startup_error_message}\n\nPlease check the Space logs for more details.")
|
| 479 |
else:
|
| 480 |
+
# Build the normal interface if checks pass
|
| 481 |
+
with gr.Blocks(theme=theme) as iface:
|
| 482 |
+
gr.Markdown(
|
| 483 |
+
f"""
|
| 484 |
+
# UniRig Auto-Rigger (Blender {BLENDER_PYTHON_VERSION_DIR} / Python {BLENDER_PYTHON_VERSION})
|
| 485 |
+
Upload a 3D mesh in `.glb` format. This application uses UniRig via Blender's Python interface to predict skeleton and skinning weights.
|
| 486 |
+
* Running main app on Python `{sys.version.split()[0]}`, UniRig steps use Blender's Python `{BLENDER_PYTHON_VERSION}`.
|
| 487 |
+
* Utilizing device: **{DEVICE.type.upper()}** (via ZeroGPU if available).
|
| 488 |
+
* UniRig Source: [https://github.com/VAST-AI-Research/UniRig](https://github.com/VAST-AI-Research/UniRig)
|
| 489 |
+
"""
|
| 490 |
+
)
|
| 491 |
+
with gr.Row():
|
| 492 |
+
with gr.Column(scale=1):
|
| 493 |
+
input_model = gr.File(
|
| 494 |
+
label="Upload .glb Mesh File",
|
| 495 |
+
type="filepath", # Use filepath for direct path access
|
| 496 |
+
file_types=[".glb"]
|
| 497 |
+
)
|
| 498 |
+
submit_button = gr.Button("Rig Model", variant="primary")
|
| 499 |
+
with gr.Column(scale=2):
|
| 500 |
+
output_model = gr.Model3D(
|
| 501 |
+
label="Rigged 3D Model (.glb)",
|
| 502 |
+
clear_color=[0.8, 0.8, 0.8, 1.0],
|
| 503 |
+
# Add interaction settings if desired
|
| 504 |
+
# camera_position=(0, 0, 5)
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
# Connect button click to the processing function
|
| 508 |
+
submit_button.click(
|
| 509 |
+
fn=rig_glb_mesh_multistep,
|
| 510 |
+
inputs=[input_model],
|
| 511 |
+
outputs=[output_model]
|
| 512 |
+
)
|
| 513 |
|
| 514 |
# --- Launch the Application ---
|
| 515 |
if __name__ == "__main__":
|
| 516 |
if 'iface' in locals():
|
| 517 |
print("Launching Gradio interface...")
|
| 518 |
+
# Set share=True for public link if needed, debug=True for more logs locally
|
| 519 |
+
iface.launch(ssr_mode=False) # Disable SSR as it was experimental
|
| 520 |
else:
|
| 521 |
print("ERROR: Gradio interface not created due to startup errors.")
|
| 522 |
|