jkorstad commited on
Commit
f104497
·
verified ·
1 Parent(s): 6195ad2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +184 -164
app.py CHANGED
@@ -23,7 +23,7 @@ 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):
@@ -36,12 +36,13 @@ 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:
39
- setup_result = subprocess.run(["bash", SETUP_SCRIPT], check=True, capture_output=True, text=True)
 
40
  print("Setup script executed successfully.")
41
  print(f"Setup STDOUT:\n{setup_result.stdout}")
42
  if setup_result.stderr: print(f"Setup STDERR:\n{setup_result.stderr}")
43
 
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}")
@@ -50,21 +51,30 @@ else:
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(
69
  [blender_executable_to_use, "--background", "--python-expr", test_script_content],
70
  capture_output=True, text=True, check=True, timeout=30 # Add timeout
@@ -73,46 +83,55 @@ if blender_executable_to_use:
73
  print("Successfully imported 'bpy' using Blender executable.")
74
  bpy_import_ok = True
75
  else:
 
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
 
 
 
89
  if not os.path.isdir(UNIRIG_REPO_DIR):
 
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:
111
  print("Warning: Gradio environment CUDA not available.")
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,9 +141,8 @@ def patch_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:
@@ -134,15 +152,11 @@ def patch_asset_py():
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
 
@@ -153,13 +167,13 @@ def patch_asset_py():
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
  """
@@ -169,9 +183,9 @@ def run_unirig_command(unirig_run_script_path: str, script_args: List[str], step
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)
@@ -180,76 +194,24 @@ def run_unirig_command(unirig_run_script_path: str, script_args: List[str], step
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} ---")
@@ -257,7 +219,7 @@ def run_unirig_command(unirig_run_script_path: str, script_args: List[str], step
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
@@ -265,18 +227,15 @@ def run_unirig_command(unirig_run_script_path: str, script_args: List[str], step
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
272
  if result.stderr:
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.")
@@ -291,21 +250,21 @@ def run_unirig_command(unirig_run_script_path: str, script_args: List[str], step
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:
@@ -313,11 +272,8 @@ def run_unirig_command(unirig_run_script_path: str, script_args: List[str], step
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
-
321
  except Exception as e_general:
322
  print(f"An unexpected Python exception occurred in run_unirig_command for {step_name}: {e_general}")
323
  import traceback
@@ -331,30 +287,32 @@ def run_unirig_command(unirig_run_script_path: str, script_args: List[str], step
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.")
 
 
358
 
359
  # --- Setup Temporary Directory ---
360
  processing_temp_dir = tempfile.mkdtemp(prefix="unirig_processing_")
@@ -363,34 +321,99 @@ def rig_glb_mesh_multistep(input_glb_file_obj):
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):
@@ -400,12 +423,11 @@ def rig_glb_mesh_multistep(input_glb_file_obj):
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):
@@ -415,13 +437,13 @@ def rig_glb_mesh_multistep(input_glb_file_obj):
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):
@@ -430,25 +452,25 @@ def rig_glb_mesh_multistep(input_glb_file_obj):
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,40 +481,38 @@ theme = gr.themes.Soft(
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")
@@ -500,8 +520,6 @@ else:
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
@@ -513,10 +531,12 @@ else:
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
 
 
23
 
24
  SETUP_SCRIPT = os.path.join(os.path.dirname(__file__), "setup_blender.sh")
25
 
26
+ # --- Initial Checks ---
27
  print("--- Environment Checks ---")
28
  blender_executable_to_use = None # Use the main blender executable
29
  if os.path.exists(BLENDER_EXEC):
 
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:
39
+ # Run setup script if Blender not found
40
+ setup_result = subprocess.run(["bash", SETUP_SCRIPT], check=True, capture_output=True, text=True, timeout=600) # 10 min timeout for setup
41
  print("Setup script executed successfully.")
42
  print(f"Setup STDOUT:\n{setup_result.stdout}")
43
  if setup_result.stderr: print(f"Setup STDERR:\n{setup_result.stderr}")
44
 
45
+ # Re-check for executable after running setup
46
  if os.path.exists(BLENDER_EXEC):
47
  blender_executable_to_use = BLENDER_EXEC
48
  print(f"Blender executable now found at: {BLENDER_EXEC}")
 
51
  print(f"Blender executable now found via symlink: {BLENDER_EXEC_SYMLINK}")
52
 
53
  if not blender_executable_to_use:
54
+ # If still not found after setup, raise a clear error
55
  raise RuntimeError(f"Setup script ran but Blender executable still not found at {BLENDER_EXEC} or {BLENDER_EXEC_SYMLINK}.")
56
 
57
+ except subprocess.TimeoutExpired:
58
+ print(f"ERROR: Setup script timed out: {SETUP_SCRIPT}")
59
+ raise gr.Error("Setup script timed out. The Space might be too slow or setup is stuck.")
60
  except subprocess.CalledProcessError as e:
61
  print(f"ERROR running setup script: {SETUP_SCRIPT}\nStderr: {e.stderr}")
62
+ # Raise a Gradio error to notify the user
63
  raise gr.Error(f"Failed to execute setup script. Check logs. Stderr: {e.stderr[-500:]}")
64
  except Exception as e:
65
+ # Catch any other exceptions during setup
66
  raise gr.Error(f"Unexpected error running setup script '{SETUP_SCRIPT}': {e}")
67
  else:
68
+ # If setup script itself is missing
69
  raise gr.Error(f"Blender executable not found and setup script missing: {SETUP_SCRIPT}")
70
 
71
  # Verify bpy import using the found Blender executable
72
  bpy_import_ok = False
73
  if blender_executable_to_use:
74
  try:
75
+ print("Testing bpy import via Blender...")
76
  test_script_content = "import bpy; print('bpy imported successfully')"
77
+ # Use --python-expr for the bpy test
78
  test_result = subprocess.run(
79
  [blender_executable_to_use, "--background", "--python-expr", test_script_content],
80
  capture_output=True, text=True, check=True, timeout=30 # Add timeout
 
83
  print("Successfully imported 'bpy' using Blender executable.")
84
  bpy_import_ok = True
85
  else:
86
+ # Log warning but don't necessarily stop startup
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
  print("WARNING: 'bpy' import test via Blender timed out.")
91
  except subprocess.CalledProcessError as e:
92
+ # Log specific error if bpy import fails
93
  print(f"WARNING: Failed to import 'bpy' using Blender executable:\nSTDOUT:{e.stdout}\nSTDERR:{e.stderr}")
94
  except Exception as e:
95
+ # Catch any other exception during the test
96
  print(f"WARNING: Unexpected error during 'bpy' import test: {e}")
97
  else:
98
+ # This case should ideally not be reached if setup logic is correct
99
  print("WARNING: Cannot test bpy import as Blender executable was not found.")
100
 
101
 
102
+ # Check for UniRig repository and run.py
103
+ unirig_repo_ok = False
104
+ unirig_run_py_ok = False
105
+ UNIRIG_RUN_PY = os.path.join(UNIRIG_REPO_DIR, "run.py")
106
  if not os.path.isdir(UNIRIG_REPO_DIR):
107
+ # Critical error if UniRig repo is missing
108
  raise gr.Error(f"UniRig repository missing at: {UNIRIG_REPO_DIR}. Ensure it's cloned correctly.")
109
  else:
110
  print(f"UniRig repository found at: {UNIRIG_REPO_DIR}")
111
+ unirig_repo_ok = True
112
+ # Check specifically for run.py within the repo
113
  if not os.path.exists(UNIRIG_RUN_PY):
114
+ # Critical error if run.py is missing
115
  raise gr.Error(f"UniRig's run.py not found at {UNIRIG_RUN_PY}. Check UniRig clone.")
116
+ else:
117
+ unirig_run_py_ok = True
118
 
119
 
120
+ # Check PyTorch and CUDA for Gradio environment (less critical for startup)
121
  DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
122
  print(f"Gradio environment using device: {DEVICE}")
123
  if DEVICE.type == 'cuda':
124
  try:
125
  print(f"Gradio CUDA Device Name: {torch.cuda.get_device_name(0)}")
 
 
126
  print(f"Gradio PyTorch CUDA Built Version: {torch.version.cuda}")
127
  except Exception as e:
128
+ print(f"Could not get Gradio CUDA device details: {e}")
129
  else:
130
  print("Warning: Gradio environment CUDA not available.")
131
 
132
  print("--- End Environment Checks ---")
133
 
134
+ # --- Helper Functions ---
135
  def patch_asset_py():
136
  """Temporary patch to fix type hinting error in UniRig's asset.py"""
137
  asset_py_path = os.path.join(UNIRIG_REPO_DIR, "src", "data", "asset.py")
 
141
  return
142
 
143
  with open(asset_py_path, "r") as f: content = f.read()
 
144
  problematic_line = "meta: Union[Dict[str, ...], None]=None"
145
+ corrected_line = "meta: Union[Dict[str, Any], None]=None"
146
  typing_import = "from typing import Any"
147
 
148
  if corrected_line in content:
 
152
 
153
  print("Applying patch to asset.py...")
154
  content = content.replace(problematic_line, corrected_line)
 
155
  if typing_import not in content:
156
  if "from typing import" in content:
 
157
  content = content.replace("from typing import", f"{typing_import}\nfrom typing import", 1)
158
  else:
 
159
  content = f"{typing_import}\n{content}"
 
160
  with open(asset_py_path, "w") as f: f.write(content)
161
  print("Successfully patched asset.py")
162
 
 
167
 
168
  # Decorator for ZeroGPU if needed
169
  @spaces.GPU
170
+ def run_unirig_command(python_script_path: str, script_args: List[str], step_name: str):
171
  """
172
  Runs a specific UniRig PYTHON script (.py) using the Blender executable
173
  in background mode (`blender --background --python script.py -- args`).
174
 
175
  Args:
176
+ python_script_path: Absolute path to the Python script to execute within Blender.
177
  script_args: A list of command-line arguments FOR THE PYTHON SCRIPT.
178
  step_name: Name of the step for logging.
179
  """
 
183
  # --- Environment Setup for Subprocess ---
184
  process_env = os.environ.copy()
185
 
186
+ # Explicitly add UniRig root AND its 'src' directory to PYTHONPATH
187
+ unirig_src_dir = os.path.join(UNIRIG_REPO_DIR, 'src')
188
+ pythonpath_parts = [UNIRIG_REPO_DIR, unirig_src_dir] # Add both
189
  existing_pythonpath = process_env.get('PYTHONPATH', '')
190
  if existing_pythonpath:
191
  pythonpath_parts.append(existing_pythonpath)
 
194
 
195
  # LD_LIBRARY_PATH: Inherit system path (for CUDA) and add Blender's libraries.
196
  blender_main_lib_path = os.path.join(BLENDER_INSTALL_DIR, "lib")
197
+ blender_python_lib_path = os.path.join(BLENDER_PYTHON_DIR, "lib")
198
  ld_path_parts = []
 
199
  if os.path.exists(blender_main_lib_path): ld_path_parts.append(blender_main_lib_path)
200
  if os.path.exists(blender_python_lib_path): ld_path_parts.append(blender_python_lib_path)
 
201
  existing_ld_path = process_env.get('LD_LIBRARY_PATH', '')
202
  if existing_ld_path: ld_path_parts.append(existing_ld_path)
 
203
  if ld_path_parts:
204
  process_env["LD_LIBRARY_PATH"] = os.pathsep.join(filter(None, ld_path_parts))
205
  print(f"Subprocess LD_LIBRARY_PATH: {process_env.get('LD_LIBRARY_PATH', 'Not set')}")
206
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
 
208
+ # --- Execute Command ---
209
+ # Command structure: blender --background --python script.py -- args
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  cmd = [
211
  blender_executable_to_use,
212
  "--background",
213
+ "--python", python_script_path,
214
+ "--" # Separator between blender args and script args
215
  ] + script_args
216
 
217
  print(f"\n--- Running UniRig Step: {step_name} ---")
 
219
 
220
  try:
221
  # Execute Blender with the Python script.
222
+ # CWD is crucial for relative imports and finding config files.
223
  result = subprocess.run(
224
  cmd,
225
  cwd=UNIRIG_REPO_DIR, # CWD is set to UniRig repo root
 
227
  text=True,
228
  check=True, # Raises CalledProcessError on non-zero exit codes
229
  env=process_env, # Pass the modified environment
230
+ timeout=1800 # 30 minutes timeout
231
  )
232
  print(f"{step_name} STDOUT:\n{result.stdout}")
 
233
  if result.stderr:
234
  print(f"{step_name} STDERR (Info/Warnings):\n{result.stderr}")
235
+ # More robust check for errors in stderr even on success
236
+ stderr_lower = result.stderr.lower()
237
+ if "error" in stderr_lower or "failed" in stderr_lower or "traceback" in stderr_lower:
238
+ print(f"WARNING: Potential error messages found in STDERR for {step_name} despite success exit code.")
 
 
239
 
240
  except subprocess.TimeoutExpired:
241
  print(f"ERROR: {step_name} timed out after 30 minutes.")
 
250
  last_lines = "\n".join(error_summary[-15:]) if error_summary else "No stderr output."
251
 
252
  specific_error = "Unknown error."
253
+ # Refine error checking based on common patterns
254
+ if "ModuleNotFoundError: No module named 'src'" in e.stderr:
255
+ specific_error = "UniRig script failed to import its own 'src' module. Check PYTHONPATH and CWD for the subprocess. See diagnostic info above."
256
+ elif "ModuleNotFoundError: No module named 'bpy'" in e.stderr:
257
  specific_error = "The 'bpy' module could not be imported by the script. Check installation in Blender's Python (via setup_blender.sh)."
258
  elif "ModuleNotFoundError: No module named 'flash_attn'" in e.stderr:
259
  specific_error = "The 'flash_attn' module is missing or failed to import. It might have failed during installation. Check setup_blender.sh logs."
 
 
260
  elif "ModuleNotFoundError" in e.stderr or "ImportError" in e.stderr:
261
  specific_error = f"An import error occurred. Check library installations. Details: {last_lines}"
262
  elif "OutOfMemoryError" in e.stderr or "CUDA out of memory" in e.stderr:
263
  specific_error = "CUDA out of memory. Try a smaller model or a Space with more GPU RAM."
264
  elif "hydra.errors.ConfigCompositionException" in e.stderr:
265
  specific_error = f"Hydra configuration error. Check the arguments passed to run.py: {script_args}. Details: {last_lines}"
266
+ elif "Error: Cannot read file" in e.stderr: # General file read error
267
+ specific_error = f"Blender could not read an input/output file. Check paths. Details: {last_lines}"
268
  elif "Error:" in e.stderr: # Generic Blender error
269
  specific_error = f"Blender reported an error. Details: {last_lines}"
270
  else:
 
272
  raise gr.Error(f"Error in UniRig '{step_name}'. {specific_error}")
273
 
274
  except FileNotFoundError:
275
+ print(f"ERROR: Could not find Blender executable '{blender_executable_to_use}' or script '{python_script_path}' for {step_name}.")
 
 
276
  raise gr.Error(f"Setup error for UniRig '{step_name}'. Blender or Python script not found.")
 
277
  except Exception as e_general:
278
  print(f"An unexpected Python exception occurred in run_unirig_command for {step_name}: {e_general}")
279
  import traceback
 
287
  def rig_glb_mesh_multistep(input_glb_file_obj):
288
  """
289
  Main Gradio function to rig a GLB mesh using UniRig's multi-step process.
 
290
  """
291
+ # Perform readiness checks at the start of the function call
292
  if not blender_executable_to_use:
293
+ gr.Warning("System not ready: Blender executable not found. Please wait or check logs.")
294
+ return None
295
+ if not unirig_repo_ok or not unirig_run_py_ok:
296
+ gr.Warning("System not ready: UniRig repository or run.py script not found. Check setup.")
 
297
  return None
298
+ if not bpy_import_ok:
299
+ gr.Warning("System warning: Initial 'bpy' import test failed. Attempting to proceed, but errors may occur.")
300
 
301
  try:
302
+ patch_asset_py() # Apply patch if needed
303
  except Exception as e:
304
  print(f"Ignoring patch error: {e}")
305
 
306
  # --- Input Validation ---
307
  if input_glb_file_obj is None:
308
+ gr.Info("Please upload a .glb file first.")
309
+ return None
310
+ input_glb_path = input_glb_file_obj
311
  print(f"Input GLB path received: {input_glb_path}")
312
+ if not isinstance(input_glb_path, str) or not os.path.exists(input_glb_path):
313
+ raise gr.Error(f"Invalid input file path received: {input_glb_path}")
314
+ if not input_glb_path.lower().endswith(".glb"):
315
+ raise gr.Error("Invalid file type. Please upload a .glb file.")
316
 
317
  # --- Setup Temporary Directory ---
318
  processing_temp_dir = tempfile.mkdtemp(prefix="unirig_processing_")
 
321
  try:
322
  # --- Define File Paths ---
323
  base_name = os.path.splitext(os.path.basename(input_glb_path))[0]
 
324
  abs_input_glb_path = os.path.abspath(input_glb_path)
325
  abs_skeleton_output_path = os.path.join(processing_temp_dir, f"{base_name}_skeleton.fbx")
326
  abs_skin_output_path = os.path.join(processing_temp_dir, f"{base_name}_skin.fbx")
327
  abs_final_rigged_glb_path = os.path.join(processing_temp_dir, f"{base_name}_rigged_final.glb")
328
 
329
+ unirig_script_to_run = UNIRIG_RUN_PY
330
+
331
+ # --- Run Blender Python Environment Diagnostic Test ---
332
+ print("\n--- Running Blender Python Environment Diagnostic Test ---")
333
+ diagnostic_script_content = f"""
334
+ import sys
335
+ import os
336
+ import traceback
337
+
338
+ print("--- Diagnostic Info from Blender Python ---")
339
+ print(f"Python Executable: {{sys.executable}}")
340
+ print(f"Current Working Directory (inside script): {{os.getcwd()}}") # Should be UNIRIG_REPO_DIR
341
+ print("sys.path:")
342
+ for p in sys.path:
343
+ print(f" {{p}}")
344
+ print("\\nPYTHONPATH Environment Variable (as seen by script):")
345
+ print(os.environ.get('PYTHONPATH', 'PYTHONPATH not set or empty'))
346
+ print("\\n--- Attempting Imports ---")
347
+ try:
348
+ import bpy
349
+ print("SUCCESS: 'bpy' imported.")
350
+ except ImportError as e:
351
+ print(f"FAILED to import 'bpy': {{e}}")
352
+ traceback.print_exc()
353
+ except Exception as e:
354
+ print(f"FAILED to import 'bpy' with other error: {{e}}")
355
+ traceback.print_exc()
356
+
357
+ try:
358
+ # Check if CWD is correct and src is importable
359
+ print("\\nChecking for 'src' in CWD (should be UniRig repo root):")
360
+ if os.path.isdir('src'):
361
+ print(" 'src' directory FOUND in CWD.")
362
+ if os.path.isfile(os.path.join('src', '__init__.py')):
363
+ print(" 'src/__init__.py' FOUND.")
364
+ else:
365
+ print(" WARNING: 'src/__init__.py' NOT FOUND. 'src' may not be treated as a package.")
366
+ else:
367
+ print(" 'src' directory NOT FOUND in CWD.")
368
+
369
+ # Attempt the import that failed previously
370
+ print("\\nAttempting: from src.inference.download import download")
371
+ from src.inference.download import download
372
+ print("SUCCESS: 'from src.inference.download import download' worked.")
373
+ except ImportError as e:
374
+ print(f"FAILED: 'from src.inference.download import download': {{e}}")
375
+ traceback.print_exc()
376
+ except Exception as e:
377
+ print(f"FAILED: 'from src.inference.download import download' with other error: {{e}}")
378
+ traceback.print_exc()
379
+ print("--- End Diagnostic Info ---")
380
+ """
381
+ diagnostic_script_path = os.path.join(processing_temp_dir, "env_diagnostic_test.py") # Use temp dir
382
+ with open(diagnostic_script_path, "w") as f:
383
+ f.write(diagnostic_script_content)
384
+
385
+ try:
386
+ # Run the diagnostic script using the *exact same* command structure
387
+ # Pass an empty list for script_args as the script takes none
388
+ run_unirig_command(diagnostic_script_path, [], "Blender Env Diagnostic")
389
+ print("--- Finished Blender Python Environment Diagnostic Test ---\n")
390
+ except Exception as e_diag:
391
+ # If the diagnostic fails, raise an error - no point continuing
392
+ print(f"ERROR during diagnostic test execution: {e_diag}")
393
+ # Clean up the script file before raising
394
+ if os.path.exists(diagnostic_script_path): os.remove(diagnostic_script_path)
395
+ raise gr.Error(f"Blender environment diagnostic failed. Cannot proceed. Check logs above for details. Error: {str(e_diag)[:500]}")
396
+ finally:
397
+ # Ensure cleanup even if run_unirig_command doesn't raise but has issues
398
+ if os.path.exists(diagnostic_script_path): os.remove(diagnostic_script_path)
399
+ # --- END DIAGNOSTIC STEP ---
400
+
401
 
402
  # --- Determine Device for UniRig ---
 
403
  unirig_device_arg = "device=cpu"
404
  if DEVICE.type == 'cuda':
 
405
  unirig_device_arg = "device=cuda:0"
406
  print(f"UniRig steps will attempt to use device argument: {unirig_device_arg}")
407
 
408
+ # --- Execute UniRig Steps ---
 
 
409
  # Step 1: Skeleton Prediction
410
  print("\nStarting Step 1: Predicting Skeleton...")
411
  skeleton_args = [
412
+ "--config-name=skeleton_config",
413
+ "with",
414
  f"input={abs_input_glb_path}",
415
  f"output={abs_skeleton_output_path}",
416
  unirig_device_arg
 
 
417
  ]
418
  run_unirig_command(unirig_script_to_run, skeleton_args, "Skeleton Prediction")
419
  if not os.path.exists(abs_skeleton_output_path):
 
423
  # Step 2: Skinning Weight Prediction
424
  print("\nStarting Step 2: Predicting Skinning Weights...")
425
  skin_args = [
426
+ "--config-name=skin_config",
427
+ "with",
428
+ f"input={abs_skeleton_output_path}",
429
  f"output={abs_skin_output_path}",
430
  unirig_device_arg
 
 
431
  ]
432
  run_unirig_command(unirig_script_to_run, skin_args, "Skinning Prediction")
433
  if not os.path.exists(abs_skin_output_path):
 
437
  # Step 3: Merge Results
438
  print("\nStarting Step 3: Merging Results...")
439
  merge_args = [
440
+ "--config-name=merge_config",
441
+ "with",
442
+ f"source_path={abs_skin_output_path}",
443
+ f"target_path={abs_input_glb_path}",
444
  f"output_path={abs_final_rigged_glb_path}",
445
+ "mode=skin",
446
  unirig_device_arg
 
447
  ]
448
  run_unirig_command(unirig_script_to_run, merge_args, "Merging Results")
449
  if not os.path.exists(abs_final_rigged_glb_path):
 
452
 
453
  # --- Return Result ---
454
  print(f"Successfully generated rigged model: {abs_final_rigged_glb_path}")
455
+ return gr.update(value=abs_final_rigged_glb_path) # Update Gradio output
 
456
 
457
+ except gr.Error as e:
458
  print(f"A Gradio Error occurred: {e}")
459
+ if os.path.exists(processing_temp_dir): shutil.rmtree(processing_temp_dir)
460
+ raise e
 
 
 
461
  except Exception as e:
462
  print(f"An unexpected error occurred in rig_glb_mesh_multistep: {e}")
463
  import traceback; traceback.print_exc()
464
+ if os.path.exists(processing_temp_dir): shutil.rmtree(processing_temp_dir)
 
 
 
465
  raise gr.Error(f"An unexpected error occurred: {str(e)[:500]}. Check logs for details.")
466
+ finally:
467
+ # General cleanup for the temp dir if it still exists (e.g., if no exception occurred)
468
+ if os.path.exists(processing_temp_dir):
469
+ try:
470
+ shutil.rmtree(processing_temp_dir)
471
+ print(f"Cleaned up temp dir: {processing_temp_dir}")
472
+ except Exception as cleanup_e:
473
+ print(f"Error cleaning up temp dir {processing_temp_dir}: {cleanup_e}")
474
 
475
 
476
  # --- Gradio Interface Definition ---
 
481
  font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"],
482
  )
