Skip to content

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

TypeScript

Add calibration diagnostics (#700)

Aaron Cherian6513b9ca1634
diff --git a/.github/workflows/diagnostics_calibration.yml b/.github/workflows/diagnostics_calibration.yml
new file mode 100644
index 00000000..ef03b76e
--- /dev/null
+++ b/.github/workflows/diagnostics_calibration.yml
@@ -0,0 +1,123 @@
+name: Run calibration diagnostics
+
+on:
+ pull_request:
+ branches: [ main ]
+ paths:
+ - 'freemocap/**'
+ push:
+ branches: [main]
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ run-diagnostics:
+ runs-on: ${{ matrix.os }}
+ strategy:
+ matrix:
+ os: [windows-latest, ubuntu-latest, macos-latest]
+ python-version: ["3.11"]
+
+ env:
+ PYTHONIOENCODING: utf-8
+ PYTHONUTF8: 1
+ PYTHONLEGACYWINDOWSSTDIO: 1
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+ with:
+ persist-credentials: false
+
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v4
+ with:
+ python-version: ${{ matrix.python-version }}
+
+ - name: Define recording path based on OS
+ shell: bash
+ run: |
+ if [[ "$RUNNER_OS" == "Windows" ]]; then
+ echo "RECORDING_PATH=C:/Users/runneradmin/freemocap_data/recording_sessions/freemocap_test_data" >> $GITHUB_ENV
+ elif [[ "$RUNNER_OS" == "Linux" ]]; then
+ echo "RECORDING_PATH=/home/runner/freemocap_data/recording_sessions/freemocap_test_data" >> $GITHUB_ENV
+ elif [[ "$RUNNER_OS" == "macOS" ]]; then
+ echo "RECORDING_PATH=/Users/runner/freemocap_data/recording_sessions/freemocap_test_data" >> $GITHUB_ENV
+ fi
+
+ - name: Install uv and dependencies
+ run: |
+ python -m pip install --upgrade pip
+ pip install uv
+ uv venv
+ uv pip install -e .
+
+ - name: Process test data
+ shell: bash
+ run: |
+ source .venv/bin/activate || source .venv/Scripts/activate
+ python freemocap/diagnostics/calibration/run_calibration.py
+
+ - name: Calculate diagnostics
+ shell: bash
+ run: |
+ source .venv/bin/activate || source .venv/Scripts/activate
+ python freemocap/diagnostics/calibration/calculate_calibration_diagnostics.py
+
+ - uses: actions/upload-artifact@v4
+ with:
+ name: data_current_calibration_${{ runner.os }}
+ path: data_current_calibration.csv
+
+ - name: Upload OS-specific calibration
+ uses: actions/upload-artifact@v4
+ with:
+ name: test_data_calibration_files${{ matrix.os }}
+ path: |
+ ${{ env.RECORDING_PATH }}/*camera_calibration*.toml
+ ${{ env.RECORDING_PATH }}/output_data/charuco_3d_xyz.npy
+ ${{ env.RECORDING_PATH }}/output_data/raw_data/charuco_2dData_numCams_numFrames_numTrackedPoints_pixelXY.npy
+
+
+ generate-report:
+ needs: run-diagnostics
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ persist-credentials: false
+
+ - name: Install uv and dependencies
+ run: |
+ python -m pip install --upgrade pip
+ pip install uv
+ uv venv
+ source .venv/bin/activate
+ uv pip install pandas plotly==5.* jinja2 packaging
+
+ - name: Download OS calibration data
+ uses: actions/download-artifact@v4
+ with:
+ pattern: data_current_calibration_*
+ path: collected
+
+ - name: Generate calibration diagnostic report
+ shell: bash
+ run: |
+ source .venv/bin/activate
+ python freemocap/diagnostics/calibration/merge_calibration_data.py
+
+ - name: Upload calibration report
+ uses: actions/upload-artifact@v4
+ with:
+ name: calibration_diagnostics_report
+ path: freemocap/diagnostics/calibration_diagnostics.html
+
+ - name: Upload summary csv
+ uses: actions/upload-artifact@v4
+ with:
+ name: calibration_diagnostics_csv
+ path: freemocap/diagnostics/diagnostic_data/calibration_diagnostics_summary.csv
diff --git a/freemocap/core_processes/capture_volume_calibration/save_3d_data_to_npy.py b/freemocap/core_processes/capture_volume_calibration/save_3d_data_to_npy.py
index 94476f2e..c82ffc2f 100644
--- a/freemocap/core_processes/capture_volume_calibration/save_3d_data_to_npy.py
+++ b/freemocap/core_processes/capture_volume_calibration/save_3d_data_to_npy.py
@@ -15,35 +15,35 @@ logger = logging.getLogger(__name__)
def save_3d_data_to_npy(
- data3d_numFrames_numTrackedPoints_XYZ: np.ndarray,
- data3d_numFrames_numTrackedPoints_reprojectionError: np.ndarray,
- data3d_numCams_numFrames_numTrackedPoints_reprojectionError: np.ndarray,
- path_to_folder_where_data_will_be_saved: Union[str, Path],
- processing_level: str,
- file_prefix: str = "",
+ data3d_numFrames_numTrackedPoints_XYZ: np.ndarray,
+ data3d_numFrames_numTrackedPoints_reprojectionError: np.ndarray,
+ data3d_numCams_numFrames_numTrackedPoints_reprojectionError: np.ndarray,
+ path_to_folder_where_data_will_be_saved: Union[str, Path],
+ processing_level: str,
+ file_prefix: str = "",
):
path_to_folder_where_data_will_be_saved = Path(path_to_folder_where_data_will_be_saved)
Path(path_to_folder_where_data_will_be_saved).mkdir(parents=True, exist_ok=True) # save spatial XYZ data
if processing_level == "raw":
data_3d_save_path = path_to_folder_where_data_will_be_saved / f"{file_prefix}_{RAW_3D_NPY_FILE_NAME}"
reprojection_error_save_path = (
- path_to_folder_where_data_will_be_saved / f"{file_prefix}_{REPROJECTION_ERROR_NPY_FILE_NAME}"
+ path_to_folder_where_data_will_be_saved / f"{file_prefix}_{REPROJECTION_ERROR_NPY_FILE_NAME}"
)
full_reprojection_error_save_path = (
- path_to_folder_where_data_will_be_saved / f"{file_prefix}_{FULL_REPROJECTION_ERROR_NPY_FILE_NAME}"
+ path_to_folder_where_data_will_be_saved / f"{file_prefix}_{FULL_REPROJECTION_ERROR_NPY_FILE_NAME}"
)
elif processing_level == "reprojection_filtered":
data_3d_save_path = (
- path_to_folder_where_data_will_be_saved
- / f"{REPROJECTION_FILTERED_PREFIX}{file_prefix}_{RAW_3D_NPY_FILE_NAME}"
+ path_to_folder_where_data_will_be_saved
+ / f"{REPROJECTION_FILTERED_PREFIX}{file_prefix}_{RAW_3D_NPY_FILE_NAME}"
)
reprojection_error_save_path = (
- path_to_folder_where_data_will_be_saved
- / f"{REPROJECTION_FILTERED_PREFIX}{file_prefix}_{REPROJECTION_ERROR_NPY_FILE_NAME}"
+ path_to_folder_where_data_will_be_saved
+ / f"{REPROJECTION_FILTERED_PREFIX}{file_prefix}_{REPROJECTION_ERROR_NPY_FILE_NAME}"
)
full_reprojection_error_save_path = (
- path_to_folder_where_data_will_be_saved
- / f"{REPROJECTION_FILTERED_PREFIX}{file_prefix}_{FULL_REPROJECTION_ERROR_NPY_FILE_NAME}"
+ path_to_folder_where_data_will_be_saved
+ / f"{REPROJECTION_FILTERED_PREFIX}{file_prefix}_{FULL_REPROJECTION_ERROR_NPY_FILE_NAME}"
)
else:
logger.exception(f"processing_level: {processing_level} not recognized")
diff --git a/freemocap/core_processes/process_motion_capture_videos/processing_pipeline_functions/image_tracking_pipeline_functions.py b/freemocap/core_processes/process_motion_capture_videos/processing_pipeline_functions/image_tracking_pipeline_functions.py
index 5ff0edd4..0ef2b67d 100644
--- a/freemocap/core_processes/process_motion_capture_videos/processing_pipeline_functions/image_tracking_pipeline_functions.py
+++ b/freemocap/core_processes/process_motion_capture_videos/processing_pipeline_functions/image_tracking_pipeline_functions.py
@@ -14,18 +14,20 @@ from freemocap.data_layer.recording_models.post_processing_parameter_models impo
)
from freemocap.system.logging.configure_logging import log_view_logging_format_string
from freemocap.system.logging.queue_logger import DirectQueueHandler
-from freemocap.system.paths_and_filenames.file_and_folder_names import LOG_VIEW_PROGRESS_BAR_STRING, \
- RAW_DATA_FOLDER_NAME
+from freemocap.system.paths_and_filenames.file_and_folder_names import (
+ LOG_VIEW_PROGRESS_BAR_STRING,
+ RAW_DATA_FOLDER_NAME,
+)
from freemocap.tests.test_image_tracking_data_shape import test_image_tracking_data_shape
logger = logging.getLogger(__name__)
def run_image_tracking_pipeline(
- processing_parameters: ProcessingParameterModel,
- kill_event: multiprocessing.Event,
- queue: multiprocessing.Queue,
- use_tqdm: bool,
+ processing_parameters: ProcessingParameterModel,
+ kill_event: multiprocessing.Event,
+ queue: multiprocessing.Queue,
+ use_tqdm: bool,
) -> np.ndarray:
if queue:
handler = DirectQueueHandler(queue)
@@ -54,7 +56,7 @@ def run_image_tracking_pipeline(
processing_parameters.recording_info_model.synchronized_videos_folder_path
),
output_data_folder_path=Path(processing_parameters.recording_info_model.output_data_folder_path)
- / RAW_DATA_FOLDER_NAME,
+ / RAW_DATA_FOLDER_NAME,
kill_event=kill_event,
use_tqdm=use_tqdm,
)
@@ -73,12 +75,12 @@ def run_image_tracking_pipeline(
def run_image_tracking(
- model_info: ModelInfo,
- tracking_params: BaseTrackingParams,
- synchronized_videos_folder_path: Path,
- output_data_folder_path: Path,
- kill_event: multiprocessing.Event = None,
- use_tqdm: bool = True,
+ model_info: ModelInfo,
+ tracking_params: BaseTrackingParams,
+ synchronized_videos_folder_path: Path,
+ output_data_folder_path: Path,
+ kill_event: multiprocessing.Event = None,
+ use_tqdm: bool = True,
):
if hasattr(tracking_params, "use_yolo_crop_method") and tracking_params.use_yolo_crop_method:
model_info.tracker_name = "YOLOMediapipeComboTracker"
diff --git a/freemocap/data_layer/recording_models/recording_info_model.py b/freemocap/data_layer/recording_models/recording_info_model.py
index fcca3917..5c34650b 100644
--- a/freemocap/data_layer/recording_models/recording_info_model.py
+++ b/freemocap/data_layer/recording_models/recording_info_model.py
@@ -41,11 +41,11 @@ logger = logging.getLogger(__name__)
class RecordingInfoModel:
def __init__(self, recording_folder_path: Union[Path, str], active_tracker: str = "mediapipe"):
if any(
- [
- Path(recording_folder_path).name == SYNCHRONIZED_VIDEOS_FOLDER_NAME,
- Path(recording_folder_path).name == ANNOTATED_VIDEOS_FOLDER_NAME,
- Path(recording_folder_path).name == OUTPUT_DATA_FOLDER_NAME,
- ]
+ [
+ Path(recording_folder_path).name == SYNCHRONIZED_VIDEOS_FOLDER_NAME,
+ Path(recording_folder_path).name == ANNOTATED_VIDEOS_FOLDER_NAME,
+ Path(recording_folder_path).name == OUTPUT_DATA_FOLDER_NAME,
+ ]
):
recording_folder_path = Path(recording_folder_path).parent
@@ -133,10 +133,10 @@ class RecordingInfoModel:
@property
def raw_data_3d_npy_file_path(self):
raw_data_path = (
- Path(self._path)
- / OUTPUT_DATA_FOLDER_NAME
- / RAW_DATA_FOLDER_NAME
- / (self.file_prefix + RAW_3D_NPY_FILE_NAME)
+ Path(self._path)
+ / OUTPUT_DATA_FOLDER_NAME
+ / RAW_DATA_FOLDER_NAME
+ / (self.file_prefix + RAW_3D_NPY_FILE_NAME)
)
old_raw_data_path = Path(self._path) / OUTPUT_DATA_FOLDER_NAME / RAW_DATA_FOLDER_NAME / OLD_RAW_3D_NPY_FILE_NAME
if self.active_tracker == "mediapipe" and old_raw_data_path.exists() and not raw_data_path.exists():
@@ -147,18 +147,18 @@ class RecordingInfoModel:
@property
def reprojection_error_data_npy_file_path(self):
reprojection_error_path = (
- Path(self._path)
- / OUTPUT_DATA_FOLDER_NAME
- / RAW_DATA_FOLDER_NAME
- / (self.file_prefix + REPROJECTION_ERROR_NPY_FILE_NAME)
+ Path(self._path)
+ / OUTPUT_DATA_FOLDER_NAME
+ / RAW_DATA_FOLDER_NAME
+ / (self.file_prefix + REPROJECTION_ERROR_NPY_FILE_NAME)
)
raw_reprojection_error_path = (
- Path(self._path) / OUTPUT_DATA_FOLDER_NAME / RAW_DATA_FOLDER_NAME / OLD_REPROJECTION_ERROR_NPY_FILE_NAME
+ Path(self._path) / OUTPUT_DATA_FOLDER_NAME / RAW_DATA_FOLDER_NAME / OLD_REPROJECTION_ERROR_NPY_FILE_NAME
)
if (
- self.active_tracker == "mediapipe"
- and raw_reprojection_error_path.exists()
- and not reprojection_error_path.exists()
+ self.active_tracker == "mediapipe"
+ and raw_reprojection_error_path.exists()
+ and not reprojection_error_path.exists()
):
return str(raw_reprojection_error_path)
else:
@@ -167,16 +167,16 @@ class RecordingInfoModel:
@property
def total_body_center_of_mass_npy_file_path(self):
total_body_com_path = (
- Path(self._path)
- / OUTPUT_DATA_FOLDER_NAME
- / CENTER_OF_MASS_FOLDER_NAME
- / (self.file_prefix + TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME)
+ Path(self._path)
+ / OUTPUT_DATA_FOLDER_NAME
+ / CENTER_OF_MASS_FOLDER_NAME
+ / (self.file_prefix + TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME)
)
raw_total_body_com_path = (
- Path(self._path)
- / OUTPUT_DATA_FOLDER_NAME
- / CENTER_OF_MASS_FOLDER_NAME
- / OLD_TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME
+ Path(self._path)
+ / OUTPUT_DATA_FOLDER_NAME
+ / CENTER_OF_MASS_FOLDER_NAME
+ / OLD_TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME
)
if self.active_tracker == "mediapipe" and raw_total_body_com_path.exists() and not total_body_com_path.exists():
return str(raw_total_body_com_path)
diff --git a/freemocap/diagnostics/calibration/calculate_calibration_diagnostics.py b/freemocap/diagnostics/calibration/calculate_calibration_diagnostics.py
new file mode 100644
index 00000000..3a1c8d1e
--- /dev/null
+++ b/freemocap/diagnostics/calibration/calculate_calibration_diagnostics.py
@@ -0,0 +1,70 @@
+import csv
+import json
+import platform
+from pathlib import Path
+
+import numpy as np
+
+from freemocap.diagnostics.calibration.calibration_utils import (
+ CharucoNeighborStats, get_neighbor_distances, get_neighbor_stats)
+
+
+def run(path_to_recording: Path):
+
+ path_to_3d_data = path_to_recording / "output_data" / "charuco_3d_xyz.npy"
+ charuco_3d_data = np.load(path_to_3d_data)
+ csv_save_path = Path("data_current_calibration.csv")
+
+ path_to_json = path_to_recording / "charuco_board_info.json"
+ with open(path_to_json, "r", encoding="utf-8") as fh:
+ charuco_board_info = json.load(fh)
+
+ charuco_square_size_mm = charuco_board_info["square_size_mm"]
+ number_of_squares_height = charuco_board_info["num_squares_height"]
+ number_of_squares_width = charuco_board_info["num_squares_width"]
+
+ distances_between_squares = get_neighbor_distances(
+ charuco_3d_data=charuco_3d_data,
+ number_of_squares_width=number_of_squares_width,
+ number_of_squares_height=number_of_squares_height,
+ )
+
+ square_stats: CharucoNeighborStats = get_neighbor_stats(
+ distances=distances_between_squares, charuco_square_size_mm=charuco_square_size_mm
+ )
+
+ raw_os = platform.system()
+ os_map = {"Darwin": "macOS", "Windows": "Windows", "Linux": "Linux"}
+ os_name = os_map.get(raw_os, raw_os)
+
+ row = {
+ "os": os_name, # Windows / Linux / Darwin
+ "version": "current", # tag for this run
+ "mean_distance": square_stats.mean_distance,
+ "median_distance": square_stats.median_distance,
+ "std_distance": square_stats.std_distance,
+ "mean_error": square_stats.mean_error,
+ }
+
+ with open(csv_save_path, "w", newline="") as fh:
+ writer = csv.DictWriter(fh, fieldnames=row.keys())
+ writer.writeheader()
+ writer.writerow(row)
+
+ print(f"βœ… one-row CSV written β†’ {csv_save_path}")
+
+
+if __name__ == "__main__":
+ # Use environment detection to handle different runners
+ import sys
+
+ if sys.platform.startswith("win"):
+ path_to_recording = Path(r"C:\Users\runneradmin\freemocap_data\recording_sessions\freemocap_test_data")
+ elif sys.platform.startswith("linux"):
+ path_to_recording = Path("/home/runner/freemocap_data/recording_sessions/freemocap_test_data")
+ elif sys.platform.startswith("darwin"):
+ path_to_recording = Path("/Users/runner/freemocap_data/recording_sessions/freemocap_test_data")
+ else:
+ raise RuntimeError(f"Unsupported OS: {sys.platform}")
+
+ run(path_to_recording=path_to_recording)
diff --git a/freemocap/diagnostics/calibration/calibration_utils.py b/freemocap/diagnostics/calibration/calibration_utils.py
new file mode 100644
index 00000000..5a1fa631
--- /dev/null
+++ b/freemocap/diagnostics/calibration/calibration_utils.py
@@ -0,0 +1,92 @@
+from pathlib import Path
+
+import numpy as np
+from pydantic import BaseModel
+from skellytracker.process_folder_of_videos import process_folder_of_videos
+from skellytracker.trackers.charuco_tracker.charuco_model_info import (
+ CharucoModelInfo, CharucoTrackingParams)
+
+
+class CharucoNeighborStats(BaseModel):
+ mean_distance: float
+ median_distance: float
+ std_distance: float
+ mean_error: float
+
+
+def get_charuco_2d_data(calibration_videos_folder_path: str | Path, num_processes: int = 1):
+ calibration_videos_folder_path = Path(calibration_videos_folder_path)
+ return process_folder_of_videos(
+ model_info=CharucoModelInfo(),
+ tracking_params=CharucoTrackingParams(),
+ synchronized_video_path=Path(calibration_videos_folder_path),
+ num_processes=num_processes,
+ )
+
+
+def get_charuco_neighbor_pairs(rows: int, cols: int):
+ neighbors = []
+ for row in range(rows):
+ for col in range(cols):
+ idx = row * cols + col
+ if col < cols - 1:
+ neighbors.append((idx, idx + 1)) # right neighbor
+ if row < rows - 1:
+ neighbors.append((idx, idx + cols)) # bottom neighbor
+ return neighbors
+
+
+def get_neighbor_distances(
+ number_of_squares_width: int, number_of_squares_height: int, charuco_3d_data: np.ndarray
+) -> list:
+ distances_per_frame = []
+ num_cols = number_of_squares_width - 1
+ num_rows = number_of_squares_height - 1
+
+ neighbor_pairs = get_charuco_neighbor_pairs(num_rows, num_cols)
+
+ for frame_num in range(charuco_3d_data.shape[0]):
+ points_3d = charuco_3d_data[frame_num]
+
+ # skip frames with missing points
+ if np.isnan(points_3d).any():
+ continue
+
+ marker_distances = []
+ for i, j in neighbor_pairs:
+ pt1, pt2 = points_3d[i], points_3d[j]
+ if not np.isnan(pt1).any() and not np.isnan(pt2).any():
+ distance = np.linalg.norm(pt2 - pt1)
+ marker_distances.append(distance)
+
+ if marker_distances:
+ distances_per_frame.append(marker_distances)
+ return np.array(distances_per_frame, dtype=np.float64)
+
+
+def get_neighbor_stats(distances: np.ndarray, charuco_square_size_mm: float) -> dict:
+ """Computes statistics for the distances between neighboring points"""
+ mean_distance = np.nanmean(distances)
+ median_distance = np.nanmedian(distances)
+ std_distance = np.nanstd(distances)
+ mean_error = mean_distance - charuco_square_size_mm
+
+ return CharucoNeighborStats(
+ mean_distance=mean_distance, median_distance=median_distance, std_distance=std_distance, mean_error=mean_error
+ )
+
+
+def calculate_calibration_diagnostics(
+ charuco_3d_data: np.ndarray,
+ charuco_square_size_mm: float,
+ number_of_squares_width: int,
+ number_of_squares_height: int,
+) -> CharucoNeighborStats:
+ distances = get_neighbor_distances(
+ number_of_squares_width=number_of_squares_width,
+ number_of_squares_height=number_of_squares_height,
+ charuco_3d_data=charuco_3d_data,
+ )
+
+ stats = get_neighbor_stats(distances=distances, charuco_square_size_mm=charuco_square_size_mm)
+ return stats
diff --git a/freemocap/diagnostics/calibration/generate_calibration_report.py b/freemocap/diagnostics/calibration/generate_calibration_report.py
new file mode 100644
index 00000000..c79b5643
--- /dev/null
+++ b/freemocap/diagnostics/calibration/generate_calibration_report.py
@@ -0,0 +1,328 @@
+from pathlib import Path
+
+import pandas as pd
+import plotly.graph_objects as go
+import plotly.io as pio
+from jinja2 import Template
+from packaging.version import Version
+from packaging.version import parse as vparse
+from plotly.subplots import make_subplots
+
+CURRENT_SENTINEL = Version("9999.0.0")
+EXPECTED = 58.0
+OS_ORDER = ["Windows", "macOS", "Linux"]
+
+
+def safe_parse(ver: str) -> Version:
+ """Parse semantic versions; return a giant sentinel for 'current'"""
+ return CURRENT_SENTINEL if ver == "current" else vparse(ver)
+
+
+def load_summary_data():
+ summary_csv = Path("freemocap/diagnostics/diagnostic_data/calibration_diagnostics_summary.csv")
+
+ print(f"Loading data from: {summary_csv}")
+ df = pd.read_csv(summary_csv)
+
+ # Standardize OS names - remove any whitespace and fix case
+ df["os"] = df["os"].str.strip()
+
+ # Add version_key for sorting
+ df["version_key"] = df["version"].apply(safe_parse)
+
+ # Calculate mean_error if not present
+ if "mean_error" not in df.columns:
+ df["mean_error"] = df["mean_distance"] - EXPECTED
+
+ # Sort by OS and version
+ df = df.sort_values(["os", "version_key"], ascending=[True, True])
+
+ return df
+
+
+def generate_figures(df):
+ OS_COLORS = {
+ "Windows": "rgb(0, 114, 178)", # blue
+ "macOS": "rgb(213, 94, 0)", # vermilion
+ "Linux": "rgb(0, 158, 115)", # bluish green
+ }
+ # Figure 1 – All OS mean distance over all versions
+ fig1 = go.Figure()
+
+ print("\n=== FIGURE 1 DATA ===")
+
+ for os_name in OS_ORDER:
+ # Try exact match first
+ os_df = df[df["os"] == os_name].sort_values("version_key")
+
+ print(f"\n{os_name}: {len(os_df)} data points")
+
+ if len(os_df) > 0:
+ print(f" Versions: {list(os_df['version'])}")
+ print(f" Values: {list(os_df['mean_distance'])}")
+
+ fig1.add_scatter(
+ x=os_df["version"],
+ y=os_df["mean_distance"],
+ mode="lines+markers",
+ name=os_name,
+ line=dict(width=2),
+ marker=dict(size=8, color=OS_COLORS.get(os_name, "gray")),
+ )
+
+ fig1.add_hline(
+ y=EXPECTED,
+ line_dash="dash",
+ line_color="black",
+ annotation_text="Expected size",
+ annotation_position="top right",
+ )
+
+ fig1.update_layout(
+ title="Mean Charuco Square Size (mm) – all operating systems",
+ yaxis_title="Square Size Estimate (mm)",
+ xaxis_title="FreeMoCap Version",
+ title_font=dict(size=20),
+ xaxis_title_font=dict(size=22),
+ yaxis_title_font=dict(size=20),
+ xaxis_tickfont=dict(size=16),
+ yaxis_tickfont=dict(size=18),
+ height=500,
+ showlegend=True,
+ legend=dict(x=0.02, y=0.98, xanchor="left", yanchor="top"),
+ )
+
+ # Figure 2 – Per OS, post-1.6.0
+ print("\n=== FIGURE 2 DATA ===")
+
+ # Filter for versions >= 1.6.0 (including "current")
+ post = df[(df["version_key"] >= vparse("1.6.0")) | (df["version"] == "current")]
+ print(f"Post-1.6.0 data: {len(post)} rows")
+ print(f"OS distribution: {post['os'].value_counts().to_dict()}")
+
+ fig2 = make_subplots(rows=1, cols=3, shared_yaxes=True, subplot_titles=OS_ORDER, horizontal_spacing=0.1)
+
+ for col, os_name in enumerate(OS_ORDER, start=1):
+ # Get data for this OS and sort by version
+ os_data = post[post["os"] == os_name].sort_values("version_key")
+
+ print(f"\n{os_name} (subplot {col}): {len(os_data)} points")
+ if len(os_data) > 0:
+ print(f" Versions: {list(os_data['version'])}")
+ print(f" Values: {list(os_data['mean_distance'])}")
+
+ if len(os_data) > 0:
+ # Add scatter plot with error bars
+ fig2.add_scatter(
+ x=os_data["version"],
+ y=os_data["mean_distance"],
+ error_y=dict(type="data", array=os_data["std_distance"], visible=True, width=4, thickness=2),
+ mode="markers",
+ marker=dict(size=10, color=OS_COLORS.get(os_name, "gray")),
+ showlegend=False,
+ row=1,
+ col=col,
+ )
+
+ # Add value annotations
+ for _, row in os_data.iterrows():
+ fig2.add_annotation(
+ x=row["version"],
+ y=row["mean_distance"] + row["std_distance"] + 0.3,
+ text=f"{row['mean_distance']:.2f}Β±{row['std_distance']:.2f}",
+ showarrow=False,
+ yanchor="bottom",
+ row=1,
+ col=col,
+ font=dict(size=10),
+ )
+
+ # Add expected line
+ fig2.add_hline(y=EXPECTED, line_dash="dash", line_color="black", row=1, col=col)
+
+ # Update x-axis
+ fig2.update_xaxes(tickfont=dict(size=14), title_font=dict(size=16), title_text="Version", row=1, col=col)
+
+ # Update y-axis (only for first subplot)
+ fig2.update_yaxes(
+ tickfont=dict(size=14),
+ title_font=dict(size=16),
+ title_text="Square-size estimate (mm)",
+ range=[EXPECTED - 3, EXPECTED + 3],
+ row=1,
+ col=1,
+ )
+
+ fig2.update_layout(title="Charuco Square Size Estimate – versions β‰₯ 1.6.0", title_font=dict(size=20), height=400)
+
+ # Figure 3 – Mean error plot
+ print("\n=== FIGURE 3 DATA ===")
+
+ fig3 = go.Figure()
+
+ for os_name in OS_ORDER:
+ os_data = post[post["os"] == os_name].sort_values("version_key")
+
+ print(f"\n{os_name}: {len(os_data)} points")
+ if len(os_data) > 0:
+ print(f" Versions: {list(os_data['version'])}")
+ print(f" Errors: {list(os_data['mean_error'])}")
+
+ if len(os_data) > 0:
+ fig3.add_trace(
+ go.Scatter(
+ x=os_data["version"],
+ y=os_data["mean_error"],
+ mode="lines+markers",
+ name=os_name,
+ line=dict(width=2),
+ marker=dict(size=8, color=OS_COLORS.get(os_name, "gray")),
+ )
+ )
+
+ fig3.add_hline(y=0, line_dash="dot", line_color="gray", annotation_text="No error", annotation_position="top right")
+
+ fig3.update_layout(
+ title="Mean Error in Square Size Estimate (Post v1.6.0)",
+ yaxis_title="Mean error (mm)",
+ xaxis_title="FreeMoCap version",
+ height=400,
+ xaxis_title_font=dict(size=22),
+ yaxis_title_font=dict(size=20),
+ xaxis_tickfont=dict(size=16),
+ yaxis_tickfont=dict(size=18),
+ showlegend=True,
+ legend=dict(x=0.02, y=0.98, xanchor="left", yanchor="top"),
+ )
+ fig3.update_yaxes(
+ range=[-0.5, 0.5],
+ )
+ return fig1, fig2, fig3
+
+
+def generate_summary_table(df):
+ print("\n=== TABLE DATA ===")
+
+ # Get the latest data for each OS (highest version_key)
+ latest = df.sort_values("version_key", ascending=False).groupby("os").first().reset_index()
+
+ print("Latest data per OS:")
+ print(latest[["os", "version", "mean_distance", "std_distance", "mean_error"]].to_string())
+
+ # Create ordered dataframe
+ ordered_latest = pd.DataFrame()
+ for os_name in OS_ORDER:
+ os_row = latest[latest["os"] == os_name]
+ if len(os_row) > 0:
+ ordered_latest = pd.concat([ordered_latest, os_row])
+
+ if len(ordered_latest) == 0:
+ print("WARNING: No data for table!")
+ ordered_latest = pd.DataFrame(
+ {"os": OS_ORDER, "mean_distance": [0, 0, 0], "std_distance": [0, 0, 0], "mean_error": [0, 0, 0]}
+ )
+
+ table = go.Figure(
+ data=[
+ go.Table(
+ header=dict(
+ values=["OS", "Mean Square Size Β± SD (mm)", "Mean Error (mm)"],
+ fill_color="lightgray",
+ align="center",
+ font=dict(size=18),
+ ),
+ cells=dict(
+ values=[
+ ordered_latest["os"],
+ [
+ f"{m:.2f} Β± {s:.2f}"
+ for m, s in zip(ordered_latest["mean_distance"], ordered_latest["std_distance"])
+ ],
+ [f"{e:.2f}" for e in ordered_latest["mean_error"]],
+ ],
+ align="center",
+ font=dict(size=16),
+ height=30,
+ fill_color="#f8f9fa",
+ ),
+ )
+ ]
+ )
+
+ table.update_layout(title="Latest Calibration Summary (per OS)", margin=dict(t=60, l=0, r=0), height=250)
+
+ return table
+
+
+def generate_html_report(df, output_path="freemocap/diagnostics/calibration_diagnostics.html"):
+ fig1, fig2, fig3 = generate_figures(df)
+ table = generate_summary_table(df)
+
+ template = Template(
+ """
+ <!DOCTYPE html>
+ <html>
+ <head>
+ <meta charset='utf-8'>
+ <title>Calibration Diagnostics Report</title>
+ <script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
+ <style>
+ body { font-family: Arial, sans-serif; margin: 40px; }
+ h1 { color: #333; }
+ .plot-container { margin: 20px 0; }
+ pre { background: #f0f0f0; padding: 10px; overflow-x: auto; }
+ </style>
+ </head>
+ <body>
+ <h1>Calibration Diagnostics Report</h1>
+
+ <hr><h2>Latest Calibration Summary (per OS)</h2>
+ <p>Expected square size: <strong>{{ expected }} mm</strong></p>
+ <div style='max-width:1200px; margin:auto;'>{{ table|safe }}</div>
+
+ <hr><h2>Mean Charuco Square Size Per OS</h2>
+ <div class="plot-container">{{ fig1|safe }}</div>
+ <p style='font-size:0.9em;'>Dashed line = expected size.</p>
+
+ <hr><h2>Mean Charuco Square Size – versions β‰₯ 1.6.0</h2>
+ <div class="plot-container">{{ fig2|safe }}</div>
+ <p style='font-size:0.9em;'>Error bars show Β±1 SD; numerical values annotated.</p>
+
+ <hr><h2>Mean Square Size Error – versions β‰₯ 1.6.0</h2>
+ <div class="plot-container">{{ fig3|safe }}</div>
+ </body>
+ </html>
+ """
+ )
+
+ # Capture debug info
+ import io
+ import sys
+
+ old_stdout = sys.stdout
+ sys.stdout = buffer = io.StringIO()
+
+ # Re-run data loading to capture debug output
+ _ = load_summary_data()
+
+ debug_output = buffer.getvalue()
+ sys.stdout = old_stdout
+
+ rendered = template.render(
+ fig1=pio.to_html(fig1, include_plotlyjs=False, full_html=False),
+ fig2=pio.to_html(fig2, include_plotlyjs=False, full_html=False),
+ fig3=pio.to_html(fig3, include_plotlyjs=False, full_html=False),
+ table=pio.to_html(table, include_plotlyjs=False, full_html=False),
+ expected=EXPECTED,
+ debug_info=debug_output,
+ )
+
+ output_file = Path(output_path)
+ output_file.parent.mkdir(parents=True, exist_ok=True)
+ output_file.write_text(rendered, encoding="utf-8")
+ print(f"\nβœ… Calibration report written to: {output_file.absolute()}")
+
+
+if __name__ == "__main__":
+ df = load_summary_data()
+ generate_html_report(df)
diff --git a/freemocap/diagnostics/calibration/merge_calibration_data.py b/freemocap/diagnostics/calibration/merge_calibration_data.py
new file mode 100644
index 00000000..a914ab38
--- /dev/null
+++ b/freemocap/diagnostics/calibration/merge_calibration_data.py
@@ -0,0 +1,102 @@
+import subprocess
+import sys
+from pathlib import Path
+
+import pandas as pd
+
+# repo root = three levels up from this script
+repo_root = Path(__file__).resolve().parents[3]
+print("🧭 repo_root =", repo_root)
+
+summary_csv = repo_root / "freemocap/diagnostics/diagnostic_data/calibration_diagnostics_summary.csv"
+collected = Path("collected") # where download-artifact puts the CSVs
+# 1) load existing summary
+if summary_csv.exists():
+ full_df = pd.read_csv(summary_csv)
+ print(f"Loaded existing summary with {len(full_df)} rows")
+else:
+ # Create empty dataframe with expected columns if file doesn't exist
+ full_df = pd.DataFrame(columns=["os", "version", "mean_distance", "median_distance", "std_distance", "mean_error"])
+ print("Created new summary dataframe")
+
+# 2) ingest rows
+csv_files = list(collected.glob("**/*.csv"))
+print(f"Found {len(csv_files)} CSV files to merge:")
+for f in csv_files:
+ print(f" - {f}")
+
+if not csv_files:
+ sys.exit("❌ No calibration rows found in ./collected")
+
+rows = []
+for f in csv_files:
+ try:
+ df = pd.read_csv(f)
+ print(f"\n Reading {f.name}:")
+ print(f" Shape: {df.shape}")
+ print(f" Columns: {list(df.columns)}")
+ if len(df) > 0:
+ print(" First row:")
+ print(f" OS: '{df.iloc[0]['os']}'")
+ print(f" Version: '{df.iloc[0]['version']}'")
+ print(f" Mean distance: {df.iloc[0]['mean_distance']}")
+ rows.append(df)
+ except Exception as e:
+ print(f" Error reading {f}: {e}")
+ # Try to read raw content
+ with open(f, "r") as fh:
+ print(f" Raw content of {f.name}:")
+ print(fh.read())
+
+
+if not rows:
+ sys.exit("❌ No valid CSV data found")
+
+new_df = pd.concat(rows, ignore_index=True)
+print(f"\nCombined into {len(new_df)} new rows")
+print("New data preview:")
+print(new_df.to_string())
+
+# Standardize OS names
+new_df["os"] = new_df["os"].str.strip()
+
+# 3) replace old 'current' rows and save
+full_df = full_df[full_df["version"] != "current"]
+full_df = pd.concat([full_df, new_df], ignore_index=True)
+
+# Ensure OS names are standardized
+full_df["os"] = full_df["os"].str.strip()
+
+# Remove duplicates - keep only the latest entry for each os/version combination
+print(f"Before deduplication: {len(full_df)} rows")
+full_df = full_df.drop_duplicates(subset=["os", "version"], keep="last")
+print(f"After deduplication: {len(full_df)} rows")
+
+print(f"Final dataframe has {len(full_df)} rows")
+print(f"OS values: {full_df['os'].unique()}")
+print(f"Version values: {full_df['version'].unique()}")
+
+# Show duplicate check
+duplicates = full_df[full_df.duplicated(subset=["os", "version"], keep=False)]
+if len(duplicates) > 0:
+ print(f"WARNING: Still have {len(duplicates)} duplicate rows!")
+ print(duplicates[["os", "version"]].value_counts())
+
+summary_csv.parent.mkdir(parents=True, exist_ok=True)
+full_df.to_csv(summary_csv, index=False)
+print(f"βœ… Summary updated: {summary_csv}")
+
+# 4) regenerate HTML
+report_script = repo_root / "freemocap/diagnostics/calibration/generate_calibration_report.py"
+if report_script.exists():
+ print(f"Running report generation script: {report_script}")
+ result = subprocess.run([sys.executable, str(report_script)], capture_output=True, text=True)
+ print("STDOUT:", result.stdout)
+ if result.stderr:
+ print("STDERR:", result.stderr)
+ if result.returncode != 0:
+ sys.exit(f"Report generation failed with code {result.returncode}")
+else:
+ print(f"⚠️ Report script not found at {report_script}")
+
+print("πŸŽ‰ Process complete!")
diff --git a/freemocap/diagnostics/calibration/run_calibration.py b/freemocap/diagnostics/calibration/run_calibration.py
new file mode 100644
index 00000000..4c45c271
--- /dev/null
+++ b/freemocap/diagnostics/calibration/run_calibration.py
@@ -0,0 +1,90 @@
+import json
+import logging
+from pathlib import Path
+
+import numpy as np
+
+from freemocap.core_processes.capture_volume_calibration.anipose_camera_calibration import \
+ freemocap_anipose
+from freemocap.core_processes.capture_volume_calibration.charuco_stuff.charuco_board_definition import \
+ CharucoBoardDefinition
+from freemocap.core_processes.capture_volume_calibration.run_anipose_capture_volume_calibration import \
+ run_anipose_capture_volume_calibration
+from freemocap.core_processes.capture_volume_calibration.triangulate_3d_data import \
+ triangulate_3d_data
+from freemocap.data_layer.recording_models.recording_info_model import \
+ RecordingInfoModel
+from freemocap.diagnostics.calibration.calibration_utils import \
+ get_charuco_2d_data
+from freemocap.diagnostics.download_data import download_test
+
+# Configure logging
+logger = logging.getLogger(__name__)
+
+
+class SessionInfo:
+ """
+ Stores paths to key processed data files.
+ """
+
+ sample_session_folder_path: str
+ recording_info_model: RecordingInfoModel
+
+
+def setup_session():
+ """
+ Downloads sample data and processes it.
+ Stores all important paths for easy access.
+ """
+ logger.info("Downloading sample data...")
+
+ SessionInfo.sample_session_folder_path = download_test()
+
+ logger.info("Initializing recording model...")
+ SessionInfo.recording_info_model = RecordingInfoModel(
+ recording_folder_path=SessionInfo.sample_session_folder_path,
+ active_tracker="mediapipe",
+ )
+
+ logger.info("Calibrating")
+
+ board_info_path = (
+ Path(SessionInfo.sample_session_folder_path) / "charuco_board_info.json"
+ ) # NOTE - I added this JSON to the sample data zip file to make it easier to get square size/height/width
+ with open(board_info_path, "r", encoding="utf-8") as fh:
+ board_info = json.load(fh)
+
+ charuco_square_size = board_info["square_size_mm"]
+ calibration_toml_path = run_anipose_capture_volume_calibration(
+ charuco_board_definition=CharucoBoardDefinition(),
+ calibration_videos_folder_path=get_synchronized_video_folder_path(),
+ charuco_square_size=charuco_square_size,
+ progress_callback=lambda _: None,
+ )
+
+ charuco_2d_xy = get_charuco_2d_data(
+ calibration_videos_folder_path=get_synchronized_video_folder_path(), num_processes=3
+ )
+
+ logger.info("Charuco 2d data detected successfully with shape: " f"{charuco_2d_xy.shape}")
+
+ charuco_2d_xy = charuco_2d_xy.astype(np.float64)
+
+ logger.info("Getting 3d Charuco data")
+ anipose_calibration_object = freemocap_anipose.CameraGroup.load(str(calibration_toml_path))
+
+ data_3d, *_ = triangulate_3d_data(
+ anipose_calibration_object=anipose_calibration_object, image_2d_data=charuco_2d_xy
+ )
+
+ np.save(Path(SessionInfo.sample_session_folder_path) / "output_data" / "charuco_3d_xyz.npy", data_3d)
+
+ logger.info("Session setup complete!")
+
+
+def get_synchronized_video_folder_path():
+ return Path(SessionInfo.recording_info_model.synchronized_videos_folder_path)
+
+
+if __name__ == "__main__":
+ setup_session()
diff --git a/freemocap/diagnostics/diagnostic_data/calibration_diagnostics_summary.csv b/freemocap/diagnostics/diagnostic_data/calibration_diagnostics_summary.csv
new file mode 100644
index 00000000..2a7ff426
--- /dev/null
+++ b/freemocap/diagnostics/diagnostic_data/calibration_diagnostics_summary.csv
@@ -0,0 +1,61 @@
+os,version,mean_distance,median_distance,std_distance,mean_error
+Linux,1.2.0,137.1659125,85.72783677,161.9539911,79.16591251
+Linux,1.2.1,136.4550822,85.41283424,161.6981303,78.45508221
+Linux,1.2.2,136.9657357,86.83022437,157.9398616,78.96573569
+Linux,1.3.0,136.8655837,85.65377829,162.1219615,78.8655837
+Linux,1.3.1,137.5314391,85.955015,162.1063861,79.53143909
+Linux,1.4.0,137.0702964,85.67454704,161.896084,79.07029636
+Linux,1.4.1,137.244204,85.77576155,161.7602418,79.24420399
+Linux,1.4.2,136.4372058,85.85042861,158.1908599,78.43720584
+Linux,1.4.3,136.6985914,85.53279152,161.447889,78.69859143
+Linux,1.4.4,136.4737415,85.39442055,160.9547187,78.47374154
+Linux,1.4.5,136.734567,85.56344645,161.375905,78.73456704
+Linux,1.4.6,136.6873677,85.55422858,161.2132639,78.68736771
+Linux,1.4.7,136.3062691,85.25731694,162.6032606,78.30626911
+Linux,1.5.1,135.0303057,84.65258036,160.1161796,77.0303057
+Linux,1.5.3,136.1912994,85.30827413,160.5058769,78.19129935
+Linux,1.5.4,136.1834643,85.27963098,160.0672174,78.18346433
+Linux,1.6.0,58.00787586,58.07475737,0.981988123,0.007875863
+Linux,1.6.1,58.04511361,58.08268581,0.975931752,0.045113608
+Linux,1.6.2,58.06129624,58.11158345,0.992606977,0.061296238
+Linux,1.6.3,57.99049774,58.05652691,0.957873111,-0.009502261
+macOS,1.2.0,120.5564851,87.09504696,160.8508056,62.55648511
+macOS,1.2.1,120.5882239,87.1308519,160.8619471,62.58822389
+macOS,1.2.2,120.5786148,87.11942996,160.8742867,62.57861476
+macOS,1.3.0,120.5776695,87.12395558,160.7987848,62.57766954
+macOS,1.3.1,120.567841,87.11540424,160.7942176,62.56784104
+macOS,1.4.0,120.5933584,87.13508913,160.8673389,62.59335843
+macOS,1.4.1,120.586529,87.12959735,160.8585454,62.58652902
+macOS,1.4.2,120.5806635,87.12114665,160.8733097,62.5806635
+macOS,1.4.3,120.5807553,87.12792503,160.7946022,62.58075527
+macOS,1.4.4,120.5819985,87.12178744,160.8786127,62.58199847
+macOS,1.4.5,120.5607187,87.11055544,160.7798159,62.56071865
+macOS,1.4.6,120.5539537,87.09248302,160.8504308,62.55395367
+macOS,1.4.7,120.6036479,87.14033672,160.9196291,62.60364792
+macOS,1.5.1,120.5695756,87.11824242,160.7869529,62.56957558
+macOS,1.5.3,120.5951622,87.13562214,160.8747511,62.59516224
+macOS,1.5.4,120.5855847,87.12504628,160.8824904,62.58558473
+macOS,1.6.0,58.05638804,58.10470142,0.988123189,0.056388035
+macOS,1.6.1,58.05689515,58.1052855,0.977694725,0.056895145
+macOS,1.6.2,58.06498102,58.10745317,0.983707682,0.064981016
+macOS,1.6.3,57.96582898,57.99550065,0.971996066,-0.034171019
+Windows,1.2.0,69.67834877,68.2427676,7.993329953,11.67834877
+Windows,1.2.1,69.23989087,67.71929943,7.620752575,11.23989087
+Windows,1.2.2,69.79847425,68.34529371,8.145847702,11.79847425
+Windows,1.3.0,69.97438269,68.22049004,8.378861732,11.97438269
+Windows,1.3.1,69.41931509,67.93259413,8.008037853,11.41931509
+Windows,1.4.0,69.51410791,68.08235321,7.919321351,11.51410791
+Windows,1.4.1,70.06368366,68.55487858,8.284212746,12.06368366
+Windows,1.4.2,70.56828573,68.86459353,8.838819923,12.56828573
+Windows,1.4.3,69.82715622,68.35279126,8.156902123,11.82715622
+Windows,1.4.4,69.40095613,67.90234459,7.903327447,11.40095613
+Windows,1.4.5,69.31196591,67.92273039,7.80299488,11.31196591
+Windows,1.4.6,69.24093676,67.90236105,7.73419367,11.24093676
+Windows,1.4.7,69.56870831,68.11136524,7.995141661,11.56870831
+Windows,1.5.1,69.87985111,68.33236362,8.424647154,11.87985111
+Windows,1.5.3,69.46175961,68.05512206,7.816077861,11.46175961
+Windows,1.5.4,69.60791988,68.16493039,7.979631383,11.60791988
+Windows,1.6.0,58.04015153,58.10293128,0.95369204,0.040151535
+Windows,1.6.1,58.05115498,58.09898241,0.954157286,0.051154976
+Windows,1.6.2,58.02978815,58.08949981,0.984754081,0.029788146
+Windows,1.6.3,58.04251716,58.08966553,0.976841876,0.042517156
diff --git a/freemocap/diagnostics/download_data.py b/freemocap/diagnostics/download_data.py
new file mode 100644
index 00000000..87d1f81e
--- /dev/null
+++ b/freemocap/diagnostics/download_data.py
@@ -0,0 +1,69 @@
+import io
+import logging
+import zipfile
+from dataclasses import dataclass
+from pathlib import Path
+
+import requests
+
+from freemocap.system.paths_and_filenames.path_getters import \
+ get_recording_session_folder_path
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class Sample:
+ url: str
+
+
+DATASETS = {
+ "test": Sample(
+ url="https://github.com/freemocap/skellysamples/releases/download/test_data_v06_09_25/freemocap_test_data.zip"
+ )
+}
+
+
+def get_dataset(key: str) -> Path:
+ try:
+ spec = DATASETS[key]
+ except KeyError:
+ raise ValueError(f"Unknown dataset '{key}'. Options: {list(DATASETS)}")
+
+ return Path(download_data(spec.url))
+
+
+def download_data(zip_file_url) -> str:
+ try:
+ logger.info(f"Downloading data from {zip_file_url}...")
+ recording_session_folder_path = Path(get_recording_session_folder_path())
+ recording_session_folder_path.mkdir(parents=True, exist_ok=True)
+ r = requests.get(zip_file_url, stream=True, timeout=(5, 60))
+ r.raise_for_status()
+
+ z = zipfile.ZipFile(io.BytesIO(r.content))
+ z.extractall(recording_session_folder_path)
+
+ recording_name = {
+ Path(p).parts[0] for p in z.namelist() if not p.endswith("/")
+ } # gets name of recording (top-level folder in zip file)
+ if len(recording_name) != 1:
+ raise ValueError(f"{zip_file_url!r} contained {len(recording_name)} top-level entries: {recording_name}")
+
+ data_path = recording_session_folder_path / recording_name.pop()
+ logger.info(f"Data extracted to {str(data_path)}")
+ return str(data_path)
+ except requests.exceptions.RequestException as e:
+ logger.error(f"Request failed: {e}")
+ raise e
+ except zipfile.BadZipFile as e:
+ logger.error(f"Failed to unzip the file: {e}")
+ raise e
+
+
+def download_test() -> str:
+ """
+ Downloads the test data zip file and extracts it to the recording session folder.
+ Returns the path to the extracted data.
+ """
+ return download_data(DATASETS["test"].url)
diff --git a/freemocap/gui/qt/actions_and_menus/menu_bar.py b/freemocap/gui/qt/actions_and_menus/menu_bar.py
index 54516e16..ef85682b 100644
--- a/freemocap/gui/qt/actions_and_menus/menu_bar.py
+++ b/freemocap/gui/qt/actions_and_menus/menu_bar.py
@@ -47,7 +47,7 @@ class MenuBar(QMenuBar):
#
# help menu
help_menu = self.addMenu("&Help")
- help_menu.addAction(actions.show_release_notes_action)
+ help_menu.addAction(actions.show_release_notes_action)
help_menu.addAction(actions.open_docs_action)
help_menu.addAction(actions.freemocap_foundation_action)
#
diff --git a/freemocap/gui/qt/freemocap_main.py b/freemocap/gui/qt/freemocap_main.py
index f0840b74..a9f938d4 100644
--- a/freemocap/gui/qt/freemocap_main.py
+++ b/freemocap/gui/qt/freemocap_main.py
@@ -6,10 +6,8 @@ from importlib.metadata import distributions
from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QApplication
-from freemocap.gui.qt.utilities.save_and_load_gui_state import save_gui_state
from freemocap.gui.qt.main_window.freemocap_main_window import MainWindow, EXIT_CODE_REBOOT
-from freemocap.gui.qt.widgets.release_notes_dialogs.tabbed_release_notes_types import ReleaseNotesDisplayOption
logging.getLogger("matplotlib").setLevel(logging.WARNING)
@@ -68,10 +66,6 @@ def handle_pop_ups(freemocap_main_window):
if not freemocap_main_window._gui_state.shown_latest_release_notes:
freemocap_main_window.open_release_notes_popup()
-
- f = 2
-
-
installed_packages = {dist.metadata["Name"] for dist in distributions()}
if "opencv-python" in installed_packages and "opencv-contrib-python" in installed_packages:
freemocap_main_window.open_opencv_conflict_dialog()
diff --git a/freemocap/gui/qt/utilities/save_and_load_gui_state.py b/freemocap/gui/qt/utilities/save_and_load_gui_state.py
index 176ca097..93987e3b 100644
--- a/freemocap/gui/qt/utilities/save_and_load_gui_state.py
+++ b/freemocap/gui/qt/utilities/save_and_load_gui_state.py
@@ -26,15 +26,17 @@ class GuiState(BaseModel):
def save_gui_state(gui_state: GuiState, file_pathstring: str | None = None) -> None:
from freemocap.system.paths_and_filenames.path_getters import get_gui_state_json_path
+
if file_pathstring is None:
file_pathstring = get_gui_state_json_path()
with open(file_pathstring, "w") as file:
json.dump(gui_state.model_dump(mode="json"), file, indent=4)
-def load_gui_state(file_pathstring: str|None=None) -> GuiState:
+def load_gui_state(file_pathstring: str | None = None) -> GuiState:
if file_pathstring is None:
from freemocap.system.paths_and_filenames.path_getters import get_gui_state_json_path
+
file_pathstring = get_gui_state_json_path()
try:
with open(file_pathstring, "r") as file:
diff --git a/freemocap/gui/qt/widgets/release_notes_dialogs/release_notes_content.py b/freemocap/gui/qt/widgets/release_notes_dialogs/release_notes_content.py
index f574bca4..f0c609f6 100644
--- a/freemocap/gui/qt/widgets/release_notes_dialogs/release_notes_content.py
+++ b/freemocap/gui/qt/widgets/release_notes_dialogs/release_notes_content.py
@@ -2,8 +2,10 @@ from dataclasses import dataclass
from freemocap.system.paths_and_filenames.file_and_folder_names import PATH_TO_FREEMOCAP_LOGO_SVG
-SKELLY_SWEAT_PNG = PATH_TO_FREEMOCAP_LOGO_SVG.replace("freemocap-logo-black-border.svg", "skelly-sweat.png")
-SKELLY_HEART_EYES_PNG = PATH_TO_FREEMOCAP_LOGO_SVG.replace("freemocap-logo-black-border.svg", "skelly-heart-eyes.png")
+SKELLY_SWEAT_PNG = PATH_TO_FREEMOCAP_LOGO_SVG.replace(
+ "freemocap-logo-black-border.svg", "skelly-sweat.png")
+SKELLY_HEART_EYES_PNG = PATH_TO_FREEMOCAP_LOGO_SVG.replace(
+ "freemocap-logo-black-border.svg", "skelly-heart-eyes.png")
@dataclass
@@ -108,7 +110,7 @@ def get_older_versions_content() -> ReleaseNoteContent:
tab_title="Older Versions",
content_title="Previous Versions",
content_html="""
- <p>For information about older versions, please visit our
+ <p>For information about older versions, please visit our
<a href='https://github.com/freemocap/freemocap/releases'>GitHub releases page</a>.</p>
""",
logo_path=None,
diff --git a/freemocap/gui/qt/widgets/release_notes_dialogs/release_notes_widgets.py b/freemocap/gui/qt/widgets/release_notes_dialogs/release_notes_widgets.py
index e62958d2..25174fa5 100644
--- a/freemocap/gui/qt/widgets/release_notes_dialogs/release_notes_widgets.py
+++ b/freemocap/gui/qt/widgets/release_notes_dialogs/release_notes_widgets.py
@@ -78,7 +78,8 @@ class ReleaseNotesDialog(QDialog):
pixmap = QPixmap(logo_path)
if not pixmap.isNull():
- scaled_pixmap = pixmap.scaled(150, 150, Qt.KeepAspectRatio, Qt.SmoothTransformation)
+ scaled_pixmap = pixmap.scaled(
+ 150, 150, Qt.KeepAspectRatio, Qt.SmoothTransformation)
logo_label.setPixmap(scaled_pixmap)
else:
print(f"Failed to load image: {logo_path}")
@@ -96,10 +97,16 @@ class ReleaseNotesDialog(QDialog):
if show_again_flag_name:
self._dont_show_again_checkbox = QCheckBox("Don't show this message again")
self._dont_show_again_checkbox.setStyleSheet("font-size: 13px;")
- self._dont_show_again_checkbox.stateChanged.connect(self._dont_show_again_checkbox_changed)
+ self._dont_show_again_checkbox.stateChanged.connect(
+ self._dont_show_again_checkbox_changed)
controls_layout.addWidget(self._dont_show_again_checkbox)
- controls_layout.addItem(QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
+ controls_layout.addItem(
+ QSpacerItem(
+ 40,
+ 20,
+ QSizePolicy.Expanding,
+ QSizePolicy.Minimum))
done_btn = QPushButton(self.get_button_text())
done_btn.setStyleSheet(self.get_button_style())
@@ -112,8 +119,13 @@ class ReleaseNotesDialog(QDialog):
"""Handle the 'don't show again' checkbox state change."""
flag_name = self.get_show_again_flag_name()
if flag_name and hasattr(self.gui_state, flag_name):
- setattr(self.gui_state, flag_name, not self._dont_show_again_checkbox.isChecked())
- save_gui_state(gui_state=self.gui_state, file_pathstring=get_gui_state_json_path())
+ setattr(
+ self.gui_state,
+ flag_name,
+ not self._dont_show_again_checkbox.isChecked())
+ save_gui_state(
+ gui_state=self.gui_state,
+ file_pathstring=get_gui_state_json_path())
def get_window_title(self) -> str:
"""Return the window title for the dialog."""
@@ -172,7 +184,8 @@ class ReleaseNotesDialog(QDialog):
class NewFeatureReleaseNotesDialog(ReleaseNotesDialog):
- def __init__(self, gui_state: GuiState, kill_thread_event: threading.Event, parent=None) -> None:
+ def __init__(self, gui_state: GuiState,
+ kill_thread_event: threading.Event, parent=None) -> None:
super().__init__(
gui_state=gui_state,
kill_thread_event=kill_thread_event,
@@ -195,19 +208,19 @@ class NewFeatureReleaseNotesDialog(ReleaseNotesDialog):
<p style="font-size: 20px; font-weight: bold; color: #2c3e50; margin-bottom: 15px;">
FreeMoCap v2.0 is Here!
</p>
-
+
<p>We're excited to announce the release of FreeMoCap v2.0 with several major improvements:</p>
-
+
<ul>
<li><span class="feature">Enhanced Tracking Accuracy:</span> Improved algorithms for more precise motion capture</li>
<li><span class="feature">Real-time Feedback:</span> Get immediate visual feedback during recording sessions</li>
<li><span class="feature">Extended Export Options:</span> New formats including FBX and BVH for better compatibility</li>
<li><span class="feature">Streamlined UI:</span> Redesigned interface for improved workflow</li>
</ul>
-
- <p>Check out our <a href="https://github.com/freemocap/freemocap/releases">release notes</a> for full details and our
+
+ <p>Check out our <a href="https://github.com/freemocap/freemocap/releases">release notes</a> for full details and our
<a href="https://freemocap.org/tutorial">tutorials</a> to get started with the new features.</p>
-
+
<p style="font-size: 13px; margin-top: 20px; color: #7f8c8d;">
Thank you to all our contributors and users for your continued support!
</p>
@@ -226,7 +239,8 @@ class NewFeatureReleaseNotesDialog(ReleaseNotesDialog):
# Path to the skelly sweat image
-SKELLY_SWEAT_SVG = PATH_TO_FREEMOCAP_LOGO_SVG.replace("freemocap-logo-black-border.svg", "skelly-sweat.png")
+SKELLY_SWEAT_SVG = PATH_TO_FREEMOCAP_LOGO_SVG.replace(
+ "freemocap-logo-black-border.svg", "skelly-sweat.png")
class ButterworthWarningDialog(ReleaseNotesDialog):
@@ -235,7 +249,8 @@ class ButterworthWarningDialog(ReleaseNotesDialog):
due to a bug in the Butterworth filtering.
"""
- def __init__(self, gui_state: GuiState, kill_thread_event: threading.Event, parent=None) -> None:
+ def __init__(self, gui_state: GuiState,
+ kill_thread_event: threading.Event, parent=None) -> None:
super().__init__(
gui_state=gui_state,
kill_thread_event=kill_thread_event,
@@ -297,6 +312,8 @@ if __name__ == "__main__":
from PySide6.QtWidgets import QApplication
app = QApplication(sys.argv)
- dialog = ButterworthWarningDialog(gui_state=GuiState(), kill_thread_event=threading.Event())
+ dialog = ButterworthWarningDialog(
+ gui_state=GuiState(),
+ kill_thread_event=threading.Event())
dialog.show()
sys.exit(app.exec())
diff --git a/freemocap/gui/qt/widgets/release_notes_dialogs/tabbed_release_notes_dialog.py b/freemocap/gui/qt/widgets/release_notes_dialogs/tabbed_release_notes_dialog.py
index aa654ad3..9bbb7352 100644
--- a/freemocap/gui/qt/widgets/release_notes_dialogs/tabbed_release_notes_dialog.py
+++ b/freemocap/gui/qt/widgets/release_notes_dialogs/tabbed_release_notes_dialog.py
@@ -38,7 +38,9 @@ class TabbedReleaseNotesDialog(QDialog):
self.setMinimumSize(min_width, min_height)
self.setWindowTitle("FreeMoCap Release Notes")
- self.setStyleSheet(ReleaseNotesStyles.get_dialog_style(dark_mode=self.dark_mode))
+ self.setStyleSheet(
+ ReleaseNotesStyles.get_dialog_style(
+ dark_mode=self.dark_mode))
# Main layout - horizontal to support side tabs
main_layout = QHBoxLayout()
@@ -49,7 +51,9 @@ class TabbedReleaseNotesDialog(QDialog):
# Create tab widget with tabs on the left side
self.tab_widget = QTabWidget()
self.tab_widget.setTabPosition(QTabWidget.South) # Set tabs to the left side
- self.tab_widget.setStyleSheet(ReleaseNotesStyles.get_tab_widget_style(dark_mode=self.dark_mode))
+ self.tab_widget.setStyleSheet(
+ ReleaseNotesStyles.get_tab_widget_style(
+ dark_mode=self.dark_mode))
self.tab_widget.tabBar().setElideMode(Qt.ElideNone)
@@ -82,7 +86,8 @@ class TabbedReleaseNotesDialog(QDialog):
# Add tab
self.tab_widget.addTab(tab, release_note.tab_title)
- def _create_release_notes_content(self, title: str, content: str, logo_path: str = None) -> QWidget:
+ def _create_release_notes_content(
+ self, title: str, content: str, logo_path: str = None) -> QWidget:
"""Create a widget with release notes content."""
content_widget = QWidget()
content_layout = QHBoxLayout(content_widget)
@@ -131,7 +136,8 @@ class TabbedReleaseNotesDialog(QDialog):
pixmap = QPixmap(logo_path)
if not pixmap.isNull():
- scaled_pixmap = pixmap.scaled(200, 200, Qt.KeepAspectRatio, Qt.SmoothTransformation)
+ scaled_pixmap = pixmap.scaled(
+ 200, 200, Qt.KeepAspectRatio, Qt.SmoothTransformation)
logo_label.setPixmap(scaled_pixmap)
else:
print(f"Failed to load image: {logo_path}")
@@ -141,8 +147,6 @@ class TabbedReleaseNotesDialog(QDialog):
return content_widget
-
-
if __name__ == "__main__":
import sys
from PySide6.QtWidgets import QApplication
@@ -152,7 +156,8 @@ if __name__ == "__main__":
# Show the new tabbed dialog with dark mode enabled
dialog = TabbedReleaseNotesDialog(
gui_state=load_gui_state(),
- kill_thread_event=threading.Event(), dark_mode=True # Set to True for dark mode, False for light mode
+ kill_thread_event=threading.Event(),
+ dark_mode=True, # Set to True for dark mode, False for light mode
)
dialog.show()