jkorstad commited on
Commit
2b04489
·
verified ·
1 Parent(s): 9c99a70

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -23
app.py CHANGED
@@ -158,17 +158,16 @@ def run_unirig_command(script_path: str, args: List[str], step_name: str):
158
  args: A list of command-line arguments for the script.
159
  step_name: Name of the step for logging.
160
  """
161
- # Command is now bash + script path + arguments
162
  cmd = ["bash", script_path] + args
163
 
164
  print(f"\n--- Running UniRig Step: {step_name} ---")
165
  print(f"Command: {' '.join(cmd)}")
166
 
167
- # Prepare the environment for the subprocess (shell script)
168
  process_env = os.environ.copy()
169
  unirig_src_dir = os.path.join(UNIRIG_REPO_DIR, "src")
170
 
171
- # 1. Set PYTHONPATH: Blender's site-packages + UniRig source
172
  pythonpath_parts = [
173
  BLENDER_PYTHON_SITE_PACKAGES,
174
  unirig_src_dir,
@@ -177,30 +176,29 @@ def run_unirig_command(script_path: str, args: List[str], step_name: str):
177
  process_env["PYTHONPATH"] = os.pathsep.join(filter(None, pythonpath_parts))
178
  print(f"Subprocess PYTHONPATH: {process_env['PYTHONPATH']}")
179
 
180
- # 2. Set LD_LIBRARY_PATH: Include Blender's Python library directory
181
  blender_lib_path = os.path.join(BLENDER_PYTHON_DIR, "lib")
182
- # Prepend Blender lib path to existing LD_LIBRARY_PATH if it exists
183
  existing_ld_path = process_env.get('LD_LIBRARY_PATH', '')
184
  process_env["LD_LIBRARY_PATH"] = f"{blender_lib_path}{os.pathsep}{existing_ld_path}" if existing_ld_path else blender_lib_path
185
  print(f"Subprocess LD_LIBRARY_PATH: {process_env['LD_LIBRARY_PATH']}")
186
 
187
- # 3. Set PATH: *Prepend* Blender's Python bin directory to the system PATH.
188
- # This makes it the *first* place the shell looks for 'python' or 'python3.11'.
189
- existing_path = process_env.get('PATH', '')
190
- process_env["PATH"] = f"{BLENDER_PYTHON_BIN_DIR}{os.pathsep}{existing_path}"
191
- print(f"Subprocess PATH: {process_env['PATH']}")
192
-
193
-
194
  try:
195
- # Execute the shell script.
196
- # cwd=UNIRIG_REPO_DIR ensures the script runs from the repo's root,
 
 
 
 
 
197
  result = subprocess.run(
198
  cmd,
199
  cwd=UNIRIG_REPO_DIR,
200
  capture_output=True,
201
  text=True,
202
- check=True, # Raises CalledProcessError on non-zero exit codes
203
- env=process_env # Pass the modified environment
204
  )
205
  print(f"{step_name} STDOUT:\n{result.stdout}")
206
  if result.stderr:
@@ -214,19 +212,15 @@ def run_unirig_command(script_path: str, args: List[str], step_name: str):
214
  print(f"--- {step_name} STDERR ---:\n{e.stderr}")
215
  error_summary = e.stderr.strip().splitlines()
216
  last_lines = "\n".join(error_summary[-5:]) if error_summary else "No stderr output."
217
- # Check specifically for bpy/torch import errors within the subprocess stderr
218
  if "ModuleNotFoundError: No module named 'bpy'" in e.stderr:
219
- raise gr.Error(f"Error in UniRig '{step_name}': Script failed to import Blender's 'bpy' module. Check environment setup.")
220
  elif "ImportError: Failed to load PyTorch C extensions" in e.stderr:
221
- raise gr.Error(f"Error in UniRig '{step_name}': Script failed to load PyTorch extensions. Check environment and PyTorch installation within Blender's Python.")
222
  else:
223
- raise gr.Error(f"Error in UniRig '{step_name}'. Check logs. Last error lines:\n{last_lines}")
224
-
225
 
226
  except FileNotFoundError:
227
- # This error means 'bash' or the script_path wasn't found
228
  print(f"ERROR: Could not find executable 'bash' or script '{script_path}' for {step_name}.")
229
- print(f"Attempted command: {' '.join(cmd)}")
230
  raise gr.Error(f"Setup error for UniRig '{step_name}'. 'bash' or script '{os.path.basename(script_path)}' not found.")
231
 
232
  except Exception as e_general:
@@ -235,6 +229,9 @@ def run_unirig_command(script_path: str, args: List[str], step_name: str):
235
  traceback.print_exc()
236
  raise gr.Error(f"Unexpected Python error during '{step_name}' execution: {str(e_general)[:500]}")
237
 
 
 
 
238
  print(f"--- Finished UniRig Step: {step_name} ---")
239
 
240
 
@@ -263,6 +260,19 @@ def rig_glb_mesh_multistep(input_glb_file_obj):
263
  if not input_glb_path.lower().endswith(".glb"):
264
  raise gr.Error("Invalid file type. Please upload a .glb file.")
265
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
  # --- Setup Temporary Directory ---
267
  processing_temp_dir = tempfile.mkdtemp(prefix="unirig_processing_")
268
  print(f"Using temporary processing directory: {processing_temp_dir}")
 
158
  args: A list of command-line arguments for the script.
159
  step_name: Name of the step for logging.
160
  """
 