483
 
484
+ # Perform critical checks before defining the interface
485
  startup_error_message = None
486
  if not blender_executable_to_use:
487
  startup_error_message = (f"CRITICAL STARTUP ERROR: Blender executable could not be located or setup failed. Check logs.")
488
+ elif not unirig_repo_ok:
489
  startup_error_message = (f"CRITICAL STARTUP ERROR: UniRig repository not found at {UNIRIG_REPO_DIR}.")
490
+ elif not unirig_run_py_ok:
491
  startup_error_message = (f"CRITICAL STARTUP ERROR: UniRig run.py not found at {UNIRIG_RUN_PY}.")
 
 
 
492
 
493
 
494
  if startup_error_message:
495
+ # If critical error, display error message instead of interface
496
  print(startup_error_message)
497
  with gr.Blocks(theme=theme) as iface:
498
  gr.Markdown(f"# Application Startup Error\n\n{startup_error_message}\n\nPlease check the Space logs for more details.")
499
  else:
500
+ # Build the normal interface if essential checks pass
501
  with gr.Blocks(theme=theme) as iface:
502
  gr.Markdown(
503
+ f"""
504
+ # UniRig Auto-Rigger (Blender {BLENDER_PYTHON_VERSION_DIR} / Python {BLENDER_PYTHON_VERSION})
505
+ Upload a 3D mesh in `.glb` format. This application uses UniRig via Blender's Python interface to predict skeleton and skinning weights.
506
+ * Running main app on Python `{sys.version.split()[0]}`, UniRig steps use Blender's Python `{BLENDER_PYTHON_VERSION}`.
507
+ * Utilizing device: **{DEVICE.type.upper()}** (via ZeroGPU if available).
508
+ * UniRig Source: [https://github.com/VAST-AI-Research/UniRig](https://github.com/VAST-AI-Research/UniRig)
509
+ """
510
+ )
511
  with gr.Row():
512
  with gr.Column(scale=1):
513
  input_model = gr.File(
514
  label="Upload .glb Mesh File",
515
+ type="filepath",
516
  file_types=[".glb"]
517
  )
518
  submit_button = gr.Button("Rig Model", variant="primary")
 
520
  output_model = gr.Model3D(
521
  label="Rigged 3D Model (.glb)",
522
  clear_color=[0.8, 0.8, 0.8, 1.0],
 
 
523
  )
524
 
525
  # Connect button click to the processing function
 
531
 
532
  # --- Launch the Application ---
533
  if __name__ == "__main__":
534
+ # Check if the interface was successfully created
535
  if 'iface' in locals():
536
  print("Launching Gradio interface...")
537
+ # Ensure share=False for security unless public link is needed
538
+ iface.launch(share=False, ssr_mode=False) # Disable SSR
539
  else:
540
+ # This indicates a startup error occurred before interface creation
541
+ print("ERROR: Gradio interface could not be created due to startup errors. Check logs above.")
542