Skip to content

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

TypeScript

porgess

jonmatthis9d83697c53f4
diff --git a/freemocap-ui/src/components/viewport3d/RigidBodyRenderer.tsx b/freemocap-ui/src/components/viewport3d/RigidBodyRenderer.tsx
index 4623d64f..44799d6d 100644
--- a/freemocap-ui/src/components/viewport3d/RigidBodyRenderer.tsx
+++ b/freemocap-ui/src/components/viewport3d/RigidBodyRenderer.tsx
@@ -5,6 +5,7 @@ import {
CylinderGeometry,
Object3D,
Vector3,
+ Color,
} from "three";
import { useFrame } from "@react-three/fiber";
import { useServer } from "@/services";
diff --git a/freemocap-ui/src/pages/VideosPage.tsx b/freemocap-ui/src/pages/VideosPage.tsx
deleted file mode 100644
index cb12f8b4..00000000
--- a/freemocap-ui/src/pages/VideosPage.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-import React from 'react';
-import Box from "@mui/material/Box";
-import ErrorBoundary from "@/components/common/ErrorBoundary";
-import {Footer} from "@/components/ui-components/Footer";
-import {useTheme} from "@mui/material/styles";
-import {Typography} from '@mui/material';
-import {useTranslation} from "react-i18next";
-
-const VideosPage: React.FC = () => {
- const theme = useTheme();
- const {t} = useTranslation();
-
- return (
- <React.Fragment>
- <Box sx={{
- py: 1,
- px: 1,
- flex: 1,
- display: 'flex',
- flexDirection: 'column',
- height: '100%',
- backgroundColor: theme.palette.mode === 'dark'
- ? theme.palette.background.default
- : theme.palette.background.paper,
- borderStyle: 'solid',
- borderWidth: '1px',
- borderColor: theme.palette.divider
- }}>
- <Box sx={{
- flex: 1,
- display: 'flex',
- flexDirection: 'column',
- justifyContent: 'center',
- alignItems: 'center',
- overflow: 'hidden',
- }}>
- <ErrorBoundary>
- <Typography variant="h4" gutterBottom>
- {t('loadSynchronizedVideos')}
- </Typography>
- <Typography variant="body1">
- {t('loadSynchronizedVideosDescription')}
- </Typography>
- </ErrorBoundary>
- </Box>
- <Box component="footer" sx={{p: 1}}>
- <Footer/>
- </Box>
- </Box>
- </React.Fragment>
- );
-};
-
-export default VideosPage;
diff --git a/freemocap-ui/src/services/server/ServerContextProvider.tsx b/freemocap-ui/src/services/server/ServerContextProvider.tsx
index 3618a033..d1e926c6 100644
--- a/freemocap-ui/src/services/server/ServerContextProvider.tsx
+++ b/freemocap-ui/src/services/server/ServerContextProvider.tsx
@@ -7,6 +7,7 @@ import { CanvasManager } from "@/services/server/server-helpers/canvas-manager";
import { serverUrls } from "@/services";
import {DetailedFramerate, FramerateStore} from "@/services/server/server-helpers/framerate-store";
import {LogStore, LogRecord} from "@/services/server/server-helpers/log-store";
+import {Point3d, RigidBodyPose} from "@/components/viewport3d/viewport3d-types";
interface ServerContextValue {
isConnected: boolean;
@@ -20,6 +21,9 @@ interface ServerContextValue {
getLogStore: () => LogStore;
connectedCameraIds: string[];
updateServerConnection: (host: string, port: number) => void;
+ subscribeToTrackedPoints: (cb: (points: Map<string, Point3d>) => void) => () => void;
+ subscribeToRigidBodies: (cb: (poses: Map<string, RigidBodyPose>) => void) => () => void;
+ getLatestTrackedPoints: () => Map<string, Point3d>;
}
const ServerContext = createContext<ServerContextValue | null>(null);
@@ -81,6 +85,12 @@ export const ServerContextProvider: React.FC<{ children: ReactNode }> = ({ child
// Latest server-side (backend) FPS stored in a ref for non-reactive access
const serverFpsRef = useRef<number | null>(null);
+ // 3D data refs and subscriber sets
+ const trackedPointsRef = useRef<Map<string, Point3d>>(new Map());
+ const rigidBodiesRef = useRef<Map<string, RigidBodyPose>>(new Map());
+ const trackedPointsSubscribersRef = useRef<Set<(points: Map<string, Point3d>) => void>>(new Set());
+ const rigidBodiesSubscribersRef = useRef<Set<(poses: Map<string, RigidBodyPose>) => void>>(new Set());
+
// Holds the latest binary payload received from the WebSocket.
// The WebSocket onmessage handler writes here synchronously;
// a separate rAF-driven processing loop reads and clears it.
@@ -137,6 +147,8 @@ export const ServerContextProvider: React.FC<{ children: ReactNode }> = ({ child
pendingPayloadRef.current = null;
lastCameraIdsRef.current = [];
framerateStoreRef.current.clear();
+ trackedPointsRef.current = new Map();
+ rigidBodiesRef.current = new Map();
setConnectedCameraIds([]);
}
};
@@ -239,6 +251,29 @@ export const ServerContextProvider: React.FC<{ children: ReactNode }> = ({ child
framerateStoreRef.current.updateBackend(jsonData.backend_framerate);
framerateStoreRef.current.updateFrontend(jsonData.frontend_framerate);
}
+ // Handle tracked 3D points
+ else if (jsonData.tracked_points3d && typeof jsonData.tracked_points3d === 'object') {
+ const pointsMap = new Map<string, Point3d>();
+ for (const [name, pt] of Object.entries(jsonData.tracked_points3d)) {
+ const p = pt as { x: number; y: number; z: number };
+ pointsMap.set(name, { x: p.x, y: p.y, z: p.z });
+ }
+ trackedPointsRef.current = pointsMap;
+ for (const cb of trackedPointsSubscribersRef.current) {
+ cb(pointsMap);
+ }
+ }
+ // Handle rigid body poses
+ else if (jsonData.rigid_body_poses && typeof jsonData.rigid_body_poses === 'object') {
+ const posesMap = new Map<string, RigidBodyPose>();
+ for (const [key, pose] of Object.entries(jsonData.rigid_body_poses)) {
+ posesMap.set(key, pose as RigidBodyPose);
+ }
+ rigidBodiesRef.current = posesMap;
+ for (const cb of rigidBodiesSubscribersRef.current) {
+ cb(posesMap);
+ }
+ }
// Handle other message types (silently ignored to avoid
// retaining object references in the DevTools console)
} catch (error) {
@@ -296,6 +331,20 @@ export const ServerContextProvider: React.FC<{ children: ReactNode }> = ({ child
return logStoreRef.current;
}, []);
+ const subscribeToTrackedPoints = useCallback((cb: (points: Map<string, Point3d>) => void): () => void => {
+ trackedPointsSubscribersRef.current.add(cb);
+ return () => { trackedPointsSubscribersRef.current.delete(cb); };
+ }, []);
+
+ const subscribeToRigidBodies = useCallback((cb: (poses: Map<string, RigidBodyPose>) => void): () => void => {
+ rigidBodiesSubscribersRef.current.add(cb);
+ return () => { rigidBodiesSubscribersRef.current.delete(cb); };
+ }, []);
+
+ const getLatestTrackedPoints = useCallback((): Map<string, Point3d> => {
+ return trackedPointsRef.current;
+ }, []);
+
const updateServerConnection = useCallback((host: string, port: number): void => {
// Update the singleton so HTTP endpoints also update
serverUrls.setHost(host);
@@ -322,7 +371,10 @@ export const ServerContextProvider: React.FC<{ children: ReactNode }> = ({ child
getLogStore,
connectedCameraIds,
updateServerConnection,
- }), [isConnected, connectedCameraIds, connect, disconnect, send, setCanvasForCamera, getFps, getServerFps, getFramerateStore, getLogStore, updateServerConnection]);
+ subscribeToTrackedPoints,
+ subscribeToRigidBodies,
+ getLatestTrackedPoints,
+ }), [isConnected, connectedCameraIds, connect, disconnect, send, setCanvasForCamera, getFps, getServerFps, getFramerateStore, getLogStore, updateServerConnection, subscribeToTrackedPoints, subscribeToRigidBodies, getLatestTrackedPoints]);
return (
<ServerContext.Provider value={contextValue}>
diff --git a/freemocap/__main__.py b/freemocap/__main__.py
index 10454770..7101747a 100644
--- a/freemocap/__main__.py
+++ b/freemocap/__main__.py
@@ -7,7 +7,7 @@ import signal
logger = logging.getLogger(__name__)
-async def main() -> None:
+async def main(force_preferred_port:bool=True) -> None:
# Heavy imports are here (not at module level) so that multiprocessing
# child processes don't re-import the entire app tree on Windows.
# Windows uses the `spawn` start method, which re-executes this file
@@ -22,12 +22,17 @@ async def main() -> None:
from freemocap.api.server_constants import (
HOSTNAME,
find_available_port,
+ PREFERRED_PORT,
format_port_sentinel,
)
from freemocap.app.app import create_fastapi_app
- port = find_available_port()
+ if force_preferred_port:
+ port = PREFERRED_PORT
+ kill_process_on_port(port=port)
+ else:
+ port = find_available_port()
# Print the port sentinel to stdout so the Electron main process can discover it.
# flush=True ensures it arrives immediately even when stdout is buffered.
print(format_port_sentinel(port=port), flush=True)
@@ -99,4 +104,4 @@ if __name__ == "__main__":
logger.exception(f"Unhandled exception: {e}")
os._exit(1)
print("Done!")
- os._exit(0)
\ No newline at end of file
+ os._exit(0)
diff --git a/freemocap/api/http/calibration/calibration_router.py b/freemocap/api/http/calibration/calibration_router.py
index 4f46f3be..d4dccb1e 100644
--- a/freemocap/api/http/calibration/calibration_router.py
+++ b/freemocap/api/http/calibration/calibration_router.py
@@ -26,38 +26,30 @@ class CalibrationConfigResponse(BaseModel):
success: bool
message: str | None = None
+class CalibrateRecordingRequest(BaseModel):
+ calibration_recording_directory: str = Field(alias="calibrationRecordingDirectory")
+ calibration_config: CalibrationPipelineConfig = Field(alias="calibrationTaskConfig",
+ default=CalibrationPipelineConfig)
-class StartCalibrationRecordingRequest(BaseModel):
- calibration_recording_directory: str = Field(alias="calibrationRecordingDirectory", default=FREEMOCAP_TEST_DATA_PATH)
- calibration_config: CalibrationPipelineConfig = Field(alias="calibrationTaskConfig")
def to_recording_info(self) -> RecordingInfo:
recording_dir = Path(self.calibration_recording_directory).expanduser()
- recording_name = recording_dir.stem
- if not recording_name.endswith("_calibration"):
- recording_name += "_calibration"
return RecordingInfo(
recording_directory=str(recording_dir.parent),
- recording_name=recording_name,
+ recording_name=recording_dir.stem,
mic_device_index=-1,
)
+class StartCalibrationRecordingRequest(CalibrateRecordingRequest):
+ # StartCalibrationRecording needs same info as CalibrateRecording. Duplicating request for pattern
+ pass
+
class StopCalibrationRecordingRequest(BaseModel):
calibration_config: CalibrationPipelineConfig = Field(alias="calibrationTaskConfig")
-class CalibrateRecordingRequest(BaseModel):
- calibration_recording_directory: str = Field(alias="calibrationRecordingDirectory", default=FREEMOCAP_TEST_DATA_PATH) # TODO - this is redundant, should use the def in the task config (retaining 'use most recent calibration' as default/none)
- calibration_config: CalibrationPipelineConfig = Field(alias="calibrationTaskConfig", default=CalibrationPipelineConfig)
- def to_recording_info(self) -> RecordingInfo:
- recording_dir = Path(self.calibration_recording_directory).expanduser()
- return RecordingInfo(
- recording_directory=str(recording_dir.parent),
- recording_name=recording_dir.stem,
- mic_device_index=-1,
- )
class StartCalibrationRecordingResponse(BaseModel):
@@ -139,13 +131,7 @@ async def calibrate_recording(request: CalibrateRecordingRequest) -> CalibrateRe
"""Process and calibrate a previously recorded session."""
app = get_freemocap_app()
try:
- if request.calibration_recording_directory is not None:
- if request.calibration_config.calibration_recording_folder is not None:
- if not Path(request.calibration_recording_directory) == Path(request.calibration_config.calibration_recording_folder):
- raise RuntimeError(f"Request recording folder does not match config:\n request.calibration_recording_directory: {request.calibration_recording_directory}, \n request.calibration_config.calibration_recording_folder: {request.calibration_config.calibration_recording_folder}")
- else:
- request.calibration_config.calibration_recording_directory = request.calibration_config.calibration_recording_folder
- logger.info(f'Calibrating recording directory: {request.calibration_config.calibration_recording_directory}')
+
recording_info = request.to_recording_info()
await app.create_posthoc_calibration_pipeline(
recording_info=recording_info,
diff --git a/freemocap/api/websocket/websocket_server.py b/freemocap/api/websocket/websocket_server.py
index eabe8431..5e1169a6 100644
--- a/freemocap/api/websocket/websocket_server.py
+++ b/freemocap/api/websocket/websocket_server.py
@@ -54,6 +54,9 @@ class WebsocketServer:
self.last_sent_frame_number: int = -1
self._display_image_sizes: dict[CameraGroupIdString, dict[str, float]] | None = None
self._frontend_framerate_trackers: dict[CameraGroupIdString, FramerateTracker] = {}
+ # Serializes all WebSocket send operations to prevent concurrent-send
+ # race conditions in the websockets legacy protocol (AssertionError in _drain_helper).
+ self._send_lock = asyncio.Lock()
async def __aenter__(self):
logger.debug("Entering WebsocketRunner context manager...")
@@ -66,7 +69,11 @@ class WebsocketServer:
logger.debug("WebsocketRunner context manager exiting...")
self._websocket_should_continue = False
if self.websocket.client_state == WebSocketState.CONNECTED:
- await self.websocket.close()
+ try:
+ await self.websocket.close()
+ except RuntimeError:
+ # Socket already closed by the client or a relay task
+ pass
for task in self.ws_tasks:
if not task.done():
task.cancel()
@@ -100,6 +107,7 @@ class WebsocketServer:
websocket=self.websocket,
settings_manager=self._settings_manager,
should_continue=lambda: self.should_continue,
+ send_lock=self._send_lock,
),
name="WebsocketSettingsStateRelay",
),
@@ -159,33 +167,38 @@ class WebsocketServer:
f"Invalid payload bytes on frame {frame_number} - "
f"got type {type(payload_bytes).__name__}"
)
- await self.websocket.send_bytes(payload_bytes)
+ async with self._send_lock:
+ await self.websocket.send_bytes(payload_bytes)
if frontend_payload and frontend_payload.charuco_overlays:
- await self.websocket.send_json({
- camera_id: overlay_data.model_dump()
- for camera_id, overlay_data in frontend_payload.charuco_overlays.items()
- })
+ async with self._send_lock:
+ await self.websocket.send_json({
+ camera_id: overlay_data.model_dump()
+ for camera_id, overlay_data in frontend_payload.charuco_overlays.items()
+ })
if frontend_payload and frontend_payload.mediapipe_overlays:
- await self.websocket.send_json({
- camera_id: overlay_data.model_dump()
- for camera_id, overlay_data in frontend_payload.mediapipe_overlays.items()
- })
+ async with self._send_lock:
+ await self.websocket.send_json({
+ camera_id: overlay_data.model_dump()
+ for camera_id, overlay_data in frontend_payload.mediapipe_overlays.items()
+ })
if frontend_payload and frontend_payload.tracked_points3d:
points3d_dict = {
point_name: tracked_point.model_dump()
for point_name, tracked_point in frontend_payload.tracked_points3d.items()
}
- await self.websocket.send_json({"tracked_points3d": points3d_dict})
+ async with self._send_lock:
+ await self.websocket.send_json({"tracked_points3d": points3d_dict})
if frontend_payload and frontend_payload.rigid_body_poses:
rigid_body_dict = {
bone_key: pose.model_dump()
for bone_key, pose in frontend_payload.rigid_body_poses.items()
}
- await self.websocket.send_json({"rigid_body_poses": rigid_body_dict})
+ async with self._send_lock:
+ await self.websocket.send_json({"rigid_body_poses": rigid_body_dict})
if frame_number is not None:
self.last_sent_frame_number = frame_number
@@ -230,7 +243,8 @@ class WebsocketServer:
continue
if log_entry.get("levelno", 0) < ws_log_level:
continue
- await self.websocket.send_json(log_entry)
+ async with self._send_lock:
+ await self.websocket.send_json(log_entry)
else:
await await_10ms()
except asyncio.CancelledError:
@@ -238,7 +252,10 @@ class WebsocketServer:
except WebSocketDisconnect:
logger.info("Client disconnected, ending log relay task...")
except Exception as e:
- logger.exception(f"Error in websocket log relay: {e.__class__}: {e}")
+ logger.exception(
+ f"Error in websocket log relay: {e.__class__.__name__}: {e or '(no message)'} "
+ f"β€” ws state: {self.websocket.client_state}"
+ )
self._websocket_should_continue = False
raise
@@ -281,7 +298,8 @@ class WebsocketServer:
raise ValueError(f"Failed to decode JSON message: {e}") from e
else:
if text_content.startswith("ping"):
- await self.websocket.send_text("pong")
+ async with self._send_lock:
+ await self.websocket.send_text("pong")
elif text_content.startswith("pong"):
pass
else:
diff --git a/freemocap/app/freemocap_application.py b/freemocap/app/freemocap_application.py
index 311dae29..b2b5b59f 100644
--- a/freemocap/app/freemocap_application.py
+++ b/freemocap/app/freemocap_application.py
@@ -151,7 +151,7 @@ class FreemocapApplication:
raise NotImplementedError(
"Stopping multiple recordings at once is not supported yet."
)
- return recording_infos[0]
+ return recording_infos[0][0]
# ------------------------------------------------------------------
# Frontend payloads
diff --git a/freemocap/app/settings_protocol.py b/freemocap/app/settings_protocol.py
index 5d92dbe3..26040629 100644
--- a/freemocap/app/settings_protocol.py
+++ b/freemocap/app/settings_protocol.py
@@ -22,6 +22,7 @@ async def settings_state_relay(
websocket: WebSocket,
settings_manager: SettingsManager,
should_continue: Callable[[], bool],
+ send_lock: asyncio.Lock | None = None,
) -> None:
"""
Push `settings/state` to the frontend whenever settings change.
@@ -31,9 +32,16 @@ async def settings_state_relay(
"""
try:
# Push initial state on connection
+ async def _send_json(msg: dict) -> None:
+ if send_lock is not None:
+ async with send_lock:
+ await websocket.send_json(msg)
+ else:
+ await websocket.send_json(msg)
+
if websocket.client_state == WebSocketState.CONNECTED:
state_msg = settings_manager.get_state_message()
- await websocket.send_json(state_msg)
+ await _send_json(state_msg)
logger.info("Sent initial settings/state")
# Push on every subsequent change
@@ -42,7 +50,7 @@ async def settings_state_relay(
if websocket.client_state != WebSocketState.CONNECTED:
break
state_msg = settings_manager.get_state_message()
- await websocket.send_json(state_msg)
+ await _send_json(state_msg)
logger.debug("Pushed settings/state")
except asyncio.CancelledError:
diff --git a/freemocap/core/blender/export_to_blender.py b/freemocap/core/blender/export_to_blender.py
index fafe32a4..5e02a3ba 100644
--- a/freemocap/core/blender/export_to_blender.py
+++ b/freemocap/core/blender/export_to_blender.py
@@ -1,39 +1,165 @@
+import inspect
import logging
+import subprocess
from pathlib import Path
-from typing import Union
+from typing import Union, List
-from freemocap.core.blender.helpers.freemocap_blender_addon_helpers.run_freemocap_blender_addon_main import \
- run_blender_addon_subprocess
+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
+import freemocap_blender_addon
logger = logging.getLogger(__name__)
+RAW_3D_NPY_FILE_NAME = "3dData_numFrames_numTrackedPoints_spatialXYZ.npy"
+REPROJECTION_ERROR_NPY_FILE_NAME = "3dData_numFrames_numTrackedPoints_reprojectionError.npy"
+FULL_REPROJECTION_ERROR_NPY_FILE_NAME = "3dData_numCams_numFrames_numTrackedPoints_reprojectionError.npy"
+REPROJECTION_FILTERED_PREFIX = "reprojection_filtered_"
+
+DATA_3D_NPY_FILE_NAME = "skeleton_3d.npy"
+RIGID_BONES_NPY_FILE_NAME = "rigid_bones_3d.npy"
+BODY_3D_DATAFRAME_CSV_FILE_NAME = "body_3d_xyz.csv"
+RIGHT_HAND_3D_DATAFRAME_CSV_FILE_NAME = "right_hand_right_hand.csv" # TODO - the names are duplicated in the right/left hand, needs fixed in skellyforge.skellymodels.human (i think?)
+LEFT_HAND_3D_DATAFRAME_CSV_FILE_NAME = "left_hand_left_hand.csv" # TODO - the names are duplicated in the right/left hand, needs fixed in skellyforge.skellymodels.human (i think?)
+FACE_3D_DATAFRAME_CSV_FILE_NAME = "face_3d_xyz.csv"
+
+TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME = "body_total_body_center_of_mass.npy"
+SEGMENT_CENTER_OF_MASS_NPY_FILE_NAME = "body_segment_center_of_mass.npy"
+
+OLD_DATA_2D_NPY_FILE_NAME = "mediapipe2dData_numCams_numFrames_numTrackedPoints_pixelXY.npy"
+OLD_RAW_3D_NPY_FILE_NAME = "mediapipe3dData_numFrames_numTrackedPoints_spatialXYZ.npy"
+OLD_REPROJECTION_ERROR_NPY_FILE_NAME = "mediapipe3dData_numFrames_numTrackedPoints_reprojectionError.npy"
+OLD_DATA_3D_NPY_FILE_NAME = "mediaPipeSkel_3d_body_hands_face.npy"
+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]):
+ logger.debug(f"Running subprocess with command list: {command_list}")
+ process = subprocess.Popen(command_list, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ return process
+
def export_to_blender(
- recording_folder_path: Union[str, Path],
- blender_file_path: Union[str, Path],
- blender_exe_path: Union[str, Path],
- method: str = "freemocap_blender_addon",
+ recording_folder_path: str|Path,
+ blender_file_path: str|Path|None=None,
+ blender_exe_path: str|Path|None=None,
):
- logger.info(
- f"Exporting session data to a Blender scene at: {str(blender_file_path)} using Blender executable at {str(blender_exe_path)}"
- )
+ try:
+ ajc_blender_addon_validator(recording_folder_path=recording_folder_path)
+ except FileNotFoundError as e:
+ logger.error("Missing required files to run AJC addon, did something go wrong during processing?")
+ raise e
+
+ if blender_exe_path is None:
+ blender_exe_path:Path = Path(get_best_guess_of_blender_path())
+ if not blender_exe_path.is_file():
+ raise RuntimeError(f"Blender executable not found at: {blender_exe_path}")
+ if blender_file_path is None:
+ blender_file_path = Path(recording_folder_path)/f"{Path(recording_folder_path).stem}.blend"
+
+ # 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}")
+
+ simple_run_script = inspect.getfile(run_simple)
+
+ command_list = [
+ str(blender_exe_path),
+ "--background",
+ "--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)
+
+ while True:
+ output = blender_process.stdout.readline()
+ if blender_process.poll() is not None:
+ break
+ if output:
+ logging.debug(output.strip().decode())
+
+ if blender_process.returncode != 0:
+ logging.error(blender_process.stderr.read().decode())
+ logger.debug("Done with blender add on")
+ blender_process.terminate() # manually terminate the process
- if method == "freemocap_blender_addon":
- run_blender_addon_subprocess(
- recording_folder_path=recording_folder_path,
- blender_file_path=blender_file_path,
- blender_exe_path=blender_exe_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
+ """
+ recording_path = Path(recording_folder_path)
+ output_data_path = recording_path / "output_data"
+
+ if active_tracker[-1] != "_":
+ active_tracker = active_tracker + "_"
+
+ if not (output_data_path / (active_tracker + "body_3d_xyz.npy")).exists():
+ raise FileNotFoundError(
+ f"Could not find required file: {output_data_path / (active_tracker + 'body_3d_xyz.npy')}"
+ )
+
+ if not (output_data_path / (active_tracker + "right_hand_right_hand.npy")).exists(): #duplicated hand dnames need fixed in skforge
+ raise FileNotFoundError(
+ f"Could not find required file: {output_data_path / (active_tracker + 'right_hand_right_hand.npy')}"
+ )
+
+ if not (output_data_path / (active_tracker + "left_hand_left_hand.npy")).exists():
+ raise FileNotFoundError(
+ f"Could not find required file: {output_data_path / (active_tracker + 'left_hand_left_hand.npy')}"
)
- logger.info("Done with Blender Export :D")
+ if not (output_data_path / (active_tracker + "face_3d_xyz.npy")).exists():
+ raise FileNotFoundError(
+ f"Could not find required file: {output_data_path / (active_tracker + 'face_3d_xyz.npy')}"
+ )
+
+ if not (output_data_path / (active_tracker + TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME)).exists():
+ if (
+ active_tracker != "mediapipe_"
+ or not (output_data_path / OLD_TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME).exists()
+ ):
+ raise FileNotFoundError(
+ f"Could not find required file: {output_data_path / (active_tracker + TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME)}"
+ )
+
+ if not (output_data_path / (active_tracker + SEGMENT_CENTER_OF_MASS_NPY_FILE_NAME)).exists():
+ if (
+ active_tracker != "mediapipe_"
+ or not (output_data_path / OLD_SEGMENT_CENTER_OF_MASS_NPY_FILE_NAME).exists()
+ ):
+ raise FileNotFoundError(
+ f"Could not find required file: {output_data_path / 'center_of_mass' / (active_tracker + SEGMENT_CENTER_OF_MASS_NPY_FILE_NAME)}"
+ )
+
+ # if not (output_data_path / "raw_data" / (active_tracker + REPROJECTION_ERROR_NPY_FILE_NAME)).exists():
+ # if (
+ # active_tracker != "mediapipe_"
+ # or not (output_data_path / "raw_data" / OLD_REPROJECTION_ERROR_NPY_FILE_NAME).exists()
+ # ):
+ # raise FileNotFoundError(
+ # f"Could not find required file: {output_data_path / 'raw_data' / (active_tracker + REPROJECTION_ERROR_NPY_FILE_NAME)}"
+ # )
if __name__ == "__main__":
- from freemocap.system.default_paths import FREEMOCAP_TEST_DATA_PATH
- _recording_path = FREEMOCAP_TEST_DATA_PATH
- _blender_output_file = str(Path(_recording_path) / f"{Path(_recording_path).stem}.blend")
- export_to_blender(recording_folder_path=_recording_path,
- blender_file_path=_blender_output_file,
- blender_exe_path=get_best_guess_of_blender_path())
+
+ recording_path_in = r"C:\Users\jonma\freemocap_data\recording_sessions\steen_pantsOn_gait"
+ blender_file_path_in = str(Path(recording_path_in) / (str(Path(recording_path_in).stem) + ".blend"))
+ blender_exe_path_in = get_best_guess_of_blender_path()
+
+ export_to_blender(
+ recording_folder_path=recording_path_in,
+ blender_file_path=blender_file_path_in,
+ blender_exe_path=blender_exe_path_in,
+ )
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
deleted file mode 100644
index 5fd61987..00000000
--- a/freemocap/core/blender/helpers/freemocap_blender_addon_helpers/run_freemocap_blender_addon_main.py
+++ /dev/null
@@ -1,163 +0,0 @@
-import inspect
-import logging
-import subprocess
-from pathlib import Path
-from typing import Union, List
-
-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
-import freemocap_blender_addon
-
-logger = logging.getLogger(__name__)
-
-RAW_3D_NPY_FILE_NAME = "3dData_numFrames_numTrackedPoints_spatialXYZ.npy"
-REPROJECTION_ERROR_NPY_FILE_NAME = "3dData_numFrames_numTrackedPoints_reprojectionError.npy"
-FULL_REPROJECTION_ERROR_NPY_FILE_NAME = "3dData_numCams_numFrames_numTrackedPoints_reprojectionError.npy"
-REPROJECTION_FILTERED_PREFIX = "reprojection_filtered_"
-
-DATA_3D_NPY_FILE_NAME = "skeleton_3d.npy"
-RIGID_BONES_NPY_FILE_NAME = "rigid_bones_3d.npy"
-BODY_3D_DATAFRAME_CSV_FILE_NAME = "body_3d_xyz.csv"
-RIGHT_HAND_3D_DATAFRAME_CSV_FILE_NAME = "right_hand_right_hand.csv" # TODO - the names are duplicated in the right/left hand, needs fixed in skellyforge.skellymodels.human (i think?)
-LEFT_HAND_3D_DATAFRAME_CSV_FILE_NAME = "left_hand_left_hand.csv" # TODO - the names are duplicated in the right/left hand, needs fixed in skellyforge.skellymodels.human (i think?)
-FACE_3D_DATAFRAME_CSV_FILE_NAME = "face_3d_xyz.csv"
-
-TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME = "body_total_body_center_of_mass.npy"
-SEGMENT_CENTER_OF_MASS_NPY_FILE_NAME = "body_segment_center_of_mass.npy"
-
-OLD_DATA_2D_NPY_FILE_NAME = "mediapipe2dData_numCams_numFrames_numTrackedPoints_pixelXY.npy"
-OLD_RAW_3D_NPY_FILE_NAME = "mediapipe3dData_numFrames_numTrackedPoints_spatialXYZ.npy"
-OLD_REPROJECTION_ERROR_NPY_FILE_NAME = "mediapipe3dData_numFrames_numTrackedPoints_reprojectionError.npy"
-OLD_DATA_3D_NPY_FILE_NAME = "mediaPipeSkel_3d_body_hands_face.npy"
-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]):
- logger.debug(f"Running subprocess with command list: {command_list}")
- process = subprocess.Popen(command_list, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- return process
-
-
-def run_blender_addon_subprocess(
- recording_folder_path: Union[str, Path],
- blender_file_path: Union[str, Path],
- blender_exe_path: Union[str, Path],
-):
- try:
- # TODO: pass active tracker into here
- ajc_blender_addon_validator(recording_folder_path=recording_folder_path)
- except FileNotFoundError as e:
- logger.error("Missing required files to run AJC addon, did something go wrong during processing?")
- raise e
-
- # 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}")
-
- 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)
-
- command_list = [
- str(blender_exe_path),
- "--background",
- "--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)
-
- while True:
- output = blender_process.stdout.readline()
- if blender_process.poll() is not None:
- break
- if output:
- logging.debug(output.strip().decode())
-
- if blender_process.returncode != 0:
- logging.error(blender_process.stderr.read().decode())
- logger.debug("Done with blender add on")
- blender_process.terminate() # manually terminate the process
-
-
-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
- """
- recording_path = Path(recording_folder_path)
- output_data_path = recording_path / "output_data"
-
- if active_tracker[-1] != "_":
- active_tracker = active_tracker + "_"
-
- if not (output_data_path / (active_tracker + "body_3d_xyz.npy")).exists():
- raise FileNotFoundError(
- f"Could not find required file: {output_data_path / (active_tracker + 'body_3d_xyz.npy')}"
- )
-
- if not (output_data_path / (active_tracker + "right_hand_right_hand.npy")).exists(): #duplicated hand dnames need fixed in skforge
- raise FileNotFoundError(
- f"Could not find required file: {output_data_path / (active_tracker + 'right_hand_right_hand.npy')}"
- )
-
- if not (output_data_path / (active_tracker + "left_hand_left_hand.npy")).exists():
- raise FileNotFoundError(
- f"Could not find required file: {output_data_path / (active_tracker + 'left_hand_left_hand.npy')}"
- )
-
- if not (output_data_path / (active_tracker + "face_3d_xyz.npy")).exists():
- raise FileNotFoundError(
- f"Could not find required file: {output_data_path / (active_tracker + 'face_3d_xyz.npy')}"
- )
-
- if not (output_data_path / (active_tracker + TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME)).exists():
- if (
- active_tracker != "mediapipe_"
- or not (output_data_path / OLD_TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME).exists()
- ):
- raise FileNotFoundError(
- f"Could not find required file: {output_data_path / (active_tracker + TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME)}"
- )
-
- if not (output_data_path / (active_tracker + SEGMENT_CENTER_OF_MASS_NPY_FILE_NAME)).exists():
- if (
- active_tracker != "mediapipe_"
- or not (output_data_path / OLD_SEGMENT_CENTER_OF_MASS_NPY_FILE_NAME).exists()
- ):
- raise FileNotFoundError(
- f"Could not find required file: {output_data_path / 'center_of_mass' / (active_tracker + SEGMENT_CENTER_OF_MASS_NPY_FILE_NAME)}"
- )
-
- # if not (output_data_path / "raw_data" / (active_tracker + REPROJECTION_ERROR_NPY_FILE_NAME)).exists():
- # if (
- # active_tracker != "mediapipe_"
- # or not (output_data_path / "raw_data" / OLD_REPROJECTION_ERROR_NPY_FILE_NAME).exists()
- # ):
- # raise FileNotFoundError(
- # f"Could not find required file: {output_data_path / 'raw_data' / (active_tracker + REPROJECTION_ERROR_NPY_FILE_NAME)}"
- # )
-
-
-if __name__ == "__main__":
-
-
- recording_path_in = r"C:\Users\jonma\freemocap_data\recording_sessions\steen_pantsOn_gait"
- blender_file_path_in = str(Path(recording_path_in) / (str(Path(recording_path_in).stem) + ".blend"))
- blender_exe_path_in = get_best_guess_of_blender_path()
-
- run_blender_addon_subprocess(
- recording_folder_path=recording_path_in,
- blender_file_path=blender_file_path_in,
- blender_exe_path=blender_exe_path_in,
- )
diff --git a/freemocap/core/mocap/posthoc_mocap_task.py b/freemocap/core/mocap/posthoc_mocap_task.py
index 41e61576..fcd4bc57 100644
--- a/freemocap/core/mocap/posthoc_mocap_task.py
+++ b/freemocap/core/mocap/posthoc_mocap_task.py
@@ -1,7 +1,6 @@
"""
run_mocap_task: posthoc motion capture processing.
-Extracted from the old PosthocMocapAggregationNode._run().
Receives collected mediapipe observations, builds skeleton via triangulation.
Called by PosthocAggregationNode after all frames are collected.
@@ -17,6 +16,8 @@ from skellytracker.trackers.legacy_mediapipe_tracker.legacy_mediapipe_observatio
LegacyMediapipeObservation
from skellytracker.trackers.mediapipe_tracker import MediapipeObservation
+from freemocap.core.blender.export_to_blender import export_to_blender
+from freemocap.core.blender.helpers.get_best_guess_of_blender_path import get_best_guess_of_blender_path
from freemocap.core.calibration.shared.calibration_paths import get_last_successful_calibration_toml_path
from freemocap.core.mocap.mocap_helpers.skeleton_from_mediapipe_observations import \
skeleton_from_mediapipe_observation_recorders
@@ -28,12 +29,13 @@ logger = logging.getLogger(__name__)
def run_post_mocap_aggregation_task(
- *,
- frame_observations: list[dict[VideoIdString, BaseObservation]],
- recording_info: RecordingInfo,
- video_metadata: dict[VideoIdString, VideoMetadata],
- task_config: MocapPipelineConfig,
- report_progress: Callable[[str, float], None]|None =None,
+ *,
+ frame_observations: list[dict[VideoIdString, BaseObservation]],
+ recording_info: RecordingInfo,
+ video_metadata: dict[VideoIdString, VideoMetadata],
+ task_config: MocapPipelineConfig,
+ create_blender_output: bool=True, #TODO - Add this to the mocap config, after we split the RT and PH pipeline
+ report_progress: Callable[[str, float], None] | None = None,
) -> None:
"""
@@ -58,7 +60,7 @@ def run_post_mocap_aggregation_task(
for frame_idx, frame_obs in enumerate(frame_observations):
for vid_id, obs in frame_obs.items():
- if not isinstance(obs, MediapipeObservation) and not isinstance(obs, LegacyMediapipeObservation):
+ if not isinstance(obs, MediapipeObservation) and not isinstance(obs, LegacyMediapipeObservation):
raise TypeError(
f"Expected MediapipeObservation for video {vid_id} frame {frame_idx}, "
f"got {type(obs).__name__}"
@@ -85,6 +87,11 @@ def run_post_mocap_aggregation_task(
path_to_calibration_toml=calibration_toml_path,
path_to_output_data_folder=output_folder,
)
+ if create_blender_output:
+
+ export_to_blender(
+ recording_folder_path=str(recording_info.full_recording_path),
+ )
if report_progress is not None:
report_progress("Mocap complete", 1.0)
logger.info(