161
  cmd = ["bash", script_path] + args
162
 
163
  print(f"\n--- Running UniRig Step: {step_name} ---")
164
  print(f"Command: {' '.join(cmd)}")
165
 
166
+ # Prepare the environment for the subprocess
167
  process_env = os.environ.copy()
168
  unirig_src_dir = os.path.join(UNIRIG_REPO_DIR, "src")
169
 
170
+ # 1. Set PYTHONPATH: Blenders site-packages + UniRig source
171
  pythonpath_parts = [
172
  BLENDER_PYTHON_SITE_PACKAGES,
173
  unirig_src_dir,
 
176
  process_env["PYTHONPATH"] = os.pathsep.join(filter(None, pythonpath_parts))
177
  print(f"Subprocess PYTHONPATH: {process_env['PYTHONPATH']}")
178
 
179
+ # 2. Set LD_LIBRARY_PATH: Include Blenders Python library directory
180
  blender_lib_path = os.path.join(BLENDER_PYTHON_DIR, "lib")
 
181
  existing_ld_path = process_env.get('LD_LIBRARY_PATH', '')
182
  process_env["LD_LIBRARY_PATH"] = f"{blender_lib_path}{os.pathsep}{existing_ld_path}" if existing_ld_path else blender_lib_path
183
  print(f"Subprocess LD_LIBRARY_PATH: {process_env['LD_LIBRARY_PATH']}")
184
 
185
+ # 3. Set PATH with a temporary 'python' symlink to Blender’s Python
186
+ temp_dir = tempfile.mkdtemp()
 
 
 
 
 
187
  try:
188
+ python_link = os.path.join(temp_dir, "python")
189
+ os.symlink(BLENDER_PYTHON_EXEC, python_link) # Links 'python' to 'python3.11'
190
+ existing_path = process_env.get('PATH', '')
191
+ process_env["PATH"] = f"{temp_dir}{os.pathsep}{BLENDER_PYTHON_BIN_DIR}{os.pathsep}{existing_path}"
192
+ print(f"Subprocess PATH: {process_env['PATH']}")
193
+
194
+ # Execute the shell script
195
  result = subprocess.run(
196
  cmd,
197
  cwd=UNIRIG_REPO_DIR,
198
  capture_output=True,
199
  text=True,
200
+ check=True,
201
+ env=process_env
202
  )
203
  print(f"{step_name} STDOUT:\n{result.stdout}")
204
  if result.stderr:
 
212
  print(f"--- {step_name} STDERR ---:\n{e.stderr}")
213
  error_summary = e.stderr.strip().splitlines()
214
  last_lines = "\n".join(error_summary[-5:]) if error_summary else "No stderr output."
 
215
  if "ModuleNotFoundError: No module named 'bpy'" in e.stderr:
216
+ raise gr.Error(f"Error in UniRig '{step_name}': Script failed to import Blender's 'bpy' module. Check environment setup.")
217
  elif "ImportError: Failed to load PyTorch C extensions" in e.stderr:
218
+ raise gr.Error(f"Error in UniRig '{step_name}': Script failed to load PyTorch extensions. Check environment and PyTorch installation.")
219
  else:
220
+ raise gr.Error(f"Error in UniRig '{step_name}'. Check logs. Last error lines:\n{last_lines}")
 
221
 
222
  except FileNotFoundError:
 
223
  print(f"ERROR: Could not find executable 'bash' or script '{script_path}' for {step_name}.")
 
224
  raise gr.Error(f"Setup error for UniRig '{step_name}'. 'bash' or script '{os.path.basename(script_path)}' not found.")
225
 
226
  except Exception as e_general:
 
229
  traceback.print_exc()
230
  raise gr.Error(f"Unexpected Python error during '{step_name}' execution: {str(e_general)[:500]}")
231
 
232
+ finally:
233
+ shutil.rmtree(temp_dir) # Clean up the temporary directory
234
+
235
  print(f"--- Finished UniRig Step: {step_name} ---")
236
 
237
 
 
260
  if not input_glb_path.lower().endswith(".glb"):
261
  raise gr.Error("Invalid file type. Please upload a .glb file.")
262
 
263
+ # Test PyTorch import in Blender’s Python
264
+ try:
265
+ result = subprocess.run(
266
+ [BLENDER_PYTHON_EXEC, "-c", "import torch; print(torch.__version__)"],
267
+ capture_output=True,
268
+ text=True,
269
+ check=True
270
+ )
271
+ print(f"PyTorch version in Blender's Python: {result.stdout.strip()}")
272
+ except subprocess.CalledProcessError as e:
273
+ print(f"Failed to import torch in Blender's Python: {e.stderr}")
274
+ raise gr.Error("PyTorch import failed in Blender's Python environment. Check installation.")
275
+
276
  # --- Setup Temporary Directory ---
277
  processing_temp_dir = tempfile.mkdtemp(prefix="unirig_processing_")
278
  print(f"Using temporary processing directory: {processing_temp_dir}")