Skip to content

Free Motion Capture for Everyone πŸ’€βœ¨

TypeScript

blenderrouterr!

jonmatthised0af427c26f
diff --git a/freemocap/api/http/blender/__init__.py b/freemocap/api/http/blender/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/freemocap/api/http/blender/blender_router.py b/freemocap/api/http/blender/blender_router.py
new file mode 100644
index 00000000..c0077f0c
--- /dev/null
+++ b/freemocap/api/http/blender/blender_router.py
@@ -0,0 +1,135 @@
+import inspect
+import logging
+from pathlib import Path
+
+from fastapi import APIRouter, HTTPException
+from freemocap.system.default_paths import FREEMOCAP_TEST_DATA_PATH
+from pydantic import BaseModel, ConfigDict, Field
+
+from freemocap.core.blender.export_to_blender import export_to_blender
+from freemocap.core.blender.helpers.freemocap_blender_addon_helpers.install_addon.install_blender_addon import \
+ install_freemocap_blender_addon
+from freemocap.core.blender.helpers.get_best_guess_of_blender_path import get_best_guess_of_blender_path
+
+logger = logging.getLogger(__name__)
+
+blender_router = APIRouter(prefix="/blender", tags=["Blender"])
+
+
+# ==================== Request/Response Models ====================
+
+
+class DetectBlenderResponse(BaseModel):
+ blender_exe_path: str | None = None
+ found: bool
+ message: str | None = None
+
+
+class InstallAddonRequest(BaseModel):
+ model_config = ConfigDict(populate_by_name=True)
+ blender_exe_path: str|None = Field(alias="blenderExePath", default=None)
+
+
+class InstallAddonResponse(BaseModel):
+ success: bool
+ message: str | None = None
+
+
+class ExportToBlenderRequest(BaseModel):
+ model_config = ConfigDict(populate_by_name=True)
+ recording_folder_path: str = Field(alias="recordingFolderPath", default=FREEMOCAP_TEST_DATA_PATH)
+ blender_exe_path: str | None = Field(alias="blenderExePath")
+
+ @property
+ def blender_file_path(self):
+ recording_name = Path(self.recording_folder_path).stem
+ return str(Path(self.recording_folder_path) /f"{recording_name}.blend")
+
+
+
+class ExportToBlenderResponse(BaseModel):
+ success: bool
+ message: str | None = None
+ blender_file_path: str | None = None
+
+
+# ==================== Endpoints ====================
+
+
+@blender_router.get("/detect")
+def detect_blender() -> DetectBlenderResponse:
+ """Detect the Blender executable on the user's system."""
+ try:
+ blender_path = get_best_guess_of_blender_path()
+ if blender_path is None:
+ return DetectBlenderResponse(
+ found=False,
+ message="Could not find a Blender installation on this system",
+ )
+ return DetectBlenderResponse(
+ blender_exe_path=str(blender_path),
+ found=True,
+ message=f"Found Blender at: {blender_path}",
+ )
+ except Exception as e:
+ logger.exception(f"Error detecting Blender: {e}")
+ raise HTTPException(status_code=500, detail=str(e))
+
+
+@blender_router.post("/addon/install")
+def install_addon(request: InstallAddonRequest) -> InstallAddonResponse:
+ """Install the freemocap_blender_addon into Blender (optional, not required for export)."""
+ try:
+ if request.blender_exe_path is None:
+ request.blender_exe_path = get_best_guess_of_blender_path()
+ blender_exe = Path(request.blender_exe_path)
+ if not blender_exe.is_file():
+
+ raise HTTPException(status_code=400, detail=f"Blender executable not found at: {request.blender_exe_path}")
+
+ from freemocap_blender_addon.main import ajc27_run_as_main_function
+ ajc_addon_main_file_path = inspect.getfile(ajc27_run_as_main_function)
+
+ install_freemocap_blender_addon(
+ blender_exe_path=str(blender_exe),
+ ajc_addon_main_file_path=ajc_addon_main_file_path,
+ )
+ return InstallAddonResponse(success=True, message="Addon installed successfully")
+ except HTTPException:
+ raise
+ except Exception as e:
+ logger.exception(f"Error installing addon: {e}")
+ raise HTTPException(status_code=500, detail=str(e))
+
+
+@blender_router.post("/export")
+def export_to_blender_endpoint(request: ExportToBlenderRequest) -> ExportToBlenderResponse:
+ """Export a recording session to a .blend file. Works without addon installation."""
+ try:
+ recording_folder = Path(request.recording_folder_path)
+ if not recording_folder.is_dir():
+ raise HTTPException(status_code=400, detail=f"Recording folder not found: {request.recording_folder_path}")
+ if request.blender_exe_path is None:
+ request.blender_exe_path = get_best_guess_of_blender_path()
+ blender_exe = Path(request.blender_exe_path)
+ if not blender_exe.is_file():
+ raise HTTPException(status_code=400, detail=f"Blender executable not found at: {request.blender_exe_path}")
+
+ export_to_blender(
+ recording_folder_path=str(recording_folder),
+ blender_file_path=request.blender_file_path,
+ blender_exe_path=str(blender_exe),
+ )
+ return ExportToBlenderResponse(
+ success=True,
+ message="Export to Blender completed",
+ blender_file_path=request.blender_file_path,
+ )
+ except HTTPException:
+ raise
+ except FileNotFoundError as e:
+ logger.exception(f"Missing required files for export: {e}")
+ raise HTTPException(status_code=400, detail=str(e))
+ except Exception as e:
+ logger.exception(f"Error exporting to Blender: {e}")
+ raise HTTPException(status_code=500, detail=str(e))
diff --git a/freemocap/api/routers.py b/freemocap/api/routers.py
index 4f7a251b..96720e6a 100644
--- a/freemocap/api/routers.py
+++ b/freemocap/api/routers.py
@@ -4,6 +4,7 @@ from freemocap.api.http.app.debug import debug_router
from freemocap.api.http.app.health import health_router
from freemocap.api.http.app.shutdown import shutdown_router
from freemocap.api.http.app.state import state_router
+from freemocap.api.http.blender.blender_router import blender_router
from freemocap.api.http.calibration.calibration_router import calibration_router
from freemocap.api.http.mocap.mocap_router import mocap_router
from freemocap.api.http.pipelines.pipeline_router import pipeline_router
@@ -19,5 +20,6 @@ SKELLYCAM_ROUTERS = [
FREEMOCAP_ROUTERS = [pipeline_router,
calibration_router,
- mocap_router
+ mocap_router,
+ blender_router,
]
diff --git a/freemocap/core/blender/helpers/freemocap_blender_addon_helpers/run_freemocap_blender_addon_main.py b/freemocap/core/blender/helpers/freemocap_blender_addon_helpers/run_freemocap_blender_addon_main.py
index 03314cec..5fd61987 100644
--- a/freemocap/core/blender/helpers/freemocap_blender_addon_helpers/run_freemocap_blender_addon_main.py
+++ b/freemocap/core/blender/helpers/freemocap_blender_addon_helpers/run_freemocap_blender_addon_main.py
@@ -4,12 +4,9 @@ import subprocess
from pathlib import Path
from typing import Union, List
-from freemocap.core.blender.helpers.freemocap_blender_addon_helpers.get_numpy_path import get_numpy_path
-from freemocap.core.blender.helpers.freemocap_blender_addon_helpers.install_addon.install_blender_addon import \
- install_freemocap_blender_addon
from freemocap.core.blender.helpers.freemocap_blender_addon_helpers.run_simple import run_simple
from freemocap.core.blender.helpers.get_best_guess_of_blender_path import get_best_guess_of_blender_path
-from freemocap_blender_addon.main import ajc27_run_as_main_function
+import freemocap_blender_addon
logger = logging.getLogger(__name__)
@@ -36,17 +33,9 @@ OLD_TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME = "total_body_center_of_mass_xyz.npy
OLD_SEGMENT_CENTER_OF_MASS_NPY_FILE_NAME = "segmentCOM_frame_joint_xyz.npy"
-def run_subprocess(command_list: List[str], append_to_python_path: List[str] = None):
+def run_subprocess(command_list: List[str]):
logger.debug(f"Running subprocess with command list: {command_list}")
- # modified_env = os.environ.copy()
- # if append_to_python_path is not None:
- # logger.debug(f"Appending to PYTHONPATH: {append_to_python_path}")
- # for addon_root_directory in append_to_python_path:
- # if not Path(addon_root_directory).exists():
- # raise FileNotFoundError(f"Could not find addon root directory at {addon_root_directory}")
- # modified_env["PYTHONPATH"] += f";{addon_root_directory}"
process = subprocess.Popen(command_list, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- # env=modified_env)
return process
@@ -62,22 +51,15 @@ def run_blender_addon_subprocess(
logger.error("Missing required files to run AJC addon, did something go wrong during processing?")
raise e
- ajc_addon_main_file_path = inspect.getfile(ajc27_run_as_main_function)
- logger.debug(f"Running freemocap_blender_addon as a subprocess using script at : {ajc_addon_main_file_path}")
+ # Resolve the site-packages directory containing freemocap_blender_addon
+ # so we can inject it into Blender's sys.path (no addon installation needed)
+ addon_package_path = Path(inspect.getfile(freemocap_blender_addon))
+ site_packages_path = str(addon_package_path.parent.parent)
+ logger.debug(f"Will inject site-packages path into Blender's sys.path: {site_packages_path}")
- addon_root_directory = str(Path(ajc_addon_main_file_path).parent.parent)
-
- # path_to_blenders_numpy = get_blenders_numpy(blender_exe_path=blender_exe_path)
- # blender_numpy_root = str(Path(path_to_blenders_numpy).parent.parent)
-
- install_freemocap_blender_addon(blender_exe_path=blender_exe_path, ajc_addon_main_file_path=ajc_addon_main_file_path)
- try:
- blender_exe_path = Path(blender_exe_path)
- if not blender_exe_path.exists():
- raise FileNotFoundError(f"Could not find the blender executable at {blender_exe_path}")
- except Exception as e:
- logger.error(e)
- raise e
+ blender_exe_path = Path(blender_exe_path)
+ if not blender_exe_path.exists():
+ raise FileNotFoundError(f"Could not find the blender executable at {blender_exe_path}")
simple_run_script = inspect.getfile(run_simple)
@@ -87,15 +69,14 @@ def run_blender_addon_subprocess(
"--python",
simple_run_script,
"--",
+ site_packages_path,
str(recording_folder_path),
str(blender_file_path),
]
logger.info(f"Starting `blender` sub-process with this command: \n {command_list}")
- blender_process = run_subprocess(
- command_list=command_list, append_to_python_path=[addon_root_directory]
- ) # , blender_numpy_root])
+ blender_process = run_subprocess(command_list=command_list)
while True:
output = blender_process.stdout.readline()
@@ -110,30 +91,6 @@ def run_blender_addon_subprocess(
blender_process.terminate() # manually terminate the process
-def get_blenders_numpy(blender_exe_path: Union[str, Path]) -> str:
- import subprocess
-
- get_numpy_script_path = inspect.getfile(get_numpy_path)
-
- command = [
- str(blender_exe_path),
- "--background",
- "--python",
- get_numpy_script_path,
- ]
- subprocess_result = subprocess.run(command, capture_output=True, text=True)
- all_output = subprocess_result.stdout
- numpy_path = None
- for line in all_output.split("\n"):
- if "numpy" in line:
- numpy_path = line
- break
- if not Path(numpy_path).exists():
- raise FileNotFoundError(f"Could not find Blender's numpy at {numpy_path}")
- logger.info(f"Got Blender's numpy path: {numpy_path}")
- return numpy_path
-
-
def ajc_blender_addon_validator(recording_folder_path: Union[str, Path], active_tracker: str = "mediapipe"):
"""
Check if the required files exist in the recording folder
diff --git a/freemocap/core/blender/helpers/freemocap_blender_addon_helpers/run_simple.py b/freemocap/core/blender/helpers/freemocap_blender_addon_helpers/run_simple.py
index 605854e3..c89c5c04 100644
--- a/freemocap/core/blender/helpers/freemocap_blender_addon_helpers/run_simple.py
+++ b/freemocap/core/blender/helpers/freemocap_blender_addon_helpers/run_simple.py
@@ -1,7 +1,12 @@
import sys
-def run_simple(recording_path_input: str, blender_file_save_path_input: str):
+def run_simple(site_packages_path: str, recording_path_input: str, blender_file_save_path_input: str):
+ # Inject the freemocap venv's site-packages so freemocap_blender_addon is importable
+ # without needing to install the addon into Blender
+ if site_packages_path not in sys.path:
+ sys.path.insert(0, site_packages_path)
+
from freemocap_blender_addon.main import ajc27_run_as_main_function
ajc27_run_as_main_function(recording_path=str(recording_path_input),
@@ -9,13 +14,15 @@ def run_simple(recording_path_input: str, blender_file_save_path_input: str):
if __name__ == "__main__":
- print(f"\nRunning {__file__} as a subprocess to install the addon...\n")
+ print(f"\nRunning {__file__} as a subprocess...\n")
argv = sys.argv
print(f"Received command line arguments: {argv}")
argv = argv[argv.index("--") + 1:]
- recording_path_input = str(argv[0])
- blender_file_save_path_input = str(argv[1])
- run_simple(recording_path_input=recording_path_input,
+ site_packages_path_input = str(argv[0])
+ recording_path_input = str(argv[1])
+ blender_file_save_path_input = str(argv[2])
+ run_simple(site_packages_path=site_packages_path_input,
+ recording_path_input=recording_path_input,
blender_file_save_path_input=blender_file_save_path_input)
print("\nDone!\n")