Free Motion Capture for Everyone ๐โจ
TypeScript
Jon/development (#757)
jonmatthis61a1497b05f9
diff --git a/.gitignore b/.gitignoreindex 5259ec9c..c9a46bb3 100644--- a/.gitignore+++ b/.gitignore@@ -159,4 +159,5 @@ freemocap/system/gui_state.json/tauri-nuxt-vue/.idea/realease/*pyapp-*/-pyapp.zip\ No newline at end of file+pyapp.zip+.vitediff --git a/freemocap-ui/.vite/deps_temp_11f3a1c5/package.json b/freemocap-ui/.vite/deps_temp_11f3a1c5/package.jsonnew file mode 100644index 00000000..3dbc1ca5--- /dev/null+++ b/freemocap-ui/.vite/deps_temp_11f3a1c5/package.json@@ -0,0 +1,3 @@+{+ "type": "module"+}diff --git a/freemocap-ui/README.md b/freemocap-ui/README.mdindex 0a643cfa..8386c138 100644--- a/freemocap-ui/README.md+++ b/freemocap-ui/README.md@@ -11,12 +11,14 @@ English | [็ฎไฝไธญๆ](README.zh-CN.md)## ๐ Overview๐ฆ Ready out of the box-๐ฏ Based on the official [template-react-ts](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts), project structure will be familiar to you+๐ฏ Based on the+official [template-react-ts](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts), project+structure will be familiar to you๐ฑ Easily extendable and customizable๐ช Supports Node.js API in the renderer process๐ฉ Supports C/C++ native addons๐ Debugger configuration included-๐ฅ Easy to implement multiple windows+๐ฅ Easy to implement multiple windows## ๐ซ Quick Setup@@ -41,7 +43,7 @@ npm run dev## ๐ Directory structureFamiliar React application structure, just with `electron` folder on the top :wink:-*Files in this folder will be separated from your React application and built into `dist-electron`*+*Files in this folder will be separated from your React application and built into `dist-electron`*```treeโโโ electron Electron-related codediff --git a/freemocap-ui/e2e/example.spec.ts b/freemocap-ui/e2e/example.spec.tsindex 88410ba6..6945042d 100644--- a/freemocap-ui/e2e/example.spec.ts+++ b/freemocap-ui/e2e/example.spec.ts@@ -1,8 +1,8 @@import {_electron as electron, expect, test} from "@playwright/test";test("homepage has title and links to intro page", async () => {- const app = await electron.launch({ args: [".", "--no-sandbox"] });- const page = await app.firstWindow();- expect(await page.title()).toBe("Electron + Vite + React");- await page.screenshot({ path: "e2e/screenshots/example.png" });+ const app = await electron.launch({args: [".", "--no-sandbox"]});+ const page = await app.firstWindow();+ expect(await page.title()).toBe("Electron + Vite + React");+ await page.screenshot({path: "e2e/screenshots/example.png"});});diff --git a/freemocap-ui/electron-builder.json b/freemocap-ui/electron-builder.jsonindex cdf12804..af64df5d 100644--- a/freemocap-ui/electron-builder.json+++ b/freemocap-ui/electron-builder.json@@ -7,12 +7,14 @@"dist-electron","dist","freemocap_server.exe",- "../shared/logo/freemocap_skelly_logo.ico"+ "../shared/freemocap-logo/freemocap-favicon.ico",+ "../shared/freemocap-logo/freemocap-logo.png"],- "icon": "../shared/logo/freemocap_skelly_logo.ico",+ "icon": "../shared/freemocap-logo/freemocap-favicon.ico","asar": true,"asarUnpack": [- "**/freemocap_server.exe"+ "**/freemocap_server.exe",+ "**/freemocap-logo.png"],"mac": {"artifactName": "${productName}_${version}_installer.${ext}",@@ -36,7 +38,7 @@"oneClick": false,"perMachine": false,"allowToChangeInstallationDirectory": true,- "deleteAppDataOnUninstall": false,+ "deleteAppDataOnUninstall": false},"publish": {"provider": "generic",diff --git a/freemocap-ui/electron/electron-env.d.ts b/freemocap-ui/electron/electron-env.d.tsdeleted file mode 100644index 82002233..00000000--- a/freemocap-ui/electron/electron-env.d.ts+++ /dev/null@@ -1,22 +0,0 @@--declare namespace NodeJS {- interface ProcessEnv {- VSCODE_DEBUG?: 'true'- /**- * The built directory structure- *- * ```tree- * โโโฌ dist-electron- * โ โโโฌ main- * โ โ โโโ index.js > Electron-Main- * โ โโโฌ preload- * โ โโโ index.mjs > Preload-Scripts- * โโโฌ dist- * โ โโโ index.html > Electron-Renderer- * ```- */- APP_ROOT: string- /** /dist/ or /public/ */- VITE_PUBLIC: string- }-}diff --git a/freemocap-ui/electron/main/api.ts b/freemocap-ui/electron/main/api.tsnew file mode 100644index 00000000..ad01c274--- /dev/null+++ b/freemocap-ui/electron/main/api.ts@@ -0,0 +1,328 @@+import { initTRPC } from '@trpc/server';+import { z } from 'zod';+import superjson from 'superjson';++// Services+import { PythonServer } from './services/python-server';+import { dialog, shell, app } from 'electron';+import path from 'node:path';+import fs from 'node:fs';+import { APP_PATHS } from './app-paths';++// Initialize tRPC+const t = initTRPC.create({+ transformer: superjson, // Handles Date/undefined/etc serialization+});++// Helper function to check if a directory contains video files+function hasVideoFiles(dirPath: string): boolean {+ if (!fs.existsSync(dirPath)) {+ return false;+ }++ try {+ const entries = fs.readdirSync(dirPath);+ const videoExtensions = ['.mp4', '.avi', '.mov', '.mkv', '.wmv', '.flv', '.webm'];++ return entries.some(entry => {+ const fullPath = path.join(dirPath, entry);+ const stats = fs.statSync(fullPath);++ if (stats.isFile()) {+ const ext = path.extname(entry).toLowerCase();+ return videoExtensions.includes(ext);+ }+ return false;+ });+ } catch (error) {+ console.error('Error checking for video files:', error);+ return false;+ }+}++// Helper function to find camera calibration TOML file+function findCameraCalibrationToml(dirPath: string): string | null {+ if (!fs.existsSync(dirPath)) {+ return null;+ }++ try {+ const entries = fs.readdirSync(dirPath);++ // Look for files matching pattern: *_camera_calibration.toml+ const calibrationFile = entries.find(entry => {+ const fullPath = path.join(dirPath, entry);+ const stats = fs.statSync(fullPath);++ return stats.isFile() &&+ entry.endsWith('_camera_calibration.toml');+ });++ return calibrationFile ? path.join(dirPath, calibrationFile) : null;+ } catch (error) {+ console.error('Error finding calibration TOML:', error);+ return null;+ }+}++// Create the main API router+export const api = t.router({+ // Python Server Management+ pythonServer: t.router({+ start: t.procedure+ .input(z.object({ exePath: z.string().nullable() }))+ .mutation(({ input }) => PythonServer.start(input.exePath)),++ stop: t.procedure+ .mutation(() => PythonServer.shutdown()),++ getExecutablePath: t.procedure+ .query(() => PythonServer.getCurrentExecutablePath()),++ getExecutableCandidates: t.procedure+ .query(() => PythonServer.validateAllCandidates()),++ refreshCandidates: t.procedure+ .mutation(() => PythonServer.refreshCandidates()),++ isRunning: t.procedure+ .query(() => PythonServer.isRunning()),++ getProcessInfo: t.procedure+ .query(() => PythonServer.getProcessInfo()),+ }),++ // File System Operations+ fileSystem: t.router({+ selectDirectory: t.procedure+ .mutation(async () => {+ const result = await dialog.showOpenDialog({+ properties: ['openDirectory'],+ });+ return result.canceled ? null : result.filePaths[0];+ }),++ openFolder: t.procedure+ .input(z.object({ path: z.string() }))+ .mutation(async ({ input }) => {+ await shell.openPath(input.path);+ return true;+ }),++ getHomeDirectory: t.procedure+ .query(() => app.getPath('home')),++ getFolderContents: t.procedure+ .input(z.object({ path: z.string() }))+ .query(({ input }) => {+ if (!fs.existsSync(input.path)) {+ throw new Error('Folder does not exist');+ }++ const entries = fs.readdirSync(input.path);+ return entries.map(entry => {+ const fullPath = path.join(input.path, entry);+ const stats = fs.statSync(fullPath);+ return {+ name: entry,+ path: fullPath,+ isDirectory: stats.isDirectory(),+ isFile: stats.isFile(),+ size: stats.size,+ modified: stats.mtime,+ };+ });+ }),++ selectExecutableFile: t.procedure+ .mutation(async () => {+ const result = await dialog.showOpenDialog({+ properties: ['openFile'],+ filters: [+ { name: 'Executable Files', extensions: ['exe'] },+ { name: 'All Files', extensions: ['*'] },+ ],+ });+ return result.canceled ? null : result.filePaths[0];+ }),++ validateCalibrationDirectory: t.procedure+ .input(z.object({ directoryPath: z.string() }))+ .query(({ input }) => {+ const result = {+ exists: false,+ canRecord: false,+ canCalibrate: false,+ cameraCalibrationTomlPath: null as string | null,+ hasSynchronizedVideos: false,+ hasVideos: false,+ errorMessage: null as string | null,+ };++ try {+ // Check if directory exists+ result.exists = fs.existsSync(input.directoryPath);++ if (!result.exists) {+ // Directory doesn't exist - can record here (will be created)+ result.canRecord = true;+ result.canCalibrate = false;+ return result;+ }++ // Directory exists - check its contents+ const stats = fs.statSync(input.directoryPath);++ if (!stats.isDirectory()) {+ result.errorMessage = 'Path exists but is not a directory';+ return result;+ }++ // Check for synchronized_videos folder+ const synchronizedVideosPath = path.join(input.directoryPath, 'synchronized_videos');+ result.hasSynchronizedVideos = fs.existsSync(synchronizedVideosPath) &&+ fs.statSync(synchronizedVideosPath).isDirectory();++ // Check for videos in synchronized_videos folder+ if (result.hasSynchronizedVideos) {+ result.hasVideos = hasVideoFiles(synchronizedVideosPath);+ }++ // If no synchronized_videos, check for videos in root directory+ if (!result.hasVideos) {+ result.hasVideos = hasVideoFiles(input.directoryPath);+ }++ // Determine if we can record+ // Can record if directory is empty or only has non-video files+ const entries = fs.readdirSync(input.directoryPath);+ result.canRecord = entries.length === 0 || !result.hasVideos;++ // Can calibrate if we have videos+ result.canCalibrate = result.hasVideos;++ // Look for camera calibration TOML file+ result.cameraCalibrationTomlPath = findCameraCalibrationToml(input.directoryPath);++ return result;++ } catch (error) {+ console.error('Error validating calibration directory:', error);+ result.errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';+ return result;+ }+ }),++ validateMocapDirectory: t.procedure+ .input(z.object({ directoryPath: z.string() }))+ .query(({ input }) => {+ const result = {+ exists: false,+ canRecord: false,+ canProcess: false,+ cameraCalibrationTomlPath: null as string | null,+ hasSynchronizedVideos: false,+ hasVideos: false,+ errorMessage: null as string | null,+ };++ try {+ // Check if directory exists+ result.exists = fs.existsSync(input.directoryPath);++ if (!result.exists) {+ // Directory doesn't exist - can record here (will be created)+ result.canRecord = true;+ result.canProcess = false;+ return result;+ }++ // Directory exists - check its contents+ const stats = fs.statSync(input.directoryPath);++ if (!stats.isDirectory()) {+ result.errorMessage = 'Path exists but is not a directory';+ return result;+ }++ // Check for synchronized_videos folder+ const synchronizedVideosPath = path.join(input.directoryPath, 'synchronized_videos');+ result.hasSynchronizedVideos = fs.existsSync(synchronizedVideosPath) &&+ fs.statSync(synchronizedVideosPath).isDirectory();++ // Check for videos in synchronized_videos folder+ if (result.hasSynchronizedVideos) {+ result.hasVideos = hasVideoFiles(synchronizedVideosPath);+ }++ // If no synchronized_videos, check for videos in root directory+ if (!result.hasVideos) {+ result.hasVideos = hasVideoFiles(input.directoryPath);+ }++ // Determine if we can record+ // Can record if directory is empty or only has non-video files+ const entries = fs.readdirSync(input.directoryPath);+ result.canRecord = !result.hasVideos;+ // Look for camera calibration TOML file+ result.cameraCalibrationTomlPath = findCameraCalibrationToml(input.directoryPath);++ // Can process if we have videos and a calibration file+ result.canProcess = result.hasVideos && result.cameraCalibrationTomlPath+++ return result;++ } catch (error) {+ console.error('Error validating calibration directory:', error);+ result.errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';+ return result;+ }+ }),+ }),++ // Asset Management+ assets: t.router({+ getLogoBase64: t.procedure+ .query((): string | null => {+ try {+ let logoPath: string | null = null;++ // Check for logo in order of preference+ if (fs.existsSync(APP_PATHS.FREEMOCAP_LOGO_PNG_SHARED_PATH)) {+ logoPath = APP_PATHS.FREEMOCAP_LOGO_PNG_SHARED_PATH;+ } else if (fs.existsSync(APP_PATHS.FREEMOCAP_LOGO_PNG_RESOURCES_PATH)) {+ logoPath = APP_PATHS.FREEMOCAP_LOGO_PNG_RESOURCES_PATH;+ }++ if (!logoPath) {+ console.error('Logo file not found in any expected location');+ return null;+ }++ // Read the file and convert to base64+ const imageBuffer = fs.readFileSync(logoPath);+ const base64String = imageBuffer.toString('base64');+ const mimeType = 'image/png'; // Since we know it's a PNG++ // Return as a data URL that can be used directly in img src+ return `data:${mimeType};base64,${base64String}`;+ } catch (error) {+ console.error('Failed to load logo as base64:', error);+ return null;+ }+ }),++ // Keep the old method for backward compatibility if needed+ getLogoPngPath: t.procedure+ .query(() => {+ if (fs.existsSync(APP_PATHS.FREEMOCAP_LOGO_PNG_SHARED_PATH)) {+ return APP_PATHS.FREEMOCAP_LOGO_PNG_SHARED_PATH;+ }+ return APP_PATHS.FREEMOCAP_LOGO_PNG_RESOURCES_PATH;+ }),+ }),+});++// Export the type for use in renderer+export type AppAPI = typeof api;diff --git a/freemocap-ui/electron/main/app-paths.ts b/freemocap-ui/electron/main/app-paths.tsnew file mode 100644index 00000000..c1224e95--- /dev/null+++ b/freemocap-ui/electron/main/app-paths.ts@@ -0,0 +1,63 @@+import path from "node:path";+import {fileURLToPath} from "node:url";+import {app} from "electron";++export const __dirname = path.dirname(fileURLToPath(import.meta.url));+++// Function to get the correct resources path based on environment+const getResourcesPath = () => {+ if (app.isPackaged) {+ const resourcesPath = path.join(process.resourcesPath, "app.asar.unpacked")+ console.log(`App is packaged. resourcesPath: ${resourcesPath}`);+ return resourcesPath;+ } else {+ const resourcesPath = path.join(__dirname, "../../");+ console.log(`App is in development. resourcesPath: ${resourcesPath}`);+ return resourcesPath;+ }++};++// Python server executable candidates in order of preference+export const PYTHON_EXECUTABLE_CANDIDATES = [+ {+ name: 'development',+ path: path.join(getResourcesPath(), '../dist/freemocap_server.exe'),+ description: 'Development build executable'+ },+ {+ name: 'installed',+ path: path.join(getResourcesPath(), 'freemocap_server.exe'),+ description: 'Executable in the installation folder'+ },++ {+ name: 'portable',+ path: path.join(process.cwd(), 'freemocap_server.exe'),+ description: 'Portable executable in current directory'+ },+ {+ name: 'system-path',+ path: 'freemocap_server.exe', // Will be found via PATH+ description: 'Executable available in system PATH'+ }+];++export const APP_PATHS = {+ PRELOAD: path.join(__dirname, "../preload/index.mjs"),+ RENDERER_HTML: path.join(__dirname, "../../dist/index.html"),+ FREEMOCAP_ICON_PATH: path.resolve(+ __dirname,+ "../../../shared/logo/freemocap-logo.ico"+ ),+ FREEMOCAP_LOGO_PNG_RESOURCES_PATH: path.join(getResourcesPath(), 'dist/freemocap-logo.png'),+ FREEMOCAP_LOGO_PNG_SHARED_PATH:path.resolve(+ __dirname,+ "../../../shared/logo/freemocap-logo.png"+ ),++};+++console.log(`APP_PATHS: ${JSON.stringify(APP_PATHS, null, 2)}`);diff --git a/freemocap-ui/electron/main/helpers/app-environment.ts b/freemocap-ui/electron/main/helpers/app-environment.tsdeleted file mode 100644index 8e53ab6a..00000000--- a/freemocap-ui/electron/main/helpers/app-environment.ts+++ /dev/null@@ -1,7 +0,0 @@--// Export the ENV_CONFIG object using the process.env values-export const APP_ENVIRONMENT = {- IS_DEV: process.env.NODE_ENV === 'development',- SHOULD_LAUNCH_PYTHON: false,--};diff --git a/freemocap-ui/electron/main/helpers/app-paths.ts b/freemocap-ui/electron/main/helpers/app-paths.tsdeleted file mode 100644index 3fecf0d8..00000000--- a/freemocap-ui/electron/main/helpers/app-paths.ts+++ /dev/null@@ -1,18 +0,0 @@-import path from "node:path";-import {fileURLToPath} from "node:url";--export const __dirname = path.dirname(fileURLToPath(import.meta.url));--export const APP_PATHS = {- PRELOAD: path.join(__dirname, '../preload/index.mjs'),- RENDERER_HTML: path.join(__dirname, '../../dist/index.html'),- PYTHON_SERVER_EXECUTABLE_PATH: path.resolve(process.resourcesPath, 'app.asar.unpacked/freemocap_server.exe'),- PYTHON_SERVER_EXECUTABLE_PATH_WINDOWS_INSTALL: "~/AppData/Local/Programs/freemocap/resources/app.asar.unpacked/freemocap_server.exe",-- PYTHON_SERVER_EXECUTABLE_DEV: path.resolve(__dirname, '../../freemocap_server.exe'),- FREEMOCAP_ICON_PATH: path.resolve(__dirname, '../../../shared/logo/freemocap_skelly_logo.ico'),- FREEMOCAP_PNG_PATH: path.resolve(__dirname, '../../../shared/logo/freemocap-skelly-logo-black-border-transparent-bkgd.png'),----};diff --git a/freemocap-ui/electron/main/helpers/ipc-manager.ts b/freemocap-ui/electron/main/helpers/ipc-manager.tsdeleted file mode 100644index 1d7963f1..00000000--- a/freemocap-ui/electron/main/helpers/ipc-manager.ts+++ /dev/null@@ -1,116 +0,0 @@-import {app, dialog, ipcMain, shell} from 'electron';-import {WindowManager} from "./window-manager";-import {PythonServer} from "./python-server";-import path from "node:path";-import fs from "node:fs";--export class IpcManager {- static initialize() {- this.handleWindowControls();- this.handlePythonControls();- this.handleFileSystemControls();- }-- private static handleWindowControls() {- ipcMain.handle('open-child-window', (_, route) => {- console.log('Opening child window with route:', route);- const child = WindowManager.createMainWindow();- child.loadURL(`${process.env.VITE_DEV_SERVER_URL}#${route}`);- });- }-- private static handleFileSystemControls() {- ipcMain.handle('select-directory', async () => {- const result = await dialog.showOpenDialog({- properties: ['openDirectory']- });-- if (!result.canceled && result.filePaths.length > 0) {- return result.filePaths[0];- }- return null;- });- ipcMain.handle('open-folder', async (_, folderPath: string) => {- try {- await shell.openPath(folderPath);- return true;- } catch (error) {- console.error('Failed to open folder:', error);- return false;- }- });- ipcMain.handle('get-home-directory', () => {- return app.getPath('home');- });--- ipcMain.handle('python-server:start', async (_, exePath: string | null) => {- console.log('Starting Python Server');-- await PythonServer.start(exePath);--- });-- ipcMain.handle('python-server:stop', async () => {- console.log('Stopping Python Server');- await PythonServer.shutdown();- });-- ipcMain.handle('get-folder-contents', async (_, folderPath: string) => {- try {- // Ensure the folder exists- if (!fs.existsSync(folderPath)) {- return {error: 'Folder does not exist', path: folderPath};- }-- // Get all files and directories in the folder- const entries = fs.readdirSync(folderPath);-- // Map the entries to include their details- const contents = entries.map(entry => {- const fullPath = path.join(folderPath, entry);- try {- const stats = fs.statSync(fullPath);- return {- name: entry,- path: fullPath,- isDirectory: stats.isDirectory(),- isFile: stats.isFile(),- size: stats.size,- created: stats.birthtime,- modified: stats.mtime,- accessed: stats.atime- };- } catch (err) {- // If we can't get stats for some reason, just return basic info- return {- name: entry,- path: fullPath,- error: 'Failed to get file stats'- };- }- });-- return {- path: folderPath,- contents: contents- };- } catch (error: any) {- console.error('Failed to get folder contents:', error);- return {- error: `Failed to get folder contents: ${error.message}`,- path: folderPath- };- }- });- }-- private static handlePythonControls() {- ipcMain.handle('restart-python-server', () => {- console.log('Restarting Python Server');- PythonServer.shutdown();- PythonServer.start(null);- });- }-}diff --git a/freemocap-ui/electron/main/helpers/logger.ts b/freemocap-ui/electron/main/helpers/logger.tsdeleted file mode 100644index 7907763d..00000000--- a/freemocap-ui/electron/main/helpers/logger.ts+++ /dev/null@@ -1,52 +0,0 @@-import {app, BrowserWindow} from 'electron';-import {APP_ENVIRONMENT} from "./app-environment";-import {APP_PATHS} from "./app-paths";-import {exec} from "child_process";--export class LifecycleLogger {- static logProcessInfo() {- console.log(`- ============================================- Starting FreeMoCap Electron App v${app.getVersion()}- \t- Environment: ${APP_ENVIRONMENT.IS_DEV ? 'Development' : 'Production'}- \t- Platform: ${process.platform}-${process.arch}- \t- Node: ${process.versions.node}- \t- Chrome: ${process.versions.chrome}- \t- Electron: ${process.versions.electron}- \t- Python Auto-Start: ${APP_ENVIRONMENT.SHOULD_LAUNCH_PYTHON}- ============================================`);- }-- static logWindowCreation(win: BrowserWindow) {- console.log(`- [Window Manager] Created main window- \t- ID: ${win.id}- \t- DevTools: ${APP_ENVIRONMENT.IS_DEV ? 'Open' : 'Closed'}- \t- Load URL: ${win.webContents.getURL()}`);- }-- static logPythonProcess(pythonProcess: ReturnType<typeof exec> ) {- console.log(`- [Python Server] Started external process- \t- PID: ${pythonProcess.pid}- \t- Command: ${pythonProcess.spawnargs.join(' ')}- \t- Executable: ${pythonProcess.spawnfile}- \t- Executable Path: ${APP_PATHS.PYTHON_SERVER_EXECUTABLE_PATH};- \t- Environment: ${JSON.stringify(APP_ENVIRONMENT)}`);- }-- static logIpcEvent(channel: string, sender: string) {- console.log(`- [IPC Event] ${new Date().toISOString()}- \t- Channel: ${channel}- \t- Origin: ${sender}`);- }-- static logShutdownSequence() {- console.log(`- [Shutdown] Initiating termination sequence- \t- Windows open: ${BrowserWindow.getAllWindows().length}- \t- Python running: ${process.env.SKELLYCAM_SHOULD_SHUTDOWN === 'true' ? 'No' : 'Yes'}- \t- Reason: Application closure requested`);- }-}diff --git a/freemocap-ui/electron/main/helpers/python-server.ts b/freemocap-ui/electron/main/helpers/python-server.tsdeleted file mode 100644index 3603da29..00000000--- a/freemocap-ui/electron/main/helpers/python-server.ts+++ /dev/null@@ -1,90 +0,0 @@-import {exec} from 'child_process';-import fs from 'node:fs';-import {LifecycleLogger} from "./logger";-import {APP_PATHS} from "./app-paths";-import {promisify} from 'util';-import treeKill from "tree-kill";-import {app} from "electron";--const treeKillAsync = promisify(treeKill);-let pythonProcess: ReturnType<typeof exec> | null = null;--export class PythonServer {- static async start(exePath: string | null) {- console.log('Starting python server subprocess');- let executablePath = APP_PATHS.PYTHON_SERVER_EXECUTABLE_PATH;- try {- await this.shutdown();-- if (exePath) {- if (!fs.existsSync(exePath)) {- throw new Error(`Provided executable path does not exist: ${exePath}`);- }- executablePath = exePath;- }- this.validateExecutable(executablePath);- } catch (error) {- try {- executablePath = APP_PATHS.PYTHON_SERVER_EXECUTABLE_PATH_WINDOWS_INSTALL- executablePath = executablePath.replace('~',app.getPath('home'));- this.validateExecutable(executablePath);- } catch (error) {- console.error('Error validating python server executable:', error);- throw error;- }- }- pythonProcess = exec(`"${executablePath}"`, {- env: {- ...process.env,- },- maxBuffer: 1024 * 1024 * 100 // 100MB buffer- });-- pythonProcess.on('exit', (code) => {- console.log(`Python exited (code: ${code})`);- });- if (!pythonProcess.pid) throw new Error('Python server failed to start!');- LifecycleLogger.logPythonProcess(pythonProcess);-- }-- static async shutdown() {- if (!pythonProcess || !pythonProcess.pid) return;- console.log('Sending SIGTERM to python process');-- try {- // Kill entire process tree- await treeKillAsync(pythonProcess.pid);- } catch (error) {- console.error('Error killing process tree:', error);- pythonProcess?.kill('SIGKILL'); // Fallback- }- if (!pythonProcess.exitCode) {- console.error('Python server did not exit cleanly');- treeKill(pythonProcess.pid, 'SIGKILL');- } else {- console.log('Python server exited cleanly');- }-- pythonProcess = null;- }-- private static validateExecutable(exePath: string) {- console.log('Validating python server executable...');- const checkPath = (path: string) => {- if (!fs.existsSync(path)) throw new Error(`Missing Python server at ${path}`);- console.log(`โ Found python server executable at: ${path}`);- try {- fs.accessSync(path, fs.constants.X_OK);- console.log(`โ Executable check passed for: ${path}`);- } catch (error) {- throw new Error(`โ File not executable: ${path}\n Details: ${error}`);- }- };-- checkPath(exePath);-- console.log(`Using python server executable at ${APP_PATHS.PYTHON_SERVER_EXECUTABLE_PATH}`);-- }-}diff --git a/freemocap-ui/electron/main/helpers/window-manager.ts b/freemocap-ui/electron/main/helpers/window-manager.tsdeleted file mode 100644index 85fbfe0e..00000000--- a/freemocap-ui/electron/main/helpers/window-manager.ts+++ /dev/null@@ -1,55 +0,0 @@-import {BrowserWindow, shell} from 'electron';-import {APP_PATHS} from "./app-paths";-import {APP_ENVIRONMENT} from "./app-environment";-import {LifecycleLogger} from "./logger";--export class WindowManager {- static createMainWindow() {- const window = new BrowserWindow({- title: 'FreeMoCap ๐๐ธ',- icon: APP_PATHS.FREEMOCAP_ICON_PATH,- width: 1280,- height: 720,- webPreferences: {- preload: APP_PATHS.PRELOAD,- contextIsolation: true,- nodeIntegration: false- }- });-- this.configureWindowHandlers(window);- this.loadContent(window);- LifecycleLogger.logWindowCreation(window);- return window;- }-- private static configureWindowHandlers(window: BrowserWindow) {- console.log('Configuring window handlers');- window.on('closed', () => {- console.log('Window closed');- });- window.webContents.on('did-finish-load', () => {- console.log('Window finished loading');- window.webContents.send('app-ready', Date.now());- });-- window.webContents.setWindowOpenHandler(({url}) => {- console.log('Opening window', url);- if (url.startsWith('https:')) shell.openExternal(url);- return {action: 'deny'};- });- }-- private static loadContent(window: BrowserWindow) {- console.log('Loading app content - APP_ENVIRONMENT.IS_DEV:', APP_ENVIRONMENT.IS_DEV);-- APP_ENVIRONMENT.IS_DEV- ? window.loadURL(process.env.VITE_DEV_SERVER_URL!)- : window.loadFile(APP_PATHS.RENDERER_HTML);-- if (APP_ENVIRONMENT.IS_DEV) {- // window.webContents.openDevTools();- }- }--}diff --git a/freemocap-ui/electron/main/index.ts b/freemocap-ui/electron/main/index.tsindex 110f63c5..2ea0958b 100644--- a/freemocap-ui/electron/main/index.ts+++ b/freemocap-ui/electron/main/index.ts@@ -1,52 +1,74 @@-import {app, BrowserWindow} from 'electron';-import {update} from './update';-import {IpcManager} from "./helpers/ipc-manager";-import {WindowManager} from "./helpers/window-manager";-import {PythonServer} from "./helpers/python-server";-import {LifecycleLogger} from "./helpers/logger";-import os from "node:os";+// electron/main/index.ts+import { app, BrowserWindow } from 'electron';+import { setupIPC } from './ipc';+import { WindowManager } from './services/window-manager';+import { PythonServer } from './services/python-server';+// import { UpdateHandler } from './services/update-handler';+import { LifecycleLogger } from './services/logger';+// import os from 'node:os'; // Uncomment if needed for platform-specific checks+// Export environment configuration+export const APP_ENVIRONMENT = {+ IS_DEV: process.env.NODE_ENV === 'development',+ VITE_DEV_SERVER_URL: process.env.VITE_DEV_SERVER_URL,+};-// Environment variables that `python` server will use for its lifecycle management-process.env.FREEMOCAP_RUNNING_IN_ELECTRON = 'true';-// Platform config-// Disable GPU Acceleration for Windows 7-if (os.release().startsWith('6.1')) app.disableHardwareAcceleration()+// if (os.release().startsWith('6.1')) app.disableHardwareAcceleration();if (process.platform === 'win32') app.setAppUserModelId(app.getName());-// Initialization Sequence-function startApplication() {- LifecycleLogger.logProcessInfo();- IpcManager.initialize();+// Prevent multiple instances+const gotTheLock = app.requestSingleInstanceLock();- app.whenReady()- .then(() => {- console.log('App is ready')+if (!gotTheLock) {+ app.quit();+} else {+ app.on('second-instance', () => {+ // Someone tried to run a second instance, focus our window instead+ const windows = BrowserWindow.getAllWindows();+ if (windows.length > 0) {+ const window = windows[0];+ if (window.isMinimized()) window.restore();+ window.focus();+ }+ });+ // App lifecycle+ app.whenReady().then(async () => {+ LifecycleLogger.logProcessInfo();+ console.log('App is ready');+ // Setup IPC+ setupIPC();+ // Create window+ const mainWindow = WindowManager.createMainWindow();- const mainWindow = WindowManager.createMainWindow();+ //TODO: Re-enable auto-updates+ // // Initialize auto-updater (only in production)+ // if (!APP_ENVIRONMENT.IS_DEV) {+ // UpdateHandler.initialize(mainWindow);+ // }- update(mainWindow);- });-}+ });-// Lifecycle Handlers-app.on('window-all-closed', async () => {- await PythonServer.shutdown();- app.quit();- LifecycleLogger.logShutdownSequence();-});--app.on('activate', () => {- if (BrowserWindow.getAllWindows().length === 0) {- WindowManager.createMainWindow();- }-});--// Start App-console.log('Starting application');-startApplication();+ app.on('window-all-closed', async () => {+ console.log('All windows closed, shutting down...');+ await PythonServer.shutdown();+ app.quit();+ });++ app.on('activate', () => {+ if (BrowserWindow.getAllWindows().length === 0) {+ WindowManager.createMainWindow();+ }+ });++ app.on('before-quit', async (event) => {+ event.preventDefault();+ console.log('App is quitting, cleaning up...');+ await PythonServer.shutdown();+ app.exit(0);+ });+}diff --git a/freemocap-ui/electron/main/ipc.ts b/freemocap-ui/electron/main/ipc.tsnew file mode 100644index 00000000..cf09c44f--- /dev/null+++ b/freemocap-ui/electron/main/ipc.ts@@ -0,0 +1,35 @@+// electron/main/ipc.ts+import { ipcMain } from 'electron';+import { api } from './api';+import superjson from 'superjson';++export function setupIPC(): void {+ ipcMain.handle('trpc', async (_event, { path, input }) => {+ try {+ const caller = api.createCaller({});++ const pathParts = path.split('.');+ let current: any = caller;++ for (let i = 0; i < pathParts.length - 1; i++) {+ current = current[pathParts[i]];+ if (!current) {+ throw new Error(`Router not found: ${pathParts.slice(0, i + 1).join('.')}`);+ }+ }++ const procedureName = pathParts[pathParts.length - 1];+ const fn = current[procedureName];++ if (typeof fn !== 'function') {+ throw new Error(`Procedure not found: ${path}`);+ }++ const result = await fn(input);+ return superjson.serialize(result);+ } catch (error) {+ console.error(`IPC Error for ${path}:`, error);+ throw error;+ }+ });+}diff --git a/freemocap-ui/electron/main/services/logger.ts b/freemocap-ui/electron/main/services/logger.tsnew file mode 100644index 00000000..deb6a09f--- /dev/null+++ b/freemocap-ui/electron/main/services/logger.ts@@ -0,0 +1,23 @@+import { app, BrowserWindow } from 'electron';+import { exec } from 'child_process';++export class LifecycleLogger {+ static logProcessInfo() {+ console.log(`+ ============================================+ Starting FreeMoCap v${app.getVersion()}+ Platform: ${process.platform}-${process.arch}+ Node: ${process.versions.node}+ Chrome: ${process.versions.chrome}+ Electron: ${process.versions.electron}+ ============================================`);+ }++ static logWindowCreation(win: BrowserWindow) {+ console.log(`[Window Manager] Created window ID: ${win.id}`);+ }++ static logPythonProcess(pythonProcess: ReturnType<typeof exec>) {+ console.log(`[Python Server] Started process PID: ${pythonProcess.pid}`);+ }+}diff --git a/freemocap-ui/electron/main/services/python-server.ts b/freemocap-ui/electron/main/services/python-server.tsnew file mode 100644index 00000000..c6b16365--- /dev/null+++ b/freemocap-ui/electron/main/services/python-server.ts@@ -0,0 +1,240 @@+import {exec} from 'child_process';+import fs from 'node:fs';+import path from 'node:path';+import {LifecycleLogger} from "./logger";+import {promisify} from 'util';+import treeKill from "tree-kill";+import {PYTHON_EXECUTABLE_CANDIDATES} from "../app-paths";++const treeKillAsync = promisify(treeKill);+let pythonProcess: ReturnType<typeof exec> | null = null;++export interface ExecutableCandidate {+ name: string;+ path: string;+ description: string;+ isValid?: boolean;+ error?: string;+ resolvedPath?: string; // Add resolved path for deduplication+}++export class PythonServer {+ private static currentExecutablePath: string | null = null;+ private static validatedCandidates: ExecutableCandidate[] = [];++ static async start(exePath: string | null = null) {+ console.log('Starting python server subprocess...');++ try {+ await this.shutdown();++ let executablePath: string;++ if (exePath) {+ // If specific path provided, validate it+ this.validateExecutable(exePath);+ executablePath = exePath;+ console.log(`Using provided executable path: ${executablePath}`);+ } else {+ // Find first valid executable from candidates+ executablePath = await this.findValidExecutablePath();+ console.log(`Using auto-detected executable path: ${executablePath}`);+ }++ this.currentExecutablePath = executablePath;+ console.log(`Launching Python server from: ${executablePath}`);+ pythonProcess = exec(`"${executablePath}"`, {+ env: {+ ...process.env,+ },+ maxBuffer: 1024 * 1024 * 100 // 100MB buffer+ });++ pythonProcess.on('exit', (code) => {+ console.log(`Python server exited (code: ${code})`);+ this.currentExecutablePath = null;+ });++ pythonProcess.on('error', (error) => {+ console.error('Python server process error:', error);+ this.currentExecutablePath = null;+ });++ if (!pythonProcess.pid) {+ throw new Error('Python server failed to start - no process ID');+ }++ LifecycleLogger.logPythonProcess(pythonProcess);+ console.log(`โ Python server started successfully (PID: ${pythonProcess.pid})`);++ } catch (error) {+ console.error('Failed to start Python server:', error);+ this.currentExecutablePath = null;+ throw error;+ }+ }++ static async shutdown() {+ if (!pythonProcess || !pythonProcess.pid) {+ console.log('No Python server process to shutdown');+ return;+ }++ console.log(`Shutting down Python server (PID: ${pythonProcess.pid})`);++ try {+ // Kill entire process tree+ await treeKillAsync(pythonProcess.pid);+ console.log('โ Python server process tree terminated');+ } catch (error) {+ console.error('Error killing process tree:', error);+ // Fallback to direct kill+ try {+ pythonProcess?.kill('SIGKILL');+ console.log('โ Python server force-killed as fallback');+ } catch (killError) {+ console.error('Failed to force-kill Python server:', killError);+ }+ }++ // Wait a moment for cleanup+ await new Promise(resolve => setTimeout(resolve, 1000));++ if (pythonProcess && !pythonProcess.killed) {+ console.warn('Python server may not have exited cleanly');+ }++ pythonProcess = null;+ this.currentExecutablePath = null;+ console.log('โ Python server shutdown complete');+ }++ static getCurrentExecutablePath(): string | null {+ return this.currentExecutablePath;+ }++ static async findValidExecutablePath(): Promise<string> {+ console.log('Searching for valid Python server executable...');++ // Validate all candidates if not done yet+ if (this.validatedCandidates.length === 0) {+ await this.validateAllCandidates();+ }++ // Find first valid candidate+ const validCandidate = this.validatedCandidates.find(candidate => candidate.isValid);++ if (!validCandidate) {+ const errorMessage = 'No valid Python server executable found in any candidate location:\n' ++ this.validatedCandidates.map(c => ` - ${c.name}: ${c.error || 'Unknown error'}`).join('\n');+ throw new Error(errorMessage);+ }++ console.log(`โ Selected executable: ${validCandidate.name} (${validCandidate.path})`);+ return validCandidate.path;+ }++ static async validateAllCandidates(): Promise<ExecutableCandidate[]> {+ console.log('Validating all executable candidates...');++ // First, validate all candidates+ const allValidatedCandidates = await Promise.all(+ PYTHON_EXECUTABLE_CANDIDATES.map(async (candidate) => {+ const validatedCandidate: ExecutableCandidate = {+ ...candidate,+ isValid: false+ };++ try {+ this.validateExecutable(candidate.path);+ validatedCandidate.isValid = true;+ // Store resolved path for deduplication+ validatedCandidate.resolvedPath = fs.existsSync(candidate.path)+ ? path.resolve(candidate.path)+ : candidate.path;+ console.log(` โ ${candidate.name}: Valid`);+ } catch (error) {+ validatedCandidate.error = error instanceof Error ? error.message : 'Unknown validation error';+ console.log(` โ ${candidate.name}: ${validatedCandidate.error}`);+ }++ return validatedCandidate;+ })+ );++ // Deduplicate by resolved path+ const seenPaths = new Set<string>();+ this.validatedCandidates = allValidatedCandidates.filter(candidate => {+ const pathKey = candidate.resolvedPath || candidate.path;++ // If we've seen this path before, skip it+ if (seenPaths.has(pathKey)) {+ console.log(` โ Skipping duplicate: ${candidate.name} (same as another candidate)`);+ return false;+ }++ // Add to seen paths+ seenPaths.add(pathKey);+ return true;+ });++ const validCount = this.validatedCandidates.filter(c => c.isValid).length;+ console.log(`Validation complete: ${validCount}/${this.validatedCandidates.length} unique candidates are valid`);++ return this.validatedCandidates;+ }++ static getPythonServerExecutableCandidates(): ExecutableCandidate[] {+ return [...this.validatedCandidates]; // Return copy to prevent mutation+ }++ static async refreshCandidates(): Promise<ExecutableCandidate[]> {+ console.log('Refreshing executable candidates validation...');+ this.validatedCandidates = [];+ return await this.validateAllCandidates();+ }++ static isRunning(): boolean {+ return pythonProcess !== null && pythonProcess.pid !== undefined && !pythonProcess.killed;+ }++ static getProcessInfo(): { pid: number | undefined; killed: boolean } | null {+ if (!pythonProcess) return null;++ return {+ pid: pythonProcess.pid,+ killed: pythonProcess.killed || false+ };+ }++ private static validateExecutable(exePath: string): void {+ // Check if file exists+ if (!fs.existsSync(exePath)) {+ throw new Error(`Executable not found at: ${exePath}`);+ }++ // Check if it's actually a file (not a directory)+ const stats = fs.statSync(exePath);+ if (!stats.isFile()) {+ throw new Error(`Path is not a file: ${exePath}`);+ }++ // Check if file is executable+ try {+ fs.accessSync(exePath, fs.constants.F_OK | fs.constants.R_OK);++ // On Windows, we mainly check if file exists and is readable+ // On Unix systems, we can check execute permissions+ if (process.platform !== 'win32') {+ fs.accessSync(exePath, fs.constants.X_OK);+ }+ } catch (error) {+ throw new Error(`File is not accessible or executable: ${exePath}`);+ }++ // Additional validation: check file extension on Windows+ if (process.platform === 'win32' && !exePath.toLowerCase().endsWith('.exe')) {+ console.warn(`Warning: Executable doesn't have .exe extension: ${exePath}`);+ }+ }+}\ No newline at end of filediff --git a/freemocap-ui/electron/main/services/update-handler.ts b/freemocap-ui/electron/main/services/update-handler.tsnew file mode 100644index 00000000..35bb6182--- /dev/null+++ b/freemocap-ui/electron/main/services/update-handler.ts@@ -0,0 +1,72 @@++import { app, ipcMain, BrowserWindow } from 'electron';+import { autoUpdater } from 'electron-updater';++export class UpdateHandler {+ private mainWindow: BrowserWindow;++ constructor(window: BrowserWindow) {+ this.mainWindow = window;+ this.setupAutoUpdater();+ this.registerIpcHandlers();+ }++ private setupAutoUpdater() {+ autoUpdater.autoDownload = false;+ autoUpdater.disableWebInstaller = false;+ autoUpdater.allowDowngrade = false;++ autoUpdater.on('checking-for-update', () => {+ console.log('Checking for updates...');+ });++ autoUpdater.on('update-available', (info) => {+ console.log('Update available:', info);+ this.mainWindow.webContents.send('update-available', {+ version: info.version,+ currentVersion: app.getVersion(),+ });+ });++ autoUpdater.on('update-not-available', () => {+ console.log('No updates available');+ });++ autoUpdater.on('download-progress', (progress) => {+ this.mainWindow.webContents.send('download-progress', progress);+ });++ autoUpdater.on('update-downloaded', () => {+ this.mainWindow.webContents.send('update-downloaded');+ });++ autoUpdater.on('error', (error) => {+ console.error('Update error:', error);+ this.mainWindow.webContents.send('update-error', error);+ });+ }++ private registerIpcHandlers() {+ ipcMain.handle('check-update', async () => {+ if (!app.isPackaged) {+ return {+ error: 'Updates only work in packaged app',+ available: false+ };+ }+ return await autoUpdater.checkForUpdatesAndNotify();+ });++ ipcMain.handle('download-update', async () => {+ return await autoUpdater.downloadUpdate();+ });++ ipcMain.handle('install-update', () => {+ autoUpdater.quitAndInstall(false, true);+ });+ }++ static initialize(window: BrowserWindow) {+ return new UpdateHandler(window);+ }+}diff --git a/freemocap-ui/electron/main/services/window-manager.ts b/freemocap-ui/electron/main/services/window-manager.tsnew file mode 100644index 00000000..70ce6ffd--- /dev/null+++ b/freemocap-ui/electron/main/services/window-manager.ts@@ -0,0 +1,113 @@+// electron/main/services/window-manager.ts+import { BrowserWindow, shell } from 'electron';+import { LifecycleLogger } from './logger';+import { APP_ENVIRONMENT } from '../index';+import {APP_PATHS} from "../app-paths";++export class WindowManager {+ private static mainWindow: BrowserWindow | null = null;++ static createMainWindow(): BrowserWindow {+ // Return existing window if already created+ if (this.mainWindow && !this.mainWindow.isDestroyed()) {+ return this.mainWindow;+ }++ const window = new BrowserWindow({+ title: 'Skellycam ๐๐ธ',+ icon: APP_PATHS.FREEMOCAP_ICON_PATH,+ width: 1280,+ height: 720,+ minWidth: 800,+ minHeight: 600,+ webPreferences: {+ preload: APP_PATHS.PRELOAD,+ contextIsolation: true,+ nodeIntegration: false,+ sandbox: true,+ },+ show: false, // Don't show until ready+ });++ this.mainWindow = window;+ this.configureWindowHandlers(window);+ this.loadContent(window);++ // Show window when ready+ window.once('ready-to-show', () => {+ window.show();+ LifecycleLogger.logWindowCreation(window);+ });++ return window;+ }++ private static configureWindowHandlers(window: BrowserWindow): void {+ console.log('Configuring window handlers');++ window.on('closed', () => {+ console.log('Window closed');+ this.mainWindow = null;+ });++ window.webContents.on('did-finish-load', () => {+ console.log('Window finished loading');+ window.webContents.send('app-ready', Date.now());+ });++ // Handle external links+ window.webContents.setWindowOpenHandler(({ url }) => {+ if (url.startsWith('http:') || url.startsWith('https:')) {+ shell.openExternal(url).catch(err =>+ console.error('Failed to open external link:', err)+ );+ }+ return { action: 'deny' };+ });++ // Intercept navigation to external links+ window.webContents.on('will-navigate', (event, url) => {+ const currentURL = window.webContents.getURL();++ // Allow navigation within the app+ if (APP_ENVIRONMENT.IS_DEV && url.startsWith(APP_ENVIRONMENT.VITE_DEV_SERVER_URL!)) {+ return;+ }++ if (!APP_ENVIRONMENT.IS_DEV && url.startsWith('file://')) {+ return;+ }++ // Prevent navigation to external URLs+ if (url.startsWith('http:') || url.startsWith('https:')) {+ event.preventDefault();+ shell.openExternal(url).catch(err =>+ console.error('Failed to open external link via navigation:', err)+ );+ }+ });++ // Handle crashes+ window.webContents.on('render-process-gone', (event, details) => {+ console.error('Renderer process gone:', details);+ if (details.reason === 'crashed') {+ window.reload();+ }+ });+ }++ private static loadContent(window: BrowserWindow): void {+ console.log('Loading app content - IS_DEV:', APP_ENVIRONMENT.IS_DEV);++ if (APP_ENVIRONMENT.IS_DEV && APP_ENVIRONMENT.VITE_DEV_SERVER_URL) {+ window.loadURL(APP_ENVIRONMENT.VITE_DEV_SERVER_URL);+ window.webContents.openDevTools();+ } else {+ window.loadFile(APP_PATHS.RENDERER_HTML);+ }+ }++ static getMainWindow(): BrowserWindow | null {+ return this.mainWindow;+ }+}diff --git a/freemocap-ui/electron/main/update.ts b/freemocap-ui/electron/main/update.tsdeleted file mode 100644index 6289b7b3..00000000--- a/freemocap-ui/electron/main/update.ts+++ /dev/null@@ -1,78 +0,0 @@-// electron/main/update.ts-import {app, ipcMain} from 'electron'-import {createRequire} from 'node:module'-import type {ProgressInfo, UpdateDownloadedEvent, UpdateInfo,} from 'electron-updater'--const { autoUpdater } = createRequire(import.meta.url)('electron-updater');--export function update(win: Electron.BrowserWindow) {-- // When set to false, the update download will be triggered through the API- autoUpdater.autoDownload = false- autoUpdater.disableWebInstaller = false- autoUpdater.allowDowngrade = false-- // start check- autoUpdater.on('checking-for-update', function () {- console.log('Checking for App update...')- })- // update available- autoUpdater.on('update-available', (arg: UpdateInfo) => {- console.log('App update available:', arg)- win.webContents.send('update-can-available', { update: true, version: app.getVersion(), newVersion: arg?.version })- })- // update not available- autoUpdater.on('update-not-available', (arg: UpdateInfo) => {- console.log('App update not available:', arg)- win.webContents.send('update-can-available', { update: false, version: app.getVersion(), newVersion: arg?.version })- })-- // Checking for updates- ipcMain.handle('check-update', async () => {- if (!app.isPackaged) {- const error = new Error('The update feature is only available after the package.')- return { message: error.message, error }- }-- try {- return await autoUpdater.checkForUpdatesAndNotify()- } catch (error) {- return { message: 'Network error', error }- }- })-- // Start downloading and feedback on progress- ipcMain.handle('start-download', (event: Electron.IpcMainInvokeEvent) => {- console.log('Start downloading...')- startDownload(- (error, progressInfo) => {- if (error) {- // feedback download error message- event.sender.send('update-error', { message: error.message, error })- } else {- // feedback update progress message- event.sender.send('download-progress', progressInfo)- }- },- () => {- // feedback update downloaded message- event.sender.send('update-downloaded')- }- )- })-- // Install now- ipcMain.handle('quit-and-install', () => {- autoUpdater.quitAndInstall(false, true)- })-}--function startDownload(- callback: (error: Error | null, info: ProgressInfo | null) => void,- complete: (event: UpdateDownloadedEvent) => void,-) {- autoUpdater.on('download-progress', (info: ProgressInfo) => callback(null, info))- autoUpdater.on('error', (error: Error) => callback(error, null))- autoUpdater.on('update-downloaded', complete)- autoUpdater.downloadUpdate()-}diff --git a/freemocap-ui/electron/preload/index.ts b/freemocap-ui/electron/preload/index.tsindex a5199c90..f088b918 100644--- a/freemocap-ui/electron/preload/index.ts+++ b/freemocap-ui/electron/preload/index.ts@@ -1,130 +1,8 @@-// /electron/preload/index.ts-import {contextBridge, ipcRenderer} from 'electron'-// Expose a limited API to the renderer process-contextBridge.exposeInMainWorld('electronAPI', {- // Specific functionality- selectDirectory: () => ipcRenderer.invoke('select-directory'),- openFolder: (folderPath: string) => ipcRenderer.invoke('open-folder', folderPath),- getHomeDirectory: () => ipcRenderer.invoke('get-home-directory'),- getFolderContents: (folderPath: string) => ipcRenderer.invoke('get-folder-contents', folderPath),- startPythonServer: (exePath: string | null) => ipcRenderer.invoke('python-server:start', exePath),- stopPythonServer: () => ipcRenderer.invoke('python-server:stop'),--})-// --------- Expose some API to the Renderer process ----------contextBridge.exposeInMainWorld('ipcRenderer', {- on(...args: Parameters<typeof ipcRenderer.on>) {- const [channel, listener] = args- return ipcRenderer.on(channel, (event, ...args) => listener(event, ...args))- },- off(...args: Parameters<typeof ipcRenderer.off>) {- const [channel, ...omit] = args- return ipcRenderer.off(channel, ...omit)- },- send(...args: Parameters<typeof ipcRenderer.send>) {- const [channel, ...omit] = args- return ipcRenderer.send(channel, ...omit)- },- invoke(...args: Parameters<typeof ipcRenderer.invoke>) {- const [channel, ...omit] = args- return ipcRenderer.invoke(channel, ...omit)- },-- // You can expose other APTs you need here.- // ...-})--// --------- Preload scripts loading ----------function domReady(condition: DocumentReadyState[] = ['complete', 'interactive']) {- console.log('Document Object Model (DOM) is ready.')- return new Promise(resolve => {- if (condition.includes(document.readyState)) {- resolve(true)- } else {- document.addEventListener('readystatechange', () => {- if (condition.includes(document.readyState)) {- resolve(true)- }- })- }- })-}--const safeDOM = {- append(parent: HTMLElement, child: HTMLElement) {- if (!Array.from(parent.children).find(e => e === child)) {- return parent.appendChild(child)- }- },- remove(parent: HTMLElement, child: HTMLElement) {- if (Array.from(parent.children).find(e => e === child)) {- return parent.removeChild(child)- }- },-}--/**- * https://tobiasahlin.com/spinkit- * https://connoratherton.com/loaders- * https://projects.lukehaas.me/css-loaders- * https://matejkustec.github.io/SpinThatShit- */-function useLoading() {- const className = `loaders-css__square-spin`- const styleContent = `-@keyframes square-spin {- 25% { transform: perspective(100px) rotateX(180deg) rotateY(0); }- 50% { transform: perspective(100px) rotateX(180deg) rotateY(180deg); }- 75% { transform: perspective(100px) rotateX(0) rotateY(180deg); }- 100% { transform: perspective(100px) rotateX(0) rotateY(0); }-}-.${className} > div {- animation-fill-mode: both;- width: 50px;- height: 50px;- background: #fff;- animation: square-spin 3s 0s cubic-bezier(0.09, 0.57, 0.49, 0.9) infinite;-}-.app-loading-wrap {- position: fixed;- top: 0;- left: 0;- width: 100vw;- height: 100vh;- display: flex;- align-items: center;- justify-content: center;- background: #282c34;- z-index: 9;-}- `- const oStyle = document.createElement('style')- const oDiv = document.createElement('div')- oStyle.id = 'app-loading-style'- oStyle.innerHTML = styleContent- oDiv.className = 'app-loading-wrap'- oDiv.innerHTML = `<div class="${className}"><div></div></div>`+import { contextBridge, ipcRenderer } from 'electron';- return {- appendLoading() {- safeDOM.append(document.head, oStyle)- safeDOM.append(document.body, oDiv)- },- removeLoading() {- safeDOM.remove(document.head, oStyle)- safeDOM.remove(document.body, oDiv)- },- }-}--// ------------------------------------------------------------------------const { appendLoading, removeLoading } = useLoading()-domReady().then(appendLoading)--window.onmessage = (ev) => {- ev.data.payload === 'removeLoading' && removeLoading()-}--setTimeout(removeLoading, 4999)+// Expose a simple tRPC bridge+contextBridge.exposeInMainWorld('electronAPI', {+ invoke: (path: string, input?: any) =>+ ipcRenderer.invoke('trpc', { path, input })+});diff --git a/freemocap-ui/index.html b/freemocap-ui/index.htmlindex fec8c78b..037bbe43 100644--- a/freemocap-ui/index.html+++ b/freemocap-ui/index.html@@ -1,14 +1,14 @@<!DOCTYPE html><html lang="en">- <head>- <meta charset="UTF-8" />- <link rel="icon" type="image/x-icon" href="/favicon.ico" />- <meta name="viewport" content="width=device-width, initial-scale=1.0" />- <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />+<head>+ <meta charset="UTF-8"/>+ <link href="/favicon.ico" rel="icon" type="image/x-icon"/>+ <meta content="width=device-width, initial-scale=1.0" name="viewport"/>+ <meta content="script-src 'self' 'unsafe-inline'; worker-src blob:;" http-equiv="Content-Security-Policy"/><title>FreeMoCap๐โจ</title>- </head>- <body>- <div id="root"></div>- <script type="module" src="/src/main.tsx"></script>- </body>+</head>+<body>+<div id="root"></div>+<script src="/src/main.tsx" type="module"></script>+</body></html>diff --git a/freemocap-ui/package.json b/freemocap-ui/package.jsonindex 3d7035a0..8f543783 100644--- a/freemocap-ui/package.json+++ b/freemocap-ui/package.json@@ -2,7 +2,8 @@"name": "freemocap","version": "2.0.0","main": "dist-electron/main/index.js",- "description": "FreeMoCap - Free and Open Source Markerless Motion Capture",+ "description": "FreeMocap - Free open source markerless motion capture for everyone.",+ "homepage": "https://freemocap.org","author": "Skelly FreeMocap <[email protected]>","license": "AGPL-3.0-or-later","debug": {@@ -14,7 +15,7 @@"scripts": {"dev": "cross-env NODE_ENV=development vite","demo": "cross-env NODE_ENV=production vite build && electron .",- "build": "tsc && vite build && electron-builder",+ "build": "cross-env NODE_ENV=production && tsc && vite build && electron-builder","preview": "vite preview","pree2e": "vite build --mode=test","e2e": "playwright test"@@ -28,10 +29,12 @@"@msgpack/msgpack": "^3.0.0-beta2","@mui/icons-material": "^6.4.5","@mui/material": "^6.1.1",- "@mui/x-tree-view": "^7.28.1",+ "@mui/x-tree-view": "^7.29.1","@react-three/drei": "^10.4.2","@react-three/fiber": "^9.1.4","@reduxjs/toolkit": "^2.5.1",+ "@trpc/client": "^11.5.1",+ "@trpc/server": "^11.5.1","axios": "^1.7.7","d3": "^7.9.0","electron-updater": "^6.1.8",@@ -41,9 +44,10 @@"react-router": "^6.26.2","react-router-dom": "^6.26.2","react-use": "^17.5.1",+ "superjson": "^2.2.2","three": "^0.178.0","tree-kill": "^1.2.2",- "zod": "^4.0.3"+ "zod": "^4.1.5"},"devDependencies": {"@playwright/test": "^1.42.1",@@ -51,17 +55,12 @@"@types/react": "^18.2.64","@types/react-dom": "^18.2.21","@vitejs/plugin-react": "^4.3.3",- "autoprefixer": "^10.4.18","cross-env": "^7.0.3","electron": "^35.0.3","electron-builder": "^24.13.3","electron-devtools-installer": "^4.0.0",- "postcss": "^8.4.35",- "postcss-import": "^16.0.1","react": "^19.1.0","react-dom": "^19.1.0",- "tailwindcss": "^3.4.1",- "typescript": "^5.4.2","vite": "^5.1.5","vite-plugin-electron": "^0.28.8","vite-plugin-electron-renderer": "^0.14.5"diff --git a/freemocap-ui/playwright.config.ts b/freemocap-ui/playwright.config.tsindex c0b96996..25b3278b 100644--- a/freemocap-ui/playwright.config.ts+++ b/freemocap-ui/playwright.config.ts@@ -10,45 +10,45 @@ import type {PlaywrightTestConfig} from "@playwright/test";* See https://playwright.dev/docs/test-configuration.*/const config: PlaywrightTestConfig = {- testDir: "./e2e",- /* Maximum time one test can run for. */- timeout: 30 * 1000,- expect: {- /**- * Maximum time expect() should wait for the condition to be met.- * For example in `await expect(locator).toHaveText();`- */- timeout: 5000,- },- /* Run tests in files in parallel */- fullyParallel: true,- /* Fail the build on CI if you accidentally left test.only in the source code. */- forbidOnly: !!process.env.CI,- /* Retry on CI only */- retries: process.env.CI ? 2 : 0,- /* Opt out of parallel tests on CI. */- workers: process.env.CI ? 1 : undefined,- /* Reporter to use. See https://playwright.dev/docs/test-reporters */- reporter: "html",- /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */- use: {- /* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */- actionTimeout: 0,- /* Base URL to use in actions like `await page.goto('/')`. */- // baseURL: 'http://localhost:3000',+ testDir: "./e2e",+ /* Maximum time one test can run for. */+ timeout: 30 * 1000,+ expect: {+ /**+ * Maximum time expect() should wait for the condition to be met.+ * For example in `await expect(locator).toHaveText();`+ */+ timeout: 5000,+ },+ /* Run tests in files in parallel */+ fullyParallel: true,+ /* Fail the build on CI if you accidentally left test.only in the source code. */+ forbidOnly: !!process.env.CI,+ /* Retry on CI only */+ retries: process.env.CI ? 2 : 0,+ /* Opt out of parallel tests on CI. */+ workers: process.env.CI ? 1 : undefined,+ /* Reporter to use. See https://playwright.dev/docs/test-reporters */+ reporter: "html",+ /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */+ use: {+ /* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */+ actionTimeout: 0,+ /* Base URL to use in actions like `await page.goto('/')`. */+ // baseURL: 'http://localhost:3000',- /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */- trace: "on-first-retry",- },+ /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */+ trace: "on-first-retry",+ },- /* Folder for test artifacts such as screenshots, videos, traces, etc. */- // outputDir: 'test-results/',+ /* Folder for test artifacts such as screenshots, videos, traces, etc. */+ // outputDir: 'test-results/',- /* Run your local dev server before starting the tests */- // webServer: {- // command: 'npm run start',- // port: 3000,- // },+ /* Run your local dev server before starting the tests */+ // webServer: {+ // command: 'npm run start',+ // port: 3000,+ // },};export default config;diff --git a/shared/logo/freemocap-skelly-logo-black-border-transparent-bkgd.png b/freemocap-ui/public/freemocap-logo.pngsimilarity index 100%rename from shared/logo/freemocap-skelly-logo-black-border-transparent-bkgd.pngrename to freemocap-ui/public/freemocap-logo.pngdiff --git a/freemocap-ui/src/App.css b/freemocap-ui/src/App.cssindex 3438a37e..1042d137 100644--- a/freemocap-ui/src/App.css+++ b/freemocap-ui/src/App.css@@ -1,50 +1,52 @@#root {- width: 100%;- height: 100vh;- overflow: hidden;+ width: 100%;+ height: 100vh;+ overflow: hidden;}+.logo-box {- position: relative;- height: 9em;+ position: relative;+ height: 9em;}.logo {- position: absolute;- left: calc(50% - 4.5em);- height: 6em;- padding: 1.5em;- will-change: filter;- transition: filter 300ms;+ position: absolute;+ left: calc(50% - 4.5em);+ height: 6em;+ padding: 1.5em;+ will-change: filter;+ transition: filter 300ms;}+.logo:hover {- filter: drop-shadow(0 0 2em #646cffaa);+ filter: drop-shadow(0 0 2em #646cffaa);}@keyframes logo-spin {- from {- transform: rotate(0deg);- }- to {- transform: rotate(360deg);- }+ from {+ transform: rotate(0deg);+ }+ to {+ transform: rotate(360deg);+ }}@media (prefers-reduced-motion: no-preference) {- .logo.electron {- animation: logo-spin infinite 20s linear;- }+ .logo.electron {+ animation: logo-spin infinite 20s linear;+ }}.card {- padding: 2em;+ padding: 2em;}.read-the-docs {- color: #888;+ color: #888;}.flex-center {- display: flex;- align-items: center;- justify-content: center;+ display: flex;+ align-items: center;+ justify-content: center;}diff --git a/freemocap-ui/src/App.tsx b/freemocap-ui/src/App.tsxindex 31e70ed4..ba07547f 100644--- a/freemocap-ui/src/App.tsx+++ b/freemocap-ui/src/App.tsx@@ -1,22 +1,18 @@import React from 'react';-import { PaperbaseContent } from "@/layout/paperbase_theme/PaperbaseContent";-import { Provider } from "react-redux";-import { AppStateStore } from "@/store/AppStateStore";-import { WebSocketContextProvider } from "@/context/websocket-context/WebSocketContext";-import { urlService } from '@/services/urlService';-import {PythonServerContextProvider} from "@/context/python-server-context/PythonServerContext";+import {Provider} from 'react-redux';+import {store} from '@/store';+import {ServerContextProvider} from "@/services/server/ServerContextProvider";+import {AppContent} from "@/layout/AppContent";+function App() {return (- <Provider store={AppStateStore}>- <PythonServerContextProvider>- <WebSocketContextProvider>- <PaperbaseContent/>- </WebSocketContextProvider>- </PythonServerContextProvider>+ <Provider store={store}>+ <ServerContextProvider>+ <AppContent/>+ </ServerContextProvider></Provider>);}export default App;-diff --git a/freemocap-ui/src/components/LogTerminal.tsx b/freemocap-ui/src/components/LogTerminal.tsxindex 33baf462..a59d0524 100644--- a/freemocap-ui/src/components/LogTerminal.tsx+++ b/freemocap-ui/src/components/LogTerminal.tsx@@ -1,37 +1,65 @@-import {alpha, Box, Chip, Collapse, ToggleButton, ToggleButtonGroup, useTheme} from "@mui/material";+// LogTerminal.tsx+import {+ alpha,+ Box,+ Chip,+ Collapse,+ IconButton,+ TextField,+ ToggleButton,+ ToggleButtonGroup,+ Tooltip,+ useTheme,+} from "@mui/material";import {useEffect, useRef, useState} from "react";-import {LogRecord} from "@/store/slices/logRecordsSlice";-import {useAppSelector} from "@/store/AppStateStore";-+import {useAppDispatch, useAppSelector} from "@/store";+import {+ selectFilteredLogs,+ selectHasErrors,+ selectLogCountsByLevel,+ selectLogsPaused+} from "@/store/slices/log-records/logs-selectors";+import {logsCleared, logsFiltered, logsPaused} from "@/store/slices/log-records/log-records-slice";+import {LogRecord} from "@/store/slices/log-records/logs-types";+import {+ Delete as DeleteIcon,+ Pause as PauseIcon,+ PlayArrow as PlayArrowIcon,+ Search as SearchIcon,+ Warning as WarningIcon+} from "@mui/icons-material";const LOG_COLORS = {- "LOOP": "#999",- "TRACE": "#ccc",- "DEBUG": "#88ccFF",- "INFO": "#00E5FF",- "SUCCESS": "#FF66FF",- "API": "#66FF66",- "WARNING": "#FFFF66",- "ERROR": "#FF6666",- "CRITICAL": "#FF0000"+ TRACE: "#ccc",+ DEBUG: "#88ccFF",+ INFO: "#00E5FF",+ SUCCESS: "#FF66FF",+ API: "#66FF66",+ WARNING: "#FFFF66",+ ERROR: "#FF6666",+ CRITICAL: "#FF0000",} as const;-const LogEntryComponent = ({log}: { log: LogRecord }) => {+const LogEntryComponent = ({ log }: { log: LogRecord }) => {const [expanded, setExpanded] = useState(false);- const color = LOG_COLORS[log.levelname.toUpperCase() as keyof typeof LOG_COLORS];+ const color =+ LOG_COLORS[log.levelname.toUpperCase() as keyof typeof LOG_COLORS] || "#ccc";const theme = useTheme();- const renderWithFormatting = (text: string) => {- return text.split('\n').map((line, i) => (- <span key={i}>- {line.split('\t').map((segment, j) => (- <span key={j}>- {segment}- {j < line.split('\t').length - 1 && <span style={{ marginRight: '2em' }} />}- </span>- ))}- {i < text.split('\n').length - 1 && <br />}- </span>+ const renderWithFormatting = (text: string | null | undefined): React.ReactNode => {+ if (!text) return null;++ return text.split("\n").map((line, i) => (+ <div+ key={i}+ style={{+ whiteSpace: "pre-wrap",+ fontFamily: "monospace",+ lineHeight: "1.2",+ }}+ >+ {line}+ </div>));};@@ -43,38 +71,51 @@ const LogEntryComponent = ({log}: { log: LogRecord }) => {pl: 1,backgroundColor: expanded? alpha(color, 0.1)- : theme.palette.mode === 'dark'- ? 'rgba(0,0,0,0.2)'- : 'rgba(0,0,0,0.05)',- cursor: 'pointer',- transition: 'background-color 0.1s',- '&:hover': {- backgroundColor: alpha(color, theme.palette.mode === 'dark' ? 0.05 : 0.1)- }+ : theme.palette.mode === "dark"+ ? "rgba(0,0,0,0.2)"+ : "rgba(0,0,0,0.05)",+ cursor: "pointer",+ transition: "background-color 0.1s",+ "&:hover": {+ backgroundColor: alpha(+ color,+ theme.palette.mode === "dark" ? 0.05 : 0.1+ ),+ },}}onClick={() => setExpanded(!expanded)}>- <Box sx={{display: 'flex', gap: 1, alignItems: 'center', py: 0.5}}>- <span style={{- color: theme.palette.mode === 'dark' ? '#888' : '#555',- fontSize: '0.9em'- }}>+ <Box sx={{ display: "flex", gap: 1, alignItems: "center", py: 0.5 }}>+ <span+ style={{+ color: theme.palette.mode === "dark" ? "#888" : "#555",+ fontSize: "0.9em",+ minWidth: "140px",+ }}+ >{log.asctime}</span>- <Chip size="small" label={log.levelname} sx={{- backgroundColor: color,- color: '#000',- height: 16,- fontSize: '0.8em',- '.MuiChip-label': {- px: 1,- }- }}/>- <span style={{- color: theme.palette.mode === 'dark' ? '#fff' : '#000',- flexGrow: 1,- fontSize: '0.9em'- }}>+ <Chip+ size="small"+ label={log.levelname}+ sx={{+ backgroundColor: color,+ color: "#000",+ height: 16,+ fontSize: "0.8em",+ minWidth: "60px",+ ".MuiChip-label": {+ px: 1,+ },+ }}+ />+ <span+ style={{+ color: theme.palette.mode === "dark" ? "#fff" : "#000",+ flexGrow: 1,+ fontSize: "0.9em",+ }}+ >{renderWithFormatting(log.message)}</span></Box>@@ -84,21 +125,31 @@ const LogEntryComponent = ({log}: { log: LogRecord }) => {sx={{pl: 2,py: 1,- fontSize: '0.8em',- color: theme.palette.mode === 'dark' ? '#888' : '#555',- borderTop: '1px solid',- borderColor: theme.palette.mode === 'dark'- ? 'rgba(255,255,255,0.1)'- : 'rgba(0,0,0,0.1)'+ fontSize: "0.8em",+ color: theme.palette.mode === "dark" ? "#888" : "#555",+ borderTop: "1px solid",+ fontFamily: 'monospace',+ borderColor:+ theme.palette.mode === "dark"+ ? "rgba(255,255,255,0.1)"+ : "rgba(0,0,0,0.1)",}}>- <div>Location: {log.module}:{log.funcName}:Line#{log.lineno}</div>+ <div>+ Location: {log.module}:{log.funcName}:Line#{log.lineno}+ </div><div>File: {log.filename}</div><div>Time delta: {log.delta_t}</div><div>Path: {log.pathname}</div>- <div>Raw message: {renderWithFormatting(log.formatted_message)}</div>- <div>Thread: {log.threadName} (ID: {log.thread})</div>- <div>Process: {log.processName} (ID: {log.process})</div>+ {log.formatted_message && (+ <div>Raw message: {renderWithFormatting(log.formatted_message)}</div>+ )}+ <div>+ Thread: {log.threadName} (ID: {log.thread})+ </div>+ <div>+ Process: {log.processName} (ID: {log.process})+ </div>{(log.exc_info || log.exc_text) && (<div>@@ -111,13 +162,16 @@ const LogEntryComponent = ({log}: { log: LogRecord }) => {{log.stack_info && (<div><div>Stack Trace:</div>- <pre style={{- whiteSpace: 'pre-wrap',- background: theme.palette.mode === 'dark' ? '#111' : '#f5f5f5',- padding: 8,- borderRadius: 4,- margin: '8px 0'- }}>+ <pre+ style={{+ whiteSpace: "pre-wrap",+ background:+ theme.palette.mode === "dark" ? "#111" : "#f5f5f5",+ padding: 8,+ borderRadius: 4,+ margin: "8px 0",+ }}+ >{renderWithFormatting(log.stack_info)}</pre></div>@@ -130,118 +184,255 @@ const LogEntryComponent = ({log}: { log: LogRecord }) => {export const LogTerminal = () => {const theme = useTheme();- const logs = useAppSelector(state => state.logRecords.entries);+ const dispatch = useAppDispatch();+ const logs = useAppSelector(selectFilteredLogs);+ const isPaused = useAppSelector(selectLogsPaused);+ const hasErrors = useAppSelector(selectHasErrors);+ const logCounts = useAppSelector(selectLogCountsByLevel);+const [selectedLevels, setSelectedLevels] = useState<string[]>([]);+ const [searchText, setSearchText] = useState<string>("");+ const [showSearch, setShowSearch] = useState(false);const logEndRef = useRef<HTMLDivElement>(null);+ const shouldAutoScroll = useRef(true);- const filteredLogs = logs.filter(log =>- selectedLevels.length === 0 || selectedLevels.includes(log.levelname.toLowerCase())- );+ // Update filter when levels or search text changes+ useEffect(() => {+ dispatch(logsFiltered({+ levels: selectedLevels,+ searchText: searchText+ }));+ }, [selectedLevels, searchText, dispatch]);+ // Auto-scroll to bottom when new logs arrive (if not paused)useEffect(() => {- logEndRef.current?.scrollIntoView({behavior: 'instant'});- }, [filteredLogs]);+ if (!isPaused && shouldAutoScroll.current) {+ logEndRef.current?.scrollIntoView({ behavior: "smooth" });+ }+ }, [logs, isPaused]);++ const handleLevelToggle = (_: React.MouseEvent<HTMLElement>, newLevels: string[]): void => {+ setSelectedLevels(newLevels);+ };++ const handlePauseToggle = (): void => {+ dispatch(logsPaused(!isPaused));+ };++ const handleClear = (): void => {+ dispatch(logsCleared());+ };++ const handleScroll = (e: React.UIEvent<HTMLDivElement>): void => {+ const element = e.currentTarget;+ const isAtBottom = element.scrollHeight - element.scrollTop <= element.clientHeight + 50;+ shouldAutoScroll.current = isAtBottom;+ };return (- <Box sx={{- height: '100%',- display: 'flex',- flexDirection: 'column',- backgroundColor: theme.palette.mode === 'dark'- ? '#1a1a1a'- : theme.palette.grey[100]- }}>- <Box sx={{- p: 0.5,- borderBottom: '1px solid',- borderColor: theme.palette.divider,- display: 'flex',- gap: 1,- alignItems: 'center'- }}>- <span style={{- color: theme.palette.text.primary,- fontSize: '0.9em'- }}>+ <Box+ sx={{+ height: "100%",+ display: "flex",+ flexDirection: "column",+ backgroundColor:+ theme.palette.mode === "dark" ? "#1a1a1a" : theme.palette.grey[100],+ }}+ >+ <Box+ sx={{+ p: 0.5,+ borderBottom: "1px solid",+ borderColor: theme.palette.divider,+ display: "flex",+ gap: 1,+ alignItems: "center",+ flexWrap: "wrap",+ }}+ >+ <span+ style={{+ color: theme.palette.text.primary,+ fontSize: "0.9em",+ fontWeight: "bold",+ }}+ >Server Logs</span>++ {hasErrors && (+ <Tooltip title="Errors detected">+ <WarningIcon+ sx={{+ color: LOG_COLORS.ERROR,+ fontSize: "1.2em",+ animation: "pulse 2s infinite",+ "@keyframes pulse": {+ "0%, 100%": { opacity: 1 },+ "50%": { opacity: 0.5 },+ },+ }}+ />+ </Tooltip>+ )}+<ToggleButtonGroupsize="small"value={selectedLevels}- onChange={(_, val) => setSelectedLevels(val)}+ onChange={handleLevelToggle}sx={{- '.MuiToggleButtonGroup-grouped': {+ ".MuiToggleButtonGroup-grouped": {border: `1px solid ${theme.palette.divider} !important`,- mx: '1px',- '&:not(:first-of-type)': {- borderRadius: '2px',+ mx: "1px",+ "&:not(:first-of-type)": {+ borderRadius: "2px",},- '&:first-of-type': {- borderRadius: '2px',+ "&:first-of-type": {+ borderRadius: "2px",},- }+ },}}>- {Object.entries(LOG_COLORS).map(([level, color]) => (- <ToggleButton- key={level}- value={level.toLowerCase()}- sx={{- py: 0.25,- px: 1,- minWidth: 0,- fontSize: '0.75em',- color: alpha(color, 0.7),- '&.Mui-selected': {- backgroundColor: alpha(color, 0.15),- color: color,- '&:hover': {- backgroundColor: alpha(color, 0.2),- }- },- '&:hover': {- backgroundColor: alpha(color, 0.1),- }- }}- >- {level}- </ToggleButton>- ))}+ {Object.entries(LOG_COLORS).map(([level, color]) => {+ const count = logCounts[level] || 0;+ return (+ <ToggleButton+ key={level}+ value={level.toLowerCase()}+ sx={{+ py: 0.25,+ px: 1,+ minWidth: 0,+ fontSize: "0.75em",+ position: "relative",+ color: alpha(color, 0.7),+ "&.Mui-selected": {+ backgroundColor: alpha(color, 0.15),+ color: color,+ "&:hover": {+ backgroundColor: alpha(color, 0.2),+ },+ },+ "&:hover": {+ backgroundColor: alpha(color, 0.1),+ },+ }}+ >+ {level}+ {count > 0 && (+ <span+ style={{+ marginLeft: "4px",+ fontSize: "0.8em",+ opacity: 0.7,+ }}+ >+ ({count})+ </span>+ )}+ </ToggleButton>+ );+ })}</ToggleButtonGroup>++ <Box sx={{ ml: "auto", display: "flex", gap: 0.5 }}>+ <IconButton+ size="small"+ onClick={() => setShowSearch(!showSearch)}+ sx={{ color: theme.palette.text.secondary }}+ >+ <SearchIcon fontSize="small" />+ </IconButton>++ <IconButton+ size="small"+ onClick={handlePauseToggle}+ sx={{+ color: isPaused ? theme.palette.warning.main : theme.palette.text.secondary+ }}+ >+ {isPaused ? <PlayArrowIcon fontSize="small" /> : <PauseIcon fontSize="small" />}+ </IconButton>++ <IconButton+ size="small"+ onClick={handleClear}+ sx={{ color: theme.palette.text.secondary }}+ >+ <DeleteIcon fontSize="small" />+ </IconButton>+ </Box></Box>- <Box sx={{- flex: 1,- overflowY: 'auto',- p: 1,- '&::-webkit-scrollbar': {- width: '8px',- backgroundColor: 'transparent',- },- '&::-webkit-scrollbar-thumb': {- backgroundColor: theme.palette.mode === 'dark'- ? 'rgba(255, 255, 255, 0.2)'- : 'rgba(0, 0, 0, 0.2)',- borderRadius: '4px',- '&:hover': {- backgroundColor: theme.palette.mode === 'dark'- ? 'rgba(255, 255, 255, 0.3)'- : 'rgba(0, 0, 0, 0.3)',+ {showSearch && (+ <Box sx={{ p: 1, borderBottom: "1px solid", borderColor: theme.palette.divider }}>+ <TextField+ size="small"+ fullWidth+ placeholder="Search logs..."+ value={searchText}+ onChange={(e) => setSearchText(e.target.value)}+ InputProps={{+ startAdornment: <SearchIcon sx={{ mr: 1, color: "text.secondary" }} />,+ }}+ />+ </Box>+ )}++ <Box+ sx={{+ flex: 1,+ overflowY: "auto",+ p: 1,+ "&::-webkit-scrollbar": {+ width: "8px",+ backgroundColor: "transparent",},- },- '&::-webkit-scrollbar-track': {- backgroundColor: 'transparent',- },- // For Firefox- scrollbarWidth: 'thin',- scrollbarColor: theme.palette.mode === 'dark'- ? 'rgba(255, 255, 255, 0.2) transparent'- : 'rgba(0, 0, 0, 0.2) transparent',- }}>- {filteredLogs.map((log, i) => (- <LogEntryComponent key={i} log={log}/>- ))}- <div ref={logEndRef}/>+ "&::-webkit-scrollbar-thumb": {+ backgroundColor:+ theme.palette.mode === "dark"+ ? "rgba(255, 255, 255, 0.2)"+ : "rgba(0, 0, 0, 0.2)",+ borderRadius: "4px",+ "&:hover": {+ backgroundColor:+ theme.palette.mode === "dark"+ ? "rgba(255, 255, 255, 0.3)"+ : "rgba(0, 0, 0, 0.3)",+ },+ },+ "&::-webkit-scrollbar-track": {+ backgroundColor: "transparent",+ },+ // For Firefox+ scrollbarWidth: "thin",+ scrollbarColor:+ theme.palette.mode === "dark"+ ? "rgba(255, 255, 255, 0.2) transparent"+ : "rgba(0, 0, 0, 0.2) transparent",+ }}+ onScroll={handleScroll}+ >+ {logs.length === 0 ? (+ <Box+ sx={{+ display: "flex",+ justifyContent: "center",+ alignItems: "center",+ height: "100%",+ color: theme.palette.text.disabled,+ }}+ >+ {isPaused ? "Logging paused" : "No logs to display"}+ </Box>+ ) : (+ <>+ {logs.map((log, i) => (+ <LogEntryComponent key={`${log.created}-${log.thread}-${i}`} log={log} />+ ))}+ <div ref={logEndRef} />+ </>+ )}</Box></Box>);diff --git a/freemocap-ui/src/components/PauseUnpauseButton.tsx b/freemocap-ui/src/components/PauseUnpauseButton.tsxindex c6fb2148..f3e80222 100644--- a/freemocap-ui/src/components/PauseUnpauseButton.tsx+++ b/freemocap-ui/src/components/PauseUnpauseButton.tsx@@ -1,10 +1,10 @@-// skellycam-ui/src/components/PauseUnpauseButton.tsx+// freemocap-ui/src/components/PauseUnpauseButton.tsximport React, {useState} from 'react';-import {Button, CircularProgress, keyframes} from '@mui/material';+import {Button, CircularProgress, keyframes, Tooltip} from '@mui/material';import {styled} from '@mui/system';import PlayArrowIcon from '@mui/icons-material/PlayArrow';import PauseIcon from '@mui/icons-material/Pause';-import {pauseUnpauseThunk} from "@/store/thunks/pause-unpause-thunk";+import {pauseUnpauseThunk} from "@/store/slices/cameras/old-camera-thunks/pause-unpause-thunk";interface PauseUnpauseButtonProps {disabled?: boolean;@@ -23,15 +23,16 @@ const pulseAnimation = keyframes``;const PulsingButton = styled(Button)<{ pulsing?: boolean }>(({pulsing}) => ({- backgroundColor: '#1976d2', // MUI primary blue- borderRadius: '8px',- padding: '10px 16px',+ // backgroundColor: '#1976d2', // MUI primary blue+ borderRadius: '80px',+ padding: '16px','&:hover': {backgroundColor: '#1565c0', // Darker blue on hover},...(pulsing && {animation: `${pulseAnimation} 1.5s infinite ease-in-out`,}),+}));export const PauseUnpauseButton: React.FC<PauseUnpauseButtonProps> = ({@@ -56,15 +57,16 @@ export const PauseUnpauseButton: React.FC<PauseUnpauseButtonProps> = ({};return (+ <Tooltip title={isPaused ? "Unpause all cameras" : "Pause all cameras"} ><PulsingButton- onClick={ handleClick}+ onClick={handleClick}variant="contained"pulsing={isPaused ? true : undefined}fullWidthdisabled={disabled || isLoading}- startIcon={isLoading ? undefined : isPaused ? <PlayArrowIcon/> : <PauseIcon/>}+ startIcon={isLoading ? <CircularProgress/> : isPaused ? <PlayArrowIcon/> : <PauseIcon/>}>- {isLoading ? <CircularProgress size={24} color="inherit"/> : (isPaused ? 'Resume' : 'Pause')}</PulsingButton>+ </Tooltip>);};diff --git a/freemocap-ui/src/components/ServerConnectionStatus.tsx b/freemocap-ui/src/components/ServerConnectionStatus.tsxnew file mode 100644index 00000000..944c1f61--- /dev/null+++ b/freemocap-ui/src/components/ServerConnectionStatus.tsx@@ -0,0 +1,104 @@+// components/ServerConnectionStatus.tsx+import React from 'react';+import {Box, IconButton, Typography} from "@mui/material";+import CheckIcon from '@mui/icons-material/Check';+import CloseIcon from '@mui/icons-material/Close';+import WifiIcon from '@mui/icons-material/Wifi';+import WifiOffIcon from '@mui/icons-material/WifiOff';++import {useServer} from "@/hooks/useServer";++export const ServerConnectionStatus: React.FC = () => {+ const { isConnected, connect, disconnect, connectedCameraIds } = useServer();++ const handleClick = (): void => {+ if (isConnected) {+ disconnect();+ } else {+ connect();+ }+ };++ const getStatusColor = (): { bg: string; border: string; text: string } => {+ if (isConnected) {+ return {+ bg: 'rgba(0, 255, 255, 0.05)',+ border: 'rgba(0, 255, 255, 0.3)',+ text: '#00ffff'+ };+ }+ return {+ bg: 'rgba(255, 0, 0, 0.1)',+ border: 'rgba(255, 0, 0, 0.3)',+ text: '#f44336'+ };+ };++ const colors = getStatusColor();++ return (+ <Box+ onClick={handleClick}+ sx={{+ display: 'flex',+ alignItems: 'center',+ gap: 1,+ padding: '8px 12px',+ cursor: 'pointer',+ border: `1px solid ${colors.border}`,+ borderRadius: '8px',+ backgroundColor: colors.bg,+ transition: 'all 0.2s ease',+ ':hover': {+ opacity: 0.8,+ transform: 'translateY(-1px)',+ boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',+ },+ }}+ >+ <IconButton+ size="small"+ sx={{+ p: 0.5,+ color: colors.text,+ backgroundColor: 'rgba(255, 255, 255, 0.1)',+ ':hover': { backgroundColor: 'rgba(255, 255, 255, 0.2)' }+ }}+ >+ {isConnected ? <WifiIcon /> : <WifiOffIcon />}+ </IconButton>++ <Box>+ <Typography+ variant="body2"+ sx={{+ fontWeight: 500,+ color: colors.text,+ display: 'flex',+ alignItems: 'center',+ gap: 0.5+ }}+ >+ WebSocket: {isConnected ? 'Connected' : 'Disconnected'}+ {isConnected ? (+ <CheckIcon sx={{ fontSize: 16 }} />+ ) : (+ <CloseIcon sx={{ fontSize: 16 }} />+ )}+ </Typography>++ {isConnected && connectedCameraIds.length > 0 && (+ <Typography variant="caption" sx={{ color: 'text.secondary' }}>+ {connectedCameraIds.length} camera{connectedCameraIds.length !== 1 ? 's' : ''} active+ </Typography>+ )}++ {!isConnected && (+ <Typography variant="caption" sx={{ color: 'text.secondary' }}>+ Click to connect+ </Typography>+ )}+ </Box>+ </Box>+ );+};diff --git a/freemocap-ui/src/components/available-cameras-panel/ApplyCameraConfigsButton.tsx b/freemocap-ui/src/components/available-cameras-panel/ApplyCameraConfigsButton.tsxdeleted file mode 100644index fa3270d5..00000000--- a/freemocap-ui/src/components/available-cameras-panel/ApplyCameraConfigsButton.tsx+++ /dev/null@@ -1,20 +0,0 @@-import React from 'react';-import { IconButton, Tooltip } from '@mui/material';-import SystemUpdateAltIcon from '@mui/icons-material/SystemUpdateAlt';-import { useAppDispatch } from '@/store/AppStateStore';-import { updateCameraConfigsThunk } from "@/store/thunks/update-camera-configs-thunk";--export const ApplyCameraConfigsButton: React.FC = () => {- const dispatch = useAppDispatch();-- return (- <Tooltip title="Apply camera configurations" arrow>- <IconButton- color="inherit"- onClick={() => dispatch(updateCameraConfigsThunk())}- >- <SystemUpdateAltIcon />- </IconButton>- </Tooltip>- );-};diff --git a/freemocap-ui/src/components/available-cameras-panel/AvailableCamerasPanel.tsx b/freemocap-ui/src/components/available-cameras-panel/AvailableCamerasPanel.tsxdeleted file mode 100644index 8e472fc3..00000000--- a/freemocap-ui/src/components/available-cameras-panel/AvailableCamerasPanel.tsx+++ /dev/null@@ -1,202 +0,0 @@-// skellycam-ui/src/components/available-cameras-panel/AvailableCamerasView.tsx-import {Accordion, AccordionDetails, Box, List, Paper, Stack, Typography, useTheme,} from "@mui/material";-import * as React from "react";-import {useEffect, useState} from "react";-import AccordionSummary from "@mui/material/AccordionSummary";-import ExpandMoreIcon from "@mui/icons-material/ExpandMore";-import VideocamIcon from "@mui/icons-material/Videocam";-import {CameraConfigPanel} from "@/components/available-cameras-panel/CameraConfigPanel";-import {CameraListItem} from "@/components/available-cameras-panel/CameraListItem";-import {RefreshDetectedCamerasButton} from "@/components/available-cameras-panel/RefreshDetectedCameras";-import {useAppDispatch, useAppSelector} from "@/store/AppStateStore";-import {ConnectToCamerasButton} from "@/components/available-cameras-panel/ConnectToCamerasButton";-import {selectAllCameras, toggleCameraSelection, updateCameraConfig,} from "@/store/slices/cameras-slices/camerasSlice";-import {connectToCameras} from "@/store/thunks/connect-to-cameras-thunk";-import {CloseCamerasButton} from "@/components/available-cameras-panel/CloseCamerasButton";-import {CameraConfig, CameraDevice} from "@/store/slices/cameras-slices/camera-types";-import {ApplyCameraConfigsButton} from "@/components/available-cameras-panel/ApplyCameraConfigsButton";-import {PauseUnpauseButton} from "../PauseUnpauseButton";-// import { detectCameraDevices } from "@/store/thunks/detect-cameras-client-thunks";-import { detectCameraDevices } from "@/store/thunks/detect-cameras-thunks/detect-cameras-server-thunk";--export const AvailableCamerasPanel = () => {- const theme = useTheme();- const dispatch = useAppDispatch();-- // Get data from the unified slice- const camerasRecord = useAppSelector(selectAllCameras);- const isLoading = useAppSelector((state) => state.cameras.isLoading);- const [expandedConfigs, setExpandedConfigs] = useState<Set<string>>(new Set());- const [camerasArray, setCamerasArray] = useState<CameraDevice[]>([]);-- useEffect(() => {- // Whenever the camerasRecord changes, update the camerasArray- if (!camerasRecord) {- setCamerasArray([]);- return;- }-- // Convert cameras record to array for easier rendering- const newCamerasArray = Object.values(camerasRecord).sort((a, b) =>- a.config.camera_index - b.config.camera_index- );-- setCamerasArray(newCamerasArray);- }, [camerasRecord]);----- // Handle expanding/collapsing camera config panels- const toggleConfig = (cameraId: string) => {- setExpandedConfigs((prev) => {- const newSet = new Set(prev);- if (newSet.has(cameraId)) {- newSet.delete(cameraId);- } else {- newSet.add(cameraId);- }- return newSet;- });- };-- // Initial camera detection- useEffect(() => {- if (camerasArray.length > 0) {- // If cameras are already detected, we don't need to detect again- return;- }- dispatch(detectCameraDevices());- }, [dispatch]);-- // Handle connection to selected cameras- const handleConnectCameras = () => {- dispatch(connectToCameras());- };-- const handleConfigChange = (cameraId: string, newConfig: CameraConfig) => {- // Update the Redux store- dispatch(- updateCameraConfig({- cameraId,- config: newConfig,- })- );- };-- return (- <Accordion- defaultExpanded- sx={{- borderRadius: 2,- "&:before": {display: "none"},- boxShadow: theme.shadows[3],- justifyContent: "left",- }}- >- <Box- sx={{- display: "flex",- alignItems: "center",- backgroundColor: theme.palette.primary.main,- borderTopLeftRadius: 8,- borderBottomLeftRadius: 8,- }}- >- <AccordionSummary- expandIcon={- <ExpandMoreIcon- sx={{color: theme.palette.primary.contrastText}}- />- }- sx={{- flex: 1,- color: theme.palette.primary.contrastText,- "&:hover": {- backgroundColor: theme.palette.primary.light,- },- }}- >- <Stack direction="row" alignItems="center" spacing={1}>- <VideocamIcon/>- <Typography variant="subtitle1" fontWeight="medium">- Cameras- </Typography>- </Stack>- </AccordionSummary>- <Box sx={{pr: 2}}>- <PauseUnpauseButton/>- </Box>- <Box sx={{pr: 2}}>- <ConnectToCamerasButton onClick={handleConnectCameras}/>- </Box>- <Box sx={{pr: 2}}>- < ApplyCameraConfigsButton/>- </Box>- <Box sx={{pr: 2}}>- <RefreshDetectedCamerasButton isLoading={isLoading}/>- </Box>- <Box sx={{pr: 2}}>- <CloseCamerasButton/>- </Box>- </Box>-- <AccordionDetails sx={{bgcolor: "background.default"}}>- <Paper- elevation={0}- sx={{- borderRadius: 2,- overflow: "hidden",- }}- >- <List dense disablePadding>- {camerasArray.map((camera, index) => (- <React.Fragment key={camera.cameraId}>- <CameraListItem- camera={camera}- isLast={index === camerasArray.length - 1}- isConfigExpanded={expandedConfigs.has(camera.cameraId)}- onToggleSelect={() =>- dispatch(toggleCameraSelection(camera.cameraId))- }- onToggleConfig={() => toggleConfig(camera.cameraId)}- />- {camera.selected && (- <CameraConfigPanel- config={camera.config}- onConfigChange={(newConfig) => {- handleConfigChange(camera.cameraId, newConfig);- }}- isExpanded={expandedConfigs.has(camera.cameraId)}- />- )}- </React.Fragment>- ))}- </List>-- {camerasArray.length === 0 && (- <Box- sx={{- p: 3,- textAlign: "center",- bgcolor: "background.paper",- borderRadius: 1,- }}- >- <Typography variant="body1" color="text.secondary">- No cameras detected- </Typography>- <Typography- variant="caption"- color="text.disabled"- sx={{mt: 1, display: "block"}}- >- Click refresh to scan for available cameras- </Typography>- </Box>- )}- </Paper>- </AccordionDetails>- </Accordion>- );-};diff --git a/freemocap-ui/src/components/available-cameras-panel/CameraConfigPanel.tsx b/freemocap-ui/src/components/available-cameras-panel/CameraConfigPanel.tsxdeleted file mode 100644index 79156107..00000000--- a/freemocap-ui/src/components/available-cameras-panel/CameraConfigPanel.tsx+++ /dev/null@@ -1,96 +0,0 @@-import {Box, Collapse, IconButton, Tooltip, useTheme} from "@mui/material";-import Grid from "@mui/material/Grid2";-import MediationIcon from '@mui/icons-material/Mediation';-import * as React from "react";-import {CameraConfigResolution} from "./CameraConfigResolution";-import {CameraConfigExposure} from "./CameraConfigExposure";-import {CameraConfigRotation} from "./CameraConfigRotation";-import {CameraConfig} from "@/store/slices/cameras-slices/camera-types";-import {copyConfigToAllCameras} from "@/store/slices/cameras-slices/camerasSlice";-import {useAppDispatch} from "@/store/AppStateStore";--interface CameraConfigPanelProps {- config: CameraConfig;- onConfigChange: (newConfig: CameraConfig) => void;- isExpanded: boolean;-}--export const CameraConfigPanel: React.FC<CameraConfigPanelProps> = ({- config,- onConfigChange,- isExpanded,- }) => {- const theme = useTheme();- const dispatch = useAppDispatch();-- const handleChange = <K extends keyof CameraConfig>(- key: K,- value: CameraConfig[K]- ) => {- onConfigChange({- ...config,- [key]: value,- });- };- const handleCopyToAllCameras = () => {- dispatch(copyConfigToAllCameras(config.camera_id));- };- return (- <Collapse in={isExpanded}>- <Box- sx={{- p: 1.5,- ml: 7,- mr: 2,- mb: 1,- borderRadius: 1,- border: `1px solid ${theme.palette.divider}`,- }}- >-- <Grid container spacing={2}>- {/* Top row with Resolution, Rotation, and Copy Settings */}- <Grid size={{xs: 12, sm: 5}}>- <CameraConfigResolution- resolution={config.resolution}- onChange={(width, height) =>- handleChange("resolution", {width, height})- }- />- </Grid>-- <Grid size={{xs: 12, sm: 5}}>- <CameraConfigRotation- rotation={config.rotation}- onChange={(value) => handleChange("rotation", value)}- />- </Grid>-- <Grid size={{xs: 12, sm: 2}} sx={{display: 'flex', alignItems: 'center', justifyContent: 'center'}}>- <Tooltip title="Copy settings to all cameras">- <IconButton- size="small"- onClick={handleCopyToAllCameras}- aria-label="Copy settings to all cameras"- >- <MediationIcon/>- </IconButton>- </Tooltip>- </Grid>-- {/* Bottom row with Exposure controls */}- <Grid size={12}>- <CameraConfigExposure- exposureMode={config.exposure_mode}- exposure={config.exposure}- onExposureModeChange={(mode) =>- handleChange("exposure_mode", mode)- }- onExposureValueChange={(value) => handleChange("exposure", value)}- />- </Grid>- </Grid>- </Box>- </Collapse>- );-};diff --git a/freemocap-ui/src/components/available-cameras-panel/CameraConfigResolution.tsx b/freemocap-ui/src/components/available-cameras-panel/CameraConfigResolution.tsxdeleted file mode 100644index 57889a0e..00000000--- a/freemocap-ui/src/components/available-cameras-panel/CameraConfigResolution.tsx+++ /dev/null@@ -1,34 +0,0 @@-import {FormControl, InputLabel, MenuItem, Select, useTheme} from "@mui/material";-import * as React from "react";-import {CameraConfig} from "@/store/slices/cameras-slices/camera-types";--interface CameraConfigResolutionProps {- resolution: CameraConfig['resolution'];- onChange: (width: number, height: number) => void;-}--export const CameraConfigResolution: React.FC<CameraConfigResolutionProps> = ({- resolution,- onChange-}) => {- const theme = useTheme();-- return (- <FormControl size="small" sx={{ flex: 1, color: theme.palette.text.primary }}>- <InputLabel sx={{ color: theme.palette.text.primary }}>Resolution</InputLabel>- <Select- value={`${resolution.width}x${resolution.height}`}- label="Resolution"- onChange={(e) => {- const [width, height] = e.target.value.split('x').map(Number);- onChange(width, height);- }}- sx={{ color: theme.palette.text.primary }}- >- <MenuItem value="640x480">640 x 480</MenuItem>- <MenuItem value="1280x720">1280 x 720</MenuItem>- <MenuItem value="1920x1080">1920 x 1080</MenuItem>- </Select>- </FormControl>-);-};diff --git a/freemocap-ui/src/components/available-cameras-panel/CameraListItem.tsx b/freemocap-ui/src/components/available-cameras-panel/CameraListItem.tsxdeleted file mode 100644index 48eb66df..00000000--- a/freemocap-ui/src/components/available-cameras-panel/CameraListItem.tsx+++ /dev/null@@ -1,104 +0,0 @@-// skellycam-ui/src/components/available-cameras-panel/CameraListItem.tsx-import {Box, Checkbox, Chip, IconButton, ListItem, ListItemIcon, ListItemText, Typography, useTheme} from "@mui/material";-import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';-import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';-import * as React from "react";-import {CameraDevice} from "@/store/slices/cameras-slices/camera-types";--interface CameraListItemProps {- camera: CameraDevice;- isLast: boolean;- isConfigExpanded: boolean;- onToggleSelect: () => void;- onToggleConfig: () => void;-}--export const CameraListItem: React.FC<CameraListItemProps> = ({- camera,- isLast,- isConfigExpanded,- onToggleSelect,- onToggleConfig- }) => {- const theme = useTheme();-- const getStatusChipProps = (status: string) => {- switch (status) {- case 'CONNECTED':- return { color: 'success' as const, label: 'Connected' };- case 'AVAILABLE':- return { color: 'primary' as const, label: 'Available' };- case 'UNAVAILABLE':- return { color: 'warning' as const, label: 'Unavailable' };- case 'IN_USE':- return { color: 'secondary' as const, label: 'In Use' };- case 'ERROR':- return { color: 'error' as const, label: 'Error' };- default:- return { color: 'default' as const, label: status || 'Unknown' };- }-};-- const statusChipProps = getStatusChipProps(camera.status);-- return (- <ListItem- sx={{- '&:hover': {- bgcolor: 'action.hover',- },- borderBottom: isLast ? 0 : 1,- borderColor: 'divider',- }}- >- <ListItemIcon>- <Checkbox- edge="start"- checked={camera.selected || false}- onChange={onToggleSelect}- color={theme.palette.primary.main as any}- disabled={camera.status === 'UNAVAILABLE' || camera.status === 'ERROR' }- />- </ListItemIcon>- <ListItemText- primary={- <Box sx={{display: 'flex', alignItems: 'center'}}>- <Typography- component="span"- variant="body2"- color={theme.palette.text.primary}- sx={{mr: 1, fontWeight: 600}}- >- Camera {camera.index}- </Typography>- <Typography- component="span"- variant="body2"- color={theme.palette.text.secondary}- sx={{mr: 1}}- >- {`${camera.label}, id: ${camera.cameraId}` || `Unknown Device ${camera.index}`}- </Typography>- <Chip- size="small"- label={statusChipProps.label}- color={statusChipProps.color}- sx={{ ml: 'auto', mr: 1 }}- />- </Box>- }- />- {camera.selected && camera.status !== 'UNAVAILABLE' && camera.status !== 'ERROR' && (- <IconButton- size="small"- onClick={onToggleConfig}- >- {isConfigExpanded- ? <KeyboardArrowUpIcon/>- : <KeyboardArrowDownIcon/>}- </IconButton>- )}- </ListItem>- );-};-diff --git a/freemocap-ui/src/components/available-cameras-panel/CloseCamerasButton.tsx b/freemocap-ui/src/components/available-cameras-panel/CloseCamerasButton.tsxdeleted file mode 100644index 6061118c..00000000--- a/freemocap-ui/src/components/available-cameras-panel/CloseCamerasButton.tsx+++ /dev/null@@ -1,25 +0,0 @@-import React from 'react';-import {IconButton, Tooltip} from '@mui/material';-import CloseIcon from '@mui/icons-material/Close';-import {useAppDispatch} from '@/store/AppStateStore';-import {closeCameras} from "@/store/thunks/close-cameras-thunks";---export const CloseCamerasButton: React.FC = () => {- const dispatch = useAppDispatch();-- const handleCloseCameras = () => {- dispatch(closeCameras());- };-- return (- <Tooltip title="Close all cameras" arrow placement="bottom">- <IconButton- color="inherit"- onClick={handleCloseCameras}- >- <CloseIcon/>- </IconButton>- </Tooltip>- );-};diff --git a/freemocap-ui/src/components/available-cameras-panel/ConnectToCamerasButton.tsx b/freemocap-ui/src/components/available-cameras-panel/ConnectToCamerasButton.tsxdeleted file mode 100644index ccc8b154..00000000--- a/freemocap-ui/src/components/available-cameras-panel/ConnectToCamerasButton.tsx+++ /dev/null@@ -1,69 +0,0 @@-// ConnectToCamerasButton.tsx-import React from 'react';-import {Button, Typography} from '@mui/material';-import extendedPaperbaseTheme from "@/layout/paperbase_theme/paperbase-theme";-import {useAppDispatch, useAppSelector} from "@/store/AppStateStore";-import {selectSelectedDevices} from "@/store/slices/cameras-slices/camerasSlice";-import {connectToCameras} from "@/store/thunks/connect-to-cameras-thunk";--interface ConnectToCamerasButtonProps {- onClick?: () => void;-}--export const ConnectToCamerasButton: React.FC<ConnectToCamerasButtonProps> = ({ onClick }) => {- const dispatch = useAppDispatch();- const isLoading = useAppSelector(state => state.cameras.isLoading);- const selectedCameras = useAppSelector(selectSelectedDevices);-- const handleConnectClick = async () => {- console.log("ConnectToCamerasButton handleConnectClick", selectedCameras, isLoading);- if (isLoading) {- console.log('Camera connection is already in progress');- return;- }-- try {- if (selectedCameras && selectedCameras.length > 0) {- // If we have an onClick prop, use that (for testing/custom handling)- if (onClick) {- onClick();- } else {- // Otherwise dispatch the thunk which will get the configs from state- await dispatch(connectToCameras()).unwrap();- console.log('Connected to selected cameras');- }- } else {- console.log('No cameras selected to connect to');- }- } catch (error) {- console.error('Error connecting to cameras:', error);- }- };-- const hasSelectedCameras = selectedCameras.length > 0;-- return (- <Button- variant="contained"- onClick={handleConnectClick}- disabled={!hasSelectedCameras || isLoading}- sx={{- ml: 1,- fontSize: 'small',- color: extendedPaperbaseTheme.palette.primary.contrastText,- backgroundColor: "#900078",- borderStyle: 'solid',- borderWidth: '1px',- borderColor: '#000b10',- '&:disabled': {- backgroundColor: "#9d729c",- color: "#333",- }- }}- >- <Typography variant={'h6'}>- {isLoading ? 'Connecting...' : 'Connect'}- </Typography>- </Button>- );-};diff --git a/freemocap-ui/src/components/available-cameras-panel/RefreshDetectedCameras.tsx b/freemocap-ui/src/components/available-cameras-panel/RefreshDetectedCameras.tsxdeleted file mode 100644index d108fab1..00000000--- a/freemocap-ui/src/components/available-cameras-panel/RefreshDetectedCameras.tsx+++ /dev/null@@ -1,33 +0,0 @@-// RefreshDetectedCameras.tsx-import React from 'react';-import { CircularProgress, IconButton, Tooltip } from '@mui/material';-import RefreshIcon from '@mui/icons-material/Refresh';-import { useAppDispatch } from '@/store/AppStateStore';-import { detectCameraDevices } from '@/store/thunks/detect-cameras-thunks/detect-cameras-server-thunk';-// import { detectCameraDevices } from '@/store/thunks/detect-cameras-client-thunks';--interface RefreshDetectedCamerasButtonProps {- isLoading: boolean;-}--export const RefreshDetectedCamerasButton: React.FC<RefreshDetectedCamerasButtonProps> = ({ isLoading }) => {- const dispatch = useAppDispatch();-- const handleRefresh = () => {- if (!isLoading) {- dispatch(detectCameraDevices());- }- };-- return (- <Tooltip title="Redetect available cameras">- <IconButton- color="inherit"- onClick={handleRefresh}- disabled={isLoading}- >- {isLoading ? <CircularProgress size={24} color="inherit" /> : <RefreshIcon />}- </IconButton>- </Tooltip>- );-};diff --git a/freemocap-ui/src/components/calibration-task-panel/CalibrationControlPanel.tsx b/freemocap-ui/src/components/calibration-task-panel/CalibrationControlPanel.tsxnew file mode 100644index 00000000..946c07dd--- /dev/null+++ b/freemocap-ui/src/components/calibration-task-panel/CalibrationControlPanel.tsx@@ -0,0 +1,476 @@+// components/CalibrationTaskTreeItem.tsx+import React, {useCallback, useEffect, useMemo, useState} from 'react';+import {+ Alert,+ Box,+ Button,+ Checkbox,+ Chip,+ FormControl,+ FormControlLabel,+ IconButton,+ InputAdornment,+ InputLabel,+ MenuItem,+ Select,+ Stack,+ TextField,+ Tooltip,+ Typography,+ useTheme,+} from '@mui/material';+import {TreeItem} from '@mui/x-tree-view/TreeItem';+import SquareFootIcon from '@mui/icons-material/SquareFoot';+import PlayArrowIcon from '@mui/icons-material/PlayArrow';+import StopIcon from '@mui/icons-material/Stop';+import FolderOpenIcon from '@mui/icons-material/FolderOpen';+import ClearIcon from '@mui/icons-material/Clear';+import CheckCircleIcon from '@mui/icons-material/CheckCircle';+import InfoIcon from '@mui/icons-material/Info';+import CloseIcon from '@mui/icons-material/Close';+import {useCalibration} from '@/hooks/useCalibration';+import {useElectronIPC} from '@/services';+import ExpandMoreIcon from "@mui/icons-material/ExpandMore";+import ChevronRightIcon from "@mui/icons-material/ChevronRight";+import {SimpleTreeView} from "@mui/x-tree-view";++type BoardPreset = '5x3' | '7x5' | 'custom';++interface BoardPresetConfig {+ xSquares: number;+ ySquares: number;+}++const BOARD_PRESETS: Record<Exclude<BoardPreset, 'custom'>, BoardPresetConfig> = {+ '5x3': { xSquares: 5, ySquares: 3 },+ '7x5': { xSquares: 7, ySquares: 5 },+};++export const CalibrationControlPanel: React.FC = () => {+ const theme = useTheme();+ const [localError, setLocalError] = useState<string | null>(null);+ const [expandedItems, setExpandedItems] = useState<string[]>([+ 'pipeline-main',+ 'calibration-intrinsic',+ 'calibration-extrinsic',+ 'mocap-task'+ ]);+ const { api } = useElectronIPC();++ const {+ config,+ error,+ isLoading,+ isRecording,+ recordingProgress,+ canStartRecording,+ canCalibrate,+ calibrationRecordingPath,+ directoryInfo,+ isUsingManualPath,+ updateCalibrationConfig,+ dispatchStopCalibrationRecording,+ dispatchStartCalibrationRecording,+ setManualRecordingPath,+ clearManualRecordingPath,+ validateDirectory,+ calibrateSelectedRecording,+ clearError,+ } = useCalibration();++ // Validate directory whenever path changes+ useEffect(() => {+ if (calibrationRecordingPath) {+ validateDirectory(calibrationRecordingPath);+ }+ }, [calibrationRecordingPath, validateDirectory]);++ // Determine current board preset based on config values+ const currentPreset = useMemo<BoardPreset>(() => {+ for (const [preset, presetConfig] of Object.entries(BOARD_PRESETS)) {+ if (+ presetConfig.xSquares === config.charucoBoardXSquares &&+ presetConfig.ySquares === config.charucoBoardYSquares+ ) {+ return preset as BoardPreset;+ }+ }+ return 'custom';+ }, [config.charucoBoardXSquares, config.charucoBoardYSquares]);++ const handleClearError = useCallback((): void => {+ clearError();+ setLocalError(null);+ }, [clearError]);++ const handlePresetChange = useCallback((preset: BoardPreset): void => {+ if (preset === 'custom') {+ // Don't change values when switching to custom+ return;+ }+ const presetConfig = BOARD_PRESETS[preset];+ updateCalibrationConfig({+ charucoBoardXSquares: presetConfig.xSquares,+ charucoBoardYSquares: presetConfig.ySquares,+ });+ }, [updateCalibrationConfig]);++ const handleXSquaresChange = useCallback((value: string): void => {+ const numValue = parseInt(value, 10);+ if (!isNaN(numValue) && numValue > 0) {+ updateCalibrationConfig({+ charucoBoardXSquares: numValue,+ });+ }+ }, [updateCalibrationConfig]);++ const handleYSquaresChange = useCallback((value: string): void => {+ const numValue = parseInt(value, 10);+ if (!isNaN(numValue) && numValue > 0) {+ updateCalibrationConfig({+ charucoBoardYSquares: numValue,+ });+ }+ }, [updateCalibrationConfig]);++ const handleSelectDirectory = async (): Promise<void> => {+ if ( !api) {+ console.warn('Electron API not available');+ return;+ }++ try {+ const result: string | null = await api.fileSystem.selectDirectory.mutate();+ if (result) {+ await setManualRecordingPath(result);+ }+ } catch (error) {+ console.error('Failed to select directory:', error);+ setLocalError('Failed to select directory');+ }+ };++ const handlePathInputChange = async (e: React.ChangeEvent<HTMLInputElement>): Promise<void> => {+ const newPath: string = e.target.value;++ // Handle tilde expansion for home directory+ if (newPath.includes('~') && api) {+ try {+ const home: string = await api.fileSystem.getHomeDirectory.query();+ const expanded: string = newPath.replace(/^~([\/\\])?/, home ? `${home}$1` : '');+ await setManualRecordingPath(expanded);+ } catch (error) {+ console.error('Failed to expand home directory:', error);+ await setManualRecordingPath(newPath);+ }+ } else {+ await setManualRecordingPath(newPath);+ }+ };++ const handleClearManualPath = useCallback((): void => {+ clearManualRecordingPath();+ }, [clearManualRecordingPath]);++ const displayError = error || localError || directoryInfo?.errorMessage;++ // Helper text for the path input+ const pathHelperText = useMemo(() => {+ if (isUsingManualPath) {+ return 'Using custom path';+ }+ return 'Using default recording directory';+ }, [isUsingManualPath]);+ const handleExpandedItemsChange = (+ event: React.SyntheticEvent,+ itemIds: string[]+ ): void => {+ setExpandedItems(itemIds);+ };+ return (+ <SimpleTreeView+ expandedItems={expandedItems}+ onExpandedItemsChange={handleExpandedItemsChange}+ slots={{+ collapseIcon: ExpandMoreIcon,+ expandIcon: ChevronRightIcon,+ }}+ sx={{ flexGrow: 1 }}+ >+ <TreeItem+ itemId="calibration-task"+ label={+ <Box sx={{ display: 'flex', alignItems: 'center', py: 1, pr: 1 }}>+ <SquareFootIcon sx={{ mr: 1, color: theme.palette.secondary.main }} />+ <Typography variant="subtitle1" sx={{ flexGrow: 1 }}>+ Capture Volume Calibration+ </Typography>+ </Box>+ }+ >+ <Box sx={{ p: 2, bgcolor: 'background.paper' }}>+ <Stack spacing={2}>+ {/* Error Display */}+ {displayError && (+ <Alert severity="error" onClose={handleClearError}>+ {displayError}+ </Alert>+ )}++ {/* Calibration Recording Path Input */}+ <Box>+ {/* Live Tracker Toggle */}+ <FormControlLabel+ control={+ <Checkbox+ checked={config.liveTrackCharuco}+ onChange={(e) => updateCalibrationConfig({ liveTrackCharuco: e.target.checked })}+ disabled={isLoading}+ sx={{ '&.Mui-checked': { color: theme.palette.text.primary } }}+ />+ }+ label="Live Track Charuco Board"+ />+ {/* Recording Controls */}+ <Stack direction="row" spacing={2} sx={{ mb: 2 }}>+ <Button+ variant="contained"+ color="primary"+ startIcon={<PlayArrowIcon />}+ onClick={dispatchStartCalibrationRecording}+ disabled={!canStartRecording || isLoading}+ fullWidth+ >+ Start Calibration Recording+ </Button>+ {isRecording && (+ <Button+ variant="contained"+ color="error"+ startIcon={<StopIcon />}+ onClick={dispatchStopCalibrationRecording}+ disabled={isLoading}+ fullWidth+ >+ Stop Recording+ </Button>+ )}+ </Stack>+ <TextField+ label="Calibration Recording Path"+ value={calibrationRecordingPath}+ onChange={handlePathInputChange}+ fullWidth+ size="small"+ helperText={pathHelperText}+ InputProps={{+ endAdornment: (+ <InputAdornment position="end">+ {isUsingManualPath && (+ <Tooltip title="Clear manual path (revert to default)">+ <IconButton+ onClick={handleClearManualPath}+ edge="end"+ size="small"+ >+ <ClearIcon fontSize="small" />+ </IconButton>+ </Tooltip>+ )}+ <Tooltip title="Select directory">+ <IconButton+ onClick={handleSelectDirectory}+ edge="end"+ >+ <FolderOpenIcon />+ </IconButton>+ </Tooltip>+ </InputAdornment>+ ),+ }}+ />+ </Box>++ {/* Directory Status Info */}+ {directoryInfo && (+ <Box sx={{+ p: 1.5,+ borderRadius: 1,+ border: `2px solid ${theme.palette.divider}`+ }}>+ <Stack spacing={1}>+ <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>+ <InfoIcon fontSize="small" color="info" />+ <Typography variant="caption" fontWeight="medium">+ Calibration Folder Status+ </Typography>+ </Box>++ <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>+ <Chip+ label={directoryInfo.exists ? "Directory exists" : "Directory will be created"}+ size="small"+ color={directoryInfo.exists ? "success" : "default"}+ icon={directoryInfo.exists ? <CheckCircleIcon /> : <CloseIcon />}+ variant={directoryInfo.exists ? "filled" : "outlined"}+ sx={!directoryInfo.exists ? {+ borderColor: theme.palette.grey[400],+ '& .MuiChip-icon': { color: theme.palette.grey[600] }+ } : {}}+ />++ <Chip+ label="Has videos"+ size="small"+ color={directoryInfo.hasVideos ? "success" : "default"}+ icon={directoryInfo.hasVideos ? <CheckCircleIcon /> : <CloseIcon />}+ variant={directoryInfo.hasVideos ? "filled" : "outlined"}+ sx={!directoryInfo.hasVideos ? {+ borderColor: theme.palette.grey[400],+ '& .MuiChip-icon': { color: theme.palette.grey[600] }+ } : {}}+ />++ <Chip+ label="Has synchronized_videos"+ size="small"+ color={directoryInfo.hasSynchronizedVideos ? "success" : "default"}+ icon={directoryInfo.hasSynchronizedVideos ? <CheckCircleIcon /> : <CloseIcon />}+ variant={directoryInfo.hasSynchronizedVideos ? "filled" : "outlined"}+ sx={!directoryInfo.hasSynchronizedVideos ? {+ borderColor: theme.palette.grey[400],+ '& .MuiChip-icon': { color: theme.palette.grey[600] }+ } : {}}+ />++ <Chip+ label="Has calibration TOML"+ size="small"+ color={directoryInfo.cameraCalibrationTomlPath ? "success" : "default"}+ icon={directoryInfo.cameraCalibrationTomlPath ? <CheckCircleIcon /> : <CloseIcon />}+ variant={directoryInfo.cameraCalibrationTomlPath ? "filled" : "outlined"}+ sx={!directoryInfo.cameraCalibrationTomlPath ? {+ borderColor: theme.palette.grey[400],+ '& .MuiChip-icon': { color: theme.palette.grey[600] }+ } : {}}+ />+ </Box>++ {directoryInfo.cameraCalibrationTomlPath && (+ <Box sx={{ mt: 1 }}>+ <Typography variant="caption" color="text.secondary">+ Found calibration file:+ </Typography>+ <Typography+ variant="caption"+ sx={{+ fontFamily: 'monospace',+ display: 'block',+ color: 'success.main',+ wordBreak: 'break-all'+ }}+ >+ {directoryInfo.cameraCalibrationTomlPath}+ </Typography>+ </Box>+ )}+ </Stack>+ </Box>+ )}++ {/* Board Size Configuration - All on one row */}+ <Stack direction="row" spacing={2}>+ <FormControl size="small" sx={{ minWidth: 140 }}>+ <InputLabel id="board-preset-label">Preset</InputLabel>+ <Select+ labelId="board-preset-label"+ value={currentPreset}+ label="Preset"+ onChange={(e) => handlePresetChange(e.target.value as BoardPreset)}+ disabled={isLoading}+ sx={{color: theme.palette.text.primary}}+ >+ <MenuItem value="5x3">5ร3</MenuItem>+ <MenuItem value="7x5">7ร5</MenuItem>+ <MenuItem value="custom">Custom</MenuItem>+ </Select>+ </FormControl>+ <TextField+ label="X Squares"+ type="number"+ value={config.charucoBoardXSquares}+ onChange={(e) => handleXSquaresChange(e.target.value)}+ disabled={isLoading}+ size="small"+ sx={{ flex: 1 }}+ inputProps={{ min: 2, max: 20 }}+ />+ <TextField+ label="Y Squares"+ type="number"+ value={config.charucoBoardYSquares}+ onChange={(e) => handleYSquaresChange(e.target.value)}+ disabled={isLoading}+ size="small"+ sx={{ flex: 1 }}+ inputProps={{ min: 2, max: 20 }}+ />+ </Stack>++ {/* Square Length */}+ <TextField+ label="Square Length (mm)"+ type="number"+ value={config.charucoSquareLength}+ onChange={(e) => updateCalibrationConfig({+ charucoSquareLength: parseFloat(e.target.value) || 0+ })}+ disabled={isLoading}+ size="small"+ fullWidth+ inputProps={{ min: 1, step: 0.1 }}+ />++ {/* Recording Progress */}+ {isRecording && (+ <Box sx={{ width: '100%' }}>+ <Typography variant="caption" color="text.secondary" gutterBottom>+ Recording in Progress: {recordingProgress.toFixed(0)}%+ </Typography>+ <Box+ sx={{+ width: '100%',+ height: 8,+ bgcolor: 'grey.300',+ borderRadius: 1,+ overflow: 'hidden',+ }}+ >+ <Box+ sx={{+ width: `${recordingProgress}%`,+ height: '100%',+ bgcolor: theme.palette.primary.main,+ transition: 'width 0.3s',+ }}+ />+ </Box>+ </Box>+ )}++ {/* Calibrate Button */}+ <Button+ variant="contained"+ color="secondary"+ onClick={calibrateSelectedRecording}+ disabled={!canCalibrate || isLoading}+ fullWidth+ >+ Calibrate Selected Recording+ </Button>+ </Stack>+ </Box>+ </TreeItem>+ </SimpleTreeView>+ );+};diff --git a/freemocap-ui/src/components/camera-config-tree-view/CameraConfigTreeSection.tsx b/freemocap-ui/src/components/camera-config-tree-view/CameraConfigTreeSection.tsxnew file mode 100644index 00000000..20bf4c4e--- /dev/null+++ b/freemocap-ui/src/components/camera-config-tree-view/CameraConfigTreeSection.tsx@@ -0,0 +1,38 @@+import React from "react";+import {TreeItem} from "@mui/x-tree-view/TreeItem";+import {useAppDispatch} from "@/store";+import {cameraDesiredConfigUpdated} from "@/store/slices/cameras/cameras-slice";+import {Camera, CameraConfig} from "@/store/slices/cameras/cameras-types";+import {CameraConfigPanel} from "@/components/camera-config-tree-view/camera-config-panel/CameraConfigPanel";++interface CameraConfigTreeSectionProps {+ camera: Camera;+}++export const CameraConfigTreeSection: React.FC<CameraConfigTreeSectionProps> = ({+ camera,+ }) => {+ const dispatch = useAppDispatch();++ const handleConfigChange = (newConfig: CameraConfig): void => {+ dispatch(+ cameraDesiredConfigUpdated({+ cameraId: camera.id,+ config: newConfig,+ })+ );+ };++ return (+ <TreeItem+ itemId={`camera-${camera.id}-config`}+ label={+ <CameraConfigPanel+ config={camera.desiredConfig}+ onConfigChange={handleConfigChange}+ isExpanded={true}+ />+ }+ />+ );+};diff --git a/freemocap-ui/src/components/camera-config-tree-view/CameraConfigTreeView.tsx b/freemocap-ui/src/components/camera-config-tree-view/CameraConfigTreeView.tsxnew file mode 100644index 00000000..ed189217--- /dev/null+++ b/freemocap-ui/src/components/camera-config-tree-view/CameraConfigTreeView.tsx@@ -0,0 +1,128 @@+import React, {useEffect, useState} from "react";+import {Paper, useTheme,} from "@mui/material";+import {SimpleTreeView} from "@mui/x-tree-view/SimpleTreeView";+import {TreeItem} from "@mui/x-tree-view/TreeItem";+import ExpandMore from "@mui/icons-material/ExpandMore";+import ChevronRight from "@mui/icons-material/ChevronRight";+import VideoCameraFrontIcon from '@mui/icons-material/VideoCameraFront';++import {CameraConfigTreeViewHeader} from "./CameraConfigTreeViewHeader";+import {CameraGroupTreeItem} from "./CameraGroupTreeItem";+import {NoCamerasPlaceholder} from "./NoCamerasPlaceholder";+import {+ Camera,+ detectCameras,+ selectCameras,+ selectConnectedCameras,+ selectIsLoading,+ selectSelectedCameras,+ useAppDispatch,+ useAppSelector+} from "@/store";++import {useServer} from "@/hooks/useServer";+++export const CameraConfigTreeView: React.FC = () => {+ const theme = useTheme();+ const dispatch = useAppDispatch();+ const {isConnected} = useServer()+ // Redux state+ const cameras = useAppSelector(selectCameras);+ const isLoading = useAppSelector(selectIsLoading);+ const connectedCameras = useAppSelector(selectConnectedCameras);+ const selectedCameras = useAppSelector(selectSelectedCameras);++ // Local state+ const [expandedItems, setExpandedItems] = useState<string[]>([+ "cameras-root",+ "cameras-connected",+ "cameras-available"+ ]);+ const [isPaused, setIsPaused] = useState<boolean>(false);++ // Group cameras by status+ const availableCameras = cameras.filter((cam: Camera) => cam.connectionStatus !== "connected");+ const isConnectedToCameras = connectedCameras.length > 0;+ const hasSelectedCameras = selectedCameras.length > 0;++ // Initial camera detection+ useEffect(() => {+ if (isConnected && cameras.length === 0) {+ dispatch(detectCameras({ filterVirtual: true }));+ }+ }, [isConnected, cameras.length, dispatch]);++ const handleExpandedItemsChange = (+ event: React.SyntheticEvent,+ itemIds: string[]+ ): void => {+ setExpandedItems(itemIds);+ };++ const handlePauseToggle = (): void => {+ setIsPaused(!isPaused);+ };+++ return (+ <Paper+ elevation={3}+ sx={{+ borderRadius: 2,+ overflow: "hidden",+ }}+ >+ <SimpleTreeView+ expandedItems={expandedItems}+ onExpandedItemsChange={handleExpandedItemsChange}+ slots={{+ collapseIcon: ExpandMore,+ expandIcon: ChevronRight,+ }}+ >+ <TreeItem+ itemId="cameras-root"+ label={+ <CameraConfigTreeViewHeader+ cameraCount={cameras.length}+ isConnected={isConnectedToCameras}+ isLoading={isLoading}+ isPaused={isPaused}+ onPauseToggle={handlePauseToggle}+ hasSelectedCameras={hasSelectedCameras}+ />+ }+ >+ {cameras.length === 0 ? (+ <NoCamerasPlaceholder />+ ) : (+ <>+ {/* Connected Cameras Group */}+ {isConnectedToCameras && connectedCameras.length > 0 && (+ <CameraGroupTreeItem+ groupId="cameras-connected"+ title="Connected Cameras"+ cameras={connectedCameras}+ icon={<VideoCameraFrontIcon color="success" />}+ expandedItems={expandedItems}+ />+ )}++ {/* Available Cameras Group */}+ {availableCameras.length > 0 && (+ <CameraGroupTreeItem+ groupId="cameras-available"+ title="Available Cameras"+ cameras={availableCameras}+ icon={<VideoCameraFrontIcon color="info" />}+ expandedItems={expandedItems}+ />+ )}+ </>+ )}+ </TreeItem>+ </SimpleTreeView>+ </Paper>+ );+};diff --git a/freemocap-ui/src/components/camera-config-tree-view/CameraConfigTreeViewHeader.tsx b/freemocap-ui/src/components/camera-config-tree-view/CameraConfigTreeViewHeader.tsxnew file mode 100644index 00000000..4adf61d9--- /dev/null+++ b/freemocap-ui/src/components/camera-config-tree-view/CameraConfigTreeViewHeader.tsx@@ -0,0 +1,182 @@+import React from "react";+import {Box, CircularProgress, IconButton, Stack, Tooltip, Typography, useTheme} from "@mui/material";+import VideocamIcon from "@mui/icons-material/Videocam";+import VideocamOffIcon from "@mui/icons-material/VideocamOff";+import PauseIcon from "@mui/icons-material/Pause";+import PlayArrowIcon from "@mui/icons-material/PlayArrow";+import YoutubeSearchedForIcon from "@mui/icons-material/YoutubeSearchedFor";++import {camerasConnectOrUpdate, closeCameras, pauseUnpauseCameras, useAppDispatch, useAppSelector} from "@/store";+import {selectSelectedCameras} from "@/store/slices/cameras/cameras-selectors";+import {detectCameras,} from "@/store/slices/cameras/cameras-thunks";+++interface CameraConfigTreeViewHeaderProps {+ cameraCount: number;+ isLoading: boolean;+ isPaused: boolean;+ onPauseToggle: () => void;+ hasSelectedCameras: boolean;+}++export const CameraConfigTreeViewHeader: React.FC<CameraConfigTreeViewHeaderProps> = ({+ cameraCount,+ isLoading,+ isPaused,+ onPauseToggle,+}) => {+ const theme = useTheme();+ const dispatch = useAppDispatch();+ const selectedCameras = useAppSelector(selectSelectedCameras);+ const hasSelected = selectedCameras.length > 0;++ const [isActionInProgress, setIsActionInProgress] = React.useState(false);++ const handleRefreshCameras = async (e: React.MouseEvent): Promise<void> => {+ e.stopPropagation();++ setIsActionInProgress(true);+ try {+ await dispatch(detectCameras({filterVirtual: true})).unwrap();+ } catch (error) {+ console.error('Error detecting cameras:', error);+ } finally {+ setIsActionInProgress(false);+ }+ };++ const handleConnectOrApply = async (e: React.MouseEvent): Promise<void> => {+ e.stopPropagation();++ setIsActionInProgress(true);+ try {+ await dispatch(camerasConnectOrUpdate()).unwrap();+ } catch (error) {+ console.error('Error with camera operation:', error);+ } finally {+ setIsActionInProgress(false);+ }+ };++ const handleCloseCameras = async (e: React.MouseEvent): Promise<void> => {+ e.stopPropagation();++ setIsActionInProgress(true);+ try {+ await dispatch(closeCameras()).unwrap();+ console.log('Closed all cameras');+ } catch (error) {+ console.error('Error closing cameras:', error);+ } finally {+ setIsActionInProgress(false);+ }+ };++ const handlePauseUnpause = async (e: React.MouseEvent): Promise<void> => {+ e.stopPropagation();++ setIsActionInProgress(true);+ try {+ await dispatch(pauseUnpauseCameras()).unwrap();+ onPauseToggle();+ } catch (error) {+ console.error('Error pausing/unpausing cameras:', error);+ } finally {+ setIsActionInProgress(false);+ }+ };++ const handleHeaderClick = (e: React.MouseEvent): void => {+ e.stopPropagation();+ };++ return (+ <Box+ onClick={handleHeaderClick}+ sx={{+ display: "flex",+ alignItems: "center",+ py: 1,+ backgroundColor: theme.palette.primary.main,+ color: theme.palette.primary.contrastText,+ }}+ >+ <VideocamIcon sx={{ml: 2, mr: 1}} />+ <Typography variant="h6" sx={{flexGrow: 1}}>+ Cameras ({cameraCount})+ </Typography>++ <Stack direction="row" spacing={1} sx={{mr: 2}}>+ {/* Connect/Apply Button */}+ <Tooltip title={"Connect to selected cameras or update connected cameras"}>+ <span>+ <IconButton+ size="small"+ onClick={handleConnectOrApply}+ sx={{color: "inherit"}}+ >++ <VideocamIcon+ sx={{+ color: theme.palette.secondary.main,+ border: `2px solid ${theme.palette.secondary.main}`,+ borderRadius: '4px',+ padding: '2px',+ scale: '1.6'+ }}+ />++ </IconButton>+ </span>+ </Tooltip>++ {/* Pause/Play Button - Always visible, disabled when not connected */}+ <Tooltip title={isPaused ? "Resume streaming" : "Pause streaming"}>+ <span>+ <IconButton+ size="small"+ onClick={handlePauseUnpause}+ sx={{+ color: "inherit",+ }}+ >+ {isPaused ? <PlayArrowIcon /> : <PauseIcon />}+ </IconButton>+ </span>+ </Tooltip>++ {/* Close Button - Always visible, disabled when not connected */}+ <Tooltip title={"Close all cameras"}>+ <span>+ <IconButton+ size="small"+ onClick={handleCloseCameras}+ sx={{+ color: "inherit",+ }}+ >+ <VideocamOffIcon />+ </IconButton>+ </span>+ </Tooltip>++ {/* Refresh/Detect Button - Always visible */}+ <Tooltip title="Detect available cameras">+ <span>+ <IconButton+ size="small"+ onClick={handleRefreshCameras}+ sx={{color: "inherit"}}+ >+ {isLoading || isActionInProgress ? (+ <CircularProgress size={20} sx={{color: "inherit"}} />+ ) : (+ <YoutubeSearchedForIcon />+ )}+ </IconButton>+ </span>+ </Tooltip>+ </Stack>+ </Box>+ );+};diff --git a/freemocap-ui/src/components/camera-config-tree-view/CameraGroupTreeItem.tsx b/freemocap-ui/src/components/camera-config-tree-view/CameraGroupTreeItem.tsxnew file mode 100644index 00000000..fc5e7767--- /dev/null+++ b/freemocap-ui/src/components/camera-config-tree-view/CameraGroupTreeItem.tsx@@ -0,0 +1,43 @@+import React from "react";+import {Box, Typography} from "@mui/material";+import {TreeItem} from "@mui/x-tree-view/TreeItem";+import {CameraTreeItem} from "./CameraTreeItem";+import {Camera} from "@/store/slices/cameras/cameras-types";++interface CameraGroupTreeItemProps {+ groupId: string;+ title: string;+ cameras: Camera[];+ icon?: React.ReactNode;+ expandedItems?: string[];+}++export const CameraGroupTreeItem: React.FC<CameraGroupTreeItemProps> = ({+ groupId,+ title,+ cameras,+ icon,+ expandedItems,+ }) => {+ return (+ <TreeItem+ itemId={groupId}+ label={+ <Box sx={{ display: "flex", alignItems: "center" }}>+ {icon}+ <Typography variant="subtitle2" sx={{ ml: 1 }}>+ {title} ({cameras.length})+ </Typography>+ </Box>+ }+ >+ {cameras.map((camera: Camera) => (+ <CameraTreeItem+ key={camera.id}+ camera={camera}+ isExpanded={expandedItems?.includes(`camera-${camera.id}`)}+ />+ ))}+ </TreeItem>+ );+};diff --git a/freemocap-ui/src/components/camera-config-tree-view/CameraTreeItem.tsx b/freemocap-ui/src/components/camera-config-tree-view/CameraTreeItem.tsxnew file mode 100644index 00000000..c4ba8949--- /dev/null+++ b/freemocap-ui/src/components/camera-config-tree-view/CameraTreeItem.tsx@@ -0,0 +1,202 @@+import React from "react";+import {Box, Chip, IconButton, Typography, useTheme} from "@mui/material";+import {TreeItem} from "@mui/x-tree-view/TreeItem";+import CheckCircleIcon from "@mui/icons-material/CheckCircle";+import RadioButtonUncheckedIcon from "@mui/icons-material/RadioButtonUnchecked";+import VideocamIcon from "@mui/icons-material/Videocam";+import SettingsIcon from "@mui/icons-material/Settings";++import {CameraConfigTreeSection} from "./CameraConfigTreeSection";+import {ROTATION_DEGREE_LABELS, RotationValue, useAppDispatch} from "@/store";+import {cameraSelectionToggled} from "@/store/slices/cameras/cameras-slice";+import {Camera} from "@/store/slices/cameras/cameras-types";++interface CameraTreeItemProps {+ camera: Camera;+ isExpanded?: boolean;+}++// Helper function to format config summary+const getConfigSummary = (config: any): string[] => {+ const summary: string[] = [];++ if (!config) return summary;++ // Add resolution if available+ if (config.resolution?.width && config.resolution?.height) {+ summary.push(`${config.resolution.width}ร${config.resolution.height}`);+ }++ if (config.framerate) {+ summary.push(`${parseFloat(config.framerate).toFixed(2)}fps`);+ }++ // Add exposure if available and not AUTO+ if (config.exposure !== undefined && config.exposure_mode === 'MANUAL') {+ summary.push(`E:${config.exposure}`);+ }++ // Add pixel format if available and not default+ if (config.pixel_format && config.pixel_format !== 'RGB') {+ summary.push(config.pixel_format);+ }++ if (config.rotation) {+ summary.push(ROTATION_DEGREE_LABELS[config.rotation as RotationValue]);+ }+ // Add capture format if different from default+ if (config.capture_fourcc) {+ summary.push(config.capture_fourcc);+ }++ return summary.filter(item => item); // Remove empty strings+};++export const CameraTreeItem: React.FC<CameraTreeItemProps> = ({camera, isExpanded = false}) => {+ const dispatch = useAppDispatch();+ const theme = useTheme();++ const handleToggleSelection = (e: React.MouseEvent): void => {+ e.stopPropagation();+ dispatch(cameraSelectionToggled(camera.id));+ };++ const getStatusColor = (): string => {+ switch (camera.connectionStatus) {+ case "connected":+ return theme.palette.success.main;+ case "available":+ return theme.palette.info.main;+ case "error":+ return theme.palette.error.main;+ default:+ return theme.palette.grey[500];+ }+ };++ const configSummary = getConfigSummary(camera.desiredConfig);+ const showConfigSummary = !isExpanded && configSummary.length > 0;++ return (+ <TreeItem+ itemId={`camera-${camera.id}`}+ label={+ <Box+ sx={{+ display: "flex",+ alignItems: "center",+ py: 0.2,+ pr: 1,+ minHeight: 32,+ }}+ >+ {/* Selection checkbox */}+ <IconButton+ size="small"+ onClick={handleToggleSelection}+ sx={{mr: 1, flexShrink: 0}}+ >+ {camera.selected ? (+ <CheckCircleIcon color="info"/>+ ) : (+ <RadioButtonUncheckedIcon color="info"/>+ )}+ </IconButton>++ {/* Camera icon */}+ <VideocamIcon sx={{mr: 1, color: getStatusColor(), flexShrink: 0}}/>++ {/* Camera name and config summary container */}+ <Box sx={{+ display: "flex",+ alignItems: "center",+ flexGrow: 1,+ minWidth: 0, // Allow shrinking+ gap: 1+ }}>+ {/* Camera name */}+ <Typography+ variant="body2"+ sx={{+ flexShrink: 0,+ whiteSpace: "nowrap",+ overflow: "hidden",+ textOverflow: "ellipsis",+ maxWidth: "200px" // Limit name width+ }}+ >+ <span style={{fontSize: '0.75rem'}}>++ Camera {camera.index}+ </span>+ <br/>+ <span style={{fontSize: '0.6rem'}}>+ {camera.name} (id: {camera.id})+ </span>+ </Typography>++ {/* Config summary - only show when collapsed */}+ {showConfigSummary && (+ <Box sx={{+ display: "flex",+ alignItems: "center",+ gap: 0.25,+ flexGrow: 1,+ minWidth: 0,+ overflow: "hidden"+ }}>+ <SettingsIcon+ sx={{+ fontSize: 14,+ color: theme.palette.text.secondary,+ flexShrink: 0+ }}+ />+ <Box sx={{+ display: "flex",+ gap: 0.5,+ flexWrap: "wrap",+ overflow: "hidden"+ }}>+ {configSummary.slice(0, 5).map((item, index) => (+ <Chip+ key={index}+ label={item}+ size="small"+ variant="outlined"+ sx={{+ height: 10,+ fontSize: 8,+ '& .MuiChip-label': {+ px: 0.75,+ },+ borderColor: theme.palette.divider,+ color: theme.palette.text.secondary,+ }}+ />+ ))}+ </Box>+ </Box>+ )}+ </Box>++ {/* Status chip */}+ <Chip+ label={camera.connectionStatus.toUpperCase()}+ size="small"+ sx={{+ ml: 1,+ flexShrink: 0,+ backgroundColor: getStatusColor(),+ color: theme.palette.getContrastText(getStatusColor()),+ fontSize: 10,+ height: 20,+ }}+ />+ </Box>+ }+ >+ <CameraConfigTreeSection camera={camera}/>+ </TreeItem>+ );+};diff --git a/freemocap-ui/src/components/camera-config-tree-view/NoCamerasPlaceholder.tsx b/freemocap-ui/src/components/camera-config-tree-view/NoCamerasPlaceholder.tsxnew file mode 100644index 00000000..901538bc--- /dev/null+++ b/freemocap-ui/src/components/camera-config-tree-view/NoCamerasPlaceholder.tsx@@ -0,0 +1,31 @@+import React from "react";+import {Box, Typography} from "@mui/material";+import {TreeItem} from "@mui/x-tree-view/TreeItem";++export const NoCamerasPlaceholder: React.FC = () => {+ return (+ <TreeItem+ itemId="no-cameras"+ label={+ <Box+ sx={{+ p: 3,+ textAlign: "center",+ bgcolor: "background.paper",+ }}+ >+ <Typography variant="body1" color="text.secondary">+ No cameras detected+ </Typography>+ <Typography+ variant="caption"+ color="text.disabled"+ sx={{ mt: 1, display: "block" }}+ >+ Click refresh to scan for available cameras+ </Typography>+ </Box>+ }+ />+ );+};diff --git a/freemocap-ui/src/components/available-cameras-panel/CameraConfigExposure.tsx b/freemocap-ui/src/components/camera-config-tree-view/camera-config-panel/CameraConfigExposure.tsxsimilarity index 73%rename from freemocap-ui/src/components/available-cameras-panel/CameraConfigExposure.tsxrename to freemocap-ui/src/components/camera-config-tree-view/camera-config-panel/CameraConfigExposure.tsxindex 90ce4e03..fb1bd382 100644--- a/freemocap-ui/src/components/available-cameras-panel/CameraConfigExposure.tsx+++ b/freemocap-ui/src/components/camera-config-tree-view/camera-config-panel/CameraConfigExposure.tsx@@ -1,12 +1,10 @@-// CameraConfigExposure.tsx-import * as React from 'react';+import React from 'react';import {Box, Slider, ToggleButton, ToggleButtonGroup, Tooltip, Typography, useTheme} from '@mui/material';-import {CAMERA_DEFAULT_CONSTRAINTS, ExposureMode} from "@/store/slices/cameras-slices/camera-types";-import {useAppDispatch} from "@/store/AppStateStore";+import {ExposureMode} from "@/store/slices/cameras/cameras-types";interface CameraConfigExposureProps {exposureMode: ExposureMode;- exposure: number ;+ exposure: number;onExposureModeChange: (mode: ExposureMode) => void;onExposureValueChange: (value: number) => void;}@@ -15,7 +13,7 @@ const ValueLabelComponent = (props: {children: React.ReactElement;value: number;}) => {- const {children, value} = props;+ const { children, value } = props;return (<Tooltip title={@@ -29,9 +27,17 @@ const ValueLabelComponent = (props: {</Tooltip>);};++// Default constraints for exposure+const EXPOSURE_CONSTRAINTS = {+ min: -13,+ max: -4,+ default: -7+};+export const CameraConfigExposure: React.FC<CameraConfigExposureProps> = ({- exposureMode = CAMERA_DEFAULT_CONSTRAINTS.exposure_modes[0], // MANUAL- exposure = CAMERA_DEFAULT_CONSTRAINTS.exposure.default,+ exposureMode = 'MANUAL',+ exposure = EXPOSURE_CONSTRAINTS.default,onExposureModeChange,onExposureValueChange}) => {@@ -39,25 +45,33 @@ export const CameraConfigExposure: React.FC<CameraConfigExposureProps> = ({const handleModeChange = (event: React.MouseEvent<HTMLElement>,- newMode: string,- ) => {+ newMode: string | null,+ ): void => {if (newMode !== null) {onExposureModeChange(newMode as ExposureMode);}};-+ const handleSliderChange = (event: Event, value: number | number[]): void => {+ onExposureValueChange(value as number);+ };const baseMarks = [- {value: CAMERA_DEFAULT_CONSTRAINTS.exposure.min, label: String(CAMERA_DEFAULT_CONSTRAINTS.exposure.min)},- {value: CAMERA_DEFAULT_CONSTRAINTS.exposure.default, label: `${CAMERA_DEFAULT_CONSTRAINTS.exposure.default} (default)`},- {value: CAMERA_DEFAULT_CONSTRAINTS.exposure.max, label: String(CAMERA_DEFAULT_CONSTRAINTS.exposure.max)}+ { value: EXPOSURE_CONSTRAINTS.min, label: String(EXPOSURE_CONSTRAINTS.min) },+ {+ value: EXPOSURE_CONSTRAINTS.default,+ label: `${EXPOSURE_CONSTRAINTS.default} (default)`+ },+ { value: EXPOSURE_CONSTRAINTS.max, label: String(EXPOSURE_CONSTRAINTS.max) }];+const marks = [...baseMarks,- ...(![CAMERA_DEFAULT_CONSTRAINTS.exposure.min as number,- CAMERA_DEFAULT_CONSTRAINTS.exposure.default as number,- CAMERA_DEFAULT_CONSTRAINTS.exposure.max as number].includes(exposure)+ ...(![+ EXPOSURE_CONSTRAINTS.min as number,+ EXPOSURE_CONSTRAINTS.default as number,+ EXPOSURE_CONSTRAINTS.max as number+ ].includes(exposure)? [{value: exposure,label: `${exposure}`,@@ -95,16 +109,16 @@ export const CameraConfigExposure: React.FC<CameraConfigExposureProps> = ({</ToggleButtonGroup></Tooltip><Tooltip title="Adjust exposure time, e.g. cv2.VideoCapture.set(cv2.CAP_PROP_EXPOSURE, value)">- <Box sx={{flexGrow: 1}}>+ <Box sx={{ flexGrow: 1 }}><Slidervalue={exposure}disabled={exposureMode === 'AUTO' || exposureMode === 'RECOMMEND'}- min={CAMERA_DEFAULT_CONSTRAINTS.exposure.min}- max={CAMERA_DEFAULT_CONSTRAINTS.exposure.max}+ min={EXPOSURE_CONSTRAINTS.min}+ max={EXPOSURE_CONSTRAINTS.max}step={1}marks={marks}valueLabelDisplay="auto"- onChange={(_, value) => onExposureValueChange(value as number)}+ onChange={handleSliderChange}components={{ValueLabel: ValueLabelComponent}}@@ -112,10 +126,9 @@ export const CameraConfigExposure: React.FC<CameraConfigExposureProps> = ({color: theme.palette.primary.light,'& .MuiSlider-thumb': {'&:hover, &.Mui-focusVisible': {- boxShadow: `0px 0px 0px 8px ${theme.palette.primary.light}33`, // Adding a cool effect on hover and focus+ boxShadow: `0px 0px 0px 8px ${theme.palette.primary.light}33`,},},-}}/></Box>@@ -123,4 +136,3 @@ export const CameraConfigExposure: React.FC<CameraConfigExposureProps> = ({</Box>);};-diff --git a/freemocap-ui/src/components/camera-config-tree-view/camera-config-panel/CameraConfigPanel.tsx b/freemocap-ui/src/components/camera-config-tree-view/camera-config-panel/CameraConfigPanel.tsxnew file mode 100644index 00000000..312d2d75--- /dev/null+++ b/freemocap-ui/src/components/camera-config-tree-view/camera-config-panel/CameraConfigPanel.tsx@@ -0,0 +1,142 @@+import React from "react";+import {Box, Collapse, IconButton, Tooltip, useTheme,} from "@mui/material";+import Grid from "@mui/material/Grid2";+import MediationIcon from "@mui/icons-material/Mediation";+import {CameraConfigResolution} from "./CameraConfigResolution";+import {CameraConfigExposure} from "./CameraConfigExposure";+import {CameraConfigRotation} from "./CameraConfigRotation";+import {CameraConfig, ExposureMode} from "@/store/slices/cameras/cameras-types";+import {useAppDispatch, useAppSelector} from "@/store";+import {configCopiedToAll, selectCameras} from "@/store/slices/cameras";++interface CameraConfigPanelProps {+ config: CameraConfig;+ onConfigChange: (newConfig: CameraConfig) => void;+ isExpanded: boolean;+}++export const CameraConfigPanel: React.FC<CameraConfigPanelProps> = ({+ config,+ onConfigChange,+ isExpanded,+ }) => {+ const theme = useTheme();+ const dispatch = useAppDispatch();++ // Get total camera count for UI feedback+ const allCameras = useAppSelector(selectCameras);+ const otherCamerasCount = allCameras.length - 1;++ const handleChange = <K extends keyof CameraConfig>(+ key: K,+ value: CameraConfig[K]+ ): void => {+ onConfigChange({+ ...config,+ [key]: value,+ });+ };++ const handleCopyToAllCameras = (): void => {+ dispatch(configCopiedToAll(config.camera_id));+ };++ const handleResolutionChange = (width: number, height: number): void => {+ handleChange("resolution", { width, height });+ };++ const handleRotationChange = (value: string): void => {+ handleChange("rotation", value as CameraConfig['rotation']);+ };++ const handleExposureModeChange = (mode: ExposureMode): void => {+ handleChange("exposure_mode", mode);+ };++ const handleExposureValueChange = (value: number): void => {+ handleChange("exposure", value);+ };++ return (+ <Collapse in={isExpanded} timeout="auto" unmountOnExit>+ <Box+ sx={{+ p: 1.5,+ ml: 7,+ mr: 2,+ mb: 1,+ borderRadius: 1,+ border: `1px solid ${theme.palette.divider}`,+ backgroundColor: theme.palette.background.paper,+ }}+ >+ <Grid container spacing={2}>+ {/* Top row with Resolution and Rotation */}+ <Grid size={{ xs: 12, md: 5 }}>+ <CameraConfigResolution+ resolution={config.resolution}+ onChange={handleResolutionChange}+ />+ </Grid>++ <Grid size={{ xs: 12, md: 5 }}>+ <CameraConfigRotation+ rotation={config.rotation}+ onChange={handleRotationChange}+ />+ </Grid>++ <Grid+ size={{ xs: 12, md: 2 }}+ sx={{+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ }}+ >+ <Tooltip+ title={+ otherCamerasCount > 0+ ? `Copy settings to ${otherCamerasCount} other camera${+ otherCamerasCount > 1 ? "s" : ""+ }`+ : "No other cameras to copy to"+ }+ >+ <span>+ <IconButton+ size="small"+ onClick={handleCopyToAllCameras}+ disabled={otherCamerasCount === 0}+ aria-label="Copy settings to all cameras"+ sx={{+ color: theme.palette.primary.main,+ "&:hover": {+ backgroundColor: theme.palette.primary.light,+ color: theme.palette.primary.contrastText,+ },+ "&:disabled": {+ color: theme.palette.action.disabled,+ },+ }}+ >+ <MediationIcon />+ </IconButton>+ </span>+ </Tooltip>+ </Grid>++ {/* Bottom row with Exposure controls */}+ <Grid size={12}>+ <CameraConfigExposure+ exposureMode={config.exposure_mode}+ exposure={config.exposure}+ onExposureModeChange={handleExposureModeChange}+ onExposureValueChange={handleExposureValueChange}+ />+ </Grid>+ </Grid>+ </Box>+ </Collapse>+ );+};diff --git a/freemocap-ui/src/components/camera-config-tree-view/camera-config-panel/CameraConfigResolution.tsx b/freemocap-ui/src/components/camera-config-tree-view/camera-config-panel/CameraConfigResolution.tsxnew file mode 100644index 00000000..ae59d11b--- /dev/null+++ b/freemocap-ui/src/components/camera-config-tree-view/camera-config-panel/CameraConfigResolution.tsx@@ -0,0 +1,36 @@+import React from "react";+import {FormControl, InputLabel, MenuItem, Select, useTheme} from "@mui/material";+import {CameraConfig} from "@/store/slices/cameras/cameras-types";++interface CameraConfigResolutionProps {+ resolution: CameraConfig['resolution'];+ onChange: (width: number, height: number) => void;+}++export const CameraConfigResolution: React.FC<CameraConfigResolutionProps> = ({+ resolution,+ onChange+ }) => {+ const theme = useTheme();++ const handleChange = (event: any): void => {+ const [width, height] = event.target.value.split('x').map(Number);+ onChange(width, height);+ };++ return (+ <FormControl size="small" sx={{ flex: 1, color: theme.palette.text.primary }}>+ <InputLabel sx={{ color: theme.palette.text.primary }}>Resolution</InputLabel>+ <Select+ value={`${resolution.width}x${resolution.height}`}+ label="Resolution"+ onChange={handleChange}+ sx={{ color: theme.palette.text.primary }}+ >+ <MenuItem value="640x480">640 x 480</MenuItem>+ <MenuItem value="1280x720">1280 x 720</MenuItem>+ <MenuItem value="1920x1080">1920 x 1080</MenuItem>+ </Select>+ </FormControl>+ );+};diff --git a/freemocap-ui/src/components/available-cameras-panel/CameraConfigRotation.tsx b/freemocap-ui/src/components/camera-config-tree-view/camera-config-panel/CameraConfigRotation.tsxsimilarity index 67%rename from freemocap-ui/src/components/available-cameras-panel/CameraConfigRotation.tsxrename to freemocap-ui/src/components/camera-config-tree-view/camera-config-panel/CameraConfigRotation.tsxindex 3f656fc5..eabca928 100644--- a/freemocap-ui/src/components/available-cameras-panel/CameraConfigRotation.tsx+++ b/freemocap-ui/src/components/camera-config-tree-view/camera-config-panel/CameraConfigRotation.tsx@@ -1,25 +1,26 @@-// CameraConfigRotation.tsx-import * as React from 'react';+import React from 'react';import ToggleButton from '@mui/material/ToggleButton';import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';import {Box, Tooltip, useTheme} from '@mui/material';-import {RotationOptions, RotationLabels} from "@/store/slices/cameras-slices/camera-types";-import {z} from 'zod';+import {ROTATION_DEGREE_LABELS, ROTATION_OPTIONS, RotationValue} from '@/store/slices/cameras/cameras-types';interface CameraConfigRotationProps {- rotation?: number; // Use number directly- onChange: (rotation: number) => void;+ rotation?: RotationValue;+ onChange: (rotation: RotationValue) => void;}++export const CameraConfigRotation: React.FC<CameraConfigRotationProps> = ({- rotation = -1, // Set default value to -1 for NO_ROTATION- onChange-}) => {+ rotation = -1,+ onChange+ }) => {const theme = useTheme();+const handleChange = (event: React.MouseEvent<HTMLElement>,- newRotation: number,- ) => {+ newRotation: RotationValue | null,+ ): void => {if (newRotation !== null) {onChange(newRotation);}@@ -46,14 +47,13 @@ export const CameraConfigRotation: React.FC<CameraConfigRotationProps> = ({}}}>- {/* Map through RotationOptions and RotationLabels to create buttons */}- {RotationOptions.map((value, index) => (- <ToggleButton key={value} value={value}>- {RotationLabels[index]}+ {ROTATION_OPTIONS.map((option: RotationValue) => (+ <ToggleButton key={option} value={option}>+ {ROTATION_DEGREE_LABELS[option]}</ToggleButton>))}</ToggleButtonGroup></Tooltip></Box>);-}\ No newline at end of file+};diff --git a/freemocap-ui/src/components/camera-view-settings-overlay/CamerasViewSettingsOverlay.tsx b/freemocap-ui/src/components/camera-view-settings-overlay/CamerasViewSettingsOverlay.tsxdeleted file mode 100644index 2198aecf..00000000--- a/freemocap-ui/src/components/camera-view-settings-overlay/CamerasViewSettingsOverlay.tsx+++ /dev/null@@ -1,40 +0,0 @@-import React, { useState } from 'react';-import IconButton from '@mui/material/IconButton';-import SettingsIcon from '@mui/icons-material/Settings';-import Box from '@mui/material/Box';-import Paper from '@mui/material/Paper';-import { useTheme } from "@mui/material/styles";-import { ImageScaleSlider } from './ImageScaleSlider';--export const CamerasViewSettingsOverlay = () => {- const [expanded, setExpanded] = useState(false);- const [scale, setScale] = useState(0.5);- const theme = useTheme();-- return (- <Box- sx={{- position: 'absolute',- top: 16,- right: 16,- zIndex: 1000,- }}- >- <IconButton onClick={() => setExpanded(!expanded)}>- <SettingsIcon />- </IconButton>- {expanded && (- <Paper- sx={{- p: 2,- mt: 1,- width: 300, // Fixed width for the expanded box- position: 'relative', // Ensure the gear icon stays pinned- }}- >- <ImageScaleSlider scale={scale} onScaleChange={setScale} />- </Paper>- )}- </Box>- );-};diff --git a/freemocap-ui/src/components/camera-views/CameraView.tsx b/freemocap-ui/src/components/camera-views/CameraView.tsxnew file mode 100644index 00000000..a506e5ab--- /dev/null+++ b/freemocap-ui/src/components/camera-views/CameraView.tsx@@ -0,0 +1,126 @@+import React, {memo, useEffect, useRef} from 'react';++import {useServer} from "@/hooks/useServer";++interface CameraViewProps {+ cameraId: string;+ scale?: number;+ maxWidth?: boolean;+}++/**+ * CameraView component - renders a canvas for a single camera feed.+ * The overlay is now composited directly into the frame before rendering.+ */+export const CameraView: React.FC<CameraViewProps> = memo(({ cameraId, scale, maxWidth }) => {+ const canvasRef = useRef<HTMLCanvasElement>(null);+ const fpsDisplayRef = useRef<HTMLSpanElement>(null);++ const { setCanvasForCamera, getFps } = useServer();+ const animationFrameRef = useRef<number | null>(null);++ // Set up canvas+ useEffect(() => {+ const canvas = canvasRef.current;+ if (canvas && cameraId) {+ console.log(`Setting up canvas for camera: ${cameraId}`);+ setCanvasForCamera(cameraId, canvas);+ }+ }, [cameraId, setCanvasForCamera]);++ // Update FPS display using direct DOM manipulation to avoid React re-renders+ useEffect(() => {+ const updateFps = (): void => {+ const fps = getFps(cameraId);+ if (fpsDisplayRef.current && fps !== null) {+ fpsDisplayRef.current.textContent = `Display FPS ${fps.toFixed(1)}`;+ }+ animationFrameRef.current = requestAnimationFrame(updateFps);+ };++ animationFrameRef.current = requestAnimationFrame(updateFps);++ return () => {+ if (animationFrameRef.current !== null) {+ cancelAnimationFrame(animationFrameRef.current);+ }+ };+ }, [cameraId, getFps]);++ // Calculate canvas styles based on scale and maxWidth settings+ const getCanvasStyle = (): React.CSSProperties => {+ const baseStyle: React.CSSProperties = {+ width: '100%',+ height: '100%',+ objectFit: 'contain',+ };++ if (maxWidth) {+ return baseStyle;+ }++ if (scale !== undefined && scale !== 1.0) {+ return {+ ...baseStyle,+ width: `${scale * 100}%`,+ height: `${scale * 100}%`,+ };+ }++ return baseStyle;+ };++ const canvasStyle = getCanvasStyle();++ return (+ <div+ style={{+ width: '100%',+ height: '100%',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: '#000',+ position: 'relative',+ overflow: 'hidden',+ }}+ >+ {/* Single canvas with composited image + overlay */}+ <canvas+ ref={canvasRef}+ style={canvasStyle}+ />++ {/* Info display */}+ <div+ style={{+ position: 'absolute',+ bottom: 8,+ left: 8,+ backgroundColor: 'rgba(0, 0, 0, 0.7)',+ color: '#fff',+ padding: '4px 8px',+ borderRadius: 4,+ fontSize: '12px',+ fontFamily: 'monospace',+ pointerEvents: 'none',+ }}+ >+ <div>{cameraId}</div>+ <div style={{ fontSize: '10px', marginTop: '2px', color: '#0f0' }}>+ <span ref={fpsDisplayRef}>-- FPS</span>+ </div>+ </div>+ </div>+ );+}, (prevProps, nextProps) => {+ // Custom comparison: only re-render if relevant props change+ return (+ prevProps.cameraId === nextProps.cameraId &&+ prevProps.scale === nextProps.scale &&+ prevProps.maxWidth === nextProps.maxWidth+ );+});++CameraView.displayName = 'CameraView';diff --git a/freemocap-ui/src/components/camera-views/CameraViewsGrid.tsx b/freemocap-ui/src/components/camera-views/CameraViewsGrid.tsxnew file mode 100644index 00000000..24d5c1f4--- /dev/null+++ b/freemocap-ui/src/components/camera-views/CameraViewsGrid.tsx@@ -0,0 +1,140 @@+import React from "react";+import {Box} from "@mui/material";+import {Panel, PanelGroup, PanelResizeHandle} from "react-resizable-panels";+import {useTheme} from "@mui/material/styles";+import {CameraView} from "./CameraView";++import {useServer} from "@/hooks/useServer";++interface CameraSettings {+ columns: number | null;+}++interface CameraViewsGridProps {+ settings?: CameraSettings;+}++interface CameraViewsGridProps {+ settings?: CameraSettings;+ resetKey?: number;+}++export const CameraViewsGrid: React.FC<CameraViewsGridProps> = ({ settings, resetKey }) => {+ const theme = useTheme();+ const { connectedCameraIds } = useServer();++ const getColumns = (total: number): number => {+ if (settings?.columns !== null && settings?.columns !== undefined) {+ return settings.columns;+ }++ if (total <= 1) return 1;+ if (total <= 4) return 2;+ if (total <= 9) return 3;+ return 4;+ };++ if (connectedCameraIds.length === 0) {+ return (+ <Box sx={{+ height: '100%',+ width: '100%',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ color: 'text.secondary',+ fontSize: '1.2rem',+ padding: 4,+ textAlign: 'center',+ }}>+ <div>+ <div>No cameras connected</div>+ <div style={{ fontSize: '0.9rem', marginTop: '0.5rem' }}>+ Waiting for camera streams...+ </div>+ </div>+ </Box>+ );+ }++ const columns = getColumns(connectedCameraIds.length);++ // Organize cameras into rows+ const rows: string[][] = [];+ for (let i = 0; i < connectedCameraIds.length; i += columns) {+ rows.push(connectedCameraIds.slice(i, i + columns));+ }++ // Calculate default size for each panel+ const defaultRowSize = 100 / rows.length;+ const minRowSize = Math.max(10, 100 / (rows.length * 2));++ return (+ <Box sx={{+ height: '100%',+ width: '100%',+ overflow: 'hidden',+ padding: 1,+ }}>+ <PanelGroup key={`camera-grid-${resetKey ?? 0}`} direction="vertical">+ {rows.map((row, rowIndex) => {+ const defaultCameraSize = 100 / row.length;+ const minCameraSize = Math.max(10, 100 / (row.length * 2));++ return (+ <React.Fragment key={`row-${rowIndex}`}>+ <Panel+ defaultSize={defaultRowSize}+ minSize={minRowSize}+ >+ <PanelGroup direction="horizontal">+ {row.map((cameraId, cameraIndex) => (+ <React.Fragment key={cameraId}>+ <Panel+ defaultSize={defaultCameraSize}+ minSize={minCameraSize}+ >+ <Box sx={{+ height: '100%',+ width: '100%',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ overflow: 'hidden',+ }}>+ <CameraView cameraId={cameraId} />+ </Box>+ </Panel>++ {/* Horizontal resize handle between cameras in same row */}+ {cameraIndex < row.length - 1 && (+ <PanelResizeHandle+ style={{+ width: "2px",+ cursor: "col-resize",+ backgroundColor: theme.palette.primary.dark,+ }}+ />+ )}+ </React.Fragment>+ ))}+ </PanelGroup>+ </Panel>++ {/* Vertical resize handle between rows */}+ {rowIndex < rows.length - 1 && (+ <PanelResizeHandle+ style={{+ height: "2px",+ cursor: "row-resize",+ backgroundColor: theme.palette.primary.dark,+ }}+ />+ )}+ </React.Fragment>+ );+ })}+ </PanelGroup>+ </Box>+ );+};diff --git a/freemocap-ui/src/components/camera-views/camera-view-settings-overlay/CamerasViewSettingsOverlay.tsx b/freemocap-ui/src/components/camera-views/camera-view-settings-overlay/CamerasViewSettingsOverlay.tsxnew file mode 100644index 00000000..58e29fca--- /dev/null+++ b/freemocap-ui/src/components/camera-views/camera-view-settings-overlay/CamerasViewSettingsOverlay.tsx@@ -0,0 +1,196 @@+import React, {useState} from 'react';+import {Box, Button, Checkbox, FormControlLabel, IconButton, Paper, TextField, Tooltip} from '@mui/material';+import SettingsIcon from '@mui/icons-material/Settings';+import CloseIcon from '@mui/icons-material/Close';+import GridViewIcon from '@mui/icons-material/GridView';+import ViewInArIcon from '@mui/icons-material/ViewInAr';+import RestartAltIcon from '@mui/icons-material/RestartAlt';++import {useServer} from "@/hooks/useServer";++interface CameraSettings {+ columns: number | null;+ show3dView: boolean;+}++interface CamerasViewSettingsOverlayProps {+ onSettingsChange: (settings: CameraSettings) => void;+ onResetViews: () => void;+}++export const CamerasViewSettingsOverlay: React.FC<CamerasViewSettingsOverlayProps> = ({+ onSettingsChange,+ onResetViews+ }) => {+ const { connectedCameraIds } = useServer();+ const [isOpen, setIsOpen] = useState<boolean>(false);+ const [isAuto, setIsAuto] = useState<boolean>(true);+ const [manualColumns, setManualColumns] = useState<number>(2);+ const [show3dView, setShow3dView] = useState<boolean>(true);++ const getAutoColumns = (total: number): number => {+ if (total <= 1) return 1;+ if (total <= 4) return 2;+ if (total <= 9) return 3;+ return 4;+ };++ const autoColumns = getAutoColumns(connectedCameraIds.length);++ const handleAutoChange = (event: React.ChangeEvent<HTMLInputElement>) => {+ const checked = event.target.checked;+ setIsAuto(checked);+ onSettingsChange({+ columns: checked ? null : manualColumns,+ show3dView+ });+ };++ const handleColumnsChange = (event: React.ChangeEvent<HTMLInputElement>) => {+ const value = parseInt(event.target.value);+ if (!isNaN(value) && value > 0) {+ setManualColumns(value);+ if (isAuto) {+ // User is adjusting input while Auto is checked, so uncheck Auto+ setIsAuto(false);+ }+ onSettingsChange({+ columns: value,+ show3dView+ });+ }+ };++ const handle3dViewChange = (event: React.ChangeEvent<HTMLInputElement>) => {+ const checked = event.target.checked;+ setShow3dView(checked);+ onSettingsChange({+ columns: isAuto ? null : manualColumns,+ show3dView: checked+ });+ };++ const handleResetViews = () => {+ onResetViews();+ };++ return (+ <>+ {/* Settings Button */}+ <Box+ sx={{+ position: 'absolute',+ top: 16,+ right: 16,+ zIndex: 1000,+ }}+ >+ <Tooltip title={isOpen ? "Close settings" : "Grid settings"}>+ <IconButton+ onClick={() => setIsOpen(!isOpen)}+ sx={{+ backgroundColor: 'background.paper',+ boxShadow: 2,+ '&:hover': {+ backgroundColor: 'action.hover',+ },+ }}+ >+ {isOpen ? <CloseIcon /> : <SettingsIcon />}+ </IconButton>+ </Tooltip>+ </Box>++ {/* Settings Panel */}+ {isOpen && (+ <Paper+ elevation={8}+ sx={{+ position: 'absolute',+ top: 70,+ right: 16,+ zIndex: 999,+ padding: 2,+ minWidth: 250,+ }}+ >+ <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 2 }}>+ <GridViewIcon fontSize="small" />+ <Box sx={{ fontWeight: 600 }}>Grid Columns</Box>+ </Box>++ <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1, mb: 3 }}>+ <FormControlLabel+ control={+ <Checkbox+ checked={isAuto}+ onChange={handleAutoChange}+ sx={{+ '&.Mui-checked': {+ color: 'text.primary',+ },+ }}+ />+ }+ label="Auto"+ />++ <TextField+ type="number"+ label="Columns"+ value={isAuto ? autoColumns : manualColumns}+ onChange={handleColumnsChange}+ fullWidth+ inputProps={{+ min: 1,+ step: 1,+ }}+ helperText={isAuto ? `Auto-detected: ${autoColumns}` : "Enter any positive number"}+ />+ </Box>++ <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 2 }}>+ <ViewInArIcon fontSize="small" />+ <Box sx={{ fontWeight: 600 }}>3D View</Box>+ </Box>++ <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1, mb: 3 }}>+ <FormControlLabel+ control={+ <Checkbox+ checked={show3dView}+ onChange={handle3dViewChange}+ sx={{+ '&.Mui-checked': {+ color: 'text.primary',+ },+ }}+ />+ }+ label="Show 3D View"+ />+ </Box>++ <Button+ variant="outlined"+ startIcon={<RestartAltIcon />}+ onClick={handleResetViews}+ fullWidth+ sx={{+ mt: 1,+ textTransform: 'none',+ color: 'text.primary',+ borderColor: 'text.primary',+ '&:hover': {+ borderColor: 'text.primary',+ backgroundColor: 'action.hover',+ },+ }}+ >+ Reset Panel Sizes+ </Button>+ </Paper>+ )}+ </>+ );+};diff --git a/freemocap-ui/src/components/camera-view-settings-overlay/ImageScaleSlider.tsx b/freemocap-ui/src/components/camera-views/camera-view-settings-overlay/ImageScaleSlider.tsxsimilarity index 73%rename from freemocap-ui/src/components/camera-view-settings-overlay/ImageScaleSlider.tsxrename to freemocap-ui/src/components/camera-views/camera-view-settings-overlay/ImageScaleSlider.tsxindex ac80a2ed..18beb8dd 100644--- a/freemocap-ui/src/components/camera-view-settings-overlay/ImageScaleSlider.tsx+++ b/freemocap-ui/src/components/camera-views/camera-view-settings-overlay/ImageScaleSlider.tsx@@ -1,5 +1,5 @@-import React, { useState } from 'react';-import { Box, Slider, Tooltip, Typography, useTheme } from '@mui/material';+import React from 'react';+import {Box, Slider, Tooltip, Typography, useTheme} from '@mui/material';interface ImageScaleSliderProps {scale: number;@@ -10,7 +10,7 @@ const ValueLabelComponent = (props: {children: React.ReactElement;value: number;}) => {- const { children, value } = props;+ const {children, value} = props;return (<Tooltip title={@@ -24,15 +24,15 @@ const ValueLabelComponent = (props: {};export const ImageScaleSlider: React.FC<ImageScaleSliderProps> = ({- scale = 0.5,- onScaleChange,-}) => {+ scale = 0.5,+ onScaleChange,+ }) => {const theme = useTheme();const marks = [- { value: 0.1, label: '0.1' },- { value: 0.5, label: '0.5 (default)' },- { value: 2.0, label: '2.0' },+ {value: 0.1, label: '0.1'},+ {value: 0.5, label: '0.5 (default)'},+ {value: 2.0, label: '2.0'},];return (@@ -62,4 +62,4 @@ export const ImageScaleSlider: React.FC<ImageScaleSliderProps> = ({/></Box>);-};\ No newline at end of file+};diff --git a/freemocap-ui/src/components/camera-views/og-canvas-strategy/CameraImage.tsx b/freemocap-ui/src/components/camera-views/og-canvas-strategy/CameraImage.tsxdeleted file mode 100644index fb3d6442..00000000--- a/freemocap-ui/src/components/camera-views/og-canvas-strategy/CameraImage.tsx+++ /dev/null@@ -1,61 +0,0 @@-import { Box, Typography } from "@mui/material";-import React, { useRef, useMemo } from "react";-import { CameraImageData } from "@/context/websocket-context/useWebsocketBinaryMessageProcessor";-import {useWebSocketContext} from "@/context/websocket-context/WebSocketContext";--interface CameraImageProps {- cameraImageData: CameraImageData;-}--export const CameraImage = ({ cameraImageData}: CameraImageProps) => {- const { cameraId, imageBitmap, imageWidth, imageHeight, cameraIndex , frameNumber} = cameraImageData;- const {acknowledgeFrameRendered} = useWebSocketContext()- const canvasRef = useRef<HTMLCanvasElement>(null);-- // Directly render the bitmap when the ref callback is called- const setCanvasRef = (canvas: HTMLCanvasElement | null) => {-- if (canvas && imageBitmap) {- const ctx = canvas.getContext('2d');- if (ctx) {- canvas.width = imageWidth;- canvas.height = imageHeight;- ctx.drawImage(imageBitmap, 0, 0);- acknowledgeFrameRendered(cameraId, frameNumber);- }- }- };-- return (- <Box- key={cameraId}- sx={{- position: 'relative',- border: "1px solid #333",- }}- >- <canvas- ref={setCanvasRef}- style={{- objectFit: 'cover',- }}- />- <Typography- variant="caption"- sx={{- position: "absolute",- bottom: 8,- left: 8,- color: "white",- backgroundColor: "rgba(0, 0, 0, 0.5)",- padding: "2px 4px",- borderRadius: "4px",- zIndex: 1,- }}- >- Camera {cameraIndex}- </Typography>-- </Box>- );-};diff --git a/freemocap-ui/src/components/camera-views/og-canvas-strategy/CameraImagesGrid.tsx b/freemocap-ui/src/components/camera-views/og-canvas-strategy/CameraImagesGrid.tsxdeleted file mode 100644index 2a305ab2..00000000--- a/freemocap-ui/src/components/camera-views/og-canvas-strategy/CameraImagesGrid.tsx+++ /dev/null@@ -1,29 +0,0 @@-import {Box} from "@mui/material";-import React from "react";-import {CameraImage} from "@/components/camera-views/og-canvas-strategy/CameraImage";-import {useWebSocketContext} from "@/context/websocket-context/WebSocketContext";---export const CameraImagesGrid = () => {- const {latestImageData} = useWebSocketContext();-- return (- <Box sx={{ height: '100%',- width: '100%',- display: 'flex',- gap: 1,- flexDirection: 'row',- flexWrap: 'wrap',- }}>-- {Object.entries(latestImageData).map(([cameraId, cameraImageData]) =>- cameraImageData ? (- <CameraImage- key={cameraId}- cameraImageData={cameraImageData}- />- ) : null- )}- </Box>- );-};diff --git a/freemocap-ui/src/components/common/ErrorBoundary.tsx b/freemocap-ui/src/components/common/ErrorBoundary.tsxindex 0b82a502..cbe18797 100644--- a/freemocap-ui/src/components/common/ErrorBoundary.tsx+++ b/freemocap-ui/src/components/common/ErrorBoundary.tsx@@ -14,19 +14,19 @@ interface ErrorBoundaryState {class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {constructor(props: ErrorBoundaryProps) {super(props);- this.state = { hasError: false, error: null, errorInfo: null };+ this.state = {hasError: false, error: null, errorInfo: null};}static getDerivedStateFromError(error: Error): Partial<ErrorBoundaryState> {// Update state so the next render shows the fallback UI.- return { hasError: true };+ return {hasError: true};}componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {// You can also log the error to an error reporting serviceconsole.error('Error caught by ErrorBoundary', error, errorInfo);// Store the error and errorInfo in state- this.setState({ error, errorInfo });+ this.setState({error, errorInfo});}render() {@@ -35,9 +35,9 @@ class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryStareturn (<div><h1>Something went wrong :(</h1>- <details style={{ whiteSpace: 'pre-wrap' }}>+ <details style={{whiteSpace: 'pre-wrap'}}>{this.state.error && this.state.error.toString()}- <br />+ <br/>{this.state.errorInfo && this.state.errorInfo.componentStack}</details></div>diff --git a/freemocap-ui/src/components/framerate-viewer/BaseD3ChartView.tsx b/freemocap-ui/src/components/framerate-viewer/BaseD3ChartView.tsxindex 9ca90ee1..1dc2aea4 100644--- a/freemocap-ui/src/components/framerate-viewer/BaseD3ChartView.tsx+++ b/freemocap-ui/src/components/framerate-viewer/BaseD3ChartView.tsx@@ -5,195 +5,199 @@ import {Box, Fade, IconButton, Tooltip, Typography} from "@mui/material"import {RestartAlt, ZoomIn, ZoomOut} from "@mui/icons-material"export type ChartMargins = {- top: number- right: number- bottom: number- left: number+ top: number+ right: number+ bottom: number+ left: number}// Define a type for elements that should be updated on zoomexport type ZoomableElement = {- selector: string;- updateFn: (selection: d3.Selection<any, any, any, any>, transform: d3.ZoomTransform) => void;+ selector: string;+ updateFn: (selection: d3.Selection<any, any, any, any>, transform: d3.ZoomTransform) => void;}type BaseChartViewProps = {- title?: string- renderChart: (params: {- svg: d3.Selection<SVGGElement, unknown, null, undefined>- chartArea: d3.Selection<SVGGElement, unknown, null, undefined>- width: number- height: number- margin: ChartMargins- transform: d3.ZoomTransform- }) => void- margin?: ChartMargins+ title?: string+ renderChart: (params: {+ svg: d3.Selection<SVGGElement, unknown, null, undefined>+ chartArea: d3.Selection<SVGGElement, unknown, null, undefined>+ width: number+ height: number+ margin: ChartMargins+ transform: d3.ZoomTransform+ }) => void+ margin?: ChartMargins}export default function BaseD3ChartView({- title,- renderChart,- margin = { top: 20, right: 100, bottom: 30, left: 60 }-}: BaseChartViewProps) {- const svgRef = useRef<SVGSVGElement>(null)- const chartRef = useRef<{- cleanup?: () => void- }>({})- const [transform, setTransform] = useState<d3.ZoomTransform>(d3.zoomIdentity)- const zoomRef = useRef<d3.ZoomBehavior<SVGSVGElement, unknown> | null>(null)- const [showControls, setShowControls] = useState(false)-- useEffect(() => {- if (!svgRef.current) return-- // Clear previous chart- d3.select(svgRef.current).selectAll("*").remove()-- // Set up dimensions- let width = svgRef.current.clientWidth - margin.left - margin.right- let height = svgRef.current.clientHeight - margin.top - margin.bottom- if (width <0) {width = 0}- if (height <0) {height = 0}- // Create SVG with a clip path for zooming- const svg = d3.select(svgRef.current)- .append("g")- .attr("transform", `translate(${margin.left},${margin.top})`)-- // Add clip path to prevent drawing outside the chart area- svg- .append("defs")- .append("clipPath")- .attr("id", "clip-chart")- .append("rect")- .attr("width", width)- .attr("height", height)-- // Create a group for the chart content that will be clipped- const chartArea = svg.append("g").attr("clip-path", "url(#clip-chart)")-- // Call the render function provided by the child component- const cleanup = renderChart({ svg, chartArea, width, height, margin, transform })-- // Store cleanup function if one is returned- if (typeof cleanup === 'function') {- chartRef.current.cleanup = cleanup+ title,+ renderChart,+ margin = {top: 20, right: 100, bottom: 30, left: 60}+ }: BaseChartViewProps) {+ const svgRef = useRef<SVGSVGElement>(null)+ const chartRef = useRef<{+ cleanup?: () => void+ }>({})+ const [transform, setTransform] = useState<d3.ZoomTransform>(d3.zoomIdentity)+ const zoomRef = useRef<d3.ZoomBehavior<SVGSVGElement, unknown> | null>(null)+ const [showControls, setShowControls] = useState(false)++ useEffect(() => {+ if (!svgRef.current) return++ // Clear previous chart+ d3.select(svgRef.current).selectAll("*").remove()++ // Set up dimensions+ let width = svgRef.current.clientWidth - margin.left - margin.right+ let height = svgRef.current.clientHeight - margin.top - margin.bottom+ if (width < 0) {+ width = 0+ }+ if (height < 0) {+ height = 0+ }+ // Create SVG with a clip path for zooming+ const svg = d3.select(svgRef.current)+ .append("g")+ .attr("transform", `translate(${margin.left},${margin.top})`)++ // Add clip path to prevent drawing outside the chart area+ svg+ .append("defs")+ .append("clipPath")+ .attr("id", "clip-chart")+ .append("rect")+ .attr("width", width)+ .attr("height", height)++ // Create a group for the chart content that will be clipped+ const chartArea = svg.append("g").attr("clip-path", "url(#clip-chart)")++ // Call the render function provided by the child component+ const cleanup = renderChart({svg, chartArea, width, height, margin, transform})++ // Store cleanup function if one is returned+ if (typeof cleanup === 'function') {+ chartRef.current.cleanup = cleanup+ }++ // Define zoom behavior+ const zoom = d3+ .zoom<SVGSVGElement, unknown>()+ .scaleExtent([0.5, 20])+ .extent([+ [0, 0],+ [width, height],+ ])+ .on("zoom", (event) => {+ // Update the transform state+ setTransform(event.transform)+ })++ // Store zoom reference for external controls+ zoomRef.current = zoom++ // Apply zoom to the SVG+ d3.select(svgRef.current).call(zoom)++ // Cleanup function+ return () => {+ if (chartRef.current.cleanup) {+ chartRef.current.cleanup()+ }+ }+ }, [renderChart, margin, transform])++ // Zoom control handlers+ const handleZoomIn = () => {+ if (svgRef.current && zoomRef.current) {+ d3.select(svgRef.current).transition().duration(300).call(zoomRef.current.scaleBy, 1.5)+ }}- // Define zoom behavior- const zoom = d3- .zoom<SVGSVGElement, unknown>()- .scaleExtent([0.5, 20])- .extent([- [0, 0],- [width, height],- ])- .on("zoom", (event) => {- // Update the transform state- setTransform(event.transform)- })-- // Store zoom reference for external controls- zoomRef.current = zoom-- // Apply zoom to the SVG- d3.select(svgRef.current).call(zoom)-- // Cleanup function- return () => {- if (chartRef.current.cleanup) {- chartRef.current.cleanup()- }+ const handleZoomOut = () => {+ if (svgRef.current && zoomRef.current) {+ d3.select(svgRef.current).transition().duration(300).call(zoomRef.current.scaleBy, 0.75)+ }}- }, [renderChart, margin, transform])- // Zoom control handlers- const handleZoomIn = () => {- if (svgRef.current && zoomRef.current) {- d3.select(svgRef.current).transition().duration(300).call(zoomRef.current.scaleBy, 1.5)+ const handleResetZoom = () => {+ if (svgRef.current && zoomRef.current) {+ d3.select(svgRef.current).transition().duration(300).call(zoomRef.current.transform, d3.zoomIdentity)+ }}- }- const handleZoomOut = () => {- if (svgRef.current && zoomRef.current) {- d3.select(svgRef.current).transition().duration(300).call(zoomRef.current.scaleBy, 0.75)- }- }-- const handleResetZoom = () => {- if (svgRef.current && zoomRef.current) {- d3.select(svgRef.current).transition().duration(300).call(zoomRef.current.transform, d3.zoomIdentity)- }- }-- return (- <Box- sx={{- width: "100%",- height: "100%",- position: "relative",- overflow: "hidden"- }}- onMouseEnter={() => setShowControls(true)}- onMouseLeave={() => setShowControls(false)}- >- {title && (- <Typography- variant="caption"- sx={{- position: "absolute",- top: 5,- left: 10,- fontSize: '0.7rem',- opacity: 0.8- }}- >- {title}- </Typography>- )}-- {/* Zoom controls that fade in/out on hover */}- <Fade in={showControls}>+ return (<Box- sx={{- position: "absolute",- top: "50%",- right: 5,- transform: "translateY(-50%)",- zIndex: 10,- bgcolor: "background.paper",- borderRadius: 1,- boxShadow: 1,- display: "flex",- flexDirection: "column",- }}+ sx={{+ width: "100%",+ height: "100%",+ position: "relative",+ overflow: "hidden"+ }}+ onMouseEnter={() => setShowControls(true)}+ onMouseLeave={() => setShowControls(false)}>- <Tooltip title="Zoom In" placement="right">- <IconButton size="small" onClick={handleZoomIn} sx={{ p: 0.5 }}>- <ZoomIn fontSize="small" />- </IconButton>- </Tooltip>- <Tooltip title="Zoom Out" placement="right">- <IconButton size="small" onClick={handleZoomOut} sx={{ p: 0.5 }}>- <ZoomOut fontSize="small" />- </IconButton>- </Tooltip>- <Tooltip title="Reset Zoom" placement="right">- <IconButton size="small" onClick={handleResetZoom} sx={{ p: 0.5 }}>- <RestartAlt fontSize="small" />- </IconButton>- </Tooltip>+ {title && (+ <Typography+ variant="caption"+ sx={{+ position: "absolute",+ top: 5,+ left: 10,+ fontSize: '0.7rem',+ opacity: 0.8+ }}+ >+ {title}+ </Typography>+ )}++ {/* Zoom controls that fade in/out on hover */}+ <Fade in={showControls}>+ <Box+ sx={{+ position: "absolute",+ top: "50%",+ right: 5,+ transform: "translateY(-50%)",+ zIndex: 10,+ bgcolor: "background.paper",+ borderRadius: 1,+ boxShadow: 1,+ display: "flex",+ flexDirection: "column",+ }}+ >+ <Tooltip title="Zoom In" placement="right">+ <IconButton size="small" onClick={handleZoomIn} sx={{p: 0.5}}>+ <ZoomIn fontSize="small"/>+ </IconButton>+ </Tooltip>+ <Tooltip title="Zoom Out" placement="right">+ <IconButton size="small" onClick={handleZoomOut} sx={{p: 0.5}}>+ <ZoomOut fontSize="small"/>+ </IconButton>+ </Tooltip>+ <Tooltip title="Reset Zoom" placement="right">+ <IconButton size="small" onClick={handleResetZoom} sx={{p: 0.5}}>+ <RestartAlt fontSize="small"/>+ </IconButton>+ </Tooltip>+ </Box>+ </Fade>++ <svg+ ref={svgRef}+ width="100%"+ height="100%"+ style={{+ display: 'block',+ overflow: "visible"+ }}+ /></Box>- </Fade>-- <svg- ref={svgRef}- width="100%"- height="100%"- style={{- display: 'block',- overflow: "visible"- }}- />- </Box>- )+ )}diff --git a/freemocap-ui/src/components/framerate-viewer/FrameRateViewer.tsx b/freemocap-ui/src/components/framerate-viewer/FrameRateViewer.tsxindex 3597080c..d607e734 100644--- a/freemocap-ui/src/components/framerate-viewer/FrameRateViewer.tsx+++ b/freemocap-ui/src/components/framerate-viewer/FrameRateViewer.tsx@@ -6,161 +6,163 @@ import {alpha, useTheme} from "@mui/material/styles"import FramerateTimeseriesView from "./FramerateTimeseriesView"import FramerateHistogramView from "./FramerateHistogramView"import FramerateStatisticsView from "./FramerateStatisticsView"-import {useAppSelector} from "@/store/AppStateStore";+import {selectFramerateViewerData, useAppSelector} from "@/store";type ViewType = "timeseries" | "histogram" | "both"export const frontendColor: string = "#1976D2"export const backendColor: string = "#ff4d00"export const FramerateViewerPanel = () => {- const theme = useTheme()- const [viewType, setViewType] = useState<ViewType>("both")+ const theme = useTheme()+ const [viewType, setViewType] = useState<ViewType>("both")- const {- currentFrontendFramerate,- currentBackendFramerate,- recentFrontendFrameDurations,- recentBackendFrameDurations- } = useAppSelector((state) => state.framerateTracker);- return (- <Box sx={{- height: '100%',- display: 'flex',- flexDirection: 'column',- backgroundColor: theme.palette.background.default,- p: 0.5,- overflow: 'hidden' // Prevent content overflow- }}>- {/* Ultra-compact header with controls */}- <Box sx={{- display: 'flex',- justifyContent: 'space-between',- alignItems: 'center',- mb: 0.25,- px: 0.5- }}>- <Typography variant="body2" fontWeight="medium" noWrap sx={{ fontSize: '0.75rem' }}>- Camera Performance Metrics- </Typography>+ // Use the new selector to get all framerate data+ const {+ currentFrontendFramerate,+ currentBackendFramerate,+ recentFrontendFrameDurations,+ recentBackendFrameDurations+ } = useAppSelector(selectFramerateViewerData);- {/* View type selector as icon buttons */}- <Stack direction="row" spacing={0.25}>- <Tooltip title="Timeline View">- <IconButton- size="small"- onClick={() => setViewType("timeseries")}- color={viewType === "timeseries" ? "primary" : "default"}- sx={{ padding: '2px' }}- >- <ShowChart sx={{ fontSize: '1rem' }} />- </IconButton>- </Tooltip>- <Tooltip title="Distribution View">- <IconButton- size="small"- onClick={() => setViewType("histogram")}- color={viewType === "histogram" ? "primary" : "default"}- sx={{ padding: '2px' }}- >- <BarChart sx={{ fontSize: '1rem' }} />- </IconButton>- </Tooltip>- <Tooltip title="Combined View">- <IconButton- size="small"- onClick={() => setViewType("both")}- color={viewType === "both" ? "primary" : "default"}- sx={{ padding: '2px' }}- >- {theme.direction === 'ltr' ? (- <ViewDay sx={{ fontSize: '1rem' }} />- ) : (- <ViewCompact sx={{ fontSize: '1rem' }} />- )}- </IconButton>- </Tooltip>- </Stack>- </Box>+ return (+ <Box sx={{+ height: '100%',+ display: 'flex',+ flexDirection: 'column',+ backgroundColor: theme.palette.background.default,+ p: 0.5,+ overflow: 'hidden' // Prevent content overflow+ }}>+ {/* Ultra-compact header with controls */}+ <Box sx={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ mb: 0.25,+ px: 0.5+ }}>+ <Typography variant="body2" fontWeight="medium" noWrap sx={{fontSize: '0.75rem'}}>+ Camera Performance Metrics+ </Typography>- {/* Stats section - ultra compact */}- <Box sx={{- px: 0.25,- mb: 0.25,- }}>- <Paper- elevation={0}- sx={{- p: 0.25,- bgcolor: alpha(theme.palette.background.paper, theme.palette.mode === 'dark' ? 0.15 : 0.05),- border: `1px solid ${alpha(theme.palette.divider, 0.1)}`- }}- >- <FramerateStatisticsView- frontendFramerate={currentFrontendFramerate}- backendFramerate={currentBackendFramerate}- compact={true}- />- </Paper>- </Box>+ {/* View type selector as icon buttons */}+ <Stack direction="row" spacing={0.25}>+ <Tooltip title="Timeline View">+ <IconButton+ size="small"+ onClick={() => setViewType("timeseries")}+ color={viewType === "timeseries" ? "primary" : "default"}+ sx={{padding: '2px'}}+ >+ <ShowChart sx={{fontSize: '1rem'}}/>+ </IconButton>+ </Tooltip>+ <Tooltip title="Distribution View">+ <IconButton+ size="small"+ onClick={() => setViewType("histogram")}+ color={viewType === "histogram" ? "primary" : "default"}+ sx={{padding: '2px'}}+ >+ <BarChart sx={{fontSize: '1rem'}}/>+ </IconButton>+ </Tooltip>+ <Tooltip title="Combined View">+ <IconButton+ size="small"+ onClick={() => setViewType("both")}+ color={viewType === "both" ? "primary" : "default"}+ sx={{padding: '2px'}}+ >+ {theme.direction === 'ltr' ? (+ <ViewDay sx={{fontSize: '1rem'}}/>+ ) : (+ <ViewCompact sx={{fontSize: '1rem'}}/>+ )}+ </IconButton>+ </Tooltip>+ </Stack>+ </Box>- {/* Main visualization area with flex-based layout */}- <Box sx={{- flex: 1,- display: 'flex',- flexDirection: viewType === 'both' ? 'row' : 'column',- gap: 0.25,- overflow: 'hidden' // Critical to prevent overflow- }}>- {(viewType === 'timeseries' || viewType === 'both') && (- <Paper- elevation={0}- sx={{- flex: 1,- display: 'flex',- flexDirection: 'column',- border: '1px solid',- borderColor: alpha(theme.palette.divider, 0.2),- overflow: 'hidden' // Ensure chart doesn't overflow- }}- >- <FramerateTimeseriesView- frontendFramerate={currentFrontendFramerate}- backendFramerate={currentBackendFramerate}- recentFrontendFrameDurations={recentFrontendFrameDurations}- recentBackendFrameDurations={recentBackendFrameDurations}- frontendColor={frontendColor}- backendColor={backendColor}- title="Frame Duration Timeline"- />- </Paper>- )}+ {/* Stats section - ultra compact */}+ <Box sx={{+ px: 0.25,+ mb: 0.25,+ }}>+ <Paper+ elevation={0}+ sx={{+ p: 0.25,+ bgcolor: alpha(theme.palette.background.paper, theme.palette.mode === 'dark' ? 0.15 : 0.05),+ border: `1px solid ${alpha(theme.palette.divider, 0.1)}`+ }}+ >+ <FramerateStatisticsView+ frontendFramerate={currentFrontendFramerate}+ backendFramerate={currentBackendFramerate}+ compact={true}+ />+ </Paper>+ </Box>- {(viewType === 'histogram' || viewType === 'both') && (- <Paper- elevation={0}- sx={{- flex: 1,- display: 'flex',- flexDirection: 'column',- border: '1px solid',- borderColor: alpha(theme.palette.divider, 0.2),- overflow: 'hidden' // Ensure chart doesn't overflow- }}- >- <FramerateHistogramView- frontendFramerate={currentFrontendFramerate}- backendFramerate={currentBackendFramerate}- recentFrontendFrameDurations={recentFrontendFrameDurations}- recentBackendFrameDurations={recentBackendFrameDurations}- frontendColor={frontendColor}- backendColor={backendColor}- title="Frame Duration Distribution"- />- </Paper>- )}- </Box>- </Box>- )+ {/* Main visualization area with flex-based layout */}+ <Box sx={{+ flex: 1,+ display: 'flex',+ flexDirection: viewType === 'both' ? 'row' : 'column',+ gap: 0.25,+ overflow: 'hidden' // Critical to prevent overflow+ }}>+ {(viewType === 'timeseries' || viewType === 'both') && (+ <Paper+ elevation={0}+ sx={{+ flex: 1,+ display: 'flex',+ flexDirection: 'column',+ border: '1px solid',+ borderColor: alpha(theme.palette.divider, 0.2),+ overflow: 'hidden' // Ensure chart doesn't overflow+ }}+ >+ <FramerateTimeseriesView+ frontendFramerate={currentFrontendFramerate}+ backendFramerate={currentBackendFramerate}+ recentFrontendFrameDurations={recentFrontendFrameDurations}+ recentBackendFrameDurations={recentBackendFrameDurations}+ frontendColor={frontendColor}+ backendColor={backendColor}+ title="Frame Duration Timeline"+ />+ </Paper>+ )}++ {(viewType === 'histogram' || viewType === 'both') && (+ <Paper+ elevation={0}+ sx={{+ flex: 1,+ display: 'flex',+ flexDirection: 'column',+ border: '1px solid',+ borderColor: alpha(theme.palette.divider, 0.2),+ overflow: 'hidden' // Ensure chart doesn't overflow+ }}+ >+ <FramerateHistogramView+ frontendFramerate={currentFrontendFramerate}+ backendFramerate={currentBackendFramerate}+ recentFrontendFrameDurations={recentFrontendFrameDurations}+ recentBackendFrameDurations={recentBackendFrameDurations}+ frontendColor={frontendColor}+ backendColor={backendColor}+ title="Frame Duration Distribution"+ />+ </Paper>+ )}+ </Box>+ </Box>+ )}export default FramerateViewerPaneldiff --git a/freemocap-ui/src/components/framerate-viewer/FramerateHistogramView.tsx b/freemocap-ui/src/components/framerate-viewer/FramerateHistogramView.tsxindex a62cf6c1..38c485ce 100644--- a/freemocap-ui/src/components/framerate-viewer/FramerateHistogramView.tsx+++ b/freemocap-ui/src/components/framerate-viewer/FramerateHistogramView.tsx@@ -2,256 +2,256 @@import {useCallback} from "react"import * as d3 from "d3"import {useTheme} from "@mui/material/styles"-import {applyAxisStyles, createTooltip, renderEmptyChart, renderThresholdLines} from "./d3ChartUtils"-import {CurrentFramerate} from "@/store/slices/framerateTrackerSlice";+import {applyAxisStyles, createTooltip, renderEmptyChart} from "./d3ChartUtils"+import {CurrentFramerate} from "@/store/slices/framerate/framerate-slice";import BaseD3ChartView from "@/components/framerate-viewer/BaseD3ChartView";type FramerateHistogramProps = {- frontendFramerate: CurrentFramerate | null- backendFramerate: CurrentFramerate | null- recentFrontendFrameDurations: number[]- recentBackendFrameDurations: number[]- frontendColor: string- backendColor: string- title?: string+ frontendFramerate: CurrentFramerate | null+ backendFramerate: CurrentFramerate | null+ recentFrontendFrameDurations: number[]+ recentBackendFrameDurations: number[]+ frontendColor: string+ backendColor: string+ title?: string}export default function FramerateHistogramView({- frontendFramerate,- backendFramerate,- recentFrontendFrameDurations,- recentBackendFrameDurations,- frontendColor,- backendColor,- title = "Frame Duration Distribution",-}: FramerateHistogramProps) {- const theme = useTheme()-- // Generate histogram data- const generateHistogram = (data: number[], binCount = 100) => {- if (data.length === 0) return null;-- // Calculate bins using d3's histogram generator- const histGenerator = d3.histogram()- .domain([0, d3.max(data) as number * 1.1]) // Add 10% padding to max- .thresholds(binCount);-- const bins = histGenerator(data);-- // Calculate densities (normalized counts)- const totalCount = data.length;- const binCounts = bins.map(bin => bin.length);- const binDensities = binCounts.map(count => count / totalCount);-- return {- bin_edges: bins.map(bin => bin.x0 as number),- bin_counts: binCounts,- bin_densities: binDensities+ frontendFramerate,+ backendFramerate,+ recentFrontendFrameDurations,+ recentBackendFrameDurations,+ frontendColor,+ backendColor,+ title = "Frame Duration Distribution",+ }: FramerateHistogramProps) {+ const theme = useTheme()++ // Generate histogram data+ const generateHistogram = (data: number[], binCount = 100) => {+ if (data.length === 0) return null;++ // Calculate bins using d3's histogram generator+ const histGenerator = d3.histogram()+ .domain([0, d3.max(data) as number * 1.1]) // Add 10% padding to max+ .thresholds(binCount);++ const bins = histGenerator(data);++ // Calculate densities (normalized counts)+ const totalCount = data.length;+ const binCounts = bins.map(bin => bin.length);+ const binDensities = binCounts.map(count => count / totalCount);++ return {+ bin_edges: bins.map(bin => bin.x0 as number),+ bin_counts: binCounts,+ bin_densities: binDensities+ };};- };-- const renderChart = useCallback(({- svg,- chartArea,- width,- height,- margin,- transform- }: {- svg: d3.Selection<SVGGElement, unknown, null, undefined>;- chartArea: d3.Selection<SVGGElement, unknown, null, undefined>;- width: number;- height: number;- margin: {top: number; right: number; bottom: number; left: number};- transform: d3.ZoomTransform;- }) => {- // Prepare the sources with histogram data- const sources = [- {- id: 'frontend',- name: frontendFramerate?.framerate_source || 'Frontend',- color: frontendColor,- histogram: generateHistogram(recentFrontendFrameDurations),- totalSamples: recentFrontendFrameDurations.length- },- {- id: 'backend',- name: backendFramerate?.framerate_source || 'Backend',- color: backendColor,- histogram: generateHistogram(recentBackendFrameDurations),- totalSamples: recentBackendFrameDurations.length- }- ];-- // Check if we have valid histogram data- if (sources.every(s => !s.histogram)) {- renderEmptyChart(svg, width, height, theme);- return;- }-- // Find domain bounds from all histograms- let minX = Infinity;- let maxX = -Infinity;- let maxDensity = 0;-- sources.forEach(source => {- if (source.histogram) {- const edges = source.histogram.bin_edges;- const densities = source.histogram.bin_densities;-- if (edges.length > 0) {- minX = Math.min(minX, edges[0]);- maxX = Math.max(maxX, edges[edges.length - 1]);- }- if (densities.length > 0) {- maxDensity = Math.max(maxDensity, Math.max(...densities));+ const renderChart = useCallback(({+ svg,+ chartArea,+ width,+ height,+ margin,+ transform+ }: {+ svg: d3.Selection<SVGGElement, unknown, null, undefined>;+ chartArea: d3.Selection<SVGGElement, unknown, null, undefined>;+ width: number;+ height: number;+ margin: { top: number; right: number; bottom: number; left: number };+ transform: d3.ZoomTransform;+ }) => {+ // Prepare the sources with histogram data+ const sources = [+ {+ id: 'frontend',+ name: frontendFramerate?.framerate_source || 'Frontend',+ color: frontendColor,+ histogram: generateHistogram(recentFrontendFrameDurations),+ totalSamples: recentFrontendFrameDurations.length+ },+ {+ id: 'backend',+ name: backendFramerate?.framerate_source || 'Backend',+ color: backendColor,+ histogram: generateHistogram(recentBackendFrameDurations),+ totalSamples: recentBackendFrameDurations.length+ }+ ];++ // Check if we have valid histogram data+ if (sources.every(s => !s.histogram)) {+ renderEmptyChart(svg, width, height, theme);+ return;}- }- });-- // If we couldn't determine bounds, use defaults- if (minX === Infinity) minX = 0;- if (maxX === -Infinity) maxX = 100;- if (maxDensity === 0) maxDensity = 1;-- // Add padding to domain- const xPadding = (maxX - minX) * 0.1;- const xDomain = [Math.max(0, minX - xPadding), maxX + xPadding];-- // Set up scales- const xScale = d3.scaleLinear().domain(xDomain).range([0, width]);- const yScale = d3.scaleLinear().domain([0, maxDensity * 1.1]).range([height, 0]);-- // Apply the current zoom transform- const xScaleZoomed = d3.scaleLinear()- .domain([Math.max(0, transform.rescaleX(xScale).domain()[0]), transform.rescaleX(xScale).domain()[1]])- .range([0, width]);-- const yScaleZoomed = d3.scaleLinear()- .domain([Math.max(0, transform.rescaleY(yScale).domain()[0]), transform.rescaleY(yScale).domain()[1]])- .range([height, 0]);- // Create axes- const xAxis = d3.axisBottom(xScaleZoomed).ticks(10).tickSize(-height);- const yAxis = d3.axisLeft(yScaleZoomed).ticks(5).tickSize(-width);-- // Add X axis with label- const xAxisGroup = svg- .append("g")- .attr("class", "x-axis")- .attr("transform", `translate(0,${height})`)- .call(xAxis);-- svg- .append("text")- .attr("transform", `translate(${width / 2}, ${height + margin.bottom - 5})`)- .style("text-anchor", "middle")- .style("font-family", "monospace")- .style("font-size", "10px")- .style("fill", theme.palette.text.secondary)- .text("Frame Duration (ms)");-- // Add Y axis with label- const yAxisGroup = svg- .append("g")- .attr("class", "y-axis")- .call(yAxis);-- svg- .append("text")- .attr("transform", "rotate(-90)")- .attr("y", 0 - margin.left)- .attr("x", 0 - height / 2)- .attr("dy", "1em")- .style("text-anchor", "middle")- .style("font-family", "monospace")- .style("font-size", "10px")- .style("fill", theme.palette.text.secondary)- .text("Density");-- // Style axes- applyAxisStyles(svg, theme);-- // Add threshold lines- // const thresholds = [- // { value: 16.67, label: "60 FPS", color: theme.palette.success.main },- // { value: 33.33, label: "30 FPS", color: theme.palette.warning.main },- // ];- //- // renderThresholdLines(chartArea, thresholds, xScaleZoomed, yScaleZoomed, width, height, false);-- // Draw histograms- sources.forEach(source => {- if (!source.histogram || source.histogram.bin_edges.length === 0) return;-- const bins = source.histogram.bin_edges.map((edge, i) => ({- x0: edge,- x1: i < source.histogram!.bin_edges.length - 1 ? source.histogram!.bin_edges[i + 1] : edge + 0.1,- density: i < source.histogram!.bin_densities.length ? source.histogram!.bin_densities[i] : 0,- count: i < source.histogram!.bin_counts.length ? source.histogram!.bin_counts[i] : 0- }));-- // Add histogram bars- chartArea- .selectAll(`.bar-${source.id}`)- .data(bins)- .enter()- .append("rect")- .attr("class", `bar-${source.id}`)- .attr("x", d => xScaleZoomed(d.x0))- .attr("width", d => Math.max(0, xScaleZoomed(d.x1) - xScaleZoomed(d.x0) - 1))- .attr("y", d => {- const y = yScaleZoomed(d.density);- // Ensure y is valid and not greater than height- return isNaN(y) ? height : Math.min(height, Math.max(0, y));- })- .attr("height", d => {- const y = yScaleZoomed(d.density);- // Calculate height ensuring it's always positive- if (isNaN(y)) return 0;- const barHeight = height - Math.min(height, Math.max(0, y));- return Math.max(0, barHeight);- })- .attr("fill", source.color)- .attr("stroke", theme.palette.background.paper)- .attr("stroke-width", 0.5)- .attr("opacity", 0.7);- });-- // Add legend- const legend = svg- .append("g")- .attr("transform", `translate(${width + 10}, 0)`)- .attr("font-family", "monospace")- .attr("font-size", "10px");-- sources.forEach((source, i) => {- if (!source.histogram) return;-- const legendItem = legend.append("g").attr("transform", `translate(0, ${i * 20})`);- legendItem.append("rect").attr("width", 12).attr("height", 12).attr("fill", source.color);- legendItem.append("text")- .attr("x", 20)- .attr("y", 10)- .style("fill", theme.palette.text.primary)- .text(`${source.name} (${source.totalSamples})`);- });-- // Add tooltip- const tooltip = createTooltip(theme);-- // Add tooltip for histogram bars- sources.forEach(source => {- if (!source.histogram) return;-- chartArea- .selectAll(`.bar-${source.id}`)- .on("mouseover", function (event, d: any) {- d3.select(this).attr("opacity", 1).attr("stroke-width", 1);-- tooltip- .style("opacity", 1)- .html(`++ // Find domain bounds from all histograms+ let minX = Infinity;+ let maxX = -Infinity;+ let maxDensity = 0;++ sources.forEach(source => {+ if (source.histogram) {+ const edges = source.histogram.bin_edges;+ const densities = source.histogram.bin_densities;++ if (edges.length > 0) {+ minX = Math.min(minX, edges[0]);+ maxX = Math.max(maxX, edges[edges.length - 1]);+ }++ if (densities.length > 0) {+ maxDensity = Math.max(maxDensity, Math.max(...densities));+ }+ }+ });++ // If we couldn't determine bounds, use defaults+ if (minX === Infinity) minX = 0;+ if (maxX === -Infinity) maxX = 100;+ if (maxDensity === 0) maxDensity = 1;++ // Add padding to domain+ const xPadding = (maxX - minX) * 0.1;+ const xDomain = [Math.max(0, minX - xPadding), maxX + xPadding];++ // Set up scales+ const xScale = d3.scaleLinear().domain(xDomain).range([0, width]);+ const yScale = d3.scaleLinear().domain([0, maxDensity * 1.1]).range([height, 0]);++ // Apply the current zoom transform+ const xScaleZoomed = d3.scaleLinear()+ .domain([Math.max(0, transform.rescaleX(xScale).domain()[0]), transform.rescaleX(xScale).domain()[1]])+ .range([0, width]);++ const yScaleZoomed = d3.scaleLinear()+ .domain([Math.max(0, transform.rescaleY(yScale).domain()[0]), transform.rescaleY(yScale).domain()[1]])+ .range([height, 0]);+ // Create axes+ const xAxis = d3.axisBottom(xScaleZoomed).ticks(10).tickSize(-height);+ const yAxis = d3.axisLeft(yScaleZoomed).ticks(5).tickSize(-width);++ // Add X axis with label+ const xAxisGroup = svg+ .append("g")+ .attr("class", "x-axis")+ .attr("transform", `translate(0,${height})`)+ .call(xAxis);++ svg+ .append("text")+ .attr("transform", `translate(${width / 2}, ${height + margin.bottom - 5})`)+ .style("text-anchor", "middle")+ .style("font-family", "monospace")+ .style("font-size", "10px")+ .style("fill", theme.palette.text.secondary)+ .text("Frame Duration (ms)");++ // Add Y axis with label+ const yAxisGroup = svg+ .append("g")+ .attr("class", "y-axis")+ .call(yAxis);++ svg+ .append("text")+ .attr("transform", "rotate(-90)")+ .attr("y", 0 - margin.left)+ .attr("x", 0 - height / 2)+ .attr("dy", "1em")+ .style("text-anchor", "middle")+ .style("font-family", "monospace")+ .style("font-size", "10px")+ .style("fill", theme.palette.text.secondary)+ .text("Density");++ // Style axes+ applyAxisStyles(svg, theme);++ // Add threshold lines+ // const thresholds = [+ // { value: 16.67, label: "60 FPS", color: theme.palette.success.main },+ // { value: 33.33, label: "30 FPS", color: theme.palette.warning.main },+ // ];+ //+ // renderThresholdLines(chartArea, thresholds, xScaleZoomed, yScaleZoomed, width, height, false);++ // Draw histograms+ sources.forEach(source => {+ if (!source.histogram || source.histogram.bin_edges.length === 0) return;++ const bins = source.histogram.bin_edges.map((edge, i) => ({+ x0: edge,+ x1: i < source.histogram!.bin_edges.length - 1 ? source.histogram!.bin_edges[i + 1] : edge + 0.1,+ density: i < source.histogram!.bin_densities.length ? source.histogram!.bin_densities[i] : 0,+ count: i < source.histogram!.bin_counts.length ? source.histogram!.bin_counts[i] : 0+ }));++ // Add histogram bars+ chartArea+ .selectAll(`.bar-${source.id}`)+ .data(bins)+ .enter()+ .append("rect")+ .attr("class", `bar-${source.id}`)+ .attr("x", d => xScaleZoomed(d.x0))+ .attr("width", d => Math.max(0, xScaleZoomed(d.x1) - xScaleZoomed(d.x0) - 1))+ .attr("y", d => {+ const y = yScaleZoomed(d.density);+ // Ensure y is valid and not greater than height+ return isNaN(y) ? height : Math.min(height, Math.max(0, y));+ })+ .attr("height", d => {+ const y = yScaleZoomed(d.density);+ // Calculate height ensuring it's always positive+ if (isNaN(y)) return 0;+ const barHeight = height - Math.min(height, Math.max(0, y));+ return Math.max(0, barHeight);+ })+ .attr("fill", source.color)+ .attr("stroke", theme.palette.background.paper)+ .attr("stroke-width", 0.5)+ .attr("opacity", 0.7);+ });++ // Add legend+ const legend = svg+ .append("g")+ .attr("transform", `translate(${width + 10}, 0)`)+ .attr("font-family", "monospace")+ .attr("font-size", "10px");++ sources.forEach((source, i) => {+ if (!source.histogram) return;++ const legendItem = legend.append("g").attr("transform", `translate(0, ${i * 20})`);+ legendItem.append("rect").attr("width", 12).attr("height", 12).attr("fill", source.color);+ legendItem.append("text")+ .attr("x", 20)+ .attr("y", 10)+ .style("fill", theme.palette.text.primary)+ .text(`${source.name} (${source.totalSamples})`);+ });++ // Add tooltip+ const tooltip = createTooltip(theme);++ // Add tooltip for histogram bars+ sources.forEach(source => {+ if (!source.histogram) return;++ chartArea+ .selectAll(`.bar-${source.id}`)+ .on("mouseover", function (event, d: any) {+ d3.select(this).attr("opacity", 1).attr("stroke-width", 1);++ tooltip+ .style("opacity", 1)+ .html(`<div style="display: grid; grid-template-columns: auto auto; gap: 4px;"><span style="color: ${theme.palette.text.secondary};">SOURCE:</span><span style="color: ${source.color};">${source.name}</span>@@ -265,30 +265,30 @@ export default function FramerateHistogramView({<span>${(1000 / d.x1).toFixed(1)} - ${(1000 / d.x0).toFixed(1)} fps</span></div>`)- .style("left", event.pageX + 10 + "px")- .style("top", event.pageY - 28 + "px");- })- .on("mouseout", function () {- d3.select(this).attr("opacity", 0.7).attr("stroke-width", 0.5);- tooltip.style("opacity", 0);+ .style("left", event.pageX + 10 + "px")+ .style("top", event.pageY - 28 + "px");+ })+ .on("mouseout", function () {+ d3.select(this).attr("opacity", 0.7).attr("stroke-width", 0.5);+ tooltip.style("opacity", 0);+ });});- });-- return () => tooltip.remove();- }, [- frontendFramerate,- backendFramerate,- recentFrontendFrameDurations,- recentBackendFrameDurations,- frontendColor,- backendColor,- theme- ]);-- return (- <BaseD3ChartView- title={title}- renderChart={renderChart}- />- );++ return () => tooltip.remove();+ }, [+ frontendFramerate,+ backendFramerate,+ recentFrontendFrameDurations,+ recentBackendFrameDurations,+ frontendColor,+ backendColor,+ theme+ ]);++ return (+ <BaseD3ChartView+ title={title}+ renderChart={renderChart}+ />+ );}diff --git a/freemocap-ui/src/components/framerate-viewer/FramerateStatisticsView.tsx b/freemocap-ui/src/components/framerate-viewer/FramerateStatisticsView.tsxindex a51609da..d02a685f 100644--- a/freemocap-ui/src/components/framerate-viewer/FramerateStatisticsView.tsx+++ b/freemocap-ui/src/components/framerate-viewer/FramerateStatisticsView.tsx@@ -1,495 +1,495 @@// src/components/framerate-viewer/FramerateStatisticsView.tsximport {- Box,- Divider,- Paper,- Table,- TableBody,- TableCell,- TableContainer,- TableHead,- TableRow,- Tooltip,- Typography,+ Box,+ Divider,+ Paper,+ Table,+ TableBody,+ TableCell,+ TableContainer,+ TableHead,+ TableRow,+ Tooltip,+ Typography,} from "@mui/material";-import { alpha, useTheme } from "@mui/material/styles";-import { CurrentFramerate } from "@/store/slices/framerateTrackerSlice";-import { useState } from "react";+import {alpha, useTheme} from "@mui/material/styles";+import {CurrentFramerate} from "@/store/slices/framerate/framerate-slice";+import {useState} from "react";type FramerateStatisticsViewProps = {- frontendFramerate: CurrentFramerate | null;- backendFramerate: CurrentFramerate | null;- compact?: boolean;+ frontendFramerate: CurrentFramerate | null;+ backendFramerate: CurrentFramerate | null;+ compact?: boolean;};// Format number with fixed precisionconst formatNumber = (num: number | null, precision = 3) => {- return num !== null ? num.toFixed(precision) : "N/A";+ return num !== null ? num.toFixed(precision) : "N/A";};type ProgressiveTooltipProps = {- shortInfo: string;- longInfo: string;- children: React.ReactElement;+ shortInfo: string;+ longInfo: string;+ children: React.ReactElement;};// Progressive tooltip component that shows more info on clickexport const ProgressiveTooltip = ({- shortInfo,- longInfo,- children,-}: ProgressiveTooltipProps) => {- const [isExpanded, setIsExpanded] = useState(false);- const theme = useTheme();+ shortInfo,+ longInfo,+ children,+ }: ProgressiveTooltipProps) => {+ const [isExpanded, setIsExpanded] = useState(false);+ const theme = useTheme();- const handleTooltipClick = (e: React.MouseEvent) => {- e.preventDefault();- setIsExpanded(!isExpanded);- };+ const handleTooltipClick = (e: React.MouseEvent) => {+ e.preventDefault();+ setIsExpanded(!isExpanded);+ };- return (- <Tooltip- title={- <Box onClick={handleTooltipClick} sx={{ cursor: "pointer" }}>- <Typography variant="body2">- {isExpanded ? longInfo : shortInfo}- </Typography>- <Typography- variant="caption"- color="text.secondary"- sx={{ display: "block", mt: 1, textAlign: "center" }}- >- {isExpanded ? "Click to show less" : "Click to learn more"}- </Typography>- </Box>- }- arrow- placement="top"- componentsProps={{- tooltip: {- sx: {- backgroundColor: theme.palette.background.paper,- color: theme.palette.text.primary,- border: `1px solid ${theme.palette.divider}`,- boxShadow: theme.shadows[3],- maxWidth: isExpanded ? 500 : 300,- p: 1.5,- },- },- }}- >- {children}- </Tooltip>- );+ return (+ <Tooltip+ title={+ <Box onClick={handleTooltipClick} sx={{cursor: "pointer"}}>+ <Typography variant="body2">+ {isExpanded ? longInfo : shortInfo}+ </Typography>+ <Typography+ variant="caption"+ color="text.secondary"+ sx={{display: "block", mt: 1, textAlign: "center"}}+ >+ {isExpanded ? "Click to show less" : "Click to learn more"}+ </Typography>+ </Box>+ }+ arrow+ placement="top"+ componentsProps={{+ tooltip: {+ sx: {+ backgroundColor: theme.palette.background.paper,+ color: theme.palette.text.primary,+ border: `1px solid ${theme.palette.divider}`,+ boxShadow: theme.shadows[3],+ maxWidth: isExpanded ? 500 : 300,+ p: 1.5,+ },+ },+ }}+ >+ {children}+ </Tooltip>+ );};type HeaderCellWithTooltipProps = {- label: string;- shortInfo: string;- longInfo: string;- style?: object;- align?: "inherit" | "left" | "center" | "right" | "justify";+ label: string;+ shortInfo: string;+ longInfo: string;+ style?: object;+ align?: "inherit" | "left" | "center" | "right" | "justify";};// Reusable tooltip component for column headersexport const HeaderCellWithTooltip = ({- label,- shortInfo,- longInfo,- style = {},- align = "center",-}: HeaderCellWithTooltipProps) => {- return (- <ProgressiveTooltip shortInfo={shortInfo} longInfo={longInfo}>- <TableCell align={align} sx={style}>- {label}- </TableCell>- </ProgressiveTooltip>- );+ label,+ shortInfo,+ longInfo,+ style = {},+ align = "center",+ }: HeaderCellWithTooltipProps) => {+ return (+ <ProgressiveTooltip shortInfo={shortInfo} longInfo={longInfo}>+ <TableCell align={align} sx={style}>+ {label}+ </TableCell>+ </ProgressiveTooltip>+ );};type FramerateRowProps = {- framerateData: CurrentFramerate | null;- colorMap: Record<string, string>;- getCellStyle: (metricType: string) => object;- isDarkMode: boolean;- theme: any;- shortTooltip: string;- longTooltip: string;+ framerateData: CurrentFramerate | null;+ colorMap: Record<string, string>;+ getCellStyle: (metricType: string) => object;+ isDarkMode: boolean;+ theme: any;+ shortTooltip: string;+ longTooltip: string;};const FramerateRow = ({- framerateData,- colorMap,- getCellStyle,- isDarkMode,- theme,- shortTooltip,- longTooltip,-}: FramerateRowProps) => {- const isBackend =- framerateData?.framerate_source === "Backend" ||- (!framerateData?.framerate_source && framerateData);+ framerateData,+ colorMap,+ getCellStyle,+ isDarkMode,+ theme,+ shortTooltip,+ longTooltip,+ }: FramerateRowProps) => {+ const isBackend =+ framerateData?.framerate_source === "Backend" ||+ (!framerateData?.framerate_source && framerateData);- return (- <TableRow>- <ProgressiveTooltip shortInfo={shortTooltip} longInfo={longTooltip}>- <TableCell- sx={{- fontWeight: "bold",- borderLeft: `3px solid ${colorMap.current}`,- paddingY: 0.5,- color: isDarkMode- ? isBackend- ? theme.palette.secondary.light- : theme.palette.primary.light- : isBackend- ? theme.palette.secondary.main- : theme.palette.primary.main,- cursor: "help",- }}- >- {framerateData?.framerate_source ||- (isBackend ? "Backend" : "Frontend")}- <Typography- variant="caption"- display="block"- color="text.secondary"- sx={{ fontSize: "0.6rem" }}- >- {framerateData?.calculation_window_size || 0} samples- </Typography>- </TableCell>- </ProgressiveTooltip>+ return (+ <TableRow>+ <ProgressiveTooltip shortInfo={shortTooltip} longInfo={longTooltip}>+ <TableCell+ sx={{+ fontWeight: "bold",+ borderLeft: `3px solid ${colorMap.current}`,+ paddingY: 0.5,+ color: isDarkMode+ ? isBackend+ ? theme.palette.secondary.light+ : theme.palette.primary.light+ : isBackend+ ? theme.palette.secondary.main+ : theme.palette.primary.main,+ cursor: "help",+ }}+ >+ {framerateData?.framerate_source ||+ (isBackend ? "Backend" : "Frontend")}+ <Typography+ variant="caption"+ display="block"+ color="text.secondary"+ sx={{fontSize: "0.6rem"}}+ >+ {framerateData?.calculation_window_size || 0} samples+ </Typography>+ </TableCell>+ </ProgressiveTooltip>- <MetricCell- label="current"- colorMap={colorMap}- getCellStyle={getCellStyle}- primaryValue={framerateData?.mean_frame_duration_ms}- primarySuffix="ms"- secondaryValue={framerateData?.mean_frames_per_second}- secondarySuffix="fps"- />+ <MetricCell+ label="current"+ colorMap={colorMap}+ getCellStyle={getCellStyle}+ primaryValue={framerateData?.mean_frame_duration_ms}+ primarySuffix="ms"+ secondaryValue={framerateData?.mean_frames_per_second}+ secondarySuffix="fps"+ />- <MetricCell- label="min"- colorMap={colorMap}- getCellStyle={getCellStyle}- primaryValue={framerateData?.frame_duration_min}- primarySuffix="ms"- secondaryValue={- framerateData?.frame_duration_min &&- framerateData.frame_duration_min > 0- ? 1000 / framerateData.frame_duration_min- : null- }- secondarySuffix="fps"- />+ <MetricCell+ label="min"+ colorMap={colorMap}+ getCellStyle={getCellStyle}+ primaryValue={framerateData?.frame_duration_min}+ primarySuffix="ms"+ secondaryValue={+ framerateData?.frame_duration_min &&+ framerateData.frame_duration_min > 0+ ? 1000 / framerateData.frame_duration_min+ : null+ }+ secondarySuffix="fps"+ />- <MetricCell- label="max"- colorMap={colorMap}- getCellStyle={getCellStyle}- primaryValue={framerateData?.frame_duration_max}- primarySuffix="ms"- secondaryValue={- framerateData?.frame_duration_max &&- framerateData.frame_duration_max > 0- ? 1000 / framerateData.frame_duration_max- : null- }- secondarySuffix="fps"- />+ <MetricCell+ label="max"+ colorMap={colorMap}+ getCellStyle={getCellStyle}+ primaryValue={framerateData?.frame_duration_max}+ primarySuffix="ms"+ secondaryValue={+ framerateData?.frame_duration_max &&+ framerateData.frame_duration_max > 0+ ? 1000 / framerateData.frame_duration_max+ : null+ }+ secondarySuffix="fps"+ />- <MetricCell- label="mean"- colorMap={colorMap}- getCellStyle={getCellStyle}- primaryValue={framerateData?.frame_duration_mean}- primarySuffix="ms"- secondaryValue={framerateData?.frame_duration_mean && framerateData.frame_duration_mean > 0- ? 1000 / framerateData.frame_duration_mean- : null}- secondarySuffix="fps"- />+ <MetricCell+ label="mean"+ colorMap={colorMap}+ getCellStyle={getCellStyle}+ primaryValue={framerateData?.frame_duration_mean}+ primarySuffix="ms"+ secondaryValue={framerateData?.frame_duration_mean && framerateData.frame_duration_mean > 0+ ? 1000 / framerateData.frame_duration_mean+ : null}+ secondarySuffix="fps"+ />- <MetricCell- label="median"- colorMap={colorMap}- getCellStyle={getCellStyle}- primaryValue={framerateData?.frame_duration_median}- primarySuffix="ms"- secondaryValue={framerateData?.frame_duration_median && framerateData.frame_duration_median > 0- ? 1000 / framerateData.frame_duration_median- : null}- secondarySuffix="fps"- />+ <MetricCell+ label="median"+ colorMap={colorMap}+ getCellStyle={getCellStyle}+ primaryValue={framerateData?.frame_duration_median}+ primarySuffix="ms"+ secondaryValue={framerateData?.frame_duration_median && framerateData.frame_duration_median > 0+ ? 1000 / framerateData.frame_duration_median+ : null}+ secondarySuffix="fps"+ />- <MetricCell- label="stdDev"- colorMap={colorMap}- getCellStyle={getCellStyle}- primaryValue={framerateData?.frame_duration_stddev}- primarySuffix="ms"- secondaryValue={- framerateData- ? framerateData.frame_duration_coefficient_of_variation * 100- : null- }- secondarySuffix="CV%"- />- </TableRow>- );+ <MetricCell+ label="stdDev"+ colorMap={colorMap}+ getCellStyle={getCellStyle}+ primaryValue={framerateData?.frame_duration_stddev}+ primarySuffix="ms"+ secondaryValue={+ framerateData+ ? framerateData.frame_duration_coefficient_of_variation * 100+ : null+ }+ secondarySuffix="CV%"+ />+ </TableRow>+ );};type MetricCellProps = {- label: string;- colorMap: Record<string, string>;- getCellStyle: (metricType: string) => object;- primaryValue: number | null | undefined;- primarySuffix?: string;- secondaryValue?: number | null | undefined;- secondarySuffix?: string;+ label: string;+ colorMap: Record<string, string>;+ getCellStyle: (metricType: string) => object;+ primaryValue: number | null | undefined;+ primarySuffix?: string;+ secondaryValue?: number | null | undefined;+ secondarySuffix?: string;};const MetricCell = ({- label,- colorMap,- getCellStyle,- primaryValue,- primarySuffix = "",- secondaryValue,- secondarySuffix = "",-}: MetricCellProps) => {- return (- <TableCell align="center" sx={getCellStyle(label)}>- <Typography- fontWeight="bold"- fontFamily="monospace"- color={colorMap[label]}- sx={{ fontSize: "0.7rem", whiteSpace: "nowrap" }}- >- {formatNumber(primaryValue ?? null)} {primarySuffix}- </Typography>- {secondaryValue !== undefined && (- <Typography- variant="caption"- color={colorMap[label]}- sx={{ fontSize: "0.6rem", opacity: 0.9, whiteSpace: "nowrap" }}- >- {formatNumber(secondaryValue ?? null)} {secondarySuffix}- </Typography>- )}- </TableCell>- );+ label,+ colorMap,+ getCellStyle,+ primaryValue,+ primarySuffix = "",+ secondaryValue,+ secondarySuffix = "",+ }: MetricCellProps) => {+ return (+ <TableCell align="center" sx={getCellStyle(label)}>+ <Typography+ fontWeight="bold"+ fontFamily="monospace"+ color={colorMap[label]}+ sx={{fontSize: "0.7rem", whiteSpace: "nowrap"}}+ >+ {formatNumber(primaryValue ?? null)} {primarySuffix}+ </Typography>+ {secondaryValue !== undefined && (+ <Typography+ variant="caption"+ color={colorMap[label]}+ sx={{fontSize: "0.6rem", opacity: 0.9, whiteSpace: "nowrap"}}+ >+ {formatNumber(secondaryValue ?? null)} {secondarySuffix}+ </Typography>+ )}+ </TableCell>+ );};export default function FramerateStatisticsView({- frontendFramerate,- backendFramerate,- compact = false,-}: FramerateStatisticsViewProps) {- const theme = useTheme();- const isDarkMode = theme.palette.mode === "dark";+ frontendFramerate,+ backendFramerate,+ compact = false,+ }: FramerateStatisticsViewProps) {+ const theme = useTheme();+ const isDarkMode = theme.palette.mode === "dark";- // Define color map with high contrast for both light and dark themes- const colorMap: Record<string, string> = {- current: isDarkMode- ? theme.palette.success.light- : theme.palette.success.main,- min: isDarkMode ? theme.palette.info.light : theme.palette.info.main,- max: isDarkMode ? theme.palette.error.light : theme.palette.error.main,- mean: isDarkMode ? theme.palette.warning.light : theme.palette.warning.main,- median: isDarkMode- ? theme.palette.warning.dark- : theme.palette.warning.dark,- stdDev: isDarkMode- ? theme.palette.primary.light- : theme.palette.primary.main,- cv: isDarkMode- ? theme.palette.secondary.light- : theme.palette.secondary.main,- };+ // Define color map with high contrast for both light and dark themes+ const colorMap: Record<string, string> = {+ current: isDarkMode+ ? theme.palette.success.light+ : theme.palette.success.main,+ min: isDarkMode ? theme.palette.info.light : theme.palette.info.main,+ max: isDarkMode ? theme.palette.error.light : theme.palette.error.main,+ mean: isDarkMode ? theme.palette.warning.light : theme.palette.warning.main,+ median: isDarkMode+ ? theme.palette.warning.dark+ : theme.palette.warning.dark,+ stdDev: isDarkMode+ ? theme.palette.primary.light+ : theme.palette.primary.main,+ cv: isDarkMode+ ? theme.palette.secondary.light+ : theme.palette.secondary.main,+ };- // Generate cell style based on metric type- const getCellStyle = (metricType: string) => {- return {- backgroundColor: alpha(- colorMap[metricType] || theme.palette.grey[500],- isDarkMode ? 0.2 : 0.1- ),- borderBottom: "none",- padding: "2px 4px",+ // Generate cell style based on metric type+ const getCellStyle = (metricType: string) => {+ return {+ backgroundColor: alpha(+ colorMap[metricType] || theme.palette.grey[500],+ isDarkMode ? 0.2 : 0.1+ ),+ borderBottom: "none",+ padding: "2px 4px",+ };};- };- // Common header cell styles- const headerCellStyle = {- fontWeight: "bold",- paddingY: 0.5,- };+ // Common header cell styles+ const headerCellStyle = {+ fontWeight: "bold",+ paddingY: 0.5,+ };- // Tooltips content - short and long versions- const tooltips = {- source: {- short: "Frontend displays frames, Backend captures frames.",- long: "The backend is the true rate at which frames are pulled/recorded from the camera, while the frontend is the rate at which they are received and displayed. Skellycam prioritizes backend performance for recording quality, so that number should stay more stable. If the frontend framerate diverges from the backend, it indicates your system resources are taxed. Consider using fewer cameras or decreasing framerate/resolution.",- },- current: {- short: "Most recent frame time and corresponding FPS.",- long: "This shows the most recent measurement of how long it takes to process a single frame (in milliseconds) and the equivalent frames per second (FPS). Lower frame times and higher FPS indicate better performance.",- },- min: {- short: "Fastest frame time (lowest latency) and highest FPS achieved.",- long: "This represents the minimum time it took to process a single frame during the sampling window. This corresponds to the maximum FPS your system achieved during optimal conditions.",- },- max: {- short: "Slowest frame time (highest latency) and lowest FPS experienced.",- long: "This represents the maximum time it took to process a single frame during the sampling window. This corresponds to the minimum FPS your system achieved during worst-case conditions. Occasional spikes are normal, but consistently high values may indicate performance issues.",- },- mean: {- short: "Average frame time and FPS across all samples.",- long: "The arithmetic mean (average) of all frame times measured during the sampling window and the corresponding FPS. This gives a good overall picture of performance but may be skewed by outliers.",- },- median: {- short: "Middle value of all frame times (50th percentile).",- long: "The median represents the middle value when all frame times are sorted from fastest to slowest. Unlike the mean, the median is not affected by extreme outliers, making it a more stable indicator of typical performance.",- },- stdDev: {- short: "Measures frame time variability. CV% is relative variability.",- long: "Standard deviation measures the amount of variation in frame times. Lower values indicate more consistent performance. The Coefficient of Variation (CV%) expresses this variability as a percentage of the mean, making it easier to compare stability across different frame rates. Lower CV% indicates more stable performance.",- },- };+ // Tooltips content - short and long versions+ const tooltips = {+ source: {+ short: "Frontend displays frames, Backend captures frames.",+ long: "The backend is the true rate at which frames are pulled/recorded from the camera, while the frontend is the rate at which they are received and displayed. Skellycam prioritizes backend performance for recording quality, so that number should stay more stable. If the frontend framerate diverges from the backend, it indicates your system resources are taxed. Consider using fewer cameras or decreasing framerate/resolution.",+ },+ current: {+ short: "Most recent frame time and corresponding FPS.",+ long: "This shows the most recent measurement of how long it takes to process a single frame (in milliseconds) and the equivalent frames per second (FPS). Lower frame times and higher FPS indicate better performance.",+ },+ min: {+ short: "Fastest frame time (lowest latency) and highest FPS achieved.",+ long: "This represents the minimum time it took to process a single frame during the sampling window. This corresponds to the maximum FPS your system achieved during optimal conditions.",+ },+ max: {+ short: "Slowest frame time (highest latency) and lowest FPS experienced.",+ long: "This represents the maximum time it took to process a single frame during the sampling window. This corresponds to the minimum FPS your system achieved during worst-case conditions. Occasional spikes are normal, but consistently high values may indicate performance issues.",+ },+ mean: {+ short: "Average frame time and FPS across all samples.",+ long: "The arithmetic mean (average) of all frame times measured during the sampling window and the corresponding FPS. This gives a good overall picture of performance but may be skewed by outliers.",+ },+ median: {+ short: "Middle value of all frame times (50th percentile).",+ long: "The median represents the middle value when all frame times are sorted from fastest to slowest. Unlike the mean, the median is not affected by extreme outliers, making it a more stable indicator of typical performance.",+ },+ stdDev: {+ short: "Measures frame time variability. CV% is relative variability.",+ long: "Standard deviation measures the amount of variation in frame times. Lower values indicate more consistent performance. The Coefficient of Variation (CV%) expresses this variability as a percentage of the mean, making it easier to compare stability across different frame rates. Lower CV% indicates more stable performance.",+ },+ };- return (- <TableContainer- component={Paper}- elevation={0}- sx={{- backgroundColor: "transparent",- border: "none",- overflowX: "auto",- }}- >- <Table- size="small"- padding="none"- sx={{- "& .MuiTableCell-root": {- fontSize: "0.65rem",- lineHeight: "1.1",- whiteSpace: "nowrap",- },- }}- >- <TableHead>- <TableRow>- <HeaderCellWithTooltip- label="Source"- shortInfo={tooltips.source.short}- longInfo={tooltips.source.long}- style={{- ...headerCellStyle,- width: "12%",- color: theme.palette.text.primary,- }}- align="left"- />- <HeaderCellWithTooltip- label="Current"- shortInfo={tooltips.current.short}- longInfo={tooltips.current.long}- style={{- ...headerCellStyle,- ...getCellStyle("current"),- }}- />- <HeaderCellWithTooltip- label="Min"- shortInfo={tooltips.min.short}- longInfo={tooltips.min.long}- style={{- ...headerCellStyle,- ...getCellStyle("min"),- }}- />- <HeaderCellWithTooltip- label="Max"- shortInfo={tooltips.max.short}- longInfo={tooltips.max.long}- style={{- ...headerCellStyle,- ...getCellStyle("max"),- }}- />- <HeaderCellWithTooltip- label="Mean"- shortInfo={tooltips.mean.short}- longInfo={tooltips.mean.long}- style={{- ...headerCellStyle,- ...getCellStyle("mean"),- }}- />- <HeaderCellWithTooltip- label="Median"- shortInfo={tooltips.median.short}- longInfo={tooltips.median.long}- style={{- ...headerCellStyle,- ...getCellStyle("median"),- }}- />- <HeaderCellWithTooltip- label="StdDev/CV"- shortInfo={tooltips.stdDev.short}- longInfo={tooltips.stdDev.long}- style={{- ...headerCellStyle,- ...getCellStyle("stdDev"),- }}- />- </TableRow>- {/* Add the divider inside TableHead */}- <TableRow>- <TableCell colSpan={7} sx={{ padding: 0 }}>- <Divider sx={{ borderColor: theme.palette.divider }} />- </TableCell>- </TableRow>- </TableHead>+ return (+ <TableContainer+ component={Paper}+ elevation={0}+ sx={{+ backgroundColor: "transparent",+ border: "none",+ overflowX: "auto",+ }}+ >+ <Table+ size="small"+ padding="none"+ sx={{+ "& .MuiTableCell-root": {+ fontSize: "0.65rem",+ lineHeight: "1.1",+ whiteSpace: "nowrap",+ },+ }}+ >+ <TableHead>+ <TableRow>+ <HeaderCellWithTooltip+ label="Source"+ shortInfo={tooltips.source.short}+ longInfo={tooltips.source.long}+ style={{+ ...headerCellStyle,+ width: "12%",+ color: theme.palette.text.primary,+ }}+ align="left"+ />+ <HeaderCellWithTooltip+ label="Current"+ shortInfo={tooltips.current.short}+ longInfo={tooltips.current.long}+ style={{+ ...headerCellStyle,+ ...getCellStyle("current"),+ }}+ />+ <HeaderCellWithTooltip+ label="Min"+ shortInfo={tooltips.min.short}+ longInfo={tooltips.min.long}+ style={{+ ...headerCellStyle,+ ...getCellStyle("min"),+ }}+ />+ <HeaderCellWithTooltip+ label="Max"+ shortInfo={tooltips.max.short}+ longInfo={tooltips.max.long}+ style={{+ ...headerCellStyle,+ ...getCellStyle("max"),+ }}+ />+ <HeaderCellWithTooltip+ label="Mean"+ shortInfo={tooltips.mean.short}+ longInfo={tooltips.mean.long}+ style={{+ ...headerCellStyle,+ ...getCellStyle("mean"),+ }}+ />+ <HeaderCellWithTooltip+ label="Median"+ shortInfo={tooltips.median.short}+ longInfo={tooltips.median.long}+ style={{+ ...headerCellStyle,+ ...getCellStyle("median"),+ }}+ />+ <HeaderCellWithTooltip+ label="StdDev/CV"+ shortInfo={tooltips.stdDev.short}+ longInfo={tooltips.stdDev.long}+ style={{+ ...headerCellStyle,+ ...getCellStyle("stdDev"),+ }}+ />+ </TableRow>+ {/* Add the divider inside TableHead */}+ <TableRow>+ <TableCell colSpan={7} sx={{padding: 0}}>+ <Divider sx={{borderColor: theme.palette.divider}}/>+ </TableCell>+ </TableRow>+ </TableHead>- <TableBody>- {/* Frontend Row */}- <FramerateRow- framerateData={frontendFramerate}- colorMap={colorMap}- getCellStyle={getCellStyle}- isDarkMode={isDarkMode}- theme={theme}- shortTooltip="Displays received frames."- longTooltip="Frontend represents the UI rendering performance. It shows how quickly your display receives and renders frames. Performance issues here won't affect recording quality but may impact your ability to monitor cameras in real-time."- />+ <TableBody>+ {/* Frontend Row */}+ <FramerateRow+ framerateData={frontendFramerate}+ colorMap={colorMap}+ getCellStyle={getCellStyle}+ isDarkMode={isDarkMode}+ theme={theme}+ shortTooltip="Displays received frames."+ longTooltip="Frontend represents the UI rendering performance. It shows how quickly your display receives and renders frames. Performance issues here won't affect recording quality but may impact your ability to monitor cameras in real-time."+ />- {/* Divider between rows - now properly inside TableBody */}- <TableRow>- <TableCell colSpan={7} sx={{ padding: 0 }}>- <Divider sx={{ borderColor: theme.palette.divider }} />- </TableCell>- </TableRow>+ {/* Divider between rows - now properly inside TableBody */}+ <TableRow>+ <TableCell colSpan={7} sx={{padding: 0}}>+ <Divider sx={{borderColor: theme.palette.divider}}/>+ </TableCell>+ </TableRow>- {/* Backend Row */}- <FramerateRow- framerateData={backendFramerate}- colorMap={colorMap}- getCellStyle={getCellStyle}- isDarkMode={isDarkMode}- theme={theme}- shortTooltip="Captures frames from camera."- longTooltip="Backend represents the camera frame-grabbing performance. This is the true rate at which frames are pulled from the camera and saved during recording. This is the most important metric for recording quality and should remain stable even if frontend performance fluctuates."- />- </TableBody>- </Table>- </TableContainer>- );+ {/* Backend Row */}+ <FramerateRow+ framerateData={backendFramerate}+ colorMap={colorMap}+ getCellStyle={getCellStyle}+ isDarkMode={isDarkMode}+ theme={theme}+ shortTooltip="Captures frames from camera."+ longTooltip="Backend represents the camera frame-grabbing performance. This is the true rate at which frames are pulled from the camera and saved during recording. This is the most important metric for recording quality and should remain stable even if frontend performance fluctuates."+ />+ </TableBody>+ </Table>+ </TableContainer>+ );}diff --git a/freemocap-ui/src/components/framerate-viewer/FramerateTimeseriesView.tsx b/freemocap-ui/src/components/framerate-viewer/FramerateTimeseriesView.tsxindex f78c829c..41e946a2 100644--- a/freemocap-ui/src/components/framerate-viewer/FramerateTimeseriesView.tsx+++ b/freemocap-ui/src/components/framerate-viewer/FramerateTimeseriesView.tsx@@ -2,206 +2,201 @@import {useCallback} from "react"import * as d3 from "d3"import {useTheme} from "@mui/material/styles"-import {CurrentFramerate} from "@/store/slices/framerateTrackerSlice"-import {- applyAxisStyles,- createTooltip,- renderEmptyChart,- renderThresholdLines-} from "@/components/framerate-viewer/d3ChartUtils";+import {CurrentFramerate} from "@/store/slices/framerate/framerate-slice"+import {applyAxisStyles, createTooltip, renderEmptyChart} from "@/components/framerate-viewer/d3ChartUtils";import BaseD3ChartView from "@/components/framerate-viewer/BaseD3ChartView";type FramerateTimeseriesProps = {- frontendFramerate: CurrentFramerate | null- backendFramerate: CurrentFramerate | null- recentFrontendFrameDurations: number[]- recentBackendFrameDurations: number[]- frontendColor: string- backendColor: string- title?: string+ frontendFramerate: CurrentFramerate | null+ backendFramerate: CurrentFramerate | null+ recentFrontendFrameDurations: number[]+ recentBackendFrameDurations: number[]+ frontendColor: string+ backendColor: string+ title?: string}type ChartRenderProps = {- svg: d3.Selection<SVGGElement, unknown, null, undefined>;- chartArea: d3.Selection<SVGGElement, unknown, null, undefined>;- width: number;- height: number;- margin: { top: number; right: number; bottom: number; left: number };- transform: d3.ZoomTransform;+ svg: d3.Selection<SVGGElement, unknown, null, undefined>;+ chartArea: d3.Selection<SVGGElement, unknown, null, undefined>;+ width: number;+ height: number;+ margin: { top: number; right: number; bottom: number; left: number };+ transform: d3.ZoomTransform;};export default function FramerateTimeseriesView({- frontendFramerate,- backendFramerate,- recentFrontendFrameDurations,- recentBackendFrameDurations,- frontendColor,- backendColor,- title = "Frame Duration Over Time"+ frontendFramerate,+ backendFramerate,+ recentFrontendFrameDurations,+ recentBackendFrameDurations,+ frontendColor,+ backendColor,+ title = "Frame Duration Over Time"}: FramerateTimeseriesProps) {- const theme = useTheme()-- const renderChart = useCallback(({ svg, chartArea, width, height, margin, transform }: ChartRenderProps) => {- // Prepare data sources - using the recent frame durations arrays- const sources = [- {- id: "frontend",- name: frontendFramerate?.framerate_source || "Frontend",- color: frontendColor,- data: recentFrontendFrameDurations.map((value, index) => ({- timestamp: Date.now() - (recentFrontendFrameDurations.length - index) *- (frontendFramerate?.mean_frame_duration_ms || 16.67),- value- }))- },- {- id: "backend",- name: backendFramerate?.framerate_source || "Backend",- color: backendColor,- data: recentBackendFrameDurations.map((value, index) => ({- timestamp: Date.now() - (recentBackendFrameDurations.length - index) *- (backendFramerate?.mean_frame_duration_ms || 33.33),- value- }))- }- ];-- if (sources.every((s) => s.data.length === 0)) {- renderEmptyChart(svg, width, height, theme);- return;- }-- // Combine all data points to determine overall domain- const allData = sources.flatMap((s) => s.data);-- // Set up scales- const xScale = d3- .scaleTime()- .domain(d3.extent(allData, (d) => new Date(d.timestamp)) as [Date, Date])- .range([0, width]);-- // Calculate y domain with some padding- const yMax = d3.max(allData, (d) => d.value) as number;- const yPadding = Math.max(1, yMax * 0.1);-- const yScale = d3- .scaleLinear()- .domain([0, yMax + yPadding])- .range([height, 0]);-- // Apply the current zoom transform- const xScaleZoomed = transform.rescaleX(xScale);- const yScaleZoomed = transform.rescaleY(yScale);-- // Create axes- const xAxis = d3- .axisBottom(xScaleZoomed)- .ticks(5)- .tickSize(-height)- .tickFormat(d3.timeFormat("%H:%M:%S") as any);-- const yAxis = d3.axisLeft(yScaleZoomed).ticks(10).tickSize(-width);-- // Add X axis- const xAxisGroup = svg- .append("g")- .attr("class", "x-axis")- .attr("transform", `translate(0,${height})`)- .call(xAxis);-- xAxisGroup- .selectAll("text")- .style("text-anchor", "end")- .attr("dx", "-.8em")- .attr("dy", ".15em")- .attr("transform", "rotate(-45)");-- // Add Y axis- const yAxisGroup = svg- .append("g")- .attr("class", "y-axis")- .call(yAxis);-- // Add Y axis label- svg- .append("text")- .attr("transform", "rotate(-90)")- .attr("y", 0 - margin.left)- .attr("x", 0 - height / 2)- .attr("dy", "1em")- .style("text-anchor", "middle")- .style("font-family", "monospace")- .style("font-size", "14px")- .style("fill", theme.palette.text.secondary)- .text("Frame Duration (ms)");-- // Style axes- applyAxisStyles(svg, theme);-- // Add threshold lines- // const thresholds = [- // { value: 16.67, label: "60 FPS", color: theme.palette.success.main },- // { value: 33.33, label: "30 FPS", color: theme.palette.warning.main },- // ];- //- // renderThresholdLines(chartArea, thresholds, xScaleZoomed, yScaleZoomed, width, height, true);-- // Create line generator- const line = d3- .line<{ timestamp: number, value: number }>()- .x((d) => xScaleZoomed(new Date(d.timestamp)))- .y((d) => yScaleZoomed(d.value))- .curve(d3.curveLinear);-- // Add lines and points for each source- sources.forEach((source) => {- if (source.data.length === 0) return;-- // Add the line path- chartArea- .append("path")- .datum(source.data)- .attr("fill", "none")- .attr("stroke", source.color)- .attr("stroke-width", 1.5)- .attr("d", line);-- });-- // Add legend- const legend = svg- .append("g")- .attr("transform", `translate(${width + 10}, 0)`)- .attr("font-family", "monospace")- .attr("font-size", "10px");-- sources.forEach((source, i) => {- if (source.data.length === 0) return;-- const legendItem = legend.append("g").attr("transform", `translate(0, ${i * 20})`);- legendItem.append("rect").attr("width", 12).attr("height", 12).attr("fill", source.color);- legendItem.append("text")- .attr("x", 20)- .attr("y", 10)- .style("fill", theme.palette.text.primary)- .text(source.name);- });-- // Add tooltip- const tooltip = createTooltip(theme);-- // Add tooltip for data points- sources.forEach((source) => {- if (source.data.length === 0) return;-- chartArea- .selectAll(`.data-point-${source.id}`)- .on("mouseover", function(event: MouseEvent, d: any) {- const element = this as unknown as SVGCircleElement;- d3.select(element).attr("r", 5).attr("fill", d3.color(source.color)!.brighter(0.5).toString());-- tooltip- .style("opacity", 1)- .html(`+ const theme = useTheme()++ const renderChart = useCallback(({svg, chartArea, width, height, margin, transform}: ChartRenderProps) => {+ // Prepare data sources - using the recent frame durations arrays+ const sources = [+ {+ id: "frontend",+ name: frontendFramerate?.framerate_source || "Frontend",+ color: frontendColor,+ data: recentFrontendFrameDurations.map((value, index) => ({+ timestamp: Date.now() - (recentFrontendFrameDurations.length - index) *+ (frontendFramerate?.mean_frame_duration_ms || 16.67),+ value+ }))+ },+ {+ id: "backend",+ name: backendFramerate?.framerate_source || "Backend",+ color: backendColor,+ data: recentBackendFrameDurations.map((value, index) => ({+ timestamp: Date.now() - (recentBackendFrameDurations.length - index) *+ (backendFramerate?.mean_frame_duration_ms || 33.33),+ value+ }))+ }+ ];++ if (sources.every((s) => s.data.length === 0)) {+ renderEmptyChart(svg, width, height, theme);+ return;+ }++ // Combine all data points to determine overall domain+ const allData = sources.flatMap((s) => s.data);++ // Set up scales+ const xScale = d3+ .scaleTime()+ .domain(d3.extent(allData, (d) => new Date(d.timestamp)) as [Date, Date])+ .range([0, width]);++ // Calculate y domain with some padding+ const yMax = d3.max(allData, (d) => d.value) as number;+ const yPadding = Math.max(1, yMax * 0.1);++ const yScale = d3+ .scaleLinear()+ .domain([0, yMax + yPadding])+ .range([height, 0]);++ // Apply the current zoom transform+ const xScaleZoomed = transform.rescaleX(xScale);+ const yScaleZoomed = transform.rescaleY(yScale);++ // Create axes+ const xAxis = d3+ .axisBottom(xScaleZoomed)+ .ticks(5)+ .tickSize(-height)+ .tickFormat(d3.timeFormat("%H:%M:%S") as any);++ const yAxis = d3.axisLeft(yScaleZoomed).ticks(10).tickSize(-width);++ // Add X axis+ const xAxisGroup = svg+ .append("g")+ .attr("class", "x-axis")+ .attr("transform", `translate(0,${height})`)+ .call(xAxis);++ xAxisGroup+ .selectAll("text")+ .style("text-anchor", "end")+ .attr("dx", "-.8em")+ .attr("dy", ".15em")+ .attr("transform", "rotate(-45)");++ // Add Y axis+ const yAxisGroup = svg+ .append("g")+ .attr("class", "y-axis")+ .call(yAxis);++ // Add Y axis label+ svg+ .append("text")+ .attr("transform", "rotate(-90)")+ .attr("y", 0 - margin.left)+ .attr("x", 0 - height / 2)+ .attr("dy", "1em")+ .style("text-anchor", "middle")+ .style("font-family", "monospace")+ .style("font-size", "14px")+ .style("fill", theme.palette.text.secondary)+ .text("Frame Duration (ms)");++ // Style axes+ applyAxisStyles(svg, theme);++ // Add threshold lines+ // const thresholds = [+ // { value: 16.67, label: "60 FPS", color: theme.palette.success.main },+ // { value: 33.33, label: "30 FPS", color: theme.palette.warning.main },+ // ];+ //+ // renderThresholdLines(chartArea, thresholds, xScaleZoomed, yScaleZoomed, width, height, true);++ // Create line generator+ const line = d3+ .line<{ timestamp: number, value: number }>()+ .x((d) => xScaleZoomed(new Date(d.timestamp)))+ .y((d) => yScaleZoomed(d.value))+ .curve(d3.curveLinear);++ // Add lines and points for each source+ sources.forEach((source) => {+ if (source.data.length === 0) return;++ // Add the line path+ chartArea+ .append("path")+ .datum(source.data)+ .attr("fill", "none")+ .attr("stroke", source.color)+ .attr("stroke-width", 1.5)+ .attr("d", line);++ });++ // Add legend+ const legend = svg+ .append("g")+ .attr("transform", `translate(${width + 10}, 0)`)+ .attr("font-family", "monospace")+ .attr("font-size", "10px");++ sources.forEach((source, i) => {+ if (source.data.length === 0) return;++ const legendItem = legend.append("g").attr("transform", `translate(0, ${i * 20})`);+ legendItem.append("rect").attr("width", 12).attr("height", 12).attr("fill", source.color);+ legendItem.append("text")+ .attr("x", 20)+ .attr("y", 10)+ .style("fill", theme.palette.text.primary)+ .text(source.name);+ });++ // Add tooltip+ const tooltip = createTooltip(theme);++ // Add tooltip for data points+ sources.forEach((source) => {+ if (source.data.length === 0) return;++ chartArea+ .selectAll(`.data-point-${source.id}`)+ .on("mouseover", function (event: MouseEvent, d: any) {+ const element = this as unknown as SVGCircleElement;+ d3.select(element).attr("r", 5).attr("fill", d3.color(source.color)!.brighter(0.5).toString());++ tooltip+ .style("opacity", 1)+ .html(`<div style="display: grid; grid-template-columns: auto auto; gap: 4px;"><span style="color: ${theme.palette.text.secondary};">SOURCE:</span><span style="color: ${source.color};">${source.name}</span>@@ -213,30 +208,30 @@ export default function FramerateTimeseriesView({<span>${(1000 / d.value).toFixed(2)}</span></div>`)- .style("left", event.pageX + 10 + "px")- .style("top", event.pageY - 28 + "px");- })- .on("mouseout", function(event: MouseEvent, d: any) {- d3.select(this).attr("r", 3).attr("fill", source.color);- tooltip.style("opacity", 0);- });- });-- return () => tooltip.remove();- }, [- frontendFramerate,- backendFramerate,- recentFrontendFrameDurations,- recentBackendFrameDurations,- frontendColor,- backendColor,- theme- ]);-- return (- <BaseD3ChartView- title={title}- renderChart={renderChart}- />- );+ .style("left", event.pageX + 10 + "px")+ .style("top", event.pageY - 28 + "px");+ })+ .on("mouseout", function (event: MouseEvent, d: any) {+ d3.select(this).attr("r", 3).attr("fill", source.color);+ tooltip.style("opacity", 0);+ });+ });++ return () => tooltip.remove();+ }, [+ frontendFramerate,+ backendFramerate,+ recentFrontendFrameDurations,+ recentBackendFrameDurations,+ frontendColor,+ backendColor,+ theme+ ]);++ return (+ <BaseD3ChartView+ title={title}+ renderChart={renderChart}+ />+ );}diff --git a/freemocap-ui/src/components/framerate-viewer/d3ChartUtils.ts b/freemocap-ui/src/components/framerate-viewer/d3ChartUtils.tsindex 4d221017..f29950d1 100644--- a/freemocap-ui/src/components/framerate-viewer/d3ChartUtils.ts+++ b/freemocap-ui/src/components/framerate-viewer/d3ChartUtils.ts@@ -3,210 +3,210 @@ import * as d3 from "d3"import {Theme} from "@mui/material/styles"export function createTooltip(theme: Theme) {- return d3- .select("body")- .append("div")- .style("position", "absolute")- .style("background-color", theme.palette.mode === "dark" ? "rgba(0, 0, 0, 0.85)" : "rgba(255, 255, 255, 0.9)")- .style("border", `1px solid ${theme.palette.divider}`)- .style("border-radius", "4px")- .style("padding", "8px")- .style("font-family", "monospace")- .style("font-size", "12px")- .style("pointer-events", "none")- .style("opacity", 0)- .style("z-index", 1000)- .style("color", theme.palette.text.primary)+ return d3+ .select("body")+ .append("div")+ .style("position", "absolute")+ .style("background-color", theme.palette.mode === "dark" ? "rgba(0, 0, 0, 0.85)" : "rgba(255, 255, 255, 0.9)")+ .style("border", `1px solid ${theme.palette.divider}`)+ .style("border-radius", "4px")+ .style("padding", "8px")+ .style("font-family", "monospace")+ .style("font-size", "12px")+ .style("pointer-events", "none")+ .style("opacity", 0)+ .style("z-index", 1000)+ .style("color", theme.palette.text.primary)}export function applyAxisStyles(- svg: d3.Selection<SVGGElement, unknown, null, undefined>,- theme: Theme+ svg: d3.Selection<SVGGElement, unknown, null, undefined>,+ theme: Theme) {- svg.selectAll(".tick line")- .attr("stroke", theme.palette.divider)- .attr("stroke-dasharray", "2,2")-- svg.selectAll(".tick text")- .style("font-family", "monospace")- .style("font-size", "10px")- .style("color", theme.palette.text.secondary)-}+ svg.selectAll(".tick line")+ .attr("stroke", theme.palette.divider)+ .attr("stroke-dasharray", "2,2")-export function renderEmptyChart(- svg: d3.Selection<SVGGElement, unknown, null, undefined>,- width: number,- height: number,- theme: Theme-) {- // Create empty scales- const xScale = d3.scaleLinear().domain([0, 100]).range([0, width])- const yScale = d3.scaleLinear().domain([0, 10]).range([height, 0])-- // Create axes- const xAxis = d3.axisBottom(xScale).ticks(10).tickSize(-height)- const yAxis = d3.axisLeft(yScale).ticks(5).tickSize(-width)-- // Add X axis- svg- .append("g")- .attr("class", "x-axis")- .style("font-family", "monospace")- .style("font-size", "10px")- .style("color", theme.palette.text.secondary)- .attr("transform", `translate(0,${height})`)- .call(xAxis)-- // Add Y axis- svg- .append("g")- .attr("class", "y-axis")- .style("font-family", "monospace")- .style("font-size", "10px")- .style("color", theme.palette.text.secondary)- .call(yAxis)-- // Style grid lines- svg.selectAll(".tick line").attr("stroke", theme.palette.divider).attr("stroke-dasharray", "2,2")-- // Add "No data" message- svg- .append("text")- .attr("x", width / 2)- .attr("y", height / 2)- .attr("text-anchor", "middle")- .style("font-family", "monospace")- .style("font-size", "14px")- .style("fill", theme.palette.text.disabled)- .text("No data available")+ svg.selectAll(".tick text")+ .style("font-family", "monospace")+ .style("font-size", "10px")+ .style("color", theme.palette.text.secondary)}-export function renderThresholdLines(- chartArea: d3.Selection<SVGGElement, unknown, null, undefined>,- thresholds: { value: number, label: string, color: string }[],- xScale: any, // Allow both time and linear scales- yScale: d3.ScaleLinear<number, number>,- width: number,- height: number,- isHorizontal: boolean+export function renderEmptyChart(+ svg: d3.Selection<SVGGElement, unknown, null, undefined>,+ width: number,+ height: number,+ theme: Theme) {- thresholds.forEach((threshold) => {- if (isHorizontal) {- // Horizontal threshold line (for time series)- chartArea- .append("line")- .attr("class", "threshold-line")- .attr("x1", 0)- .attr("y1", yScale(threshold.value))- .attr("x2", width)- .attr("y2", yScale(threshold.value))- .attr("stroke", threshold.color)- .attr("stroke-width", 1)- .attr("stroke-dasharray", "4,4")-- // Add threshold label- chartArea- .append("text")- .attr("class", "threshold-label")- .attr("x", width)- .attr("y", yScale(threshold.value) - 5)- .attr("text-anchor", "end")+ // Create empty scales+ const xScale = d3.scaleLinear().domain([0, 100]).range([0, width])+ const yScale = d3.scaleLinear().domain([0, 10]).range([height, 0])++ // Create axes+ const xAxis = d3.axisBottom(xScale).ticks(10).tickSize(-height)+ const yAxis = d3.axisLeft(yScale).ticks(5).tickSize(-width)++ // Add X axis+ svg+ .append("g")+ .attr("class", "x-axis").style("font-family", "monospace").style("font-size", "10px")- .style("fill", threshold.color)- .text(threshold.label)- } else {- // Vertical threshold line (for histogram)- chartArea- .append("line")- .attr("class", "threshold-line")- .attr("x1", xScale(threshold.value))- .attr("y1", 0)- .attr("x2", xScale(threshold.value))- .attr("y2", height)- .attr("stroke", threshold.color)- .attr("stroke-width", 1.5)- .attr("stroke-dasharray", "4,4")-- // Add threshold label- chartArea+ .style("color", theme.palette.text.secondary)+ .attr("transform", `translate(0,${height})`)+ .call(xAxis)++ // Add Y axis+ svg+ .append("g")+ .attr("class", "y-axis")+ .style("font-family", "monospace")+ .style("font-size", "10px")+ .style("color", theme.palette.text.secondary)+ .call(yAxis)++ // Style grid lines+ svg.selectAll(".tick line").attr("stroke", theme.palette.divider).attr("stroke-dasharray", "2,2")++ // Add "No data" message+ svg.append("text")- .attr("class", "threshold-label")- .attr("x", xScale(threshold.value))- .attr("y", 15)+ .attr("x", width / 2)+ .attr("y", height / 2).attr("text-anchor", "middle").style("font-family", "monospace")- .style("font-size", "10px")- .style("fill", threshold.color)- .text(threshold.label)- }- })+ .style("font-size", "14px")+ .style("fill", theme.palette.text.disabled)+ .text("No data available")+}++export function renderThresholdLines(+ chartArea: d3.Selection<SVGGElement, unknown, null, undefined>,+ thresholds: { value: number, label: string, color: string }[],+ xScale: any, // Allow both time and linear scales+ yScale: d3.ScaleLinear<number, number>,+ width: number,+ height: number,+ isHorizontal: boolean+) {+ thresholds.forEach((threshold) => {+ if (isHorizontal) {+ // Horizontal threshold line (for time series)+ chartArea+ .append("line")+ .attr("class", "threshold-line")+ .attr("x1", 0)+ .attr("y1", yScale(threshold.value))+ .attr("x2", width)+ .attr("y2", yScale(threshold.value))+ .attr("stroke", threshold.color)+ .attr("stroke-width", 1)+ .attr("stroke-dasharray", "4,4")++ // Add threshold label+ chartArea+ .append("text")+ .attr("class", "threshold-label")+ .attr("x", width)+ .attr("y", yScale(threshold.value) - 5)+ .attr("text-anchor", "end")+ .style("font-family", "monospace")+ .style("font-size", "10px")+ .style("fill", threshold.color)+ .text(threshold.label)+ } else {+ // Vertical threshold line (for histogram)+ chartArea+ .append("line")+ .attr("class", "threshold-line")+ .attr("x1", xScale(threshold.value))+ .attr("y1", 0)+ .attr("x2", xScale(threshold.value))+ .attr("y2", height)+ .attr("stroke", threshold.color)+ .attr("stroke-width", 1.5)+ .attr("stroke-dasharray", "4,4")++ // Add threshold label+ chartArea+ .append("text")+ .attr("class", "threshold-label")+ .attr("x", xScale(threshold.value))+ .attr("y", 15)+ .attr("text-anchor", "middle")+ .style("font-family", "monospace")+ .style("font-size", "10px")+ .style("fill", threshold.color)+ .text(threshold.label)+ }+ })}// Helper functions for zoom updates// Update thresholds on zoomexport function updateThresholdsOnZoom(- chartArea: d3.Selection<SVGGElement, unknown, null, undefined>,- transform: d3.ZoomTransform,- xScale: any,- yScale: d3.ScaleLinear<number, number>,- isHorizontal: boolean+ chartArea: d3.Selection<SVGGElement, unknown, null, undefined>,+ transform: d3.ZoomTransform,+ xScale: any,+ yScale: d3.ScaleLinear<number, number>,+ isHorizontal: boolean) {- if (isHorizontal) {- // Update horizontal threshold lines- chartArea.selectAll(".threshold-line")- .attr("y1", (d: any) => transform.applyY(yScale(d.value)))- .attr("y2", (d: any) => transform.applyY(yScale(d.value)));-- // Update labels- chartArea.selectAll(".threshold-label")- .attr("y", (d: any) => transform.applyY(yScale(d.value)) - 5);- } else {- // Update vertical threshold lines- chartArea.selectAll(".threshold-line")- .attr("x1", (d: any) => transform.applyX(xScale(d.value)))- .attr("x2", (d: any) => transform.applyX(xScale(d.value)));-- // Update labels- chartArea.selectAll(".threshold-label")- .attr("x", (d: any) => transform.applyX(xScale(d.value)));- }+ if (isHorizontal) {+ // Update horizontal threshold lines+ chartArea.selectAll(".threshold-line")+ .attr("y1", (d: any) => transform.applyY(yScale(d.value)))+ .attr("y2", (d: any) => transform.applyY(yScale(d.value)));++ // Update labels+ chartArea.selectAll(".threshold-label")+ .attr("y", (d: any) => transform.applyY(yScale(d.value)) - 5);+ } else {+ // Update vertical threshold lines+ chartArea.selectAll(".threshold-line")+ .attr("x1", (d: any) => transform.applyX(xScale(d.value)))+ .attr("x2", (d: any) => transform.applyX(xScale(d.value)));++ // Update labels+ chartArea.selectAll(".threshold-label")+ .attr("x", (d: any) => transform.applyX(xScale(d.value)));+ }}// Update histogram bars on zoomexport function updateHistogramBarsOnZoom(- chartArea: d3.Selection<SVGGElement, unknown, null, undefined>,- selector: string,- transform: d3.ZoomTransform,- xScale: d3.ScaleLinear<number, number>,- yScale: d3.ScaleLinear<number, number>,- height: number+ chartArea: d3.Selection<SVGGElement, unknown, null, undefined>,+ selector: string,+ transform: d3.ZoomTransform,+ xScale: d3.ScaleLinear<number, number>,+ yScale: d3.ScaleLinear<number, number>,+ height: number) {- chartArea.selectAll(selector)- .attr("x", (d: any) => transform.applyX(xScale(d.x0)))- .attr("y", (d: any) => transform.applyY(yScale(d.density)))- .attr("width", (d: any) => Math.max(0, transform.k * (xScale(d.x1) - xScale(d.x0)) - 1))- .attr("height", (d: any) => height - transform.applyY(yScale(d.density)));+ chartArea.selectAll(selector)+ .attr("x", (d: any) => transform.applyX(xScale(d.x0)))+ .attr("y", (d: any) => transform.applyY(yScale(d.density)))+ .attr("width", (d: any) => Math.max(0, transform.k * (xScale(d.x1) - xScale(d.x0)) - 1))+ .attr("height", (d: any) => height - transform.applyY(yScale(d.density)));}// Update time series lines on zoomexport function updateTimeSeriesOnZoom(- chartArea: d3.Selection<SVGGElement, unknown, null, undefined>,- transform: d3.ZoomTransform,- xScale: d3.ScaleTime<number, number>,- yScale: d3.ScaleLinear<number, number>+ chartArea: d3.Selection<SVGGElement, unknown, null, undefined>,+ transform: d3.ZoomTransform,+ xScale: d3.ScaleTime<number, number>,+ yScale: d3.ScaleLinear<number, number>) {- // Update line paths-chartArea.selectAll("path")- .attr("d", (data) =>- d3.line<any>()- .x(d => transform.applyX(xScale(new Date(d.timestamp))))- .y(d => transform.applyY(yScale(d.value)))- .curve(d3.curveLinear)(data as any)- );- // Update data points- chartArea.selectAll("circle")- .attr("cx", (d: any) => transform.applyX(xScale(new Date(d.timestamp))))- .attr("cy", (d: any) => transform.applyY(yScale(d.value)));+ // Update line paths+ chartArea.selectAll("path")+ .attr("d", (data) =>+ d3.line<any>()+ .x(d => transform.applyX(xScale(new Date(d.timestamp))))+ .y(d => transform.applyY(yScale(d.value)))+ .curve(d3.curveLinear)(data as any)+ );+ // Update data points+ chartArea.selectAll("circle")+ .attr("cx", (d: any) => transform.applyX(xScale(new Date(d.timestamp))))+ .attr("cy", (d: any) => transform.applyY(yScale(d.value)));}diff --git a/freemocap-ui/src/components/mocap-task-panel/MocapTaskTreeItem.tsx b/freemocap-ui/src/components/mocap-task-panel/MocapTaskTreeItem.tsxnew file mode 100644index 00000000..d373c737--- /dev/null+++ b/freemocap-ui/src/components/mocap-task-panel/MocapTaskTreeItem.tsx@@ -0,0 +1,352 @@+// components/MocapTaskTreeItem.tsx+import React, {useCallback, useMemo, useState} from 'react';+import {+ Alert,+ Box,+ Button,+ Chip,+ IconButton,+ InputAdornment,+ Stack,+ TextField,+ Tooltip,+ Typography,+ useTheme,+} from '@mui/material';+import {TreeItem} from '@mui/x-tree-view/TreeItem';+import DirectionsRunIcon from '@mui/icons-material/DirectionsRun';+import PlayArrowIcon from '@mui/icons-material/PlayArrow';+import StopIcon from '@mui/icons-material/Stop';+import FolderOpenIcon from '@mui/icons-material/FolderOpen';+import ClearIcon from '@mui/icons-material/Clear';+import CheckCircleIcon from '@mui/icons-material/CheckCircle';+import InfoIcon from '@mui/icons-material/Info';+import CloseIcon from '@mui/icons-material/Close';+import {useMocap} from '@/hooks/useMocap';+import {useElectronIPC} from '@/services';+import ExpandMoreIcon from "@mui/icons-material/ExpandMore";+import ChevronRightIcon from "@mui/icons-material/ChevronRight";+import {SimpleTreeView} from "@mui/x-tree-view";+++export const MocapTaskTreeItem: React.FC = () => {+ const theme = useTheme();+ const [localError, setLocalError] = useState<string | null>(null);+ const [expandedItems, setExpandedItems] = useState<string[]>([+ 'pipeline-main',+ 'calibration-intrinsic',+ 'calibration-extrinsic',+ 'mocap-task'+ ]);+ const handleExpandedItemsChange = (+ event: React.SyntheticEvent,+ itemIds: string[]+ ): void => {+ setExpandedItems(itemIds);+ };+ const { api, isElectron } = useElectronIPC();++ const {+ config,+ error,+ isLoading,+ isRecording,+ recordingProgress,+ canStartRecording,+ canProcessMocapRecording,+ mocapRecordingPath,+ directoryInfo,+ isUsingManualPath,+ updateMocapConfig,+ dispatchStopMocapRecording,+ dispatchStartMocapRecording,+ setManualRecordingPath,+ clearManualRecordingPath,+ dispatchProcessMocapRecording,+ clearError,+ } = useMocap();+++++ const handleClearError = useCallback((): void => {+ clearError();+ setLocalError(null);+ }, [clearError]);++++ const handleSelectDirectory = async (): Promise<void> => {+ if (!isElectron || !api) {+ console.warn('Electron API not available');+ return;+ }++ try {+ const result: string | null = await api.fileSystem.selectDirectory.mutate();+ if (result) {+ await setManualRecordingPath(result);+ }+ } catch (error) {+ console.error('Failed to select directory:', error);+ setLocalError('Failed to select directory');+ }+ };++ const handlePathInputChange = async (e: React.ChangeEvent<HTMLInputElement>): Promise<void> => {+ const newPath: string = e.target.value;++ // Handle tilde expansion for home directory+ if (newPath.includes('~') && isElectron && api) {+ try {+ const home: string = await api.fileSystem.getHomeDirectory.query();+ const expanded: string = newPath.replace(/^~([\/\\])?/, home ? `${home}$1` : '');+ await setManualRecordingPath(expanded);+ } catch (error) {+ console.error('Failed to expand home directory:', error);+ await setManualRecordingPath(newPath);+ }+ } else {+ await setManualRecordingPath(newPath);+ }+ };++ const handleClearManualPath = useCallback((): void => {+ clearManualRecordingPath();+ }, [clearManualRecordingPath]);++ const displayError = error || localError || directoryInfo?.errorMessage;++ // Helper text for the path input+ const pathHelperText = useMemo(() => {+ if (isUsingManualPath) {+ return 'Using custom path';+ }+ return 'Using default recording directory';+ }, [isUsingManualPath]);++ return (+ <SimpleTreeView+ expandedItems={expandedItems}+ onExpandedItemsChange={handleExpandedItemsChange}+ slots={{+ collapseIcon: ExpandMoreIcon,+ expandIcon: ChevronRightIcon,+ }}+ sx={{ flexGrow: 1 }}+ >+ <TreeItem+ itemId="mocap-task"+ label={+ <Box sx={{ display: 'flex', alignItems: 'center', py: 1, pr: 1 }}>+ <DirectionsRunIcon sx={{ mr: 1, color: theme.palette.secondary.main }} />+ <Typography variant="subtitle1" sx={{ flexGrow: 1 }}>+ Motion Capture+ </Typography>+ </Box>+ }+ >+ <Box sx={{ p: 2, bgcolor: 'background.paper' }}>+ <Stack spacing={2}>+ {/* Error Display */}+ {displayError && (+ <Alert severity="error" onClose={handleClearError}>+ {displayError}+ </Alert>+ )}++ {/* Mocap Recording Path Input */}+ <Box>++ {/* Recording Controls */}+ <Stack direction="row" spacing={2} sx={{ mb: 2 }}>+ <Button+ variant="contained"+ color="primary"+ startIcon={<PlayArrowIcon />}+ onClick={dispatchStartMocapRecording}+ disabled={!canStartRecording || isLoading}+ fullWidth+ >+ Start Mocap Recording+ </Button>+ {isRecording && (+ <Button+ variant="contained"+ color="error"+ startIcon={<StopIcon />}+ onClick={dispatchStopMocapRecording}+ disabled={isLoading}+ fullWidth+ >+ Stop Recording+ </Button>+ )}+ </Stack>+ <TextField+ label="Mocap Recording Path"+ value={mocapRecordingPath}+ onChange={handlePathInputChange}+ fullWidth+ size="small"+ helperText={pathHelperText}+ InputProps={{+ endAdornment: (+ <InputAdornment position="end">+ {isUsingManualPath && (+ <Tooltip title="Clear manual path (revert to default)">+ <IconButton+ onClick={handleClearManualPath}+ edge="end"+ size="small"+ >+ <ClearIcon fontSize="small" />+ </IconButton>+ </Tooltip>+ )}+ <Tooltip title="Select directory">+ <IconButton+ onClick={handleSelectDirectory}+ edge="end"+ disabled={!isElectron}+ >+ <FolderOpenIcon />+ </IconButton>+ </Tooltip>+ </InputAdornment>+ ),+ }}+ />+ </Box>++ {/* Directory Status Info */}+ {directoryInfo && (+ <Box sx={{+ p: 1.5,+ borderRadius: 1,+ border: `2px solid ${theme.palette.divider}`+ }}>+ <Stack spacing={1}>+ <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>+ <InfoIcon fontSize="small" color="info" />+ <Typography variant="caption" fontWeight="medium">+ Mocap Folder Status+ </Typography>+ </Box>++ <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>+ <Chip+ label={directoryInfo.exists ? "Directory exists" : "Directory will be created"}+ size="small"+ color={directoryInfo.exists ? "success" : "default"}+ icon={directoryInfo.exists ? <CheckCircleIcon /> : <CloseIcon />}+ variant={directoryInfo.exists ? "filled" : "outlined"}+ sx={!directoryInfo.exists ? {+ borderColor: theme.palette.grey[400],+ '& .MuiChip-icon': { color: theme.palette.grey[600] }+ } : {}}+ />++ <Chip+ label="Has videos"+ size="small"+ color={directoryInfo.hasVideos ? "success" : "default"}+ icon={directoryInfo.hasVideos ? <CheckCircleIcon /> : <CloseIcon />}+ variant={directoryInfo.hasVideos ? "filled" : "outlined"}+ sx={!directoryInfo.hasVideos ? {+ borderColor: theme.palette.grey[400],+ '& .MuiChip-icon': { color: theme.palette.grey[600] }+ } : {}}+ />++ <Chip+ label="Has synchronized_videos"+ size="small"+ color={directoryInfo.hasSynchronizedVideos ? "success" : "default"}+ icon={directoryInfo.hasSynchronizedVideos ? <CheckCircleIcon /> : <CloseIcon />}+ variant={directoryInfo.hasSynchronizedVideos ? "filled" : "outlined"}+ sx={!directoryInfo.hasSynchronizedVideos ? {+ borderColor: theme.palette.grey[400],+ '& .MuiChip-icon': { color: theme.palette.grey[600] }+ } : {}}+ />++ <Chip+ label="Has calibration TOML"+ size="small"+ color={directoryInfo.cameraMocapTomlPath ? "success" : "default"}+ icon={directoryInfo.cameraMocapTomlPath ? <CheckCircleIcon /> : <CloseIcon />}+ variant={directoryInfo.cameraMocapTomlPath ? "filled" : "outlined"}+ sx={!directoryInfo.cameraMocapTomlPath ? {+ borderColor: theme.palette.grey[400],+ '& .MuiChip-icon': { color: theme.palette.grey[600] }+ } : {}}+ />+ </Box>++ {directoryInfo.cameraMocapTomlPath && (+ <Box sx={{ mt: 1 }}>+ <Typography variant="caption" color="text.secondary">+ Found calibration file:+ </Typography>+ <Typography+ variant="caption"+ sx={{+ fontFamily: 'monospace',+ display: 'block',+ color: 'success.main',+ wordBreak: 'break-all'+ }}+ >+ {directoryInfo.cameraMocapTomlPath}+ </Typography>+ </Box>+ )}+ </Stack>+ </Box>+ )}+++ {/* Recording Progress */}+ {isRecording && (+ <Box sx={{ width: '100%' }}>+ <Typography variant="caption" color="text.secondary" gutterBottom>+ Recording in Progress: {recordingProgress.toFixed(0)}%+ </Typography>+ <Box+ sx={{+ width: '100%',+ height: 8,+ bgcolor: 'grey.300',+ borderRadius: 1,+ overflow: 'hidden',+ }}+ >+ <Box+ sx={{+ width: `${recordingProgress}%`,+ height: '100%',+ bgcolor: theme.palette.primary.main,+ transition: 'width 0.3s',+ }}+ />+ </Box>+ </Box>+ )}++ {/* Process Recording Button */}+ <Button+ variant="contained"+ color="secondary"+ onClick={dispatchProcessMocapRecording}+ // disabled={!canProcessMocapRecording || isLoading}+ fullWidth+ >+ Process Selected Recording+ </Button>+ </Stack>+ </Box>+ </TreeItem>+ </SimpleTreeView>+ );+};diff --git a/freemocap-ui/src/components/processing-pipeline-panel/PipelineConnectionStatus.tsx b/freemocap-ui/src/components/processing-pipeline-panel/PipelineConnectionStatus.tsxindex 83a8eabe..9c658847 100644--- a/freemocap-ui/src/components/processing-pipeline-panel/PipelineConnectionStatus.tsx+++ b/freemocap-ui/src/components/processing-pipeline-panel/PipelineConnectionStatus.tsx@@ -1,27 +1,44 @@-import {Box, Typography} from "@mui/material";+import {Box, CircularProgress, Typography} from "@mui/material";import CheckIcon from '@mui/icons-material/Check';import CloseIcon from '@mui/icons-material/Close';-import {useState} from "react";-import {connectPipelineThunk, disconnectPipelineThunk} from "@/store/thunks/connect-pipeline-thunk";-import {useAppDispatch} from "@/store/AppStateStore";+import {useAppDispatch, useAppSelector} from "@/store/hooks";+import {+ closePipeline,+ connectRealtimePipeline,+ selectCanConnectPipeline,+ selectCanDisconnectPipeline,+ selectIsPipelineConnected,+ selectIsPipelineLoading,+ selectPipelineError,+ selectPipelineId,+} from "@/store/slices/pipeline";export const PipelineConnectionStatus = () => {const dispatch = useAppDispatch();- const [isConnected, setIsConnected] = useState(false);- const [pipelineId, setPipelineId] = useState<string | null>(null);- const handleToggleConnection = async () => {+ const isConnected = useAppSelector(selectIsPipelineConnected);+ const pipelineId = useAppSelector(selectPipelineId);+ const isLoading = useAppSelector(selectIsPipelineLoading);+ const error = useAppSelector(selectPipelineError);+ const canConnect = useAppSelector(selectCanConnectPipeline);+ const canDisconnect = useAppSelector(selectCanDisconnectPipeline);++ const handleToggleConnection = async (e: React.MouseEvent) => {+ e.stopPropagation();++ if (isLoading) return;+if (isConnected) {console.log('Disconnecting from pipeline');- await dispatch(disconnectPipelineThunk());+ await dispatch(closePipeline());} else {console.log('Connecting to pipeline');- const pipelineIdConnected = await dispatch(connectPipelineThunk());- setPipelineId(pipelineIdConnected.payload as string);+ await dispatch(connectRealtimePipeline(undefined));}- setIsConnected(!isConnected);};+ const isClickable = canConnect || canDisconnect;+return (<Boxsx={{@@ -30,16 +47,17 @@ export const PipelineConnectionStatus = () => {padding: '10px',flexDirection: 'column',pl: 4,- cursor: 'pointer',+ cursor: isClickable ? 'pointer' : 'not-allowed',border: '4px solid rgb(0, 125, 125)',backgroundColor: isConnected ? '#005d94' : '#395067',borderRadius: '8px',- ':hover': {+ opacity: isClickable ? 1 : 0.6,+ ':hover': isClickable ? {backgroundColor: 'rgba(255, 255, 255, 0.05)',- borderColor: 'rgb(0,225, 225)',- },+ borderColor: 'rgb(0, 225, 225)',+ } : {},}}- onClick={handleToggleConnection}+ onClick={isClickable ? handleToggleConnection : undefined}><Typographyvariant="body1"@@ -55,7 +73,7 @@ export const PipelineConnectionStatus = () => {width: '24px',height: '24px',marginRight: '8px',- cursor: 'pointer',+ cursor: isClickable ? 'pointer' : 'not-allowed',borderRadius: '4px',transition: 'background-color 0.3s, border-color 0.3s',backgroundColor: isConnected ? 'rgba(0, 255, 255, 0.1)' : 'rgba(255, 0, 0, 0.1)',@@ -65,20 +83,28 @@ export const PipelineConnectionStatus = () => {alignItems: 'center',padding: '4px',justifyContent: 'center',- '&:hover': {+ '&:hover': isClickable ? {backgroundColor: 'rgba(255, 255, 255, 0.05)',borderColor: 'rgba(255, 255, 255, 0.2)',- },+ } : {},}}>- {isConnected ? (+ {isLoading ? (+ <CircularProgress size={16} sx={{ color: 'cyan' }} />+ ) : isConnected ? (<CheckIcon sx={{ color: 'green' }} />) : (<CloseIcon fontSize="small" sx={{ color: 'red' }} />)}</Box>- Pipeline: {isConnected ? `connected (id:${pipelineId})` : 'disconnected'}+ Pipeline: {isConnected ? `connected (id: ${pipelineId})` : 'disconnected'}+ {error && (+ <Typography variant="caption" color="error" sx={{ ml: 1 }}>+ {error}+ </Typography>+ )}</Typography></Box>);};+export default PipelineConnectionStatus;diff --git a/freemocap-ui/src/components/processing-pipeline-panel/ProcessingPipelinePanel.tsx b/freemocap-ui/src/components/processing-pipeline-panel/ProcessingPipelinePanel.tsxindex 93e1f4b5..bb91a72b 100644--- a/freemocap-ui/src/components/processing-pipeline-panel/ProcessingPipelinePanel.tsx+++ b/freemocap-ui/src/components/processing-pipeline-panel/ProcessingPipelinePanel.tsx@@ -1,23 +1,28 @@-import React from "react";-import {Box, Button, Typography, useTheme} from "@mui/material";+import React, {useState} from "react";+import {Box, Typography, useTheme} from "@mui/material";import {SimpleTreeView} from "@mui/x-tree-view/SimpleTreeView";import {TreeItem} from "@mui/x-tree-view/TreeItem";import ExpandMoreIcon from "@mui/icons-material/ExpandMore";import ChevronRightIcon from "@mui/icons-material/ChevronRight";-import {useAppDispatch} from "@/store/AppStateStore";-import {- StartStopRecordingButton-} from "@/components/recording-info-panel/recording-subcomponents/StartStopRecordingButton";-import {RecordingPathTreeItem} from "@/components/recording-info-panel/RecordingPathTreeItem";import LanIcon from '@mui/icons-material/Lan';-import {- FullRecordingPathPreview-} from "@/components/recording-info-panel/recording-subcomponents/FullRecordingPathPreview";import PipelineConnectionStatus from "@/components/processing-pipeline-panel/PipelineConnectionStatus";+import {RecordingInfoPanel} from "@/components/recording-info-panel/RecordingInfoPanel";export const ProcessingPipelinePanel: React.FC = () => {const theme = useTheme();- const dispatch = useAppDispatch();+ const [expandedItems, setExpandedItems] = useState<string[]>([+ 'pipeline-main',+ 'calibration-intrinsic',+ 'calibration-extrinsic',+ 'mocap-task'+ ]);++ const handleExpandedItemsChange = (+ event: React.SyntheticEvent,+ itemIds: string[]+ ): void => {+ setExpandedItems(itemIds);+ };return (<Box@@ -29,35 +34,34 @@ export const ProcessingPipelinePanel: React.FC = () => {}}><SimpleTreeView+ expandedItems={expandedItems}+ onExpandedItemsChange={handleExpandedItemsChange}slots={{collapseIcon: ExpandMoreIcon,expandIcon: ChevronRightIcon,}}- sx={{flexGrow: 1}}+ sx={{ flexGrow: 1 }}><TreeItem- itemId="calibration-pipeline-main"+ itemId="pipeline-main"label={<Boxsx={{display: "flex",alignItems: "center",width: "100%",- r: 2,+ py: 1,}}>- <LanIcon sx={{transform: 'scaleY(-1.3) scaleX(1.25)'}}/>+ <LanIcon sx={{ transform: 'scaleY(-1.05) scaleX(1)' }} />- <Typography sx={{pl: 1, flexGrow: 1}} variant="h6" component="div">- Data Processing+ <Typography sx={{ pl: 1, flexGrow: 1 }} variant="h6" component="div">+ Realtime Pipeline</Typography>- <PipelineConnectionStatus/>+ <PipelineConnectionStatus /></Box>}>- <Box sx={{display: 'flex', alignItems: 'center', gap: 1}}>- tree stuff- </Box></TreeItem></SimpleTreeView></Box>diff --git a/freemocap-ui/src/components/recording-info-panel/RecordingControlsTreeSection.tsx b/freemocap-ui/src/components/recording-info-panel/RecordingControlsTreeSection.tsxindex 84f1ef8e..b05994c8 100644--- a/freemocap-ui/src/components/recording-info-panel/RecordingControlsTreeSection.tsx+++ b/freemocap-ui/src/components/recording-info-panel/RecordingControlsTreeSection.tsx@@ -1,91 +1,94 @@import React from 'react';-import { Box } from '@mui/material';-import { DelayRecordingStartControl } from "@/components/recording-info-panel/recording-subcomponents/DelayRecordingStartControl";-import { BaseRecordingDirectoryInput } from "@/components/recording-info-panel/recording-subcomponents/BaseRecordingDirectoryInput";-import { RecordingNamePreview } from "@/components/recording-info-panel/recording-subcomponents/RecordingNamePreview";-import { RecordingSettingsSection } from "@/components/recording-info-panel/recording-subcomponents/RecordingSettingsSection";+import {Box} from '@mui/material';+import {+ DelayRecordingStartControl+} from "@/components/recording-info-panel/recording-subcomponents/DelayRecordingStartControl";+import {+ BaseRecordingDirectoryInput+} from "@/components/recording-info-panel/recording-subcomponents/BaseRecordingDirectoryInput";+import {RecordingNamePreview} from "@/components/recording-info-panel/recording-subcomponents/RecordingNamePreview";+import {+ RecordingSettingsSection+} from "@/components/recording-info-panel/recording-subcomponents/RecordingSettingsSection";interface RecordingControlsSectionProps {- recordingDirectory: string;- recordingName: string;- recordingTag: string;- useDelayStart: boolean;- delaySeconds: number;- useTimestamp: boolean;- baseName: string;- useIncrement: boolean;- currentIncrement: number;- createSubfolder: boolean;- customSubfolderName: string;- isRecording: boolean;- onDelayToggle: (value: boolean) => void;- onDelayChange: (value: number) => void;- onTagChange: (value: string) => void;- onUseTimestampChange: (value: boolean) => void;- onBaseNameChange: (value: string) => void;- onUseIncrementChange: (value: boolean) => void;- onIncrementChange: (value: number) => void;- onCreateSubfolderChange: (value: boolean) => void;- onCustomSubfolderNameChange: (value: string) => void;+ recordingDirectory: string;+ recordingTag: string;+ useDelayStart: boolean;+ delaySeconds: number;+ useTimestamp: boolean;+ baseName: string;+ useIncrement: boolean;+ currentIncrement: number;+ createSubfolder: boolean;+ customSubfolderName: string;+ isRecording: boolean;+ onDelayToggle: (value: boolean) => void;+ onDelayChange: (value: number) => void;+ onTagChange: (value: string) => void;+ onUseTimestampChange: (value: boolean) => void;+ onBaseNameChange: (value: string) => void;+ onUseIncrementChange: (value: boolean) => void;+ onIncrementChange: (value: number) => void;+ onCreateSubfolderChange: (value: boolean) => void;+ onCustomSubfolderNameChange: (value: string) => void;}export const RecordingControlsSection: React.FC<RecordingControlsSectionProps> = ({- recordingDirectory,- recordingName,- recordingTag,- useDelayStart,- delaySeconds,- useTimestamp,- baseName,- useIncrement,- currentIncrement,- createSubfolder,- customSubfolderName,- isRecording,- onDelayToggle,- onDelayChange,- onTagChange,- onUseTimestampChange,- onBaseNameChange,- onUseIncrementChange,- onIncrementChange,- onCreateSubfolderChange,- onCustomSubfolderNameChange-}) => {- return (- <Box sx={{ pl: 2, pt: 1, display: 'flex', flexDirection: 'column', gap: 2 }}>- <DelayRecordingStartControl- useDelay={useDelayStart}- delaySeconds={delaySeconds}- onDelayToggle={onDelayToggle}- onDelayChange={onDelayChange}- />+ recordingDirectory,+ recordingTag,+ useDelayStart,+ delaySeconds,+ useTimestamp,+ baseName,+ useIncrement,+ currentIncrement,+ createSubfolder,+ customSubfolderName,+ isRecording,+ onDelayToggle,+ onDelayChange,+ onTagChange,+ onUseTimestampChange,+ onBaseNameChange,+ onUseIncrementChange,+ onIncrementChange,+ onCreateSubfolderChange,+ onCustomSubfolderNameChange+ }) => {+ return (+ <Box sx={{pl: 2, pt: 1, display: 'flex', flexDirection: 'column', gap: 2}}>+ <DelayRecordingStartControl+ useDelay={useDelayStart}+ delaySeconds={delaySeconds}+ onDelayToggle={onDelayToggle}+ onDelayChange={onDelayChange}+ />- <BaseRecordingDirectoryInput- value={recordingDirectory}- />+ <BaseRecordingDirectoryInput+ baseRecordingFolder={recordingDirectory}+ />- <RecordingNamePreview- name={recordingName}- tag={recordingTag}- isRecording={isRecording}- onTagChange={onTagChange}- />+ <RecordingNamePreview+ tag={recordingTag}+ isRecording={isRecording}+ onTagChange={onTagChange}+ />- <RecordingSettingsSection- useTimestamp={useTimestamp}- baseName={baseName}- useIncrement={useIncrement}- currentIncrement={currentIncrement}- createSubfolder={createSubfolder}- customSubfolderName={customSubfolderName}- onUseTimestampChange={onUseTimestampChange}- onBaseNameChange={onBaseNameChange}- onUseIncrementChange={onUseIncrementChange}- onIncrementChange={onIncrementChange}- onCreateSubfolderChange={onCreateSubfolderChange}- onCustomSubfolderNameChange={onCustomSubfolderNameChange}- />- </Box>- );-};\ No newline at end of file+ <RecordingSettingsSection+ useTimestamp={useTimestamp}+ baseName={baseName}+ useIncrement={useIncrement}+ currentIncrement={currentIncrement}+ createSubfolder={createSubfolder}+ customSubfolderName={customSubfolderName}+ onUseTimestampChange={onUseTimestampChange}+ onBaseNameChange={onBaseNameChange}+ onUseIncrementChange={onUseIncrementChange}+ onIncrementChange={onIncrementChange}+ onCreateSubfolderChange={onCreateSubfolderChange}+ onCustomSubfolderNameChange={onCustomSubfolderNameChange}+ />+ </Box>+ );+};diff --git a/freemocap-ui/src/components/recording-info-panel/RecordingInfoPanel.tsx b/freemocap-ui/src/components/recording-info-panel/RecordingInfoPanel.tsxindex 80843143..2c26ae2a 100644--- a/freemocap-ui/src/components/recording-info-panel/RecordingInfoPanel.tsx+++ b/freemocap-ui/src/components/recording-info-panel/RecordingInfoPanel.tsx@@ -5,47 +5,98 @@ import {TreeItem} from "@mui/x-tree-view/TreeItem";import ExpandMoreIcon from "@mui/icons-material/ExpandMore";import ChevronRightIcon from "@mui/icons-material/ChevronRight";import VideocamIcon from "@mui/icons-material/Videocam";-import {useAppDispatch, useAppSelector} from "@/store/AppStateStore";+import {recordingInfoUpdated, startRecording, stopRecording, useAppDispatch, useAppSelector} from "@/store";import {StartStopRecordingButton} from "@/components/recording-info-panel/recording-subcomponents/StartStopRecordingButton";-import {startRecording, stopRecording,} from "@/store/thunks/start-stop-recording-thunks";-import {setRecordingInfo} from "@/store/slices/recordingInfoSlice";+import {useElectronIPC} from "@/services";import {RecordingPathTreeItem} from "@/components/recording-info-panel/RecordingPathTreeItem";++interface RecordingOperation {+ type: 'start' | 'stop';+ timestamp: number;+}+export const RecordingInfoPanel: React.FC = () => {const theme = useTheme();const dispatch = useAppDispatch();const recordingInfo = useAppSelector(- (state) => state.recordingStatus.currentRecordingInfo+ (state) => state.recording);// Local UI state- const [createSubfolder, setCreateSubfolder] = useState(false);- const [useDelayStart, setUseDelayStart] = useState(false);- const [delaySeconds, setDelaySeconds] = useState(3);+ const [createSubfolder, setCreateSubfolder] = useState<boolean>(false);+ const [useDelayStart, setUseDelayStart] = useState<boolean>(false);+ const [delaySeconds, setDelaySeconds] = useState<number>(3);const [countdown, setCountdown] = useState<number | null>(null);+ // Track pending operation and recording start time+ const [pendingOperation, setPendingOperation] = useState<RecordingOperation | null>(null);+ const [recordingStartTime, setRecordingStartTime] = useState<number | null>(null);+// Local recording naming- const [useTimestamp, setUseTimestamp] = useState(true);- const [useIncrement, setUseIncrement] = useState(false);- const [currentIncrement, setCurrentIncrement] = useState(1);- const [baseName, setBaseName] = useState("recording");- const [customSubfolderName, setCustomSubfolderName] = useState("");- const [recordingTag, setRecordingTag] = useState("");+ const [useTimestamp, setUseTimestamp] = useState<boolean>(true);+ const [useIncrement, setUseIncrement] = useState<boolean>(false);+ const [currentIncrement, setCurrentIncrement] = useState<number>(1);+ const [baseName, setBaseName] = useState<string>("recording");+ const [customSubfolderName, setCustomSubfolderName] = useState<string>("");+ const [recordingTag, setRecordingTag] = useState<string>("");+ const {isElectron, api} = useElectronIPC();++ // Track when recording state changes to clear pending state+ useEffect(() => {+ if (pendingOperation) {+ const isNowRecording = recordingInfo.isRecording;+ const wasStarting = pendingOperation.type === 'start';+ const wasStopping = pendingOperation.type === 'stop';++ // Clear pending if state changed as expected+ if ((wasStarting && isNowRecording) || (wasStopping && !isNowRecording)) {+ setPendingOperation(null);++ // Set or clear recording start time+ if (wasStarting && isNowRecording) {+ setRecordingStartTime(Date.now());+ } else if (wasStopping && !isNowRecording) {+ setRecordingStartTime(null);+ }+ }++ // Timeout fallback - clear pending after 5 seconds if thunk hasn't responded+ const timeoutMs = 5000;+ const elapsed = Date.now() - pendingOperation.timestamp;+ if (elapsed > timeoutMs) {+ console.error(`Recording ${pendingOperation.type} operation timed out after ${timeoutMs}ms`);+ setPendingOperation(null);+ }+ }+ }, [recordingInfo.isRecording, pendingOperation]);++ // Set initial recording start time if already recording on mount+ useEffect(() => {+ if (recordingInfo.isRecording && !recordingStartTime) {+ setRecordingStartTime(Date.now());+ }+ }, []);// replace ~ with user's home directoryuseEffect(() => {- if (recordingInfo?.recordingDirectory?.startsWith("~")) {- window.electronAPI.getHomeDirectory().then((homePath: string) => {- const updatedDirectory = recordingInfo.recordingDirectory.replace(- "~",- homePath- );- dispatch(setRecordingInfo({recordingDirectory: updatedDirectory}));- });+ if (recordingInfo?.recordingDirectory?.startsWith("~") && isElectron && api) {+ api.fileSystem.getHomeDirectory.query()+ .then((homePath: string) => {+ const updatedDirectory = recordingInfo.recordingDirectory.replace(+ "~",+ homePath+ );+ dispatch(recordingInfoUpdated({recordingDirectory: updatedDirectory}));+ })+ .catch((error: unknown) => {+ console.error("Failed to get home directory:", error);+ throw error; // Fail loudly as per preferences+ });}- }, [recordingInfo, dispatch]);+ }, [recordingInfo.recordingDirectory, isElectron, api, dispatch]);// Handle countdown timeruseEffect(() => {@@ -61,7 +112,6 @@ export const RecordingInfoPanel: React.FC = () => {const getTimestampString = (): string => {const now = new Date();- // Format date in local time with timezone infoconst dateOptions: Intl.DateTimeFormatOptions = {year: "numeric",month: "2-digit",@@ -73,40 +123,35 @@ export const RecordingInfoPanel: React.FC = () => {timeZoneName: "shortOffset",};- // Get formatted partsconst formatter = new Intl.DateTimeFormat("en-US", dateOptions);const parts = formatter.formatToParts(now);- // Create a map of the parts for easy accessconst partMap: Record<string, string> = {};parts.forEach((part) => {partMap[part.type] = part.value;});- // Build the timestamp string in a filename-friendly format- const timestamp = `${partMap.year}-${partMap.month}-${partMap.day}_${+ return `${partMap.year}-${partMap.month}-${partMap.day}_${partMap.hour}-${partMap.minute}-${partMap.second}_${partMap.timeZoneName.replace(":","")}`;-- return timestamp;};- const handleRecordingTagChange = (tag: string) => {++ const handleRecordingTagChange = (tag: string): void => {setRecordingTag(tag);};+const buildRecordingName = (): string => {const parts: string[] = [];- // Base name componentif (useTimestamp) {parts.push(getTimestampString());} else {parts.push(baseName);}- // Add tag if presentif (recordingTag) {parts.push(recordingTag);}@@ -114,7 +159,7 @@ export const RecordingInfoPanel: React.FC = () => {return parts.join("_");};- const handleStartRecording = () => {+ const handleStartRecording = async (): Promise<void> => {console.log("Starting recording...");const recordingName = buildRecordingName();@@ -132,23 +177,45 @@ export const RecordingInfoPanel: React.FC = () => {setCurrentIncrement((prev) => prev + 1);}- dispatch(- startRecording({- recordingName,- recordingDirectory: recordingPath,- })- );+ // Set pending state before dispatching+ setPendingOperation({ type: 'start', timestamp: Date.now() });++ try {+ await dispatch(+ startRecording({+ recordingName,+ recordingDirectory: recordingPath,+ })+ ).unwrap();+ } catch (error) {+ console.error("Failed to start recording:", error);+ setPendingOperation(null);+ throw error; // Fail loudly as per preferences+ }};- const handleRecordButtonClick = () => {+ const handleRecordButtonClick = async (): Promise<void> => {+ // Don't allow clicking while pending+ if (pendingOperation) {+ return;+ }+if (recordingInfo.isRecording) {console.log("Stopping recording...");- dispatch(stopRecording());+ setPendingOperation({ type: 'stop', timestamp: Date.now() });++ try {+ await dispatch(stopRecording()).unwrap();+ } catch (error) {+ console.error("Failed to stop recording:", error);+ setPendingOperation(null);+ throw error; // Fail loudly as per preferences+ }} else if (useDelayStart) {console.log(`Starting countdown from ${delaySeconds} seconds`);setCountdown(delaySeconds);} else {- handleStartRecording();+ await handleStartRecording();}};@@ -163,7 +230,8 @@ export const RecordingInfoPanel: React.FC = () => {color: "text.primary",backgroundColor: theme.palette.primary.main,borderRadius: 1,- mb: 2,+ mx: 1,+ my: 0.5,}}><SimpleTreeView@@ -172,7 +240,17 @@ export const RecordingInfoPanel: React.FC = () => {collapseIcon: ExpandMoreIcon,expandIcon: ChevronRightIcon,}}- sx={{flexGrow: 1}}+ sx={{+ flexGrow: 1,+ '& .MuiTreeItem-content': {+ padding: '2px 4px',+ margin: '1px 0',+ },+ '& .MuiTreeItem-label': {+ fontSize: 13,+ padding: '1px 0',+ },+ }}><TreeItemitemId="recording-main"@@ -181,36 +259,30 @@ export const RecordingInfoPanel: React.FC = () => {sx={{display: "flex",alignItems: "center",- // justifyContent: "space-between",width: "100%",- r: 2,+ py: 0.25,}}>- <VideocamIcon/>- <Typography sx={{pl: 1, flexGrow: 1}} variant="h6" component="div">- Record Videos+ <VideocamIcon sx={{ fontSize: 16, mr: 0.5 }} />+ <Typography sx={{ flexGrow: 1, fontSize: 13, fontWeight: 500 }}>+ Record</Typography>-- <Box sx={{display: "flex", flexGrow:1, pl: 2, alignItems: "left"}}>- <StartStopRecordingButton- isRecording={recordingInfo.isRecording}- countdown={countdown}- onClick={handleRecordButtonClick}- />- </Box>--+ <StartStopRecordingButton+ isRecording={recordingInfo.isRecording}+ isPending={pendingOperation !== null}+ countdown={countdown}+ recordingStartTime={recordingStartTime}+ onClick={handleRecordButtonClick}+ /></Box>}-><RecordingPathTreeItemrecordingDirectory={recordingInfo.recordingDirectory}recordingName={recordingName}subfolder={subfolderName}countdown={countdown}- // Pass down all the control propsrecordingTag={recordingTag}useDelayStart={useDelayStart}delaySeconds={delaySeconds}diff --git a/freemocap-ui/src/components/recording-info-panel/RecordingPathTreeItem.tsx b/freemocap-ui/src/components/recording-info-panel/RecordingPathTreeItem.tsxindex 7344158f..92eb5578 100644--- a/freemocap-ui/src/components/recording-info-panel/RecordingPathTreeItem.tsx+++ b/freemocap-ui/src/components/recording-info-panel/RecordingPathTreeItem.tsx@@ -1,107 +1,103 @@import React from 'react';-import { Box, Typography } from '@mui/material';-import { TreeItem } from '@mui/x-tree-view/TreeItem';-import { FullRecordingPathPreview } from "@/components/recording-info-panel/recording-subcomponents/FullRecordingPathPreview";-import { RecordingControlsSection } from "@/components/recording-info-panel/RecordingControlsTreeSection";+import {Box, Typography} from '@mui/material';+import {TreeItem} from '@mui/x-tree-view/TreeItem';+import {+ FullRecordingPathPreview+} from "@/components/recording-info-panel/recording-subcomponents/FullRecordingPathPreview";+import {RecordingControlsSection} from "@/components/recording-info-panel/RecordingControlsTreeSection";+import {useAppSelector} from '@/store';interface RecordingPathTreeItemProps {- recordingDirectory: string;- recordingName: string;- subfolder?: string;- countdown: number | null;- // Add all the control props- recordingTag: string;- useDelayStart: boolean;- delaySeconds: number;- useTimestamp: boolean;- baseName: string;- useIncrement: boolean;- currentIncrement: number;- createSubfolder: boolean;- customSubfolderName: string;- isRecording: boolean;- onDelayToggle: (value: boolean) => void;- onDelayChange: (value: number) => void;- onTagChange: (value: string) => void;- onUseTimestampChange: (value: boolean) => void;- onBaseNameChange: (value: string) => void;- onUseIncrementChange: (value: boolean) => void;- onIncrementChange: (value: number) => void;- onCreateSubfolderChange: (value: boolean) => void;- onCustomSubfolderNameChange: (value: string) => void;+ countdown: number | null;+ // Config props+ recordingTag: string;+ useDelayStart: boolean;+ delaySeconds: number;+ useTimestamp: boolean;+ baseName: string;+ useIncrement: boolean;+ currentIncrement: number;+ createSubfolder: boolean;+ customSubfolderName: string;+ isRecording: boolean;+ onDelayToggle: (value: boolean) => void;+ onDelayChange: (value: number) => void;+ onTagChange: (value: string) => void;+ onUseTimestampChange: (value: boolean) => void;+ onBaseNameChange: (value: string) => void;+ onUseIncrementChange: (value: boolean) => void;+ onIncrementChange: (value: number) => void;+ onCreateSubfolderChange: (value: boolean) => void;+ onCustomSubfolderNameChange: (value: string) => void;}export const RecordingPathTreeItem: React.FC<RecordingPathTreeItemProps> = ({- recordingDirectory,- recordingName,- subfolder,- countdown,- // Control props- recordingTag,- useDelayStart,- delaySeconds,- useTimestamp,- baseName,- useIncrement,- currentIncrement,- createSubfolder,- customSubfolderName,- isRecording,- onDelayToggle,- onDelayChange,- onTagChange,- onUseTimestampChange,- onBaseNameChange,- onUseIncrementChange,- onIncrementChange,- onCreateSubfolderChange,- onCustomSubfolderNameChange-}) => {- return (- <TreeItem- itemId="recording-path"- label={- <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>- <FullRecordingPathPreview- directory={recordingDirectory}- filename={recordingName}- subfolder={subfolder}- />- </Box>- }- >- <Box sx={{ pl: 2, pt: 1, display: 'flex', flexDirection: 'column', gap: 2 }}>- {/* Countdown display in controls section */}- {countdown !== null && (- <Typography variant="h4" align="center" color="secondary">- Starting in {countdown}...- </Typography>- )}+ countdown,+ // Control props+ recordingTag,+ useDelayStart,+ delaySeconds,+ useTimestamp,+ baseName,+ useIncrement,+ currentIncrement,+ createSubfolder,+ customSubfolderName,+ isRecording,+ onDelayToggle,+ onDelayChange,+ onTagChange,+ onUseTimestampChange,+ onBaseNameChange,+ onUseIncrementChange,+ onIncrementChange,+ onCreateSubfolderChange,+ onCustomSubfolderNameChange+ }) => {+ // Read computed values directly from store+ const recordingDirectory = useAppSelector((state) => state.recording.recordingDirectory);+ const computed = useAppSelector((state) => state.recording.computed);- <RecordingControlsSection- recordingDirectory={recordingDirectory}- recordingName={recordingName}- recordingTag={recordingTag}- useDelayStart={useDelayStart}- delaySeconds={delaySeconds}- useTimestamp={useTimestamp}- baseName={baseName}- useIncrement={useIncrement}- currentIncrement={currentIncrement}- createSubfolder={createSubfolder}- customSubfolderName={customSubfolderName}- isRecording={isRecording}- onDelayToggle={onDelayToggle}- onDelayChange={onDelayChange}- onTagChange={onTagChange}- onUseTimestampChange={onUseTimestampChange}- onBaseNameChange={onBaseNameChange}- onUseIncrementChange={onUseIncrementChange}- onIncrementChange={onIncrementChange}- onCreateSubfolderChange={onCreateSubfolderChange}- onCustomSubfolderNameChange={onCustomSubfolderNameChange}- />- </Box>- </TreeItem>- );-};\ No newline at end of file+ return (+ <TreeItem+ itemId="recording-path"+ label={+ <Box sx={{display: 'flex', alignItems: 'center', gap: 1}}>+ <FullRecordingPathPreview />+ </Box>+ }+ >+ <Box sx={{pl: 2, pt: 1, display: 'flex', flexDirection: 'column', gap: 2}}>+ {/* Countdown display in controls section */}+ {countdown !== null && (+ <Typography variant="h4" align="center" color="secondary">+ Starting in {countdown}...+ </Typography>+ )}++ <RecordingControlsSection+ recordingDirectory={recordingDirectory}+ recordingTag={recordingTag}+ useDelayStart={useDelayStart}+ delaySeconds={delaySeconds}+ useTimestamp={useTimestamp}+ baseName={baseName}+ useIncrement={useIncrement}+ currentIncrement={currentIncrement}+ createSubfolder={createSubfolder}+ customSubfolderName={customSubfolderName}+ isRecording={isRecording}+ onDelayToggle={onDelayToggle}+ onDelayChange={onDelayChange}+ onTagChange={onTagChange}+ onUseTimestampChange={onUseTimestampChange}+ onBaseNameChange={onBaseNameChange}+ onUseIncrementChange={onUseIncrementChange}+ onIncrementChange={onIncrementChange}+ onCreateSubfolderChange={onCreateSubfolderChange}+ onCustomSubfolderNameChange={onCustomSubfolderNameChange}+ />+ </Box>+ </TreeItem>+ );+};diff --git a/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/BaseRecordingDirectoryInput.tsx b/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/BaseRecordingDirectoryInput.tsxindex 1428773f..4c7ba33b 100644--- a/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/BaseRecordingDirectoryInput.tsx+++ b/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/BaseRecordingDirectoryInput.tsx@@ -1,55 +1,72 @@import React from 'react';import {IconButton, InputAdornment, TextField} from '@mui/material';import FolderOpenIcon from '@mui/icons-material/FolderOpen';-import {useAppDispatch} from "@/store/AppStateStore";-import {setRecordingInfo} from "@/store/slices/recordingInfoSlice";+import {useAppDispatch} from '@/store';+import {recordingDirectoryChanged} from '@/store/slices/recording/recording-slice';+import {useElectronIPC} from '@/services';interface DirectoryInputProps {- value: string;+ baseRecordingFolder: string;}-export const BaseRecordingDirectoryInput: React.FC<DirectoryInputProps> = ({value}) => {++export const BaseRecordingDirectoryInput: React.FC<DirectoryInputProps> = ({ baseRecordingFolder }) => {const dispatch = useAppDispatch();+ const { api, isElectron } = useElectronIPC();++ const handleSelectDirectory = async (): Promise<void> => {+ // Only try to use electron API if we're in electron environment+ if (!isElectron || !api) {+ console.warn('Electron API not available');+ return;+ }- const handleSelectDirectory = async () => {try {- const result = await window.electronAPI.selectDirectory();+ const result: string | null = await api.fileSystem.selectDirectory.mutate();if (result) {- dispatch(setRecordingInfo({recordingDirectory: result}));+ // Use the specific action for recording directory changes+ dispatch(recordingDirectoryChanged(result));}} catch (error) {console.error('Failed to select directory:', error);}};- const handleInputChange = async (e: React.ChangeEvent<HTMLInputElement>) => {- const newPath = e.target.value;+ const handleInputChange = async (e: React.ChangeEvent<HTMLInputElement>): Promise<void> => {+ const newPath: string = e.target.value;- // If the path contains a tilde, expand it immediately- if (newPath.includes('~')) {+ // Handle tilde expansion for home directory+ if (newPath.includes('~') && isElectron && api) {try {- const expandedPath = await window.electronAPI.expandPath(newPath);- dispatch(setRecordingInfo({recordingDirectory: expandedPath}));+ const home: string = await api.fileSystem.getHomeDirectory.query();+ // Replace ~ at the beginning of the path with home directory+ const expanded: string = newPath.replace(/^~(\/|\\)?/, home ? `${home}$1` : '');+ dispatch(recordingDirectoryChanged(expanded));} catch (error) {- console.error('Failed to expand path:', error);- dispatch(setRecordingInfo({recordingDirectory: newPath}));+ console.error('Failed to expand home directory:', error);+ // Fall back to using the path as-is+ dispatch(recordingDirectoryChanged(newPath));}} else {- dispatch(setRecordingInfo({recordingDirectory: newPath}));+ dispatch(recordingDirectoryChanged(newPath));}};return (<TextFieldlabel="Recording Directory"- value={value}+ value={baseRecordingFolder}onChange={handleInputChange}fullWidthsize="small"InputProps={{endAdornment: (<InputAdornment position="end">- <IconButton onClick={handleSelectDirectory} edge="end">- <FolderOpenIcon/>+ <IconButton+ onClick={handleSelectDirectory}+ edge="end"+ disabled={!isElectron}+ >+ <FolderOpenIcon /></IconButton></InputAdornment>),diff --git a/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/DelayRecordingStartControl.tsx b/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/DelayRecordingStartControl.tsxindex a48d0443..f961e2aa 100644--- a/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/DelayRecordingStartControl.tsx+++ b/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/DelayRecordingStartControl.tsx@@ -9,11 +9,11 @@ interface DelayStartControlProps {}export const DelayRecordingStartControl: React.FC<DelayStartControlProps> = ({- useDelay,- delaySeconds,- onDelayToggle,- onDelayChange-}) => {+ useDelay,+ delaySeconds,+ onDelayToggle,+ onDelayChange+ }) => {const theme = useTheme();return (<Box display="flex" alignItems="center" gap={2}>@@ -22,7 +22,12 @@ export const DelayRecordingStartControl: React.FC<DelayStartControlProps> = ({<Checkboxchecked={useDelay}onChange={(e) => onDelayToggle(e.target.checked)}- color="primary"+ sx={{+ color: theme.palette.text.primary,+ '&.Mui-checked': {+ color: theme.palette.text.primary,+ },+ }}/>}label="Delay Start"diff --git a/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/FullRecordingPathPreview.tsx b/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/FullRecordingPathPreview.tsxindex 35ac3eeb..7b55e723 100644--- a/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/FullRecordingPathPreview.tsx+++ b/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/FullRecordingPathPreview.tsx@@ -1,40 +1,36 @@-// skellycam-ui/src/components/recording-info-panel/recording-subcomponents/FullRecordingPathPreview.tsximport React from 'react';import {Box, IconButton, Paper, Tooltip, Typography, useTheme} from '@mui/material';import FolderIcon from '@mui/icons-material/Folder';import FolderSpecialIcon from '@mui/icons-material/FolderSpecial';import ChevronRightIcon from '@mui/icons-material/ChevronRight';import FolderOpenIcon from '@mui/icons-material/FolderOpen';+import {useElectronIPC} from "@/services";+import {useAppSelector} from '@/store';-interface FullPathPreviewProps {- directory: string;- subfolder?: string;- filename: string;-}--export const FullRecordingPathPreview: React.FC<FullPathPreviewProps> = ({- directory,- filename,- subfolder- }) => {+export const FullRecordingPathPreview: React.FC = () => {const theme = useTheme();+ const { api } = useElectronIPC();++ // Read directly from RTK store+ const recordingDirectory = useAppSelector((state) => state.recording.recordingDirectory);+ const computed = useAppSelector((state) => state.recording.computed);const parts = [- {icon: <FolderIcon/>, text: directory},- ...(subfolder ? [{icon: <FolderIcon/>, text: subfolder}] : []),- {icon: <FolderSpecialIcon/>, text: filename}+ {icon: <FolderIcon/>, text: recordingDirectory},+ ...(computed.subfolderName ? [{icon: <FolderIcon/>, text: computed.subfolderName}] : []),+ {icon: <FolderSpecialIcon/>, text: computed.recordingName}];- const fullPath = parts.map(p => p.text).join('/');+ const fullPath: string = parts.map(p => p.text).join('/');// Get the directory path only (without the filename)- const directoryToOpen = subfolder- ? `${directory}/${subfolder}`- : directory;+ const directoryToOpen: string = computed.subfolderName+ ? `${recordingDirectory}/${computed.subfolderName}`+ : recordingDirectory;- const handleOpenFolder = async () => {+ const handleOpenFolder = async (): Promise<void> => {try {- await window.electronAPI.openFolder(directoryToOpen);+ await api?.fileSystem.openFolder.mutate({ path: directoryToOpen });} catch (error) {console.error('Failed to open folder:', error);}@@ -59,8 +55,6 @@ export const FullRecordingPathPreview: React.FC<FullPathPreviewProps> = ({alignItems: 'center',mb: 1}}>--{/* Mobile/Narrow view */}<Box sx={{display: {xs: 'block', md: 'none'}}}><Tooltip title={fullPath} placement="bottom-start">@@ -92,7 +86,6 @@ export const FullRecordingPathPreview: React.FC<FullPathPreviewProps> = ({display: 'flex',alignItems: 'center',color: 'text.secondary',- // backgroundColor: 'background.paper',borderRadius: 1,px: 1,py: 0.5,@@ -132,7 +125,6 @@ export const FullRecordingPathPreview: React.FC<FullPathPreviewProps> = ({</IconButton></Tooltip></Box>-</Paper>);};diff --git a/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/RecordingNamePreview.tsx b/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/RecordingNamePreview.tsxindex 8f527f01..5dea4ee4 100644--- a/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/RecordingNamePreview.tsx+++ b/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/RecordingNamePreview.tsx@@ -1,29 +1,35 @@import React from 'react';import {TextField, Typography} from '@mui/material';+import {useAppSelector} from '@/store';interface RecordingNamePreviewProps {- name: string;tag: string;isRecording: boolean;onTagChange: (tag: string) => void;}export const RecordingNamePreview: React.FC<RecordingNamePreviewProps> = ({- name,- tag,- isRecording,- onTagChange-}) => {+ tag,+ isRecording,+ onTagChange+ }) => {+ // Read computed recording name from store+ const recordingName = useAppSelector((state) => state.recording.computed.recordingName);+return (<><Typography variant="body2" sx={{mb: 1}}>- Recording Name: {name}+ Recording Name: {recordingName}</Typography>{!isRecording && (<TextFieldlabel="Recording Tag"value={tag}onChange={(e) => onTagChange(e.target.value)}+ onKeyDown={(e) => {+ // Stop the TreeView from intercepting keyboard navigation+ e.stopPropagation();+ }}size="small"fullWidthplaceholder="Optional tag"@@ -31,4 +37,4 @@ export const RecordingNamePreview: React.FC<RecordingNamePreviewProps> = ({)}</>);-};\ No newline at end of file+};diff --git a/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/RecordingSettingsSection.tsx b/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/RecordingSettingsSection.tsxindex d938738e..bb8114bb 100644--- a/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/RecordingSettingsSection.tsx+++ b/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/RecordingSettingsSection.tsx@@ -17,19 +17,19 @@ interface RecordingSettingsProps {}export const RecordingSettingsSection: React.FC<RecordingSettingsProps> = ({- useTimestamp,- baseName,- useIncrement,- currentIncrement,- createSubfolder,- customSubfolderName,- onUseTimestampChange,- onBaseNameChange,- onUseIncrementChange,- onIncrementChange,- onCreateSubfolderChange,- onCustomSubfolderNameChange,-}) => {+ useTimestamp,+ baseName,+ useIncrement,+ currentIncrement,+ createSubfolder,+ customSubfolderName,+ onUseTimestampChange,+ onBaseNameChange,+ onUseIncrementChange,+ onIncrementChange,+ onCreateSubfolderChange,+ onCustomSubfolderNameChange,+ }) => {const theme = useTheme();return (@@ -41,7 +41,7 @@ export const RecordingSettingsSection: React.FC<RecordingSettingsProps> = ({: 'rgba(0, 0, 0, 0.04)',borderRadius: 1}}>- <Typography variant="subtitle1" sx={{ mb: 2 }}>Recording Settings</Typography>+ <Typography variant="subtitle1" sx={{mb: 2}}>Recording Settings</Typography><Grid container spacing={2} alignItems="center">{/* Timestamp & Base name row */}@@ -49,8 +49,13 @@ export const RecordingSettingsSection: React.FC<RecordingSettingsProps> = ({<FormControlLabelcontrol={<Checkbox- color="primary"- checked={useTimestamp}+ sx={{+ color: theme.palette.text.primary,+ '&.Mui-checked': {+ color: theme.palette.text.primary,+ },+ }}+ checked={useTimestamp}onChange={(e) => onUseTimestampChange(e.target.checked)}/>}@@ -73,7 +78,12 @@ export const RecordingSettingsSection: React.FC<RecordingSettingsProps> = ({<FormControlLabelcontrol={<Checkbox- color="primary"+ sx={{+ color: theme.palette.text.primary,+ '&.Mui-checked': {+ color: theme.palette.text.primary,+ },+ }}checked={createSubfolder}onChange={(e) => onCreateSubfolderChange(e.target.checked)}@@ -101,6 +111,12 @@ export const RecordingSettingsSection: React.FC<RecordingSettingsProps> = ({<Checkboxchecked={useIncrement}onChange={(e) => onUseIncrementChange(e.target.checked)}+ sx={{+ color: theme.palette.text.primary,+ '&.Mui-checked': {+ color: theme.palette.text.primary,+ },+ }}/>}label="Auto Increment"@@ -113,7 +129,7 @@ export const RecordingSettingsSection: React.FC<RecordingSettingsProps> = ({value={currentIncrement}onChange={(e) => onIncrementChange(parseInt(e.target.value) || 1)}disabled={!useIncrement}- inputProps={{ min: 1, step: 1 }}+ inputProps={{min: 1, step: 1}}size="small"fullWidth/>diff --git a/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/StartStopRecordingButton.tsx b/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/StartStopRecordingButton.tsxindex 83a3bde6..0905a9d0 100644--- a/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/StartStopRecordingButton.tsx+++ b/freemocap-ui/src/components/recording-info-panel/recording-subcomponents/StartStopRecordingButton.tsx@@ -1,11 +1,12 @@-import React from 'react';-import {Button, keyframes, Typography} from '@mui/material';+import React, {useEffect, useState} from 'react';+import {Box, Button, CircularProgress, keyframes, Typography} from '@mui/material';import {styled} from '@mui/system';-import {useTheme} from "@mui/material/styles";interface StartStopButtonProps {isRecording: boolean;+ isPending: boolean;countdown: number | null;+ recordingStartTime: number | null;onClick: () => void;}@@ -14,44 +15,140 @@ const pulseAnimation = keyframes`background-color: #fb1402;}50% {- background-color: #d43333;+ background-color: #711c1c;}100% {background-color: #fb1402;}`;-const PulsingButton = styled(Button)(({isRecording}: { isRecording: boolean | undefined }) => ({+// Use shouldForwardProp to prevent custom props from being passed to the DOM+const PulsingButton = styled(Button, {+ shouldForwardProp: (prop) => !['isRecording', 'isPending'].includes(prop as string)+})<{ isRecording: boolean; isPending: boolean }>(({ isRecording, isPending }) => ({backgroundColor: isRecording ? '#8d0a02' : '#005d94',borderStyle: 'solid',borderWidth: '3px',- borderColor: '#ff55ff',+ borderColor: isPending ? '#ffa500' : '#ff55ff',padding: 10,+ position: 'relative',+ transition: 'all 0.3s ease',+ opacity: isPending ? 0.8 : 1,'&:hover': {- borderColor: '#fb1402',+ borderColor: isPending ? '#ffa500' : '#fb1402',borderWidth: '3px',-},- ...(isRecording && {- animation: `${pulseAnimation} 1.5s infinite ease-in-out`,+ '&:disabled': {+ opacity: 0.8,+ cursor: 'not-allowed',+ },+ ...(isRecording && !isPending && {+ animation: `${pulseAnimation} 3s infinite ease-in-out`,}),}));+const formatDuration = (seconds: number): string => {+ const hours = Math.floor(seconds / 3600);+ const minutes = Math.floor((seconds % 3600) / 60);+ const secs = seconds % 60;++ const parts: string[] = [];+ if (hours > 0) {+ parts.push(hours.toString().padStart(2, '0'));+ }+ parts.push(minutes.toString().padStart(2, '0'));+ parts.push(secs.toString().padStart(2, '0'));++ return parts.join(':');+};+export const StartStopRecordingButton: React.FC<StartStopButtonProps> = ({isRecording,+ isPending,countdown,+ recordingStartTime,onClick}) => {+ const [recordingDuration, setRecordingDuration] = useState<number>(0);++ // Update recording duration every second+ useEffect(() => {+ if (!isRecording || !recordingStartTime || isPending) {+ setRecordingDuration(0);+ return;+ }++ const updateDuration = (): void => {+ const now = Date.now();+ const duration = Math.floor((now - recordingStartTime) / 1000);+ setRecordingDuration(duration);+ };++ // Update immediately+ updateDuration();++ // Then update every second+ const interval = setInterval(updateDuration, 1000);++ return () => clearInterval(interval);+ }, [isRecording, recordingStartTime, isPending]);++ const getButtonContent = (): React.ReactNode => {+ // Show countdown if active+ if (countdown !== null && countdown > 0) {+ return (+ <Box display="flex" alignItems="center" gap={1}>+ <Typography variant="h6">+ Starting in {countdown}...+ </Typography>+ </Box>+ );+ }++ // Show pending state+ if (isPending) {+ return (+ <Box display="flex" alignItems="center" gap={1}>+ <CircularProgress size={20} color="inherit" />+ <Typography variant="h6">+ {isRecording ? 'Stopping...' : 'Starting...'}+ </Typography>+ </Box>+ );+ }++ // Show recording state with duration+ if (isRecording) {+ return (+ <Box display="flex" flexDirection="column" alignItems="center">+ <Typography variant="h6">+ ๐ด Stop Recording+ </Typography>+ <Typography variant="caption" sx={{ fontSize: '0.9rem', fontFamily: 'monospace' }}>+ {formatDuration(recordingDuration)}+ </Typography>+ </Box>+ );+ }++ // Default start state+ return (+ <Typography variant="h6">+ ๐ด Start Recording+ </Typography>+ );+ };+return (<PulsingButtononClick={onClick}variant="contained"isRecording={isRecording}+ isPending={isPending}+ disabled={isPending || countdown !== null}fullWidth>- <Typography variant="h6">- {isRecording ? '๐ด Stop Recording' : '๐ด Start Recording'}- </Typography>+ {getButtonContent()}</PulsingButton>);};diff --git a/freemocap-ui/src/components/server-settings-panel/ServerConnectionStatus.tsx b/freemocap-ui/src/components/server-settings-panel/ServerConnectionStatus.tsxdeleted file mode 100644index b5b3b4e0..00000000--- a/freemocap-ui/src/components/server-settings-panel/ServerConnectionStatus.tsx+++ /dev/null@@ -1,70 +0,0 @@-import {Box, Typography} from "@mui/material";-import CheckIcon from '@mui/icons-material/Check';-import CloseIcon from '@mui/icons-material/Close';-import {usePythonServerContext} from "@/context/python-server-context/PythonServerContext";--export const ServerConnectionStatus = () => {- const {isPythonRunning, startPythonServer, stopPythonServer} = usePythonServerContext();-- const handleToggleConnection = () => {- if (isPythonRunning) {- console.log('Toggling Python Server: stopping');- stopPythonServer();- } else {- console.log('Toggling Python Server: starting');- startPythonServer(null);- }- };- return (-- <Box- sx={{- display: 'flex',- justifyContent: 'flex-end',- padding: '10px',- flexDirection: 'column',- pl: 4,- color: '#dadada',- cursor: 'pointer',- border: '1px solid rgba(255, 255, 255, 0.1)',- borderRadius: '8px',- ':hover': {- backgroundColor: 'rgba(255, 255, 255, 0.05)',- borderColor: 'rgba(255, 255, 255, 0.2)',- },- }}- onClick={handleToggleConnection}- >- <Typography- variant="body1"- component="div"- sx={{- display: 'flex',- alignItems: 'center',- gap: 1,- }}- >- <Box sx={{- border: '1px solid rgba(255, 255, 255, 0.3)',- backgroundColor: isPythonRunning ? 'rgba(0, 255, 255, 0.1)' : 'rgba(255, 0, 0, 0.1)',- borderColor: isPythonRunning ? 'rgba(0, 255, 255, 0.5)' : 'rgba(255, 0, 0, 0.5)',-- width: '24px',- height: '24px',- marginRight: '8px',- borderRadius: '4px',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- }}>- {isPythonRunning ? (- <CheckIcon sx={{color: 'green', fontSize: '16px'}}/>- ) : (- <CloseIcon fontSize="small" sx={{color: 'red'}}/>- )}- </Box>- Python Server: {isPythonRunning ? 'running' : 'stopped'}- </Typography>- </Box>- );-};diff --git a/freemocap-ui/src/components/server-settings-panel/ServerSettingsPanel.tsx b/freemocap-ui/src/components/server-settings-panel/ServerSettingsPanel.tsxdeleted file mode 100644index 194740e9..00000000--- a/freemocap-ui/src/components/server-settings-panel/ServerSettingsPanel.tsx+++ /dev/null@@ -1,184 +0,0 @@-import * as React from 'react';-import Box from '@mui/material/Box';-import {SimpleTreeView} from '@mui/x-tree-view/SimpleTreeView';-import {TreeItem} from '@mui/x-tree-view/TreeItem';-import {Checkbox, FormControlLabel, Slider, TextField, Typography} from '@mui/material';-import WebsocketConnectionStatus from './WebsocketConnectionStatus';-import ExpandMoreIcon from '@mui/icons-material/ExpandMore';-import ChevronRightIcon from '@mui/icons-material/ChevronRight';-import {useWebSocketContext} from "@/context/websocket-context/WebSocketContext";-import {ServerConnectionStatus} from "@/components/server-settings-panel/ServerConnectionStatus";---export const ServerSettingsPanel = () => {- const {isConnected} = useWebSocketContext();- const [startServer, setStartServer] = React.useState(true);- const [serverExecutablePath, setServerExecutablePath] = React.useState('/path/to/server/executable');- const [host, setHost] = React.useState('localhost');- const [httpPort, setHttpPort] = React.useState(8006);- const [limitFramerate, setLimitFramerate] = React.useState(false);- const [framerate, setFramerate] = React.useState(30);- const [preShrink, setPreShrink] = React.useState(true);- const [shrinkFactor, setShrinkFactor] = React.useState(0.5);-- const maxFramerate = 60;-- const handleFramerateChange = (event: Event, newValue: number | number[]) => {- setFramerate(newValue as number);- };-- const handleShrinkFactorChange = (event: Event, newValue: number | number[]) => {- setShrinkFactor(newValue as number);- };-- return (- <Box sx={{padding: 2, color: 'text.primary'}}>- <SimpleTreeView- slots={{- collapseIcon: ExpandMoreIcon,- expandIcon: ChevronRightIcon- }}- sx={{flexGrow: 1, maxWidth: 400}}- >- <TreeItem- itemId="server-status"- label={- <Box sx={{display: 'flex', alignItems: 'center', gap: 1}}>- <span>Server status:</span>- <Box- sx={{- display: 'inline-flex',- alignItems: 'center',- bgcolor: isConnected ? 'rgba(0, 255, 255, 0.25)' : 'rgba(255, 0, 0, 0.25)',- px: 1,- py: 0.5,- borderRadius: 1- }}- >- {isConnected ? 'Connected' : 'Disconnected'}- </Box>- </Box>- }- >- <Box sx={{pl: 2, pt: 1, borderTop: '2px solid', borderColor: 'darkcyan'}}>- <ServerConnectionStatus/>- <WebsocketConnectionStatus/>- <TreeItem itemId="server-settings" label="Server Settings">- <Box sx={{pl: 2, pt: 1, display: 'flex', flexDirection: 'column', gap: 2}}>- <FormControlLabel- control={- <Checkbox- checked={startServer}- onChange={(e) => setStartServer(e.target.checked)}- />- }- label="Start server executable"- />-- <TextField- label="Server executable path"- value={serverExecutablePath}- onChange={(e) => setServerExecutablePath(e.target.value)}- fullWidth- size="small"- disabled={true}- />-- <Box sx={{display: 'flex', alignItems: 'center', gap: 1}}>- <TextField- label="Host"- value={host}- onChange={(e) => setHost(e.target.value)}- size="small"- sx={{flex: 1}}- disabled={true}-- />- <TextField- label="HTTP Port"- type="number"- value={httpPort}- onChange={(e) => setHttpPort(Number(e.target.value))}- size="small"- sx={{width: 100}}- disabled={true}-- />- </Box>-- <Typography variant="body2" color="textSecondary">- WebSocket URL: ws://{host}:{httpPort}/websocket/connect- </Typography>- </Box>- </TreeItem>-- <TreeItem itemId="display-settings" label="Display Settings">- <Box sx={{pl: 2, pt: 1, display: 'flex', flexDirection: 'column', gap: 2}}>- <FormControlLabel- control={- <Checkbox- checked={limitFramerate}- onChange={(e) => setLimitFramerate(e.target.checked)}- disabled={true}-- />- }- label="Limit display framerate"- />-- {limitFramerate && (- <Box sx={{pl: 4}}>- <Typography gutterBottom>- Framerate: {framerate} FPS- </Typography>- <Slider- value={framerate}- onChange={handleFramerateChange}- min={0}- max={maxFramerate}- valueLabelDisplay="auto"- size="small"- disabled={true}-- />- </Box>- )}-- <FormControlLabel- control={- <Checkbox- checked={preShrink}- onChange={(e) => setPreShrink(e.target.checked)}- disabled={true}-- />- }- label="Pre-shrink images"- />-- {preShrink && (- <Box sx={{pl: 4}}>- <Typography gutterBottom>- Shrink factor: {shrinkFactor.toFixed(2)}- </Typography>- <Slider- value={shrinkFactor}- onChange={handleShrinkFactorChange}- min={0}- max={1}- step={0.01}- valueLabelDisplay="auto"- size="small"- disabled={true}-- />- </Box>- )}- </Box>- </TreeItem>- </Box>- </TreeItem>- </SimpleTreeView>- </Box>- );-};diff --git a/freemocap-ui/src/components/server-settings-panel/WebsocketConnectionStatus.tsx b/freemocap-ui/src/components/server-settings-panel/WebsocketConnectionStatus.tsxdeleted file mode 100644index ea870386..00000000--- a/freemocap-ui/src/components/server-settings-panel/WebsocketConnectionStatus.tsx+++ /dev/null@@ -1,81 +0,0 @@-import {Box, Tooltip, Typography} from "@mui/material";-import {useWebSocketContext} from "@/context/websocket-context/WebSocketContext";-import CheckIcon from '@mui/icons-material/Check';-import CloseIcon from '@mui/icons-material/Close';--const WebsocketConnectionStatus = () => {- const {isConnected, disconnect, connect} = useWebSocketContext();-- const handleToggleConnection = () => {- if (isConnected) {- console.log('Toggling WebSocket: disconnecting');- disconnect(false);- } else {- console.log('Toggling WebSocket: connecting');- connect();- }- };-- return (- // <Tooltip title={`WebSocket URL: ${wsUrl}`} placement="bottom-start" arrow>- <Box- sx={{- display: 'flex',- justifyContent: 'flex-end',- padding: '10px',- flexDirection: 'column',- pl: 4,- color: '#dadada',- cursor: 'pointer',- border: '1px solid rgba(255, 255, 255, 0.1)',- borderRadius: '8px',- ':hover': {- backgroundColor: 'rgba(255, 255, 255, 0.05)',- borderColor: 'rgba(255, 255, 255, 0.2)',- },- }}- onClick={handleToggleConnection}- >- <Typography- variant="body1"- component="div" // Override the default <p> to <div>- sx={{- display: 'flex',- alignItems: 'center',- gap: 1,- }}- >- <Box sx={{- border: '1px solid rgba(255, 255, 255, 0.3)',- width: '24px',- height: '24px',- marginRight: '8px',- cursor: 'pointer',- borderRadius: '4px',- transition: 'background-color 0.3s, border-color 0.3s',- backgroundColor: isConnected ? 'rgba(0, 255, 255, 0.1)' : 'rgba(255, 0, 0, 0.1)',- borderColor: isConnected ? 'rgba(0, 255, 255, 0.5)' : 'rgba(255, 0, 0, 0.5)',- boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)',- display: 'flex',- alignItems: 'center',- padding: '4px',- justifyContent: 'center',- '&:hover': {- backgroundColor: 'rgba(255, 255, 255, 0.05)',- borderColor: 'rgba(255, 255, 255, 0.2)',- },- }}>- {isConnected ? (- <CheckIcon sx={{ color: 'green' }} />- ) : (- <CloseIcon fontSize="small" sx={{ color: 'red' }} />- )}- </Box>- Websocket: {isConnected ? 'connected' : 'disconnected'}- </Typography>- </Box>- // </Tooltip>- )- ;-};-export default WebsocketConnectionStatus;diff --git a/freemocap-ui/src/components/ui-components/BottomPanelContent.tsx b/freemocap-ui/src/components/ui-components/BottomPanelContent.tsxindex bf5e43a0..f1359035 100644--- a/freemocap-ui/src/components/ui-components/BottomPanelContent.tsx+++ b/freemocap-ui/src/components/ui-components/BottomPanelContent.tsx@@ -1,21 +1,22 @@-// skellycam-ui/src/components/ui-components/BottomPanelContent.tsx+// freemocap-ui/src/components/ui-components/BottomPanelContent.tsximport * as React from 'react';import Box from '@mui/material/Box';import {LogTerminal} from "@/components/LogTerminal";-import FramerateViewerPanel from "@/components/framerate-viewer/FrameRateViewer";import {Panel, PanelGroup, PanelResizeHandle} from "react-resizable-panels";import {useTheme} from "@mui/material/styles";+import FramerateViewerPanel from "@/components/framerate-viewer/FrameRateViewer";export default function BottomPanelContent() {const theme = useTheme();return (- <Box sx={{ width: '100%', height: '100%' }}>+ <Box sx={{width: '100%', height: '100%'}}><PanelGroup direction="horizontal">{/* Framerate Viewer Panel */}- <Panel defaultSize={50} minSize={20}>- <Box sx={{ height: '100%', overflow: 'auto' }}>- <FramerateViewerPanel />+ <Panel defaultSize={30} minSize={20}>+ <Box sx={{height: '100%', overflow: 'auto'}}>+ <FramerateViewerPanel/>+ Framerate Viewer</Box></Panel>@@ -29,9 +30,9 @@ export default function BottomPanelContent() {/>{/* Logs Terminal Panel */}- <Panel defaultSize={50} minSize={20}>- <Box sx={{ height: '100%', overflow: 'auto' }}>- <LogTerminal />+ <Panel defaultSize={70} minSize={20}>+ <Box sx={{height: '100%', overflow: 'auto'}}>+ <LogTerminal/></Box></Panel></PanelGroup>diff --git a/freemocap-ui/src/components/ui-components/Copyright.tsx b/freemocap-ui/src/components/ui-components/Copyright.tsxdeleted file mode 100644index 6163d342..00000000--- a/freemocap-ui/src/components/ui-components/Copyright.tsx+++ /dev/null@@ -1,26 +0,0 @@-// Update Copyright.tsx-import Typography from "@mui/material/Typography";-import Link from "@mui/material/Link";-import * as React from "react";-import {useTheme} from "@mui/material";--export const Copyright = function() {- const theme = useTheme();-- return (- <Typography- variant="body2"- color={theme.palette.mode === 'dark' ? "rgba(255,255,255,0.7)" : "rgba(0,0,0,0.6)"}- align="center"- >- {'w/ '}- <Link color="inherit" href="https://github.com/freemocap/">- โค๏ธ- </Link>{' from the '}- <Link color="inherit" href="https://github.com/freemocap/">- FreeMoCap Foundation- </Link>{' '}- {new Date().getFullYear()}- </Typography>- );-}diff --git a/freemocap-ui/src/components/ui-components/Footer.tsx b/freemocap-ui/src/components/ui-components/Footer.tsxnew file mode 100644index 00000000..441c19a8--- /dev/null+++ b/freemocap-ui/src/components/ui-components/Footer.tsx@@ -0,0 +1,26 @@+// Update Copyright.tsx+import Typography from "@mui/material/Typography";+import Link from "@mui/material/Link";+import * as React from "react";+import {useTheme} from "@mui/material";++export const Footer = function () {+ const theme = useTheme();++ return (+ <Typography+ variant="body2"+ color={theme.palette.mode === 'dark' ? "rgba(255,255,255,0.7)" : "rgba(0,0,0,0.6)"}+ align="center"+ >+ {'w/ '}+ <Link color="inherit" href="https://github.com/freemocap/">+ โค๏ธ+ </Link>{' from the '}+ <Link color="inherit" href="https://github.com/freemocap/">+ FreeMoCap Foundation+ </Link>{' '}+ {new Date().getFullYear()}+ </Typography>+ );+}diff --git a/freemocap-ui/src/components/ui-components/Header.tsx b/freemocap-ui/src/components/ui-components/Header.tsxindex 449a8b4a..bd443e8c 100644--- a/freemocap-ui/src/components/ui-components/Header.tsx+++ b/freemocap-ui/src/components/ui-components/Header.tsx@@ -6,7 +6,7 @@ import Typography from '@mui/material/Typography';import {Box, useTheme} from '@mui/material';import ThemeToggle from './ThemeToggle';-export const Header = function() {+export const Header = function () {const theme = useTheme();return (@@ -20,11 +20,11 @@ export const Header = function() {}}><Toolbar>- <Typography variant="h6" color="inherit" sx={{ flexGrow: 1 }}>- SkellyCam ๐๐ธ+ <Typography variant="h6" color="inherit" sx={{flexGrow: 1}}>+ FreeMoCap ๐๐ธ</Typography>- <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>- <ThemeToggle />+ <Box sx={{display: 'flex', alignItems: 'center', gap: 1}}>+ <ThemeToggle/></Box></Toolbar></AppBar>diff --git a/freemocap-ui/src/components/ui-components/LeftSidePanelContent.tsx b/freemocap-ui/src/components/ui-components/LeftSidePanelContent.tsxindex 176ea073..a4b1f607 100644--- a/freemocap-ui/src/components/ui-components/LeftSidePanelContent.tsx+++ b/freemocap-ui/src/components/ui-components/LeftSidePanelContent.tsx@@ -1,29 +1,31 @@-// skellycam-ui/src/components/ui-components/LeftSidePanelContent.tsx+// freemocap-ui/src/components/ui-components/LeftSidePanelContent.tsximport * as React from 'react';import Box from "@mui/material/Box";import {IconButton, List, ListItem, useTheme} from "@mui/material";-import {AvailableCamerasPanel} from "@/components/available-cameras-panel/AvailableCamerasPanel";-import {RecordingInfoPanel} from "@/components/recording-info-panel/RecordingInfoPanel";import ThemeToggle from "@/components/ui-components/ThemeToggle";import HomeIcon from '@mui/icons-material/Home';import {useLocation, useNavigate} from "react-router-dom";import VideocamIcon from '@mui/icons-material/Videocam';-import VideoLibraryIcon from '@mui/icons-material/VideoLibrary';import DirectionsRunIcon from '@mui/icons-material/DirectionsRun';import {VideoFolderPanel} from "@/components/video-folder-panel/VideoFolderPanel";+import {CameraConfigTreeView} from "@/components/camera-config-tree-view/CameraConfigTreeView";+import {ServerConnectionStatus} from "@/components/ServerConnectionStatus";import {ProcessingPipelinePanel} from "@/components/processing-pipeline-panel/ProcessingPipelinePanel";-import {ServerSettingsPanel} from "@/components/server-settings-panel/ServerSettingsPanel";+import {CalibrationControlPanel} from "@/components/calibration-task-panel/CalibrationControlPanel";+import {MocapTaskTreeItem} from "@/components/mocap-task-panel/MocapTaskTreeItem";+import {RecordingInfoPanel} from "@/components/recording-info-panel/RecordingInfoPanel";+// Extract reusable scrollbar stylesconst scrollbarStyles = {'&::-webkit-scrollbar': {- width: '8px',+ width: '6px',backgroundColor: 'transparent',},'&::-webkit-scrollbar-thumb': {backgroundColor: (theme: { palette: { mode: string; }; }) => theme.palette.mode === 'dark'? 'rgba(255, 255, 255, 0.2)': 'rgba(0, 0, 0, 0.2)',- borderRadius: '4px',+ borderRadius: '3px','&:hover': {backgroundColor: (theme: { palette: { mode: string; }; }) => theme.palette.mode === 'dark'? 'rgba(255, 255, 255, 0.3)'@@ -44,55 +46,56 @@ export const LeftSidePanelContent = () => {const navigate = useNavigate();const location = useLocation();- // Dynamic styles based on theme- const item = {- py: '2px',- px: 3,- color: theme.palette.primary.contrastText,- '&:hover, &:focus': {- bgcolor: theme.palette.mode === 'dark'- ? 'rgba(255, 255, 255, 0.08)'- : 'rgba(0, 0, 0, 0.04)',- },- };-- const itemCategory = {- boxShadow: theme.palette.mode === 'dark'- ? '0 -1px 0 rgb(255,255,255,0.1) inset'- : '0 -1px 0 rgba(0,0,0,0.1) inset',- py: 1.5,- px: 3,- };-return (<Box sx={{width: '100%',height: '100%',- backgroundColor: theme.palette.primary.dark,- color: theme.palette.primary.contrastText,+ backgroundColor: theme.palette.mode === 'dark'+ ? theme.palette.background.paper+ : theme.palette.grey[50],+ color: theme.palette.text.primary,display: 'flex',flexDirection: 'column',- overflow: 'hidden'+ overflowY: 'auto',+ overflowX: 'hidden',+ ...scrollbarStyles}}>+ {/* Header */}<List disablePadding><ListItemsx={{- ...item,- ...itemCategory,- fontSize: 22,- color: theme.palette.common.white,+ borderBottom: theme.palette.mode === 'dark'+ ? '1px solid rgba(255,255,255,0.08)'+ : '1px solid rgba(0,0,0,0.08)',+ py: 0.75,+ px: 1.5,+ minHeight: 40,display: 'flex',- justifyContent: 'space-between'+ justifyContent: 'space-between',+ alignItems: 'center',}}>- <Box component="span" sx={{ml: 1}}>FreeMoCap๐โจ</Box>+ <Box+ component="span"+ sx={{+ fontSize: 16,+ fontWeight: 600,+ color: theme.palette.text.primary+ }}+ >+ FreeMoCap ๐๐ธ+ </Box>- <Box sx={{display: 'flex', alignItems: 'center'}}>+ <Box sx={{display: 'flex', alignItems: 'center', gap: 0.25}}><IconButton- color="inherit"+ size="small"onClick={() => navigate('/')}+ sx={{+ padding: '4px',+ color: location.pathname === '/' ? theme.palette.success.main : theme.palette.text.secondary+ }}>- <HomeIcon/>+ <HomeIcon sx={{ fontSize: 18 }} /></IconButton><IconButtoncolor="inherit"@@ -102,51 +105,49 @@ export const LeftSidePanelContent = () => {</IconButton><IconButton- color="inherit"+ size="small"onClick={() => navigate('/cameras')}+ sx={{+ padding: '4px',+ color: location.pathname === '/cameras' ? theme.palette.success.main : theme.palette.text.secondary+ }}>- <VideocamIcon/>- </IconButton>- <IconButton- color="inherit"- onClick={() => navigate('/videos')}- >- <VideoLibraryIcon/>+ <VideocamIcon sx={{ fontSize: 18 }} /></IconButton><ThemeToggle/></Box>-</ListItem></List>- <ServerSettingsPanel/>-- <Box sx={{- flex: 1,- overflowY: 'auto',- overflowX: 'hidden',- ...scrollbarStyles- }}>- <RecordingInfoPanel/>- <AvailableCamerasPanel/>- <ProcessingPipelinePanel/>-- </Box>+ {/* Server Settings - Compact */}+ <ServerConnectionStatus/>+ {/* Video Panel for Videos Page */}{location.pathname === '/videos' && (<Box sx={{- flex: 1,- overflowY: 'auto',- overflowX: 'hidden',- ...scrollbarStyles+ borderTop: '1px solid',+ borderColor: theme.palette.divider,}}><VideoFolderPanel/>- <ProcessingPipelinePanel/>-</Box>)}+ {/* Main Content Area */}+ <Box sx={{+ display: 'flex',+ flexDirection: 'column',+ gap: 0.5,+ pt: 0.5,+ pb: 2,+ }}>+ <ProcessingPipelinePanel/>+ <CameraConfigTreeView/>+ {/*<RecordingInfoPanel/>*/}+ <CalibrationControlPanel />+ <MocapTaskTreeItem />++ </Box></Box>);}diff --git a/freemocap-ui/src/components/ui-components/ThemeToggle.tsx b/freemocap-ui/src/components/ui-components/ThemeToggle.tsxindex 4ce0cfca..9e8d4a40 100644--- a/freemocap-ui/src/components/ui-components/ThemeToggle.tsx+++ b/freemocap-ui/src/components/ui-components/ThemeToggle.tsx@@ -2,32 +2,32 @@ import React from 'react';import {IconButton, Tooltip, useTheme} from '@mui/material';import Brightness4Icon from '@mui/icons-material/Brightness4'; // Dark mode iconimport Brightness7Icon from '@mui/icons-material/Brightness7'; // Light mode icon-import {useAppDispatch, useAppSelector} from '@/store/AppStateStore';-import {toggleThemeMode} from '@/store/slices/themeSlice';+import {useAppDispatch, useAppSelector} from '@/store';+import {themeModeToggled} from '@/store/slices/theme';export const ThemeToggle: React.FC = () => {- const dispatch = useAppDispatch();- const theme = useTheme();- const themeMode = useAppSelector(state => state.theme.mode);- const isDarkMode = themeMode === 'dark';+ const dispatch = useAppDispatch();+ const theme = useTheme();+ const themeMode = useAppSelector(state => state.theme.mode);+ const isDarkMode = themeMode === 'dark';- return (- <Tooltip title={isDarkMode ? "Switch to light mode" : "Switch to dark mode"}>- <IconButton- onClick={() => dispatch(toggleThemeMode())}- color="inherit"- aria-label="toggle theme"- edge="end"- sx={{- '&:hover': {- backgroundColor: theme.palette.action.hover,- },- }}- >- {isDarkMode ? <Brightness7Icon /> : <Brightness4Icon />}- </IconButton>- </Tooltip>- );+ return (+ <Tooltip title={isDarkMode ? "Switch to light mode" : "Switch to dark mode"}>+ <IconButton+ onClick={() => dispatch(themeModeToggled())}+ color="inherit"+ aria-label="toggle theme"+ edge="end"+ sx={{+ '&:hover': {+ backgroundColor: theme.palette.action.hover,+ },+ }}+ >+ {isDarkMode ? <Brightness7Icon /> : <Brightness4Icon />}+ </IconButton>+ </Tooltip>+ );};export default ThemeToggle;diff --git a/freemocap-ui/src/components/update/Modal/index.tsx b/freemocap-ui/src/components/update/Modal/index.tsxindex 1e54db5a..45799665 100644--- a/freemocap-ui/src/components/update/Modal/index.tsx+++ b/freemocap-ui/src/components/update/Modal/index.tsx@@ -3,65 +3,67 @@ import {createPortal} from 'react-dom'import './modal.css'const ModalTemplate: React.FC<React.PropsWithChildren<{- title?: ReactNode- footer?: ReactNode- cancelText?: string- okText?: string- onCancel?: () => void- onOk?: () => void- width?: number+ title?: ReactNode+ footer?: ReactNode+ cancelText?: string+ okText?: string+ onCancel?: () => void+ onOk?: () => void+ width?: number}>> = props => {- const {- title,- children,- footer,- cancelText = 'Cancel',- okText = 'OK',- onCancel,- onOk,- width = 530,- } = props+ const {+ title,+ children,+ footer,+ cancelText = 'Cancel',+ okText = 'OK',+ onCancel,+ onOk,+ width = 530,+ } = props- return (- <div className='update-modal'>- <div className='update-modal__mask' />- <div className='update-modal__warp'>- <div className='update-modal__content' style={{ width }}>- <div className='content__header'>- <div className='content__header-text'>{title}</div>- <span- className='update-modal--close'- onClick={onCancel}- >+ return (+ <div className='update-modal'>+ <div className='update-modal__mask'/>+ <div className='update-modal__warp'>+ <div className='update-modal__content' style={{width}}>+ <div className='content__header'>+ <div className='content__header-text'>{title}</div>+ <span+ className='update-modal--close'+ onClick={onCancel}+ ><svg- viewBox="0 0 1024 1024"- version="1.1" xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 1024 1024"+ version="1.1" xmlns="http://www.w3.org/2000/svg">- <path d="M557.312 513.248l265.28-263.904c12.544-12.48 12.608-32.704 0.128-45.248-12.512-12.576-32.704-12.608-45.248-0.128l-265.344 263.936-263.04-263.84C236.64 191.584 216.384 191.52 203.84 204 191.328 216.48 191.296 236.736 203.776 249.28l262.976 263.776L201.6 776.8c-12.544 12.48-12.608 32.704-0.128 45.248 6.24 6.272 14.464 9.44 22.688 9.44 8.16 0 16.32-3.104 22.56-9.312l265.216-263.808 265.44 266.24c6.24 6.272 14.432 9.408 22.656 9.408 8.192 0 16.352-3.136 22.592-9.344 12.512-12.48 12.544-32.704 0.064-45.248L557.312 513.248z" p-id="2764" fill="currentColor">+ <path+ d="M557.312 513.248l265.28-263.904c12.544-12.48 12.608-32.704 0.128-45.248-12.512-12.576-32.704-12.608-45.248-0.128l-265.344 263.936-263.04-263.84C236.64 191.584 216.384 191.52 203.84 204 191.328 216.48 191.296 236.736 203.776 249.28l262.976 263.776L201.6 776.8c-12.544 12.48-12.608 32.704-0.128 45.248 6.24 6.272 14.464 9.44 22.688 9.44 8.16 0 16.32-3.104 22.56-9.312l265.216-263.808 265.44 266.24c6.24 6.272 14.432 9.408 22.656 9.408 8.192 0 16.352-3.136 22.592-9.344 12.512-12.48 12.544-32.704 0.064-45.248L557.312 513.248z"+ p-id="2764" fill="currentColor"></path></svg></span>- </div>- <div className='content__body'>{children}</div>- {typeof footer !== 'undefined' ? (- <div className='content__footer'>- <button onClick={onCancel}>{cancelText}</button>- <button onClick={onOk}>{okText}</button>+ </div>+ <div className='content__body'>{children}</div>+ {typeof footer !== 'undefined' ? (+ <div className='content__footer'>+ <button onClick={onCancel}>{cancelText}</button>+ <button onClick={onOk}>{okText}</button>+ </div>+ ) : footer}+ </div></div>- ) : footer}</div>- </div>- </div>- )+ )}const Modal = (props: Parameters<typeof ModalTemplate>[0] & { open: boolean }) => {- const { open, ...omit } = props+ const {open, ...omit} = props- return createPortal(- open ? ModalTemplate(omit) : null,- document.body,- )+ return createPortal(+ open ? ModalTemplate(omit) : null,+ document.body,+ )}export default Modaldiff --git a/freemocap-ui/src/components/update/Modal/modal.css b/freemocap-ui/src/components/update/Modal/modal.cssindex d52cacba..77e2e17b 100644--- a/freemocap-ui/src/components/update/Modal/modal.css+++ b/freemocap-ui/src/components/update/Modal/modal.css@@ -1,87 +1,87 @@.update-modal {- --primary-color: rgb(224, 30, 90);+ --primary-color: rgb(224, 30, 90);- .update-modal__mask {- width: 100vw;- height: 100vh;- position: fixed;- left: 0;- top: 0;- z-index: 9;- background: rgba(0, 0, 0, 0.45);- }+ .update-modal__mask {+ width: 100vw;+ height: 100vh;+ position: fixed;+ left: 0;+ top: 0;+ z-index: 9;+ background: rgba(0, 0, 0, 0.45);+ }- .update-modal__warp {- position: fixed;- top: 50%;- left: 50%;- transform: translate(-50%, -50%);- z-index: 19;- }+ .update-modal__warp {+ position: fixed;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%);+ z-index: 19;+ }- .update-modal__content {- box-shadow: 0 0 10px -4px rgb(130, 86, 208);- overflow: hidden;- border-radius: 4px;+ .update-modal__content {+ box-shadow: 0 0 10px -4px rgb(130, 86, 208);+ overflow: hidden;+ border-radius: 4px;- .content__header {- display: flex;- line-height: 38px;- background-color: var(--primary-color);+ .content__header {+ display: flex;+ line-height: 38px;+ background-color: var(--primary-color);- .content__header-text {- font-weight: bold;- width: 0;- flex-grow: 1;- }- }+ .content__header-text {+ font-weight: bold;+ width: 0;+ flex-grow: 1;+ }+ }- .update-modal--close {- width: 30px;- height: 30px;- margin: 4px;- line-height: 34px;- text-align: center;- cursor: pointer;+ .update-modal--close {+ width: 30px;+ height: 30px;+ margin: 4px;+ line-height: 34px;+ text-align: center;+ cursor: pointer;- svg {- width: 17px;- height: 17px;- }- }+ svg {+ width: 17px;+ height: 17px;+ }+ }- .content__body {- padding: 10px;- background-color: #fff;- color: #333;- }+ .content__body {+ padding: 10px;+ background-color: #fff;+ color: #333;+ }- .content__footer {- padding: 10px;- background-color: #fff;- display: flex;- justify-content: flex-end;+ .content__footer {+ padding: 10px;+ background-color: #fff;+ display: flex;+ justify-content: flex-end;- button {- padding: 7px 11px;- background-color: var(--primary-color);- font-size: 14px;- margin-left: 10px;+ button {+ padding: 7px 11px;+ background-color: var(--primary-color);+ font-size: 14px;+ margin-left: 10px;- &:first-child {- margin-left: 0;+ &:first-child {+ margin-left: 0;+ }+ }}- }}- }- .icon {- padding: 0 15px;- width: 20px;- fill: currentColor;+ .icon {+ padding: 0 15px;+ width: 20px;+ fill: currentColor;- &:hover {- color: rgba(0, 0, 0, 0.4);+ &:hover {+ color: rgba(0, 0, 0, 0.4);+ }}- }-}\ No newline at end of file+}diff --git a/freemocap-ui/src/components/update/Progress/index.tsx b/freemocap-ui/src/components/update/Progress/index.tsxindex 1701dc57..8e393f40 100644--- a/freemocap-ui/src/components/update/Progress/index.tsx+++ b/freemocap-ui/src/components/update/Progress/index.tsx@@ -2,21 +2,21 @@ import React from 'react'import './progress.css'const Progress: React.FC<React.PropsWithChildren<{- percent?: number+ percent?: number}>> = props => {- const { percent = 0 } = props+ const {percent = 0} = props- return (- <div className='update-progress'>- <div className='update-progress-pr'>- <div- className='update-progress-rate'- style={{ width: `${3 * percent}px` }}- />- </div>- <span className='update-progress-num'>{(percent ?? 0).toString().substring(0, 4)}%</span>- </div>- )+ return (+ <div className='update-progress'>+ <div className='update-progress-pr'>+ <div+ className='update-progress-rate'+ style={{width: `${3 * percent}px`}}+ />+ </div>+ <span className='update-progress-num'>{(percent ?? 0).toString().substring(0, 4)}%</span>+ </div>+ )}export default Progressdiff --git a/freemocap-ui/src/components/update/Progress/progress.css b/freemocap-ui/src/components/update/Progress/progress.cssindex 2cef7c1b..6abc00cc 100644--- a/freemocap-ui/src/components/update/Progress/progress.css+++ b/freemocap-ui/src/components/update/Progress/progress.css@@ -1,21 +1,21 @@.update-progress {- display: flex;- align-items: center;+ display: flex;+ align-items: center;- .update-progress-pr {- border: 1px solid #000;- border-radius: 3px;- height: 6px;- width: 300px;- }+ .update-progress-pr {+ border: 1px solid #000;+ border-radius: 3px;+ height: 6px;+ width: 300px;+ }- .update-progress-rate {- height: 6px;- border-radius: 3px;- background-image: linear-gradient(to right, rgb(130, 86, 208) 0%, var(--primary-color) 100%)- }+ .update-progress-rate {+ height: 6px;+ border-radius: 3px;+ background-image: linear-gradient(to right, rgb(130, 86, 208) 0%, var(--primary-color) 100%)+ }- .update-progress-num {- margin: 0 10px;- }-}\ No newline at end of file+ .update-progress-num {+ margin: 0 10px;+ }+}diff --git a/freemocap-ui/src/components/update/README.md b/freemocap-ui/src/components/update/README.mdindex d119a117..ca7f9eb0 100644--- a/freemocap-ui/src/components/update/README.md+++ b/freemocap-ui/src/components/update/README.md@@ -12,7 +12,8 @@ npm i electron-updater1. ##### Configuration of the update the service address and update information script:- Add a `publish` field to `electron-builder.json5` for configuring the update address and which strategy to use as the update service.+ Add a `publish` field to `electron-builder.json5` for configuring the update address and which strategy to use as the+ update service.``` json5{@@ -24,26 +25,32 @@ npm i electron-updater}```- For more information, please refer to : [electron-builder.json5...](https://github.com/electron-vite/electron-vite-react/blob/2f2880a9f19de50ff14a0785b32a4d5427477e55/electron-builder.json5#L38)+ For more information, please refer+ to : [electron-builder.json5...](https://github.com/electron-vite/electron-vite-react/blob/2f2880a9f19de50ff14a0785b32a4d5427477e55/electron-builder.json5#L38)2. ##### The update logic of Electron:- - Checking if an update is available;- - Checking the version of the software on the server;- - Checking if an update is available;- - Downloading the new version of the software from the server (when an update is available);- - Installation method;+ - Checking if an update is available;+ - Checking the version of the software on the server;+ - Checking if an update is available;+ - Downloading the new version of the software from the server (when an update is available);+ - Installation method;- For more information, please refer to : [update...](https://github.com/electron-vite/electron-vite-react/blob/main/electron/main/update.ts)+ For more information, please refer+ to : [update...](https://github.com/electron-vite/electron-vite-react/blob/main/electron/main/update.ts)3. ##### Updating UI pages in Electron:- The main function is to provide a UI page for users to trigger the update logic mentioned in (2.) above. Users can click on the page to trigger different update functions in Electron.-- For more information, please refer to : [components/update...](https://github.com/electron-vite/electron-vite-react/blob/main/src/components/update/index.tsx)+ The main function is to provide a UI page for users to trigger the update logic mentioned in (2.) above. Users can+ click on the page to trigger different update functions in Electron.++ For more information, please refer+ to : [components/update...](https://github.com/electron-vite/electron-vite-react/blob/main/src/components/update/index.tsx)----Here it is recommended to trigger updates through user actions (in this project, Electron update function is triggered after the user clicks on the "Check for updates" button).+Here it is recommended to trigger updates through user actions (in this project, Electron update function is triggered+after the user clicks on the "Check for updates" button).-For more information on using `electron-updater` for Electron updates, please refer to the documentation : [auto-update](https://www.electron.build/.html)+For more information on using `electron-updater` for Electron updates, please refer to the+documentation : [auto-update](https://www.electron.build/.html)diff --git a/freemocap-ui/src/components/update/README.zh-CN.md b/freemocap-ui/src/components/update/README.zh-CN.mdindex f2c65fcd..8270f747 100644--- a/freemocap-ui/src/components/update/README.zh-CN.md+++ b/freemocap-ui/src/components/update/README.zh-CN.md@@ -28,21 +28,21 @@ npm i electron-updater2. ##### Electronๆดๆฐ้ป่พ- - ๆฃๆตๆดๆฐๆฏๅฆๅฏ็จ๏ผ+ - ๆฃๆตๆดๆฐๆฏๅฆๅฏ็จ๏ผ- - ๆฃๆตๆๅก็ซฏ็่ฝฏไปถ็ๆฌ๏ผ+ - ๆฃๆตๆๅก็ซฏ็่ฝฏไปถ็ๆฌ๏ผ- - ๆฃๆตๆดๆฐๆฏๅฆๅฏ็จ๏ผ+ - ๆฃๆตๆดๆฐๆฏๅฆๅฏ็จ๏ผ- - ไธ่ฝฝๆๅก็ซฏๆฐ็่ฝฏไปถ๏ผๅฝๆดๆฐๅฏ็จ๏ผ๏ผ- - ๅฎ่ฃ ๆนๅผ๏ผ+ - ไธ่ฝฝๆๅก็ซฏๆฐ็่ฝฏไปถ๏ผๅฝๆดๆฐๅฏ็จ๏ผ๏ผ+ - ๅฎ่ฃ ๆนๅผ๏ผ- ๆดๅค่ง : [update...](https://github.com/electron-vite/electron-vite-react/blob/main/electron/main/update.ts)+ๆดๅค่ง : [update...](https://github.com/electron-vite/electron-vite-react/blob/main/electron/main/update.ts)3. ##### ElectronๆดๆฐUI้กต้ข- ไธป่ฆๅ่ฝๆฏ๏ผ็จๆท่งฆๅไธ่ฟฐ(2.)ๆดๆฐ้ป่พ็UI้กต้ขใ็จๆทๅฏไปฅ้่ฟ็นๅป้กต้ข่งฆๅelectronๆดๆฐ็ไธๅๅ่ฝใ- ๆดๅค่ง : [components/update.ts...](https://github.com/electron-vite/electron-vite-react/tree/main/src/components/update/index.tsx)+ ไธป่ฆๅ่ฝๆฏ๏ผ็จๆท่งฆๅไธ่ฟฐ(2.)ๆดๆฐ้ป่พ็UI้กต้ขใ็จๆทๅฏไปฅ้่ฟ็นๅป้กต้ข่งฆๅelectronๆดๆฐ็ไธๅๅ่ฝใ+ ๆดๅค่ง : [components/update.ts...](https://github.com/electron-vite/electron-vite-react/tree/main/src/components/update/index.tsx)---diff --git a/freemocap-ui/src/components/update/index.tsx b/freemocap-ui/src/components/update/index.tsxindex 93f1f383..fef88a9f 100644--- a/freemocap-ui/src/components/update/index.tsx+++ b/freemocap-ui/src/components/update/index.tsx@@ -5,128 +5,129 @@ import Progress from '@/components/update/Progress'import './update.css'const Update = () => {- const [checking, setChecking] = useState(false)- const [updateAvailable, setUpdateAvailable] = useState(false)- const [versionInfo, setVersionInfo] = useState<VersionInfo>()- const [updateError, setUpdateError] = useState<ErrorType>()- const [progressInfo, setProgressInfo] = useState<Partial<ProgressInfo>>()- const [modalOpen, setModalOpen] = useState<boolean>(false)- const [modalBtn, setModalBtn] = useState<{- cancelText?: string- okText?: string- onCancel?: () => void- onOk?: () => void- }>({- onCancel: () => setModalOpen(false),- onOk: () => window.ipcRenderer.invoke('start-download'),- })+ const [checking, setChecking] = useState(false)+ const [updateAvailable, setUpdateAvailable] = useState(false)+ const [versionInfo, setVersionInfo] = useState<VersionInfo>()+ const [updateError, setUpdateError] = useState<ErrorType>()+ const [progressInfo, setProgressInfo] = useState<Partial<ProgressInfo>>()+ const [modalOpen, setModalOpen] = useState<boolean>(false)+ const [modalBtn, setModalBtn] = useState<{+ cancelText?: string+ okText?: string+ onCancel?: () => void+ onOk?: () => void+ }>({+ onCancel: () => setModalOpen(false),+ onOk: () => window.ipcRenderer.invoke('start-download'),+ })- const checkUpdate = async () => {- setChecking(true)- /**- * @type {import('electron-updater').UpdateCheckResult | null | { message: string, error: Error }}- */- const result = await window.ipcRenderer.invoke('check-update')- setProgressInfo({ percent: 0 })- setChecking(false)- setModalOpen(true)- if (result?.error) {- setUpdateAvailable(false)- setUpdateError(result?.error)+ const checkUpdate = async () => {+ setChecking(true)+ /**+ * @type {import('electron-updater').UpdateCheckResult | null | { message: string, error: Error }}+ */+ const result = await window.ipcRenderer.invoke('check-update')+ setProgressInfo({percent: 0})+ setChecking(false)+ setModalOpen(true)+ if (result?.error) {+ setUpdateAvailable(false)+ setUpdateError(result?.error)+ }}- }- const onUpdateCanAvailable = useCallback((_event: Electron.IpcRendererEvent, arg1: VersionInfo) => {- setVersionInfo(arg1)- setUpdateError(undefined)- // Can be update- if (arg1.update) {- setModalBtn(state => ({- ...state,- cancelText: 'Cancel',- okText: 'Update',- onOk: () => window.ipcRenderer.invoke('start-download'),- }))- setUpdateAvailable(true)- } else {- setUpdateAvailable(false)- }- }, [])+ const onUpdateCanAvailable = useCallback((_event: Electron.IpcRendererEvent, arg1: VersionInfo) => {+ setVersionInfo(arg1)+ setUpdateError(undefined)+ // Can be update+ if (arg1.update) {+ setModalBtn(state => ({+ ...state,+ cancelText: 'Cancel',+ okText: 'Update',+ onOk: () => window.ipcRenderer.invoke('start-download'),+ }))+ setUpdateAvailable(true)+ } else {+ setUpdateAvailable(false)+ }+ }, [])- const onUpdateError = useCallback((_event: Electron.IpcRendererEvent, arg1: ErrorType) => {- setUpdateAvailable(false)- setUpdateError(arg1)- }, [])+ const onUpdateError = useCallback((_event: Electron.IpcRendererEvent, arg1: ErrorType) => {+ setUpdateAvailable(false)+ setUpdateError(arg1)+ }, [])- const onDownloadProgress = useCallback((_event: Electron.IpcRendererEvent, arg1: ProgressInfo) => {- setProgressInfo(arg1)- }, [])+ const onDownloadProgress = useCallback((_event: Electron.IpcRendererEvent, arg1: ProgressInfo) => {+ setProgressInfo(arg1)+ }, [])- const onUpdateDownloaded = useCallback((_event: Electron.IpcRendererEvent, ...args: any[]) => {- setProgressInfo({ percent: 100 })- setModalBtn(state => ({- ...state,- cancelText: 'Later',- okText: 'Install now',- onOk: () => window.ipcRenderer.invoke('quit-and-install'),- }))- }, [])+ const onUpdateDownloaded = useCallback((_event: Electron.IpcRendererEvent, ...args: any[]) => {+ setProgressInfo({percent: 100})+ setModalBtn(state => ({+ ...state,+ cancelText: 'Later',+ okText: 'Install now',+ onOk: () => window.ipcRenderer.invoke('quit-and-install'),+ }))+ }, [])- useEffect(() => {- // Get version information and whether to update- window.ipcRenderer.on('update-can-available', onUpdateCanAvailable)- window.ipcRenderer.on('update-error', onUpdateError)- window.ipcRenderer.on('download-progress', onDownloadProgress)- window.ipcRenderer.on('update-downloaded', onUpdateDownloaded)+ useEffect(() => {+ // Get version information and whether to update+ window.ipcRenderer.on('update-can-available', onUpdateCanAvailable)+ window.ipcRenderer.on('update-error', onUpdateError)+ window.ipcRenderer.on('download-progress', onDownloadProgress)+ window.ipcRenderer.on('update-downloaded', onUpdateDownloaded)- return () => {- window.ipcRenderer.off('update-can-available', onUpdateCanAvailable)- window.ipcRenderer.off('update-error', onUpdateError)- window.ipcRenderer.off('download-progress', onDownloadProgress)- window.ipcRenderer.off('update-downloaded', onUpdateDownloaded)- }- }, [])+ return () => {+ window.ipcRenderer.off('update-can-available', onUpdateCanAvailable)+ window.ipcRenderer.off('update-error', onUpdateError)+ window.ipcRenderer.off('download-progress', onDownloadProgress)+ window.ipcRenderer.off('update-downloaded', onUpdateDownloaded)+ }+ }, [])- return (- <>- <Modal- open={modalOpen}- cancelText={modalBtn?.cancelText}- okText={modalBtn?.okText}- onCancel={modalBtn?.onCancel}- onOk={modalBtn?.onOk}- footer={updateAvailable ? /* hide footer */null : undefined}- >- <div className='modal-slot'>- {updateError- ? (- <div>- <p>Error downloading the latest version.</p>- <p>{updateError.message}</p>- </div>- ) : updateAvailable- ? (- <div>- <div>The last version is: v{versionInfo?.newVersion}</div>- <div className='new-version__target'>v{versionInfo?.version} -> v{versionInfo?.newVersion}</div>- <div className='update__progress'>- <div className='progress__title'>Update progress:</div>- <div className='progress__bar'>- <Progress percent={progressInfo?.percent} ></Progress>- </div>- </div>+ return (+ <>+ <Modal+ open={modalOpen}+ cancelText={modalBtn?.cancelText}+ okText={modalBtn?.okText}+ onCancel={modalBtn?.onCancel}+ onOk={modalBtn?.onOk}+ footer={updateAvailable ? /* hide footer */null : undefined}+ >+ <div className='modal-slot'>+ {updateError+ ? (+ <div>+ <p>Error downloading the latest version.</p>+ <p>{updateError.message}</p>+ </div>+ ) : updateAvailable+ ? (+ <div>+ <div>The last version is: v{versionInfo?.newVersion}</div>+ <div+ className='new-version__target'>v{versionInfo?.version} -> v{versionInfo?.newVersion}</div>+ <div className='update__progress'>+ <div className='progress__title'>Update progress:</div>+ <div className='progress__bar'>+ <Progress percent={progressInfo?.percent}></Progress>+ </div>+ </div>+ </div>+ )+ : (+ <div className='can-not-available'>{JSON.stringify(versionInfo ?? {}, null, 2)}</div>+ )}</div>- )- : (- <div className='can-not-available'>{JSON.stringify(versionInfo ?? {}, null, 2)}</div>- )}- </div>- </Modal>- <button disabled={checking} onClick={checkUpdate}>- {checking ? 'Checking...' : 'Check update'}- </button>- </>- )+ </Modal>+ <button disabled={checking} onClick={checkUpdate}>+ {checking ? 'Checking...' : 'Check update'}+ </button>+ </>+ )}export default Updatediff --git a/freemocap-ui/src/components/update/update.css b/freemocap-ui/src/components/update/update.cssindex e7769684..44bbb48b 100644--- a/freemocap-ui/src/components/update/update.css+++ b/freemocap-ui/src/components/update/update.css@@ -1,24 +1,24 @@.modal-slot {- .update-progress {- display: flex;- }+ .update-progress {+ display: flex;+ }- .new-version__target,- .update__progress {- margin-left: 40px;- }+ .new-version__target,+ .update__progress {+ margin-left: 40px;+ }- .progress__title {- margin-right: 10px;- }+ .progress__title {+ margin-right: 10px;+ }- .progress__bar {- width: 0;- flex-grow: 1;- }+ .progress__bar {+ width: 0;+ flex-grow: 1;+ }- .can-not-available {- padding: 20px;- text-align: center;- }-}\ No newline at end of file+ .can-not-available {+ padding: 20px;+ text-align: center;+ }+}diff --git a/freemocap-ui/src/components/video-folder-panel/VideoFolderPanel.tsx b/freemocap-ui/src/components/video-folder-panel/VideoFolderPanel.tsxindex db89427a..3fb9f3da 100644--- a/freemocap-ui/src/components/video-folder-panel/VideoFolderPanel.tsx+++ b/freemocap-ui/src/components/video-folder-panel/VideoFolderPanel.tsx@@ -1,26 +1,26 @@-// skellycam-ui/src/components/video-folder-panel/VideoFolderPanel.tsx+// freemocap-ui/src/components/video-folder-panel/VideoFolderPanel.tsximport React, {useState} from 'react';import {- Accordion,- AccordionDetails,- AccordionSummary,- alpha,- Box,- Button,- Checkbox,- FormControlLabel,- IconButton,- List,- ListItem,- ListItemButton,- ListItemIcon,- ListItemText,- Paper,- Stack,- TextField,- Tooltip,- Typography,- useTheme+ Accordion,+ AccordionDetails,+ AccordionSummary,+ alpha,+ Box,+ Button,+ Checkbox,+ FormControlLabel,+ IconButton,+ List,+ ListItem,+ ListItemButton,+ ListItemIcon,+ ListItemText,+ Paper,+ Stack,+ TextField,+ Tooltip,+ Typography,+ useTheme} from '@mui/material';import SettingsIcon from '@mui/icons-material/Settings';import VideoLibraryIcon from '@mui/icons-material/VideoLibrary';@@ -28,265 +28,274 @@ import ExpandMoreIcon from '@mui/icons-material/ExpandMore';import FolderOpenIcon from '@mui/icons-material/FolderOpen';import PlayArrowIcon from '@mui/icons-material/PlayArrow';import VideoFileIcon from '@mui/icons-material/VideoFile';-import { useAppDispatch, useAppSelector } from "@/store/AppStateStore";-import { loadVideos, openVideoFile, selectVideoFolder } from "@/store/thunks/video-loading-thunks";+// Updated imports - using the videos thunks and selectors from the store barrel export+import {loadVideos, openVideoFile, selectVideoLoadFolder, useAppDispatch, useAppSelector} from "@/store";export const VideoFolderPanel: React.FC = () => {- const theme = useTheme();- const dispatch = useAppDispatch();+ const theme = useTheme();+ const dispatch = useAppDispatch();- const { videoFolder, videoFiles, isLoading, error } = useAppSelector(state => state.videoLoading);+ // Updated selectors to match the store structure+ const videoFolder = useAppSelector(state => state.videos.folder);+ const videoFiles = useAppSelector(state => state.videos.files);+ const isLoading = useAppSelector(state => state.videos.isLoading);+ const error = useAppSelector(state => state.videos.error);- const [showSettings, setShowSettings] = useState(false);- const [selectedVideos, setSelectedVideos] = useState<string[]>([]);- const [filterText, setFilterText] = useState('');+ const [showSettings, setShowSettings] = useState(false);+ const [selectedVideos, setSelectedVideos] = useState<string[]>([]);+ const [filterText, setFilterText] = useState('');- const handleSelectFolder = async () => {- dispatch(selectVideoFolder());- setSelectedVideos([]);- };+ const handleSelectFolder = async () => {+ dispatch(selectVideoLoadFolder());+ setSelectedVideos([]);+ };- const handleLoadVideos = () => {- if (videoFiles.length === 0) return;+ const handleLoadVideos = () => {+ if (videoFiles.length === 0) return;- const filesToLoad = selectedVideos.length > 0- ? videoFiles.filter(file => selectedVideos.includes(file.path))- : videoFiles;- dispatch(loadVideos({ folder: videoFolder, files: filesToLoad }));- };+ const filesToLoad = selectedVideos.length > 0+ ? videoFiles.filter(file => selectedVideos.includes(file.path))+ : videoFiles;+ dispatch(loadVideos({folder: videoFolder, files: filesToLoad}));+ };- const handleVideoSelect = (path: string) => {- setSelectedVideos(prev => prev.includes(path) ? prev.filter(p => p !== path) : [...prev, path]);- };+ const handleVideoSelect = (path: string) => {+ setSelectedVideos(prev => prev.includes(path) ? prev.filter(p => p !== path) : [...prev, path]);+ };- const handleSelectAll = () => {- setSelectedVideos(prev => prev.length === filteredVideos.length ? [] : filteredVideos.map(file => file.path));- };+ const handleSelectAll = () => {+ setSelectedVideos(prev => prev.length === filteredVideos.length ? [] : filteredVideos.map(file => file.path));+ };- const handleOpenVideo = (path: string) => {- dispatch(openVideoFile(path));- };+ const handleOpenVideo = (path: string) => {+ dispatch(openVideoFile(path));+ };- const filteredVideos = videoFiles.filter(file =>- file.name.toLowerCase().includes(filterText.toLowerCase())- );+ const filteredVideos = videoFiles.filter(file =>+ file.name.toLowerCase().includes(filterText.toLowerCase())+ );- return (- <Accordion- defaultExpanded- sx={{- borderRadius: 2,- '&:before': { display: 'none' },- boxShadow: theme.shadows[3]- }}- >- <Box sx={{- display: 'flex',- alignItems: 'center',- backgroundColor: theme.palette.primary.main,- borderTopLeftRadius: 8,- borderTopRightRadius: 8,- }}>- <AccordionSummary- expandIcon={<ExpandMoreIcon sx={{ color: theme.palette.primary.contrastText }} />}- sx={{- flex: 1,- color: theme.palette.primary.contrastText,- '&:hover': {- backgroundColor: theme.palette.primary.light,- }- }}- >- <Stack direction="row" alignItems="center" spacing={1}>- <VideoLibraryIcon />- <Typography variant="subtitle1" fontWeight="medium">- Video Folder Selection- </Typography>- </Stack>- </AccordionSummary>-- <Box sx={{ pr: 2 }}>- <Button- variant="contained"- color="secondary"- disabled={videoFiles.length === 0 || isLoading || (selectedVideos.length === 0 && videoFiles.length > 0)}- onClick={handleLoadVideos}- startIcon={<PlayArrowIcon />}- sx={{ minWidth: '120px' }}- >- Load Videos- </Button>- </Box>-- <Box sx={{ pr: 2 }}>- <IconButton- onClick={() => setShowSettings(!showSettings)}+ return (+ <Accordion+ defaultExpandedsx={{- color: showSettings- ? theme.palette.primary.contrastText- : alpha(theme.palette.primary.contrastText, 0.7)+ borderRadius: 2,+ '&:before': {display: 'none'},+ boxShadow: theme.shadows[3]}}- >- <SettingsIcon />- </IconButton>- </Box>- </Box>-- <AccordionDetails sx={{ p: 2, bgcolor: 'background.default' }}>- <Paper- elevation={0}- sx={{- bgcolor: 'background.paper',- borderRadius: 2,- overflow: 'hidden',- p: 2- }}>- <Stack spacing={2}>- <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>- <TextField- fullWidth- label="Video Folder Path"- variant="outlined"- value={videoFolder}- InputProps={{- readOnly: true,- }}- disabled={isLoading}- />- <Button- variant="outlined"- startIcon={<FolderOpenIcon />}- onClick={handleSelectFolder}- disabled={isLoading}- >- Browse- </Button>- </Box>-- {error && (- <Typography color="error" variant="body2">- Error: {error}- </Typography>- )}+ <Box sx={{+ display: 'flex',+ alignItems: 'center',+ backgroundColor: theme.palette.primary.main,+ borderTopLeftRadius: 8,+ borderTopRightRadius: 8,+ }}>+ <AccordionSummary+ expandIcon={<ExpandMoreIcon sx={{color: theme.palette.primary.contrastText}}/>}+ sx={{+ flex: 1,+ color: theme.palette.primary.contrastText,+ '&:hover': {+ backgroundColor: theme.palette.primary.light,+ }+ }}+ >+ <Stack direction="row" alignItems="center" spacing={1}>+ <VideoLibraryIcon/>+ <Typography variant="subtitle1" fontWeight="medium">+ Video Folder Selection+ </Typography>+ </Stack>+ </AccordionSummary>- {videoFiles.length > 0 && (- <Box>- <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>- <Typography variant="subtitle2">- Found {videoFiles.length} video files- {filterText && ` (${filteredVideos.length} shown)`}:- </Typography>+ <Box sx={{pr: 2}}>+ <Button+ variant="contained"+ color="secondary"+ disabled={videoFiles.length === 0 || isLoading || (selectedVideos.length === 0 && videoFiles.length > 0)}+ onClick={handleLoadVideos}+ startIcon={<PlayArrowIcon/>}+ sx={{minWidth: '120px'}}+ >+ Load Videos+ </Button>+ </Box>- <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>- <TextField- size="small"- placeholder="Filter videos..."- value={filterText}- onChange={(e) => setFilterText(e.target.value)}- sx={{ width: '200px' }}- />- <FormControlLabel- control={- <Checkbox- checked={selectedVideos.length === filteredVideos.length && filteredVideos.length > 0}- indeterminate={selectedVideos.length > 0 && selectedVideos.length < filteredVideos.length}- onChange={handleSelectAll}- disabled={filteredVideos.length === 0}- />- }- label="Select All"- />- </Box>+ <Box sx={{pr: 2}}>+ <IconButton+ onClick={() => setShowSettings(!showSettings)}+ sx={{+ color: showSettings+ ? theme.palette.primary.contrastText+ : alpha(theme.palette.primary.contrastText, 0.7)+ }}+ >+ <SettingsIcon/>+ </IconButton></Box>+ </Box>+ <AccordionDetails sx={{p: 2, bgcolor: 'background.default'}}><Paper- variant="outlined"- sx={{- maxHeight: '200px',- overflow: 'auto',- p: 0,- }}+ elevation={0}+ sx={{+ bgcolor: 'background.paper',+ borderRadius: 2,+ overflow: 'hidden',+ p: 2+ }}>- <List dense disablePadding>- {filteredVideos.map((file) => (- <ListItem- key={file.path}- disablePadding- secondaryAction={- <Tooltip title="Open video">- <IconButton- edge="end"- size="small"- onClick={() => handleOpenVideo(file.path)}- >- <PlayArrowIcon />- </IconButton>- </Tooltip>- }- >- <ListItemButton- dense- onClick={() => handleVideoSelect(file.path)}- selected={selectedVideos.includes(file.path)}- >- <ListItemIcon sx={{ minWidth: 36 }}>- <Checkbox- edge="start"- checked={selectedVideos.includes(file.path)}- tabIndex={-1}- disableRipple+ <Stack spacing={2}>+ <Box sx={{display: 'flex', alignItems: 'center', gap: 1}}>+ <TextField+ fullWidth+ label="Video Folder Path"+ variant="outlined"+ value={videoFolder}+ InputProps={{+ readOnly: true,+ }}+ disabled={isLoading}/>- </ListItemIcon>- <ListItemIcon sx={{ minWidth: 36 }}>- <VideoFileIcon fontSize="small" />- </ListItemIcon>- <ListItemText- primary={file.name}- primaryTypographyProps={{- variant: 'body2',- sx: { fontFamily: 'monospace' }- }}- />- </ListItemButton>- </ListItem>- ))}- </List>- </Paper>- </Box>- )}+ <Button+ variant="outlined"+ startIcon={<FolderOpenIcon/>}+ onClick={handleSelectFolder}+ disabled={isLoading}+ >+ Browse+ </Button>+ </Box>++ {error && (+ <Typography color="error" variant="body2">+ Error: {error}+ </Typography>+ )}- {showSettings && (- <Paper- variant="outlined"- sx={{ p: 2 }}- >- <Typography variant="subtitle2" gutterBottom>- Video Loading Settings- </Typography>- <Typography variant="body2" color="text.secondary" gutterBottom>- Configure how videos are loaded and processed.- </Typography>+ {videoFiles.length > 0 && (+ <Box>+ <Box sx={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ mb: 1+ }}>+ <Typography variant="subtitle2">+ Found {videoFiles.length} video files+ {filterText && ` (${filteredVideos.length} shown)`}:+ </Typography>- <Stack spacing={1} sx={{ mt: 1 }}>- <FormControlLabel- control={<Checkbox defaultChecked />}- label="Automatically synchronize videos"- />- <FormControlLabel- control={<Checkbox />}- label="Extract frames on load"- />- <FormControlLabel- control={<Checkbox />}- label="Generate thumbnails"- />- </Stack>- </Paper>- )}- </Stack>- </Paper>- </AccordionDetails>- </Accordion>- );+ <Box sx={{display: 'flex', alignItems: 'center', gap: 1}}>+ <TextField+ size="small"+ placeholder="Filter videos..."+ value={filterText}+ onChange={(e) => setFilterText(e.target.value)}+ sx={{width: '200px'}}+ />+ <FormControlLabel+ control={+ <Checkbox+ checked={selectedVideos.length === filteredVideos.length && filteredVideos.length > 0}+ indeterminate={selectedVideos.length > 0 && selectedVideos.length < filteredVideos.length}+ onChange={handleSelectAll}+ disabled={filteredVideos.length === 0}+ />+ }+ label="Select All"+ />+ </Box>+ </Box>++ <Paper+ variant="outlined"+ sx={{+ maxHeight: '200px',+ overflow: 'auto',+ p: 0,+ }}+ >+ <List dense disablePadding>+ {filteredVideos.map((file) => (+ <ListItem+ key={file.path}+ disablePadding+ secondaryAction={+ <Tooltip title="Open video">+ <IconButton+ edge="end"+ size="small"+ onClick={() => handleOpenVideo(file.path)}+ >+ <PlayArrowIcon/>+ </IconButton>+ </Tooltip>+ }+ >+ <ListItemButton+ dense+ onClick={() => handleVideoSelect(file.path)}+ selected={selectedVideos.includes(file.path)}+ >+ <ListItemIcon sx={{minWidth: 36}}>+ <Checkbox+ edge="start"+ checked={selectedVideos.includes(file.path)}+ tabIndex={-1}+ disableRipple+ />+ </ListItemIcon>+ <ListItemIcon sx={{minWidth: 36}}>+ <VideoFileIcon fontSize="small"/>+ </ListItemIcon>+ <ListItemText+ primary={file.name}+ primaryTypographyProps={{+ variant: 'body2',+ sx: {fontFamily: 'monospace'}+ }}+ />+ </ListItemButton>+ </ListItem>+ ))}+ </List>+ </Paper>+ </Box>+ )}++ {showSettings && (+ <Paper+ variant="outlined"+ sx={{p: 2}}+ >+ <Typography variant="subtitle2" gutterBottom>+ Video Loading Settings+ </Typography>+ <Typography variant="body2" color="text.secondary" gutterBottom>+ Configure how videos are loaded and processed.+ </Typography>++ <Stack spacing={1} sx={{mt: 1}}>+ <FormControlLabel+ control={<Checkbox defaultChecked/>}+ label="Automatically synchronize videos"+ />+ <FormControlLabel+ control={<Checkbox/>}+ label="Extract frames on load"+ />+ <FormControlLabel+ control={<Checkbox/>}+ label="Generate thumbnails"+ />+ </Stack>+ </Paper>+ )}+ </Stack>+ </Paper>+ </AccordionDetails>+ </Accordion>+ );};diff --git a/freemocap-ui/src/components/viewport3d/ImageMesh.tsx b/freemocap-ui/src/components/viewport3d/ImageMesh.tsxindex 9fb2a619..a1edca6a 100644--- a/freemocap-ui/src/components/viewport3d/ImageMesh.tsx+++ b/freemocap-ui/src/components/viewport3d/ImageMesh.tsx@@ -1,94 +1,78 @@-import React, { useEffect, useRef, useState } from 'react';+import {useEffect, useMemo, useRef} from 'react';+import {useFrame} from '@react-three/fiber';import * as THREE from 'three';-import { CameraImageData } from "@/context/websocket-context/useWebsocketBinaryMessageProcessor";-import { useWebSocketContext } from "@/context/websocket-context/WebSocketContext";-import {Vector3} from "three";+import {useServer} from '@/services';interface ImageMeshProps {- cameraImageData: CameraImageData;- position: [number, number, number];+ cameraId: string;+ position: [number, number, number];}-export const ImageMesh: React.FC<ImageMeshProps> = ({ cameraImageData, position }) => {- const { cameraId, imageBitmap, imageWidth, imageHeight, frameNumber } = cameraImageData;- const { acknowledgeFrameRendered } = useWebSocketContext();- const meshRef = useRef<THREE.Mesh>(null);- const textureRef = useRef<THREE.Texture | null>(null);- const [aspectRatio, setAspectRatio] = useState(2);-- // Initialize texture once- useEffect(() => {- // Create texture only once and reuse it- if (!textureRef.current) {- const newTexture = new THREE.Texture();- // Set Color Management- newTexture.minFilter = THREE.LinearFilter;- newTexture.magFilter = THREE.LinearFilter;+export function ImageMesh({ cameraId, position }: ImageMeshProps) {+ const { subscribeToFrames } = useServer();- // Do a buncha weird nonsense to get the image to show up correctly in the scene- newTexture.wrapS = THREE.RepeatWrapping;- newTexture.repeat.x = -1; // Flip texture horizontally- newTexture.center = new THREE.Vector2(0.5, 0.5);- newTexture.rotation = Math.PI;- newTexture.flipY = false;- textureRef.current = newTexture;- }+ const currentBitmapRef = useRef<ImageBitmap | null>(null);+ const textureRef = useRef<THREE.Texture | null>(null);+ const hasNewFrameRef = useRef<boolean>(false);- return () => {- // Clean up texture on unmount- if (textureRef.current) {- textureRef.current.dispose();- textureRef.current = null;- }- };+ // FIX 1: Change from CanvasTexture to Texture+ const texture = useMemo(() => {+ const tex = new THREE.Texture(); // โ Changed from CanvasTexture+ tex.minFilter = THREE.LinearFilter;+ tex.magFilter = THREE.LinearFilter;+ tex.format = THREE.RGBAFormat;+ tex.generateMipmaps = false;+ textureRef.current = tex;+ return tex;}, []);- // Update texture with new image data- useEffect(() => {- if (!imageBitmap || !meshRef.current || !textureRef.current) return;+ const material = useMemo(() => {+ return new THREE.MeshBasicMaterial({+ map: texture,+ side: THREE.DoubleSide,+ });+ }, [texture]);- try {- // Update aspect ratio only when dimensions change- const newAspectRatio = imageWidth / imageHeight;- if (aspectRatio !== newAspectRatio) {- setAspectRatio(newAspectRatio);+ // FIX 2: Subscribe with cameraId parameter+ useEffect(() => {+ const unsubscribe = subscribeToFrames(cameraId, (bitmap) => {+ // Close previous bitmap to free memory+ if (currentBitmapRef.current) {+ currentBitmapRef.current.close();}+ currentBitmapRef.current = bitmap;+ hasNewFrameRef.current = true;+ });- // Update texture with new image data without creating a new texture- textureRef.current.image = imageBitmap;- textureRef.current.flipY = true;-- textureRef.current.needsUpdate = true;-- // Apply texture to material if not already applied- if (meshRef.current.material instanceof THREE.MeshBasicMaterial) {- if (meshRef.current.material.map !== textureRef.current) {- meshRef.current.material.map = textureRef.current;- }- meshRef.current.material.needsUpdate = true;+ return () => {+ unsubscribe();+ if (currentBitmapRef.current) {+ currentBitmapRef.current.close();+ currentBitmapRef.current = null;}+ };+ }, [cameraId, subscribeToFrames]);- // Acknowledge that the frame was rendered- acknowledgeFrameRendered(cameraId, frameNumber);- } catch (error) {- console.error('Error processing image:', error);+ // Update texture in render loop+ useFrame(() => {+ if (hasNewFrameRef.current && currentBitmapRef.current && textureRef.current) {+ textureRef.current.image = currentBitmapRef.current;+ textureRef.current.needsUpdate = true;+ hasNewFrameRef.current = false;}- }, [cameraId, imageBitmap, imageWidth, imageHeight, frameNumber, aspectRatio, acknowledgeFrameRendered]);+ });- // Calculate dimensions for the plane geometry- let meshWidth, meshHeight;- if (imageWidth >= imageHeight) {- const meshWidth = 2;- const meshHeight = meshWidth / aspectRatio;- } else {- const meshHeight = 2;- const meshWidth = meshHeight * aspectRatio;- }+ const meshGeometry = useMemo(() => {+ const height = 2.0;+ const width = height * (16 / 9);+ return new THREE.PlaneGeometry(width, height);+ }, []);return (- <mesh ref={meshRef} position={position}>- <planeGeometry args={[imageWidth/300, imageHeight/300]} />- <meshBasicMaterial transparent={false} />- </mesh>+ <mesh+ position={position}+ geometry={meshGeometry}+ material={material}+ />);-};+}diff --git a/freemocap-ui/src/components/viewport3d/ThreeJsCanvas.tsx b/freemocap-ui/src/components/viewport3d/ThreeJsCanvas.tsxindex 2e41345e..27061efa 100644--- a/freemocap-ui/src/components/viewport3d/ThreeJsCanvas.tsx+++ b/freemocap-ui/src/components/viewport3d/ThreeJsCanvas.tsx@@ -1,18 +1,21 @@import {Canvas} from "@react-three/fiber";import {ThreeJsScene} from "@/components/viewport3d/ThreeJsScene";+import {Box} from "@mui/material";export function ThreeJsCanvas() {return (- <div className="h-screen w-screen" >+ <Box sx={{width: '100%',+ height: '100%',+ }}><Canvasshadowscamera={{position: [5, 5, 5], fov: 75}}><ThreeJsScene/></Canvas>- </div>+ </Box>);}diff --git a/freemocap-ui/src/components/viewport3d/ThreeJsScene.tsx b/freemocap-ui/src/components/viewport3d/ThreeJsScene.tsxindex 68216f73..31d5a62e 100644--- a/freemocap-ui/src/components/viewport3d/ThreeJsScene.tsx+++ b/freemocap-ui/src/components/viewport3d/ThreeJsScene.tsx@@ -1,77 +1,207 @@-import {useMemo, useRef} from "react";-import {CameraHelper, InstancedMesh, Matrix4, MeshStandardMaterial, PerspectiveCamera, SphereGeometry} from "three";+import {useEffect, useMemo, useRef} from "react";+import {+ CameraHelper,+ InstancedMesh,+ MeshStandardMaterial,+ PerspectiveCamera,+ SphereGeometry,+ Object3D,+ Matrix4,+ Vector3+} from "three";import {extend, useFrame} from "@react-three/fiber";import {CameraControls, Grid} from "@react-three/drei";-import {ImageMesh} from "@/components/viewport3d/ImageMesh";-import {useWebSocketContext} from "@/context/websocket-context/WebSocketContext";+import {useServer} from "@/services";extend({CameraHelper});+const MAX_POINTS = 1000; // Pre-allocate for max expected points+const POINT_SCALE = 1; // Scale points down since they're in meters+const DUMMY = new Object3D(); // Reusable dummy object for matrix updates++interface Point3d {+ x: number;+ y: number;+ z: number;+}+export function ThreeJsScene() {- const {latestImageData} = useWebSocketContext();- const sphereRef = useRef<InstancedMesh>(null);+ const { connectedCameraIds, subscribeToTrackedPoints } = useServer();+ const instancedMeshRef = useRef<InstancedMesh>(null);const cameraRefs = useRef<PerspectiveCamera[]>([]);- const latestPoints3d = {} // dummy for now- const numPoints = latestPoints3d?Object.keys(latestPoints3d).length : 0;- const numberOfCameras = latestImageData ? Object.keys(latestImageData).length : 0;- const sphereGeometry = useMemo(() => new SphereGeometry(0.1, 16, 16), []);- const sphereMaterial = useMemo(() => new MeshStandardMaterial({color: 'red'}), []);- const maxRowsColumns = Math.ceil(Math.sqrt(numberOfCameras))+1;-- const cameraPositionsMap = Object.fromEntries(- Object.entries(latestImageData).map(([cameraId, cameraImageData]) => {- // Calculate position in a grid with max columns based on sqrt of camera count- const cameraIndex = cameraImageData?.cameraIndex ;- const columnIndex = cameraImageData?.cameraIndex % maxRowsColumns;- const rowIndex = Math.floor(cameraImageData?.cameraIndex / maxRowsColumns);-- // Set spacing between cameras- const verticalSpacing = 2.5;- const horizontalSpacing = 2.2;- const verticalOffset = 1;-- const xPosition = columnIndex * horizontalSpacing - horizontalSpacing; // Center the grid++ // Performance-critical: Direct refs to avoid React re-renders+ const trackedPointsRef = useRef<Map<string, Point3d>>(new Map());+ const pointNameToIndexRef = useRef<Map<string, number>>(new Map());+ const nextAvailableIndexRef = useRef<number>(0);+ const dirtyIndicesRef = useRef<Set<number>>(new Set());++ // Pre-create geometry and material once+ const sphereGeometry = useMemo(() => new SphereGeometry(0.05, 8, 6), []); // Bigger spheres+ const sphereMaterial = useMemo(() => new MeshStandardMaterial({+ color: '#ff0066', // Brighter color for visibility+ roughness: 0.4,+ metalness: 0.6,+ emissive: '#ff0066',+ emissiveIntensity: 0.2+ }), []);++ // Calculate positions for cameras in a grid+ const cameraPositions = useMemo(() => {+ const numCameras = connectedCameraIds.length;+ if (numCameras === 0) return [];++ const maxRowsColumns = Math.ceil(Math.sqrt(numCameras));+ const verticalSpacing = 2.5;+ const horizontalSpacing = 2.2;+ const verticalOffset = 1;++ return connectedCameraIds.map((_, index) => {+ const columnIndex = index % maxRowsColumns;+ const rowIndex = Math.floor(index / maxRowsColumns);++ const xPosition = columnIndex * horizontalSpacing - (maxRowsColumns * horizontalSpacing) / 2;const yPosition = rowIndex * verticalSpacing + verticalOffset;- // const xPosition = cameraIndex * horizontalSpacing - numberOfCameras/2; // Center the grid- // const yPosition = 2;//rowIndex * verticalSpacing + verticalOffset;const zPosition = 0;- return [cameraId, [xPosition, yPosition, zPosition]];- })- );- useFrame(() => {+ return [xPosition, yPosition, zPosition] as [number, number, number];+ });+ }, [connectedCameraIds]);++ // Subscribe to tracked points updates+ useEffect(() => {+ const unsubscribe = subscribeToTrackedPoints((newPoints: Map<string, Point3d>) => {+ // Only update the ref and mark dirty indices - no React state updates!+ const prevPoints = trackedPointsRef.current;+ trackedPointsRef.current = newPoints;++ // Find new points that need indices assigned+ for (const [pointName, point] of newPoints) {+ if (!pointNameToIndexRef.current.has(pointName)) {+ // New point detected - assign it an index+ if (nextAvailableIndexRef.current >= MAX_POINTS) {+ console.error(`Maximum points (${MAX_POINTS}) exceeded!`);+ continue;+ }++ const newIndex = nextAvailableIndexRef.current++;+ pointNameToIndexRef.current.set(pointName, newIndex);+ dirtyIndicesRef.current.add(newIndex);+ } else {+ // Existing point - check if position changed+ const prevPoint = prevPoints.get(pointName);+ if (!prevPoint ||+ prevPoint.x !== point.x ||+ prevPoint.y !== point.y ||+ prevPoint.z !== point.z) {+ const index = pointNameToIndexRef.current.get(pointName)!;+ dirtyIndicesRef.current.add(index);+ }+ }+ }++ // Mark removed points as dirty (move them far away to hide)+ for (const [pointName] of prevPoints) {+ if (!newPoints.has(pointName)) {+ const index = pointNameToIndexRef.current.get(pointName);+ if (index !== undefined) {+ dirtyIndicesRef.current.add(index);+ }+ }+ }+ });++ return unsubscribe;+ }, [subscribeToTrackedPoints]);- // Make the camera look at the origin (0, 0, 0)+ // Initialize instance matrices on mount+ useEffect(() => {+ if (!instancedMeshRef.current) return;++ // Hide all instances initially by moving them far away+ const farAway = new Vector3(10000, 10000, 10000);+ for (let i = 0; i < MAX_POINTS; i++) {+ DUMMY.position.copy(farAway);+ DUMMY.scale.set(POINT_SCALE, POINT_SCALE, POINT_SCALE);+ DUMMY.updateMatrix();+ instancedMeshRef.current.setMatrixAt(i, DUMMY.matrix);+ }+ instancedMeshRef.current.instanceMatrix.needsUpdate = true;+ instancedMeshRef.current.count = MAX_POINTS;+ }, []);++ // Update matrices in the render loop for maximum performance+ useFrame(() => {+ // Update camera orientationscameraRefs.current.forEach(camera => {if (camera) {camera.lookAt(0, 0, 0);}- })+ });++ // Only update if we have dirty indices+ if (!instancedMeshRef.current || dirtyIndicesRef.current.size === 0) return;++ const mesh = instancedMeshRef.current;+ const points = trackedPointsRef.current;+ const nameToIndex = pointNameToIndexRef.current;+ const farAway = new Vector3(10000, 10000, 10000);++ // Process only dirty indices+ for (const index of dirtyIndicesRef.current) {+ // Find the point name for this index+ let pointName: string | null = null;+ for (const [name, idx] of nameToIndex) {+ if (idx === index) {+ pointName = name;+ break;+ }+ }++ if (pointName && points.has(pointName)) {+ // Update position for visible point+ const point = points.get(pointName)!;+ // Scale coordinates to bring them closer to origin+ const scale = 0.2; // Adjust this to fit your scene+ DUMMY.position.set(+ point.x * scale,+ point.y * scale,+ (point.z - 15) * scale // Center around z=15 then scale+ );+ DUMMY.scale.set(POINT_SCALE, POINT_SCALE, POINT_SCALE);+ } else {+ // Hide removed/missing points+ DUMMY.position.copy(farAway);+ DUMMY.scale.set(0, 0, 0);+ }++ DUMMY.updateMatrix();+ mesh.setMatrixAt(index, DUMMY.matrix);+ }++ // Only update the GPU buffer if we made changes+ if (dirtyIndicesRef.current.size > 0) {+ mesh.instanceMatrix.needsUpdate = true;+ dirtyIndicesRef.current.clear();+ }});return (<><CameraControls makeDefault/>- {/*{cameraPositions.map((position, index) => (*/}- {/* <perspectiveCamera*/}- {/* key={index}*/}- {/* ref={el => cameraRefs.current[index] = el!}*/}- {/* // @ts-ignore*/}- {/* position={position}*/}- {/* near={0.1}*/}- {/* far={1}*/}- {/* />*/}- {/*))}*/}+{cameraRefs.current.map((camera, index) => camera && (<cameraHelper key={index} args={[camera]} />))}- <ambientLight intensity={0.1}/>++ <ambientLight intensity={0.5}/><directionalLightcastShadow- position={[0, 0.01, 0]}- intensity={0.1}+ position={[5, 5, 5]}+ intensity={0.5}shadow-mapSize={1024}/>+<GridrenderOrder={-1}position={[0, -0.01, 0]}@@ -84,20 +214,15 @@ export function ThreeJsScene() {sectionColor={[0.5, 0, 0.5]}fadeDistance={100}/>+<axesHelper/>- {latestImageData &&- Object.entries(latestImageData).map(([cameraId, cameraImageData], index) =>- cameraImageData?.imageBitmap ? (- <ImageMesh- key={cameraId}- cameraImageData={cameraImageData}- position={cameraPositionsMap[cameraId] as [number, number, number] }- />- ) : null- )}- {numPoints > 0 && (- <instancedMesh ref={sphereRef} args={[sphereGeometry, sphereMaterial, numPoints]}/>- )}++ {/* Single InstancedMesh for all tracked points */}+ <instancedMesh+ ref={instancedMeshRef}+ args={[sphereGeometry, sphereMaterial, MAX_POINTS]}+ frustumCulled={false}+ /></>);}diff --git a/freemocap-ui/src/config/appUrlService.ts b/freemocap-ui/src/config/appUrlService.tsdeleted file mode 100644index 35e15067..00000000--- a/freemocap-ui/src/config/appUrlService.ts+++ /dev/null@@ -1,50 +0,0 @@-export interface DefaultUrlConfig {- host: string;- port: number;-}--// Default URL configuration-const defaultUrlConfig: DefaultUrlConfig = {- host: 'localhost',- port: 8007,-};---// Get the base HTTP URL-const getBaseHttpUrl = () => {- const {host, port} = defaultUrlConfig;- return `http://${host}:${port}`;-};--// Get a specific API URL-const getApiUrl = (path: string) => {- return `${getBaseHttpUrl()}${path}`;-};--// Get WebSocket URL-const getWebSocketUrl = () => {- const {host, port} = defaultUrlConfig;- return `ws://${host}:${port}/freemocap/websocket/connect`;-};--// Get all HTTP endpoint URLs-const getHttpEndpointUrls = () => {- return {- detectCameras: getApiUrl('/skellycam/camera/detect'),- createGroup: getApiUrl('/skellycam/camera/group/create'),- closeAll: getApiUrl('/skellycam/camera/group/close/all'),- updateConfigs: getApiUrl('/skellycam/camera/update'),- startRecording: getApiUrl('/skellycam/camera/group/all/record/start'),- stopRecording: getApiUrl('/skellycam/camera/group/all/record/stop'),- pauseUnpauseCameras: getApiUrl('/skellycam/camera/group/all/pause_unpause'),- connectPipeline: getApiUrl('/freemocap/pipeline/connect'),- disconnectPipeline: getApiUrl('/freemocap/pipeline/disconnect/all'),- };-};--export const urlService = {- getBaseHttpUrl,- getApiUrl,- getWebSocketUrl,- getHttpEndpointUrls,-};diff --git a/freemocap-ui/src/context/python-server-context/PythonServerContext.tsx b/freemocap-ui/src/context/python-server-context/PythonServerContext.tsxdeleted file mode 100644index a9c1d5e1..00000000--- a/freemocap-ui/src/context/python-server-context/PythonServerContext.tsx+++ /dev/null@@ -1,32 +0,0 @@-import React, { createContext, useContext, ReactNode } from "react";-import { usePythonServer } from "./usePythonServer";--interface PythonServerContextProps {- isPythonRunning: boolean;- startPythonServer: (exePath:string|null) => void;- stopPythonServer: () => void;-}--const PythonServerContext = createContext<PythonServerContextProps | undefined>(undefined);--interface PythonServerProviderProps {- children: ReactNode;-}--export const PythonServerContextProvider: React.FC<PythonServerProviderProps> = ({ children }) => {- const pythonServer = usePythonServer();-- return (- <PythonServerContext.Provider value={pythonServer}>- {children}- </PythonServerContext.Provider>- );-};--export const usePythonServerContext = () => {- const context = useContext(PythonServerContext);- if (!context) {- throw new Error('usePythonServerContext must be used within a PythonServerProvider');- }- return context;-};diff --git a/freemocap-ui/src/context/python-server-context/usePythonServer.ts b/freemocap-ui/src/context/python-server-context/usePythonServer.tsdeleted file mode 100644index 1d622884..00000000--- a/freemocap-ui/src/context/python-server-context/usePythonServer.ts+++ /dev/null@@ -1,31 +0,0 @@-import { useState, useCallback } from "react";--export const usePythonServer = () => {- const [isPythonRunning, setIsRunning] = useState(false);-- const startPythonServer = useCallback(async (exePath:string|null) => {- try {- console.log("Starting Python server...");- await window.electronAPI.startPythonServer(exePath);- setIsRunning(true);- } catch (error) {- console.error('Failed to start Python server:', error);- }- }, []);-- const stopPythonServer = useCallback(async () => {- try {- console.log("Stopping Python server...");- await window.electronAPI.stopPythonServer();- setIsRunning(false);- } catch (error) {- console.error('Failed to stop Python server:', error);- }- }, []);-- return {- isPythonRunning,- startPythonServer,- stopPythonServer- };-};diff --git a/freemocap-ui/src/context/websocket-context/WebSocketContext.tsx b/freemocap-ui/src/context/websocket-context/WebSocketContext.tsxdeleted file mode 100644index 67815ee7..00000000--- a/freemocap-ui/src/context/websocket-context/WebSocketContext.tsx+++ /dev/null@@ -1,38 +0,0 @@-import React, {createContext, ReactNode, useContext} from "react";-import { useWebSocket} from "@/context/websocket-context/useWebSocket";-import {CameraImageData} from "@/context/websocket-context/useWebsocketBinaryMessageProcessor";-import * as THREE from "three";---interface WebSocketContextProps {- isConnected: boolean;- connect: () => void;- disconnect: (shouldReconnect:boolean) => void;- latestImageData: Record<string, CameraImageData>;- acknowledgeFrameRendered: (cameraId: string, frameNumber: number) => void;-}---interface WebSocketProviderProps {- children: ReactNode;-}--const WebSocketContext = createContext<WebSocketContextProps | undefined>(undefined);--export const WebSocketContextProvider: React.FC<WebSocketProviderProps> = ({ children}) => {- const { isConnected, connect, disconnect, latestImageData,acknowledgeFrameRendered } = useWebSocket();-- return (- <WebSocketContext.Provider value={{isConnected, connect, disconnect,latestImageData,acknowledgeFrameRendered}}>- {children}- </WebSocketContext.Provider>- )-}--export const useWebSocketContext = () => {- const context = useContext(WebSocketContext);- if (!context) {- throw new Error('useWebSocketContext must be used within a WebSocketProvider');- }- return context;-};diff --git a/freemocap-ui/src/context/websocket-context/useWebSocket.ts b/freemocap-ui/src/context/websocket-context/useWebSocket.tsdeleted file mode 100644index 06f0bbf4..00000000--- a/freemocap-ui/src/context/websocket-context/useWebSocket.ts+++ /dev/null@@ -1,181 +0,0 @@-import {useCallback, useEffect, useRef, useState} from "react";-import {useAppDispatch} from "@/store/AppStateStore";-import {- FrameRenderAcknowledgment,- useWebsocketBinaryMessageProcessor-} from "@/context/websocket-context/useWebsocketBinaryMessageProcessor";-import {setBackendFramerate, setFrontendFramerate} from "@/store/slices/framerateTrackerSlice";-import {FramerateUpdateWebSocketMessage, WebSocketMessageSchema} from "@/context/websocket-context/websocket-types";-import {addLog} from "@/store/slices/logRecordsSlice";-import {urlService} from "@/config/appUrlService";---export const useWebSocket = () => {- const [isConnected, setIsConnected] = useState(false);- const [shouldReconnect, setShouldReconnect] = useState(true);- const [websocket, setWebSocket] = useState<WebSocket | null>(null);- const [connectAttempt, setConnectAttempt] = useState(0);- const dispatch = useAppDispatch();- const {- processBinaryMessage,- latestImageData,- } = useWebsocketBinaryMessageProcessor();- const latestFrameAcknowledgment = useRef<FrameRenderAcknowledgment | null>(null);- const latestCameraFrameAcknowledgment = useRef<Record<string, number>>({});-- // Handler for framerate update messages- const handleFramerateUpdate = useCallback((message: FramerateUpdateWebSocketMessage) => {- dispatch(setBackendFramerate(message.backend_framerate));- dispatch(setFrontendFramerate(message.frontend_framerate));-- }, [dispatch]);-- // handler frame render acknowledgment messages- const acknowledgeFrameRendered = useCallback(- (cameraId: string, frameNumber: number) => {- latestCameraFrameAcknowledgment.current[cameraId] = frameNumber;- const allAcknowledged = Object.values(latestCameraFrameAcknowledgment.current).every(- (acknowledgedFrame) => acknowledgedFrame === latestFrameAcknowledgment.current?.frameNumber);-- if (allAcknowledged && latestFrameAcknowledgment.current) {- // Schedule the acknowledgment to be sent on the next frame- setTimeout(() => {- if (websocket?.readyState === WebSocket.OPEN) {- websocket.send(- JSON.stringify(latestFrameAcknowledgment.current)- );- } else {- console.error('WebSocket is not open. Message not sent.');- }-- }, 0);- }- },- [latestCameraFrameAcknowledgment, latestFrameAcknowledgment, websocket]- )- // Process JSON messages with type discrimination- const processJsonMessage = useCallback((jsonData: unknown) => {- try {- // Now validate against the full message schema- const result = WebSocketMessageSchema.safeParse(jsonData);- if (!result.success) {- throw new Error("Invalid base message format: " + result.error.message);-- }-- const message = result.data;-- // Handle different message types- switch (message.message_type) {- case "framerate_update":- handleFramerateUpdate(message);- break;- case "log_record":- // Add the log record to the Redux store- dispatch(addLog(message));- break;- default:- console.log(`Received websocket message of unknown type: ${message}`);- }- } catch (error) {- console.error(`Error processing JSON message:${error}\n\nData:`, jsonData);-- }- }, [handleFramerateUpdate]);-- const handleIncomingMessage = useCallback(- async (event: MessageEvent, ws: WebSocket) => {- const data = event.data;-- // Handle binary data- if (data instanceof ArrayBuffer) {- latestFrameAcknowledgment.current = await processBinaryMessage(data);- } else if (typeof data === "string") {- if (data === 'ping') {- console.log("Received ping message, sending pong response");- ws.send("pong");- return;- }-- try {- const jsonData = JSON.parse(data);- processJsonMessage(jsonData);- } catch (error) {- console.log("Received non-JSON string data:", data);- }- } else {- console.warn("Received unsupported message type:", typeof data);- }- },- [processBinaryMessage, processJsonMessage]- );-- const connect = useCallback(() => {- if (websocket && websocket.readyState !== WebSocket.CLOSED) {- return;- }-- const ws = new WebSocket(urlService.getWebSocketUrl());- ws.binaryType = "arraybuffer";-- ws.onopen = () => {- setIsConnected(true);- setConnectAttempt(0);- setShouldReconnect(true);- ws.send("Hello from the FreeMoCap Frontend๐โจ๐");- console.log(`Websocket is connected to url: ${urlService.getWebSocketUrl()}`);- };-- ws.onclose = () => {- setIsConnected(false);- setConnectAttempt((prev) => prev + 1);- };-- ws.onmessage = (event) => {- handleIncomingMessage(event, ws).then(- () => {- }- ).catch((error) => {- console.error("Error processing incoming message:", error);- }- );- };-- ws.onerror = (error) => {- console.error("Websocket error:", error);- };- setWebSocket(ws);- }, [websocket, connectAttempt]);-- const disconnect = useCallback((shouldReconnect:boolean=true) => {- if (websocket) {- websocket.close();- setWebSocket(null);- }- setShouldReconnect(shouldReconnect)- }, [websocket]);-- useEffect(() => {- if (isConnected || !shouldReconnect) {- return;- }- const timeout = setTimeout(() => {- console.log(- `Connecting to websocket at url: ${urlService.getWebSocketUrl()} (attempt #${connectAttempt + 1})`- );- connect();- }, Math.min(1000 * Math.pow(2, connectAttempt), 10000)); // exponential backoff-- return () => {- clearTimeout(timeout);- };- }, [connect, connectAttempt]);-- return {- isConnected,- connect,- disconnect,- latestImageData,- acknowledgeFrameRendered,- };-};diff --git a/freemocap-ui/src/context/websocket-context/useWebsocketBinaryMessageProcessor.ts b/freemocap-ui/src/context/websocket-context/useWebsocketBinaryMessageProcessor.tsdeleted file mode 100644index 5f0b1987..00000000--- a/freemocap-ui/src/context/websocket-context/useWebsocketBinaryMessageProcessor.ts+++ /dev/null@@ -1,275 +0,0 @@-import {useCallback, useRef, useState} from "react";-import * as THREE from "three";--// Define the message types from the Python code-enum MessageType {- PAYLOAD_HEADER = 0,- FRAME_HEADER = 1,- PAYLOAD_FOOTER = 2,-}--// Structure sizes and offsets based on the Python dtype definitions-// Payload Header constants-const PAYLOAD_HEADER_SIZE = 24;-const PAYLOAD_HEADER_MESSAGE_TYPE_OFFSET = 0;-const PAYLOAD_HEADER_MESSAGE_TYPE_SIZE = 1;-const PAYLOAD_HEADER_PADDING_SIZE = 7;-const PAYLOAD_HEADER_FRAME_NUMBER_OFFSET = PAYLOAD_HEADER_MESSAGE_TYPE_SIZE + PAYLOAD_HEADER_PADDING_SIZE;-const PAYLOAD_HEADER_FRAME_NUMBER_SIZE = 8;-const PAYLOAD_HEADER_NUM_CAMERAS_OFFSET = PAYLOAD_HEADER_FRAME_NUMBER_OFFSET + PAYLOAD_HEADER_FRAME_NUMBER_SIZE;-const PAYLOAD_HEADER_NUM_CAMERAS_SIZE = 4;-const PAYLOAD_HEADER_PADDING_END_SIZE = 4;--// Frame Header constants-const FRAME_HEADER_SIZE = 56;-const FRAME_HEADER_MESSAGE_TYPE_OFFSET = 0;-const FRAME_HEADER_MESSAGE_TYPE_SIZE = 1;-const FRAME_HEADER_PADDING_SIZE = 7;-const FRAME_HEADER_FRAME_NUMBER_OFFSET = FRAME_HEADER_MESSAGE_TYPE_SIZE + FRAME_HEADER_PADDING_SIZE;-const FRAME_HEADER_FRAME_NUMBER_SIZE = 8;-const FRAME_HEADER_CAMERA_ID_OFFSET = FRAME_HEADER_FRAME_NUMBER_OFFSET + FRAME_HEADER_FRAME_NUMBER_SIZE;-const FRAME_HEADER_CAMERA_ID_SIZE = 16;-const FRAME_HEADER_CAMERA_INDEX_OFFSET = FRAME_HEADER_CAMERA_ID_OFFSET + FRAME_HEADER_CAMERA_ID_SIZE;-const FRAME_HEADER_CAMERA_INDEX_SIZE = 4;-const FRAME_HEADER_IMAGE_WIDTH_OFFSET = FRAME_HEADER_CAMERA_INDEX_OFFSET + FRAME_HEADER_CAMERA_INDEX_SIZE;-const FRAME_HEADER_IMAGE_WIDTH_SIZE = 4;-const FRAME_HEADER_IMAGE_HEIGHT_OFFSET = FRAME_HEADER_IMAGE_WIDTH_OFFSET + FRAME_HEADER_IMAGE_WIDTH_SIZE;-const FRAME_HEADER_IMAGE_HEIGHT_SIZE = 4;-const FRAME_HEADER_COLOR_CHANNELS_OFFSET = FRAME_HEADER_IMAGE_HEIGHT_OFFSET + FRAME_HEADER_IMAGE_HEIGHT_SIZE;-const FRAME_HEADER_COLOR_CHANNELS_SIZE = 4;-const FRAME_HEADER_JPEG_LENGTH_OFFSET = FRAME_HEADER_COLOR_CHANNELS_OFFSET + FRAME_HEADER_COLOR_CHANNELS_SIZE;-const FRAME_HEADER_JPEG_LENGTH_SIZE = 4;--// Payload Footer constants-const PAYLOAD_FOOTER_SIZE = 24;-const PAYLOAD_FOOTER_MESSAGE_TYPE_OFFSET = 0;-const PAYLOAD_FOOTER_MESSAGE_TYPE_SIZE = 1;-const PAYLOAD_FOOTER_PADDING_SIZE = 7;-const PAYLOAD_FOOTER_FRAME_NUMBER_OFFSET = PAYLOAD_FOOTER_MESSAGE_TYPE_SIZE + PAYLOAD_FOOTER_PADDING_SIZE;-const PAYLOAD_FOOTER_FRAME_NUMBER_SIZE = 8;-const PAYLOAD_FOOTER_NUM_CAMERAS_OFFSET = PAYLOAD_FOOTER_FRAME_NUMBER_OFFSET + PAYLOAD_FOOTER_FRAME_NUMBER_SIZE;-const PAYLOAD_FOOTER_NUM_CAMERAS_SIZE = 4;-const PAYLOAD_FOOTER_PADDING_END_SIZE = 4;--interface MessageHeaderFooter {- messageType: number;- frameNumber: number;- numberOfCameras: number;-}--interface FrameHeader {- messageType: number;- frameNumber: number;- cameraId: string;- cameraIndex: number;- imageWidth: number;- imageHeight: number;- colorChannels: number;- jpegStringLength: number;-}--export interface CameraImageData {- imageBitmap?: ImageBitmap;- imageWidth: number;- imageHeight: number;- frameNumber: number;- cameraId: string;- cameraIndex: number;-}--export interface CameraDisplaySize {- width: number;- height: number;-}--export interface FrameRenderAcknowledgment {- frameNumber: number;- displayImageSizes: Record<string, CameraDisplaySize>;-}-export const useWebsocketBinaryMessageProcessor = () => {- const [latestCameraImageData, setLatestCameraImageData] = useState<Record<string, CameraImageData>>({});--- const textDecoderRef = useRef(new TextDecoder());--- const parsePayloadHeader = useCallback((dataView: DataView): MessageHeaderFooter | null => {- try {- const messageType = dataView.getUint8(PAYLOAD_HEADER_MESSAGE_TYPE_OFFSET);-- if (messageType !== MessageType.PAYLOAD_HEADER) {- console.error(`Expected payload header (0), got ${messageType}`);- return null;- }-- const frameNumber = Number(dataView.getBigInt64(PAYLOAD_HEADER_FRAME_NUMBER_OFFSET, true));- const numberOfCameras = dataView.getInt32(PAYLOAD_HEADER_NUM_CAMERAS_OFFSET, true);-- return {messageType, frameNumber, numberOfCameras};- } catch (error) {- console.error('Error parsing payload header:', error);- return null;- }- }, []);-- const parseFrameHeader = useCallback((dataView: DataView, textDecoder: TextDecoder): FrameHeader | null => {- try {- const messageType = dataView.getUint8(FRAME_HEADER_MESSAGE_TYPE_OFFSET);-- if (messageType !== MessageType.FRAME_HEADER) {- console.error(`Expected frame header (1), got ${messageType}`);- return null;- }-- const frameNumber = Number(dataView.getBigInt64(FRAME_HEADER_FRAME_NUMBER_OFFSET, true));-- // Extract camera ID (fixed 16 bytes)- const cameraIdBytes = new Uint8Array(- dataView.buffer,- dataView.byteOffset + FRAME_HEADER_CAMERA_ID_OFFSET,- FRAME_HEADER_CAMERA_ID_SIZE- );-- // Find the null terminator- let cameraIdLength = 0;- while (cameraIdLength < FRAME_HEADER_CAMERA_ID_SIZE && cameraIdBytes[cameraIdLength] !== 0) {- cameraIdLength++;- }-- const cameraId = textDecoder.decode(cameraIdBytes.slice(0, cameraIdLength));- const cameraIndex = dataView.getInt32(FRAME_HEADER_CAMERA_INDEX_OFFSET, true);- const imageWidth = dataView.getInt32(FRAME_HEADER_IMAGE_WIDTH_OFFSET, true);- const imageHeight = dataView.getInt32(FRAME_HEADER_IMAGE_HEIGHT_OFFSET, true);- const colorChannels = dataView.getInt32(FRAME_HEADER_COLOR_CHANNELS_OFFSET, true);- const jpegStringLength = dataView.getInt32(FRAME_HEADER_JPEG_LENGTH_OFFSET, true);--- return {- messageType,- frameNumber,- cameraId,- cameraIndex,- imageWidth,- imageHeight,- colorChannels,- jpegStringLength- };- } catch (error) {- console.error('Error parsing frame header:', error);- return null;- }- }, []);-- const parsePayloadFooter = useCallback((dataView: DataView,): MessageHeaderFooter | null => {- try {- const messageType = dataView.getUint8(PAYLOAD_FOOTER_MESSAGE_TYPE_OFFSET);-- if (messageType !== MessageType.PAYLOAD_FOOTER) {- console.error(`Expected payload footer (2), got ${messageType}`);- return null;- }-- const frameNumber = Number(dataView.getBigInt64(PAYLOAD_FOOTER_FRAME_NUMBER_OFFSET, true));- const numberOfCameras = dataView.getInt32(PAYLOAD_FOOTER_NUM_CAMERAS_OFFSET, true);-- return {messageType, frameNumber, numberOfCameras};- } catch (error) {- console.error('Error parsing payload footer:', error);- return null;- }- }, []);--- const processBinaryMessage = useCallback(async (data: ArrayBuffer): Promise<FrameRenderAcknowledgment | null> => {- try {- let offset = 0;-- // Process payload header as a chunk- const headerView = new DataView(data, offset, PAYLOAD_HEADER_SIZE);- const payloadHeader = parsePayloadHeader(headerView);-- if (!payloadHeader) {- return null;- }-- const {frameNumber, numberOfCameras} = payloadHeader;- offset += PAYLOAD_HEADER_SIZE;-- if (numberOfCameras <= 0) {- console.warn(`No cameras found in frame ${frameNumber}`);- return null;- }- const frameRenderAcknowledgment: FrameRenderAcknowledgment = {- frameNumber: frameNumber,- displayImageSizes: {},- }-- // Process each camera frame- const textDecoder = textDecoderRef.current;- const newCameraImageData: Record<string, CameraImageData> = {};-- for (let i = 0; i < numberOfCameras; i++) {- // Process frame header as a chunk- const frameHeaderView = new DataView(data, offset, FRAME_HEADER_SIZE);- const frameHeader = parseFrameHeader(frameHeaderView, textDecoder);-- if (!frameHeader) {- return null;- }-- if (frameHeader.frameNumber !== frameNumber) {- console.error(`Frame header mismatch: expected frame ${frameNumber}, got ${frameHeader.frameNumber}`);- return null;- }-- offset += FRAME_HEADER_SIZE;-- // Extract JPEG data as a chunk- const jpegData = new Uint8Array(data, offset, frameHeader.jpegStringLength);- offset += frameHeader.jpegStringLength;--- if (latestCameraImageData[frameHeader.cameraId]?.imageWidth !== frameHeader.imageWidth ||- latestCameraImageData[frameHeader.cameraId]?.imageHeight !== frameHeader.imageHeight) {- // If the image dimensions or frame number have changed, update the state- newCameraImageData[frameHeader.cameraId] = {- imageWidth: frameHeader.imageWidth,- imageHeight: frameHeader.imageHeight,- frameNumber: frameHeader.frameNumber,- cameraId: frameHeader.cameraId,- cameraIndex: frameHeader.cameraIndex,- imageBitmap: await createImageBitmap(new Blob([jpegData], { type: 'image/jpeg' }))- }- }- }- setLatestCameraImageData(newCameraImageData);---- // Process payload footer as a chunk- const footerView = new DataView(data, offset, PAYLOAD_FOOTER_SIZE);- const payloadFooter = parsePayloadFooter(footerView);-- if (!payloadFooter) {- return null;- }-- // Verify footer matches header- if (payloadFooter.frameNumber !== frameNumber || payloadFooter.numberOfCameras !== numberOfCameras) {- console.error(`Footer mismatch: expected frame ${frameNumber}/${numberOfCameras}, got ${payloadFooter.frameNumber}/${payloadFooter.numberOfCameras}`);- return null;- }--- return frameRenderAcknowledgment;- } catch (error) {- console.error('Error processing binary frame:', error);- return null;- }- }, [parsePayloadHeader, parseFrameHeader, parsePayloadFooter]);-- return {- latestImageData: latestCameraImageData,- processBinaryMessage,- };-};diff --git a/freemocap-ui/src/context/websocket-context/websocket-types.ts b/freemocap-ui/src/context/websocket-context/websocket-types.tsdeleted file mode 100644index 4564fba5..00000000--- a/freemocap-ui/src/context/websocket-context/websocket-types.ts+++ /dev/null@@ -1,64 +0,0 @@-import {CurrentFramerateSchema} from "@/store/slices/framerateTrackerSlice";-import {z} from 'zod'--export const BaseWebsocketMessageSchema = z.object({- message_type: z.string(),-});-// Framerate update message schema-export const FramerateUpdateWebsocketMessageSchema = BaseWebsocketMessageSchema.extend({- message_type: z.literal("framerate_update"),- camera_group_id: z.string(),- backend_framerate: CurrentFramerateSchema,- frontend_framerate: CurrentFramerateSchema,-});----// Log record message schema - matching the Python LogRecordModel-export const LogRecordWebsocketMessageSchema = BaseWebsocketMessageSchema.extend({- message_type: z.literal("log_record"),- name: z.string(),- msg: z.string().nullable(),- args: z.array(z.any()),- levelname: z.string(),- levelno: z.number(),- pathname: z.string(),- filename: z.string(),- module: z.string(),- exc_info: z.string().nullable(),- exc_text: z.string().nullable(),- stack_info: z.string().nullable(),- lineno: z.number(),- funcName: z.string(),- created: z.number(),- msecs: z.number(),- relativeCreated: z.number(),- thread: z.number(),- threadName: z.string(),- processName: z.string(),- process: z.number(),- delta_t: z.string(),- message: z.string(),- asctime: z.string(),- formatted_message: z.string(),- type: z.string()-});-----// Add more message schemas as needed-// const OtherMessageTypeSchema = BaseMessageSchema.extend({-// message_type: z.literal("other_message_type"),-// // other fields...-// });--// Union of all message types-export const WebSocketMessageSchema = z.discriminatedUnion("message_type", [- FramerateUpdateWebsocketMessageSchema,- LogRecordWebsocketMessageSchema,- // Add more message schemas to the union as needed-]);--export type WebSocketMessage = z.infer<typeof WebSocketMessageSchema>;-export type FramerateUpdateWebSocketMessage = z.infer<typeof FramerateUpdateWebsocketMessageSchema>;diff --git a/freemocap-ui/src/demos/ipc.ts b/freemocap-ui/src/demos/ipc.tsindex ba4daa0c..808658c3 100644--- a/freemocap-ui/src/demos/ipc.ts+++ b/freemocap-ui/src/demos/ipc.ts@@ -1,4 +1,3 @@-window.ipcRenderer.on('main-process-message', (_event, ...args) => {- console.log('[Receive Main-process message]:', ...args)+ console.log('[Receive Main-process message]:', ...args)})diff --git a/freemocap-ui/src/demos/node.ts b/freemocap-ui/src/demos/node.tsindex e2b97576..4ed5fb9f 100644--- a/freemocap-ui/src/demos/node.ts+++ b/freemocap-ui/src/demos/node.ts@@ -2,7 +2,7 @@ import {lstat} from 'node:fs/promises'import {cwd} from 'node:process'lstat(cwd()).then(stats => {- console.log('[fs.lstat]', stats)+ console.log('[fs.lstat]', stats)}).catch(err => {- console.error(err)+ console.error(err)})diff --git a/freemocap-ui/src/hooks/server-urls.ts b/freemocap-ui/src/hooks/server-urls.tsnew file mode 100644index 00000000..0f414eaa--- /dev/null+++ b/freemocap-ui/src/hooks/server-urls.ts@@ -0,0 +1,63 @@+class ServerUrls {+ private readonly host = 'localhost';+ private readonly port = 53117;++ /**+ * Get HTTP base URL+ */+ getHttpUrl(): string {+ return `http://${this.host}:${this.port}`;+ }++ /**+ * Get WebSocket base URL+ */+ getWebSocketUrl(): string {+ return `ws://${this.host}:${this.port}/websocket/connect`;+ }+ get endpoints() {+ const baseUrl = this.getHttpUrl();++ return {+ // Server management+ health: `${baseUrl}/health`,+ shutdown: `${baseUrl}/shutdown`,++ // Camera endpoints+ detectCameras: `${baseUrl}/skellycam/camera/detect`,+ camerasConnectOrUpdate: `${baseUrl}/skellycam/camera/group/apply`,+ closeAll: `${baseUrl}/skellycam/camera/group/close/all`,+ updateConfigs: `${baseUrl}/skellycam/camera/update`,+ pauseUnpauseCameras: `${baseUrl}/skellycam/camera/group/all/pause_unpause`,++ // Recording endpoints+ startRecording: `${baseUrl}/skellycam/camera/group/all/record/start`,+ stopRecording: `${baseUrl}/skellycam/camera/group/all/record/stop`,++ // Pipeline endpoints+ pipelineConnectOrUpdate: `${baseUrl}/freemocap/pipeline/connect`,+ pipelineClose: `${baseUrl}/freemocap/pipeline/all/close`,+ pipelinePauseUnpause: `${baseUrl}/freemocap/pipeline/all/pause_unpause`,+ pipelineRecordStart: `${baseUrl}/freemocap/pipeline/all/record/start`,+ pipelineRecordStop: `${baseUrl}/freemocap/pipeline/all/record/stop`,++ // Calibration endpoints+ calibrationStartRecording: `${baseUrl}/freemocap/calibration/recording/start`,+ calibrationStopRecording: `${baseUrl}/freemocap/calibration/recording/stop`,+ calibrateRecording: `${baseUrl}/freemocap/calibration/recording/calibrate`,+ updateCalibrationConfig: `${baseUrl}/freemocap/calibration/config/update/all`,++ // Mocap endpoints+ mocapStartRecording: `${baseUrl}/freemocap/mocap/recording/start`,+ mocapStopRecording: `${baseUrl}/freemocap/mocap/recording/stop`,+ processMocapRecording: `${baseUrl}/freemocap/mocap/recording/process`,+ updateMocapConfig: `${baseUrl}/freemocap/mocap/config/update/all`,++ // WebSocket+ websocket: this.getWebSocketUrl(),+ };+ }+}++// Export singleton instance+export const serverUrls = new ServerUrls();diff --git a/freemocap-ui/src/hooks/useCalibration.ts b/freemocap-ui/src/hooks/useCalibration.tsnew file mode 100644index 00000000..8888a26a--- /dev/null+++ b/freemocap-ui/src/hooks/useCalibration.ts@@ -0,0 +1,114 @@+// hooks/useCalibration.ts+import {useCallback} from 'react';+import {useAppDispatch, useAppSelector} from '@/store/hooks';++import {useElectronIPC} from '@/services';+import {+ calibrateRecording,+ CalibrationConfig,+ calibrationConfigUpdated,+ calibrationDirectoryInfoUpdated,+ calibrationErrorCleared,+ manualCalibrationRecordingPathChanged,+ manualCalibrationRecordingPathCleared,+ selectCalibration,+ selectCalibrationDirectoryInfo,+ selectCalibrationRecordingPath,+ selectCanCalibrate,+ selectCanStartCalibrationRecording,+ selectIsUsingManualCalibrationPath,+ startCalibrationRecording,+ stopCalibrationRecording,+ updateCalibrationConfigOnServer+} from "@/store/slices/calibration";++export function useCalibration() {+ const dispatch = useAppDispatch();+ const { api, isElectron } = useElectronIPC();+ const calibrationState = useAppSelector(selectCalibration);+ const canStartRecording = useAppSelector(selectCanStartCalibrationRecording);+ const canCalibrate = useAppSelector(selectCanCalibrate);+ const calibrationRecordingPath = useAppSelector(selectCalibrationRecordingPath);+ const directoryInfo = useAppSelector(selectCalibrationDirectoryInfo);+ const isUsingManualPath = useAppSelector(selectIsUsingManualCalibrationPath);++ const updateCalibrationConfig = useCallback(+ (updates: Partial<CalibrationConfig>) => {+ // Update local state first+ dispatch(calibrationConfigUpdated(updates));+ // Then sync to server - this reads from the updated state+ dispatch(updateCalibrationConfigOnServer());+ },+ [dispatch]+ );++ const validateDirectory = useCallback(+ async (directoryPath: string) => {+ if (!isElectron || !api) {+ console.warn('Electron API not available - skipping directory validation');+ return;+ }++ try {+ const info = await api.fileSystem.validateCalibrationDirectory.query({ directoryPath });+ dispatch(calibrationDirectoryInfoUpdated(info));+ } catch (error) {+ console.error('Failed to validate calibration directory:', error);+ // Don't throw - just log the error+ }+ },+ [dispatch, isElectron, api]+ );++ const setManualRecordingPath = useCallback(+ async (path: string) => {+ dispatch(manualCalibrationRecordingPathChanged(path));+ // Validate the new path+ await validateDirectory(path);+ },+ [dispatch, validateDirectory]+ );++ const clearManualRecordingPath = useCallback(() => {+ dispatch(manualCalibrationRecordingPathCleared());+ }, [dispatch]);++ const dispatchStartCalibrationRecording = useCallback(() => {+ dispatch(startCalibrationRecording());+ }, [dispatch]);++ const dispatchStopCalibrationRecording = useCallback(() => {+ dispatch(stopCalibrationRecording());+ }, [dispatch]);++ const calibrate = useCallback(() => {+ dispatch(calibrateRecording());+ }, [dispatch]);++ const clearError = useCallback(() => {+ dispatch(calibrationErrorCleared());+ }, [dispatch]);++ return {+ // State+ config: calibrationState.config,+ error: calibrationState.error,+ isLoading: calibrationState.isLoading,+ isRecording: calibrationState.isRecording,+ recordingProgress: calibrationState.recordingProgress,+ calibrationRecordingPath,+ directoryInfo,+ isUsingManualPath,+ canStartRecording,+ canCalibrate,+ // Actions+ updateCalibrationConfig,+ setManualRecordingPath,+ clearManualRecordingPath,+ validateDirectory,+ dispatchStartCalibrationRecording,+ dispatchStopCalibrationRecording,+ calibrateSelectedRecording: calibrate,+ clearError,+ };+}diff --git a/freemocap-ui/src/hooks/useCameraGridLayout.ts b/freemocap-ui/src/hooks/useCameraGridLayout.tsdeleted file mode 100644index 22561f0a..00000000--- a/freemocap-ui/src/hooks/useCameraGridLayout.ts+++ /dev/null@@ -1,96 +0,0 @@-import { useMemo } from 'react';-import {CameraImageData} from "@/context/websocket-context/useWebsocketBinaryMessageProcessor";--interface GridLayout {- rows: number;- columns: number;-}--/**- * Hook to calculate optimal grid layout for camera views- * @param imageData The camera image data- * @param containerWidth The container width- * @param containerHeight The container height- * @param manualRows Optional manual row setting- * @param manualColumns Optional manual column setting- */-export function useCameraGridLayout(- imageData: Record<string, CameraImageData>,- containerWidth?: number,- containerHeight?: number,- manualRows?: number,- manualColumns?: number-): GridLayout {- return useMemo(() => {- // If manual values are provided, use them- if (manualRows !== undefined && manualColumns !== undefined) {- return { rows: manualRows, columns: manualColumns };- }-- const imageDataArray:CameraImageData[] = Object.values(imageData);- if (!imageDataArray || imageDataArray.length === 0) return { rows: 1, columns: 1 };-- // For static grid without container dimensions, use simple layout- if (!containerWidth || !containerHeight) {- // Simple layout calculation based on number of cameras- if (imageDataArray.length <= 1) return { rows: 1, columns: 1 };- if (imageDataArray.length <= 2) return { rows: 1, columns: 2 };- if (imageDataArray.length <= 4) return { rows: 2, columns: 2 };- if (imageDataArray.length <= 6) return { rows: 2, columns: 3 };- if (imageDataArray.length <= 9) return { rows: 3, columns: 3 };- return {- rows: Math.ceil(Math.sqrt(imageDataArray.length)),- columns: Math.ceil(Math.sqrt(imageDataArray.length))- };- }-- // Advanced layout calculation for dynamic grid with container dimensions- // Find the grid configuration that maximizes image size while handling both portrait and landscape orientations- let bestLayout = { columns: 1, rows: 1, area: 0 };-- // Calculate average aspect ratio to inform grid layout- const avgAspectRatio = imageDataArray.reduce((sum, img) =>- sum + (img.imageWidth / img.imageHeight), 0) / imageDataArray.length;-- // Container aspect ratio- const containerAspect = containerWidth / containerHeight;-- // Try different grid configurations- for (let columns = 1; columns <= imageDataArray.length; columns++) {- const rows = Math.ceil(imageDataArray.length / columns);-- // Calculate the area each image would get- const cellWidth = containerWidth / columns;- const cellHeight = containerHeight / rows;- const cellAspect = cellWidth / cellHeight;-- // Calculate how well images would fit in this grid- let totalFitScore = 0;- imageDataArray.forEach(image => {- const imgAspect = image.imageWidth / image.imageHeight;-- // Calculate how well the image fits the cell (1.0 = perfect fit)- // This handles both portrait and landscape orientations equally well- const fitScore = Math.min(- imgAspect / cellAspect,- cellAspect / imgAspect- );- totalFitScore += fitScore;- });-- // Average fit score for this configuration- const avgFitScore = totalFitScore / imageDataArray.length;-- // Calculate effective area with fit score as a factor- // Add a slight bias toward more balanced layouts (closer to square)- const balanceFactor = 1 - 0.2 * Math.abs(columns/rows - containerAspect/avgAspectRatio);- const effectiveArea = avgFitScore * balanceFactor * (cellWidth * cellHeight);-- if (effectiveArea > bestLayout.area) {- bestLayout = { columns, rows, area: effectiveArea };- }- }-- return { columns: bestLayout.columns, rows: bestLayout.rows };- }, [imageData, containerWidth, containerHeight, manualRows, manualColumns]);-}diff --git a/freemocap-ui/src/hooks/useElectronApi.ts b/freemocap-ui/src/hooks/useElectronApi.tsnew file mode 100644index 00000000..d75a84bc--- /dev/null+++ b/freemocap-ui/src/hooks/useElectronApi.ts@@ -0,0 +1,136 @@+// src/hooks/useElectronAPI.ts+import {useEffect, useMemo, useState} from 'react';+import {electronIpcClient, isElectron} from "@/services";++interface UseElectronAPIReturn {+ isElectron: boolean;+ isLoading: boolean;+ api: typeof electronIpcClient | null;+ // Helper methods for common operations+ pythonServer: {+ start: (exePath?: string | null) => Promise<void>;+ stop: () => Promise<void>;+ isRunning: () => Promise<boolean>;+ getStatus: () => Promise<{+ running: boolean;+ path: string | null;+ processInfo: any;+ }>;+ } | null;+ fileSystem: {+ openSelectDirectoryDialog: () => Promise<string | null>;+ selectExecutable: () => Promise<string | null>;+ openFolder: (path: string) => Promise<boolean>;+ getHomeDirectory: () => Promise<string>;+ } | null;+}++export function useElectronAPI(): UseElectronAPIReturn {+ const [isElectronEnv, setIsElectronEnv] = useState<boolean>(false);+ const [isLoading, setIsLoading] = useState<boolean>(true);++ useEffect(() => {+ // Check if we're in Electron environment+ const electronAvailable = isElectron();+ setIsElectronEnv(electronAvailable);+ setIsLoading(false);++ // Log the environment for debugging+ console.log('Electron environment detected:', electronAvailable);+ }, []);++ // Create memoized helper objects+ const pythonServer = useMemo(() => {+ if (!isElectronEnv) return null;++ return {+ start: async (exePath: string | null = null) => {+ try {+ await electronIpcClient.pythonServer.start.mutate({ exePath });+ } catch (error) {+ console.error('Failed to start Python server:', error);+ throw error;+ }+ },+ stop: async () => {+ try {+ await electronIpcClient.pythonServer.stop.mutate();+ } catch (error) {+ console.error('Failed to stop Python server:', error);+ throw error;+ }+ },+ isRunning: async () => {+ try {+ return await electronIpcClient.pythonServer.isRunning.query();+ } catch (error) {+ console.error('Failed to check Python server status:', error);+ return false;+ }+ },+ getStatus: async () => {+ try {+ const [running, path, processInfo] = await Promise.all([+ electronIpcClient.pythonServer.isRunning.query(),+ electronIpcClient.pythonServer.getExecutablePath.query(),+ electronIpcClient.pythonServer.getProcessInfo.query(),+ ]);+ return { running, path, processInfo };+ } catch (error) {+ console.error('Failed to get Python server status:', error);+ return { running: false, path: null, processInfo: null };+ }+ },+ };+ }, [isElectronEnv]);++ const fileSystem = useMemo(() => {+ if (!isElectronEnv) return null;++ return {+ openSelectDirectoryDialog: async () => {+ try {+ return await electronIpcClient.fileSystem.openSelectDirectoryDialog.mutate();+ } catch (error) {+ console.error('Failed to select directory:', error);+ return null;+ }+ },+ selectExecutable: async () => {+ try {+ return await electronIpcClient.fileSystem.selectExecutableFile.mutate();+ } catch (error) {+ console.error('Failed to select executable:', error);+ return null;+ }+ },+ openFolder: async (path: string) => {+ try {+ return await electronIpcClient.fileSystem.openFolder.mutate({ path });+ } catch (error) {+ console.error('Failed to open folder:', error);+ return false;+ }+ },+ getHomeDirectory: async () => {+ try {+ return await electronIpcClient.fileSystem.getHomeDirectory.query();+ } catch (error) {+ console.error('Failed to get home directory:', error);+ return '';+ }+ },+ };+ }, [isElectronEnv]);++ return {+ isElectron: isElectronEnv,+ isLoading,+ api: isElectronEnv ? electronIpcClient : null,+ pythonServer,+ fileSystem,+ };+}++// Export a singleton instance for use outside of React components+export const electronAPI = isElectron() ? electronIpcClient : null;diff --git a/freemocap-ui/src/hooks/useMocap.ts b/freemocap-ui/src/hooks/useMocap.tsnew file mode 100644index 00000000..2d5c36f0--- /dev/null+++ b/freemocap-ui/src/hooks/useMocap.ts@@ -0,0 +1,114 @@+// hooks/useMocap.ts+import {useCallback} from 'react';+import {useAppDispatch, useAppSelector} from '@/store/hooks';++import {useElectronIPC} from '@/services';+import {+ manualMocapRecordingPathChanged,+ manualMocapRecordingPathCleared,+ MocapConfig,+ mocapConfigUpdated,+ mocapDirectoryInfoUpdated,+ mocapErrorCleared,+ processMocapRecording,+ selectCanProcessMocapRecording,+ selectCanStartMocapRecording,+ selectIsUsingManualMocapPath,+ selectMocap,+ selectMocapDirectoryInfo,+ selectMocapRecordingPath,+ startMocapRecording,+ stopMocapRecording,+ updateMocapConfigOnServer+} from "@/store/slices/mocap";++export function useMocap() {+ const dispatch = useAppDispatch();+ const { api, isElectron } = useElectronIPC();+ const mocapState = useAppSelector(selectMocap);+ const canStartRecording = useAppSelector(selectCanStartMocapRecording);+ const canProcessMocapRecording = useAppSelector(selectCanProcessMocapRecording);+ const mocapRecordingPath = useAppSelector(selectMocapRecordingPath);+ const directoryInfo = useAppSelector(selectMocapDirectoryInfo);+ const isUsingManualPath = useAppSelector(selectIsUsingManualMocapPath);++ const updateMocapConfig = useCallback(+ (updates: Partial<MocapConfig>) => {+ // Update local state first+ dispatch(mocapConfigUpdated(updates));+ // Then sync to server - this reads from the updated state+ dispatch(updateMocapConfigOnServer());+ },+ [dispatch]+ );++ const validateDirectory = useCallback(+ async (directoryPath: string) => {+ if (!isElectron || !api) {+ console.warn('Electron API not available - skipping directory validation');+ return;+ }++ try {+ const info = await api.fileSystem.validateMocapDirectory.query({ directoryPath });+ dispatch(mocapDirectoryInfoUpdated(info));+ } catch (error) {+ console.error('Failed to validate mocap directory:', error);+ // Don't throw - just log the error+ }+ },+ [dispatch, isElectron, api]+ );++ const setManualRecordingPath = useCallback(+ async (path: string) => {+ dispatch(manualMocapRecordingPathChanged(path));+ // Validate the new path+ await validateDirectory(path);+ },+ [dispatch, validateDirectory]+ );++ const clearManualRecordingPath = useCallback(() => {+ dispatch(manualMocapRecordingPathCleared());+ }, [dispatch]);++ const dispatchStartMocapRecording = useCallback(() => {+ dispatch(startMocapRecording());+ }, [dispatch]);++ const dispatchStopMocapRecording = useCallback(() => {+ dispatch(stopMocapRecording());+ }, [dispatch]);++ const dispatchProcessMocapRecording = useCallback(() => {+ dispatch(processMocapRecording());+ }, [dispatch]);++ const clearError = useCallback(() => {+ dispatch(mocapErrorCleared());+ }, [dispatch]);++ return {+ // State+ config: mocapState.config,+ error: mocapState.error,+ isLoading: mocapState.isLoading,+ isRecording: mocapState.isRecording,+ recordingProgress: mocapState.recordingProgress,+ mocapRecordingPath,+ directoryInfo,+ isUsingManualPath,+ canStartRecording,+ canProcessMocapRecording,+ // Actions+ updateMocapConfig,+ setManualRecordingPath,+ clearManualRecordingPath,+ validateDirectory,+ dispatchStartMocapRecording,+ dispatchStopMocapRecording,+ dispatchProcessMocapRecording,+ clearError,+ };+}diff --git a/freemocap-ui/src/hooks/useServer.ts b/freemocap-ui/src/hooks/useServer.tsnew file mode 100644index 00000000..e09bb2a6--- /dev/null+++ b/freemocap-ui/src/hooks/useServer.ts@@ -0,0 +1,10 @@+import {useContext} from "react";+import {ServerContext, ServerContextValue} from "@/services";++export const useServer = (): ServerContextValue => {+ const context = useContext(ServerContext);+ if (!context) {+ throw new Error('useServer must be used within ServerContextProvider');+ }+ return context;+};diff --git a/freemocap-ui/src/index.css b/freemocap-ui/src/index.cssindex 637e9130..e79b5fbc 100644--- a/freemocap-ui/src/index.css+++ b/freemocap-ui/src/index.css@@ -3,91 +3,97 @@@tailwind utilities;:root {- font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;- line-height: 1.5;- font-weight: 400;-- color-scheme: light dark;- color: rgba(255, 255, 255, 0.87);- background-color: #242424;-- font-synthesis: none;- text-rendering: optimizeLegibility;- -webkit-font-smoothing: antialiased;- -moz-osx-font-smoothing: grayscale;- -webkit-text-size-adjust: 100%;+ font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;+ line-height: 1.5;+ font-weight: 400;++ color-scheme: light dark;+ color: rgba(255, 255, 255, 0.87);+ background-color: #242424;++ font-synthesis: none;+ text-rendering: optimizeLegibility;+ -webkit-font-smoothing: antialiased;+ -moz-osx-font-smoothing: grayscale;+ -webkit-text-size-adjust: 100%;}a {- font-weight: 500;- color: #646cff;- text-decoration: inherit;+ font-weight: 500;+ color: #646cff;+ text-decoration: inherit;}+a:hover {- color: #535bf2;+ color: #535bf2;}body {- margin: 0;- padding: 0;- width: 100%;- height: 100vh;- overflow: hidden;+ margin: 0;+ padding: 0;+ width: 100%;+ height: 100vh;+ overflow: hidden;}h1 {- font-size: 3.2em;- line-height: 1.1;+ font-size: 3.2em;+ line-height: 1.1;}button {- border-radius: 8px;- border: 1px solid transparent;- padding: 0.6em 1.2em;- font-size: 1em;- font-weight: 500;- font-family: inherit;- background-color: #1a1a1a;- cursor: pointer;- transition: border-color 0.25s;+ border-radius: 8px;+ border: 1px solid transparent;+ padding: 0.6em 1.2em;+ font-size: 1em;+ font-weight: 500;+ font-family: inherit;+ background-color: #1a1a1a;+ cursor: pointer;+ transition: border-color 0.25s;}+button:hover {- border-color: #646cff;+ border-color: #646cff;}+button:focus,button:focus-visible {- outline: 4px auto -webkit-focus-ring-color;+ outline: 4px auto -webkit-focus-ring-color;}code {- background-color: #1a1a1a;- padding: 2px 4px;- margin: 0 4px;- border-radius: 4px;+ background-color: #1a1a1a;+ padding: 2px 4px;+ margin: 0 4px;+ border-radius: 4px;}.card {- padding: 2em;+ padding: 2em;}#root {- width: 100%;- height: 100vh;- overflow: hidden;+ width: 100%;+ height: 100vh;+ overflow: hidden;}@media (prefers-color-scheme: light) {- :root {- color: #213547;- background-color: #ffffff;- }- a:hover {- color: #747bff;- }- button {- background-color: #f9f9f9;- }- code {- background-color: #f9f9f9;- }+ :root {+ color: #213547;+ background-color: #ffffff;+ }++ a:hover {+ color: #747bff;+ }++ button {+ background-color: #f9f9f9;+ }++ code {+ background-color: #f9f9f9;+ }}diff --git a/freemocap-ui/src/layout/AppContent.tsx b/freemocap-ui/src/layout/AppContent.tsxnew file mode 100644index 00000000..0ca1171d--- /dev/null+++ b/freemocap-ui/src/layout/AppContent.tsx@@ -0,0 +1,29 @@+import * as React from 'react';+import {ThemeProvider} from '@mui/material/styles';+import {HashRouter} from 'react-router-dom';+import {CssBaseline} from "@mui/material";+import {BasePanelLayout} from "@/layout/BasePanelLayout";+import {createExtendedTheme} from "@/layout/paperbase-theme";+import {useAppSelector} from "@/store";+import {BaseContentRouter} from "@/layout/BaseContentRouter";++export const AppContent = function () {++ const themeMode = useAppSelector(state => state.theme.mode);+ // Create theme dynamically based on current mode++ const theme = React.useMemo(() =>+ createExtendedTheme(themeMode),+ [themeMode]+ );+ return (+ <ThemeProvider theme={theme}>+ <CssBaseline/>+ <HashRouter>+ <BasePanelLayout>+ <BaseContentRouter/>+ </BasePanelLayout>+ </HashRouter>+ </ThemeProvider>+ );+}diff --git a/freemocap-ui/src/layout/BaseContentRouter.tsx b/freemocap-ui/src/layout/BaseContentRouter.tsxindex b6559f01..3834b231 100644--- a/freemocap-ui/src/layout/BaseContentRouter.tsx+++ b/freemocap-ui/src/layout/BaseContentRouter.tsx@@ -1,22 +1,20 @@-// skellycam-ui/src/layout/BaseContent.tsx+// freemocap-ui/src/layout/BaseContent.tsximport React from 'react';import {Navigate, Route, Routes} from 'react-router-dom';-import {CamerasPage} from "@/layout/pages/CamerasPage";-import {Viewport3dPage} from "@/layout/pages/Viewport3dPage";-import VideosPage from "@/layout/pages/VideosPage"-import ErrorBoundary from "@/components/common/ErrorBoundary";-+import {CamerasPage} from "@/pages/CamerasPage";+import VideosPage from "@/pages/VideosPage";+import WelcomePage from "@/pages/WelcomePage";+import {Viewport3dPage} from "@/pages/Viewport3dPage";export const BaseContentRouter: React.FC = () => {return (- <ErrorBoundary>- <Routes>- {/*<Route path="/" element={<WelcomePage />} />*/}- <Route path="/" element={<CamerasPage/>}/>- <Route path="/viewport3d" element={<Viewport3dPage/>}/>- <Route path="/videos" element={<VideosPage/>}/>- <Route path="*" element={<Navigate to="/" replace/>}/>- </Routes>- </ErrorBoundary>+ <Routes>+ <Route path="/" element={<WelcomePage />} />+ <Route path="/cameras" element={<CamerasPage/>}/>+ <Route path="/videos" element={<VideosPage/>}/>+ <Route path="/viewport3d" element={<Viewport3dPage/>}/>+ <Route path="/videos" element={<VideosPage/>}/>+ <Route path="*" element={<Navigate to="/" replace/>}/>+ </Routes>);};diff --git a/freemocap-ui/src/layout/BasePanelLayout.tsx b/freemocap-ui/src/layout/BasePanelLayout.tsxindex fcb0424a..cd5f4ae7 100644--- a/freemocap-ui/src/layout/BasePanelLayout.tsx+++ b/freemocap-ui/src/layout/BasePanelLayout.tsx@@ -1,32 +1,21 @@-// skellycam-ui/src/layout/BasePanelLayout.tsx+// freemocap-ui/src/layout/BasePanelLayout.tsximport React from "react";-import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";-import { LeftSidePanelContent } from "@/components/ui-components/LeftSidePanelContent";+import {Panel, PanelGroup, PanelResizeHandle} from "react-resizable-panels";+import {LeftSidePanelContent} from "@/components/ui-components/LeftSidePanelContent";import BottomPanelContent from "@/components/ui-components/BottomPanelContent";-import { useTheme } from "@mui/material/styles";-import { Box } from "@mui/material";-import { useLocation } from "react-router-dom";+import {useTheme} from "@mui/material/styles";+import {Box} from "@mui/material";+import {useLocation} from "react-router-dom";export const BasePanelLayout = ({children}: { children: React.ReactNode }) => {const theme = useTheme();const location = useLocation();- // Only show panels on cameras and videos pages- // const showPanels = location.pathname === '/cameras' || location.pathname === '/videos';-- // if (!showPanels) {- // return (- // <Box sx={{ display: 'flex', flexDirection: 'column', height: '100vh' }}>- // {children}- // </Box>- // );- // }-return (- <Box sx={{ display: 'flex', flexDirection: 'column', height: '100vh' }}>+ <Box sx={{display: 'flex', flexDirection: 'column', height: '100vh'}}><PanelGroupdirection="vertical"- style={{ flex: 1 }}+ style={{flex: 1}}>{/* Top section (horizontal panels) - 80% height */}<Panel defaultSize={87} minSize={20}>diff --git a/freemocap-ui/src/layout/pages/CamerasPage.tsx b/freemocap-ui/src/layout/pages/CamerasPage.tsxdeleted file mode 100644index 1d3f4c5b..00000000--- a/freemocap-ui/src/layout/pages/CamerasPage.tsx+++ /dev/null@@ -1,42 +0,0 @@-// skellycam-ui/src/layout/BaseContent.tsx-import React from 'react';-import Box from "@mui/material/Box";-import ErrorBoundary from "@/components/common/ErrorBoundary";-import {Copyright} from "@/components/ui-components/Copyright";-import {useTheme} from "@mui/material/styles";-import {CameraImagesGrid} from "@/components/camera-views/og-canvas-strategy/CameraImagesGrid";-import {CamerasViewSettingsOverlay} from "@/components/camera-view-settings-overlay/CamerasViewSettingsOverlay";--export const CamerasPage = () => {- const theme = useTheme();-- return (- <React.Fragment>- <Box sx={{- py: 1,- px: 1,- flex: 1,- display: 'flex',- flexDirection: 'column',- height: '100%',- width: '100%',- backgroundColor: theme.palette.mode === 'dark'- ? theme.palette.background.default- : theme.palette.background.paper,- overflow: "scroll"-- }}>- {/*<CamerasViewSettingsOverlay/>*/}-- <Box>- <ErrorBoundary>- <CameraImagesGrid/>- </ErrorBoundary>- </Box>- <Box component="footer" sx={{p: 1}}>- <Copyright/>- </Box>- </Box>- </React.Fragment>- )-}diff --git a/freemocap-ui/src/layout/pages/WelcomePage.tsx b/freemocap-ui/src/layout/pages/WelcomePage.tsxdeleted file mode 100644index fb80d589..00000000--- a/freemocap-ui/src/layout/pages/WelcomePage.tsx+++ /dev/null@@ -1,176 +0,0 @@-import React from 'react';-import {Box, Button, Typography, Container, Paper, Fade, Grow, darken} from '@mui/material';-import { useNavigate } from 'react-router-dom';-import { useTheme } from '@mui/material/styles';-import VideocamIcon from '@mui/icons-material/Videocam';-import VideoLibraryIcon from '@mui/icons-material/VideoLibrary';-import { Copyright } from '@/components/ui-components/Copyright';--const WelcomePage: React.FC = () => {- const theme = useTheme();- const navigate = useNavigate();-- return (- <Container maxWidth="md" sx={{- height: '100%',- width: '100%',- bgcolor: theme.palette.background.default,- display: 'flex',- flexDirection: 'column',- justifyContent: 'center',- alignItems: 'center',- py: 4- }}>- <Fade in={true} timeout={800}>- <Paper- elevation={6}- sx={{- p: { xs: 3, sm: 5 },- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- width: '100%',- backgroundColor: theme.palette.background.paper,- mx: 'auto',- borderRadius: 3,- boxShadow: theme.palette.mode === 'dark'- ? '0 8px 32px rgba(0, 0, 0, 0.5)'- : '0 8px 32px rgba(0, 0, 0, 0.1)',- overflow: 'hidden',- position: 'relative'- }}- >- {/* Background accent */}- <Box sx={{- position: 'absolute',- top: 0,- left: 0,- width: '100%',- height: '8px',- background: `linear-gradient(90deg, ${theme.palette.primary.main}, ${theme.palette.secondary.main})`,- }} />-- <Grow in={true} timeout={1000}>- <Box- sx={{- width: 180,- height: 180,- mb: 4,- mt: 2,- display: 'flex',- justifyContent: 'center',- alignItems: 'center',- transition: 'transform 0.3s ease-in-out',- '&:hover': {- transform: 'scale(1.05)'- }- }}- >- <img- src="/skellycam-logo.png"- alt="SkellyCam Logo"- style={{- maxWidth: '100%',- maxHeight: '100%',- objectFit: 'contain',- filter: theme.palette.mode === 'dark' ? 'drop-shadow(0 0 10px rgba(255,255,255,0.2))' : 'drop-shadow(0 0 10px rgba(0,0,0,0.1))'- }}- />- </Box>- </Grow>-- <Typography- variant="h3"- component="h1"- gutterBottom- sx={{- fontWeight: 'bold',- textAlign: 'center',- background: theme.palette.text.primary,- WebkitBackgroundClip: 'text',- WebkitTextFillColor: 'transparent',- backgroundClip: 'text',- textFillColor: 'transparent',- mb: 2- }}- >- Welcome to SkellyCam- </Typography>-- <Typography- variant="subtitle1"- color="text.secondary"- sx={{- mb: 5,- textAlign: 'center',- maxWidth: '80%',- fontSize: '1.1rem'- }}- >- Record and View Synchronized Videos- </Typography>-- <Box sx={{- display: 'flex',- flexDirection: { xs: 'column', sm: 'row' },- gap: 3,- width: '100%',- mt: 2,- justifyContent: 'center'- }}>- <Button- variant="contained"- size="large"- fullWidth- startIcon={<VideocamIcon />}- onClick={() => navigate('/cameras')}- sx={{- py: 2.5,- fontSize: '1.1rem',- backgroundColor: theme.palette.primary.main,- borderRadius: 2,- transition: 'all 0.3s ease',- '&:hover': {- transform: 'translateY(-3px)',- boxShadow: theme.palette.mode === 'dark'- ? '0 7px 15px rgba(0, 0, 0, 0.4)'- : '0 7px 15px rgba(0, 0, 0, 0.2)',- }- }}- >- Record New Videos- </Button>- <Button- variant="contained"- size="large"- fullWidth- startIcon={<VideoLibraryIcon />}- onClick={() => navigate('/videos')}- sx={{- py: 2.5,- fontSize: '1.1rem',- backgroundColor: darken(theme.palette.secondary.main, 0.2),- borderRadius: 2,- transition: 'all 0.3s ease',- '&:hover': {- transform: 'translateY(-3px)',- boxShadow: theme.palette.mode === 'dark'- ? '0 7px 15px rgba(0, 0, 0, 0.4)'- : '0 7px 15px rgba(0, 0, 0, 0.2)',- }- }}- >- Load Synchronized Videos- </Button>- </Box>-- <Box component="footer" sx={{p: 3}}>- <Copyright />- </Box>- </Paper>- </Fade>- </Container>- );-};--export default WelcomePage;diff --git a/freemocap-ui/src/layout/paperbase-theme.ts b/freemocap-ui/src/layout/paperbase-theme.tsnew file mode 100644index 00000000..e54b7202--- /dev/null+++ b/freemocap-ui/src/layout/paperbase-theme.ts@@ -0,0 +1,412 @@+// freemocap-ui/src/layout/paperbase_theme/paperbase-theme.ts+import {createTheme, PaletteMode} from '@mui/material/styles';++// Define common theme settings+const getBaseTheme = (mode: PaletteMode) => ({+ typography: {+ h5: {+ fontWeight: 500,+ fontSize: 22,+ letterSpacing: 0.5,+ },+ h6: {+ fontSize: 16,+ fontWeight: 500,+ },+ subtitle2: {+ fontSize: 13,+ fontWeight: 500,+ },+ body2: {+ fontSize: 13,+ },+ caption: {+ fontSize: 11,+ }+ },+ shape: {+ borderRadius: 6,+ },+ mixins: {+ toolbar: {+ minHeight: 40,+ },+ },+ components: {+ MuiTab: {+ defaultProps: {+ disableRipple: true,+ },+ },+ },+});++// Define the dark theme palette with better visibility+const darkPalette = {+ mode: 'dark' as PaletteMode,+ primary: {+ light: '#5e92f3',+ main: '#104172',+ dark: '#002a60',+ contrastText: '#ffffff',+ },+ secondary: {+ light: '#ff6090',+ main: '#f50057',+ dark: '#c51162',+ contrastText: '#ffffff',+ },+ background: {+ default: '#0a0e1a',+ paper: '#262f44',+ },+ text: {+ primary: '#ffffff',+ secondary: '#b3b9c6',+ },+ divider: 'rgba(255, 255, 255, 0.12)',+ action: {+ active: '#ffffff',+ hover: 'rgba(255, 255, 255, 0.08)',+ selected: 'rgba(255, 255, 255, 0.16)',+ disabled: 'rgba(255, 255, 255, 0.3)',+ disabledBackground: 'rgba(255, 255, 255, 0.12)',+ },+ success: {+ main: '#4caf50',+ light: '#80e27e',+ dark: '#087f23',+ },+ warning: {+ main: '#ff9800',+ light: '#ffcc80',+ dark: '#c66900',+ },+ error: {+ main: '#f44336',+ light: '#ff7961',+ dark: '#ba000d',+ },+ info: {+ main: '#29b6f6',+ light: '#73e8ff',+ dark: '#0086c3',+ },+ grey: {+ 50: '#fafafa',+ 100: '#f5f5f5',+ 200: '#eeeeee',+ 300: '#e0e0e0',+ 400: '#bdbdbd',+ 500: '#9e9e9e',+ 600: '#757575',+ 700: '#616161',+ 800: '#424242',+ 900: '#212121',+ },+};++// Define the light theme palette+const lightPalette = {+ mode: 'light' as PaletteMode,+ primary: {+ light: '#4791db',+ main: '#1976d2',+ dark: '#115293',+ contrastText: '#ffffff',+ },+ secondary: {+ light: '#ff5983',+ main: '#f50057',+ dark: '#ab003c',+ contrastText: '#ffffff',+ },+ background: {+ default: '#f5f7fa',+ paper: '#ffffff',+ },+ text: {+ primary: '#2c3e50',+ secondary: '#546e7a',+ },+ divider: 'rgba(0, 0, 0, 0.12)',+ action: {+ active: 'rgba(0, 0, 0, 0.54)',+ hover: 'rgba(0, 0, 0, 0.04)',+ selected: 'rgba(0, 0, 0, 0.08)',+ disabled: 'rgba(0, 0, 0, 0.26)',+ disabledBackground: 'rgba(0, 0, 0, 0.12)',+ },+ success: {+ main: '#4caf50',+ light: '#80e27e',+ dark: '#087f23',+ },+ warning: {+ main: '#ff9800',+ light: '#ffcc80',+ dark: '#c66900',+ },+ error: {+ main: '#f44336',+ light: '#ff7961',+ dark: '#ba000d',+ },+ info: {+ main: '#2196f3',+ light: '#64b5f6',+ dark: '#1565c0',+ },+};++// Create theme based on the palette mode+export const createAppTheme = (mode: PaletteMode) => {+ const baseTheme = getBaseTheme(mode);+ const palette = mode === 'dark' ? darkPalette : lightPalette;++ return createTheme({+ ...baseTheme,+ palette,+ });+};++// Export base themes for reference+export const paperbaseThemeLight = createAppTheme('light');+export const paperbaseThemeDark = createAppTheme('dark');++// Create the extended theme components that apply to both light/dark modes+export const createExtendedTheme = (mode: PaletteMode) => {+ const baseTheme = createAppTheme(mode);++ return {+ ...baseTheme,+ components: {+ ...baseTheme.components,+ MuiDrawer: {+ styleOverrides: {+ paper: {+ backgroundColor: mode === 'dark' ? '#0f1419' : '#f8f9fa',+ },+ },+ },+ MuiButton: {+ styleOverrides: {+ root: {+ textTransform: 'none',+ fontSize: 12,+ padding: '4px 12px',+ minHeight: 28,+ },+ contained: {+ boxShadow: 'none',+ '&:active': {+ boxShadow: 'none',+ },+ },+ },+ },+ MuiIconButton: {+ styleOverrides: {+ root: {+ padding: 6,+ },+ small: {+ padding: 4,+ },+ },+ },+ MuiCheckbox: {+ styleOverrides: {+ root: {+ color: mode === 'dark' ? baseTheme.palette.grey[400] : baseTheme.palette.grey[600],+ '&.Mui-checked': {+ color: baseTheme.palette.primary.main,+ },+ '&.Mui-disabled': {+ color: mode === 'dark' ? baseTheme.palette.grey[700] : baseTheme.palette.grey[400],+ },+ },+ },+ },+ MuiRadio: {+ styleOverrides: {+ root: {+ color: mode === 'dark' ? baseTheme.palette.grey[400] : baseTheme.palette.grey[600],+ '&.Mui-checked': {+ color: baseTheme.palette.primary.main,+ },+ },+ },+ },+ MuiSwitch: {+ styleOverrides: {+ root: {+ padding: 8,+ },+ switchBase: {+ padding: 9,+ '&.Mui-checked': {+ color: baseTheme.palette.primary.main,+ '& + .MuiSwitch-track': {+ backgroundColor: baseTheme.palette.primary.light,+ opacity: 0.7,+ },+ },+ },+ track: {+ backgroundColor: mode === 'dark' ? baseTheme.palette.grey[700] : baseTheme.palette.grey[400],+ },+ },+ },+ MuiFormControlLabel: {+ styleOverrides: {+ root: {+ marginLeft: 0,+ marginRight: 0,+ },+ label: {+ fontSize: 12,+ },+ },+ },+ MuiTreeItem: {+ styleOverrides: {+ content: {+ padding: '2px 8px',+ margin: '2px 0',+ },+ label: {+ fontSize: 13,+ padding: '2px 0',+ },+ },+ },+ MuiChip: {+ styleOverrides: {+ root: {+ height: 20,+ fontSize: 11,+ },+ sizeSmall: {+ height: 18,+ fontSize: 10,+ },+ },+ },+ MuiTextField: {+ styleOverrides: {+ root: {+ '& .MuiOutlinedInput-root': {+ color: mode === 'dark' ? 'white' : 'rgba(0, 0, 0, 0.87)',+ '& fieldset': {+ borderColor: mode === 'dark' ? 'rgba(255, 255, 255, 0.3)' : 'rgba(0, 0, 0, 0.23)',+ },+ '&:hover fieldset': {+ borderColor: mode === 'dark' ? 'rgba(255, 255, 255, 0.5)' : 'rgba(0, 0, 0, 0.87)',+ },+ '&.Mui-focused fieldset': {+ borderColor: baseTheme.palette.primary.main,+ },+ },+ '& .MuiInputLabel-root': {+ color: mode === 'dark' ? 'rgba(255, 255, 255, 0.7)' : 'rgba(0, 0, 0, 0.6)',+ fontSize: 13,+ },+ '& .MuiInputBase-input': {+ color: mode === 'dark' ? 'white' : 'rgba(0, 0, 0, 0.87)',+ fontSize: 13,+ padding: '8px 12px',+ },+ '& .MuiInputBase-inputSizeSmall': {+ padding: '4px 8px',+ fontSize: 12,+ },+ },+ },+ },+ MuiSelect: {+ styleOverrides: {+ root: {+ fontSize: 13,+ },+ select: {+ padding: '8px 12px',+ },+ },+ },+ MuiPaper: {+ styleOverrides: {+ root: {+ backgroundImage: 'none',+ },+ },+ },+ MuiCard: {+ styleOverrides: {+ root: {+ backgroundImage: 'none',+ },+ },+ },+ MuiTypography: {+ styleOverrides: {+ root: {+ color: mode === 'dark' ? 'white' : 'rgba(0, 0, 0, 0.87)',+ },+ },+ },+ MuiDivider: {+ styleOverrides: {+ root: {+ backgroundColor: mode === 'dark' ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.08)',+ },+ },+ },+ MuiTooltip: {+ styleOverrides: {+ tooltip: {+ borderRadius: 4,+ fontSize: 11,+ },+ },+ },+ MuiListItemButton: {+ styleOverrides: {+ root: {+ padding: '4px 8px',+ '&.Mui-selected': {+ backgroundColor: mode === 'dark'+ ? 'rgba(25, 118, 210, 0.16)'+ : 'rgba(25, 118, 210, 0.08)',+ color: baseTheme.palette.primary.main,+ },+ },+ },+ },+ MuiListItemText: {+ styleOverrides: {+ primary: {+ fontSize: 13,+ fontWeight: baseTheme.typography.fontWeightMedium,+ },+ },+ },+ MuiListItemIcon: {+ styleOverrides: {+ root: {+ color: 'inherit',+ minWidth: 'auto',+ marginRight: baseTheme.spacing(1),+ '& svg': {+ fontSize: 18,+ },+ },+ },+ },+ },+ };+};++// Re-export the default theme for backward compatibility+export const paperbaseTheme = paperbaseThemeDark;+export default createExtendedTheme('dark');diff --git a/freemocap-ui/src/layout/paperbase_theme/paperbase-theme.ts b/freemocap-ui/src/layout/paperbase_theme/paperbase-theme.tsindex 9ee4287f..9718e96d 100644--- a/freemocap-ui/src/layout/paperbase_theme/paperbase-theme.ts+++ b/freemocap-ui/src/layout/paperbase_theme/paperbase-theme.ts@@ -1,4 +1,4 @@-// skellycam-ui/src/layout/paperbase_theme/paperbase-theme.ts+// freemocap-ui/src/layout/paperbase_theme/paperbase-theme.tsimport {createTheme, PaletteMode} from '@mui/material/styles';// Define common theme settingsdiff --git a/freemocap-ui/src/main.tsx b/freemocap-ui/src/main.tsxindex 6e9182c7..3125360e 100644--- a/freemocap-ui/src/main.tsx+++ b/freemocap-ui/src/main.tsx@@ -7,7 +7,7 @@ import './index.css'ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(<React.StrictMode>- <App/>+ <App/></React.StrictMode>,)diff --git a/freemocap-ui/src/pages/CamerasPage.tsx b/freemocap-ui/src/pages/CamerasPage.tsxnew file mode 100644index 00000000..31949e79--- /dev/null+++ b/freemocap-ui/src/pages/CamerasPage.tsx@@ -0,0 +1,98 @@+import React, {useState} 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 {Panel, PanelGroup, PanelResizeHandle} from "react-resizable-panels";+import {CameraViewsGrid} from "@/components/camera-views/CameraViewsGrid";+import {+ CamerasViewSettingsOverlay+} from "@/components/camera-views/camera-view-settings-overlay/CamerasViewSettingsOverlay";+import {ThreeJsCanvas} from "@/components/viewport3d/ThreeJsCanvas";++interface CameraSettings {+ columns: number | null;+ show3dView: boolean;+}++export const CamerasPage = () => {+ const theme = useTheme();+ const [settings, setSettings] = useState<CameraSettings>({+ columns: null, // auto+ show3dView: true,+ });+ const [resetKey, setResetKey] = useState<number>(0);++ const handleSettingsChange = (newSettings: CameraSettings) => {+ setSettings(newSettings);+ };++ const handleResetViews = () => {+ setResetKey(prev => prev + 1);+ };++ return (+ <React.Fragment>+ <Box sx={{+ py: 1,+ px: 1,+ flex: 1,+ display: 'flex',+ flexDirection: 'column',+ height: '100%',+ width: '100%',+ backgroundColor: theme.palette.mode === 'dark'+ ? theme.palette.background.default+ : theme.palette.background.paper,+ overflow: "hidden",+ position: 'relative',+ }}>+ <CamerasViewSettingsOverlay+ onSettingsChange={handleSettingsChange}+ onResetViews={handleResetViews}+ />++ <Box sx={{ flex: 1, overflow: 'hidden' }}>+ {settings.show3dView ? (+ <PanelGroup key={`main-panels-${resetKey}`} direction="vertical">+ {/* Camera Grid View Panel */}+ <Panel defaultSize={80} minSize={20}>+ <Box sx={{ height: '100%', overflow: 'auto' }}>+ <ErrorBoundary>+ <CameraViewsGrid settings={settings} resetKey={resetKey} />+ </ErrorBoundary>+ </Box>+ </Panel>++ {/* Vertical Resize Handle */}+ <PanelResizeHandle+ style={{+ height: "2px",+ cursor: "row-resize",+ backgroundColor: theme.palette.primary.dark,+ }}+ />++ {/* 3D View Panel */}+ <Panel defaultSize={20} minSize={10}>+ <Box sx={{ height: '100%' }}>+ <ThreeJsCanvas />+ </Box>+ </Panel>+ </PanelGroup>+ ) : (+ <Box sx={{ height: '100%', overflow: 'auto' }}>+ <ErrorBoundary>+ <CameraViewsGrid settings={settings} resetKey={resetKey} />+ </ErrorBoundary>+ </Box>+ )}+ </Box>++ <Box component="footer" sx={{ p: 1 }}>+ <Footer />+ </Box>+ </Box>+ </React.Fragment>+ );+};diff --git a/freemocap-ui/src/layout/pages/VideosPage.tsx b/freemocap-ui/src/pages/VideosPage.tsxsimilarity index 66%rename from freemocap-ui/src/layout/pages/VideosPage.tsxrename to freemocap-ui/src/pages/VideosPage.tsxindex 6fd58798..f144b3b7 100644--- a/freemocap-ui/src/layout/pages/VideosPage.tsx+++ b/freemocap-ui/src/pages/VideosPage.tsx@@ -1,6 +1,7 @@import React from 'react';import Box from "@mui/material/Box";-import {Copyright} from "@/components/ui-components/Copyright";+import ErrorBoundary from "@/components/common/ErrorBoundary";+import {Footer} from "@/components/ui-components/Footer";import {useTheme} from "@mui/material/styles";import {Typography} from '@mui/material';@@ -31,16 +32,18 @@ const VideosPage: React.FC = () => {alignItems: 'center',overflow: 'hidden',}}>- <Typography variant="h4" gutterBottom>- Load Synchronized Videos- </Typography>- <Typography variant="body1">- This page will allow you to load and synchronize pre-recorded videos.- </Typography>- {/* Add your video loading components here */}+ <ErrorBoundary>+ <Typography variant="h4" gutterBottom>+ Load Synchronized Videos+ </Typography>+ <Typography variant="body1">+ This page will allow you to load and synchronize pre-recorded videos.+ </Typography>+ {/* Add your video loading components here */}+ </ErrorBoundary></Box><Box component="footer" sx={{p: 1}}>- <Copyright/>+ <Footer/></Box></Box></React.Fragment>diff --git a/freemocap-ui/src/layout/pages/Viewport3dPage.tsx b/freemocap-ui/src/pages/Viewport3dPage.tsxsimilarity index 75%rename from freemocap-ui/src/layout/pages/Viewport3dPage.tsxrename to freemocap-ui/src/pages/Viewport3dPage.tsxindex ae76fef8..860dd0a0 100644--- a/freemocap-ui/src/layout/pages/Viewport3dPage.tsx+++ b/freemocap-ui/src/pages/Viewport3dPage.tsx@@ -4,7 +4,9 @@ import {ThreeJsCanvas} from "@/components/viewport3d/ThreeJsCanvas";export const Viewport3dPage = () => {return (- <Box sx={{display: "flex", flexDirection: "column", height: "81vh"}}>+ <Box sx={{width: '100%',+ height: '100%',+ }}><ThreeJsCanvas/></Box>);diff --git a/freemocap-ui/src/pages/WelcomePage.tsx b/freemocap-ui/src/pages/WelcomePage.tsxnew file mode 100644index 00000000..f05b03f2--- /dev/null+++ b/freemocap-ui/src/pages/WelcomePage.tsx@@ -0,0 +1,299 @@+import React, {useEffect, useRef, useState} from 'react';+import {+ Box,+ Button,+ CircularProgress,+ Container,+ darken,+ Fade,+ Grow,+ Link as MuiLink,+ Paper,+ Typography+} from '@mui/material';+import {useNavigate} from 'react-router-dom';+import {useTheme} from '@mui/material/styles';+import VideocamIcon from '@mui/icons-material/Videocam';+import {Footer} from '@/components/ui-components/Footer';+import {useElectronIPC} from "@/services";+import {connectRealtimePipeline, useAppDispatch} from "@/store";+import {useServer} from "@/hooks/useServer";++const WelcomePage: React.FC = () => {+ const theme = useTheme();+ const navigate = useNavigate();+ const dispatch = useAppDispatch();+ const [logoDataUrl, setLogoDataUrl] = useState<string | null>(null);+ const [isConnecting, setIsConnecting] = useState<boolean>(false);+ const { isElectron, api } = useElectronIPC();+ const { connectedCameraIds } = useServer();++ // Track previous camera count to detect 0 -> >0 transition+ const prevCountRef = useRef(connectedCameraIds.length);++ useEffect(() => {+ const prevCount = prevCountRef.current;+ const currentCount = connectedCameraIds.length;++ // Auto-navigate to cameras page only when first camera connects (0 -> >0 transition)+ if (prevCount === 0 && currentCount > 0) {+ navigate('/cameras');+ }++ prevCountRef.current = currentCount;+ }, [connectedCameraIds, navigate]);++ useEffect(() => {+ const fetchLogo = async (): Promise<void> => {+ try {+ if (isElectron && api) {+ // Use the new base64 method that returns a data URL+ const dataUrl = await api.assets.getLogoBase64.query();+ if (dataUrl) {+ setLogoDataUrl(dataUrl);+ } else {+ console.warn('Logo image not found...');+ }+ }+ } catch (error) {+ console.error('Failed to load logo:', error);+ }+ };++ fetchLogo();+ }, [isElectron, api]);++ const handleConnectCameras = async (): Promise<void> => {+ setIsConnecting(true);+ try {+ await dispatch(connectRealtimePipeline()).unwrap();+ // Navigation will happen automatically via the useEffect above+ } catch (error) {+ console.error('Error connecting to cameras:', error);+ setIsConnecting(false);+ }+ };++ return (+ <Container maxWidth="md" sx={{+ height: '100%',+ width: '100%',+ bgcolor: theme.palette.background.default,+ display: 'flex',+ flexDirection: 'column',+ justifyContent: 'center',+ alignItems: 'center',+ py: 4,+ gap: 3+ }}>+ <Fade in={true} timeout={800}>+ <Paper+ elevation={6}+ sx={{+ p: { xs: 3, sm: 5 },+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ width: '100%',+ backgroundColor: theme.palette.background.paper,+ mx: 'auto',+ borderRadius: 3,+ boxShadow: theme.palette.mode === 'dark'+ ? '0 8px 32px rgba(0, 0, 0, 0.5)'+ : '0 8px 32px rgba(0, 0, 0, 0.1)',+ overflow: 'hidden',+ position: 'relative',+ }}+ >+ {/* Background accent */}+ <Box sx={{+ position: 'absolute',+ top: 0,+ left: 0,+ width: '100%',+ height: '8px',+ background: `linear-gradient(90deg, ${theme.palette.primary.main}, ${theme.palette.secondary.main})`,+ }} />++ <Grow in={true} timeout={1000}>+ <Box+ sx={{+ width: 240,+ height: 240,+ mb: 4,+ mt: 2,+ display: 'flex',+ justifyContent: 'center',+ alignItems: 'center',+ transition: 'transform 0.3s ease-in-out',+ '&:hover': {+ transform: 'scale(1.05)'+ }+ }}+ >+ {logoDataUrl && (+ <img+ src={logoDataUrl}+ alt="FreeMoCap Logo"+ style={{+ maxWidth: '100%',+ maxHeight: '100%',+ objectFit: 'contain',+ filter: theme.palette.mode === 'dark'+ ? 'drop-shadow(0 0 10px rgba(255,255,255,0.2))'+ : 'drop-shadow(0 0 10px rgba(0,0,0,0.1))'+ }}+ />+ )}+ </Box>+ </Grow>++ <Typography+ variant="h3"+ component="h1"+ gutterBottom+ sx={{+ fontWeight: 'bold',+ textAlign: 'center',+ background: theme.palette.text.primary,+ WebkitBackgroundClip: 'text',+ WebkitTextFillColor: 'transparent',+ backgroundClip: 'text',+ mb: 2+ }}+ >+ Welcome to FreeMoCap+ </Typography>++ <Typography+ variant="subtitle1"+ color="text.secondary"+ sx={{+ mb: 4,+ textAlign: 'center',+ maxWidth: '80%',+ fontSize: '1.1rem'+ }}+ >+ Free and open source markerless motion capture for everyone.+ </Typography>++ <Button+ variant="contained"+ size="large"+ onClick={handleConnectCameras}+ disabled={isConnecting}+ startIcon={isConnecting ? <CircularProgress size={20} color="inherit" /> : <VideocamIcon />}+ sx={{+ mb: 3,+ py: 2,+ px: 6,+ fontSize: '1.2rem',+ fontWeight: 'bold',+ borderRadius: 3,+ textTransform: 'none',+ boxShadow: theme.palette.mode === 'dark'+ ? '0 4px 20px rgba(0, 0, 0, 0.5)'+ : '0 4px 20px rgba(0, 0, 0, 0.15)',+ // background: `linear-gradient(135deg, ${theme.palette.primary.main}, ${darken(theme.palette.secondary.main, 0.25)})`,+ background: darken(theme.palette.secondary.main, 0.25),+ transition: 'all 0.3s ease-in-out',+ '&:hover': {+ transform: 'translateY(-2px)',+ boxShadow: theme.palette.mode === 'dark'+ ? '0 6px 24px rgba(0, 0, 0, 0.6)'+ : '0 6px 24px rgba(0, 0, 0, 0.2)',+ },+ '&:disabled': {+ background: theme.palette.action.disabledBackground,+ }+ }}+ >+ {isConnecting ? 'Connecting...' : 'Connect Cameras'}+ </Button>++ <Box component="footer" sx={{ p: 3, mt: 2 }}>+ <Footer />+ </Box>+ </Paper>+ </Fade>++ {/* Research Tool Disclaimer - Outside main clickable area */}+ <Paper+ elevation={1}+ sx={{+ p: 2.5,+ width: '100%',+ backgroundColor: theme.palette.mode === 'dark'+ ? 'rgba(255, 255, 255, 0.03)'+ : 'rgba(0, 0, 0, 0.02)',+ borderRadius: 2,+ }}+ >+ <Typography+ variant="body2"+ color="text.secondary"+ sx={{+ fontSize: '0.85rem',+ lineHeight: 1.8,+ '& a': {+ color: theme.palette.mode === 'dark'+ ? theme.palette.primary.light+ : theme.palette.primary.main,+ textDecoration: 'none',+ fontWeight: 500,+ transition: 'all 0.2s',+ '&:hover': {+ textDecoration: 'underline',+ color: theme.palette.mode === 'dark'+ ? theme.palette.primary.main+ : theme.palette.primary.dark+ }+ }+ }}+ >+ FreeMoCap is currently a research and educational tool, not cleared by the FDA for clinical use. Motion capture devices are regulated under{' '}+ <MuiLink+ href="https://www.ecfr.gov/current/title-21/chapter-I/subchapter-H/part-890"+ target="_blank"+ rel="noopener noreferrer"+ onClick={(e: React.MouseEvent) => e.stopPropagation()}+ >+ 21 CFR Part 890 (Physical Medicine Devices)+ </MuiLink>+ {' '}and require{' '}+ <MuiLink+ href="https://www.fda.gov/medical-devices/premarket-submissions-selecting-and-preparing-correct-submission/premarket-notification-510k"+ target="_blank"+ rel="noopener noreferrer"+ onClick={(e: React.MouseEvent) => e.stopPropagation()}+ >+ 510(k) clearance+ </MuiLink>+ {' '}for clinical applications.+ <br />+ <br />+ <MuiLink+ href="https://freemocap.github.io/documentation/validation/"+ target="_blank"+ rel="noopener noreferrer"+ onClick={(e: React.MouseEvent) => e.stopPropagation()}+ >+ - View our validation studies+ </MuiLink>+ <br />+ <MuiLink+ href="https://freemocap.github.io/documentation/community/fda_pathway/"+ target="_blank"+ rel="noopener noreferrer"+ onClick={(e: React.MouseEvent) => e.stopPropagation()}+ >+ - Join our journey towards FDA certification+ </MuiLink>+ </Typography>+ </Paper>+ </Container>+ );+};++export default WelcomePage;diff --git a/freemocap-ui/src/services/electron-ipc/electron-ipc-client.ts b/freemocap-ui/src/services/electron-ipc/electron-ipc-client.tsnew file mode 100644index 00000000..087b27fc--- /dev/null+++ b/freemocap-ui/src/services/electron-ipc/electron-ipc-client.ts@@ -0,0 +1,98 @@+// src/hooks/electron-service/electron-ipc-client.ts+import {createTRPCProxyClient} from '@trpc/client';+import superjson from 'superjson';+import type {AppAPI} from '../../../electron/main/api';++// Type for the electron API exposed via preload+interface ElectronAPI {+ invoke: (path: string, input?: any) => Promise<any>;+}++declare global {+ interface Window {+ electronAPI: ElectronAPI;+ }+}++// Observable-like class to satisfy tRPC requirements+class IPCObservable<T> {+ constructor(+ private subscribeFn: (observer: {+ next: (value: T) => void;+ error: (error: any) => void;+ complete: () => void;+ }) => { unsubscribe: () => void }+ ) {}++ subscribe(observer: {+ next: (value: T) => void;+ error: (error: any) => void;+ complete: () => void;+ }) {+ return this.subscribeFn(observer);+ }++ // Required pipe method for tRPC compatibility+ pipe(..._operations: any[]): any {+ // For IPC, we don't need complex piping, just return this+ return this;+ }+}++// Custom link for Electron IPC+const createElectronLink = () => {+ return () => {+ return ({ op }: any) => {+ return new IPCObservable((observer) => {+ const execute = async () => {+ try {+ // Check if electronAPI is available+ if (!window.electronAPI) {+ throw new Error('Electron API not available');+ }++ // Call through the IPC bridge+ const serializedResult = await window.electronAPI.invoke(+ op.path,+ op.input+ );++ // Deserialize the result+ const result = superjson.deserialize(serializedResult);++ observer.next({+ result: {+ type: 'data',+ data: result,+ },+ });+ observer.complete();+ } catch (error) {+ console.error(`IPC Error for ${op.path}:`, error);+ observer.error(+ error instanceof Error+ ? error+ : new Error(String(error))+ );+ }+ };++ // Execute the request+ execute();++ // Return unsubscribe function+ return {+ unsubscribe: () => {+ // No-op for now, but could be used for cancellation+ },+ };+ });+ };+ };+};++// Create the typed client - transformer moved to link if using newer tRPC+export const electronIpcClient = createTRPCProxyClient<AppAPI>({+ links: [createElectronLink()],+});+diff --git a/freemocap-ui/src/services/electron-ipc/electron-ipc.ts b/freemocap-ui/src/services/electron-ipc/electron-ipc.tsnew file mode 100644index 00000000..002d0a4a--- /dev/null+++ b/freemocap-ui/src/services/electron-ipc/electron-ipc.ts@@ -0,0 +1,23 @@+// Check if running in Electron+import {electronIpcClient} from "@/services/electron-ipc/electron-ipc-client";+// Type-safe wrapper hook for React components+import {useMemo} from 'react';++export const isElectron = (): boolean => {+ return typeof window !== 'undefined' && !!window.electronAPI;+};++// Export the API client or null if not in Electron+export const electronIpc = isElectron() ? electronIpcClient : null;++export function useElectronIPC() {+ const api = useMemo(() => {+ if (!isElectron()) return null;+ return electronIpcClient;+ }, []);++ return {+ isElectron: isElectron(),+ api,+ };+}diff --git a/freemocap-ui/src/services/electron-ipc/index.ts b/freemocap-ui/src/services/electron-ipc/index.tsnew file mode 100644index 00000000..d560975e--- /dev/null+++ b/freemocap-ui/src/services/electron-ipc/index.ts@@ -0,0 +1,3 @@+// services/index.ts+export * from './electron-ipc'+export * from './electron-ipc-client'diff --git a/freemocap-ui/src/services/index.ts b/freemocap-ui/src/services/index.tsnew file mode 100644index 00000000..7d4a9d34--- /dev/null+++ b/freemocap-ui/src/services/index.ts@@ -0,0 +1,2 @@+export * from './electron-ipc'+export * from './server'diff --git a/freemocap-ui/src/services/server/ServerContextProvider.tsx b/freemocap-ui/src/services/server/ServerContextProvider.tsxnew file mode 100644index 00000000..e483e928--- /dev/null+++ b/freemocap-ui/src/services/server/ServerContextProvider.tsx@@ -0,0 +1,362 @@+import React, {createContext, ReactNode, useCallback, useEffect, useRef, useState} from 'react';+import {useDispatch} from 'react-redux';+import {AppDispatch} from '@/store/types';++import {ConnectionState, WebSocketConnection} from "@/services/server/server-helpers/websocket-connection";+import {FrameProcessor} from "@/services/server/server-helpers/frame-processor/frame-processor";+import {CanvasManager} from "@/services/server/server-helpers/canvas-manager";+import {backendFramerateUpdated, DetailedFramerate, frontendFramerateUpdated, logAdded, LogRecord} from '@/store';++import {FrameCompositor} from "@/services/server/server-helpers/frame_compositor";+import {serverUrls} from "@/hooks/server-urls";+import {+ CharucoObservation,+ CharucoOverlayDataMessage,+ CharucoOverlayDataMessageSchema+} from "@/services/server/server-helpers/image-overlay/charuco-types";+import {+ MediapipeOverlayDataMessage,+ MediapipeOverlayDataMessageSchema+} from "@/services/server/server-helpers/image-overlay/mediapipe-types";+import {+ OverlayManager,+ OverlayRendererFactory+} from "@/services/server/server-helpers/image-overlay/overlay-renderer-factory";+import {ModelInfo} from "@/services/server/server-helpers/image-overlay/image-overlay-system";+import {MediapipeObservation} from "@/services/server/server-helpers/image-overlay/mediapipe-overlay-renderer";++type FrameSubscriber = (bitmap: ImageBitmap) => void;+type TrackedPointsSubscriber = (points: Map<string, Point3d>) => void;++export interface Point3d {+ x: number;+ y: number;+ z: number;+}++export interface ServerContextValue {+ isConnected: boolean;+ connect: () => void;+ disconnect: () => void;+ send: (data: string | object) => void;+ setCanvasForCamera: (cameraId: string, canvas: HTMLCanvasElement) => void;+ getFps: (cameraId: string) => number | null;+ connectedCameraIds: string[];+ subscribeToFrames: (cameraId: string, callback: FrameSubscriber) => () => void;+ subscribeToTrackedPoints: (callback: TrackedPointsSubscriber) => () => void;+ getLatestTrackedPoints: () => Map<string, Point3d>;+}++export const ServerContext = createContext<ServerContextValue | null>(null);++function arraysEqual(a: string[], b: string[]): boolean {+ if (a.length !== b.length) return false;+ const sortedA = [...a].sort();+ const sortedB = [...b].sort();+ return sortedA.every((val, idx) => val === sortedB[idx]);+}++function isLogRecord(data: any): data is LogRecord {+ return (+ data &&+ typeof data === 'object' &&+ data.message_type === 'log_record' &&+ typeof data.levelname === 'string' &&+ typeof data.message === 'string'+ );+}++interface FramerateUpdateMessage {+ message_type: 'framerate_update';+ camera_group_id: string;+ backend_framerate: DetailedFramerate;+ frontend_framerate: DetailedFramerate;+}++function isFramerateUpdate(data: any): data is FramerateUpdateMessage {+ return (+ data &&+ typeof data === 'object' &&+ data.message_type === 'framerate_update' &&+ typeof data.camera_group_id === 'string' &&+ data.backend_framerate &&+ typeof data.backend_framerate === 'object' &&+ data.frontend_framerate &&+ typeof data.frontend_framerate === 'object'+ );+}++function isCharucoOverlayDataMessage(data: any): data is CharucoOverlayDataMessage {+ const result = CharucoOverlayDataMessageSchema.safeParse(data);+ return result.success;+}+function isMediapipeOverlayDataMessage(data: any): data is MediapipeOverlayDataMessage {+ const result = MediapipeOverlayDataMessageSchema.safeParse(data);+ return result.success;+}++function handleModelInfoUpdate(modelInfo: ModelInfo): void {+ console.log(`Received model info for tracker: ${modelInfo.tracker_name}`);+ OverlayRendererFactory.setModelInfo(modelInfo.tracker_name, modelInfo);+}++export const ServerContextProvider: React.FC<{ children: ReactNode }> = ({children}) => {+ const dispatch = useDispatch<AppDispatch>();++ const [isConnected, setIsConnected] = useState<boolean>(false);+ const [connectedCameraIds, setConnectedCameraIds] = useState<string[]>([]);++ const wsConnectionRef = useRef<WebSocketConnection | null>(null);+ const frameProcessorRef = useRef<FrameProcessor | null>(null);+ const canvasManagerRef = useRef<CanvasManager | null>(null);+ const overlayManagerRef = useRef<OverlayManager | null>(null);+ const frameCompositorRef = useRef<FrameCompositor | null>(null);+ const frameSubscribersRef = useRef<Map<string, Set<FrameSubscriber>>>(new Map());+ const latestObservationsRef = useRef<Map<string, CharucoObservation|MediapipeObservation>>(new Map());+ const latestTrackedPoints = useRef<Map<string, Point3d>>(new Map());+ const trackedPointsSubscribersRef = useRef<Set<TrackedPointsSubscriber>>(new Set());++ useEffect(() => {+ wsConnectionRef.current = new WebSocketConnection({+ url: serverUrls.getWebSocketUrl(),+ reconnectDelay: 1000,+ maxReconnectAttempts: 5,+ heartbeatInterval: 30000+ });+ frameProcessorRef.current = new FrameProcessor();+ canvasManagerRef.current = new CanvasManager();+ overlayManagerRef.current = new OverlayManager();+ frameCompositorRef.current = new FrameCompositor();++ return () => {+ if (wsConnectionRef.current) {+ wsConnectionRef.current.disconnect();+ }+ if (canvasManagerRef.current) {+ canvasManagerRef.current.terminateAllWorkers();+ }+ if (frameProcessorRef.current) {+ frameProcessorRef.current.reset();+ }+ if (frameCompositorRef.current) {+ frameCompositorRef.current.destroy();+ }+ latestObservationsRef.current.clear();+ latestTrackedPoints.current.clear();+ trackedPointsSubscribersRef.current.clear();+ };+ }, []);++ useEffect(() => {+ const ws = wsConnectionRef.current;+ if (!ws) return;++ const handleStateChange = (newState: ConnectionState): void => {+ const connected = newState === ConnectionState.CONNECTED;+ setIsConnected(connected);++ if (newState === ConnectionState.DISCONNECTED || newState === ConnectionState.FAILED) {+ canvasManagerRef.current?.terminateAllWorkers();+ frameProcessorRef.current?.reset();+ overlayManagerRef.current?.clearAll();+ latestObservationsRef.current.clear();+ latestTrackedPoints.current.clear();+ setConnectedCameraIds([]);+ }+ };++ const handleMessage = async (event: MessageEvent): Promise<void> => {+ if (event.data instanceof ArrayBuffer) {+ try {+ const result = await frameProcessorRef.current!.processFramePayload(event.data);+ if (!result) return;++ const {frames, cameraIds, frameNumbers} = result;++ const currentCameraIds = Array.from(cameraIds).sort();+ setConnectedCameraIds(prevIds => {+ if (!arraysEqual(prevIds, currentCameraIds)) {+ console.log(`Camera list updated: ${currentCameraIds.join(', ')}`);++ const removedCameras = prevIds.filter(id => !cameraIds.has(id));+ for (const cameraId of removedCameras) {+ console.log(`Removing camera ${cameraId} - not in latest payload`);+ canvasManagerRef.current?.terminateWorker(cameraId);+ overlayManagerRef.current?.clearCamera(cameraId); // Clear overlay renderer+ latestObservationsRef.current.delete(cameraId);+ }++ return currentCameraIds;+ }+ return prevIds;+ });++ // Track remaining frames to render+ let remainingFrames = frames.length;+ const maxFrameNumber = Math.max(...Array.from(frameNumbers));++ const onFrameRendered = (): void => {+ remainingFrames--;+ if (remainingFrames === 0) {+ ws.send({type: 'frameAcknowledgment', frameNumber: maxFrameNumber});+ }+ };++ // Process frames with generic overlay manager+ const overlayManager = overlayManagerRef.current!;+ for (const frameData of frames) {+ const observation = latestObservationsRef.current.get(frameData.cameraId) || null;++ // Use generic overlay manager to composite frame+ const compositeBitmap = await overlayManager.processFrame(+ frameData.cameraId,+ frameData.bitmap,+ observation+ );++ // Send to subscribers if any+ if (frameSubscribersRef.current.size > 0) {+ const subscribers = frameSubscribersRef.current.get(frameData.cameraId);+ if (subscribers && subscribers.size > 0) {+ for (const callback of subscribers) {+ const clonedBitmap = await createImageBitmap(compositeBitmap);+ callback(clonedBitmap);+ }+ }+ }++ // Send to canvas worker+ canvasManagerRef.current!.sendFrameToWorker(+ frameData.cameraId,+ compositeBitmap,+ onFrameRendered+ );+ }+ } catch (error) {+ console.error('Error processing frame:', error);+ throw error;+ }+ }+ else if (typeof event.data === 'string') {+ try {+ const jsonData = JSON.parse(event.data);++ // Handle different observation types+ if (isCharucoOverlayDataMessage(jsonData)) {+ for (const [cameraId, observation] of Object.entries(jsonData)) {+ latestObservationsRef.current.set(cameraId, observation);+ }+ }+ else if (isMediapipeOverlayDataMessage(jsonData)) {+ for (const [cameraId, observation] of Object.entries(jsonData)) {+ latestObservationsRef.current.set(cameraId, observation);+ }+ }+ else if ('model_info' in jsonData && jsonData.model_info) {+ // Handle model info updates+ handleModelInfoUpdate(jsonData.model_info);+ }+ else if ('tracked_points3d' in jsonData) {+ // Handle 3D tracked points+ console.log(`Received 3d data - ${JSON.stringify(jsonData.tracked_points3d)}`);+ latestTrackedPoints.current = new Map(Object.entries(jsonData.tracked_points3d));++ for (const subscriber of trackedPointsSubscribersRef.current) {+ subscriber(latestTrackedPoints.current);+ }+ }+ else if (isLogRecord(jsonData)) {+ dispatch(logAdded(jsonData));+ }+ else if (isFramerateUpdate(jsonData)) {+ dispatch(backendFramerateUpdated(jsonData.backend_framerate));+ dispatch(frontendFramerateUpdated(jsonData.frontend_framerate));+ }+ } catch (error) {+ console.error('Error parsing JSON message:', error);+ throw error;+ }+ }+ };++ ws.on('state-change', handleStateChange);+ ws.on('message', handleMessage);++ ws.connect();++ return () => {+ ws.off('state-change', handleStateChange);+ ws.off('message', handleMessage);+ ws.disconnect();+ };+ }, [dispatch]);++ const connect = useCallback((): void => {+ wsConnectionRef.current?.connect();+ }, []);++ const disconnect = useCallback((): void => {+ wsConnectionRef.current?.disconnect();+ }, []);++ const send = useCallback((data: string | object): void => {+ wsConnectionRef.current?.send(data);+ }, []);++ const setCanvasForCamera = useCallback((cameraId: string, canvas: HTMLCanvasElement): void => {+ canvasManagerRef.current?.setCanvasForCamera(cameraId, canvas);+ }, []);++ const getFps = useCallback((cameraId: string): number | null => {+ return frameProcessorRef.current?.getFps(cameraId) ?? null;+ }, []);++ const subscribeToFrames = useCallback((cameraId: string, callback: FrameSubscriber): (() => void) => {+ if (!frameSubscribersRef.current.has(cameraId)) {+ frameSubscribersRef.current.set(cameraId, new Set());+ }+ frameSubscribersRef.current.get(cameraId)!.add(callback);++ return () => {+ const subscribers = frameSubscribersRef.current.get(cameraId);+ subscribers?.delete(callback);+ if (subscribers?.size === 0) {+ frameSubscribersRef.current.delete(cameraId);+ }+ };+ }, []);++ const subscribeToTrackedPoints = useCallback((callback: TrackedPointsSubscriber): (() => void) => {+ trackedPointsSubscribersRef.current.add(callback);++ // Immediately call with current points if any exist+ if (latestTrackedPoints.current.size > 0) {+ callback(latestTrackedPoints.current);+ }++ return () => {+ trackedPointsSubscribersRef.current.delete(callback);+ };+ }, []);++ const getLatestTrackedPoints = useCallback((): Map<string, Point3d> => {+ return latestTrackedPoints.current;+ }, []);++ return (+ <ServerContext.Provider value={{+ isConnected,+ connect,+ disconnect,+ send,+ setCanvasForCamera,+ getFps,+ connectedCameraIds,+ subscribeToFrames,+ subscribeToTrackedPoints,+ getLatestTrackedPoints+ }}>+ {children}+ </ServerContext.Provider>+ );+};diff --git a/freemocap-ui/src/services/server/index.ts b/freemocap-ui/src/services/server/index.tsnew file mode 100644index 00000000..8f1b48fe--- /dev/null+++ b/freemocap-ui/src/services/server/index.ts@@ -0,0 +1,8 @@+export * from './ServerContextProvider'+export * from '@/services/server/server-helpers/frame-processor/binary-frame-parser'+export * from './server-helpers/canvas-manager'+export * from '@/services/server/server-helpers/frame-processor/frame-processor'+export * from './server-helpers/offscreen-renderer.worker'+export * from '../../hooks/server-urls'+export * from './server-helpers/websocket-connection'+export {useServer} from "@/hooks/useServer";diff --git a/freemocap-ui/src/services/server/server-helpers/canvas-manager.ts b/freemocap-ui/src/services/server/server-helpers/canvas-manager.tsnew file mode 100644index 00000000..921963b5--- /dev/null+++ b/freemocap-ui/src/services/server/server-helpers/canvas-manager.ts@@ -0,0 +1,197 @@+import {workerCode} from "@/services/server/server-helpers/offscreen-renderer.worker";++export interface FrameData {+ cameraId: string;+ frameNumber: number;+ bitmap: ImageBitmap;+}++export interface CanvasWorker {+ worker: Worker;+ canvas: HTMLCanvasElement;+ initialized: boolean;+}++export class CanvasManager {+ private workers: Map<string, CanvasWorker> = new Map();+ private workerErrors: Map<string, number> = new Map();+ private pendingCanvases: Map<string, HTMLCanvasElement> = new Map();+ private renderCallbacks: Map<string, () => void> = new Map(); // cameraId -> callback+ private readonly maxWorkerErrors: number = 3;++ public setCanvasForCamera(cameraId: string, canvas: HTMLCanvasElement): boolean {+ const existing = this.workers.get(cameraId);+ if (existing?.canvas === canvas && existing.initialized) {+ return true;+ }++ if (existing && existing.canvas !== canvas) {+ console.log(`Canvas changed for camera ${cameraId}, recreating worker`);+ this.terminateWorker(cameraId);+ }++ this.pendingCanvases.set(cameraId, canvas);++ try {+ const worker = this.createWorker(cameraId);+ const offscreen = canvas.transferControlToOffscreen();++ worker.postMessage(+ { type: 'init', canvas: offscreen },+ [offscreen]+ );++ this.workers.set(cameraId, {+ worker,+ canvas,+ initialized: true+ });++ this.workerErrors.delete(cameraId);+ this.pendingCanvases.delete(cameraId);++ console.log(`Worker created for camera ${cameraId}`);+ return true;++ } catch (error) {+ console.error(`Failed to create worker for camera ${cameraId}:`, error);+ this.recordWorkerError(cameraId);+ return false;+ }+ }++ public sendFrameToWorker(+ cameraId: string,+ bitmap: ImageBitmap,+ onRendered?: () => void+ ): boolean {+ const workerInfo = this.workers.get(cameraId);++ if (!workerInfo?.initialized) {+ const pendingCanvas = this.pendingCanvases.get(cameraId);+ if (pendingCanvas) {+ console.log(`Worker not ready for ${cameraId}, attempting to create from pending canvas`);+ if (this.setCanvasForCamera(cameraId, pendingCanvas)) {+ return this.sendFrameToWorker(cameraId, bitmap, onRendered);+ }+ }++ console.warn(`No initialized worker for camera ${cameraId}, dropping frame`);+ bitmap.close();+ onRendered?.();+ return false;+ }++ try {+ // Store callback for this camera+ if (onRendered) {+ this.renderCallbacks.set(cameraId, onRendered);+ }++ workerInfo.worker.postMessage(+ { type: 'frame', bitmap },+ [bitmap]+ );+ return true;+ } catch (error) {+ console.error(`Failed to send frame to worker ${cameraId}:`, error);+ bitmap.close();+ onRendered?.();+ this.recordWorkerError(cameraId);+ return false;+ }+ }++ public terminateWorker(cameraId: string): void {+ const workerInfo = this.workers.get(cameraId);+ if (workerInfo) {+ try {+ workerInfo.worker.terminate();+ console.log(`Worker terminated for camera ${cameraId}`);+ } catch (error) {+ console.error(`Error terminating worker for ${cameraId}:`, error);+ }+ this.workers.delete(cameraId);+ }++ // Clean up callback+ this.renderCallbacks.delete(cameraId);+ this.pendingCanvases.delete(cameraId);+ }++ public terminateAllWorkers(): void {+ console.log(`Terminating all workers (${this.workers.size} active)`);+ for (const [cameraId] of this.workers) {+ this.terminateWorker(cameraId);+ }+ this.workerErrors.clear();+ this.pendingCanvases.clear();+ this.renderCallbacks.clear();+ }++ public getActiveCameraIds(): string[] {+ return Array.from(this.workers.keys());+ }++ public hasWorker(cameraId: string): boolean {+ const worker = this.workers.get(cameraId);+ return worker?.initialized ?? false;+ }++ private createWorker(cameraId: string): Worker {+ const blob = new Blob([workerCode], { type: 'application/javascript' });+ const workerUrl = URL.createObjectURL(blob);++ try {+ const worker = new Worker(workerUrl);++ worker.onerror = (error) => {+ console.error(`Worker error for camera ${cameraId}:`, error);+ this.recordWorkerError(cameraId);+ };++ worker.onmessageerror = (error) => {+ console.error(`Worker message error for camera ${cameraId}:`, error);+ };++ worker.onmessage = (e) => {+ if (e.data.type === 'frameRendered') {+ const callback = this.renderCallbacks.get(cameraId);+ if (callback) {+ callback();+ this.renderCallbacks.delete(cameraId);+ }+ }+ };++ return worker;+ } finally {+ URL.revokeObjectURL(workerUrl);+ }+ }++ private recordWorkerError(cameraId: string): void {+ const errorCount = (this.workerErrors.get(cameraId) ?? 0) + 1;+ this.workerErrors.set(cameraId, errorCount);++ if (errorCount >= this.maxWorkerErrors) {+ console.error(+ `Worker for camera ${cameraId} has failed ${errorCount} times, disabling. ` ++ `Worker will be recreated if canvas is set again.`+ );+ this.terminateWorker(cameraId);+ }+ }++ public getWorkerStatus(cameraId: string): {+ hasWorker: boolean;+ errorCount: number;+ hasPendingCanvas: boolean;+ } {+ return {+ hasWorker: this.workers.has(cameraId),+ errorCount: this.workerErrors.get(cameraId) ?? 0,+ hasPendingCanvas: this.pendingCanvases.has(cameraId)+ };+ }+}diff --git a/freemocap-ui/src/services/server/server-helpers/frame-processor/binary-frame-parser.ts b/freemocap-ui/src/services/server/server-helpers/frame-processor/binary-frame-parser.tsnew file mode 100644index 00000000..e75eeeb3--- /dev/null+++ b/freemocap-ui/src/services/server/server-helpers/frame-processor/binary-frame-parser.ts@@ -0,0 +1,251 @@+// binary-frame-parser.ts+import {+ FRAME_HEADER_FIELDS,+ FRAME_HEADER_SIZE,+ MESSAGE_TYPE,+ PAYLOAD_FOOTER_FIELDS,+ PAYLOAD_FOOTER_SIZE,+ PAYLOAD_HEADER_FIELDS,+ PAYLOAD_HEADER_SIZE,+} from './binary-protocol';++export interface ParsedFrame {+ cameraId: string;+ cameraIndex: number;+ frameNumber: number;+ width: number;+ height: number;+ colorChannels: number;+ bitmap: ImageBitmap;+}++// Single reusable TextDecoder+const sharedTextDecoder = new TextDecoder();++// Optimized ImageBitmap options for camera feeds+const BITMAP_OPTIONS: ImageBitmapOptions = {+ premultiplyAlpha: 'none',+ colorSpaceConversion: 'none',+ resizeQuality: 'pixelated'+};++/**+ * Parse an ASCII string field from the buffer (16-byte fixed-length camera_id)+ */+function parseAsciiField(view: DataView, baseOffset: number, fieldOffset: number, size: number): string {+ const offset = baseOffset + fieldOffset;++ // Find actual string length (until null terminator)+ let length = 0;+ while (length < size && view.getUint8(offset + length) !== 0) {+ length++;+ }++ if (length === 0) return '';++ const bytes = new Uint8Array(view.buffer, view.byteOffset + offset, length);+ return sharedTextDecoder.decode(bytes);+}++/**+ * Parse a multi-frame payload from binary data+ * Matches the Python create_frontend_payload function's output format+ */+export async function parseMultiFramePayload(+ data: ArrayBuffer+): Promise<ParsedFrame[] | null> {+ const view = new DataView(data);++ // Validate minimum size+ if (data.byteLength < PAYLOAD_HEADER_SIZE) {+ console.warn(`Payload too small: ${data.byteLength} bytes`);+ return null;+ }++ // Validate payload header+ const messageType = view.getUint8(PAYLOAD_HEADER_FIELDS.message_type.offset);+ if (messageType !== MESSAGE_TYPE.PAYLOAD_HEADER) {+ console.warn(`Invalid payload header: expected ${MESSAGE_TYPE.PAYLOAD_HEADER}, got ${messageType}`);+ return null;+ }++ // Extract payload header fields+ const frameNumber = Number(+ view.getBigInt64(PAYLOAD_HEADER_FIELDS.frame_number.offset, true)+ );++ const numCameras = view.getInt32(+ PAYLOAD_HEADER_FIELDS.number_of_cameras.offset,+ true+ );++ // Validate camera count+ if (numCameras <= 0 ) {+ console.warn(`Invalid camera count: ${numCameras}`);+ return null;+ }++ // Pre-allocate array for frame metadata+ const frameMetadata: Array<{+ cameraId: string;+ cameraIndex: number;+ frameNumber: number;+ width: number;+ height: number;+ colorChannels: number;+ jpegStart: number;+ jpegLength: number;+ }> = new Array(numCameras);++ let currentOffset = PAYLOAD_HEADER_SIZE;+ let validFrameCount = 0;++ // Parse each frame header+ for (let i = 0; i < numCameras; i++) {+ // Check if we have enough bytes for the frame header+ if (currentOffset + FRAME_HEADER_SIZE > data.byteLength) {+ console.warn(`Not enough bytes for frame header at offset ${currentOffset}`);+ break;+ }++ // Validate frame header message type+ const frameMessageType = view.getUint8(+ currentOffset + FRAME_HEADER_FIELDS.message_type.offset+ );++ if (frameMessageType !== MESSAGE_TYPE.FRAME_METADATA) {+ console.warn(+ `Invalid frame header at offset ${currentOffset}: ` ++ `expected ${MESSAGE_TYPE.FRAME_METADATA}, got ${frameMessageType}`+ );+ break;+ }++ // Extract frame number+ const frameNum = Number(+ view.getBigInt64(+ currentOffset + FRAME_HEADER_FIELDS.frame_number.offset,+ true+ )+ );++ // Extract camera_id (16-byte ASCII string)+ const cameraId = parseAsciiField(+ view,+ currentOffset,+ FRAME_HEADER_FIELDS.camera_id.offset,+ FRAME_HEADER_FIELDS.camera_id.size+ );++ // Extract camera_index+ const cameraIndex = view.getInt32(+ currentOffset + FRAME_HEADER_FIELDS.camera_index.offset,+ true+ );++ // Extract image metadata+ const width = view.getInt32(+ currentOffset + FRAME_HEADER_FIELDS.image_width.offset,+ true+ );++ const height = view.getInt32(+ currentOffset + FRAME_HEADER_FIELDS.image_height.offset,+ true+ );++ const colorChannels = view.getInt32(+ currentOffset + FRAME_HEADER_FIELDS.color_channels.offset,+ true+ );++ const jpegLength = view.getInt32(+ currentOffset + FRAME_HEADER_FIELDS.jpeg_string_length.offset,+ true+ );++ // Validate JPEG length+ if (jpegLength <= 0 ) {+ console.warn(`Invalid JPEG length: ${jpegLength}`);+ break;+ }++ // Check if we have enough bytes for the JPEG data+ const jpegStart = currentOffset + FRAME_HEADER_SIZE;+ if (jpegStart + jpegLength > data.byteLength) {+ console.warn(+ `Not enough bytes for JPEG data: need ${jpegLength} bytes ` ++ `at offset ${jpegStart}, but buffer only has ${data.byteLength} bytes`+ );+ break;+ }++ // Store metadata+ frameMetadata[validFrameCount] = {+ cameraId: cameraId,+ cameraIndex: cameraIndex,+ frameNumber: frameNum,+ width: width,+ height: height,+ colorChannels: colorChannels,+ jpegStart: jpegStart,+ jpegLength: jpegLength+ };++ validFrameCount++;+ currentOffset += FRAME_HEADER_SIZE + jpegLength;+ }++ if (validFrameCount === 0) {+ console.warn('No valid frames found in payload');+ return null;+ }++ // Optional: Validate footer if present+ if (currentOffset + PAYLOAD_FOOTER_SIZE <= data.byteLength) {+ const footerMessageType = view.getUint8(currentOffset + PAYLOAD_FOOTER_FIELDS.message_type.offset);+ if (footerMessageType === MESSAGE_TYPE.PAYLOAD_FOOTER) {+ const footerFrameNumber = Number(+ view.getBigInt64(currentOffset + PAYLOAD_FOOTER_FIELDS.frame_number.offset, true)+ );+ const footerNumCameras = view.getInt32(+ currentOffset + PAYLOAD_FOOTER_FIELDS.number_of_cameras.offset,+ true+ );++ if (footerFrameNumber !== frameNumber || footerNumCameras !== numCameras) {+ console.warn(+ `Footer mismatch: header(frame=${frameNumber}, cameras=${numCameras}) ` ++ `footer(frame=${footerFrameNumber}, cameras=${footerNumCameras})`+ );+ }+ }+ }++ // Trim array to actual size.+ frameMetadata.length = validFrameCount;++ // Create ImageBitmaps in parallel+ const bitmapPromises = frameMetadata.map(async (metadata) => {+ try {+ const jpegData = new Uint8Array(data, metadata.jpegStart, metadata.jpegLength);+ const blob = new Blob([jpegData], { type: 'image/jpeg' });+ const bitmap = await createImageBitmap(blob, BITMAP_OPTIONS);++ return {+ cameraId: metadata.cameraId,+ cameraIndex: metadata.cameraIndex,+ frameNumber: metadata.frameNumber,+ width: metadata.width,+ height: metadata.height,+ colorChannels: metadata.colorChannels,+ bitmap: bitmap,+ } as ParsedFrame;+ } catch (error) {+ console.error(`Failed to create bitmap for camera ${metadata.cameraId}:`, error);+ throw error;+ }+ });++ return Promise.all(bitmapPromises);+}diff --git a/freemocap-ui/src/services/server/server-helpers/frame-processor/binary-protocol.ts b/freemocap-ui/src/services/server/server-helpers/frame-processor/binary-protocol.tsnew file mode 100644index 00000000..a6d625af--- /dev/null+++ b/freemocap-ui/src/services/server/server-helpers/frame-processor/binary-protocol.ts@@ -0,0 +1,78 @@+// binary-protocol.ts+/**+ * Binary protocol definition for frame payloads+ * Matches the Python FRONTEND_PAYLOAD_HEADER_FOOTER_DTYPE and FRONTEND_FRAME_HEADER_DTYPE+ * WITH align=True (includes padding for natural alignment)+ * All offsets and sizes are in bytes+ */++// Message type constants (matches Python MessageType class)+export const MESSAGE_TYPE = {+ PAYLOAD_HEADER: 0,+ FRAME_METADATA: 1,+ PAYLOAD_FOOTER: 2,+} as const;++// Field sizes (in bytes)+const FIELD_SIZES = {+ // Primitive types+ U1: 1, // unsigned 8-bit+ I4: 4, // signed 32-bit integer+ I8: 8, // signed 64-bit integer+ S16: 16, // 16-byte ASCII string (for camera_id)+} as const;++// Payload header structure (matches FRONTEND_PAYLOAD_HEADER_FOOTER_DTYPE with align=True)+// Structure with padding:+// message_type (1 byte) + padding (7 bytes) + frame_number (8 bytes) + number_of_cameras (4 bytes) + padding (4 bytes)+export const PAYLOAD_HEADER_FIELDS = {+ message_type: { offset: 0, size: FIELD_SIZES.U1, type: 'uint8' },+ // 7 bytes padding here for 8-byte alignment of frame_number+ frame_number: { offset: 8, size: FIELD_SIZES.I8, type: 'int64' },+ number_of_cameras: { offset: 16, size: FIELD_SIZES.I4, type: 'int32' },+ // 4 bytes padding here for struct alignment+} as const;++export const PAYLOAD_HEADER_SIZE = 24; // Total: 1 + 7 padding + 8 + 4 + 4 padding++// Frame header structure (matches FRONTEND_FRAME_HEADER_DTYPE with align=True)+// Structure with padding:+// message_type (1 byte) + padding (7 bytes) + frame_number (8 bytes) + camera_id (16 bytes) ++// camera_index (4 bytes) + image_width (4 bytes) + image_height (4 bytes) ++// color_channels (4 bytes) + jpeg_string_length (4 bytes) + padding (4 bytes)+export const FRAME_HEADER_FIELDS = {+ message_type: { offset: 0, size: FIELD_SIZES.U1, type: 'uint8' },+ // 7 bytes padding here for 8-byte alignment of frame_number+ frame_number: { offset: 8, size: FIELD_SIZES.I8, type: 'int64' },+ camera_id: { offset: 16, size: FIELD_SIZES.S16, type: 'ascii' },+ camera_index: { offset: 32, size: FIELD_SIZES.I4, type: 'int32' },+ image_width: { offset: 36, size: FIELD_SIZES.I4, type: 'int32' },+ image_height: { offset: 40, size: FIELD_SIZES.I4, type: 'int32' },+ color_channels: { offset: 44, size: FIELD_SIZES.I4, type: 'int32' },+ jpeg_string_length: { offset: 48, size: FIELD_SIZES.I4, type: 'int32' },+ // 4 bytes padding here for struct alignment+} as const;++export const FRAME_HEADER_SIZE = 56; // Total: 1 + 7 padding + 8 + 16 + 4 + 4 + 4 + 4 + 4 + 4 padding++// Payload footer structure (matches FRONTEND_PAYLOAD_HEADER_FOOTER_DTYPE with align=True)+export const PAYLOAD_FOOTER_FIELDS = {+ message_type: { offset: 0, size: FIELD_SIZES.U1, type: 'uint8' },+ // 7 bytes padding here for 8-byte alignment of frame_number+ frame_number: { offset: 8, size: FIELD_SIZES.I8, type: 'int64' },+ number_of_cameras: { offset: 16, size: FIELD_SIZES.I4, type: 'int32' },+ // 4 bytes padding here for struct alignment+} as const;++export const PAYLOAD_FOOTER_SIZE = 24; // Total: 1 + 7 padding + 8 + 4 + 4 padding++// Helper type definitions+export type FieldType = 'uint8' | 'int32' | 'int64' | 'ascii';++export interface FieldDefinition {+ offset: number;+ size: number;+ type: FieldType;+}++export type MessageType = typeof MESSAGE_TYPE[keyof typeof MESSAGE_TYPE];diff --git a/freemocap-ui/src/services/server/server-helpers/frame-processor/frame-processor.ts b/freemocap-ui/src/services/server/server-helpers/frame-processor/frame-processor.tsnew file mode 100644index 00000000..089a2526--- /dev/null+++ b/freemocap-ui/src/services/server/server-helpers/frame-processor/frame-processor.ts@@ -0,0 +1,78 @@+// frame-processor.ts+import {+ ParsedFrame,+ parseMultiFramePayload+} from "@/services/server/server-helpers/frame-processor/binary-frame-parser";++export interface FrameData {+ cameraId: string;+ cameraIndex: number;+ frameNumber: number;+ width: number;+ height: number;+ colorChannels: number;+ bitmap: ImageBitmap;+}++export interface ProcessedFrameResult {+ frames: FrameData[];+ cameraIds: Set<string>;+ frameNumbers: Set<number>;+}++export class FrameProcessor {+ private lastFrameTime: Map<string, number> = new Map();+ private currentFps: Map<string, number> = new Map();++ public async processFramePayload(data: ArrayBuffer): Promise<ProcessedFrameResult | null> {+ try {+ const parsedFrames = await parseMultiFramePayload(data);+ if (!parsedFrames) {+ console.warn('Failed to parse frame payload');+ return null;+ }++ const cameraIds = new Set<string>();+ const frameNumbers = new Set<number>();++ // Convert ParsedFrame to FrameData (they have the same structure now)+ const frames: FrameData[] = parsedFrames.map((frame: ParsedFrame) => ({+ cameraId: frame.cameraId,+ cameraIndex: frame.cameraIndex,+ frameNumber: frame.frameNumber,+ width: frame.width,+ height: frame.height,+ colorChannels: frame.colorChannels,+ bitmap: frame.bitmap+ }));++ for (const frame of frames) {+ cameraIds.add(frame.cameraId);+ frameNumbers.add(frame.frameNumber);++ // Track frame timing and calculate FPS+ const now = performance.now();+ const lastTime = this.lastFrameTime.get(frame.cameraId);+ if (lastTime) {+ const fps = 1000 / (now - lastTime);+ this.currentFps.set(frame.cameraId, fps);+ }+ this.lastFrameTime.set(frame.cameraId, now);+ }++ return { frames, cameraIds, frameNumbers };+ } catch (error) {+ console.error('Error processing frame payload:', error);+ throw new Error(`Frame processing failed: ${error}`);+ }+ }++ public getFps(cameraId: string): number | null {+ return this.currentFps.get(cameraId) ?? null;+ }++ public reset(): void {+ this.lastFrameTime.clear();+ this.currentFps.clear();+ }+}diff --git a/freemocap-ui/src/services/server/server-helpers/frame_compositor.ts b/freemocap-ui/src/services/server/server-helpers/frame_compositor.tsnew file mode 100644index 00000000..50486d2c--- /dev/null+++ b/freemocap-ui/src/services/server/server-helpers/frame_compositor.ts@@ -0,0 +1,216 @@+import {ArucoMarker, CharucoObservation, CharucoPoint} from "@/services/server/server-helpers/charuco_types";++/**+ * Composites overlay graphics directly onto an ImageBitmap.+ * Returns a new ImageBitmap with the overlay drawn on top.+ */+export class FrameCompositor {+ private offscreenCanvas: OffscreenCanvas;+ private ctx: OffscreenCanvasRenderingContext2D;++ // Style constants+ private readonly CHARUCO_COLOR = '#00FF00';+ private readonly CHARUCO_STROKE = '#009600';+ private readonly ARUCO_COLOR = '#FF6400';+ private readonly ARUCO_STROKE = '#C85000';+ private readonly TEXT_COLOR = '#ccc';+ private readonly TEXT_STROKE = '#111';+ private readonly INFO_BG = 'rgba(0, 0, 0, 0.7)';+ private readonly SCALE: number = 1.0;++ constructor() {+ // Create a reusable offscreen canvas for compositing+ this.offscreenCanvas = new OffscreenCanvas(1, 1);+ const ctx = this.offscreenCanvas.getContext('2d', {+ alpha: true,+ desynchronized: true,+ });++ if (!ctx) {+ throw new Error('Failed to get 2D context for compositor');+ }++ this.ctx = ctx;+ }++ /**+ * Composite overlay onto an ImageBitmap and return a new ImageBitmap+ */+ public async compositeFrame(+ sourceBitmap: ImageBitmap,+ observation: CharucoObservation | null,+ ): Promise<ImageBitmap> {+ const { width, height } = sourceBitmap;++ // Resize canvas if needed+ if (this.offscreenCanvas.width !== width || this.offscreenCanvas.height !== height) {+ this.offscreenCanvas.width = width;+ this.offscreenCanvas.height = height;+ }++ // Draw source image+ this.ctx.clearRect(0, 0, width, height);+ this.ctx.drawImage(sourceBitmap, 0, 0);++ // Draw overlay if we have observation data+ if (observation) {+ this.drawOverlay(observation);+ }++ // Create new bitmap from composited result+ const compositeBitmap = await createImageBitmap(this.offscreenCanvas);++ // Close the source bitmap since we're done with it+ sourceBitmap.close();++ return compositeBitmap;+ }++ private drawOverlay(observation: CharucoObservation): void {+ this.ctx.save();+ this.ctx.scale(this.SCALE, this.SCALE);++ // Draw ArUco markers (behind Charuco corners)+ this.drawArucoMarkers(observation.aruco_markers);++ // Draw Charuco corners+ this.drawCharucoCorners(observation.charuco_corners);++ // Draw info overlay+ this.drawInfoOverlay(observation);++ this.ctx.restore();+ }++ private drawCharucoCorners(corners: CharucoPoint[]): void {+ if (corners.length === 0) return;++ for (const corner of corners) {+ // Draw filled circle+ this.ctx.fillStyle = this.CHARUCO_COLOR;+ this.ctx.beginPath();+ this.ctx.arc(corner.x, corner.y, 5, 0, Math.PI * 2);+ this.ctx.fill();++ // Draw stroke+ this.ctx.strokeStyle = this.CHARUCO_STROKE;+ this.ctx.lineWidth = 2;+ this.ctx.stroke();++ // Draw ID label+ this.drawText(+ corner.id.toString(),+ corner.x + 8,+ corner.y - 8,+ 10,+ this.CHARUCO_COLOR,+ this.TEXT_STROKE,+ 2+ );+ }+ }++ private drawArucoMarkers(markers: ArucoMarker[]): void {+ if (markers.length === 0) return;++ for (const marker of markers) {+ // Draw marker outline+ this.ctx.strokeStyle = this.ARUCO_COLOR;+ this.ctx.lineWidth = 3;+ this.ctx.beginPath();++ // Draw square connecting the 4 corners+ this.ctx.moveTo(marker.corners[0][0], marker.corners[0][1]);+ for (let i = 1; i < 4; i++) {+ this.ctx.lineTo(marker.corners[i][0], marker.corners[i][1]);+ }+ this.ctx.closePath();+ this.ctx.stroke();++ // Draw corner points+ this.ctx.fillStyle = this.ARUCO_COLOR;+ for (const corner of marker.corners) {+ this.ctx.beginPath();+ this.ctx.arc(corner[0], corner[1], 4, 0, Math.PI * 2);+ this.ctx.fill();+ }++ // Draw marker ID at center+ const centerX = marker.corners.reduce((sum, c) => sum + c[0], 0) / marker.corners.length;+ const centerY = marker.corners.reduce((sum, c) => sum + c[1], 0) / marker.corners.length;++ this.drawText(+ marker.id.toString(),+ centerX,+ centerY,+ 14,+ this.TEXT_COLOR,+ this.ARUCO_COLOR,+ 3,+ 'bold'+ );+ }+ }++ private drawInfoOverlay(observation: CharucoObservation): void {+ const { metadata, frame_number } = observation;++ // Info text+ const infoText =+ `Frame: ${frame_number} | ` ++ `Charuco: ${metadata.n_charuco_detected}/${metadata.n_charuco_total} | ` ++ `ArUco: ${metadata.n_aruco_detected}/${metadata.n_aruco_total}` ++ (metadata.has_pose ? ' | POSE โ' : '');++ // Status text+ let statusText = '';+ let statusColor = '';+ if (metadata.n_charuco_detected === 0 && metadata.n_aruco_detected === 0) {+ statusText = 'โ NO BOARD DETECTED';+ statusColor = '#FF4444';+ } else if (metadata.n_charuco_detected < 4) {+ statusText = 'โ INSUFFICIENT CORNERS';+ statusColor = '#FFAA00';+ } else {+ statusText = 'โ BOARD DETECTED';+ statusColor = '#00FF00';+ }++ // Draw info background+ this.ctx.fillStyle = this.INFO_BG;+ this.ctx.fillRect(5, 5, 500, 60);++ // Draw info text+ this.drawText(infoText, 10, 25, 14, this.TEXT_COLOR, this.TEXT_STROKE, 2);++ // Draw status text+ this.drawText(statusText, 10, 50, 16, statusColor, this.TEXT_STROKE, 2);+ }++ private drawText(+ text: string,+ x: number,+ y: number,+ fontSize: number,+ fillColor: string,+ strokeColor: string,+ strokeWidth: number,+ fontWeight: string = 'normal'+ ): void {+ this.ctx.font = `${fontWeight} ${fontSize}px Arial, sans-serif`;+ this.ctx.textBaseline = 'middle';++ // Draw stroke (outline)+ this.ctx.strokeStyle = strokeColor;+ this.ctx.lineWidth = strokeWidth + 2;+ this.ctx.strokeText(text, x, y);++ // Draw fill+ this.ctx.fillStyle = fillColor;+ this.ctx.fillText(text, x, y);+ }++ public destroy(): void {+ // Cleanup if needed+ }+}diff --git a/freemocap-ui/src/services/server/server-helpers/image-overlay/charuco-overlay-renderer.ts b/freemocap-ui/src/services/server/server-helpers/image-overlay/charuco-overlay-renderer.tsnew file mode 100644index 00000000..6416d25f--- /dev/null+++ b/freemocap-ui/src/services/server/server-helpers/image-overlay/charuco-overlay-renderer.ts@@ -0,0 +1,184 @@+// charuco-overlay-renderer.ts++import {+ BaseOverlayRenderer,+ DrawStyle,+ Point2D+} from "@/services/server/server-helpers/image-overlay/image-overlay-system";+import {+ ArucoMarker,+ CharucoObservation,+ CharucoPoint+} from "@/services/server/server-helpers/image-overlay/charuco-types";++export class CharucoOverlayRenderer extends BaseOverlayRenderer {+ // Charuco-specific styles+ private readonly charucoStyle: DrawStyle = {+ pointColor: '#00FF00',+ pointStroke: '#009600',+ pointRadius: 5,+ lineColor: '#00FF00',+ lineWidth: 2,+ labelColor: '#00FF00',+ labelStroke: this.TEXT_STROKE,+ labelFontSize: 10,+ showLabels: true,+ };++ private readonly arucoStyle: DrawStyle = {+ pointColor: '#FF6400',+ pointStroke: '#C85000',+ pointRadius: 4,+ lineColor: '#FF6400',+ lineWidth: 3,+ labelColor: this.TEXT_COLOR,+ labelStroke: '#FF6400',+ labelFontSize: 14,+ showLabels: true,+ };++ /**+ * Composite charuco overlay onto frame+ */+ public async compositeFrame(+ sourceBitmap: ImageBitmap,+ observation: CharucoObservation | null,+ ): Promise<ImageBitmap> {+ this.prepareCanvas(sourceBitmap);++ if (observation) {+ this.drawCharucoOverlay(observation);+ }++ return this.createBitmap(sourceBitmap);+ }++ private drawCharucoOverlay(observation: CharucoObservation): void {+ this.ctx.save();++ // Draw ArUco markers first (behind Charuco corners)+ this.drawArucoMarkers(observation.aruco_markers);++ // Draw Charuco corners+ this.drawCharucoCorners(observation.charuco_corners);++ // Draw segments if model info is available+ if (this.modelInfo) {+ this.drawCharucoSegments(observation.charuco_corners);+ }++ // Draw info overlay+ this.drawCharucoInfo(observation);++ this.ctx.restore();+ }++ private drawCharucoCorners(corners: CharucoPoint[]): void {+ if (corners.length === 0) return;++ // Convert CharucoPoint[] to Point2D[]+ const points: Point2D[] = corners.map(corner => ({+ x: corner.x,+ y: corner.y,+ id: corner.id,+ }));++ this.drawPoints(points, this.charucoStyle);+ }++ private drawCharucoSegments(corners: CharucoPoint[]): void {+ if (!this.modelInfo || corners.length === 0) return;++ // Create a map of corner ID to Point2D+ const pointMap = new Map<string | number, Point2D>();+ for (const corner of corners) {+ pointMap.set(corner.id.toString(), {+ x: corner.x,+ y: corner.y,+ id: corner.id,+ });+ }++ // Get segments from model info+ const bodyAspect = this.modelInfo.aspects['body'];+ if (bodyAspect?.segment_connections) {+ this.drawSegments(pointMap, bodyAspect.segment_connections, {+ ...this.charucoStyle,+ lineColor: 'rgba(0, 255, 0, 0.5)', // Semi-transparent green+ lineWidth: 1,+ });+ }+ }++ private drawArucoMarkers(markers: ArucoMarker[]): void {+ if (markers.length === 0) return;++ for (const marker of markers) {+ this.drawPolygon(+ marker.corners,+ this.arucoStyle,+ true,+ marker.id.toString()+ );+ }+ }++ private drawCharucoInfo(observation: CharucoObservation): void {+ const { metadata, frame_number } = observation;++ // Build status info+ let statusText = '';+ let statusColor = '';+ if (metadata.n_charuco_detected === 0 && metadata.n_aruco_detected === 0) {+ statusText = 'โ NO BOARD DETECTED';+ statusColor = '#FF4444';+ } else if (metadata.n_charuco_detected < 4) {+ statusText = 'โ INSUFFICIENT CORNERS';+ statusColor = '#FFAA00';+ } else {+ statusText = 'โ BOARD DETECTED';+ statusColor = '#00FF00';+ }++ const additionalInfo = [+ `Charuco: ${metadata.n_charuco_detected}/${metadata.n_charuco_total} | ` ++ `ArUco: ${metadata.n_aruco_detected}/${metadata.n_aruco_total}` ++ (metadata.has_pose ? ' | POSE โ' : ''),+ statusText,+ ];++ // Draw background and info+ this.ctx.fillStyle = this.INFO_BG;+ this.ctx.fillRect(5, 5, 500, 85);++ this.drawText(+ `Frame: ${frame_number}`,+ 10,+ 25,+ 14,+ this.TEXT_COLOR,+ this.TEXT_STROKE,+ 2+ );++ this.drawText(+ additionalInfo[0],+ 10,+ 50,+ 14,+ this.TEXT_COLOR,+ this.TEXT_STROKE,+ 2+ );++ this.drawText(+ additionalInfo[1],+ 10,+ 75,+ 16,+ statusColor,+ this.TEXT_STROKE,+ 2+ );+ }+}diff --git a/freemocap-ui/src/services/server/server-helpers/image-overlay/charuco-types.ts b/freemocap-ui/src/services/server/server-helpers/image-overlay/charuco-types.tsnew file mode 100644index 00000000..74fa788a--- /dev/null+++ b/freemocap-ui/src/services/server/server-helpers/image-overlay/charuco-types.ts@@ -0,0 +1,43 @@+import {z} from 'zod';++// Zod schemas for CharucoObservation data+export const CharucoPointSchema = z.object({+ id: z.number(),+ x: z.number(),+ y: z.number(),+});++export const ArucoMarkerSchema = z.object({+ id: z.number(),+ corners: z.array(z.tuple([z.number(), z.number()])).length(4),+});++export const CharucoMetadataSchema = z.object({+ n_charuco_detected: z.number(),+ n_charuco_total: z.number(),+ n_aruco_detected: z.number(),+ n_aruco_total: z.number(),+ has_pose: z.boolean(),+ image_width: z.number(),+ image_height: z.number(),+});++// Schema for a single camera's charuco observation+export const CharucoOverlaySchema = z.object({+ message_type: z.literal("charuco_overlay"),+ camera_id: z.string(),+ frame_number: z.number(),+ charuco_corners: z.array(CharucoPointSchema),+ aruco_markers: z.array(ArucoMarkerSchema),+ metadata: CharucoMetadataSchema,+});++// Schema for the websocket message containing multiple camera observations+// Structure: { "camera_1": {...}, "camera_2": {...}, ... }+export const CharucoOverlayDataMessageSchema = z.record(z.string(), CharucoOverlaySchema);++// Type exports+export type CharucoPoint = z.infer<typeof CharucoPointSchema>;+export type ArucoMarker = z.infer<typeof ArucoMarkerSchema>;+export type CharucoObservation = z.infer<typeof CharucoOverlaySchema>;+export type CharucoOverlayDataMessage = z.infer<typeof CharucoOverlayDataMessageSchema>;diff --git a/freemocap-ui/src/services/server/server-helpers/image-overlay/image-overlay-system.ts b/freemocap-ui/src/services/server/server-helpers/image-overlay/image-overlay-system.tsnew file mode 100644index 00000000..f0fe2b21--- /dev/null+++ b/freemocap-ui/src/services/server/server-helpers/image-overlay/image-overlay-system.ts@@ -0,0 +1,303 @@+// base-overlay-renderer.ts+import { z } from 'zod';++// Generic types for any observation+export interface Point2D {+ x: number;+ y: number;+ id?: string | number;+ visibility?: number; // 0-1, for confidence/visibility+}++export interface Segment {+ proximal: string | number;+ distal: string | number;+}++export interface ModelInfo {+ name: string;+ tracker_name: string;+ aspects: Record<string, AspectInfo>;+ order: string[];+}++export interface AspectInfo {+ tracked_points: {+ type: 'list' | 'generated';+ names?: string[];+ convention?: string;+ count?: number;+ };+ segment_connections?: Record<string, Segment>;+ joint_hierarchy?: Record<string, string[]>;+}++export interface DrawStyle {+ pointColor: string;+ pointStroke: string;+ pointRadius: number;+ lineColor: string;+ lineWidth: number;+ labelColor: string;+ labelStroke: string;+ labelFontSize: number;+ showLabels: boolean;+}++export interface ObservationMetadata {+ frame_number: number;+ [key: string]: any; // Allow additional metadata+}++export abstract class BaseOverlayRenderer {+ protected offscreenCanvas: OffscreenCanvas;+ protected ctx: OffscreenCanvasRenderingContext2D;+ protected modelInfo: ModelInfo | null = null;++ // Common style constants+ protected readonly INFO_BG = 'rgba(0, 0, 0, 0.7)';+ protected readonly TEXT_COLOR = '#ccc';+ protected readonly TEXT_STROKE = '#111';++ constructor() {+ this.offscreenCanvas = new OffscreenCanvas(1, 1);+ const ctx = this.offscreenCanvas.getContext('2d', {+ alpha: true,+ desynchronized: true,+ });++ if (!ctx) {+ throw new Error('Failed to get 2D context for overlay renderer');+ }++ this.ctx = ctx;+ }++ /**+ * Set the model info for this renderer+ */+ public setModelInfo(modelInfo: ModelInfo): void {+ this.modelInfo = modelInfo;+ }++ /**+ * Main composite method - to be implemented by specific renderers+ */+ public abstract compositeFrame(+ sourceBitmap: ImageBitmap,+ observation: any | null,+ ): Promise<ImageBitmap>;++ /**+ * Resize canvas if needed and draw source image+ */+ protected prepareCanvas(sourceBitmap: ImageBitmap): void {+ const { width, height } = sourceBitmap;++ if (this.offscreenCanvas.width !== width || this.offscreenCanvas.height !== height) {+ this.offscreenCanvas.width = width;+ this.offscreenCanvas.height = height;+ }++ this.ctx.clearRect(0, 0, width, height);+ this.ctx.drawImage(sourceBitmap, 0, 0);+ }++ /**+ * Generic method to draw points+ */+ protected drawPoints(+ points: Point2D[],+ style: DrawStyle+ ): void {+ for (const point of points) {+ // Skip invalid points+ if (!this.isValidPoint(point)) continue;++ // Optional visibility threshold+ if (point.visibility !== undefined && point.visibility < 0.5) continue;++ // Draw filled circle+ this.ctx.fillStyle = style.pointColor;+ this.ctx.beginPath();+ this.ctx.arc(point.x, point.y, style.pointRadius, 0, Math.PI * 2);+ this.ctx.fill();++ // Draw stroke+ this.ctx.strokeStyle = style.pointStroke;+ this.ctx.lineWidth = 2;+ this.ctx.stroke();++ // Draw label if enabled+ if (style.showLabels && point.id !== undefined) {+ this.drawText(+ point.id.toString(),+ point.x + style.pointRadius + 3,+ point.y - style.pointRadius - 3,+ style.labelFontSize,+ style.labelColor,+ style.labelStroke,+ 2+ );+ }+ }+ }++ /**+ * Generic method to draw segments/connections between points+ */+ protected drawSegments(+ points: Map<string | number, Point2D>,+ segments: Record<string, Segment>,+ style: DrawStyle+ ): void {+ for (const [_, segment] of Object.entries(segments)) {+ const proximalPoint = points.get(segment.proximal);+ const distalPoint = points.get(segment.distal);++ if (!proximalPoint || !distalPoint) continue;+ if (!this.isValidPoint(proximalPoint) || !this.isValidPoint(distalPoint)) continue;++ // Draw line+ this.ctx.strokeStyle = style.lineColor;+ this.ctx.lineWidth = style.lineWidth;+ this.ctx.beginPath();+ this.ctx.moveTo(proximalPoint.x, proximalPoint.y);+ this.ctx.lineTo(distalPoint.x, distalPoint.y);+ this.ctx.stroke();+ }+ }++ /**+ * Generic method to draw a polygon (like ArUco markers)+ */+ protected drawPolygon(+ corners: [number, number][],+ style: DrawStyle,+ fillPoints: boolean = true,+ label?: string+ ): void {+ if (corners.length < 3) return;++ // Draw outline+ this.ctx.strokeStyle = style.lineColor;+ this.ctx.lineWidth = style.lineWidth;+ this.ctx.beginPath();+ this.ctx.moveTo(corners[0][0], corners[0][1]);+ for (let i = 1; i < corners.length; i++) {+ this.ctx.lineTo(corners[i][0], corners[i][1]);+ }+ this.ctx.closePath();+ this.ctx.stroke();++ // Draw corner points if requested+ if (fillPoints) {+ this.ctx.fillStyle = style.pointColor;+ for (const corner of corners) {+ this.ctx.beginPath();+ this.ctx.arc(corner[0], corner[1], style.pointRadius, 0, Math.PI * 2);+ this.ctx.fill();+ }+ }++ // Draw label at center if provided+ if (label) {+ const centerX = corners.reduce((sum, c) => sum + c[0], 0) / corners.length;+ const centerY = corners.reduce((sum, c) => sum + c[1], 0) / corners.length;++ this.drawText(+ label,+ centerX,+ centerY,+ style.labelFontSize * 1.2,+ this.TEXT_COLOR,+ style.pointColor,+ 3,+ 'bold'+ );+ }+ }++ /**+ * Draw text with stroke (outline)+ */+ protected drawText(+ text: string,+ x: number,+ y: number,+ fontSize: number,+ fillColor: string,+ strokeColor: string,+ strokeWidth: number,+ fontWeight: string = 'normal'+ ): void {+ this.ctx.font = `${fontWeight} ${fontSize}px Arial, sans-serif`;+ this.ctx.textBaseline = 'middle';++ // Draw stroke (outline)+ this.ctx.strokeStyle = strokeColor;+ this.ctx.lineWidth = strokeWidth + 2;+ this.ctx.strokeText(text, x, y);++ // Draw fill+ this.ctx.fillStyle = fillColor;+ this.ctx.fillText(text, x, y);+ }++ /**+ * Draw info overlay with metadata+ */+ protected drawInfoOverlay(+ metadata: ObservationMetadata,+ additionalInfo?: string[]+ ): void {+ const lines: string[] = [+ `Frame: ${metadata.frame_number}`,+ ...(additionalInfo || [])+ ];++ // Calculate background size+ const lineHeight = 25;+ const bgHeight = lines.length * lineHeight + 10;+ const bgWidth = 500;++ // Draw background+ this.ctx.fillStyle = this.INFO_BG;+ this.ctx.fillRect(5, 5, bgWidth, bgHeight);++ // Draw lines+ let y = 25;+ for (const line of lines) {+ this.drawText(line, 10, y, 14, this.TEXT_COLOR, this.TEXT_STROKE, 2);+ y += lineHeight;+ }+ }++ /**+ * Check if a point is valid (not NaN or undefined)+ */+ protected isValidPoint(point: Point2D): boolean {+ return (+ point &&+ typeof point.x === 'number' &&+ typeof point.y === 'number' &&+ !isNaN(point.x) &&+ !isNaN(point.y) &&+ isFinite(point.x) &&+ isFinite(point.y)+ );+ }++ /**+ * Create final bitmap from canvas+ */+ protected async createBitmap(sourceBitmap: ImageBitmap): Promise<ImageBitmap> {+ const compositeBitmap = await createImageBitmap(this.offscreenCanvas);+ sourceBitmap.close();+ return compositeBitmap;+ }++ public destroy(): void {+ // Cleanup if needed+ }+}\ No newline at end of filediff --git a/freemocap-ui/src/services/server/server-helpers/image-overlay/mediapipe-overlay-renderer.ts b/freemocap-ui/src/services/server/server-helpers/image-overlay/mediapipe-overlay-renderer.tsnew file mode 100644index 00000000..5027cf9b--- /dev/null+++ b/freemocap-ui/src/services/server/server-helpers/image-overlay/mediapipe-overlay-renderer.ts@@ -0,0 +1,360 @@+// mediapipe-overlay-renderer.ts++import {+ BaseOverlayRenderer,+ DrawStyle,+ Point2D+} from "@/services/server/server-helpers/image-overlay/image-overlay-system";++export interface MediapipePoint {+ name: string;+ x: number;+ y: number;+ z?: number;+ visibility?: number;+}++export interface MediapipeObservation {+ message_type: 'mediapipe_overlay';+ camera_id: string;+ frame_number: number;+ body_points?: MediapipePoint[];+ right_hand_points?: MediapipePoint[];+ left_hand_points?: MediapipePoint[];+ face_points?: MediapipePoint[];+ metadata: {+ image_width: number;+ image_height: number;+ n_body_detected: number;+ n_right_hand_detected: number;+ n_left_hand_detected: number;+ n_face_detected: number;+ };+}++export class MediapipeOverlayRenderer extends BaseOverlayRenderer {+ // Aspect-specific styles+ private readonly bodyStyle: DrawStyle = {+ pointColor: '#00FF00',+ pointStroke: '#008800',+ pointRadius: 4,+ lineColor: '#00FF00',+ lineWidth: 2,+ labelColor: '#00FF00',+ labelStroke: this.TEXT_STROKE,+ labelFontSize: 8,+ showLabels: false, // Too many points to label+ };++ private readonly rightHandStyle: DrawStyle = {+ pointColor: '#FF6400',+ pointStroke: '#AA4400',+ pointRadius: 3,+ lineColor: '#FF6400',+ lineWidth: 1.5,+ labelColor: '#FF6400',+ labelStroke: this.TEXT_STROKE,+ labelFontSize: 8,+ showLabels: false,+ };++ private readonly leftHandStyle: DrawStyle = {+ pointColor: '#00AAFF',+ pointStroke: '#0066AA',+ pointRadius: 3,+ lineColor: '#00AAFF',+ lineWidth: 1.5,+ labelColor: '#00AAFF',+ labelStroke: this.TEXT_STROKE,+ labelFontSize: 8,+ showLabels: false,+ };++ private readonly faceStyle: DrawStyle = {+ pointColor: '#FFD700',+ pointStroke: '#AA9900',+ pointRadius: 1,+ lineColor: '#FFD700',+ lineWidth: 1,+ labelColor: '#FFD700',+ labelStroke: this.TEXT_STROKE,+ labelFontSize: 6,+ showLabels: false,+ };++ /**+ * Composite mediapipe overlay onto frame+ */+ public async compositeFrame(+ sourceBitmap: ImageBitmap,+ observation: MediapipeObservation | null,+ ): Promise<ImageBitmap> {+ this.prepareCanvas(sourceBitmap);++ if (observation) {+ this.drawMediapipeOverlay(observation);+ }++ return this.createBitmap(sourceBitmap);+ }++ private drawMediapipeOverlay(observation: MediapipeObservation): void {+ this.ctx.save();++ // Draw each aspect in order (face behind, body in middle, hands on top)+ if (observation.face_points) {+ this.drawFaceAspect(observation.face_points);+ }++ if (observation.body_points) {+ this.drawBodyAspect(observation.body_points);+ }++ if (observation.right_hand_points) {+ this.drawHandAspect(observation.right_hand_points, 'right_hand', this.rightHandStyle);+ }++ if (observation.left_hand_points) {+ this.drawHandAspect(observation.left_hand_points, 'left_hand', this.leftHandStyle);+ }++ // Draw info overlay+ this.drawMediapipeInfo(observation);++ this.ctx.restore();+ }++ private drawBodyAspect(points: MediapipePoint[]): void {+ if (points.length === 0) return;++ // Create point map for segment drawing+ const pointMap = new Map<string | number, Point2D>();+ const point2DArray: Point2D[] = [];++ for (const point of points) {+ const point2D: Point2D = {+ x: point.x,+ y: point.y,+ id: point.name,+ visibility: point.visibility,+ };+ pointMap.set(point.name, point2D);+ point2DArray.push(point2D);+ }++ // Draw segments first (behind points)+ if (this.modelInfo?.aspects['body']?.segment_connections) {+ this.drawSegments(pointMap, this.modelInfo.aspects['body'].segment_connections, {+ ...this.bodyStyle,+ lineColor: 'rgba(0, 255, 0, 0.6)', // Semi-transparent+ });+ }++ // Draw points on top+ this.drawPoints(point2DArray, this.bodyStyle);++ // Highlight key points with labels+ this.drawKeyBodyPoints(pointMap);+ }++ private drawKeyBodyPoints(pointMap: Map<string | number, Point2D>): void {+ // Label only important landmarks for clarity+ const keyPoints = ['nose', 'left_shoulder', 'right_shoulder', 'left_hip', 'right_hip'];++ for (const key of keyPoints) {+ const point = pointMap.get(key);+ if (point && this.isValidPoint(point)) {+ this.drawText(+ key.replace('_', ' '),+ point.x + 5,+ point.y - 5,+ 8,+ this.bodyStyle.labelColor,+ this.bodyStyle.labelStroke,+ 1+ );+ }+ }+ }++ private drawHandAspect(+ points: MediapipePoint[],+ aspectName: string,+ style: DrawStyle+ ): void {+ if (points.length === 0) return;++ const pointMap = new Map<string | number, Point2D>();+ const point2DArray: Point2D[] = [];++ for (const point of points) {+ const point2D: Point2D = {+ x: point.x,+ y: point.y,+ id: point.name,+ visibility: point.visibility,+ };+ pointMap.set(point.name, point2D);+ point2DArray.push(point2D);+ }++ // Draw hand skeleton connections+ this.drawHandConnections(pointMap, style);++ // Draw points+ this.drawPoints(point2DArray, style);+ }++ private drawHandConnections(+ pointMap: Map<string | number, Point2D>,+ style: DrawStyle+ ): void {+ // Define hand connections (MediaPipe hand landmark connections)+ const handConnections = [+ // Thumb+ ['wrist', 'thumb_cmc'],+ ['thumb_cmc', 'thumb_mcp'],+ ['thumb_mcp', 'thumb_ip'],+ ['thumb_ip', 'thumb_tip'],+ // Index finger+ ['wrist', 'index_finger_mcp'],+ ['index_finger_mcp', 'index_finger_pip'],+ ['index_finger_pip', 'index_finger_dip'],+ ['index_finger_dip', 'index_finger_tip'],+ // Middle finger+ ['wrist', 'middle_finger_mcp'],+ ['middle_finger_mcp', 'middle_finger_pip'],+ ['middle_finger_pip', 'middle_finger_dip'],+ ['middle_finger_dip', 'middle_finger_tip'],+ // Ring finger+ ['wrist', 'ring_finger_mcp'],+ ['ring_finger_mcp', 'ring_finger_pip'],+ ['ring_finger_pip', 'ring_finger_dip'],+ ['ring_finger_dip', 'ring_finger_tip'],+ // Pinky+ ['wrist', 'pinky_mcp'],+ ['pinky_mcp', 'pinky_pip'],+ ['pinky_pip', 'pinky_dip'],+ ['pinky_dip', 'pinky_tip'],+ // Palm connections+ ['index_finger_mcp', 'middle_finger_mcp'],+ ['middle_finger_mcp', 'ring_finger_mcp'],+ ['ring_finger_mcp', 'pinky_mcp'],+ ];++ for (const [start, end] of handConnections) {+ const startPoint = pointMap.get(start);+ const endPoint = pointMap.get(end);++ if (startPoint && endPoint && this.isValidPoint(startPoint) && this.isValidPoint(endPoint)) {+ this.ctx.strokeStyle = style.lineColor;+ this.ctx.lineWidth = style.lineWidth;+ this.ctx.beginPath();+ this.ctx.moveTo(startPoint.x, startPoint.y);+ this.ctx.lineTo(endPoint.x, endPoint.y);+ this.ctx.stroke();+ }+ }+ }++ private drawFaceAspect(points: MediapipePoint[]): void {+ if (points.length === 0) return;++ // For face, we just draw the points as a mesh without connections+ // (too many points to draw connections clearly)+ const point2DArray: Point2D[] = points.map(point => ({+ x: point.x,+ y: point.y,+ id: point.name,+ visibility: point.visibility,+ }));++ this.drawPoints(point2DArray, this.faceStyle);++ // Optionally draw face contour lines if we have the indices+ if (this.modelInfo?.aspects['face']) {+ this.drawFaceContour(points);+ }+ }++ private drawFaceContour(points: MediapipePoint[]): void {+ // Draw simplified face contour for better visibility+ // This would use the face contour indices from the model info+ // For now, just highlight key face points+ const keyFacePoints = points.filter(p =>+ p.name.includes('eye') ||+ p.name.includes('mouth') ||+ p.name.includes('nose')+ );++ const highlightStyle = {+ ...this.faceStyle,+ pointRadius: 2,+ pointColor: '#FFFF00',+ };++ this.drawPoints(+ keyFacePoints.map(p => ({+ x: p.x,+ y: p.y,+ id: p.name,+ visibility: p.visibility,+ })),+ highlightStyle+ );+ }++ private drawMediapipeInfo(observation: MediapipeObservation): void {+ const { metadata, frame_number } = observation;++ // Build detection status+ const detections: string[] = [];+ if (metadata.n_body_detected > 0) detections.push('Body');+ if (metadata.n_right_hand_detected > 0) detections.push('R-Hand');+ if (metadata.n_left_hand_detected > 0) detections.push('L-Hand');+ if (metadata.n_face_detected > 0) detections.push('Face');++ const statusText = detections.length > 0+ ? `โ Detected: ${detections.join(', ')}`+ : 'โ No detection';++ const statusColor = detections.length > 0 ? '#00FF00' : '#FF4444';++ // Draw info background+ this.ctx.fillStyle = this.INFO_BG;+ this.ctx.fillRect(5, 5, 500, 85);++ // Draw frame info+ this.drawText(+ `Frame: ${frame_number}`,+ 10,+ 25,+ 14,+ this.TEXT_COLOR,+ this.TEXT_STROKE,+ 2+ );++ // Draw detection counts+ this.drawText(+ `Body: ${metadata.n_body_detected} | Hands: ${metadata.n_right_hand_detected + metadata.n_left_hand_detected} | Face: ${metadata.n_face_detected > 0 ? 'โ' : 'โ'}`,+ 10,+ 50,+ 14,+ this.TEXT_COLOR,+ this.TEXT_STROKE,+ 2+ );++ // Draw status+ this.drawText(+ statusText,+ 10,+ 75,+ 16,+ statusColor,+ this.TEXT_STROKE,+ 2+ );+ }+}diff --git a/freemocap-ui/src/services/server/server-helpers/image-overlay/mediapipe-types.ts b/freemocap-ui/src/services/server/server-helpers/image-overlay/mediapipe-types.tsnew file mode 100644index 00000000..2bf9d74e--- /dev/null+++ b/freemocap-ui/src/services/server/server-helpers/image-overlay/mediapipe-types.ts@@ -0,0 +1,41 @@+import z from "zod";++// Individual point schema+export const MediapipePointSchema = z.object({+ name: z.string(),+ x: z.number(),+ y: z.number(),+ z: z.number(),+ visibility: z.number(),+});++// Metadata schema+export const MediapipeMetadataSchema = z.object({+ n_body_detected: z.number(),+ n_right_hand_detected: z.number(),+ n_left_hand_detected: z.number(),+ n_face_detected: z.number(),+ image_width: z.number(),+ image_height: z.number(),+});++// Single camera observation schema+export const MediapipeOverlaySchema = z.object({+ message_type: z.literal("mediapipe_overlay"),+ camera_id: z.string(),+ frame_number: z.number(),+ body_points: z.array(MediapipePointSchema),+ right_hand_points: z.array(MediapipePointSchema),+ left_hand_points: z.array(MediapipePointSchema),+ face_points: z.array(MediapipePointSchema),+ metadata: MediapipeMetadataSchema,+});++// Multi-camera message schema (matches CharucoOverlayDataMessage structure)+export const MediapipeOverlayDataMessageSchema = z.record(z.string(), MediapipeOverlaySchema);++// Type exports+export type MediapipePoint = z.infer<typeof MediapipePointSchema>;+export type MediapipeMetadata = z.infer<typeof MediapipeMetadataSchema>;+export type MediapipeObservation = z.infer<typeof MediapipeOverlaySchema>;+export type MediapipeOverlayDataMessage = z.infer<typeof MediapipeOverlayDataMessageSchema>;diff --git a/freemocap-ui/src/services/server/server-helpers/image-overlay/overlay-renderer-factory.ts b/freemocap-ui/src/services/server/server-helpers/image-overlay/overlay-renderer-factory.tsnew file mode 100644index 00000000..d5a10c92--- /dev/null+++ b/freemocap-ui/src/services/server/server-helpers/image-overlay/overlay-renderer-factory.ts@@ -0,0 +1,148 @@+// overlay-renderer-factory.ts+import { CharucoOverlayRenderer } from './charuco-overlay-renderer';+import { MediapipeOverlayRenderer, MediapipeObservation } from './mediapipe-overlay-renderer';+import {BaseOverlayRenderer, ModelInfo} from "@/services/server/server-helpers/image-overlay/image-overlay-system";+import {CharucoObservation} from "@/services/server/server-helpers/image-overlay/charuco-types";++export type ObservationType = 'charuco_overlay' | 'mediapipe_overlay' | 'rtmpose_overlay';+++/**+ * Factory for creating appropriate overlay renderers based on observation type+ */+export class OverlayRendererFactory {+ private static rendererCache: Map<ObservationType, BaseOverlayRenderer> = new Map();+ private static modelInfoCache: Map<string, ModelInfo> = new Map();++ /**+ * Get or create a renderer for the specified observation type+ */+ public static getRenderer(type: ObservationType): BaseOverlayRenderer {+ // Check cache first+ let renderer = this.rendererCache.get(type);+ if (renderer) {+ return renderer;+ }++ // Create new renderer based on type+ switch (type) {+ case 'charuco_overlay':+ renderer = new CharucoOverlayRenderer();+ break;+ case 'mediapipe_overlay':+ renderer = new MediapipeOverlayRenderer();+ break;+ case 'rtmpose_overlay':+ // Future: implement RTMPoseOverlayRenderer+ throw new Error('RTMPose overlay not yet implemented');+ default:+ throw new Error(`Unknown observation type: ${type}`);+ }++ this.rendererCache.set(type, renderer);+ return renderer;+ }++ /**+ * Set model info for a specific tracker type+ */+ public static setModelInfo(trackerName: string, modelInfo: ModelInfo): void {+ this.modelInfoCache.set(trackerName, modelInfo);++ // Update all renderers that might use this model info+ for (const [type, renderer] of this.rendererCache) {+ if (this.shouldUseModelInfo(type, trackerName)) {+ renderer.setModelInfo(modelInfo);+ }+ }+ }++ /**+ * Clear all cached renderers+ */+ public static clearCache(): void {+ for (const renderer of this.rendererCache.values()) {+ renderer.destroy();+ }+ this.rendererCache.clear();+ this.modelInfoCache.clear();+ }++ /**+ * Determine if a renderer type should use a specific model info+ */+ private static shouldUseModelInfo(+ rendererType: ObservationType,+ trackerName: string+ ): boolean {+ const mapping: Record<ObservationType, string[]> = {+ 'charuco_overlay': ['CharucoTracker'],+ 'mediapipe_overlay': ['MediapipeHolisticTracker', 'MediapipeTracker'],+ 'rtmpose_overlay': ['RTMPoseTracker'],+ };++ return mapping[rendererType]?.includes(trackerName) || false;+ }+}++/**+ * Manager for handling overlay rendering across multiple cameras+ */+export class OverlayManager {+ private renderers: Map<string, BaseOverlayRenderer> = new Map();+ private observationTypeMap: Map<string, ObservationType> = new Map();++ /**+ * Process a frame with overlay+ */+ public async processFrame(+ cameraId: string,+ sourceBitmap: ImageBitmap,+ observation: CharucoObservation | MediapipeObservation | null+ ): Promise<ImageBitmap> {+ // Determine observation type+ const observationType = observation?.message_type as ObservationType;++ if (!observationType && !observation) {+ // No observation, just return the source bitmap+ return sourceBitmap;+ }++ // Get or create renderer for this camera+ let renderer = this.renderers.get(cameraId);+ const previousType = this.observationTypeMap.get(cameraId);++ // Check if we need a different renderer type+ if (!renderer || previousType !== observationType) {+ renderer = OverlayRendererFactory.getRenderer(observationType);+ this.renderers.set(cameraId, renderer);+ this.observationTypeMap.set(cameraId, observationType);+ }++ // Process the frame+ return renderer.compositeFrame(sourceBitmap, observation);+ }++ /**+ * Clear renderer for a specific camera+ */+ public clearCamera(cameraId: string): void {+ const renderer = this.renderers.get(cameraId);+ if (renderer) {+ renderer.destroy();+ this.renderers.delete(cameraId);+ this.observationTypeMap.delete(cameraId);+ }+ }++ /**+ * Clear all renderers+ */+ public clearAll(): void {+ for (const renderer of this.renderers.values()) {+ renderer.destroy();+ }+ this.renderers.clear();+ this.observationTypeMap.clear();+ }+}diff --git a/freemocap-ui/src/services/server/server-helpers/image-overlay/overlay-types.ts b/freemocap-ui/src/services/server/server-helpers/image-overlay/overlay-types.tsnew file mode 100644index 00000000..ea043a32--- /dev/null+++ b/freemocap-ui/src/services/server/server-helpers/image-overlay/overlay-types.ts@@ -0,0 +1,17 @@+import {CharucoObservation, CharucoOverlayDataMessage} from "@/services/server/server-helpers/image-overlay/charuco-types";+import {MediapipeObservation, MediapipeOverlayDataMessage} from "@/services/server/server-helpers/image-overlay/mediapipe-types";++// Union type for all observation data messages+export type ObservationDataMessage = CharucoOverlayDataMessage | MediapipeOverlayDataMessage;++// Union type for individual observations+export type Observation = CharucoObservation | MediapipeObservation;++// Type guard functions+export function isCharucoObservation(obs: Observation): obs is CharucoObservation {+ return obs.message_type === 'charuco_overlay';+}++export function isMediapipeObservation(obs: Observation): obs is MediapipeObservation {+ return obs.message_type === 'mediapipe_overlay';+}diff --git a/freemocap-ui/src/services/server/server-helpers/offscreen-renderer.worker.ts b/freemocap-ui/src/services/server/server-helpers/offscreen-renderer.worker.tsnew file mode 100644index 00000000..6b982fd4--- /dev/null+++ b/freemocap-ui/src/services/server/server-helpers/offscreen-renderer.worker.ts@@ -0,0 +1,89 @@+export const workerCode = `+let offscreenCanvas;+let ctx;+let pendingFrame = null;+let isRendering = false;+let stats = {+ framesRendered: 0,+ framesDropped: 0,+ totalRenderTime: 0+};++self.onmessage = (e) => {+ const { type } = e.data;++ switch (type) {+ case 'init':+ initCanvas(e.data);+ break;++ case 'frame':+ handleFrame(e.data);+ break;++ case 'getStats':+ self.postMessage({ type: 'stats', stats });+ break;+ }+};++function initCanvas(data) {+ offscreenCanvas = data.canvas;+ ctx = offscreenCanvas.getContext('bitmaprenderer');+ renderLoop();+ self.postMessage({ type: 'initialized' });+}++function handleFrame(data) {+ const bitmap = data.bitmap;++ if (!bitmap || bitmap.width <= 0 || bitmap.height <= 0) {+ console.error('Invalid bitmap dimensions:', bitmap?.width, bitmap?.height);+ if (bitmap) bitmap.close();+ return;+ }++ // Resize canvas if needed+ if (offscreenCanvas.width !== bitmap.width || offscreenCanvas.height !== bitmap.height) {+ offscreenCanvas.width = bitmap.width;+ offscreenCanvas.height = bitmap.height;+ }++ // Drop old frame if still pending+ if (pendingFrame) {+ pendingFrame.close();+ stats.framesDropped++;+ }++ pendingFrame = bitmap;+}++function renderLoop() {+ const startTime = performance.now();++ if (pendingFrame && !isRendering) {+ isRendering = true;++ // Render the frame+ ctx.transferFromImageBitmap(pendingFrame);+ pendingFrame.close();+ pendingFrame = null;++ // Update stats+ stats.framesRendered++;+ const renderTime = performance.now() - startTime;+ stats.totalRenderTime += renderTime;++ if (renderTime > 16.67) {+ console.warn(\`Slow frame: \${renderTime.toFixed(2)}ms\`);+ }++ isRendering = false;++ // Notify that frame is rendered+ self.postMessage({ type: 'frameRendered' });+ }++ requestAnimationFrame(renderLoop);+}+`;diff --git a/freemocap-ui/src/services/server/server-helpers/websocket-connection.ts b/freemocap-ui/src/services/server/server-helpers/websocket-connection.tsnew file mode 100644index 00000000..c2813d86--- /dev/null+++ b/freemocap-ui/src/services/server/server-helpers/websocket-connection.ts@@ -0,0 +1,197 @@+export interface WebSocketConfig {+ url: string;+ reconnectDelay?: number;+ maxReconnectAttempts?: number;+ heartbeatInterval?: number;+}++export enum ConnectionState {+ DISCONNECTED = 'DISCONNECTED',+ CONNECTING = 'CONNECTING',+ CONNECTED = 'CONNECTED',+ RECONNECTING = 'RECONNECTING',+ FAILED = 'FAILED'+}++type EventCallback = (...args: any[]) => void;++export class WebSocketConnection {+ private ws: WebSocket | null = null;+ private config: Required<WebSocketConfig>;+ private reconnectAttempts: number = 0;+ private reconnectTimer: number | null = null;+ private heartbeatTimer: number | null = null;+ private state: ConnectionState = ConnectionState.DISCONNECTED;++ // Simple event emitter implementation for browser+ private listeners: Map<string, Set<EventCallback>> = new Map();++ constructor(config: WebSocketConfig) {+ this.config = {+ reconnectDelay: config.reconnectDelay ?? 1000,+ maxReconnectAttempts: config.maxReconnectAttempts ?? 5,+ heartbeatInterval: config.heartbeatInterval ?? 30000,+ url: config.url+ };+ }++ public on(event: string, callback: EventCallback): void {+ if (!this.listeners.has(event)) {+ this.listeners.set(event, new Set());+ }+ this.listeners.get(event)!.add(callback);+ }++ public off(event: string, callback: EventCallback): void {+ this.listeners.get(event)?.delete(callback);+ }++ private emit(event: string, ...args: any[]): void {+ this.listeners.get(event)?.forEach(callback => {+ try {+ callback(...args);+ } catch (error) {+ console.error(`Error in event listener for ${event}:`, error);+ }+ });+ }++ public connect(): void {+ if (this.state === ConnectionState.CONNECTING || this.state === ConnectionState.CONNECTED) {+ return;+ }++ this.setState(ConnectionState.CONNECTING);++ try {+ console.log(`Connecting to WebSocket at ${this.config.url}`);+ this.ws = new WebSocket(this.config.url);+ this.ws.binaryType = 'arraybuffer';++ this.ws.onopen = this.handleOpen.bind(this);+ this.ws.onclose = this.handleClose.bind(this);+ this.ws.onerror = this.handleError.bind(this);+ this.ws.onmessage = this.handleMessage.bind(this);+ } catch (error) {+ this.handleError(error as Event);+ }+ }++ public disconnect(): void {+ this.clearTimers();+ this.reconnectAttempts = 0;++ if (this.ws) {+ // Remove handlers to avoid reconnection on close+ this.ws.onclose = null;+ this.ws.close();+ this.ws = null;+ }++ this.setState(ConnectionState.DISCONNECTED);+ }++ public send(data: string | object): boolean {+ if (!this.isConnected()) {+ console.warn('WebSocket not connected, queuing message');+ this.emit('send-failed', data);+ return false;+ }++ try {+ const payload = typeof data === 'string' ? data : JSON.stringify(data);+ this.ws!.send(payload);+ return true;+ } catch (error) {+ console.error('Failed to send WebSocket message:', error);+ this.emit('send-error', error);+ return false;+ }+ }++ public isConnected(): boolean {+ return this.ws?.readyState === WebSocket.OPEN;+ }++ public getState(): ConnectionState {+ return this.state;+ }++ private setState(state: ConnectionState): void {+ const previousState = this.state;+ this.state = state;+ this.emit('state-change', state, previousState);+ }++ private handleOpen(): void {+ console.log('WebSocket connected');+ this.reconnectAttempts = 0;+ this.setState(ConnectionState.CONNECTED);+ this.startHeartbeat();+ this.emit('open');+ }++ private handleClose(event: CloseEvent): void {+ console.log(`WebSocket closed: code=${event.code}, reason=${event.reason}`);+ this.clearTimers();++ const wasConnected = this.state === ConnectionState.CONNECTED;++ if (wasConnected && this.reconnectAttempts < this.config.maxReconnectAttempts) {+ this.scheduleReconnect();+ } else if (this.reconnectAttempts >= this.config.maxReconnectAttempts) {+ this.setState(ConnectionState.FAILED);+ this.emit('max-reconnect-attempts');+ } else {+ this.setState(ConnectionState.DISCONNECTED);+ }++ this.emit('close', event);+ }++ private handleError(error: Event): void {+ console.error('WebSocket error:', error);+ this.emit('error', error);+ }++ private handleMessage(event: MessageEvent): void {+ this.emit('message', event);+ }++ private scheduleReconnect(): void {+ if (this.reconnectTimer) return;++ this.setState(ConnectionState.RECONNECTING);+ const delay = Math.min(+ this.config.reconnectDelay * Math.pow(2, this.reconnectAttempts),+ 10000 // Max 10 seconds+ );++ console.log(`Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts + 1}/${this.config.maxReconnectAttempts})`);++ this.reconnectTimer = window.setTimeout(() => {+ this.reconnectTimer = null;+ this.reconnectAttempts++;+ this.connect();+ }, delay);+ }++ private startHeartbeat(): void {+ this.heartbeatTimer = window.setInterval(() => {+ if (this.isConnected()) {+ this.send({type: 'ping'});+ }+ }, this.config.heartbeatInterval);+ }++ private clearTimers(): void {+ if (this.reconnectTimer) {+ clearTimeout(this.reconnectTimer);+ this.reconnectTimer = null;+ }+ if (this.heartbeatTimer) {+ clearInterval(this.heartbeatTimer);+ this.heartbeatTimer = null;+ }+ }+}diff --git a/freemocap-ui/src/store/AppStateStore.ts b/freemocap-ui/src/store/AppStateStore.tsdeleted file mode 100644index f8fad22f..00000000--- a/freemocap-ui/src/store/AppStateStore.ts+++ /dev/null@@ -1,25 +0,0 @@-// skellycam-ui/src/store/AppStateStore.ts-import {configureStore} from "@reduxjs/toolkit"-import {recordingInfoSlice} from "./slices/recordingInfoSlice"-import {framerateTrackerSlice} from "./slices/framerateTrackerSlice"-import {logRecordsSlice} from "@/store/slices/logRecordsSlice";-import {type TypedUseSelectorHook, useDispatch, useSelector} from "react-redux";-import {camerasSlice} from "@/store/slices/cameras-slices/camerasSlice";-import {themeSlice} from "@/store/slices/themeSlice";-import {videoLoadingSlice} from "@/store/slices/videoLoadingSlice";--export const AppStateStore = configureStore({- reducer: {- cameras: camerasSlice.reducer,- logRecords: logRecordsSlice.reducer,- recordingStatus: recordingInfoSlice.reducer,- framerateTracker: framerateTrackerSlice.reducer,- videoLoading: videoLoadingSlice.reducer,- theme: themeSlice.reducer,- },-})--export type RootState = ReturnType<typeof AppStateStore.getState>-export type AppDispatch = typeof AppStateStore.dispatch-export const useAppDispatch = () => useDispatch<AppDispatch>()-export const useAppSelector: TypedUseSelectorHook<RootState> = useSelectordiff --git a/freemocap-ui/src/store/hooks.ts b/freemocap-ui/src/store/hooks.tsnew file mode 100644index 00000000..fd5b5512--- /dev/null+++ b/freemocap-ui/src/store/hooks.ts@@ -0,0 +1,5 @@+import {TypedUseSelectorHook, useDispatch, useSelector} from 'react-redux';+import type {AppDispatch, RootState} from './types';++export const useAppDispatch = (): AppDispatch => useDispatch<AppDispatch>();+export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;diff --git a/freemocap-ui/src/store/index.ts b/freemocap-ui/src/store/index.tsnew file mode 100644index 00000000..c1da4ad5--- /dev/null+++ b/freemocap-ui/src/store/index.ts@@ -0,0 +1,14 @@+export { store } from './store';+export type { RootState, AppDispatch, AppThunk } from './types';+export { useAppDispatch, useAppSelector } from './hooks';+++// Re-export all slice actions and selectors for a nice 'barrel' design pattern, which makes imports cleaner+export * from './slices/cameras';+export * from './slices/recording';+export * from './slices/framerate';+export * from './slices/log-records';+export * from './slices/theme';+export * from './slices/videos';+export * from './slices/pipeline';+export * from './slices/mocap';diff --git a/freemocap-ui/src/store/slices/calibration/calibration-slice.ts b/freemocap-ui/src/store/slices/calibration/calibration-slice.tsnew file mode 100644index 00000000..8fbe1c37--- /dev/null+++ b/freemocap-ui/src/store/slices/calibration/calibration-slice.ts@@ -0,0 +1,230 @@+// store/slices/calibration/calibration-slice.ts+import {createSelector, createSlice, PayloadAction} from '@reduxjs/toolkit';+import {RootState} from '../../types';+import {+ calibrateRecording,+ startCalibrationRecording,+ stopCalibrationRecording,+ updateCalibrationConfigOnServer,+} from "@/store/slices/calibration/calibration-thunks";++// ==================== Types ====================++export interface CalibrationConfig {+ liveTrackCharuco: boolean;+ charucoBoardXSquares: number;+ charucoBoardYSquares: number;+ charucoSquareLength: number;+ minSharedViewsPerCamera: number;+ autoStopOnMinViewCount: boolean;+}++export interface CalibrationDirectoryInfo {+ exists: boolean;+ canRecord: boolean; // true if directory doesn't exist OR exists but is empty+ canCalibrate: boolean; // true if has videos (either in synchronized_videos or root)+ cameraCalibrationTomlPath: string | null;+ hasSynchronizedVideos: boolean;+ hasVideos: boolean;+ errorMessage: string | null;+}++export interface CalibrationState {+ config: CalibrationConfig;+ isRecording: boolean;+ recordingProgress: number;+ isLoading: boolean;+ error: string | null;+ lastCalibrationRecordingPath: string | null; // Path from last recording+ manualCalibrationRecordingPath: string | null; // User-selected override path+ directoryInfo: CalibrationDirectoryInfo | null; // Info about the current calibration directory+}++// ==================== Initial State ====================++const initialState: CalibrationState = {+ config: {+ liveTrackCharuco: true,+ charucoBoardXSquares: 5,+ charucoBoardYSquares: 3,+ charucoSquareLength: 1,+ minSharedViewsPerCamera: 200,+ autoStopOnMinViewCount: true,+ },+ isRecording: false,+ recordingProgress: 0,+ isLoading: false,+ error: null,+ lastCalibrationRecordingPath: null,+ manualCalibrationRecordingPath: null,+ directoryInfo: null,+};++// ==================== Slice ====================++export const calibrationSlice = createSlice({+ name: 'calibration',+ initialState,+ reducers: {+ calibrationConfigUpdated: (state, action: PayloadAction<Partial<CalibrationConfig>>) => {+ state.config = { ...state.config, ...action.payload };+ },++ calibrationProgressUpdated: (state, action: PayloadAction<number>) => {+ state.recordingProgress = action.payload;+ },++ calibrationErrorCleared: (state) => {+ state.error = null;+ },++ // New action to set manual path+ manualCalibrationRecordingPathChanged: (state, action: PayloadAction<string>) => {+ state.manualCalibrationRecordingPath = action.payload;+ },++ // New action to clear manual path (revert to default)+ manualCalibrationRecordingPathCleared: (state) => {+ state.manualCalibrationRecordingPath = null;+ },++ // New action to update directory info+ calibrationDirectoryInfoUpdated: (state, action: PayloadAction<CalibrationDirectoryInfo>) => {+ state.directoryInfo = action.payload;+ },++ resetCalibrationState: () => initialState,+ },++ extraReducers: (builder) => {+ // Start Recording+ builder+ .addCase(startCalibrationRecording.pending, (state) => {+ state.isLoading = true;+ state.error = null;+ })+ .addCase(startCalibrationRecording.fulfilled, (state, action) => {+ state.isLoading = false;+ state.isRecording = true;+ state.recordingProgress = 0;+ // Store the path returned from the server+ if (action.payload.calibrationRecordingPath) {+ state.lastCalibrationRecordingPath = action.payload.calibrationRecordingPath;+ }+ })+ .addCase(startCalibrationRecording.rejected, (state, action) => {+ state.isLoading = false;+ state.error = action.payload || 'Failed to start recording';+ });++ // Stop Recording+ builder+ .addCase(stopCalibrationRecording.pending, (state) => {+ state.isLoading = true;+ state.error = null;+ })+ .addCase(stopCalibrationRecording.fulfilled, (state) => {+ state.isLoading = false;+ state.isRecording = false;+ state.recordingProgress = 0;+ })+ .addCase(stopCalibrationRecording.rejected, (state, action) => {+ state.isLoading = false;+ state.error = action.payload || 'Failed to stop recording';+ });++ // Calibrate Recording+ builder+ .addCase(calibrateRecording.pending, (state) => {+ state.isLoading = true;+ state.error = null;+ })+ .addCase(calibrateRecording.fulfilled, (state) => {+ state.isLoading = false;+ })+ .addCase(calibrateRecording.rejected, (state, action) => {+ state.isLoading = false;+ state.error = action.payload || 'Failed to calibrate recording';+ });++ // Update Config on Server+ builder+ .addCase(updateCalibrationConfigOnServer.rejected, (state, action) => {+ state.error = action.payload || 'Failed to sync config to server';+ });+ },+});++// ==================== Selectors ====================++export const selectCalibration = (state: RootState) => state.calibration;+export const selectCalibrationConfig = (state: RootState) => state.calibration.config;+export const selectCalibrationIsLoading = (state: RootState) => state.calibration.isLoading;+export const selectCalibrationIsRecording = (state: RootState) => state.calibration.isRecording;+export const selectCalibrationProgress = (state: RootState) => state.calibration.recordingProgress;+export const selectCalibrationError = (state: RootState) => state.calibration.error;+export const selectCalibrationDirectoryInfo = (state: RootState) => state.calibration.directoryInfo;++export const selectCalibrationRecordingPath = createSelector(+ [+ (state: RootState) => state.calibration.manualCalibrationRecordingPath,+ (state: RootState) => state.calibration.lastCalibrationRecordingPath,+ (state: RootState) => state.recording.computed,+ ],+ (manualPath, lastPath, recordingComputed) => {+ if (manualPath) return manualPath;+ if (lastPath) return lastPath;++ // Build calibration path from recording computed values+ const calibrationFolderName = `${recordingComputed.recordingName}_calibration`;+ return `${recordingComputed.fullRecordingPath}/${calibrationFolderName}`;+ }+);++// Selector to check if using manual path+export const selectIsUsingManualCalibrationPath = createSelector(+ [(state: RootState) => state.calibration.manualCalibrationRecordingPath],+ (manualPath) => manualPath !== null+);++export const selectCanStartCalibrationRecording = createSelector(+ [+ selectCalibrationIsRecording,+ selectCalibrationIsLoading,+ selectCalibrationRecordingPath,+ selectCalibrationDirectoryInfo+ ],+ (isRecording, isLoading, recordingPath, directoryInfo) => {+ // Can start if: not recording, not loading, have a path, and directory can be recorded to+ return !isRecording && !isLoading && !!recordingPath && (directoryInfo?.canRecord ?? true);+ }+);++export const selectCanCalibrate = createSelector(+ [+ selectCalibrationRecordingPath,+ selectCalibrationIsLoading,+ selectCalibrationIsRecording,+ selectCalibrationDirectoryInfo+ ],+ (calibrationPath, isLoading, isRecording, directoryInfo) => {+ // Can calibrate if: have path, not loading, not recording, and directory has videos+ return !!calibrationPath && !isLoading && !isRecording && (directoryInfo?.canCalibrate ?? false);+ }+);++// ==================== Actions Export ====================++export const {+ calibrationConfigUpdated,+ calibrationProgressUpdated,+ calibrationErrorCleared,+ manualCalibrationRecordingPathChanged,+ manualCalibrationRecordingPathCleared,+ calibrationDirectoryInfoUpdated,+ resetCalibrationState+} = calibrationSlice.actions;++// ==================== Reducer Export ====================++export default calibrationSlice.reducer;diff --git a/freemocap-ui/src/store/slices/calibration/calibration-thunks.ts b/freemocap-ui/src/store/slices/calibration/calibration-thunks.tsnew file mode 100644index 00000000..ea23bdc4--- /dev/null+++ b/freemocap-ui/src/store/slices/calibration/calibration-thunks.ts@@ -0,0 +1,223 @@+import {createAsyncThunk} from "@reduxjs/toolkit";+import {RootState} from "@/store";+import {serverUrls} from "@/hooks/server-urls";+import {selectCalibrationRecordingPath} from "./calibration-slice";++// Helper function to extract detailed error info from failed responses+async function getDetailedErrorMessage(response: Response): Promise<string> {+ let errorDetails: unknown;++ try {+ // Try to parse JSON error response+ errorDetails = await response.json();+ console.error('โ Server returned validation/error details:', errorDetails);+ } catch {+ // If not JSON, try to get text+ try {+ errorDetails = await response.text();+ console.error('โ Server returned error text:', errorDetails);+ } catch {+ console.error('โ Could not read error response body');+ }+ }++ // Build comprehensive error message+ const baseError = `HTTP ${response.status}: ${response.statusText}`;++ if (errorDetails) {+ // Pretty print the error details+ const detailsStr = typeof errorDetails === 'string'+ ? errorDetails+ : JSON.stringify(errorDetails, null, 2);+ return `${baseError}\n\nValidation/Error Details:\n${detailsStr}`;+ }++ return baseError;+}++// Helper function to generate calibration recording name based on recording config+function generateCalibrationRecordingName(state: RootState): string {+ const recordingConfig = state.recording.config;+ const parts: string[] = [];++ // Add base name if configured+ if (recordingConfig.baseName && recordingConfig.baseName !== 'recording') {+ parts.push(recordingConfig.baseName);+ }++ const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);+ parts.push(timestamp);++ // Add recording tag if provided+ if (recordingConfig.recordingTag) {+ parts.push(recordingConfig.recordingTag);+ }++ parts.push('calibration');++ return parts.join('_');+}++export const startCalibrationRecording = createAsyncThunk<+ { success: boolean; message?: string; calibrationRecordingPath?: string },+ void,+ { state: RootState; rejectValue: string }+>(+ 'calibration/startRecording',+ async (_, { getState, rejectWithValue }) => {+ try {+ const state = getState();+ const calibrationTaskConfig = state.calibration.config;+ const calibrationRecordingDirectory = selectCalibrationRecordingPath(state);++ if (!calibrationRecordingDirectory) {+ return rejectWithValue('Recording directory is not set');+ }++ console.log('๐ฌ Starting calibration recording with:', {+ calibrationRecordingDirectory,+ calibrationTaskConfig,+ });++ const response = await fetch(serverUrls.endpoints.calibrationStartRecording, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ calibrationRecordingDirectory,+ calibrationTaskConfig,+ }),+ });++ if (!response.ok) {+ const errorMessage = await getDetailedErrorMessage(response);+ return rejectWithValue(errorMessage);+ }++ const result = await response.json();+ console.log('โ Started calibration recording:', result);+ return result;+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';+ console.error('โ Failed to start calibration recording:', errorMessage);+ return rejectWithValue(errorMessage);+ }+ }+);++export const stopCalibrationRecording = createAsyncThunk<+ { success: boolean },+ void,+ { state: RootState; rejectValue: string }+>(+ 'calibration/stopRecording',+ async (_, { getState, rejectWithValue }) => {+ try {+ const state = getState();+ const calibrationTaskConfig = state.calibration.config;+++ console.log(`๐ฌ Stoping calibration recording and starting calibration with: ${JSON.stringify(calibrationTaskConfig, null, 2)}`);+++ const response = await fetch(serverUrls.endpoints.calibrationStopRecording, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({calibrationTaskConfig}),+ });++ if (!response.ok) {+ const errorMessage = await getDetailedErrorMessage(response);+ return rejectWithValue(errorMessage);+ }++ const result = await response.json();+ console.log('โ Stopped calibration recording:', result);+ return result;+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';+ console.error('โ Failed to stop calibration recording:', errorMessage);+ return rejectWithValue(errorMessage);+ }+ }+);++export const calibrateRecording = createAsyncThunk<+ { success: boolean; message?: string; results?: unknown },+ void,+ { state: RootState; rejectValue: string }+>(+ 'calibration/calibrateRecording',+ async (_, { getState, rejectWithValue }) => {+ try {+ const state = getState();+ const calibrationTaskConfig = state.calibration.config;+ const calibrationRecordingDirectory = selectCalibrationRecordingPath(state);++ if (!calibrationRecordingDirectory) {+ return rejectWithValue('No calibration recording path available. Please set a recording directory or record a calibration first.');+ }++ console.log('๐ง Calibrating recording:', {+ calibrationRecordingDirectory,+ calibrationTaskConfig,+ });++ const response = await fetch(serverUrls.endpoints.calibrateRecording, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ calibrationRecordingDirectory,+ calibrationTaskConfig,+ }),+ });++ if (!response.ok) {+ const errorMessage = await getDetailedErrorMessage(response);+ return rejectWithValue(errorMessage);+ }++ const result = await response.json();+ console.log('โ Calibration completed:', result);+ return result;+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';+ console.error('โ Failed to calibrate recording:', errorMessage);+ return rejectWithValue(errorMessage);+ }+ }+);++export const updateCalibrationConfigOnServer = createAsyncThunk<+ { success: boolean; message?: string },+ void,+ { state: RootState; rejectValue: string }+>(+ 'calibration/updateConfig',+ async (_, { getState, rejectWithValue }) => {+ try {+ const state = getState();+ const config = state.calibration.config;++ console.log('โ๏ธ Updating calibration config on server:', config);++ const response = await fetch(serverUrls.endpoints.updateCalibrationConfig, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ config }),+ });++ if (!response.ok) {+ const errorMessage = await getDetailedErrorMessage(response);+ return rejectWithValue(errorMessage);+ }++ const result = await response.json();+ console.log('โ Config updated on server:', result);+ return result;+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';+ console.error('โ Failed to update config on server:', errorMessage);+ return rejectWithValue(errorMessage);+ }+ }+);diff --git a/freemocap-ui/src/store/slices/calibration/index.ts b/freemocap-ui/src/store/slices/calibration/index.tsnew file mode 100644index 00000000..b50cd008--- /dev/null+++ b/freemocap-ui/src/store/slices/calibration/index.ts@@ -0,0 +1,3 @@++export * from './calibration-slice';+export * from './calibration-thunks';diff --git a/freemocap-ui/src/store/slices/cameras-slices/camera-types.ts b/freemocap-ui/src/store/slices/cameras-slices/camera-types.tsdeleted file mode 100644index 4ec32875..00000000--- a/freemocap-ui/src/store/slices/cameras-slices/camera-types.ts+++ /dev/null@@ -1,96 +0,0 @@-import {z} from 'zod';--// Define string literals as const for better type safety-export const PixelFormats = ['RGB', 'BGR', 'GRAY'];-export const ExposureModes = ['MANUAL', 'AUTO', 'RECOMMEND'];-export const CameraStatus = ['CONNECTED', 'AVAILABLE', 'UNAVAILABLE', 'IN_USE', 'ERROR'];-export const RotationOptions = [-1, 0, 1, 2]; // NO_ROTATION, cv2.CLOCKWISE_90, cv2.ROTATE_180, cv2.COUNTERCLOCKWISE_90-export const RotationLabels = ['None', '90ยฐ', '180ยฐ', '270ยฐ']; // Human-readable labels-export const FourccOptions = ['MJPG', 'X264', 'YUYV', 'H264'];-export const ResolutionPresets = [- {width: 640, height: 480, label: "VGA (4:3)"},- {width: 1280, height: 720, label: "HD 720p (16:9)"},- {width: 1920, height: 1080, label: "Full HD 1080p(16:9)"}-];-export const CAMERA_DEFAULT_CONSTRAINTS = {- resolution: {- min: {width: 640, height: 480},- max: {width: 1920, height: 1080},- default: {width: 1280, height: 720},- presets: ResolutionPresets- },- exposure: {- min: -12,- max: -4,- default: -7,- step: 1- },- framerate: {- min: 1,- max: 60,- default: 30,- available: [15, 30, 60]- },- pixel_formats: PixelFormats,- exposure_modes: ExposureModes,- status_options: CameraStatus,- rotation_options: RotationOptions,- fourcc_options: FourccOptions-};--export interface CameraDevice {- index: number;- deviceId: string;- cameraId: string;- status: string;- groupId: string;- kind: string;- label: string;- selected: boolean;- constraints: typeof CAMERA_DEFAULT_CONSTRAINTS;- config: CameraConfig;-}---// Helper function-export const createDefaultCameraConfig = (index: number, label: string, id: string): CameraConfig => ({- camera_index: index,- camera_name: label || `Camera ${index}`,- camera_id: id,- use_this_camera: true,- resolution: CAMERA_DEFAULT_CONSTRAINTS.resolution.default,- color_channels: 3,- pixel_format: PixelFormats[0],- exposure_mode: ExposureModes[0], // 'MANUAL'- exposure: CAMERA_DEFAULT_CONSTRAINTS.exposure.default,- framerate: CAMERA_DEFAULT_CONSTRAINTS.framerate.default,- rotation: RotationOptions[0], // '-1' for NO_ROTATION- capture_fourcc: FourccOptions[0], // 'MJPG'- writer_fourcc: FourccOptions[1], // 'X264'-});--export const CameraConfigSchema = z.object({- camera_index: z.number(),- camera_id: z.string(),- camera_name: z.string(),- use_this_camera: z.boolean(),- resolution: z.object({- width: z.number().int(),- height: z.number().int()- }),- color_channels: z.number(),- pixel_format: z.string(),- exposure_mode: z.string(),- exposure: z.number(),- framerate: z.number(),- rotation: z.number(),- capture_fourcc: z.string(),- writer_fourcc: z.string(),-});--export const CameraConfigsSchema = z.record(z.string(), CameraConfigSchema);--export type CameraConfig = z.infer<typeof CameraConfigSchema>;-export type CameraConfigs = z.infer<typeof CameraConfigsSchema>;-export type ExposureMode = typeof ExposureModes[number];-diff --git a/freemocap-ui/src/store/slices/cameras-slices/camerasSlice.ts b/freemocap-ui/src/store/slices/cameras-slices/camerasSlice.tsdeleted file mode 100644index 8674d881..00000000--- a/freemocap-ui/src/store/slices/cameras-slices/camerasSlice.ts+++ /dev/null@@ -1,172 +0,0 @@-// skellycam-ui/src/store/slices/cameras-slices/camerasSlice.ts-import {createSelector, createSlice, PayloadAction} from '@reduxjs/toolkit'-import {RootState} from "@/store/AppStateStore";-import {CameraConfig, CameraDevice, createDefaultCameraConfig} from "@/store/slices/cameras-slices/camera-types";--export interface CamerasState {- cameras: Record<string, CameraDevice>;- isLoading: boolean;- error: string | null;-}--const initialState: CamerasState = {- cameras: {},- isLoading: false,- error: null-}--export const camerasSlice = createSlice({- name: 'cameras',- initialState,- reducers: {- setAvailableCameras: (state, action: PayloadAction<CameraDevice[]>) => {- action.payload.forEach(device => {- const cameraId = device.cameraId;- const existingCamera = state.cameras[cameraId];-- state.cameras[cameraId] = {- ...device,- selected: existingCamera ? existingCamera.selected : device.selected,- config: existingCamera?.config || device.config- };- });- },- setLoading: (state, action: PayloadAction<boolean>) => {- state.isLoading = action.payload;- },- setError: (state, action: PayloadAction<string | null>) => {- state.error = action.payload;- },- setCameraStatus: (state, action: PayloadAction<{cameraId: string, status: string}>) => {- const { cameraId, status } = action.payload;- if (state.cameras[cameraId]) {- state.cameras[cameraId].status = status;- }- },- toggleCameraSelection: (state, action: PayloadAction<string>) => {- const cameraId = action.payload;- if (state.cameras[cameraId]) {- const newSelected = !state.cameras[cameraId].selected;-- state.cameras[cameraId] = {- ...state.cameras[cameraId],- selected: newSelected,- config: {- ...state.cameras[cameraId].config,- use_this_camera: newSelected- }- };- }- },- updateCameraConfig: (state, action: PayloadAction<{- cameraId: string;- config: Partial<CameraConfig>;- }>) => {- const { cameraId, config } = action.payload;- if (state.cameras[cameraId]) {- state.cameras[cameraId] = {- ...state.cameras[cameraId],- config: {- ...state.cameras[cameraId].config,- ...config- }- };- }- },- updateCameraConfigs: (state, action: PayloadAction<Record<string, CameraConfig>>) => {- const configs = action.payload;- console.log(`Updating camera configs for Cameras: `, Object.keys(configs));- Object.keys(configs).forEach(cameraId => {- if (state.cameras[cameraId]) {- state.cameras[cameraId] = {- ...state.cameras[cameraId],- config: {- ...state.cameras[cameraId].config,- ...configs[cameraId]- }- };- } else {- // If camera doesn't exist, throw an error- throw new Error(`Camera with ID ${cameraId} does not exist in the state.`);- }- });- },--- copyConfigToAllCameras: (state, action: PayloadAction<string>) => {- const sourceCameraId = action.payload;- const sourceCamera = state.cameras[sourceCameraId];-- if (sourceCamera) {- const sourceConfig = sourceCamera.config;-- // Copy specific config properties we want to share- // (excluding camera-specific properties like camera_id, camera_name, etc.)- const configToCopy = {- resolution: sourceConfig.resolution,- color_channels: sourceConfig.color_channels,- pixel_format: sourceConfig.pixel_format,- exposure_mode: sourceConfig.exposure_mode,- exposure: sourceConfig.exposure,- framerate: sourceConfig.framerate,- rotation: sourceConfig.rotation,- capture_fourcc: sourceConfig.capture_fourcc,- writer_fourcc: sourceConfig.writer_fourcc,- };-- // Apply to all other cameras- Object.keys(state.cameras).forEach(cameraId => {- if (cameraId !== sourceCameraId) {- state.cameras[cameraId] = {- ...state.cameras[cameraId],- config: {- ...state.cameras[cameraId].config,- ...configToCopy- }- };- }- });- }- },-- },-});--export const selectAllCameras = (state: RootState) => state.cameras.cameras;--export const selectSelectedDevices = createSelector(- [selectAllCameras],- (cameras) => {- return Object.values(cameras).filter(camera => camera.selected);- }-);--export const selectCameraById = (cameraId: string) =>- (state: RootState) => state.cameras.cameras[cameraId];--export const selectConfigsForSelectedCameras = createSelector(- [selectSelectedDevices],- (selectedCameras) => {- const selectedConfigs: Record<string, CameraConfig> = {};- selectedCameras.forEach(camera => {- if (camera.config) {- selectedConfigs[camera.cameraId] = camera.config;- }- });- return selectedConfigs;- }-);--export const {- setAvailableCameras,- setLoading,- setCameraStatus,- toggleCameraSelection,- updateCameraConfig,- updateCameraConfigs,- copyConfigToAllCameras,- setError-} = camerasSlice.actions;--export default camerasSlice.reducer;-diff --git a/freemocap-ui/src/store/slices/cameras/cameras-selectors.ts b/freemocap-ui/src/store/slices/cameras/cameras-selectors.tsnew file mode 100644index 00000000..bab7b94c--- /dev/null+++ b/freemocap-ui/src/store/slices/cameras/cameras-selectors.ts@@ -0,0 +1,159 @@+// cameras-selectors.ts+import {createSelector} from '@reduxjs/toolkit';+import {RootState} from '../../types';+import {CameraConfig} from './cameras-types';++// ========== Basic Selectors ==========+export const selectCameras = (state: RootState) => state.cameras.cameras;+export const selectIsLoading = (state: RootState) => state.cameras.isLoading;+export const selectError = (state: RootState) => state.cameras.error;++// ========== Derived Selectors ==========+export const selectCameraById = createSelector(+ [selectCameras, (_: RootState, cameraId: string) => cameraId],+ (cameras, cameraId) => cameras.find(cam => cam.id === cameraId)+);++export const selectSelectedCameras = createSelector(+ [selectCameras],+ (cameras) => cameras.filter(cam => cam.selected)+);++export const selectConnectedCameras = createSelector(+ [selectCameras],+ (cameras) => cameras.filter(cam => cam.connectionStatus === 'connected')+);++// Get desired configs for selected cameras (for API calls)+export const selectSelectedCameraConfigs = createSelector(+ [selectSelectedCameras],+ (cameras): Record<string, CameraConfig> => {+ return cameras.reduce(+ (configs, camera) => ({+ ...configs,+ [camera.id]: camera.desiredConfig, // Use desired config+ }),+ {} as Record<string, CameraConfig>+ );+ }+);++++// ========== Mismatch Selectors ==========+export const selectCamerasWithConfigMismatch = createSelector(+ [selectCameras],+ (cameras) => cameras.filter(cam => cam.hasConfigMismatch)+);++export const selectHasAnyConfigMismatch = createSelector(+ [selectCamerasWithConfigMismatch],+ (camerasWithMismatch) => camerasWithMismatch.length > 0+);++export const selectCameraHasConfigMismatch = createSelector(+ [selectCameraById],+ (camera) => camera?.hasConfigMismatch ?? false+);++// Get config comparison for a specific camera+export const selectCameraConfigComparison = createSelector(+ [selectCameraById],+ (camera) => {+ if (!camera) return null;++ return {+ actual: camera.actualConfig,+ desired: camera.desiredConfig,+ hasMismatch: camera.hasConfigMismatch,+ differences: camera.hasConfigMismatch ?+ getConfigDifferences(camera.actualConfig, camera.desiredConfig) : []+ };+ }+);++// ========== Count Selectors ==========+export const selectCameraCount = createSelector(+ [selectCameras],+ (cameras) => cameras.length+);++export const selectHasConnectedCameras = createSelector(+ [selectConnectedCameras],+ (cameras) => cameras.length > 0+);++// ========== Helper Functions ==========+function getConfigDifferences(+ actual: CameraConfig,+ desired: CameraConfig+): Array<{ field: string; actual: any; desired: any }> {+ const differences: Array<{ field: string; actual: any; desired: any }> = [];++ // Compare each field+ if (actual.resolution.width !== desired.resolution.width) {+ differences.push({+ field: 'resolution.width',+ actual: actual.resolution.width,+ desired: desired.resolution.width+ });+ }+ if (actual.resolution.height !== desired.resolution.height) {+ differences.push({+ field: 'resolution.height',+ actual: actual.resolution.height,+ desired: desired.resolution.height+ });+ }+ if (actual.framerate !== desired.framerate) {+ differences.push({+ field: 'framerate',+ actual: actual.framerate,+ desired: desired.framerate+ });+ }+ if (actual.exposure_mode !== desired.exposure_mode) {+ differences.push({+ field: 'exposure_mode',+ actual: actual.exposure_mode,+ desired: desired.exposure_mode+ });+ }+ if (actual.exposure !== desired.exposure) {+ differences.push({+ field: 'exposure',+ actual: actual.exposure,+ desired: desired.exposure+ });+ }+ if (actual.rotation !== desired.rotation) {+ differences.push({+ field: 'rotation',+ actual: actual.rotation,+ desired: desired.rotation+ });+ }+ if (actual.pixel_format !== desired.pixel_format) {+ differences.push({+ field: 'pixel_format',+ actual: actual.pixel_format,+ desired: desired.pixel_format+ });+ }+ if (actual.capture_fourcc !== desired.capture_fourcc) {+ differences.push({+ field: 'capture_fourcc',+ actual: actual.capture_fourcc,+ desired: desired.capture_fourcc+ });+ }+ if (actual.writer_fourcc !== desired.writer_fourcc) {+ differences.push({+ field: 'writer_fourcc',+ actual: actual.writer_fourcc,+ desired: desired.writer_fourcc+ });+ }++ return differences;+}diff --git a/freemocap-ui/src/store/slices/cameras/cameras-slice.ts b/freemocap-ui/src/store/slices/cameras/cameras-slice.tsnew file mode 100644index 00000000..0b35f593--- /dev/null+++ b/freemocap-ui/src/store/slices/cameras/cameras-slice.ts@@ -0,0 +1,120 @@+// cameras-slice.ts+import {createSlice, PayloadAction} from '@reduxjs/toolkit';+import {areConfigsEqual, CameraConfig, CamerasState, extractConfigSettings,} from './cameras-types';+import {detectCameras,} from './cameras-thunks';+import {closePipeline, connectRealtimePipeline} from '../pipeline/pipeline-thunks';+++const initialState: CamerasState = {+ cameras: [],+ isLoading: false,+ error: null,+};++export const cameraSlice = createSlice({+ name: 'cameras',+ initialState,+ reducers: {+ // ========== Selection ==========+ cameraSelectionToggled: (state, action: PayloadAction<string>) => {+ const camera = state.cameras.find(cam => cam.id === action.payload);+ if (camera) {+ camera.selected = !camera.selected;+ camera.desiredConfig.use_this_camera = camera.selected;+ }+ },++ // ========== Configuration ==========+ // User updates desired config+ cameraDesiredConfigUpdated: (+ state,+ action: PayloadAction<{+ cameraId: string;+ config: Partial<CameraConfig>+ }>+ ) => {+ const camera = state.cameras.find(+ cam => cam.id === action.payload.cameraId+ );+ if (camera) {+ camera.desiredConfig = {...camera.desiredConfig, ...action.payload.config};+ // Check if there's now a mismatch+ camera.hasConfigMismatch = !areConfigsEqual(camera.actualConfig, camera.desiredConfig);+ }+ },++ configCopiedToAll: (state, action: PayloadAction<string>) => {+ const sourceCamera = state.cameras.find(cam => cam.id === action.payload);+ if (!sourceCamera) return;++ // Extract copyable settings (exclude identity fields)+ const settings = extractConfigSettings(sourceCamera.desiredConfig);++ state.cameras.forEach(camera => {+ if (camera.id !== action.payload) {+ camera.desiredConfig = {+ ...camera.desiredConfig,+ ...settings+ };+ camera.hasConfigMismatch = !areConfigsEqual(camera.actualConfig, camera.desiredConfig);+ }+ });+ },+ },++ extraReducers: (builder) => {+ builder+ // ========== Detect Cameras ==========+ .addCase(detectCameras.pending, (state) => {+ state.isLoading = true;+ state.error = null;+ })+ .addCase(detectCameras.fulfilled, (state, action) => {+ state.isLoading = false;+ state.cameras = action.payload;+ })+ .addCase(detectCameras.rejected, (state, action) => {+ state.isLoading = false;+ state.error = action.error.message || 'Failed to detect cameras';+ })++ // ========== Connect Pipeline ==========+ .addCase(connectRealtimePipeline.pending, (state) => {+ state.isLoading = true;+ state.error = null;+ })+ .addCase(connectRealtimePipeline.fulfilled, (state, action) => {+ state.isLoading = false;+ // Update camera actual configs from server response+ Object.entries(action.payload.camera_configs).forEach(+ ([cameraId, config]) => {+ const camera = state.cameras.find(cam => cam.id === cameraId);+ if (camera) {+ camera.actualConfig = config as CameraConfig;+ camera.hasConfigMismatch = !areConfigsEqual(camera.actualConfig, camera.desiredConfig);+ camera.connectionStatus = 'connected';+ }+ }+ );+ })+ .addCase(connectRealtimePipeline.rejected, (state, action) => {+ state.isLoading = false;+ state.error = action.error.message || 'Failed to connect to cameras';+ })++ // ========== Close Pipeline ==========+ .addCase(closePipeline.fulfilled, (state) => {+ state.cameras.forEach(camera => {+ camera.connectionStatus = 'available';+ camera.metrics = undefined;+ camera.hasConfigMismatch = false;+ });+ });+ },+});++export const {+ cameraSelectionToggled,+ cameraDesiredConfigUpdated,+ configCopiedToAll,+} = cameraSlice.actions;diff --git a/freemocap-ui/src/store/slices/cameras/cameras-thunks.ts b/freemocap-ui/src/store/slices/cameras/cameras-thunks.tsnew file mode 100644index 00000000..775fbcc3--- /dev/null+++ b/freemocap-ui/src/store/slices/cameras/cameras-thunks.ts@@ -0,0 +1,123 @@+// cameras-thunks.ts+import {createAsyncThunk} from '@reduxjs/toolkit';+import {RootState} from '../../types';+import {serverUrls} from '@/services';+import {+ Camera,+ CamerasConnectOrUpdateRequest,+ ConnectCamerasResponse,+ createDefaultCameraConfig,+ DetectCamerasRequest,+ DetectCamerasResponse,+} from './cameras-types';+import {selectSelectedCameraConfigs} from "@/store";++export const detectCameras = createAsyncThunk<+ Camera[],+ DetectCamerasRequest | undefined,+ { state: RootState }+>(+ 'cameras/detect',+ async (request = { filterVirtual: true }, { getState }) => {+ const state = getState();+ const existingCameras = state.cameras.cameras;++ const response = await fetch(serverUrls.endpoints.detectCameras, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(request),+ });++ if (!response.ok) {+ throw new Error(`Failed to detect cameras: ${response.statusText}`);+ }++ const data: DetectCamerasResponse = await response.json();++ return data.cameras.map((serverCamera): Camera => {+ const cameraId = serverCamera.index.toString();+ const existing = existingCameras.find(cam => cam.id === cameraId);++ const defaultConfig = createDefaultCameraConfig(+ cameraId,+ serverCamera.index,+ serverCamera.name,+ );++ return {+ id: cameraId,+ name: serverCamera.name,+ index: serverCamera.index,+ // If camera exists, preserve its configs, otherwise use defaults+ actualConfig: existing?.actualConfig || defaultConfig,+ desiredConfig: existing?.desiredConfig || { ...defaultConfig },+ hasConfigMismatch: existing?.hasConfigMismatch ?? false,+ connectionStatus: 'available',+ selected: existing?.selected ?? true,+ deviceInfo: {+ vendorId: serverCamera.vendor_id,+ productId: serverCamera.product_id,+ },+ metrics: existing?.metrics,+ };+ });+ }+);++export const camerasConnectOrUpdate = createAsyncThunk<+ ConnectCamerasResponse,+ void,+ { state: RootState }+>(+ 'cameras/connect',+ async (_, { getState }) => {+ const state = getState();+ const cameraConfigs = selectSelectedCameraConfigs(state);++ if (Object.keys(cameraConfigs).length === 0) {+ throw new Error('No cameras selected for connection');+ }++ const request: CamerasConnectOrUpdateRequest = { camera_configs: cameraConfigs };++ const response = await fetch(serverUrls.endpoints.camerasConnectOrUpdate, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(request),+ });++ if (!response.ok) {+ const error = await response.json();+ throw new Error(error.detail || 'Failed to connect to cameras');+ }++ return await response.json() as Promise<ConnectCamerasResponse>;+ }+);+++export const closeCameras = createAsyncThunk<void, void, { state: RootState }>(+ 'cameras/close',+ async () => {+ const response = await fetch(serverUrls.endpoints.closeAll, {+ method: 'DELETE',+ });++ if (!response.ok) {+ throw new Error(`Failed to close cameras: ${response.statusText}`);+ }+ }+);++export const pauseUnpauseCameras = createAsyncThunk<void, void, { state: RootState }>(+ 'cameras/pause',+ async () => {+ const response = await fetch(serverUrls.endpoints.pauseUnpauseCameras, {+ method: 'GET',+ });++ if (!response.ok) {+ throw new Error(`Failed to pause/unpause cameras: ${response.statusText}`);+ }+ }+);diff --git a/freemocap-ui/src/store/slices/cameras/cameras-types.ts b/freemocap-ui/src/store/slices/cameras/cameras-types.tsnew file mode 100644index 00000000..880d5e44--- /dev/null+++ b/freemocap-ui/src/store/slices/cameras/cameras-types.ts@@ -0,0 +1,175 @@+// cameras-types.ts+import {z} from 'zod';++// ==================== Constants ====================+export const PIXEL_FORMATS = ['RGB', 'BGR', 'GRAY'] as const;+export const EXPOSURE_MODES = ['MANUAL', 'AUTO', 'RECOMMEND'] as const;+export const CONNECTION_STATUS = ['disconnected', 'connecting', 'connected', 'error'] as const;+++export const ROTATION_DEGREE_LABELS: Record<RotationValue, string> = {+ [-1]: '0ยฐ',+ [0]: '90ยฐ',+ [1]: '180ยฐ',+ [2]: '270ยฐ',+};++export const ROTATION_OPTIONS = [-1, 0, 1, 2] as const;+export const FOURCC_OPTIONS = ['MJPG', 'X264', 'YUYV', 'H264'] as const;++export type PixelFormat = typeof PIXEL_FORMATS[number];+export type ExposureMode = typeof EXPOSURE_MODES[number];+export type ConnectionStatus = typeof CONNECTION_STATUS[number];+export type RotationValue = typeof ROTATION_OPTIONS[number];+export type FourccOption = typeof FOURCC_OPTIONS[number];++// Helper to get rotation label for UI+export const ROTATION_LABELS: Record<RotationValue, string> = {+ [-1]: 'No Rotation',+ [0]: '90ยฐ',+ [1]: '180ยฐ',+ [2]: '270ยฐ',+};++// ==================== Camera Configuration ====================+const CameraConfigSchema = z.object({+ // Identity+ camera_id: z.string(),+ camera_index: z.number(),+ camera_name: z.string(),+ use_this_camera: z.boolean(),++ // Video settings+ resolution: z.object({+ width: z.number().int(),+ height: z.number().int()+ }),+ framerate: z.number().min(1).max(1000),++ // Image settings+ color_channels: z.number().int().min(1).max(4),+ pixel_format: z.enum(PIXEL_FORMATS),+ rotation: z.union([z.literal(-1), z.literal(0), z.literal(1), z.literal(2)]),++ // Exposure settings+ exposure_mode: z.enum(EXPOSURE_MODES),+ exposure: z.number(),++ // Codec settings+ capture_fourcc: z.enum(FOURCC_OPTIONS),+ writer_fourcc: z.enum(FOURCC_OPTIONS),+});++export type CameraConfig = z.infer<typeof CameraConfigSchema>;++// ==================== Camera State ====================+export interface Camera {+ id: string; // Primary key (same as camera_id in config) - must be unique+ index: number; // Device index, e.g. the port number used in cv2.VideoCapture() - must be unique+ name: string; // Human-readable name, e.g. "Logitech C920" - not necessarily unique+ actualConfig: CameraConfig; // Configuration extracted from camera stream+ desiredConfig: CameraConfig; // User's desired configuration+ hasConfigMismatch: boolean; // Whether actual differs from desired+ connectionStatus: 'available' | 'connected' | 'error'; // Connection state+ selected: boolean; // UI selection state++ // Device info (from detection)+ deviceInfo: {+ virtual?: boolean;+ vendorId?: string;+ productId?: string;+ };++ // Performance metrics (optional, updated from websocket)+ metrics?: {+ fps: number;+ droppedFrames: number;+ lastFrameTime: number;+ };+}++// ==================== Store State ====================+export interface CamerasState {+ cameras: Camera[];+ isLoading: boolean;+ error: string | null;+}++// ==================== API Types ====================+export interface DetectCamerasRequest {+ filterVirtual?: boolean;+}++export interface DetectCamerasResponse {+ cameras: Array<{+ index: number;+ name: string;+ vendor_id?: string;+ product_id?: string;+ }>;+}++export interface CamerasConnectOrUpdateRequest {+ camera_configs: Record<string, CameraConfig>;+}++export interface ConnectCamerasResponse {+ camera_configs: Record<string, CameraConfig>;+}++// ==================== Helper Functions ====================+export function createDefaultCameraConfig(+ id: string,+ index: number,+ name: string,+): CameraConfig {+ return {+ camera_id: id,+ camera_index: index,+ camera_name: name,+ use_this_camera: true,+ resolution: { width: 1280, height: 720 },+ framerate: 30,+ color_channels: 3,+ pixel_format: 'RGB',+ rotation: -1,+ exposure_mode: 'MANUAL',+ exposure: -7,+ capture_fourcc: 'MJPG',+ writer_fourcc: 'X264',+ };+}++export function areConfigsEqual(+ config1: CameraConfig,+ config2: CameraConfig+): boolean {+ return (+ config1.resolution.width === config2.resolution.width &&+ config1.resolution.height === config2.resolution.height &&+ config1.framerate === config2.framerate &&+ config1.exposure_mode === config2.exposure_mode &&+ config1.exposure === config2.exposure &&+ config1.rotation === config2.rotation &&+ config1.pixel_format === config2.pixel_format &&+ config1.capture_fourcc === config2.capture_fourcc &&+ config1.writer_fourcc === config2.writer_fourcc+ );+}++export function extractConfigSettings(+ config: CameraConfig+): Partial<CameraConfig> {+ // Extract copyable settings (exclude identity fields)+ return {+ resolution: { ...config.resolution },+ framerate: config.framerate,+ color_channels: config.color_channels,+ pixel_format: config.pixel_format,+ rotation: config.rotation,+ exposure_mode: config.exposure_mode,+ exposure: config.exposure,+ capture_fourcc: config.capture_fourcc,+ writer_fourcc: config.writer_fourcc,+ };+}diff --git a/freemocap-ui/src/store/slices/cameras/index.ts b/freemocap-ui/src/store/slices/cameras/index.tsnew file mode 100644index 00000000..3fe15df1--- /dev/null+++ b/freemocap-ui/src/store/slices/cameras/index.ts@@ -0,0 +1,4 @@+export * from './cameras-slice';+export * from './cameras-types';+export * from './cameras-selectors';+export * from './cameras-thunks';diff --git a/freemocap-ui/src/store/slices/framerate/framerate-selectors.ts b/freemocap-ui/src/store/slices/framerate/framerate-selectors.tsnew file mode 100644index 00000000..81ca51b8--- /dev/null+++ b/freemocap-ui/src/store/slices/framerate/framerate-selectors.ts@@ -0,0 +1,98 @@+// framerate-selectors.ts+import {createSelector} from '@reduxjs/toolkit';+import {RootState} from '../../types';+import {DetailedFramerate} from './framerate-types';++// Basic selectors for current framerates+export const selectCurrentFrontendFramerate = (state: RootState): DetailedFramerate | null =>+ state.framerate.currentFrontendFramerate;++export const selectCurrentBackendFramerate = (state: RootState): DetailedFramerate | null =>+ state.framerate.currentBackendFramerate;++// Quick FPS value selectors+export const selectFrontendFps = (state: RootState): number =>+ state.framerate.currentFrontendFramerate?.mean_frames_per_second ?? 0;++export const selectBackendFps = (state: RootState): number =>+ state.framerate.currentBackendFramerate?.mean_frames_per_second ?? 0;++// Historical data selectors+export const selectRecentFrontendFrameDurations = (state: RootState): number[] =>+ state.framerate.recentFrontendFrameDurations;++export const selectRecentBackendFrameDurations = (state: RootState): number[] =>+ state.framerate.recentBackendFrameDurations;++// Calculated average framerates from historical data+export const selectAverageFramerates = createSelector(+ [selectRecentFrontendFrameDurations, selectRecentBackendFrameDurations],+ (frontendDurations, backendDurations) => {+ const calcAverage = (durations: number[]): number => {+ if (durations.length === 0) return 0;+ const sum = durations.reduce((a, b) => a + b, 0);+ return 1000 / (sum / durations.length); // Convert ms to FPS+ };++ return {+ frontend: calcAverage(frontendDurations),+ backend: calcAverage(backendDurations),+ };+ }+);++// Statistics selectors+export const selectFramerateStatistics = createSelector(+ [selectCurrentFrontendFramerate, selectCurrentBackendFramerate],+ (frontend, backend) => ({+ frontend: {+ mean: frontend?.mean_frames_per_second ?? 0,+ std: frontend?.frame_duration_stddev ?? 0,+ current: frontend?.mean_frames_per_second ?? 0,+ },+ backend: {+ mean: backend?.mean_frames_per_second ?? 0,+ std: backend?.frame_duration_stddev ?? 0,+ current: backend?.mean_frames_per_second ?? 0,+ },+ })+);++// Combined selector for UI components that need all framerate info+export const selectFramerateInfo = createSelector(+ [+ selectCurrentFrontendFramerate,+ selectCurrentBackendFramerate,+ selectAverageFramerates,+ ],+ (frontend, backend, averages) => ({+ frontend: {+ current: frontend?.mean_frames_per_second ?? 0,+ mean: frontend?.mean_frames_per_second ?? 0,+ std: frontend?.frame_duration_stddev ?? 0,+ average: averages.frontend,+ },+ backend: {+ current: backend?.mean_frames_per_second ?? 0,+ mean: backend?.mean_frames_per_second ?? 0,+ std: backend?.frame_duration_stddev ?? 0,+ average: averages.backend,+ },+ })+);++// Selector for all framerate data needed by the viewer components+export const selectFramerateViewerData = createSelector(+ [+ selectCurrentFrontendFramerate,+ selectCurrentBackendFramerate,+ selectRecentFrontendFrameDurations,+ selectRecentBackendFrameDurations,+ ],+ (currentFrontendFramerate, currentBackendFramerate, recentFrontendFrameDurations, recentBackendFrameDurations) => ({+ currentFrontendFramerate,+ currentBackendFramerate,+ recentFrontendFrameDurations,+ recentBackendFrameDurations,+ })+);diff --git a/freemocap-ui/src/store/slices/framerate/framerate-slice.ts b/freemocap-ui/src/store/slices/framerate/framerate-slice.tsnew file mode 100644index 00000000..2eb2ac5f--- /dev/null+++ b/freemocap-ui/src/store/slices/framerate/framerate-slice.ts@@ -0,0 +1,60 @@+// framerate-slice.ts+import {createSlice, PayloadAction} from '@reduxjs/toolkit';+import {DetailedFramerate} from './framerate-types';++// Export DetailedFramerate as CurrentFramerate for component compatibility+export type CurrentFramerate = DetailedFramerate;++interface FramerateState {+ currentBackendFramerate: DetailedFramerate | null;+ currentFrontendFramerate: DetailedFramerate | null;+ // Arrays for historical data to calculate averages and render charts+ recentFrontendFrameDurations: number[];+ recentBackendFrameDurations: number[];+}++const initialState: FramerateState = {+ currentBackendFramerate: null,+ currentFrontendFramerate: null,+ recentFrontendFrameDurations: [],+ recentBackendFrameDurations: [],+};++const MAX_DURATION_HISTORY = 100; // Keep last 100 frame durations++export const framerateSlice = createSlice({+ name: 'framerate',+ initialState,+ reducers: {+ backendFramerateUpdated: (state, action: PayloadAction<DetailedFramerate>) => {+ state.currentBackendFramerate = action.payload;+ // Add mean frame duration to history+ if (action.payload.mean_frame_duration_ms > 0) {+ state.recentBackendFrameDurations = [+ ...state.recentBackendFrameDurations.slice(-(MAX_DURATION_HISTORY - 1)),+ action.payload.mean_frame_duration_ms+ ];+ }+ },+ frontendFramerateUpdated: (state, action: PayloadAction<DetailedFramerate>) => {+ state.currentFrontendFramerate = action.payload;+ // Add mean frame duration to history+ if (action.payload.mean_frame_duration_ms > 0) {+ state.recentFrontendFrameDurations = [+ ...state.recentFrontendFrameDurations.slice(-(MAX_DURATION_HISTORY - 1)),+ action.payload.mean_frame_duration_ms+ ];+ }+ },+ clearFramerateHistory: (state) => {+ state.recentFrontendFrameDurations = [];+ state.recentBackendFrameDurations = [];+ },+ },+});++export const {+ backendFramerateUpdated,+ frontendFramerateUpdated,+ clearFramerateHistory+} = framerateSlice.actions;diff --git a/freemocap-ui/src/store/slices/framerate/framerate-types.ts b/freemocap-ui/src/store/slices/framerate/framerate-types.tsnew file mode 100644index 00000000..780cbb4e--- /dev/null+++ b/freemocap-ui/src/store/slices/framerate/framerate-types.ts@@ -0,0 +1,37 @@+// framerate-types.ts+import {z} from 'zod';++// The actual framerate data structure used in the Redux store+export const FramerateDataSchema = z.object({+ mean: z.number(),+ std: z.number(),+ current: z.number(),+});++export type FramerateData = z.infer<typeof FramerateDataSchema>;++// If you have a different schema from the backend with more detailed stats,+// you can keep it separate for parsing/validation but transform it to FramerateData+export const DetailedFramerateSchema = z.object({+ mean_frame_duration_ms: z.number(),+ mean_frames_per_second: z.number(),+ frame_duration_max: z.number(),+ frame_duration_min: z.number(),+ frame_duration_mean: z.number(),+ frame_duration_stddev: z.number(),+ frame_duration_median: z.number(),+ frame_duration_coefficient_of_variation: z.number(),+ calculation_window_size: z.number(),+ framerate_source: z.string(),+});++export type DetailedFramerate = z.infer<typeof DetailedFramerateSchema>;++// Helper function to convert detailed framerate to simple framerate data+export function detailedToSimpleFramerate(detailed: DetailedFramerate): FramerateData {+ return {+ mean: detailed.mean_frames_per_second,+ std: detailed.frame_duration_stddev,+ current: detailed.mean_frames_per_second, // or calculate from mean_frame_duration_ms+ };+}diff --git a/freemocap-ui/src/store/slices/framerate/index.ts b/freemocap-ui/src/store/slices/framerate/index.tsnew file mode 100644index 00000000..cbf3bf84--- /dev/null+++ b/freemocap-ui/src/store/slices/framerate/index.ts@@ -0,0 +1,3 @@+export * from './framerate-slice';+export * from './framerate-types';+export * from './framerate-selectors';diff --git a/freemocap-ui/src/store/slices/framerateTrackerSlice.ts b/freemocap-ui/src/store/slices/framerateTrackerSlice.tsdeleted file mode 100644index 91b5de2d..00000000--- a/freemocap-ui/src/store/slices/framerateTrackerSlice.ts+++ /dev/null@@ -1,69 +0,0 @@-import type {PayloadAction} from '@reduxjs/toolkit'-import {createSlice} from '@reduxjs/toolkit'-import {z} from 'zod'--export const FramerateHistorgramSchema = z.object({- bin_edges: z.array(z.number()),- bin_counts: z.array(z.number()),- bin_densities: z.array(z.number()),-})-export const CurrentFramerateSchema = z.object({- mean_frame_duration_ms: z.number(),- mean_frames_per_second: z.number(),- frame_duration_max: z.number(),- frame_duration_min: z.number(),- frame_duration_mean: z.number(),- frame_duration_stddev: z.number(),- frame_duration_median: z.number(),- frame_duration_coefficient_of_variation: z.number(),- calculation_window_size: z.number(),- framerate_source: z.string(),-});-export type CurrentFramerate = z.infer<typeof CurrentFramerateSchema>;---// Set a maximum number of framerate entries to store-const MAX_FRAMERATE_ENTRIES = 1000;--interface FramerateState {- currentFrontendFramerate: z.infer<typeof CurrentFramerateSchema> | null;- currentBackendFramerate: z.infer<typeof CurrentFramerateSchema> | null;- recentFrontendFrameDurations: number[]- recentBackendFrameDurations: number[]-}--const initialState: FramerateState = {- currentFrontendFramerate: null,- currentBackendFramerate: null,- recentFrontendFrameDurations: [],- recentBackendFrameDurations: [],-}--export const framerateTrackerSlice = createSlice({- name: 'framerate',- initialState,- reducers: {- setFrontendFramerate: (state, action: PayloadAction<CurrentFramerate>) => {- state.currentFrontendFramerate = CurrentFramerateSchema.parse(action.payload);-- // Keep a rolling list of recent framerates- state.recentFrontendFrameDurations.push(state.currentFrontendFramerate.frame_duration_median);- if (state.recentFrontendFrameDurations.length > MAX_FRAMERATE_ENTRIES) {- state.recentFrontendFrameDurations.shift();- }- },- setBackendFramerate: (state, action: PayloadAction<CurrentFramerate>) => {- state.currentBackendFramerate = CurrentFramerateSchema.parse(action.payload);-- // Keep a rolling list of recent framerates- state.recentBackendFrameDurations.push(state.currentBackendFramerate.frame_duration_median);- if (state.recentBackendFrameDurations.length > MAX_FRAMERATE_ENTRIES) {- state.recentBackendFrameDurations.shift();- }-- },- }-})--export const {setFrontendFramerate, setBackendFramerate} = framerateTrackerSlice.actions-export default framerateTrackerSlice.reducerdiff --git a/freemocap-ui/src/store/slices/log-records/index.ts b/freemocap-ui/src/store/slices/log-records/index.tsnew file mode 100644index 00000000..e48b73b3--- /dev/null+++ b/freemocap-ui/src/store/slices/log-records/index.ts@@ -0,0 +1,3 @@+export * from './log-records-slice';+export * from './logs-types';+export * from './logs-selectors';diff --git a/freemocap-ui/src/store/slices/log-records/log-records-slice.ts b/freemocap-ui/src/store/slices/log-records/log-records-slice.tsnew file mode 100644index 00000000..8924cc42--- /dev/null+++ b/freemocap-ui/src/store/slices/log-records/log-records-slice.ts@@ -0,0 +1,86 @@+// log-records-slice.ts+import {createSlice, PayloadAction} from '@reduxjs/toolkit';+import {LogRecord} from './logs-types';++interface LogRecordsState {+ entries: LogRecord[];+ maxEntries: number;+ isPaused: boolean;+ filter: {+ levels: string[];+ searchText: string;+ };+}++const initialState: LogRecordsState = {+ entries: [],+ maxEntries: 1000,+ isPaused: false,+ filter: {+ levels: [],+ searchText: '',+ },+};++export const logRecordsSlice = createSlice({+ name: 'logs',+ initialState,+ reducers: {+ logAdded: (state, action: PayloadAction<LogRecord>) => {+ if (state.isPaused) return;++ state.entries.push(action.payload);++ // Keep only the last maxEntries+ if (state.entries.length > state.maxEntries) {+ state.entries = state.entries.slice(-state.maxEntries);+ }+ },++ logsAdded: (state, action: PayloadAction<LogRecord[]>) => {+ if (state.isPaused) return;++ state.entries.push(...action.payload);++ // Keep only the last maxEntries+ if (state.entries.length > state.maxEntries) {+ state.entries = state.entries.slice(-state.maxEntries);+ }+ },++ logsCleared: (state) => {+ state.entries = [];+ },++ logsPaused: (state, action: PayloadAction<boolean>) => {+ state.isPaused = action.payload;+ },++ logsFiltered: (state, action: PayloadAction<{ levels?: string[]; searchText?: string }>) => {+ if (action.payload.levels !== undefined) {+ state.filter.levels = action.payload.levels;+ }+ if (action.payload.searchText !== undefined) {+ state.filter.searchText = action.payload.searchText;+ }+ },++ maxEntriesUpdated: (state, action: PayloadAction<number>) => {+ state.maxEntries = action.payload;++ // Trim entries if new max is smaller+ if (state.entries.length > action.payload) {+ state.entries = state.entries.slice(-action.payload);+ }+ },+ },+});++export const {+ logAdded,+ logsAdded,+ logsCleared,+ logsPaused,+ logsFiltered,+ maxEntriesUpdated+} = logRecordsSlice.actions;diff --git a/freemocap-ui/src/store/slices/log-records/logs-selectors.ts b/freemocap-ui/src/store/slices/log-records/logs-selectors.tsnew file mode 100644index 00000000..3f1905ed--- /dev/null+++ b/freemocap-ui/src/store/slices/log-records/logs-selectors.ts@@ -0,0 +1,96 @@+// logs-selectors.ts+import {createSelector} from '@reduxjs/toolkit';+import {RootState} from '../../types';+import {LogRecord} from './logs-types';++// Basic selectors+export const selectAllLogs = (state: RootState): LogRecord[] =>+ state.logs.entries;++export const selectLogsPaused = (state: RootState): boolean =>+ state.logs.isPaused;++export const selectLogsFilter = (state: RootState) =>+ state.logs.filter;++export const selectMaxLogEntries = (state: RootState): number =>+ state.logs.maxEntries;++// Filtered logs based on current filter settings+export const selectFilteredLogs = createSelector(+ [selectAllLogs, selectLogsFilter],+ (logs, filter) => {+ let filtered = logs;++ // Filter by levels if any are selected+ if (filter.levels.length > 0) {+ filtered = filtered.filter(log =>+ filter.levels.includes(log.levelname.toLowerCase())+ );+ }++ // Filter by search text if provided+ if (filter.searchText) {+ const searchLower = filter.searchText.toLowerCase();+ filtered = filtered.filter(log =>+ log.message.toLowerCase().includes(searchLower) ||+ log.module.toLowerCase().includes(searchLower) ||+ log.funcName.toLowerCase().includes(searchLower) ||+ log.formatted_message?.toLowerCase().includes(searchLower)+ );+ }++ return filtered;+ }+);++// Get logs by specific level+export const selectLogsByLevel = createSelector(+ [selectAllLogs, (_: RootState, level: string) => level],+ (logs, level) => logs.filter(log => log.levelname === level)+);++// Get recent logs (last N entries)+export const selectRecentLogs = createSelector(+ [selectAllLogs, (_: RootState, count: number = 10) => count],+ (logs, count) => logs.slice(-count)+);++// Get filtered recent logs+export const selectRecentFilteredLogs = createSelector(+ [selectFilteredLogs, (_: RootState, count: number = 10) => count],+ (logs, count) => logs.slice(-count)+);++// Count logs by level+export const selectLogCountsByLevel = createSelector(+ [selectAllLogs],+ (logs) => {+ const counts: Record<string, number> = {};+ logs.forEach(log => {+ const level = log.levelname;+ counts[level] = (counts[level] || 0) + 1;+ });+ return counts;+ }+);++// Get error and critical logs+export const selectErrorLogs = createSelector(+ [selectAllLogs],+ (logs) => logs.filter(log =>+ log.levelname === 'ERROR' || log.levelname === 'CRITICAL'+ )+);++// Check if there are any errors+export const selectHasErrors = createSelector(+ [selectErrorLogs],+ (errorLogs) => errorLogs.length > 0+);++// Get the most recent error+export const selectMostRecentError = createSelector(+ [selectErrorLogs],+ (errorLogs) => errorLogs[errorLogs.length - 1] || null+);diff --git a/freemocap-ui/src/store/slices/log-records/logs-types.ts b/freemocap-ui/src/store/slices/log-records/logs-types.tsnew file mode 100644index 00000000..d899112c--- /dev/null+++ b/freemocap-ui/src/store/slices/log-records/logs-types.ts@@ -0,0 +1,31 @@+import {z} from 'zod';++export const LogRecordSchema = z.object({+ name: z.string(),+ msg: z.string().nullable().default(""),+ args: z.array(z.any()),+ levelname: z.string(),+ levelno: z.number(),+ pathname: z.string(),+ filename: z.string(),+ module: z.string(),+ exc_info: z.string().nullable(),+ exc_text: z.string().nullable(),+ stack_info: z.string().nullable(),+ lineno: z.number(),+ funcName: z.string(),+ created: z.number(),+ msecs: z.number(),+ relativeCreated: z.number(),+ thread: z.number(),+ threadName: z.string(),+ processName: z.string(),+ process: z.number(),+ delta_t: z.string(),+ message: z.string(),+ asctime: z.string(),+ formatted_message: z.string(),+ type: z.string(),+});++export type LogRecord = z.infer<typeof LogRecordSchema>;diff --git a/freemocap-ui/src/store/slices/logRecordsSlice.ts b/freemocap-ui/src/store/slices/logRecordsSlice.tsdeleted file mode 100644index 584ac758..00000000--- a/freemocap-ui/src/store/slices/logRecordsSlice.ts+++ /dev/null@@ -1,115 +0,0 @@-import type {PayloadAction} from "@reduxjs/toolkit";-import {createSlice} from "@reduxjs/toolkit"-import {z} from "zod";---// Updated to match the server's LogRecordModel-export const LogRecordSchema = z.object({- name: z.string(),- msg: z.string().nullable().default(""),- args: z.array(z.any()),- levelname: z.string(),- levelno: z.number(),- pathname: z.string(),- filename: z.string(),- module: z.string(),- exc_info: z.string().nullable(),- exc_text: z.string().nullable(),- stack_info: z.string().nullable(),- lineno: z.number(),- funcName: z.string(),- created: z.number(),- msecs: z.number(),- relativeCreated: z.number(),- thread: z.number(),- threadName: z.string(),- processName: z.string(),- process: z.number(),- delta_t: z.string(),- message: z.string(),- asctime: z.string(),- formatted_message: z.string(),- type: z.string(),-});-export type LogRecord = z.infer<typeof LogRecordSchema>;--export const IncomingLogsSchema = z.object({- logs: z.array(LogRecordSchema),-});--export type IncomingLogs = z.infer<typeof IncomingLogsSchema>;--interface LogsState {- entries: LogRecord[]-}-const initialLogRecord: LogRecord = {- name: "initial",- msg: "Log entry initialized",- args: [],- levelname: "DEBUG",- levelno: 10,- filename: "filename",- pathname: "pathname",- module: "module",- exc_info: "exc_info",- exc_text: "exc_text",- stack_info: "stack_info",- lineno: 0,- funcName: "funcName",- created: 0,- msecs: 0,- relativeCreated: 0,- thread: 0,- threadName: "threadName",- processName: "processName",- process: 0,- delta_t: "0.000",- message: "Initial log message",- asctime: new Date().toISOString(),- formatted_message: "Initial log message",- type: "log",-}-const initialState: LogsState = {- entries: [initialLogRecord],-}-const MAX_LOG_ENTRIES = 300-export const logRecordsSlice = createSlice({- name: "logs",- initialState,- reducers: {- addLog: (state,- action: PayloadAction<LogRecord>) => {- const newLogEntry: LogRecord = {- ...action.payload,- }-- // if we're at the limit, remove the oldest entry first- if (state.entries.length >= MAX_LOG_ENTRIES) {- state.entries.shift() // Remove the oldest log entry- }-- state.entries.push(newLogEntry)- },- addLogs: (state,- action: PayloadAction<IncomingLogs>) => {- const newLogs: LogRecord[] = action.payload.logs- // Add new logs to the state, ensuring we don't exceed the max limit- for (const log of newLogs) {- const newLogEntry: LogRecord = {- ...log,- }-- // if we're at the limit, remove the oldest entry first- if (state.entries.length >= MAX_LOG_ENTRIES) {- state.entries.shift() // Remove the oldest log entry- }-- state.entries.push(newLogEntry)- }- }- },--})--export const {addLog, addLogs} = logRecordsSlice.actions-export default logRecordsSlice.reducerdiff --git a/freemocap-ui/src/store/slices/mocap/index.ts b/freemocap-ui/src/store/slices/mocap/index.tsnew file mode 100644index 00000000..f3a3b8e3--- /dev/null+++ b/freemocap-ui/src/store/slices/mocap/index.ts@@ -0,0 +1,3 @@++export * from './mocap-slice';+export * from './mocap-thunks';diff --git a/freemocap-ui/src/store/slices/mocap/mocap-slice.ts b/freemocap-ui/src/store/slices/mocap/mocap-slice.tsnew file mode 100644index 00000000..053b3a80--- /dev/null+++ b/freemocap-ui/src/store/slices/mocap/mocap-slice.ts@@ -0,0 +1,224 @@+// store/slices/mocap/mocap-slice.ts+import {createSelector, createSlice, PayloadAction} from '@reduxjs/toolkit';+import {RootState} from '../../types';+import {+ processMocapRecording,+ startMocapRecording,+ stopMocapRecording,+ updateMocapConfigOnServer,+} from "@/store/slices/mocap/mocap-thunks";++// ==================== Types ====================++export interface MocapConfig {+}++export interface MocapDirectoryInfo {+ exists: boolean;+ canRecord: boolean; // true if directory doesn't exist OR exists but is empty+ canCalibrate: boolean; // true if has videos (either in synchronized_videos or root)+ cameraMocapTomlPath: string | null;+ hasSynchronizedVideos: boolean;+ hasVideos: boolean;+ errorMessage: string | null;+}++export interface MocapState {+ config: MocapConfig;+ isRecording: boolean;+ recordingProgress: number;+ isLoading: boolean;+ error: string | null;+ lastMocapRecordingPath: string | null; // Path from last recording+ manualMocapRecordingPath: string | null; // User-selected override path+ directoryInfo: MocapDirectoryInfo | null; // Info about the current mocap directory+}++// ==================== Initial State ====================++const initialState: MocapState = {+ config: {+ liveTrackCharuco: true,+ charucoBoardXSquares: 5,+ charucoBoardYSquares: 3,+ charucoSquareLength: 1,+ minSharedViewsPerCamera: 200,+ autoStopOnMinViewCount: true,+ },+ isRecording: false,+ recordingProgress: 0,+ isLoading: false,+ error: null,+ lastMocapRecordingPath: null,+ manualMocapRecordingPath: null,+ directoryInfo: null,+};++// ==================== Slice ====================++export const mocapSlice = createSlice({+ name: 'mocap',+ initialState,+ reducers: {+ mocapConfigUpdated: (state, action: PayloadAction<Partial<MocapConfig>>) => {+ state.config = { ...state.config, ...action.payload };+ },++ mocapProgressUpdated: (state, action: PayloadAction<number>) => {+ state.recordingProgress = action.payload;+ },++ mocapErrorCleared: (state) => {+ state.error = null;+ },++ // New action to set manual path+ manualMocapRecordingPathChanged: (state, action: PayloadAction<string>) => {+ state.manualMocapRecordingPath = action.payload;+ },++ // New action to clear manual path (revert to default)+ manualMocapRecordingPathCleared: (state) => {+ state.manualMocapRecordingPath = null;+ },++ // New action to update directory info+ mocapDirectoryInfoUpdated: (state, action: PayloadAction<MocapDirectoryInfo>) => {+ state.directoryInfo = action.payload;+ },++ resetMocapState: () => initialState,+ },++ extraReducers: (builder) => {+ // Start Recording+ builder+ .addCase(startMocapRecording.pending, (state) => {+ state.isLoading = true;+ state.error = null;+ })+ .addCase(startMocapRecording.fulfilled, (state, action) => {+ state.isLoading = false;+ state.isRecording = true;+ state.recordingProgress = 0;+ // Store the path returned from the server+ if (action.payload.mocapRecordingPath) {+ state.lastMocapRecordingPath = action.payload.mocapRecordingPath;+ }+ })+ .addCase(startMocapRecording.rejected, (state, action) => {+ state.isLoading = false;+ state.error = action.payload || 'Failed to start recording';+ });++ // Stop Recording+ builder+ .addCase(stopMocapRecording.pending, (state) => {+ state.isLoading = true;+ state.error = null;+ })+ .addCase(stopMocapRecording.fulfilled, (state) => {+ state.isLoading = false;+ state.isRecording = false;+ state.recordingProgress = 0;+ })+ .addCase(stopMocapRecording.rejected, (state, action) => {+ state.isLoading = false;+ state.error = action.payload || 'Failed to stop recording';+ });++ // Process Mocap Recording+ builder+ .addCase(processMocapRecording.pending, (state) => {+ state.isLoading = true;+ state.error = null;+ })+ .addCase(processMocapRecording.fulfilled, (state) => {+ state.isLoading = false;+ })+ .addCase(processMocapRecording.rejected, (state, action) => {+ state.isLoading = false;+ state.error = action.payload || 'Failed to calibrate recording';+ });++ // Update Config on Server+ builder+ .addCase(updateMocapConfigOnServer.rejected, (state, action) => {+ state.error = action.payload || 'Failed to sync config to server';+ });+ },+});++// ==================== Selectors ====================++export const selectMocap = (state: RootState) => state.mocap;+export const selectMocapConfig = (state: RootState) => state.mocap.config;+export const selectMocapIsLoading = (state: RootState) => state.mocap.isLoading;+export const selectMocapIsRecording = (state: RootState) => state.mocap.isRecording;+export const selectMocapProgress = (state: RootState) => state.mocap.recordingProgress;+export const selectMocapError = (state: RootState) => state.mocap.error;+export const selectMocapDirectoryInfo = (state: RootState) => state.mocap.directoryInfo;++export const selectMocapRecordingPath = createSelector(+ [+ (state: RootState) => state.mocap.manualMocapRecordingPath,+ (state: RootState) => state.mocap.lastMocapRecordingPath,+ (state: RootState) => state.recording.computed,+ ],+ (manualPath, lastPath, recordingComputed) => {+ if (manualPath) return manualPath;+ if (lastPath) return lastPath;++ // Build mocap path from recording computed values+ const mocapFolderName = `${recordingComputed.recordingName}_mocap`;+ return `${recordingComputed.fullRecordingPath}/${mocapFolderName}`;+ }+);++// Selector to check if using manual path+export const selectIsUsingManualMocapPath = createSelector(+ [(state: RootState) => state.mocap.manualMocapRecordingPath],+ (manualPath) => manualPath !== null+);++export const selectCanStartMocapRecording = createSelector(+ [+ selectMocapIsRecording,+ selectMocapIsLoading,+ selectMocapRecordingPath,+ selectMocapDirectoryInfo+ ],+ (isRecording, isLoading, recordingPath, directoryInfo) => {+ // Can start if: not recording, not loading, have a path, and directory can be recorded to+ return !isRecording && !isLoading && !!recordingPath && (directoryInfo?.canRecord ?? true);+ }+);++export const selectCanProcessMocapRecording = createSelector(+ [+ selectMocapRecordingPath,+ selectMocapIsLoading,+ selectMocapIsRecording,+ selectMocapDirectoryInfo+ ],+ (mocapPath, isLoading, isRecording, directoryInfo) => {+ // Can process if: have path, not loading, not recording, and directory has videos+ return !!mocapPath && !isLoading && !isRecording && (directoryInfo?.canCalibrate ?? false);+ }+);++// ==================== Actions Export ====================++export const {+ mocapConfigUpdated,+ mocapProgressUpdated,+ mocapErrorCleared,+ manualMocapRecordingPathChanged,+ manualMocapRecordingPathCleared,+ mocapDirectoryInfoUpdated,+ resetMocapState+} = mocapSlice.actions;++// ==================== Reducer Export ====================++export default mocapSlice.reducer;diff --git a/freemocap-ui/src/store/slices/mocap/mocap-thunks.ts b/freemocap-ui/src/store/slices/mocap/mocap-thunks.tsnew file mode 100644index 00000000..ad2665a6--- /dev/null+++ b/freemocap-ui/src/store/slices/mocap/mocap-thunks.ts@@ -0,0 +1,223 @@+import {createAsyncThunk} from "@reduxjs/toolkit";+import {RootState} from "@/store";+import {serverUrls} from "@/hooks/server-urls";+import {selectMocapRecordingPath} from "./mocap-slice";++// Helper function to extract detailed error info from failed responses+async function getDetailedErrorMessage(response: Response): Promise<string> {+ let errorDetails: unknown;++ try {+ // Try to parse JSON error response+ errorDetails = await response.json();+ console.error('โ Server returned validation/error details:', errorDetails);+ } catch {+ // If not JSON, try to get text+ try {+ errorDetails = await response.text();+ console.error('โ Server returned error text:', errorDetails);+ } catch {+ console.error('โ Could not read error response body');+ }+ }++ // Build comprehensive error message+ const baseError = `HTTP ${response.status}: ${response.statusText}`;++ if (errorDetails) {+ // Pretty print the error details+ const detailsStr = typeof errorDetails === 'string'+ ? errorDetails+ : JSON.stringify(errorDetails, null, 2);+ return `${baseError}\n\nValidation/Error Details:\n${detailsStr}`;+ }++ return baseError;+}++// Helper function to generate mocap recording name based on recording config+function generateMocapRecordingName(state: RootState): string {+ const recordingConfig = state.recording.config;+ const parts: string[] = [];++ // Add base name if configured+ if (recordingConfig.baseName && recordingConfig.baseName !== 'recording') {+ parts.push(recordingConfig.baseName);+ }++ const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);+ parts.push(timestamp);++ // Add recording tag if provided+ if (recordingConfig.recordingTag) {+ parts.push(recordingConfig.recordingTag);+ }++ parts.push('mocap');++ return parts.join('_');+}++export const startMocapRecording = createAsyncThunk<+ { success: boolean; message?: string; mocapRecordingPath?: string },+ void,+ { state: RootState; rejectValue: string }+>(+ 'mocap/startRecording',+ async (_, { getState, rejectWithValue }) => {+ try {+ const state = getState();+ const mocapTaskConfig = state.mocap.config;+ const mocapRecordingDirectory = selectMocapRecordingPath(state);++ if (!mocapRecordingDirectory) {+ return rejectWithValue('Recording directory is not set');+ }++ console.log('๐ฌ Starting mocap recording with:', {+ mocapRecordingDirectory,+ mocapTaskConfig,+ });++ const response = await fetch(serverUrls.endpoints.mocapStartRecording, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ mocapRecordingDirectory,+ mocapTaskConfig,+ }),+ });++ if (!response.ok) {+ const errorMessage = await getDetailedErrorMessage(response);+ return rejectWithValue(errorMessage);+ }++ const result = await response.json();+ console.log('โ Started mocap recording:', result);+ return result;+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';+ console.error('โ Failed to start mocap recording:', errorMessage);+ return rejectWithValue(errorMessage);+ }+ }+);++export const stopMocapRecording = createAsyncThunk<+ { success: boolean },+ void,+ { state: RootState; rejectValue: string }+>(+ 'mocap/stopRecording',+ async (_, { getState, rejectWithValue }) => {+ try {+ const state = getState();+ const mocapTaskConfig = state.mocap.config;+++ console.log(`๐ฌ Stoping mocap recording and starting mocap with: ${JSON.stringify(mocapTaskConfig, null, 2)}`);+++ const response = await fetch(serverUrls.endpoints.mocapStopRecording, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({mocapTaskConfig}),+ });++ if (!response.ok) {+ const errorMessage = await getDetailedErrorMessage(response);+ return rejectWithValue(errorMessage);+ }++ const result = await response.json();+ console.log('โ Stopped mocap recording:', result);+ return result;+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';+ console.error('โ Failed to stop mocap recording:', errorMessage);+ return rejectWithValue(errorMessage);+ }+ }+);++export const processMocapRecording = createAsyncThunk<+ { success: boolean; message?: string; results?: unknown },+ void,+ { state: RootState; rejectValue: string }+>(+ 'mocap/processMocapRecording',+ async (_, { getState, rejectWithValue }) => {+ try {+ const state = getState();+ const mocapTaskConfig = state.mocap.config;+ const mocapRecordingDirectory = selectMocapRecordingPath(state);++ if (!mocapRecordingDirectory) {+ return rejectWithValue('No mocap recording path available. Please set a recording directory or record a mocap first.');+ }++ console.log('๐ง Calibrating recording:', {+ mocapRecordingDirectory,+ mocapTaskConfig,+ });++ const response = await fetch(serverUrls.endpoints.processMocapRecording, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ mocapRecordingDirectory,+ mocapTaskConfig,+ }),+ });++ if (!response.ok) {+ const errorMessage = await getDetailedErrorMessage(response);+ return rejectWithValue(errorMessage);+ }++ const result = await response.json();+ console.log('โ Mocap completed:', result);+ return result;+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';+ console.error('โ Failed to process recording:', errorMessage);+ return rejectWithValue(errorMessage);+ }+ }+);++export const updateMocapConfigOnServer = createAsyncThunk<+ { success: boolean; message?: string },+ void,+ { state: RootState; rejectValue: string }+>(+ 'mocap/updateConfig',+ async (_, { getState, rejectWithValue }) => {+ try {+ const state = getState();+ const config = state.mocap.config;++ console.log('โ๏ธ Updating mocap config on server:', config);++ const response = await fetch(serverUrls.endpoints.updateMocapConfig, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ config }),+ });++ if (!response.ok) {+ const errorMessage = await getDetailedErrorMessage(response);+ return rejectWithValue(errorMessage);+ }++ const result = await response.json();+ console.log('โ Config updated on server:', result);+ return result;+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';+ console.error('โ Failed to update config on server:', errorMessage);+ return rejectWithValue(errorMessage);+ }+ }+);diff --git a/freemocap-ui/src/store/slices/pipeline/index.ts b/freemocap-ui/src/store/slices/pipeline/index.tsnew file mode 100644index 00000000..09453243--- /dev/null+++ b/freemocap-ui/src/store/slices/pipeline/index.ts@@ -0,0 +1,4 @@+export * from './pipeline-slice';+export * from './pipeline-selectors';+export * from './pipeline-thunks';+export * from './pipeline-types';diff --git a/freemocap-ui/src/store/slices/pipeline/pipeline-selectors.ts b/freemocap-ui/src/store/slices/pipeline/pipeline-selectors.tsnew file mode 100644index 00000000..74365541--- /dev/null+++ b/freemocap-ui/src/store/slices/pipeline/pipeline-selectors.ts@@ -0,0 +1,34 @@+// basic selectors+import {RootState} from "@/store";+import {createSelector} from "@reduxjs/toolkit";++export const selectPipelineState = (state: RootState) => state.pipeline;+export const selectIsPipelineConnected = (state: RootState) => state.pipeline.isConnected;+export const selectPipelineId = (state: RootState) => state.pipeline.pipelineId;+export const selectCameraGroupId = (state: RootState) => state.pipeline.cameraGroupId;+export const selectIsPipelineLoading = (state: RootState) => state.pipeline.isLoading;+export const selectPipelineError = (state: RootState) => state.pipeline.error;++// derived selectors+export const selectPipelineInfo = createSelector(+ [selectIsPipelineConnected, selectPipelineId, selectCameraGroupId],+ (isConnected, pipelineId, cameraGroupId) => ({+ isConnected,+ pipelineId,+ cameraGroupId,+ })+);++export const selectCanConnectPipeline = createSelector(+ [selectIsPipelineConnected, selectIsPipelineLoading, (state: RootState) => state.cameras.cameras],+ (isConnected, isLoading, cameras) => {+ const anyCameraSelected = cameras.some(cam => cam.selected);+ return !isConnected && !isLoading && anyCameraSelected;+ }+);++export const selectCanDisconnectPipeline = createSelector(+ [selectIsPipelineConnected, selectIsPipelineLoading],+ (isConnected, isLoading) => isConnected && !isLoading+);+diff --git a/freemocap-ui/src/store/slices/pipeline/pipeline-slice.ts b/freemocap-ui/src/store/slices/pipeline/pipeline-slice.tsnew file mode 100644index 00000000..4466a78c--- /dev/null+++ b/freemocap-ui/src/store/slices/pipeline/pipeline-slice.ts@@ -0,0 +1,62 @@+import {createSlice} from "@reduxjs/toolkit";+import {PipelineState} from "@/store/slices/pipeline/pipeline-types";+import {closePipeline, connectRealtimePipeline} from "@/store/slices/pipeline/pipeline-thunks";++const initialState: PipelineState = {+ cameraGroupId: null,+ pipelineId: null,+ isConnected: false,+ isLoading: false,+ error: null,+}++export const pipelineSlice = createSlice({+ name: 'pipeline',+ initialState,+ reducers: {+ // Manual state reset+ pipelineStateReset: (state) => {+ state.cameraGroupId = null;+ state.pipelineId = null;+ state.isConnected = false;+ state.isLoading = false;+ state.error = null;+ }+ },+ extraReducers: (builder) => {+ builder+ // Connect Pipeline+ .addCase(connectRealtimePipeline.pending, (state) => {+ state.isLoading = true;+ state.error = null;+ })+ .addCase(connectRealtimePipeline.fulfilled, (state, action) => {+ state.cameraGroupId = action.payload.camera_group_id;+ state.pipelineId = action.payload.pipeline_id;+ state.isConnected = true;+ state.isLoading = false;+ })+ .addCase(connectRealtimePipeline.rejected, (state, action) => {+ state.isLoading = false;+ state.error = action.error.message || 'Failed to connect pipeline';+ })++ // disconnect pipeline+ .addCase(closePipeline.pending, (state) => {+ state.isLoading = true;+ state.error = null;+ })+ .addCase(closePipeline.fulfilled, (state) => {+ state.cameraGroupId = null;+ state.pipelineId = null;+ state.isConnected = false;+ state.isLoading = false;+ })+ .addCase(closePipeline.rejected, (state, action) => {+ state.isLoading = false;+ state.error = action.error.message || 'Failed to disconnect pipeline';+ });+ },+});++export const {pipelineStateReset} = pipelineSlice.actions;diff --git a/freemocap-ui/src/store/slices/pipeline/pipeline-thunks.ts b/freemocap-ui/src/store/slices/pipeline/pipeline-thunks.tsnew file mode 100644index 00000000..1815b84c--- /dev/null+++ b/freemocap-ui/src/store/slices/pipeline/pipeline-thunks.ts@@ -0,0 +1,56 @@+import {createAsyncThunk} from "@reduxjs/toolkit";+import {RootState, selectSelectedCameraConfigs} from "@/store";+import {serverUrls} from "@/services";+import {PipelineConnectRequest, PipelineConnectResponse,} from "@/store/slices/pipeline/pipeline-types";++export const connectRealtimePipeline = createAsyncThunk<+ PipelineConnectResponse,+ PipelineConnectRequest | undefined,+ { state: RootState }>(+ 'pipeline/connect',+ async (request={}, {getState}) => {+ const state = getState();++ const cameraConfigs = selectSelectedCameraConfigs(state);+ const response = await fetch(serverUrls.endpoints.pipelineConnectOrUpdate, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ camera_configs: cameraConfigs, ...request }),+ });++ if (!response.ok) {+ const error = await response.json()+ throw new Error(`Failed to connect pipeline: ${error.message || response.statusText}`);+ }+ return await response.json() as Promise<PipelineConnectResponse>;+ })+++export const closePipeline = createAsyncThunk<void, void, { state: RootState }>(+ 'pipeline/close',+ async () => {+ const response = await fetch(serverUrls.endpoints.pipelineClose, {+ method: 'DELETE',+ });++ if (!response.ok) {+ console.error(`Failed to close pipeline: ${response.statusText}`);+ }+ }+);+++++export const pauseUnpausePipeline = createAsyncThunk<void, void, { state: RootState }>(+ 'cameras/pause',+ async () => {+ const response = await fetch(serverUrls.endpoints.pipelinePauseUnpause, {+ method: 'GET',+ });++ if (!response.ok) {+ throw new Error(`Failed to pause/unpause cameras: ${response.statusText}`);+ }+ }+);diff --git a/freemocap-ui/src/store/slices/pipeline/pipeline-types.ts b/freemocap-ui/src/store/slices/pipeline/pipeline-types.tsnew file mode 100644index 00000000..1444992c--- /dev/null+++ b/freemocap-ui/src/store/slices/pipeline/pipeline-types.ts@@ -0,0 +1,45 @@+import {z} from 'zod';+import {CameraConfig} from "@/store";++// ==================== API Request/Response Types ====================+export interface PipelineConnectRequest {+ camera_configs?: string[];+}++export interface PipelineConnectResponse {+ camera_group_id: string;+ pipeline_id: string;+ camera_configs: Record<string, CameraConfig>;+}++// ==================== Pipeline State ====================+export interface PipelineState {+ cameraGroupId: string | null;+ pipelineId: string | null;+ isConnected: boolean;+ isLoading: boolean;+ error: string | null;+}+++const ProcessingPipelineConfigSchema = z.object({+ pipeline_id: z.string(),+ parameters: z.record(z.string(), z.any()),+})+++export type ProcessingPipelineConfig = z.infer<typeof ProcessingPipelineConfigSchema>;+export interface ProcessingPipeline {+ id: string;+ name: string;+ isActive: boolean;+ config: ProcessingPipelineConfig+}++export interface ProcessingPipelineState {+ pipelines: ProcessingPipeline[];+ isLoading: boolean;+ isActive: boolean;+ error: string | null;+}+diff --git a/freemocap-ui/src/store/slices/recording/index.ts b/freemocap-ui/src/store/slices/recording/index.tsnew file mode 100644index 00000000..bc073c3e--- /dev/null+++ b/freemocap-ui/src/store/slices/recording/index.ts@@ -0,0 +1,3 @@+export * from './recording-slice';+export * from './recording-types';+export * from './recording-thunks';diff --git a/freemocap-ui/src/store/slices/recording/recording-slice.ts b/freemocap-ui/src/store/slices/recording/recording-slice.tsnew file mode 100644index 00000000..255dd726--- /dev/null+++ b/freemocap-ui/src/store/slices/recording/recording-slice.ts@@ -0,0 +1,197 @@+import {createSlice, PayloadAction} from '@reduxjs/toolkit';+import {ComputedRecordingPath, RecordingConfig, RecordingInfo} from './recording-types';+import {startRecording, stopRecording} from './recording-thunks';++const getTimestampString = (): string => {+ const now = new Date();++ const dateOptions: Intl.DateTimeFormatOptions = {+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ hour: "2-digit",+ minute: "2-digit",+ second: "2-digit",+ hour12: false,+ timeZoneName: "shortOffset",+ };++ const formatter = new Intl.DateTimeFormat("en-US", dateOptions);+ const parts = formatter.formatToParts(now);++ const partMap: Record<string, string> = {};+ parts.forEach((part) => {+ partMap[part.type] = part.value;+ });++ return `${partMap.year}-${partMap.month}-${partMap.day}_${partMap.hour}-${partMap.minute}-${partMap.second}_${partMap.timeZoneName.replace(":", "")}`;+};++const computeRecordingPath = (+ recordingDirectory: string,+ config: RecordingConfig+): ComputedRecordingPath => {+ const parts: string[] = [];++ if (config.useTimestamp) {+ parts.push(getTimestampString());+ } else {+ parts.push(config.baseName);+ }++ if (config.useIncrement) {+ parts.push(String(config.currentIncrement).padStart(3, '0'));+ }++ if (config.recordingTag) {+ parts.push(config.recordingTag);+ }++ const recordingName = parts.join("_");++ const subfolderName = config.createSubfolder+ ? config.customSubfolderName || getTimestampString()+ : "";++ const fullRecordingPath = config.createSubfolder+ ? `${recordingDirectory}/${subfolderName}`+ : recordingDirectory;++ return {+ recordingName,+ subfolderName,+ fullRecordingPath,+ };+};++const initialState: RecordingInfo = {+ isRecording: false,+ recordingDirectory: '~/freemocap_data/recordings',+ recordingName: null,+ startedAt: null,+ duration: 0,+ config: {+ useDelayStart: false,+ delaySeconds: 3,+ useTimestamp: true,+ useIncrement: false,+ currentIncrement: 1,+ baseName: 'recording',+ recordingTag: '',+ createSubfolder: false,+ customSubfolderName: '',+ },+ computed: {+ recordingName: '',+ subfolderName: '',+ fullRecordingPath: '~/freemocap_data/recordings',+ },+};++// Initialize computed values+initialState.computed = computeRecordingPath(+ initialState.recordingDirectory,+ initialState.config+);++export const recordingSlice = createSlice({+ name: 'recording',+ initialState,+ reducers: {+ recordingInfoUpdated: (state, action: PayloadAction<Partial<RecordingInfo>>) => {+ Object.assign(state, action.payload);+ state.computed = computeRecordingPath(state.recordingDirectory, state.config);+ },+ recordingDirectoryChanged: (state, action: PayloadAction<string>) => {+ state.recordingDirectory = action.payload;+ state.computed = computeRecordingPath(state.recordingDirectory, state.config);+ },+ recordingDurationUpdated: (state, action: PayloadAction<number>) => {+ state.duration = action.payload;+ },++ // Config updates+ configUpdated: (state, action: PayloadAction<Partial<RecordingConfig>>) => {+ Object.assign(state.config, action.payload);+ state.computed = computeRecordingPath(state.recordingDirectory, state.config);+ },+ useDelayStartToggled: (state, action: PayloadAction<boolean>) => {+ state.config.useDelayStart = action.payload;+ // No need to recompute path for delay settings+ },+ delaySecondsChanged: (state, action: PayloadAction<number>) => {+ state.config.delaySeconds = action.payload;+ // No need to recompute path for delay settings+ },+ useTimestampToggled: (state, action: PayloadAction<boolean>) => {+ state.config.useTimestamp = action.payload;+ state.computed = computeRecordingPath(state.recordingDirectory, state.config);+ },+ useIncrementToggled: (state, action: PayloadAction<boolean>) => {+ state.config.useIncrement = action.payload;+ state.computed = computeRecordingPath(state.recordingDirectory, state.config);+ },+ currentIncrementChanged: (state, action: PayloadAction<number>) => {+ state.config.currentIncrement = action.payload;+ state.computed = computeRecordingPath(state.recordingDirectory, state.config);+ },+ currentIncrementIncremented: (state) => {+ state.config.currentIncrement += 1;+ state.computed = computeRecordingPath(state.recordingDirectory, state.config);+ },+ baseNameChanged: (state, action: PayloadAction<string>) => {+ state.config.baseName = action.payload;+ state.computed = computeRecordingPath(state.recordingDirectory, state.config);+ },+ recordingTagChanged: (state, action: PayloadAction<string>) => {+ state.config.recordingTag = action.payload;+ state.computed = computeRecordingPath(state.recordingDirectory, state.config);+ },+ createSubfolderToggled: (state, action: PayloadAction<boolean>) => {+ state.config.createSubfolder = action.payload;+ state.computed = computeRecordingPath(state.recordingDirectory, state.config);+ },+ customSubfolderNameChanged: (state, action: PayloadAction<string>) => {+ state.config.customSubfolderName = action.payload;+ state.computed = computeRecordingPath(state.recordingDirectory, state.config);+ },+ // Force recomputation of path (useful for timestamp updates)+ pathRecomputed: (state) => {+ state.computed = computeRecordingPath(state.recordingDirectory, state.config);+ },+ },+ extraReducers: (builder) => {+ builder+ .addCase(startRecording.fulfilled, (state, action) => {+ state.isRecording = true;+ state.recordingName = action.meta.arg.recordingName;+ state.recordingDirectory = action.meta.arg.recordingDirectory;+ state.startedAt = new Date().toISOString();+ state.duration = 0;+ })+ .addCase(stopRecording.fulfilled, (state) => {+ state.isRecording = false;+ state.recordingName = null;+ state.startedAt = null;+ state.duration = 0;+ });+ },+});++export const {+ recordingInfoUpdated,+ recordingDirectoryChanged,+ recordingDurationUpdated,+ configUpdated,+ useDelayStartToggled,+ delaySecondsChanged,+ useTimestampToggled,+ useIncrementToggled,+ currentIncrementChanged,+ currentIncrementIncremented,+ baseNameChanged,+ recordingTagChanged,+ createSubfolderToggled,+ customSubfolderNameChanged,+ pathRecomputed,+} = recordingSlice.actions;diff --git a/freemocap-ui/src/store/slices/recording/recording-thunks.ts b/freemocap-ui/src/store/slices/recording/recording-thunks.tsnew file mode 100644index 00000000..06730f18--- /dev/null+++ b/freemocap-ui/src/store/slices/recording/recording-thunks.ts@@ -0,0 +1,62 @@+import {createAsyncThunk} from '@reduxjs/toolkit';+import {z} from 'zod';+import {RootState} from '@/store/types';+import {serverUrls} from "@/services";++const RecordStartRequestSchema = z.object({+ recording_name: z.string(),+ recording_directory: z.string(),+ mic_device_index: z.number().default(-1),+});++interface StartRecordingParams {+ recordingName: string;+ recordingDirectory: string;+ micDeviceIndex?: number;+}++export const startRecording = createAsyncThunk<+ void,+ StartRecordingParams,+ { state: RootState }+>(+ 'recording/start',+ async ({ recordingName, recordingDirectory, micDeviceIndex = -1 }, { getState }) => {+ const state = getState();++ const payload = RecordStartRequestSchema.parse({+ recording_name: recordingName,+ recording_directory: recordingDirectory,+ mic_device_index: micDeviceIndex,+ });++ const response = await fetch(serverUrls.endpoints.pipelineRecordStart, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload),+ });++ if (!response.ok) {+ throw new Error(`Failed to start recording: ${response.statusText}`);+ }+ }+);++export const stopRecording = createAsyncThunk<+ void,+ void,+ { state: RootState }+>(+ 'recording/stop',+ async (_, { getState }) => {+ const state = getState();++ const response = await fetch(serverUrls.endpoints.pipelineRecordStop, {+ method: 'GET',+ });++ if (!response.ok) {+ throw new Error(`Failed to stop recording: ${response.statusText}`);+ }+ }+);diff --git a/freemocap-ui/src/store/slices/recording/recording-types.ts b/freemocap-ui/src/store/slices/recording/recording-types.tsnew file mode 100644index 00000000..353973cb--- /dev/null+++ b/freemocap-ui/src/store/slices/recording/recording-types.ts@@ -0,0 +1,38 @@+import {z} from 'zod';++export const RecordingConfigSchema = z.object({+ // Recording behavior settings+ useDelayStart: z.boolean(),+ delaySeconds: z.number(),++ // Naming settings+ useTimestamp: z.boolean(),+ useIncrement: z.boolean(),+ currentIncrement: z.number(),+ baseName: z.string(),+ recordingTag: z.string(),++ // Folder settings+ createSubfolder: z.boolean(),+ customSubfolderName: z.string(),+});++export const ComputedRecordingPathSchema = z.object({+ recordingName: z.string(),+ subfolderName: z.string(),+ fullRecordingPath: z.string(),+});++export const RecordingInfoSchema = z.object({+ isRecording: z.boolean(),+ recordingDirectory: z.string(),+ recordingName: z.string().nullable(),+ startedAt: z.string().nullable(),+ duration: z.number().nullable(),+ config: RecordingConfigSchema,+ computed: ComputedRecordingPathSchema,+});++export type RecordingConfig = z.infer<typeof RecordingConfigSchema>;+export type ComputedRecordingPath = z.infer<typeof ComputedRecordingPathSchema>;+export type RecordingInfo = z.infer<typeof RecordingInfoSchema>;diff --git a/freemocap-ui/src/store/slices/recordingInfoSlice.ts b/freemocap-ui/src/store/slices/recordingInfoSlice.tsdeleted file mode 100644index 8e521f0e..00000000--- a/freemocap-ui/src/store/slices/recordingInfoSlice.ts+++ /dev/null@@ -1,44 +0,0 @@-// recordingInfoSlice.ts-import {createSlice, PayloadAction} from '@reduxjs/toolkit'-import {z} from 'zod';------export const RecordingInfoSchema = z.object({- isRecording: z.boolean(),- recordingDirectory: z.string(),- recordingName: z.string().nullable(),-});--export type RecordingInfo = z.infer<typeof RecordingInfoSchema>;--interface RecordingStatusState {- currentRecordingInfo: RecordingInfo;-}--const initialState: RecordingStatusState = {- currentRecordingInfo: RecordingInfoSchema.parse({- isRecording: false,- recordingDirectory: '~/skellycam_data/recordings',- recordingName: null,- })-};--export const recordingInfoSlice = createSlice({- name: 'recordingStatus',- initialState,- reducers: {- setRecordingInfo: (state, action: PayloadAction<Partial<RecordingInfo>>) => {- console.log('Updating recording info:', action.payload);- state.currentRecordingInfo = {- ...state.currentRecordingInfo,- ...action.payload- };- },- }-});--export const {setRecordingInfo} = recordingInfoSlice.actions;-export default recordingInfoSlice.reducer;diff --git a/freemocap-ui/src/store/slices/theme/index.ts b/freemocap-ui/src/store/slices/theme/index.tsnew file mode 100644index 00000000..dd1ab93b--- /dev/null+++ b/freemocap-ui/src/store/slices/theme/index.ts@@ -0,0 +1,3 @@+export * from './theme-slice';+export * from './theme-types';+export * from './theme-selectors';diff --git a/freemocap-ui/src/store/slices/theme/theme-selectors.ts b/freemocap-ui/src/store/slices/theme/theme-selectors.tsnew file mode 100644index 00000000..f9d12576--- /dev/null+++ b/freemocap-ui/src/store/slices/theme/theme-selectors.ts@@ -0,0 +1,5 @@+import {RootState} from '../../types';++export const selectThemeMode = (state: RootState) => state.theme.mode;+export const selectSystemThemePreference = (state: RootState) =>+ state.theme.systemPreference;diff --git a/freemocap-ui/src/store/slices/theme/theme-slice.ts b/freemocap-ui/src/store/slices/theme/theme-slice.tsnew file mode 100644index 00000000..3cf18110--- /dev/null+++ b/freemocap-ui/src/store/slices/theme/theme-slice.ts@@ -0,0 +1,50 @@+import {createSlice, PayloadAction} from '@reduxjs/toolkit';+import {ThemeMode} from './theme-types';++const getInitialTheme = (): ThemeMode => {+ if (typeof window !== 'undefined') {+ const saved = localStorage.getItem('themeMode');+ if (saved === 'light' || saved === 'dark') {+ return saved;+ }+ // Check system preference+ if (window.matchMedia?.('(prefers-color-scheme: dark)').matches) {+ return 'dark';+ }+ }+ return 'dark';+};++interface ThemeState {+ mode: ThemeMode;+ systemPreference: ThemeMode | null;+}++const initialState: ThemeState = {+ mode: getInitialTheme(),+ systemPreference: null,+};++export const themeSlice = createSlice({+ name: 'theme',+ initialState,+ reducers: {+ themeModeSet: (state, action: PayloadAction<ThemeMode>) => {+ state.mode = action.payload;+ localStorage.setItem('themeMode', action.payload);+ },+ themeModeToggled: (state) => {+ state.mode = state.mode === 'dark' ? 'light' : 'dark';+ localStorage.setItem('themeMode', state.mode);+ },+ systemPreferenceUpdated: (state, action: PayloadAction<ThemeMode>) => {+ state.systemPreference = action.payload;+ },+ },+});++export const {+ themeModeSet,+ themeModeToggled,+ systemPreferenceUpdated,+} = themeSlice.actions;diff --git a/freemocap-ui/src/store/slices/theme/theme-types.ts b/freemocap-ui/src/store/slices/theme/theme-types.tsnew file mode 100644index 00000000..c5ad70d8--- /dev/null+++ b/freemocap-ui/src/store/slices/theme/theme-types.ts@@ -0,0 +1 @@+export type ThemeMode = 'light' | 'dark';diff --git a/freemocap-ui/src/store/slices/themeSlice.ts b/freemocap-ui/src/store/slices/themeSlice.tsdeleted file mode 100644index 43ecf136..00000000--- a/freemocap-ui/src/store/slices/themeSlice.ts+++ /dev/null@@ -1,50 +0,0 @@-// skellycam-ui/src/store/slices/themeSlice.ts-import {createSlice, PayloadAction} from "@reduxjs/toolkit";--export type ThemeMode = 'light' | 'dark';--interface ThemeState {- mode: ThemeMode;-}--// Get initial theme from localStorage or default to 'dark'-const getInitialTheme = (): ThemeMode => {- const savedTheme = localStorage.getItem('themeMode');- // Check if in browser environment (not SSR)- if (typeof window !== 'undefined') {- // Check for saved preference first- if (savedTheme && (savedTheme === 'light' || savedTheme === 'dark')) {- return savedTheme;- }- // Otherwise check system preference- if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {- return 'dark';- }- }- // Default to dark theme- return 'dark';-};--const initialState: ThemeState = {- mode: getInitialTheme(),-};--export const themeSlice = createSlice({- name: "theme",- initialState,- reducers: {- setThemeMode: (state, action: PayloadAction<ThemeMode>) => {- state.mode = action.payload;- // Save to localStorage for persistence- localStorage.setItem('themeMode', action.payload);- },- toggleThemeMode: (state) => {- state.mode = state.mode === 'dark' ? 'light' : 'dark';- // Save to localStorage for persistence- localStorage.setItem('themeMode', state.mode);- },- },-});--export const { setThemeMode, toggleThemeMode } = themeSlice.actions;-export default themeSlice.reducer;diff --git a/freemocap-ui/src/store/slices/videoLoadingSlice.ts b/freemocap-ui/src/store/slices/videoLoadingSlice.tsdeleted file mode 100644index 2c3b1067..00000000--- a/freemocap-ui/src/store/slices/videoLoadingSlice.ts+++ /dev/null@@ -1,55 +0,0 @@-// skellycam-ui/src/store/slices/videoLoadingSlice.ts-import { createSlice, PayloadAction } from '@reduxjs/toolkit';--interface VideoFile {- name: string;- path: string;-}--interface VideoLoadingState {- videoFolder: string;- videoFiles: VideoFile[];- isLoading: boolean;- error: string | null;-}--const initialState: VideoLoadingState = {- videoFolder: '',- videoFiles: [],- isLoading: false,- error: null,-};--export const videoLoadingSlice = createSlice({- name: 'videoLoading',- initialState,- reducers: {- setVideoFolder: (state, action: PayloadAction<string>) => {- state.videoFolder = action.payload;- },- setVideoFiles: (state, action: PayloadAction<VideoFile[]>) => {- state.videoFiles = action.payload;- },- setIsLoading: (state, action: PayloadAction<boolean>) => {- state.isLoading = action.payload;- },- setError: (state, action: PayloadAction<string | null>) => {- state.error = action.payload;- },- clearVideoData: (state) => {- state.videoFolder = '';- state.videoFiles = [];- state.error = null;- },- },-});--export const {- setVideoFolder,- setVideoFiles,- setIsLoading,- setError,- clearVideoData,-} = videoLoadingSlice.actions;--export default videoLoadingSlice.reducer;\ No newline at end of filediff --git a/freemocap-ui/src/store/slices/videos/index.ts b/freemocap-ui/src/store/slices/videos/index.tsnew file mode 100644index 00000000..99a7ab8b--- /dev/null+++ b/freemocap-ui/src/store/slices/videos/index.ts@@ -0,0 +1,4 @@+export * from './videos-slice';+export * from './videos-types';+export * from './videos-thunks';+export * from './videos-selectors';diff --git a/freemocap-ui/src/store/slices/videos/videos-selectors.ts b/freemocap-ui/src/store/slices/videos/videos-selectors.tsnew file mode 100644index 00000000..558c7fda--- /dev/null+++ b/freemocap-ui/src/store/slices/videos/videos-selectors.ts@@ -0,0 +1,20 @@+import {createSelector} from '@reduxjs/toolkit';+import {RootState} from '../../types';++export const selectVideoFolder = (state: RootState) => state.videos.folder;+export const selectVideoFiles = (state: RootState) => state.videos.files;+export const selectSelectedVideo = (state: RootState) => state.videos.selectedFile;+export const selectVideoPlaybackState = (state: RootState) => state.videos.playbackState;+export const selectVideoLoadingState = (state: RootState) => state.videos.isLoading;+export const selectVideoError = (state: RootState) => state.videos.error;++export const selectVideosByExtension = createSelector(+ [selectVideoFiles, (_: RootState, extension: string) => extension],+ (files, extension) =>+ files.filter((file: { name: string; }) => file.name.toLowerCase().endsWith(extension))+);++export const selectIsVideoPlaying = createSelector(+ [selectVideoPlaybackState],+ (playback) => playback.isPlaying+);diff --git a/freemocap-ui/src/store/slices/videos/videos-slice.ts b/freemocap-ui/src/store/slices/videos/videos-slice.tsnew file mode 100644index 00000000..d5c74b44--- /dev/null+++ b/freemocap-ui/src/store/slices/videos/videos-slice.ts@@ -0,0 +1,94 @@+import {createSlice, PayloadAction} from '@reduxjs/toolkit';+import {VideoFile, VideosState} from './videos-types';+import {loadVideos, openVideoFile, selectVideoLoadFolder,} from './videos-thunks';+++const initialState: VideosState = {+ folder: '',+ files: [],+ selectedFile: null,+ isLoading: false,+ error: null,+ playbackState: {+ isPlaying: false,+ currentTime: 0,+ duration: 0,+ volume: 1,+ playbackRate: 1,+ },+};++export const videosSlice = createSlice({+ name: 'videos',+ initialState,+ reducers: {+ videoFolderSet: (state, action: PayloadAction<string>) => {+ state.folder = action.payload;+ },+ videoFilesSet: (state, action: PayloadAction<VideoFile[]>) => {+ state.files = action.payload;+ },+ videoFileSelected: (state, action: PayloadAction<VideoFile | null>) => {+ state.selectedFile = action.payload;+ if (action.payload) {+ state.playbackState = {+ ...state.playbackState,+ isPlaying: false,+ currentTime: 0,+ duration: 0,+ };+ }+ },+ playbackStateUpdated: (+ state,+ action: PayloadAction<Partial<VideosState['playbackState']>>+ ) => {+ state.playbackState = { ...state.playbackState, ...action.payload };+ },+ videosCleared: () => initialState,+ },+ extraReducers: (builder) => {+ builder+ // Select folder+ .addCase(selectVideoLoadFolder.pending, (state) => {+ state.isLoading = true;+ state.error = null;+ })+ .addCase(selectVideoLoadFolder.fulfilled, (state, action) => {+ state.isLoading = false;+ if (action.payload) {+ state.folder = action.payload.folder;+ state.files = action.payload.files;+ }+ })+ .addCase(selectVideoLoadFolder.rejected, (state, action) => {+ state.isLoading = false;+ state.error = action.error.message || 'Failed to select folder';+ })+ // Load videos+ .addCase(loadVideos.pending, (state) => {+ state.isLoading = true;+ })+ .addCase(loadVideos.fulfilled, (state) => {+ state.isLoading = false;+ })+ .addCase(loadVideos.rejected, (state, action) => {+ state.isLoading = false;+ state.error = action.error.message || 'Failed to load videos';+ })+ // Open video file+ .addCase(openVideoFile.fulfilled, (state, action) => {+ if (!action.payload.success && action.payload.error) {+ state.error = action.payload.error.message || 'Failed to open video';+ }+ });+ },+});++export const {+ videoFolderSet,+ videoFilesSet,+ videoFileSelected,+ playbackStateUpdated,+ videosCleared,+} = videosSlice.actions;diff --git a/freemocap-ui/src/store/slices/videos/videos-thunks.ts b/freemocap-ui/src/store/slices/videos/videos-thunks.tsnew file mode 100644index 00000000..26e93e23--- /dev/null+++ b/freemocap-ui/src/store/slices/videos/videos-thunks.ts@@ -0,0 +1,80 @@+import {createAsyncThunk} from '@reduxjs/toolkit';+import {electronIpc} from "@/services/electron-ipc/electron-ipc";+import {VideoFile} from "@/store";++const VIDEO_EXTENSIONS = ['.mp4', '.avi', '.mov', '.mkv', '.webm'];++interface FolderEntry {+ name: string;+ path: string;+ isDirectory: boolean;+ isFile: boolean;+ size: number;+ modified: string | number | Date;+}++export const selectVideoLoadFolder = createAsyncThunk<+ { folder: string; files: VideoFile[] } | null+>('videos/selectFolder', async () => {+ if (!electronIpc) {+ throw new Error('Electron API not available');+ }++ const selectedFolder = await electronIpc.fileSystem.selectDirectory.mutate();+ if (!selectedFolder) return null;++ const entries: FolderEntry[] = await electronIpc.fileSystem.getFolderContents.query({+ path: selectedFolder,+ });++ const videoFiles = (entries ?? [])+ .filter(+ (item) =>+ item.isFile &&+ VIDEO_EXTENSIONS.some((ext) => item.name.toLowerCase().endsWith(ext))+ )+ .map((file) => ({+ name: file.name,+ path: file.path,+ size: file.size,+ }));++ return { folder: selectedFolder, files: videoFiles };+});++export const loadVideos = createAsyncThunk<+ { success: boolean },+ { folder: string; files: VideoFile[] }+>('videos/load', async ({ folder }) => {+ if (!electronIpc) {+ throw new Error('Electron API not available');+ }++ const success = await electronIpc.fileSystem.openFolder.mutate({ path: folder });+ if (!success) {+ throw new Error('Failed to open folder');+ }+ return { success: true };+});++export const openVideoFile = createAsyncThunk<+ { success: boolean; error?: Error },+ string+>('videos/openFile', async (filePath) => {+ if (!electronIpc) {+ return { success: false, error: new Error('Electron API not available') };+ }++ try {+ const idx = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'));+ const folderPath = idx >= 0 ? filePath.substring(0, idx) : filePath;+ await electronIpc.fileSystem.openFolder.mutate({ path: folderPath });+ return { success: true };+ } catch (error) {+ console.error('Failed to open video file:', error);+ return {+ success: false,+ error: error instanceof Error ? error : new Error('Unknown error'),+ };+ }+});diff --git a/freemocap-ui/src/store/slices/videos/videos-types.ts b/freemocap-ui/src/store/slices/videos/videos-types.tsnew file mode 100644index 00000000..570b86f8--- /dev/null+++ b/freemocap-ui/src/store/slices/videos/videos-types.ts@@ -0,0 +1,22 @@+export interface VideoFile {+ name: string;+ path: string;+ size?: number;+ duration?: number;+ thumbnail?: string;+}++export interface VideosState {+ folder: string;+ files: VideoFile[];+ selectedFile: VideoFile | null;+ isLoading: boolean;+ error: string | null;+ playbackState: {+ isPlaying: boolean;+ currentTime: number;+ duration: number;+ volume: number;+ playbackRate: number;+ };+}diff --git a/freemocap-ui/src/store/store.ts b/freemocap-ui/src/store/store.tsnew file mode 100644index 00000000..1f289268--- /dev/null+++ b/freemocap-ui/src/store/store.ts@@ -0,0 +1,26 @@+import {configureStore} from "@reduxjs/toolkit";+import {framerateSlice} from "./slices/framerate/framerate-slice";+import {cameraSlice} from "./slices/cameras/cameras-slice";+import {recordingSlice} from "./slices/recording/recording-slice";+import {themeSlice} from "./slices/theme/theme-slice";+import {videosSlice} from "./slices/videos/videos-slice";+import {logRecordsSlice} from "./slices/log-records/log-records-slice";+import {pipelineSlice} from "./slices/pipeline/pipeline-slice";+import {calibrationSlice} from "@/store/slices/calibration/calibration-slice";+import {mocapSlice} from "@/store/slices/mocap/mocap-slice";++export const store = configureStore({+ reducer: {+ cameras: cameraSlice.reducer,+ recording: recordingSlice.reducer,+ framerate: framerateSlice.reducer,+ logs: logRecordsSlice.reducer,+ theme: themeSlice.reducer,+ videos: videosSlice.reducer,+ pipeline: pipelineSlice.reducer,+ calibration: calibrationSlice.reducer,+ mocap: mocapSlice.reducer,+ }+});++diff --git a/freemocap-ui/src/store/thunks/close-cameras-thunks.ts b/freemocap-ui/src/store/thunks/close-cameras-thunks.tsdeleted file mode 100644index 1e9bd369..00000000--- a/freemocap-ui/src/store/thunks/close-cameras-thunks.ts+++ /dev/null@@ -1,31 +0,0 @@-import {createAsyncThunk} from '@reduxjs/toolkit';-import {urlService} from "@/config/appUrlService";----export const closeCameras = createAsyncThunk(- 'cameras/close',- async () => {- console.log(`Closing cameras...`);- try {- const closeCamerasURL = urlService.getHttpEndpointUrls().closeAll;--- console.log(`Sending close request to ${closeCamerasURL}`);- const response = await fetch(closeCamerasURL, {- method: 'DELETE',--- });-- if (response.ok) {- console.log('Cameras closed successfully');- } else {- throw new Error(`Failed to close cameras: ${response.statusText}`);- }- } catch (error) {- console.error('Recording start failed:', error);- throw error;- }- }-);diff --git a/freemocap-ui/src/store/thunks/connect-pipeline-thunk.ts b/freemocap-ui/src/store/thunks/connect-pipeline-thunk.tsdeleted file mode 100644index 2231263d..00000000--- a/freemocap-ui/src/store/thunks/connect-pipeline-thunk.ts+++ /dev/null@@ -1,103 +0,0 @@-import {createAsyncThunk} from "@reduxjs/toolkit";-import {selectConfigsForSelectedCameras, setError, setLoading} from "@/store/slices/cameras-slices/camerasSlice";-import {urlService} from "@/config/appUrlService";--export const connectPipelineThunk = createAsyncThunk(- 'pipeline/connect',- async (_, { dispatch, getState }) : Promise<string> => {- const state = getState() as any;- const cameraConfigs = selectConfigsForSelectedCameras(state);-- if (!cameraConfigs || Object.keys(cameraConfigs).length === 0) {- const errorMsg = 'No camera configurations available to connect the pipeline.';- console.error(errorMsg);- dispatch(setError(errorMsg));- return Promise.reject(new Error(errorMsg));- }-- const cameraIds = Object.keys(cameraConfigs || {});-- dispatch(setLoading(true));- const connectUrl = urlService.getHttpEndpointUrls().connectPipeline;-- const payload = {- camera_ids: cameraIds,- };-- const requestBody = JSON.stringify(payload, null, 2);- try {- console.log(`Connecting to pipeline at ${connectUrl} with body:`, requestBody);- const response = await fetch(connectUrl, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- },- body: requestBody- });-- const data = await response.json();-- if (!response.ok) {- let errorMsg = 'Failed to connect to pipeline.';- if (data.detail) {- errorMsg += ` Details: ${JSON.stringify(data.detail)}`;- }- console.error('Error:', errorMsg);- dispatch(setError(errorMsg));- throw new Error(errorMsg);- }-- dispatch(setError(null));- console.log(`Connected to pipeline successfully: ${JSON.stringify(data, null, 2)}`);- return data.pipeline_id as string;- } catch (error) {- const errorMessage = error instanceof Error- ? `Failed to connect to pipeline: ${error.message}`- : 'Failed to connect to pipeline: Unknown error';-- dispatch(setError(errorMessage));- console.error(errorMessage, error);- throw error;- } finally {- dispatch(setLoading(false));- }- }-);--export const disconnectPipelineThunk = createAsyncThunk(- 'pipeline/disconnect',- async (_, { dispatch}) : Promise<void> => {- dispatch(setLoading(true));- const disconnectUrl = urlService.getHttpEndpointUrls().disconnectPipeline;-- try {- console.log(`Sending disconnect request to ${disconnectUrl}`);- const response = await fetch(disconnectUrl, {method: 'GET'});-- const data = await response.json();-- if (!response.ok) {- let errorMsg = 'Failed to disconnect from pipeline.';- if (data.detail) {- errorMsg += ` Details: ${JSON.stringify(data.detail)}`;- }- console.error('Error:', errorMsg);- dispatch(setError(errorMsg));- throw new Error(errorMsg);- }-- dispatch(setError(null));- console.log(`Disconnected from pipeline successfully: ${JSON.stringify(data, null, 2)}`);- } catch (error) {- const errorMessage = error instanceof Error- ? `Failed to disconnect from pipeline: ${error.message}`- : 'Failed to disconnect from pipeline: Unknown error';-- dispatch(setError(errorMessage));- console.error(errorMessage, error);- throw error;- } finally {- dispatch(setLoading(false));- }- }-);diff --git a/freemocap-ui/src/store/thunks/connect-to-cameras-thunk.ts b/freemocap-ui/src/store/thunks/connect-to-cameras-thunk.tsdeleted file mode 100644index 0cd91eb7..00000000--- a/freemocap-ui/src/store/thunks/connect-to-cameras-thunk.ts+++ /dev/null@@ -1,68 +0,0 @@-import {createAsyncThunk} from "@reduxjs/toolkit";-import {- selectConfigsForSelectedCameras,- setError,- setLoading,- updateCameraConfigs-} from "@/store/slices/cameras-slices/camerasSlice";-import {CameraConfig} from "@/store/slices/cameras-slices/camera-types";-import {urlService} from "@/config/appUrlService";--export const connectToCameras = createAsyncThunk(- 'cameras/connect',- async (_, { dispatch, getState }) => {- const state = getState() as any;- const cameraConfigs = selectConfigsForSelectedCameras(state);-- if (!cameraConfigs || Object.keys(cameraConfigs).length === 0) {- const errorMsg = 'No camera devices selected for connection';- dispatch(setError(errorMsg));- throw new Error(errorMsg);- }-- dispatch(setLoading(true));- const connectUrl = urlService.getHttpEndpointUrls().createGroup;-- const payload = {- camera_configs: cameraConfigs- };-- const requestBody = JSON.stringify(payload, null, 2);- try {- console.log(`Connecting to cameras at ${connectUrl} with body:`, requestBody);- const response = await fetch(connectUrl, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- },- body: requestBody- });-- // Parse the response body- const data = await response.json();-- // Check for different error status codes- if (!response.ok) {- let errorMsg = 'Failed to connect to cameras';- console.error('Errors:', data.detail);- dispatch(setError(errorMsg));- throw new Error(errorMsg);- }-- dispatch(setError(null));- dispatch(updateCameraConfigs(data.camera_configs as Record<string, CameraConfig>));- return data;- } catch (error) {- // Handle network errors and JSON parsing errors- const errorMessage = error instanceof Error- ? `Failed to connect to cameras: ${error.message}`- : 'Failed to connect to cameras: Unknown error';-- dispatch(setError(errorMessage));- console.error(errorMessage, error);- throw error;- } finally {- dispatch(setLoading(false));- }- }-);diff --git a/freemocap-ui/src/store/thunks/detect-cameras-thunks/detect-cameras-client-thunks.ts b/freemocap-ui/src/store/thunks/detect-cameras-thunks/detect-cameras-client-thunks.tsdeleted file mode 100644index 90903fdc..00000000--- a/freemocap-ui/src/store/thunks/detect-cameras-thunks/detect-cameras-client-thunks.ts+++ /dev/null@@ -1,132 +0,0 @@-// skellycam-ui/src/store/thunks/camera-thunks.ts-import {createAsyncThunk} from '@reduxjs/toolkit';-import {setAvailableCameras, setCameraStatus, setError, setLoading} from "@/store/slices/cameras-slices/camerasSlice";-import {- CAMERA_DEFAULT_CONSTRAINTS,- CameraDevice,- createDefaultCameraConfig-} from "@/store/slices/cameras-slices/camera-types";-import {RootState} from "@/store/AppStateStore";--const isVirtualCamera = (label: string): boolean => {- const virtualCameraKeywords = ['virtual'];- return virtualCameraKeywords.some(keyword => label.toLowerCase().includes(keyword));-};--export const validateVideoStream = async (deviceId: string): Promise<{ isValid: boolean; status: string }> => {- try {- const stream = await navigator.mediaDevices.getUserMedia({- video: {- deviceId: { exact: deviceId }- }- });-- const video = document.createElement('video');- video.srcObject = stream;- return new Promise((resolve) => {- video.onloadedmetadata = () => {- if (video.videoWidth > 0 && video.videoHeight > 0) {- resolve({ isValid: true, status: 'AVAILABLE' });- } else {- resolve({ isValid: false, status: 'ERROR' });- }- stream.getTracks().forEach(track => track.stop());- video.remove();- };-- video.onerror = () => {- stream.getTracks().forEach(track => track.stop());- video.remove();- resolve({ isValid: false, status: 'ERROR' });- };-- setTimeout(() => {- stream.getTracks().forEach(track => track.stop());- video.remove();- resolve({ isValid: false, status: 'ERROR' });- }, 3000);- });- } catch (error) {- console.warn(`Failed to validate device ${deviceId}:`, error);-- if (error instanceof DOMException) {- if (error.name === 'NotReadableError' ||- error.message.includes('in use') ||- error.message.includes('busy') ||- error.message.includes('already in use')) {- return { isValid: false, status: 'IN_USE' };- }- }-- return { isValid: false, status: 'ERROR' };- }-};--export const detectCameraDevices = createAsyncThunk(- 'cameras/detectBrowserDevices',- async (filterVirtual: boolean = true, { dispatch, getState }) => {- try {- dispatch(setLoading(true));- const devices = await navigator.mediaDevices.enumerateDevices();-- const cameras = devices.filter(({ kind }) => kind === "videoinput");- if (cameras.length === 0) {- dispatch(setError('No camera devices found'));- console.warn('No camera devices found');- return [];- }- console.log(`Found ${cameras.length} camera(s) `, cameras);-- const state = getState() as RootState;- const existingCameras = state.cameras.cameras;-- const initialFiltered = filterVirtual ?- cameras.filter(({ label }) => !isVirtualCamera(label)) :- cameras;- console.log(`After removing virtual cameras, ${initialFiltered.length} camera(s) remain`, initialFiltered);-- Object.keys(existingCameras).forEach(cameraId => {- const stillExists = initialFiltered.some(device => device.deviceId.slice(-5) === cameraId);- if (!stillExists) {- dispatch(setCameraStatus({ cameraId, status: 'UNAVAILABLE' }));- }- });-- const validatedCameras: CameraDevice[] = [];- for (const camera of initialFiltered) {- const cameraId = camera.deviceId.slice(-5);- const validationResult = await validateVideoStream(camera.deviceId);- const existingCamera = existingCameras[cameraId];- const newCamera: CameraDevice = {- ...camera.toJSON(),- index: existingCamera?.index ?? validatedCameras.length,- cameraId,- selected: existingCamera?.selected ?? (validationResult.status === 'AVAILABLE'),- status: validationResult.status,- constraints: CAMERA_DEFAULT_CONSTRAINTS,- config: existingCamera?.config ||- createDefaultCameraConfig(- existingCamera?.index ?? validatedCameras.length,- camera.label,- cameraId- )- };-- validatedCameras.push(newCamera);- if (!validationResult.isValid) {- console.warn(`Camera ${camera.label} validation status: ${validationResult.status}`);- }- }- console.log(`After validation, ${validatedCameras.length} camera(s) processed`, validatedCameras);-- dispatch(setAvailableCameras(validatedCameras));- dispatch(setError(null));- return validatedCameras;- } catch (error) {- dispatch(setError('Failed to detect browser devices'));- console.error('Error detecting browser devices:', error);- } finally {- dispatch(setLoading(false));- }- }-);diff --git a/freemocap-ui/src/store/thunks/detect-cameras-thunks/detect-cameras-server-thunk.ts b/freemocap-ui/src/store/thunks/detect-cameras-thunks/detect-cameras-server-thunk.tsdeleted file mode 100644index a2955563..00000000--- a/freemocap-ui/src/store/thunks/detect-cameras-thunks/detect-cameras-server-thunk.ts+++ /dev/null@@ -1,90 +0,0 @@-import {createAsyncThunk} from "@reduxjs/toolkit";-import {- setError,- setLoading,- setAvailableCameras,- setCameraStatus-} from "@/store/slices/cameras-slices/camerasSlice";-import {- CAMERA_DEFAULT_CONSTRAINTS,- CameraDevice,- createDefaultCameraConfig-} from "@/store/slices/cameras-slices/camera-types";-import {RootState} from "@/store/AppStateStore";-import {urlService} from "@/config/appUrlService";--export const detectCameraDevices = createAsyncThunk<- CameraDevice[]- >('cameras/detectServer',- async (args, { dispatch, getState }) => {- const filterVirtual = true;- dispatch(setLoading(true));-- try {- const connectUrl = urlService.getHttpEndpointUrls().detectCameras;-- console.log(`Detecting cameras at ${connectUrl}`);- const response = await fetch(connectUrl, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- },- body: JSON.stringify({ filterVirtual }),- });-- const data = await response.json();- const serverCameras = data.cameras;-- // Convert server cameras to CameraDevice objects- const validatedCameras: CameraDevice[] = [];- const state = getState() as RootState;- const existingCameras = state.cameras.cameras;-- Object.keys(existingCameras).forEach(cameraId => {- const stillExists = serverCameras.some((device: { index: number; }) => device.index === parseInt(cameraId));- if (!stillExists) {- dispatch(setCameraStatus({ cameraId, status: 'UNAVAILABLE' }));- }- });-- for (const serverCamera of serverCameras) {- const existingCamera = existingCameras[serverCamera.index];- const newCamera: CameraDevice = {- index: serverCamera.index,- deviceId: serverCamera.vendor_id?.toString() + serverCamera.product_id?.toString(),- cameraId: serverCamera.index,- selected: true, // Select all cameras by default- status: 'AVAILABLE', // TODO: do we want to validate the cameras again? JSM - yes, we want to track camera status (somehow or another) to show it as "available, in use, unavailable, error etc")- label: serverCamera.name,- groupId: '', // TODO: not sure if this needs to be passed form the server? JSM - this is originally to hold the 'groupId' returned by MediaDevices.enumerateDevices(). I don't think `cv2_enumerate_devices` returns it? I don't really know what it refers to tbh- kind: 'videoinput',- constraints: CAMERA_DEFAULT_CONSTRAINTS,- config: existingCamera?.config ||- createDefaultCameraConfig(- serverCamera.index,- serverCamera.name,- serverCamera.index.toString()- )- };-- validatedCameras.push(newCamera);- }-- console.log(`After validation, ${validatedCameras.length} camera(s) processed`, validatedCameras);- dispatch(setAvailableCameras(validatedCameras));- dispatch(setError(null));- return validatedCameras;- } catch (error) {- // Handle network errors and JSON parsing errors- const errorMessage = error instanceof Error- ? `Failed to detect cameras: ${error.message}`- : 'Failed to detect cameras: Unknown error';-- dispatch(setError(errorMessage));- console.error(errorMessage, error);- throw error;- } finally {- dispatch(setLoading(false));- }- }-);diff --git a/freemocap-ui/src/store/thunks/pause-unpause-thunk.ts b/freemocap-ui/src/store/thunks/pause-unpause-thunk.tsdeleted file mode 100644index ea5dc265..00000000--- a/freemocap-ui/src/store/thunks/pause-unpause-thunk.ts+++ /dev/null@@ -1,12 +0,0 @@-import {urlService} from "@/config/appUrlService";--export const pauseUnpauseThunk = async () => {- const pauseUnpauseUrl = urlService.getHttpEndpointUrls().pauseUnpauseCameras;- const response = await fetch(pauseUnpauseUrl, {method: 'GET'});-- if (!response.ok) {- throw new Error(`HTTP error! status: ${response.status}`);- }-- return response;-};\ No newline at end of filediff --git a/freemocap-ui/src/store/thunks/start-stop-recording-thunks.ts b/freemocap-ui/src/store/thunks/start-stop-recording-thunks.tsdeleted file mode 100644index 1dea1f82..00000000--- a/freemocap-ui/src/store/thunks/start-stop-recording-thunks.ts+++ /dev/null@@ -1,80 +0,0 @@-// recording-thunks.ts-import {createAsyncThunk} from '@reduxjs/toolkit';-import {z} from 'zod';-import {setRecordingInfo} from "@/store/slices/recordingInfoSlice";-import {urlService} from "@/config/appUrlService";--const RecordStartRequestSchema = z.object({- recording_name: z.string(),- recording_directory: z.string(),- mic_device_index: z.number().default(-1),-});--type StartRecordingParams = {- recordingName: string;- recordingDirectory: string;-};--export const startRecording = createAsyncThunk<void, StartRecordingParams>(- 'appState/startRecording',- async ({recordingName, recordingDirectory}, {dispatch,}) => {- console.log(`Starting recording with name: ${recordingName} in directory: ${recordingDirectory}`);- try {- const recStartUrl = urlService.getHttpEndpointUrls().startRecording;-- const requestPayload = RecordStartRequestSchema.parse({- recording_name: recordingName,- recording_directory: recordingDirectory,-- });- console.log(`Request payload: ${JSON.stringify(requestPayload, null, 2)}`);- const response = await fetch(recStartUrl, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- },- body: JSON.stringify(requestPayload),- });-- if (response.ok) {- dispatch(setRecordingInfo({- isRecording: true,- recordingName,- recordingDirectory,- }));- console.log('Recording started successfully');- } else {- throw new Error(`Failed to start recording: ${response.statusText}`);- }- } catch (error) {- console.error('Recording start failed:', error);- throw error;- }- }-);--export const stopRecording = createAsyncThunk<void, void>(- 'appState/stopRecording',- async (_, {dispatch}) => {- console.log('Stopping recording...');- try {- const recStopUrl = urlService.getHttpEndpointUrls().stopRecording;- const response = await fetch(recStopUrl, {- method: 'GET',- });-- if (response.ok) {- dispatch(setRecordingInfo({- isRecording: false,- recordingName: null,- }));- console.log('Recording stopped successfully');- } else {- throw new Error(`Failed to stop recording: ${response.statusText}`);- }- } catch (error) {- console.error('Recording stop failed:', error);- throw error;- }- }-);diff --git a/freemocap-ui/src/store/thunks/update-camera-configs-thunk.ts b/freemocap-ui/src/store/thunks/update-camera-configs-thunk.tsdeleted file mode 100644index 6c6fb52b..00000000--- a/freemocap-ui/src/store/thunks/update-camera-configs-thunk.ts+++ /dev/null@@ -1,59 +0,0 @@-import {createAsyncThunk} from "@reduxjs/toolkit";-import {- selectCameraById,- selectConfigsForSelectedCameras,- setError,- setLoading, updateCameraConfig, updateCameraConfigs-} from "@/store/slices/cameras-slices/camerasSlice";-import { CameraConfig } from "../slices/cameras-slices/camera-types";-import {urlService} from "@/config/appUrlService";-export const updateCameraConfigsThunk = createAsyncThunk(- 'camera/update',- async (_, { dispatch, getState }) => {- const state = getState() as any;- dispatch(setLoading(true));- const connectUrl = urlService.getHttpEndpointUrls().updateConfigs;-- const payload = {- camera_configs: selectConfigsForSelectedCameras(state)- };-- const requestBody = JSON.stringify(payload, null, 2);- try {- console.log(`Updating Camera Configs at ${connectUrl} with request body keys:`, Object.keys(payload));- const response = await fetch(connectUrl, {- method: 'PUT',- headers: {- 'Content-Type': 'application/json',- },- body: requestBody- });-- // Parse the response body- const data = await response.json();-- // Check for different error status codes- if (!response.ok) {- let errorMsg = 'Failed to connect to cameras';- console.error('Errors:', data.detail);- dispatch(setError(errorMsg));- throw new Error(errorMsg);- }- // Convert the response data to a Record<string, CameraConfig>- dispatch(updateCameraConfigs(data.camera_configs as Record<string, CameraConfig>));- dispatch(setError(null));- return data;- } catch (error) {- // Handle network errors and JSON parsing errors- const errorMessage = error instanceof Error- ? `Failed to connect to cameras: ${error.message}`- : 'Failed to connect to cameras: Unknown error';-- dispatch(setError(errorMessage));- console.error(errorMessage, error);- throw error;- } finally {- dispatch(setLoading(false));- }- }-);diff --git a/freemocap-ui/src/store/thunks/video-loading-thunks.ts b/freemocap-ui/src/store/thunks/video-loading-thunks.tsdeleted file mode 100644index a9104925..00000000--- a/freemocap-ui/src/store/thunks/video-loading-thunks.ts+++ /dev/null@@ -1,92 +0,0 @@-// skellycam-ui/src/store/thunks/video-loading-thunks.ts-import { createAsyncThunk } from '@reduxjs/toolkit';-import {- setVideoFolder,- setVideoFiles,- setIsLoading,- setError-} from '../slices/videoLoadingSlice';--const VIDEO_EXTENSIONS = ['.mp4', '.avi', '.mov', '.mkv', '.webm'];-export const selectVideoFolder = createAsyncThunk(- 'videoLoading/selectFolder',- async (_, { dispatch }) => {- try {- dispatch(setIsLoading(true));- dispatch(setError(null));-- const selectedFolder = await window.electronAPI.selectDirectory();-- if (!selectedFolder) {- return null;- }- dispatch(setVideoFolder(selectedFolder));-- const folderContents = await window.electronAPI.getFolderContents(selectedFolder);-- if (folderContents.error) {- throw new Error(`Failed to read folder contents: ${folderContents.error}`);- }-- const videoFiles = folderContents.contents- ?.filter(item =>- item.isFile &&- VIDEO_EXTENSIONS.some(ext =>- item.name.toLowerCase().endsWith(ext)- )- )- .map(file => ({- name: file.name,- path: file.path- })) || [];- dispatch(setVideoFiles(videoFiles));-- return {- folder: selectedFolder,- files: videoFiles- };- } catch (error) {- dispatch(setError(error instanceof Error ? error.message : 'Unknown error'));- throw error;- } finally {- dispatch(setIsLoading(false));- }- }-);--export const loadVideos = createAsyncThunk(- 'videoLoading/loadVideos',- async ({ folder, files }: { folder: string, files: { name: string, path: string }[] }, { dispatch }) => {- try {- dispatch(setIsLoading(true));- dispatch(setError(null));-- const success = await window.electronAPI.openFolder(folder);-- if (!success) {- throw new Error('Failed to open folder');- }- return { success: true };- } catch (error) {- dispatch(setError(error instanceof Error ? error.message : 'Unknown error'));- throw error;- } finally {- dispatch(setIsLoading(false));- }- }-);--export const openVideoFile = createAsyncThunk(- 'videoLoading/openVideoFile',- async (filePath: string, { dispatch }) => {- try {- const folderPath = filePath.substring(0, filePath.lastIndexOf('/'));- await window.electronAPI.openFolder(folderPath);-- return { success: true };- } catch (error) {- console.error('Failed to open video file:', error);- return { success: false, error };- }- }-);diff --git a/freemocap-ui/src/store/types.ts b/freemocap-ui/src/store/types.tsnew file mode 100644index 00000000..be6112cd--- /dev/null+++ b/freemocap-ui/src/store/types.ts@@ -0,0 +1,11 @@+import {store} from './store';+import {Action, ThunkAction} from '@reduxjs/toolkit';++export type RootState = ReturnType<typeof store.getState>;+export type AppDispatch = typeof store.dispatch;+export type AppThunk<ReturnType = void> = ThunkAction<+ ReturnType,+ RootState,+ unknown,+ Action<string>+>;diff --git a/freemocap-ui/src/types/electron-updater.d.ts b/freemocap-ui/src/types/electron-updater.d.tsdeleted file mode 100644index 5b26aba3..00000000--- a/freemocap-ui/src/types/electron-updater.d.ts+++ /dev/null@@ -1,10 +0,0 @@-interface VersionInfo {- update: boolean- version: string- newVersion?: string-}--interface ErrorType {- message: string- error: Error-}diff --git a/freemocap-ui/src/types/electron.d.ts b/freemocap-ui/src/types/electron.d.tsdeleted file mode 100644index 87f0a72d..00000000--- a/freemocap-ui/src/types/electron.d.ts+++ /dev/null@@ -1,34 +0,0 @@-declare global {- interface Window {- electronAPI: {- selectDirectory: () => Promise<string | null>;- openFolder: (folderPath: string) => Promise<boolean>;- getHomeDirectory: () => Promise<string>;- expandPath: (path: string) => Promise<string>;- getFolderContents: (folderPath: string) => Promise<{- path: string;- contents?: Array<{- name: string;- path: string;- isDirectory?: boolean;- isFile?: boolean;- size?: number;- created?: Date;- modified?: Date;- accessed?: Date;- error?: string;- }>;- error?: string;- }>;- }- ipcRenderer: {- on: (channel: string, func: (...args: any[]) => void) => void;- off: (channel: string, func: (...args: any[]) => void) => void;- send: (channel: string, ...args: any[]) => void;- invoke: (channel: string, ...args: any[]) => Promise<any>;- }- }-}--// This export is needed to make this a module-export {}\ No newline at end of filediff --git a/freemocap-ui/src/vite-env.d.ts b/freemocap-ui/src/vite-env.d.tsindex 53361d32..c574b80c 100644--- a/freemocap-ui/src/vite-env.d.ts+++ b/freemocap-ui/src/vite-env.d.ts@@ -1,6 +1,6 @@/// <reference types="vite/client" />interface Window {- // expose in the `electron/preload/index.ts`- ipcRenderer: import('electron').IpcRenderer+ // expose in the `electron/preload/index.ts`+ ipcRenderer: import('electron').IpcRenderer}diff --git a/freemocap-ui/tsconfig.json b/freemocap-ui/tsconfig.jsonindex e8891723..b9883eaa 100644--- a/freemocap-ui/tsconfig.json+++ b/freemocap-ui/tsconfig.json@@ -2,7 +2,11 @@"compilerOptions": {"target": "ESNext","useDefineForClassFields": true,- "lib": ["DOM", "DOM.Iterable", "ESNext"],+ "lib": [+ "DOM",+ "DOM.Iterable",+ "ESNext"+ ],"allowJs": false,"skipLibCheck": true,"esModuleInterop": false,@@ -20,8 +24,16 @@"@/*": ["src/*"]- },+ }},- "include": ["src", "electron", "src/types/**/*" ],- "references": [{ "path": "./tsconfig.node.json" }]+ "include": [+ "src",+ "old_electron",+ "src/lib/**/*"+ ],+ "references": [+ {+ "path": "./tsconfig.node.json"+ }+ ]}diff --git a/freemocap-ui/tsconfig.node.json b/freemocap-ui/tsconfig.node.jsonindex 1e7e7d60..46b61ba0 100644--- a/freemocap-ui/tsconfig.node.json+++ b/freemocap-ui/tsconfig.node.json@@ -6,5 +6,8 @@"resolveJsonModule": true,"allowSyntheticDefaultImports": true},- "include": ["vite.config.ts", "package.json"]+ "include": [+ "vite.config.ts",+ "package.json"+ ]}diff --git a/freemocap-ui/vite.config.ts b/freemocap-ui/vite.config.tsindex 77d49bc2..07031ab9 100644--- a/freemocap-ui/vite.config.ts+++ b/freemocap-ui/vite.config.ts@@ -6,78 +6,78 @@ import electron from 'vite-plugin-electron/simple'import pkg from './package.json'// https://vitejs.dev/config/-export default defineConfig(({ command }) => {- rmSync('dist-electron', { recursive: true, force: true })+export default defineConfig(({command}) => {+ rmSync('dist-electron', {recursive: true, force: true})- const isServe = command === 'serve'- const isBuild = command === 'build'- const sourcemap = isServe || !!process.env.VSCODE_DEBUG+ const isServe = command === 'serve'+ const isBuild = command === 'build'+ const sourcemap = isServe || !!process.env.VSCODE_DEBUG- return {- resolve: {- alias: {- '@': path.join(__dirname, 'src')- },- },- plugins: [- react(),- electron({- main: {- // Shortcut of `build.lib.entry`- entry: 'electron/main/index.ts',- onstart(args) {- if (process.env.VSCODE_DEBUG) {- console.log(/* For `.vscode/.debug.script.mjs` */'[startup] Electron App')- } else {- args.startup()- }- },- vite: {- build: {- sourcemap,- minify: isBuild,- outDir: 'dist-electron/main',- rollupOptions: {- external: Object.keys('dependencies' in pkg ? pkg.dependencies : {}),- },- },- },- },- preload: {- // Shortcut of `build.rollupOptions.input`.- // Preload scripts may contain Web assets, so use the `build.rollupOptions.input` instead `build.lib.entry`.- input: 'electron/preload/index.ts',- vite: {- build: {- sourcemap: sourcemap ? 'inline' : undefined, // #332- minify: isBuild,- outDir: 'dist-electron/preload',- rollupOptions: {- external: Object.keys('dependencies' in pkg ? pkg.dependencies : {}),- },+ return {+ resolve: {+ alias: {+ '@': path.join(__dirname, 'src')},- },},- // Ployfill the Electron and Node.js API for Renderer process.- // If you want use Node.js in Renderer process, the `nodeIntegration` needs to be enabled in the Main process.- // See ๐ https://github.com/electron-vite/vite-plugin-electron-renderer- renderer: {},- }),- ],- optimizeDeps: {- exclude: ["@ffmpeg/ffmpeg", "@ffmpeg/util"],- },- server: process.env.VSCODE_DEBUG && (() => {- const url = new URL(pkg.debug.env.VITE_DEV_SERVER_URL)- return {- host: url.hostname,- port: +url.port,- headers: {- "Cross-Origin-Opener-Policy": "same-origin",- "Cross-Origin-Embedder-Policy": "require-corp",+ plugins: [+ react(),+ electron({+ main: {+ // Shortcut of `build.lib.entry`+ entry: 'electron/main/index.ts',+ onstart(args) {+ if (process.env.VSCODE_DEBUG) {+ console.log(/* For `.vscode/.debug.script.mjs` */'[startup] Electron App')+ } else {+ args.startup()+ }+ },+ vite: {+ build: {+ sourcemap,+ minify: isBuild,+ outDir: 'dist-electron/main',+ rollupOptions: {+ external: Object.keys('dependencies' in pkg ? pkg.dependencies : {}),+ },+ },+ },+ },+ preload: {+ // Shortcut of `build.rollupOptions.input`.+ // Preload scripts may contain Web assets, so use the `build.rollupOptions.input` instead `build.lib.entry`.+ input: 'electron/preload/index.ts',+ vite: {+ build: {+ sourcemap: sourcemap ? 'inline' : undefined, // #332+ minify: isBuild,+ outDir: 'dist-electron/preload',+ rollupOptions: {+ external: Object.keys('dependencies' in pkg ? pkg.dependencies : {}),+ },+ },+ },+ },+ // Ployfill the Electron and Node.js API for Renderer process.+ // If you want use Node.js in Renderer process, the `nodeIntegration` needs to be enabled in the Main process.+ // See ๐ https://github.com/electron-vite/vite-plugin-electron-renderer+ renderer: {},+ }),+ ],+ optimizeDeps: {+ exclude: ["@ffmpeg/ffmpeg", "@ffmpeg/util"],},- }- })(),- clearScreen: false,- }+ server: process.env.VSCODE_DEBUG && (() => {+ const url = new URL(pkg.debug.env.VITE_DEV_SERVER_URL)+ return {+ host: url.hostname,+ port: +url.port,+ headers: {+ "Cross-Origin-Opener-Policy": "same-origin",+ "Cross-Origin-Embedder-Policy": "require-corp",+ },+ }+ })(),+ clearScreen: false,+ }})diff --git a/freemocap/__init__.py b/freemocap/__init__.pyindex 04fcf0dc..4019a2e0 100644--- a/freemocap/__init__.py+++ b/freemocap/__init__.py@@ -14,4 +14,3 @@ from freemocap.system.logging_configuration.log_levels import LogLevelsLOG_LEVEL = LogLevels.TRACEconfigure_logging(LOG_LEVEL)-diff --git a/freemocap/__main__.py b/freemocap/__main__.pyindex ba9f8f01..be33e35a 100644--- a/freemocap/__main__.py+++ b/freemocap/__main__.py@@ -1,46 +1,91 @@+import asyncioimport loggingimport multiprocessing+import signalimport sys-import freemocap-from freemocap.freemocap_app.freemocap_application import create_freemocap_app, get_freemocap_app-from freemocap.run_freemocap_server import run_freemocap_server-from freemocap.system.paths_and_filenames.file_and_folder_names import SPARKLES_EMOJI_STRING, SKULL_EMOJI_STRING-from freemocap.utilities.clean_path import clean_path-from freemocap.utilities.setup_windows_app_id import setup_app_id_for_windows+import uvicorn+from skellycam.utilities.kill_process_on_port import kill_process_on_port+from skellycam.utilities.wait_functions import await_1s++from freemocap.api.server_constants import HOSTNAME, PORT+from freemocap.app.app import create_fastapi_applogger = logging.getLogger(__name__)-logger.debug(- f"Initializing {freemocap.__package_name__} package, version: {freemocap.__version__}, from file: {__file__}")+async def main() -> None:+ # Create shared kill flag for subprocesses+ global_kill_flag: multiprocessing.Value = multiprocessing.Value("b", False)+ heartbeat_timestamp:multiprocessing.Value = multiprocessing.Value("d", 0)+ subprocess_registry: list[multiprocessing.Process] = []+ server: uvicorn.Server | None = None-def main():- logger.info(f"Running from __main__: {__name__} - {clean_path(__file__)}")+ def handle_signal(signum: int, frame: object) -> None:+ """Handle shutdown signals."""+ logger.info(f"Received signal {signum}, initiating shutdown...")+ global_kill_flag.value = True+ if server:+ server.should_exit = True- global_kill_flag = multiprocessing.Value('b', False)- create_freemocap_app(global_kill_flag=global_kill_flag)+ # Setup signal handlers+ signal.signal(signal.SIGTERM, handle_signal)+ signal.signal(signal.SIGINT, handle_signal)- logger.info("Starting server...")- run_freemocap_server(global_kill_flag)+ try:+ # Clean up any existing process on the port+ kill_process_on_port(port=PORT)- global_kill_flag.value = True- get_freemocap_app().close()+ # Create FastAPI app+ app = create_fastapi_app(global_kill_flag=global_kill_flag,+ heartbeat_timestamp=heartbeat_timestamp,+ subprocess_registry=subprocess_registry)- logger.info("Exiting `main`...")+ # Configure and create Uvicorn server+ config = uvicorn.Config(+ app=app,+ host=HOSTNAME,+ port=PORT,+ log_level="warning",+ reload=False+ )+ server = uvicorn.Server(config)++ logger.info(f"Starting server on {HOSTNAME}:{PORT}")++ # Run server (blocks until shutdown)+ await server.serve()-if __name__ == "__main__":- multiprocessing.freeze_support()- if sys.platform == "win32":- setup_app_id_for_windows()- try:- main()except KeyboardInterrupt:- logger.info("Keyboard interrupt - shutting down!")+ logger.info("Keyboard interrupt received")except Exception as e:- logger.exception("An unexpected error occurred", exc_info=e)+ logger.error(f"Fatal error: {e}")raise- print("\n\n--------------------------------------------------\n--------------------------------------------------")- print(f"Thank you for using FreeMoCap {SKULL_EMOJI_STRING} {SPARKLES_EMOJI_STRING}")- print("--------------------------------------------------\n--------------------------------------------------\n\n")+ finally:+ # Ensure kill flag is set and server is stopped+ global_kill_flag.value = True+ if server:+ server.should_exit = True+ await await_1s() # Give it time to shut down gracefully++ for process in subprocess_registry:+ if process.is_alive():+ logger.info(f"Terminating subprocess {process.name} (PID: {process.pid})")+ process.terminate()+ process.join(timeout=2)+ if process.is_alive():+ logger.warning(f"Force killing subprocess {process.name} (PID: {process.pid})")+ process.kill()+ process.join()+ logger.success("Done! Thank you for using SkellyCam ๐๐ธโจ")+++if __name__ == "__main__":+ try:+ asyncio.run(main())+ except Exception as e:+ logger.exception(f"Unhandled exception: {e}")+ sys.exit(1)+ else:+ sys.exit(0)diff --git a/freemocap/api/http/app/health.py b/freemocap/api/http/app/health.pyindex b24e62a5..ddf96c7e 100644--- a/freemocap/api/http/app/health.py+++ b/freemocap/api/http/app/health.py@@ -2,19 +2,14 @@ import loggingfrom fastapi import APIRouter-HELLO_FROM_FREEMOCAP_BACKEND_MESSAGE = {"message": "Hello from the FreeMoCap Backend ๐โจ"}-logger = logging.getLogger(__name__)health_router = APIRouter()-@health_router.get("/healthcheck", summary="Hello๐", tags=['App'])+@health_router.get("/health", summary="Hello๐", tags=['App'])def healthcheck_endpoint():"""- A simple endpoint to greet the user of the FreeMoCap API.-- This can be used as a sanity check to ensure the API is responding.+ A simple endpoint to show the server is alive and happy"""- logger.api("Hello requested! Deploying Hello!")- return HELLO_FROM_FREEMOCAP_BACKEND_MESSAGE+ return "Hello๐"diff --git a/freemocap/api/http/app/shutdown.py b/freemocap/api/http/app/shutdown.pyindex 93db0b66..215e7998 100644--- a/freemocap/api/http/app/shutdown.py+++ b/freemocap/api/http/app/shutdown.py@@ -1,18 +1,47 @@+"""+Clean shutdown endpoint with proper async handling.+"""import logging+import os+import signal-from fastapi import APIRouter--from freemocap.freemocap_app.freemocap_application import get_freemocap_app+from fastapi import APIRouter, Request+from fastapi.responses import JSONResponse+from skellycam.utilities.wait_functions import await_100mslogger = logging.getLogger(__name__)-app_shutdown_router = APIRouter()+shutdown_router = APIRouter(tags=["App"])+++@shutdown_router.get(+ "/shutdown",+ summary="Gracefully shutdown the server",+ response_model=dict[str, str]+)+async def shutdown_server(+ request: Request,+) -> JSONResponse:+ """+ Initiate graceful server shutdown.++ This endpoint triggers a graceful shutdown of the entire SkellyCam system,+ including all camera groups and the server itself.-@app_shutdown_router.get("/shutdown", summary="goodbye๐", tags=['App'])-def shutdown_server():- from freemocap.api.server.server_singleton import get_server_manager- logger.api("Shutdown requested - Closing camera connections and shutting down server...")- get_freemocap_app().shutdown_freemocap()+ Returns:+ JSON response confirming shutdown initiation+ """+ logger.api(f"Shutdown requested via API - {request.url}")- get_server_manager().shutdown_server()- logger.api("Server shutdown complete - Killing process... Bye!๐")+ # Send SIGTERM to ourselves - this triggers the existing shutdown flow+ request.app.state.global_kill_flag.value = True+ await await_100ms()+ os.kill(os.getpid(), signal.SIGTERM)+ logger.info("Sent SIGTERM signal to initiate shutdown")+ return JSONResponse(+ content={+ "status": "shutdown_initiated",+ "message": "Server shutting down. Goodbye! ๐"+ },+ status_code=200+ )diff --git a/freemocap/api/http/app/state.py b/freemocap/api/http/app/state.pynew file mode 100644index 00000000..d62df2ca--- /dev/null+++ b/freemocap/api/http/app/state.py@@ -0,0 +1,17 @@+import logging++from fastapi import APIRouter+from skellycam.skellycam_app.skellycam_app import get_skellycam_app++logger = logging.getLogger(__name__)+state_router = APIRouter()+++@state_router.get("/state", summary="Application State", tags=['App'])+def app_state_endpoint():+ """+ A simple endpoint that serves the current state of the application+ """+ logger.api("Serving application state from `app/state` endpoint...")++ return get_skellycam_app().state_dto()diff --git a/freemocap/core/pipelines/__init__.py b/freemocap/api/http/calibration/__init__.pysimilarity index 100%rename from freemocap/core/pipelines/__init__.pyrename to freemocap/api/http/calibration/__init__.pydiff --git a/freemocap/api/http/calibration/calibration_router.py b/freemocap/api/http/calibration/calibration_router.pynew file mode 100644index 00000000..37d2b5d4--- /dev/null+++ b/freemocap/api/http/calibration/calibration_router.py@@ -0,0 +1,134 @@+import logging+from pathlib import Path++from fastapi import APIRouter, HTTPException+from pydantic import BaseModel+from pydantic import Field+from skellycam.core.recorders.videos.recording_info import RecordingInfo++from freemocap.app.freemocap_application import get_freemocap_app+from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.posthoc_calibration_pipeline import \+ CalibrationpipelineConfig++logger = logging.getLogger(__name__)++calibration_router = APIRouter(prefix="/calibration", tags=["Calibration"])+++# ==================== Request/Response Models ====================+++class CalibrationConfigRequest(BaseModel):+ config: CalibrationpipelineConfig+++class CalibrationConfigResponse(BaseModel):+ success: bool+ message: str | None = None+++class StartCalibrationRecordingRequest(BaseModel):+ calibration_recording_directory: str = Field(alias="calibrationRecordingDirectory")+ calibration_pipeline_config: CalibrationpipelineConfig = Field(alias="calibrationTaskConfig")++ def to_recording_info(self) -> RecordingInfo:+ recordings_directory = Path(self.calibration_recording_directory).parent+ recording_name = Path(self.calibration_recording_directory).stem+ if not recording_name.endswith('_calibration'):+ recording_name += '_calibration'+ return RecordingInfo(+ recording_directory=str(Path(self.calibration_recording_directory).parent).replace('~', str(Path.home())),+ recording_name=recording_name,+ mic_device_index=-1+ )+++class StopCalibrationRecordingRequest(BaseModel):+ calibration_pipeline_config: CalibrationpipelineConfig = Field(alias="calibrationTaskConfig")+++class CalibrateRecordingRequest(BaseModel):+ calibration_recording_directory: str = Field(alias="calibrationRecordingDirectory")+ calibration_pipeline_config: CalibrationpipelineConfig = Field(alias="calibrationTaskConfig")++ def to_recording_info(self) -> RecordingInfo:++ return RecordingInfo(+ recording_directory=str(Path(self.calibration_recording_directory).parent).replace('~', str(Path.home())),+ recording_name=Path(self.calibration_recording_directory).stem,+ mic_device_index=-1+ )+++class StartCalibrationRecordingResponse(BaseModel):+ success: bool+ message: str | None = None+++class CalibrateRecordingResponse(BaseModel):+ success: bool+ message: str | None = None+ results: dict | None = None+++# ==================== Endpoints ====================++@calibration_router.post("/config/update/all")+def update_all_calibration_config(request: CalibrationConfigRequest) -> CalibrationConfigResponse:+ """Update calibration configuration."""+ try:+ get_freemocap_app().realtime_pipeline_manager.update_calibration_task_config(request.config)+ return CalibrationConfigResponse(success=True, message="Configuration updated")+ except Exception as e:+ logger.exception(f"Error updating calibration config: {e}")+ raise HTTPException(status_code=500, detail=str(e))+++@calibration_router.post("/recording/start")+async def start_calibration_recording(request: StartCalibrationRecordingRequest) -> StartCalibrationRecordingResponse:+ """Start calibration recording with given config."""+ try:+ recording_info = request.to_recording_info()+ if not recording_info.recording_name.endswith('_calibration'):+ recording_info.recording_name += '_calibration'++ await get_freemocap_app().start_recording_all(recording_info=recording_info, )+ logger.info(f"Starting recording : {recording_info}")+ return StartCalibrationRecordingResponse(success=True, message="Recording started")+ except Exception as e:+ logger.exception(f"Error starting recording: {e}")+ raise HTTPException(status_code=500, detail=str(e))+++@calibration_router.post("/recording/stop")+async def stop_calibration_recording(request: StopCalibrationRecordingRequest) -> dict[str, bool]:+ """Stop current calibration recording."""+ app = get_freemocap_app()+ try:+ recording_info = await app.stop_recording_all()+ await app.create_posthoc_calibration_pipeline(recording_info=recording_info,+ calibration_pipeline_config=request.calibration_pipeline_config)+ logger.info("Stopping recording")+ return {"success": True}+ except Exception as e:+ logger.error(f"Error stopping recording: {e}")+ raise HTTPException(status_code=500, detail=str(e))+++@calibration_router.post("/recording/calibrate")+async def calibrate_recording(request: CalibrateRecordingRequest) -> CalibrateRecordingResponse:+ """Process and calibrate a recorded session."""+ app = get_freemocap_app()+ try:+ recording_info = request.to_recording_info()+ await app.create_posthoc_calibration_pipeline(recording_info=recording_info,+ calibration_pipeline_config=request.calibration_pipeline_config)+ logger.info(f"Calibrating recording at: {recording_info.full_recording_path}")+ return CalibrateRecordingResponse(+ success=True,+ message="Calibration completed",+ results={}+ )+ except Exception as e:+ logger.error(f"Error calibrating recording: {e}")+ raise HTTPException(status_code=500, detail=str(e))diff --git a/freemocap/core/pipelines/calibration_pipeline/multi_camera_calibration/__init__.py b/freemocap/api/http/mocap/__init__.pysimilarity index 100%rename from freemocap/core/pipelines/calibration_pipeline/multi_camera_calibration/__init__.pyrename to freemocap/api/http/mocap/__init__.pydiff --git a/freemocap/api/http/mocap/mocap_router.py b/freemocap/api/http/mocap/mocap_router.pynew file mode 100644index 00000000..4c96a3dc--- /dev/null+++ b/freemocap/api/http/mocap/mocap_router.py@@ -0,0 +1,134 @@+import logging+from pathlib import Path++from fastapi import APIRouter, HTTPException+from pydantic import BaseModel+from pydantic import Field+from skellycam.core.recorders.videos.recording_info import RecordingInfo++from freemocap.app.freemocap_application import get_freemocap_app+from freemocap.core.pipeline.posthoc_pipelines.posthoc_mocap_pipeline.posthoc_mocap_pipeline import \+ MocapPipelineTaskConfig++logger = logging.getLogger(__name__)++mocap_router = APIRouter(prefix="/mocap", tags=["Mocap"])+++# ==================== Request/Response Models ====================+++class MocapConfigRequest(BaseModel):+ config: MocapPipelineTaskConfig+++class MocapConfigResponse(BaseModel):+ success: bool+ message: str | None = None+++class StartMocapRecordingRequest(BaseModel):+ mocap_recording_directory: str = Field(alias="mocapRecordingDirectory")+ mocap_task_config: MocapPipelineTaskConfig = Field(alias="mocapTaskConfig")++ def to_recording_info(self) -> RecordingInfo:+ recordings_directory = Path(self.mocap_recording_directory).parent+ recording_name = Path(self.mocap_recording_directory).stem+ if not recording_name.endswith('_mocap'):+ recording_name += '_mocap'+ return RecordingInfo(+ recording_directory=str(recordings_directory),+ recording_name=recording_name,+ mic_device_index=-1+ )+++class StopMocapRecordingRequest(BaseModel):+ mocap_task_config: MocapPipelineTaskConfig = Field(alias="mocapTaskConfig")+++class ProcessMocapRecordingRequest(BaseModel):+ mocap_recording_directory: str = Field(alias="mocapRecordingDirectory")+ mocap_task_config: MocapPipelineTaskConfig = Field(alias="mocapTaskConfig")++ def to_recording_info(self) -> RecordingInfo:+ return RecordingInfo(+ recording_directory=str(Path(self.mocap_recording_directory).parent),+ recording_name=Path(self.mocap_recording_directory).stem,+ mic_device_index=-1+ )+++class StartMocapRecordingResponse(BaseModel):+ success: bool+ message: str | None = None+++class MocapRecordingResponse(BaseModel):+ success: bool+ message: str | None = None+ results: dict | None = None+++# ==================== Endpoints ====================++@mocap_router.post("/config/update/all")+def update_all_mocap_config(request: MocapConfigRequest) -> MocapConfigResponse:+ """Update mocap configuration."""+ try:+ get_freemocap_app().realtime_pipeline_manager.update_mocap_task_config(request.config)+ return MocapConfigResponse(success=True, message="Mocap Configuration updated")+ except Exception as e:+ logger.exception(f"Error updating mocap config: {e}")+ raise HTTPException(status_code=500, detail=str(e))+++@mocap_router.post("/recording/start")+async def start_mocap_recording(request: StartMocapRecordingRequest) -> StartMocapRecordingResponse:+ """Start mocap recording with given config."""+ try:+ recording_info = request.to_recording_info()+ if not recording_info.recording_name.endswith('_mocap'):+ recording_info.recording_name += '_mocap'++ # await get_freemocap_app().create_or_update_realtime_mocap_pipeline(request.mocap_task_config)+ await get_freemocap_app().start_recording_all(recording_info=recording_info, )+ logger.info(f"Starting mocap recording : {recording_info}")+ return StartMocapRecordingResponse(success=True, message="Mocap recording started")+ except Exception as e:+ logger.exception(f"Error starting recording: {e}")+ raise HTTPException(status_code=500, detail=str(e))+++@mocap_router.post("/recording/stop")+async def stop_mocap_recording(request: StopMocapRecordingRequest) -> dict[str, bool]:+ """Stop current mocap recording."""+ app = get_freemocap_app()+ try:+ recording_info = await app.stop_recording_all()+ await app.posthoc_pipeline_manager.create_posthoc_mocap_pipeline(recording_info=recording_info,+ mocap_task_config=request.mocap_task_config)+ logger.info("Stopping recording")+ return {"success": True}+ except Exception as e:+ logger.error(f"Error stopping recording: {e}")+ raise HTTPException(status_code=500, detail=str(e))+++@mocap_router.post("/recording/process")+async def process_mocap_recording(request: ProcessMocapRecordingRequest) -> MocapRecordingResponse:+ """Process and calibrate a recorded session."""+ app = get_freemocap_app()+ try:+ recording_info = request.to_recording_info()+ await app.posthoc_pipeline_manager.create_posthoc_mocap_pipeline(recording_info=recording_info,+ mocap_task_config=request.mocap_task_config)+ logger.info(f"Processing mocap recording at: {recording_info.full_recording_path}")+ return MocapRecordingResponse(+ success=True,+ message="Mocap processing pipeline completed",+ results={}+ )+ except Exception as e:+ logger.error(f"Error calibrating recording: {e}")+ raise HTTPException(status_code=500, detail=str(e))diff --git a/freemocap/api/http/pipelines/pipeline_router.py b/freemocap/api/http/pipelines/pipeline_router.pyindex 57c2e92b..59ecde88 100644--- a/freemocap/api/http/pipelines/pipeline_router.py+++ b/freemocap/api/http/pipelines/pipeline_router.py@@ -1,44 +1,82 @@-import loggingfrom pathlib import Path-from fastapi import APIRouter, Body, HTTPException+from fastapi import APIRouter, Body, HTTPException, Requestfrom pydantic import BaseModel, Field-from skellycam.core.camera.config.camera_config import CameraConfigs, CameraConfig-from skellycam.core.camera_group.camera_group import CameraGroup+from skellycam.core.camera.config.camera_config import CameraConfig+from skellycam.core.camera_group.camera_group import CameraConfigs+from skellycam.core.recorders.videos.recording_info import RecordingInfofrom skellycam.core.types.type_overloads import CameraGroupIdString, CameraIdString-from freemocap.freemocap_app.freemocap_application import get_freemocap_app+from freemocap.app.freemocap_application import get_freemocap_app+from freemocap.core.pipeline.pipeline_configs import RealtimePipelineConfig+from freemocap.system.default_paths import default_recording_name, get_default_recording_folder_pathlogger = logging.getLogger(__name__)pipeline_router = APIRouter(prefix=f"/pipeline",- tags=["Processing Pipelines"],)+ tags=["Processing Pipelines"], )class PipelineConnectRequest(BaseModel):- camera_ids: list[CameraIdString] = Field(..., description="List of camera IDs comprising the CameraGroup we're attaching a pipeline to")+ camera_configs: CameraConfigs = Field(...,+ description="List of camera IDs comprising the CameraGroup we're attaching a pipeline to")+ pipeline_config: RealtimePipelineConfig | None = None++ @property+ def camera_ids(self) -> list[CameraIdString] | None:+ if self.camera_configs:+ return list(self.camera_configs.keys())+ return Noneclass PipelineCreateResponse(BaseModel):camera_group_id: CameraGroupIdString = Field(..., description="ID of the camera group attached to the pipeline")pipeline_id: str = Field(..., description="ID of the processing pipeline to which the camera group is attached")+ camera_configs: CameraConfigs = Field(..., description="Camera configurations for the cameras in the camera group")++ @classmethod+ def from_pipeline(cls, pipeline) -> "PipelineCreateResponse":+ return cls(+ camera_group_id=pipeline.camera_group.id,+ pipeline_id=pipeline.id,+ camera_configs=pipeline.camera_configs,+ )+++class StartRecordingRequest(BaseModel):+ recording_name: str = Field(+ default_factory=default_recording_name,+ description="Name of the recording"+ )+ recording_directory: str = Field(+ default_factory=get_default_recording_folder_path,+ description="Path to save the recording"+ )+ mic_device_index: int = Field(+ default=-1,+ description="Index of the microphone device"+ )++ def recording_full_path(self) -> str:+ return str(Path(self.recording_directory) / self.recording_name)+@pipeline_router.post("/connect",- summary="Create a processing pipeline and attach it to a camera group"- )-def pipeline_connect_post_endpoint(+ summary="Create a processing pipeline and attach it to a camera group"+ )+async def pipeline_connect_endpoint(request: PipelineConnectRequest = Body(...,description="Request body containing desired camera configuration",examples=[- PipelineConnectRequest(camera_ids=['0'])]), ) -> PipelineCreateResponse:+ PipelineConnectRequest(camera_configs={+ '0': CameraConfig(camera_id='0')})])) -> PipelineCreateResponse:logger.api(f"Received `pipeline/connect` POST request - \n {request.model_dump_json(indent=2)}")try:-- camera_group = get_freemocap_app().skellycam_app.camera_group_manager.camera_group_from_camera_ids(camera_ids=request.camera_ids)- camera_group_id, pipeline_id = get_freemocap_app().connect_pipeline(camera_group=camera_group)- response = PipelineCreateResponse(camera_group_id=camera_group_id,- pipeline_id=pipeline_id)+ pipeline_config = request.pipeline_config or RealtimePipelineConfig.from_camera_configs(+ camera_configs=request.camera_configs)+ pipeline = await get_freemocap_app().create_or_update_realtime_pipeline(pipeline_config=pipeline_config)+ response = PipelineCreateResponse.from_pipeline(pipeline=pipeline)logger.api(f"`pipeline/connect` POST request handled successfully - \n {response.model_dump_json(indent=2)}")return response@@ -48,18 +86,59 @@ def pipeline_connect_post_endpoint(raise HTTPException(status_code=500,detail=f"Error when processing `pipeline/connect` request: {type(e).__name__} - {e}")-@pipeline_router.get("/disconnect/all",- summary="Disconnect/shutdown all processing pipelines"- )-def pipeline_disconnect_post_endpoint( ):- logger.api(f"Received `pipeline/disconnect` GET request")++@pipeline_router.delete("/all/close",+ summary="Disconnect/shutdown all processing pipelines"+ )+async def pipeline_close_endpoint():+ logger.api(f"Received `pipeline/close` DELETE request")try:- get_freemocap_app().disconnect_pipeline()+ get_freemocap_app().close_pipelines()logger.api(- f"`pipeline/disconnect` GET request handled successfully ")+ f"`pipeline/disconnect` DELETE request handled successfully ")except Exception as e:logger.error(f"Error when processing `pipeline/disconnect` request: {type(e).__name__} - {e}")logger.exception(e)raise HTTPException(status_code=500,- detail=f"Error when processing `pipeline/disconnect` request: {type(e).__name__} - {e}")\ No newline at end of file+ detail=f"Error when processing `pipeline/disconnect` request: {type(e).__name__} - {e}")+++@pipeline_router.get("/all/pause_unpause", summary="Pause/unpause cameras")+def pause_camera_groups(request: Request) -> bool:+ try:+ get_freemocap_app().pause_unpause_pipelines()+ return True+ except Exception as e:+ logger.error(f"Error in {request.url}: {type(e).__name__} - {e}", exc_info=True)+ raise HTTPException(status_code=500, detail=str(e))+++@pipeline_router.post("/all/record/start", summary="Start recording")+def start_recording(+ request: Request,+ request_body: StartRecordingRequest = Body(..., examples=[StartRecordingRequest()])+) -> bool:+ try:+ if request_body.recording_directory.startswith("~"):+ request_body.recording_directory = str(+ Path(request_body.recording_directory.replace("~", str(Path.home()), 1))+ )++ Path(request_body.recording_directory).mkdir(parents=True, exist_ok=True)+ get_freemocap_app().start_recording_all(RecordingInfo(**request_body.model_dump()))++ return True+ except Exception as e:+ logger.error(f"Error in {request.url}: {type(e).__name__} - {e}", exc_info=True)+ raise HTTPException(status_code=500, detail=str(e))+++@pipeline_router.get("/all/record/stop", summary="Stop recording")+def stop_recording(request: Request) -> bool:+ try:+ get_freemocap_app().stop_recording_all()+ return True+ except Exception as e:+ logger.error(f"Error in {request.url}: {type(e).__name__} - {e}", exc_info=True)+ raise HTTPException(status_code=500, detail=str(e))diff --git a/freemocap/api/middleware/add_middleware.py b/freemocap/api/middleware/add_middleware.pyindex 5e5e6f1a..5cf96329 100644--- a/freemocap/api/middleware/add_middleware.py+++ b/freemocap/api/middleware/add_middleware.py@@ -1,22 +1,66 @@import logging+import time+import traceback-from fastapi import FastAPI+from fastapi import FastAPI, Request, Responselogger = logging.getLogger(__name__)-def add_middleware(app: FastAPI):+def add_middleware(app: FastAPI) -> None:logger.debug("Adding middleware...")- # @app.middleware("http")- # async def log_requests(request: Request, call_next):- # start_time = time.time()- # response: Response = await call_next(request)- # process_time = time.time() - start_time- # logger.debug(- # f"Request: {request.url} processed in {process_time:.6f} seconds and returned status code: {response.status_code}")- # get_app_state().log_api_call(url_path=request.url.path,- # start_time=start_time,- # process_time=process_time,- # status_code=response.status_code)- # return response+ @app.middleware("http")+ async def log_requests(request: Request, call_next) -> Response:+ logger.api(f"Received request: {request.method} {request.url}")+ start_time = time.time()++ try:+ response: Response = await call_next(request)+ process_time = time.time() - start_time++ # For error responses, consume the body to log it+ if response.status_code >= 400:+ # Consume the entire response body+ response_body = b""+ async for chunk in response.body_iterator:+ response_body += chunk++ # Try to decode and log the error+ try:+ error_content = response_body.decode("utf-8")+ logger.error(+ f"Request FAILED: {request.method} {request.url} "+ f"[{response.status_code}] in {process_time:.6f}s - "+ f"Error: {error_content}"+ )+ except UnicodeDecodeError:+ logger.error(+ f"Request FAILED: {request.method} {request.url} "+ f"[{response.status_code}] in {process_time:.6f}s - "+ f"Error body could not be decoded (length: {len(response_body)} bytes)"+ )++ # Recreate the response with the consumed body so the client still gets it+ return Response(+ content=response_body,+ status_code=response.status_code,+ headers=dict(response.headers),+ media_type=response.media_type,+ )+ else:+ logger.api(+ f"Handled Request: {request.url} processed in {process_time:.6f} seconds "+ f"and returned status code: {response.status_code}"+ )++ return response++ except Exception as e:+ process_time = time.time() - start_time+ logger.error(+ f"Request EXCEPTION: {request.method} {request.url} "+ f"failed in {process_time:.6f}s with exception: {type(e).__name__}: {str(e)}"+ )+ logger.error(f"Traceback:\n{traceback.format_exc()}")+ raisediff --git a/freemocap/api/routers.py b/freemocap/api/routers.pyindex a25ca659..5dcf98ff 100644--- a/freemocap/api/routers.py+++ b/freemocap/api/routers.py@@ -1,15 +1,14 @@from skellycam.api.http.cameras.camera_router import camera_router-from skellycam.api.http.videos.videos_router import load_videos_router-from freemocap.api.http.app.health import health_router+from freemocap.api.http.calibration.calibration_router import calibration_router+from freemocap.api.http.mocap.mocap_router import mocap_routerfrom freemocap.api.http.pipelines.pipeline_router import pipeline_router-from freemocap.api.websocket.websocket_connect import websocket_routerSKELLYCAM_ROUTERS = [camera_router,- load_videos_router,]-FREEMOCAP_ROUTERS = [websocket_router,- health_router,- pipeline_router]+FREEMOCAP_ROUTERS = [pipeline_router,+ calibration_router,+ mocap_router+ ]diff --git a/freemocap/api/server/server_constants.py b/freemocap/api/server/server_constants.pyindex 0625093a..a6d19787 100644--- a/freemocap/api/server/server_constants.py+++ b/freemocap/api/server/server_constants.py@@ -1,4 +1,4 @@PROTOCOL = "http"HOSTNAME = "localhost"-PORT = 8007+PORT = 53117APP_URL = f"{PROTOCOL}://{HOSTNAME}:{PORT}"diff --git a/freemocap/api/server/server_manager.py b/freemocap/api/server/server_manager.pyindex b2349f3f..f89ff338 100644--- a/freemocap/api/server/server_manager.py+++ b/freemocap/api/server/server_manager.py@@ -5,11 +5,11 @@ import timeimport psutilimport uvicorn+from freemocap.app.freemocap_app_lifespan.freemocap_app_setup import create_freemocap_fastapi_appfrom uvicorn import Serverfrom freemocap.api.server.server_constants import HOSTNAME, PORT-from freemocap.freemocap_app.freemocap_app_lifespan.freemocap_app_setup import create_freemocap_fastapi_app-from freemocap.freemocap_app.freemocap_application import get_freemocap_app+from freemocap.app.freemocap_application import get_freemocap_appfrom freemocap.utilities.kill_process_on_port import kill_process_on_portlogger = logging.getLogger(__name__)@@ -25,15 +25,14 @@ class UvicornServerManager:get_freemocap_app()self.hostname: str = hostnameself.port: int = port- self.server_thread: threading.Thread|None = None- self.server: Server|None = None+ self.server_thread: threading.Thread | None = None+ self.server: Server | None = Noneself.log_level: str = log_levelself.shutdown_listener_thread = threading.Thread(target=self.shutdown_listener_loop,name="UvicornServerManagerShutdownListenerThread",daemon=True)self.shutdown_listener_thread.start()-@propertydef is_running(self):return self.server_thread.is_alive() if self.server_thread else False@@ -57,7 +56,7 @@ class UvicornServerManager:logger.debug("Server thread started")try:logger.debug("Running uvicorn server...")- self.server.run() #blocks until server is stopped+ self.server.run() # blocks until server is stoppedlogger.info("Running uvicorn server...")except Exception as e:logger.error(f"A fatal error occurred in the uvicorn server: {e}")@@ -91,7 +90,7 @@ class UvicornServerManager:def shutdown_listener_loop(self):logger.info("Starting shutdown listener loop")- while self._global_kill_flag.value is False :+ while self._global_kill_flag.value is False:time.sleep(1)if self._global_kill_flag.value:logger.info("Detected global kill flag - shutting down server")diff --git a/freemocap/api/server_constants.py b/freemocap/api/server_constants.pynew file mode 100644index 00000000..a6d19787--- /dev/null+++ b/freemocap/api/server_constants.py@@ -0,0 +1,4 @@+PROTOCOL = "http"+HOSTNAME = "localhost"+PORT = 53117+APP_URL = f"{PROTOCOL}://{HOSTNAME}:{PORT}"diff --git a/freemocap/api/websocket/websocket_connect.py b/freemocap/api/websocket/websocket_connect.pyindex 7b86fe7a..9b0499ae 100644--- a/freemocap/api/websocket/websocket_connect.py+++ b/freemocap/api/websocket/websocket_connect.py@@ -12,7 +12,9 @@ websocket_router = APIRouter(tags=["Websocket"], prefix="/websocket")@websocket_router.websocket("/connect")async def websocket_server_connect(websocket: WebSocket):await websocket.accept()- logger.success(f"Websocket connection established!")- async with WebsocketServer(websocket=websocket) as websocket_server:+ app = websocket.scope["app"]+ logger.success(f"Websocket connection established at url: {websocket.url}")+ async with WebsocketServer(websocket=websocket,+ fastapi_app=app) as websocket_server:await websocket_server.run()logger.info("Websocket closed")diff --git a/freemocap/api/websocket/websocket_server.py b/freemocap/api/websocket/websocket_server.pyindex b3267b2c..0273142d 100644--- a/freemocap/api/websocket/websocket_server.py+++ b/freemocap/api/websocket/websocket_server.py@@ -1,30 +1,33 @@import asyncioimport jsonimport logging-import time+from fastapi import FastAPI+from skellycam.core.recorders.framerate_tracker import FramerateTracker+from skellycam.core.types.type_overloads import CameraGroupIdString, CameraIdStringfrom starlette.websockets import WebSocket, WebSocketState, WebSocketDisconnect-from skellycam.core.recorders.framerate_tracker import FramerateTracker, CurrentFramerate-from skellycam.core.types.type_overloads import CameraGroupIdString, FrameNumberInt, MultiframeTimestampFloat-from skellycam.skellycam_app.skellycam_app import SkellycamApplication, get_skellycam_app--from freemocap.freemocap_app.freemocap_application import FreemocapApplication, get_freemocap_app-from freemocap.system.logging_configuration.handlers.websocket_log_queue_handler import LogRecordModel, \- get_websocket_log_queue-from freemocap.system.logging_configuration.log_levels import LogLevels-from skellycam.utilities.wait_functions import async_wait_10ms+from freemocap.app.freemocap_application import FreemocApplication, get_freemocap_app+from freemocap.core.pipeline.frontend_payload import FrontendPayload+from freemocap.core.types.type_overloads import FrameNumberInt+from freemocap.system.logging_configuration.handlers.websocket_log_queue_handler import get_websocket_log_queue, \+ MIN_LOG_LEVEL_FOR_WEBSOCKET+from freemocap.utilities.wait_functions import await_10mslogger = logging.getLogger(__name__)-BACKPRESSURE_WARNING_THRESHOLD: int = 15 # Number of frames before we warn about backpressure+BACKPRESSURE_WARNING_THRESHOLD: int = 100 # Number of frames before we warn about backpressureclass WebsocketServer:- def __init__(self, websocket: WebSocket):+ def __init__(self, fastapi_app: FastAPI, websocket: WebSocket):self.websocket = websocket- self._app: FreemocapApplication = get_freemocap_app()+ if not hasattr(fastapi_app, "state") or not hasattr(fastapi_app.state, "global_kill_flag"):+ raise RuntimeError(+ "FastAPI app does not have a global_kill_flag in its state - define those fields when creating fastapi app")+ self._global_kill_flag = fastapi_app.state.global_kill_flag+ self._app: FreemocApplication = get_freemocap_app()self._websocket_should_continue = Trueself.ws_tasks: list[asyncio.Task] = []@@ -33,7 +36,6 @@ class WebsocketServer:self._display_image_sizes: dict[CameraGroupIdString, dict[str, float]] | None = Noneself._frontend_framerate_trackers: dict[CameraGroupIdString, FramerateTracker] = {}-async def __aenter__(self):logger.debug("Entering WebsocketRunner context manager...")self._websocket_should_continue = True@@ -55,7 +57,7 @@ class WebsocketServer:@propertydef should_continue(self):return (- self._app.should_continue+ not self._global_kill_flag.valueand self._websocket_should_continueand self.websocket.client_state == WebSocketState.CONNECTED)@@ -63,7 +65,6 @@ class WebsocketServer:async def run(self):logger.info("Starting websocket runner...")self.ws_tasks = [asyncio.create_task(self._frontend_image_relay(), name="WebsocketFrontendImageRelay"),- # asyncio.create_task(self._ipc_queue_relay(), name="WebsocketIPCQueueRelay"),asyncio.create_task(self._logs_relay(), name="WebsocketLogsRelay"),asyncio.create_task(self._client_message_handler(), name="WebsocketClientMessageHandler")]@@ -82,83 +83,112 @@ class WebsocketServer:return Truereturn self.last_received_frontend_confirmation >= self.last_sent_frame_number- async def _frontend_image_relay(self):+ # Updated section for _frontend_image_relay method in websocket_server.py++ async def _frontend_image_relay(self) -> None:"""Relay image payloads from the shared memory to the frontend via the websocket."""- logger.info(- f"Starting frontend image payload relay...")+ logger.info(f"Starting frontend image payload relay...")try:skipped_previous = Falsewhile self.should_continue:- await async_wait_10ms()+ await await_10ms()+ frontend_payloads = self._app.get_latest_frontend_payloads(if_newer_than=self.last_sent_frame_number)+if self.check_frame_acknowledgment_status():if skipped_previous: # skip an extra frame if there was backpressure from frontendskipped_previous = Falseelse:- new_frontend_payloads: dict[- CameraGroupIdString, tuple[- FrameNumberInt, MultiframeTimestampFloat, bytes]] = self._app.skellycam_app.get_new_frontend_payloads(- if_newer_than=self.last_sent_frame_number,- display_image_sizes=self._display_image_sizes)-- for camera_group_id, (frame_number,- multiframe_timestamp,- payload_bytes) in new_frontend_payloads.items():- await self.websocket.send_bytes(payload_bytes)- self.last_sent_frame_number = frame_number- if camera_group_id not in self._frontend_framerate_trackers:- self._frontend_framerate_trackers[camera_group_id] = FramerateTracker.create(- framerate_source=f"Frontend-{camera_group_id}")- self._frontend_framerate_trackers[camera_group_id].update(multiframe_timestamp)+ for pipeline_id, (payload_bytes, frontend_payload) in frontend_payloads.items():+ frame_number = None+ if not payload_bytes and not frontend_payload:+ continue+ if frontend_payload:+ if not isinstance(frontend_payload, FrontendPayload):+ frame_number = frontend_payload+ frontend_payload = None+ else:+ frame_number = frontend_payload.frame_number++ if not isinstance(payload_bytes, (bytes, bytearray)):+ logger.warning(f"Invalid payload bytes on frame{frame_number} -"+ f" got type {type(payload_bytes)}")+ continue++ # Send the image bytes first+ if payload_bytes:+ await self.websocket.send_bytes(payload_bytes)++ # Send observation overlays as a single message per observation type+ if frontend_payload and frontend_payload.observation_overlays:+ # Group overlays by message type+ overlays_by_type: dict[str, dict[CameraIdString, dict]] = {}++ for camera_id, overlay_data in frontend_payload.observation_overlays.items():+ message_type = overlay_data.message_type+ if message_type not in overlays_by_type:+ overlays_by_type[message_type] = {}+ overlays_by_type[message_type][camera_id] = overlay_data.model_dump()++ # Send each observation type as separate message+ # This matches what the frontend expects+ for message_type, camera_overlays in overlays_by_type.items():+ await self.websocket.send_json(camera_overlays)++ # Send tracked points if present+ 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})++ if frame_number is not None:+ self.last_sent_frame_number = frame_numberelse:skipped_previous = Truebackpressure = self.last_sent_frame_number - self.last_received_frontend_confirmation- if backpressure > BACKPRESSURE_WARNING_THRESHOLD:+ if (backpressure > BACKPRESSURE_WARNING_THRESHOLD and+ backpressure % BACKPRESSURE_WARNING_THRESHOLD == 0):logger.trace(- f"Backpressure detected: {backpressure} frames not acknowledged by frontend! Last sent frame: {self.last_sent_frame_number}, last received confirmation: {self.last_received_frontend_confirmation}")-- backend_framerate_updates:dict[CameraGroupIdString,CurrentFramerate] = self._app.skellycam_app.camera_group_manager.get_backend_framerate_updates()- if backend_framerate_updates:- for camera_group_id, backend_framerate in backend_framerate_updates.items():- if camera_group_id not in self._frontend_framerate_trackers:- continue- framerate_message = {- "message_type": "framerate_update",- "camera_group_id": camera_group_id,- "backend_framerate": backend_framerate.model_dump(),- "frontend_framerate": self._frontend_framerate_trackers[camera_group_id].current_framerate.model_dump()- }- await self.websocket.send_json(framerate_message)- self._frontend_framerate_trackers[camera_group_id].clear()+ f"Backpressure detected: {backpressure} frames not acknowledged by frontend! "+ f"Last sent frame: {self.last_sent_frame_number}, last received confirmation: "+ f"{self.last_received_frontend_confirmation}")+except WebSocketDisconnect:logger.api("Client disconnected, ending Frontend Image relay task...")except asyncio.CancelledError:passexcept Exception as e:logger.exception(f"Error in image payload relay: {e.__class__}: {e}")- get_skellycam_app().kill_everything()+ self._global_kill_flag.value = Trueraise-- async def _logs_relay(self, ws_log_level: LogLevels = LogLevels.INFO):+ async def _logs_relay(self, ws_log_level: int = MIN_LOG_LEVEL_FOR_WEBSOCKET):logger.info("Starting websocket log relay listener...")logs_queue = get_websocket_log_queue()try:while self.should_continue:if not logs_queue.empty() and self.websocket.client_state == WebSocketState.CONNECTED:- log_record: LogRecordModel = LogRecordModel(**logs_queue.get_nowait())- if log_record.levelno < ws_log_level.value:+ log_record: logging.LogRecord = logs_queue.get_nowait()+ if log_record.levelno < ws_log_level:continue # Skip logs below the specified level- await self.websocket.send_json(log_record.model_dump())++ # if traceback is present, replace with string+ if log_record.exc_info:+ log_record.exc_text = logging.Formatter().formatException(log_record.exc_info)+ log_record.exc_info = None+ print("Sending log record via websocket:", log_record.getMessage())+ await self.websocket.send_json(log_record)else:- await async_wait_10ms()+ await await_10ms()except asyncio.CancelledError:logger.debug("Log relay task cancelled")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}")- get_skellycam_app().kill_everything()+ self._global_kill_flag.value = Trueraiseasync def _client_message_handler(self):@@ -186,10 +216,14 @@ class WebsocketServer:logger.error(f"Failed to decode JSON message: {e}")else:# Handle plain text messages- logger.info(f"Websocket received message: `{text_content}`")- # Add any specific handling for plain text commands here--+ if text_content.startswith("ping"):+ await self.websocket.send_text("pong")+ elif text_content.startswith("pong"):+ pass+ else:+ logger.info(f"Websocket received message: `{text_content}`")+ elif "websocket" in message:+ logger.trace(f"Received unknown websocket control message: {message}")else:logger.warning(f"Received unexpected message format: {message}")@@ -197,7 +231,7 @@ class WebsocketServer:logger.debug("Client message handler task cancelled")except Exception as e:logger.exception(f"Error handling client message: {e.__class__}: {e}")- get_skellycam_app().kill_everything()+ self._global_kill_flag.value = Trueraisefinally:logger.info("Ending client message handler...")diff --git a/freemocap/core/pubsub/__init__.py b/freemocap/app/__init__.pysimilarity index 100%rename from freemocap/core/pubsub/__init__.pyrename to freemocap/app/__init__.pydiff --git a/freemocap/app/app.py b/freemocap/app/app.pynew file mode 100644index 00000000..db0301ae--- /dev/null+++ b/freemocap/app/app.py@@ -0,0 +1,217 @@+"""+Consolidated FastAPI app factory with proper lifecycle management.+"""+import asyncio+import logging+import multiprocessing+import os+import signal+import time+from contextlib import asynccontextmanager+from pathlib import Path+from typing import AsyncGenerator++import skellycam+from fastapi import FastAPI+from fastapi.openapi.utils import get_openapi+from fastapi.responses import RedirectResponse+from starlette.responses import FileResponse++import freemocap+from freemocap.api.http.app.health import health_router+from freemocap.api.http.app.shutdown import shutdown_router+from freemocap.api.middleware.add_middleware import add_middleware+from freemocap.api.middleware.cors import cors+from freemocap.api.routers import SKELLYCAM_ROUTERS, FREEMOCAP_ROUTERS+from freemocap.api.server_constants import APP_URL+from freemocap.api.websocket.websocket_connect import websocket_router+from freemocap.app.freemocap_application import create_freemocap_app, get_freemocap_app+from freemocap.system.default_paths import (+ get_default_freemocap_base_folder_path, FREEMOCAP_FAVICON_ICO_PATH+)+from freemocap.utilities.wait_functions import await_1s++logger = logging.getLogger(__name__)++async def keep_alive_task(*,+ heartbeat_timestamp: multiprocessing.Value,+ global_kill_flag: multiprocessing.Value) -> None:+ """A simple task that increments a counter every second to indicate the main process is alive."""+ logger.debug("Starting heartbeat task...")+ while not global_kill_flag.value:+ with heartbeat_timestamp.get_lock():+ heartbeat_timestamp.value = time.perf_counter()+ await asyncio.sleep(1.0)+ logger.debug("Heartbeat task ended")++async def monitor_kill_flag(app: FastAPI) -> None:+ """+ Background task to monitor the kill flag and trigger shutdown.+ """+ while not app.state.global_kill_flag.value:+ await await_1s()++ logger.info("Kill flag detected, initiating shutdown...")+ os.kill(os.getpid(), signal.SIGTERM)+++@asynccontextmanager+async def app_lifespan(+ app: FastAPI+) -> AsyncGenerator[None, None]:+ """+ Manage the application lifecycle.+ All startup and shutdown logic goes here.+ """+ # ===== STARTUP =====+ logger.api("FreeMoCap API starting...")++ # Ensure base folder exists+ base_path = Path(get_default_freemocap_base_folder_path())+ base_path.mkdir(parents=True, exist_ok=True)+ logger.info(f"Base folder: {base_path}")+ create_freemocap_app(fastapi_app=app)++ # Initialize heartbeat timestamp with current time+ with app.state.heartbeat_timestamp.get_lock():+ app.state.heartbeat_timestamp.value = time.perf_counter()++ # Start heartbeat task IN THE APP CONTEXT+ heartbeat_task = asyncio.create_task(+ keep_alive_task(+ heartbeat_timestamp=app.state.heartbeat_timestamp,+ global_kill_flag=app.state.global_kill_flag+ )+ )+ # Start background task to monitor kill flag+ monitor_task = asyncio.create_task(monitor_kill_flag(app=app))++ logger.success(+ f"FreeMoCap API {freemocap.__version__} started successfully ๐โจ\n"+ f"Swagger API docs: {APP_URL}/docs"+ )++ # Let the application do its thing+ yield++ # ===== SHUTDOWN =====+ logger.api("FreeMoCap API shutting down...")++ # Cancel the background tasks+ heartbeat_task.cancel()+ monitor_task.cancel()++ try:+ await heartbeat_task+ except asyncio.CancelledError:+ pass++ try:+ await monitor_task+ except asyncio.CancelledError:+ pass++ # Cleanup SkellyCam application+ app.state.global_kill_flag.value = True+ get_freemocap_app().close()++ logger.success("FreeMoCap API shutdown complete - Goodbye! ๐")+++def create_fastapi_app(global_kill_flag: multiprocessing.Value,+ heartbeat_timestamp: multiprocessing.Value,+ subprocess_registry: list[multiprocessing.Process]) -> FastAPI:+ """+ Create and configure the FastAPI application.++ Args:+ global_kill_flag: Shared flag for coordinated shutdown+ heartbeat_timestamp: Shared heartbeat timestamp value+ subprocess_registry: List to track subprocesses++ Returns:+ Configured FastAPI application+ """+ # Create app with lifespan manager+ app = FastAPI(lifespan=app_lifespan)++ # Store dependencies in app state+ app.state.global_kill_flag = global_kill_flag+ app.state.subprocess_registry = subprocess_registry+ app.state.heartbeat_timestamp = heartbeat_timestamp+++ # Configure CORS+ cors(app)++ # Register routes+ _register_routes(app)++ # Add middleware+ add_middleware(app)++ # Customize OpenAPI+ _customize_openapi(app)++ return app+++def _register_routes(app: FastAPI) -> None:+ """Register all application routes."""++ # Root redirect+ @app.get("/", include_in_schema=False)+ async def root():+ return RedirectResponse("/docs")++ # Favicon+ @app.get("/favicon.ico", include_in_schema=False)+ async def favicon():+ return FileResponse(FREEMOCAP_FAVICON_ICO_PATH)++ logger.api(f"\nRegistering WebSocket routes:")+ app.include_router(websocket_router)+ for route in websocket_router.routes:+ logger.api(f"\tRegistered WebSocket route: {route.path}")+ # Health and shutdown routes (no prefix)+ logger.api("\nRegistering App level routes:")+ for router in [health_router, shutdown_router]:+ app.include_router(router)+ for route in router.routes:+ logger.api(f"\tRegistered: {route.path} with methods: [{', '.join(route.methods)}]")++ logger.api("\nRegistering FreeMoCap endpoints:")+ for router in FREEMOCAP_ROUTERS:+ app.include_router(router, prefix=f"/{freemocap.__package_name__}")+ for route in router.routes:+ logger.api(+ f"\tRegistering route: `/{freemocap.__package_name__}{route.path}` with methods: [{', '.join(route.methods)}]")++ logger.api("\nRegistering SkellyCam endpoints:")+ for router in SKELLYCAM_ROUTERS:+ for route in router.routes:+ logger.api(+ f"\tRegistering route: `/{skellycam.__package_name__}{route.path}` with methods: [{', '.join(route.methods)}]")+ app.include_router(router, prefix=f"/{skellycam.__package_name__}")+++def _customize_openapi(app: FastAPI) -> None:+ """Customize the OpenAPI schema."""++ def custom_openapi():+ if app.openapi_schema:+ return app.openapi_schema++ schema = get_openapi(+ title="FreeMoCap API ๐โจ",+ version=freemocap.__version__,+ description=(+ f"FastAPI Backend for FreeMoCap: {freemocap.__description__}"+ ),+ routes=app.routes,+ )++ app.openapi_schema = schema+ return schema++ app.openapi = custom_openapidiff --git a/freemocap/app/freemocap_application.py b/freemocap/app/freemocap_application.pynew file mode 100644index 00000000..8c5f3c29--- /dev/null+++ b/freemocap/app/freemocap_application.py@@ -0,0 +1,154 @@+import logging+import multiprocessing+from dataclasses import dataclass++from fastapi import FastAPI+from pydantic import BaseModel, ConfigDict+from skellycam.core.camera_group.camera_group import CameraGroupState+from skellycam.core.camera_group.camera_group_manager import CameraGroupManager, get_or_create_camera_group_manager+from skellycam.core.recorders.videos.recording_info import RecordingInfo+from skellycam.core.types.type_overloads import CameraGroupIdString++from freemocap.core.pipeline.frontend_payload import FrontendPayload+from freemocap.core.pipeline.pipeline_configs import RealtimePipelineConfig+from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.posthoc_calibration_pipeline import \+ CalibrationpipelineConfig+from freemocap.core.pipeline.posthoc_pipelines.posthoc_pipeline_manager import PosthocPipelineManager+from freemocap.core.pipeline.realtime_pipeline.realtime_pipeline import RealtimeProcessingPipeline+from freemocap.core.pipeline.realtime_pipeline.realtime_pipeline_manager import RealtimePipelineManager+from freemocap.core.types.type_overloads import PipelineIdString, FrameNumberInt++logger = logging.getLogger(__name__)+++class WorkerState(BaseModel):+ """Serializable representation of a worker process state."""+ model_config = ConfigDict(+ validate_assignment=True,+ frozen=True+ )+ pid: int+ name: str+ alive: bool+ error: str | None = None+++class AppState(BaseModel):+ """Serializable representation of the application state."""+ model_config = ConfigDict(+ validate_assignment=True,+ frozen=True+ )+ # pipelines: dict[PipelineIdString, PipelineState]+ camera_groups: dict[CameraGroupIdString, CameraGroupState]+ workers: dict[str, WorkerState]+++@dataclass+class FreemocApplication:+ global_kill_flag: multiprocessing.Value+ pipeline_shutdown_event: multiprocessing.Event+ realtime_pipeline_manager: RealtimePipelineManager+ posthoc_pipeline_manager: PosthocPipelineManager+ camera_group_manager: CameraGroupManager++ @classmethod+ def create(cls, fastapi_app: FastAPI) -> 'FreemocApplication':++ return cls(global_kill_flag=fastapi_app.state.global_kill_flag,+ pipeline_shutdown_event=multiprocessing.Event(),+ realtime_pipeline_manager=RealtimePipelineManager.from_fastapi_app(fastapi_app),+ posthoc_pipeline_manager=PosthocPipelineManager.from_fastapi_app(fastapi_app),+ camera_group_manager=get_or_create_camera_group_manager(app=fastapi_app)+ )++ @property+ def should_continue(self) -> bool:+ return not self.global_kill_flag.value++ async def create_or_update_realtime_pipeline(self,+ pipeline_config: RealtimePipelineConfig) -> RealtimeProcessingPipeline:+ pipeline = self.realtime_pipeline_manager.get_pipeline_by_camera_ids(+ camera_ids=pipeline_config.camera_ids)+ if pipeline is not None:+ pipeline = await self.realtime_pipeline_manager.update_realtime_pipeline(pipeline_config=pipeline_config)+ else:+ camera_group = await self.camera_group_manager.create_or_update_camera_group(+ camera_configs=pipeline_config.camera_configs+ )+ pipeline = await self.realtime_pipeline_manager.create_realtime_pipeline(+ camera_group=camera_group,+ pipeline_config=pipeline_config)+ return pipeline++ async def create_posthoc_calibration_pipeline(self,+ recording_info: RecordingInfo,+ calibration_pipeline_config:CalibrationpipelineConfig) -> RealtimeProcessingPipeline:+ pipeline = await self.posthoc_pipeline_manager.create_posthoc_calibration_pipeline(+ recording_info=recording_info,+ calibration_pipeline_config=calibration_pipeline_config+ )+ return pipeline+ def close_pipelines(self):+ self.realtime_pipeline_manager.close_all_realtime_pipelines()+ self.posthoc_pipeline_manager.close_all_posthoc_pipelines()++ def pause_unpause_pipelines(self):+ self.realtime_pipeline_manager.pause_unpause_pipelines()++ async def start_recording_all(self, recording_info: RecordingInfo):+ await self.camera_group_manager.start_recording_all_groups(recording_info=recording_info)++ async def stop_recording_all(self)-> RecordingInfo| None:+ recording_infos = await self.camera_group_manager.stop_recording_all_groups()+ if len(recording_infos) == 0:+ logger.warning(f"No recordings were stopped.")+ return None+ elif len(recording_infos) >1:+ raise NotImplementedError("Stopping multiple recordings at once is not supported yet.")+ return recording_infos[0]++ def get_latest_frontend_payloads(self, if_newer_than: FrameNumberInt) -> dict[+ PipelineIdString | CameraGroupIdString, tuple[bytes, FrontendPayload | FrameNumberInt]]:+ if len(self.realtime_pipeline_manager.realtime_pipelines) == 0 or all(+ [not p.alive for p in self.realtime_pipeline_manager.realtime_pipelines.values()]):+ # if there are no pipelines, return the latest payloads from the camera groups instead+ cg_payloads = self.camera_group_manager.get_latest_frontend_payloads(if_newer_than=if_newer_than)+ cg_payloads = {camera_group_id: (payload[-1], payload[0]) for camera_group_id, payload in cg_payloads.items()}+ return cg_payloads++ return self.realtime_pipeline_manager.get_latest_frontend_payloads(if_newer_than=if_newer_than)++ def close(self):+ self.global_kill_flag.value = True+ self.pipeline_shutdown_event.set()+ self.realtime_pipeline_manager.close_all_realtime_pipelines()++ def to_app_state(self):+ return AppState.from_app(self)++ async def create_or_update_realtime_calibration_pipeline(self, calibration_task_config: CalibrationpipelineConfig) -> RealtimeProcessingPipeline:+ pipeline = await self.realtime_pipeline_manager.create_or_update_realtime_calibration_pipeline(+ calibration_task_config=calibration_task_config+ )+ return pipeline++++FREEMOCAP_APP: FreemocApplication | None = None+++def create_freemocap_app(fastapi_app) -> FreemocApplication:+ global FREEMOCAP_APP+ if FREEMOCAP_APP is None:+ FREEMOCAP_APP = FreemocApplication.create(fastapi_app=fastapi_app)+ else:+ raise ValueError("FreemocApp already exists!")+ return FREEMOCAP_APP+++def get_freemocap_app() -> FreemocApplication:+ global FREEMOCAP_APP+ if FREEMOCAP_APP is None:+ raise ValueError("FreemocApp does not exist!")+ return FREEMOCAP_APPdiff --git a/freemocap/core/__init__.py b/freemocap/core/__init__.pyindex 04fcf0dc..4019a2e0 100644--- a/freemocap/core/__init__.py+++ b/freemocap/core/__init__.py@@ -14,4 +14,3 @@ from freemocap.system.logging_configuration.log_levels import LogLevelsLOG_LEVEL = LogLevels.TRACEconfigure_logging(LOG_LEVEL)-diff --git a/freemocap/freemocap_app/__init__.py b/freemocap/core/blender/__init__.pysimilarity index 100%rename from freemocap/freemocap_app/__init__.pyrename to freemocap/core/blender/__init__.pydiff --git a/freemocap/core/blender/blender_trajectory_loader.py b/freemocap/core/blender/blender_trajectory_loader.pynew file mode 100644index 00000000..8a3ea73e--- /dev/null+++ b/freemocap/core/blender/blender_trajectory_loader.py@@ -0,0 +1,407 @@+"""+Blender script to load mediapipe body tracking data from CSV+"""++import bpy+import csv+import colorsys+from pathlib import Path+from dataclasses import dataclass+++@dataclass+class TrackingPoint:+ """Single tracking point from mediapipe"""+ frame: int+ keypoint: str+ x: float+ y: float+ z: float+ model: str+ trajectory: str+++def clear_scene() -> None:+ """Remove all objects from the scene"""+ bpy.ops.object.select_all(action='SELECT')+ bpy.ops.object.delete(use_global=False)++ for collection in bpy.data.collections:+ bpy.data.collections.remove(collection)+++def read_mediapipe_csv(*, filepath: str) -> dict[str, list[TrackingPoint]]:+ """+ Read mediapipe tracking data from CSV file++ Args:+ filepath: Path to the CSV file++ Returns:+ Dictionary mapping keypoint names to their tracking points++ Raises:+ FileNotFoundError: If CSV file doesn't exist+ ValueError: If CSV format is invalid+ """+ if not Path(filepath).exists():+ raise FileNotFoundError(f"CSV file not found: {filepath}")++ points_by_keypoint: dict[str, list[TrackingPoint]] = {}++ with open(filepath, 'r') as csvfile:+ reader = csv.DictReader(csvfile)++ if not reader.fieldnames:+ raise ValueError("CSV file is empty or has no headers")++ required_headers = {'frame', 'keypoint', 'x', 'y', 'z', 'model', 'trajectory'}+ if not required_headers.issubset(reader.fieldnames):+ missing = required_headers - set(reader.fieldnames)+ raise ValueError(f"CSV missing required headers: {missing}")++ for row_num, row in enumerate(reader, start=2):+ # Check for required fields+ frame_str = row.get('frame', '').strip()+ keypoint = row.get('keypoint', '').strip()+ x_str = row.get('x', '').strip()+ y_str = row.get('y', '').strip()+ z_str = row.get('z', '').strip()+ model = row.get('model', '').strip()+ trajectory = row.get('trajectory', '').strip()++ if not frame_str or not keypoint:+ raise ValueError(f"Row {row_num}: Missing frame or keypoint")++ # Skip rows with missing coordinates+ if not x_str or not y_str or not z_str:+ continue+ if 'face' in keypoint.lower():+ continue++ try:+ point = TrackingPoint(+ frame=int(frame_str),+ keypoint=keypoint,+ x=float(x_str),+ y=float(y_str),+ z=float(z_str),+ model=model,+ trajectory=trajectory+ )++ if keypoint not in points_by_keypoint:+ points_by_keypoint[keypoint] = []+ points_by_keypoint[keypoint].append(point)++ except ValueError as e:+ raise ValueError(f"Row {row_num}: Invalid data - {e}") from e++ if not points_by_keypoint:+ raise ValueError("No valid tracking data found in CSV")++ return points_by_keypoint+++def get_keypoint_color(*, keypoint_name: str) -> tuple[float, float, float, float]:+ """+ Get a consistent color for a keypoint based on its name++ Args:+ keypoint_name: Name of the keypoint++ Returns:+ RGBA color tuple+ """+ # Use hash to generate consistent color+ hash_val = hash(keypoint_name) % 360+ hue = hash_val / 360.0+ rgb = colorsys.hsv_to_rgb(hue, 0.8, 1.0)+ return (*rgb, 1.0)+++def create_keypoint_sphere(*, keypoint_name: str, radius: float = 0.001) -> bpy.types.Object:+ """+ Create a sphere mesh for a keypoint++ Args:+ keypoint_name: Name of the keypoint+ radius: Sphere radius in Blender units++ Returns:+ Created sphere object+ """+ bpy.ops.mesh.primitive_uv_sphere_add(+ segments=8,+ ring_count=6,+ radius=radius,+ location=(0, 0, 0)+ )++ obj = bpy.context.active_object+ if obj is None:+ raise RuntimeError(f"Failed to create sphere for keypoint {keypoint_name}")++ obj.name = f"keypoint_{keypoint_name}"++ # Add material+ mat = bpy.data.materials.new(name=f"mat_{keypoint_name}")+ mat.use_nodes = True+ mat.node_tree.nodes["Principled BSDF"].inputs[0].default_value = get_keypoint_color(keypoint_name=keypoint_name)+ obj.data.materials.append(mat)++ return obj+++def animate_keypoints(+ *,+ points_by_keypoint: dict[str, list[TrackingPoint]],+ scale_factor: float = 0.001,+ trajectory_filter: str|None = None+) -> dict[str, bpy.types.Object]:+ """+ Create and animate keypoint objects++ Args:+ points_by_keypoint: Dictionary of keypoint names to tracking points+ scale_factor: Scale factor for coordinates (mm to meters)+ trajectory_filter: Only use points with this trajectory type (e.g., "3d_xyz" or "rigid_3d_xyz")++ Returns:+ Dictionary mapping keypoint names to created objects+ """+ keypoint_objects: dict[str, bpy.types.Object] = {}++ for keypoint_name, points in points_by_keypoint.items():+ # Filter by trajectory type if specified+ if trajectory_filter:+ points = [p for p in points if p.trajectory == trajectory_filter]+ if not points:+ continue++ # Create sphere for this keypoint+ obj = create_keypoint_sphere(keypoint_name=keypoint_name)+ keypoint_objects[keypoint_name] = obj++ # Sort points by frame+ points = sorted(points, key=lambda p: p.frame)++ # Apply keyframes+ for point in points:+ # Convert coordinates+ # Mediapipe: X-right, Y-down, Z-forward+ # Blender: X-right, Y-forward, Z-up+ location = (+ point.x * scale_factor,+ -point.z * scale_factor, # Forward becomes -Z+ -point.y * scale_factor # Down becomes -Y (up in Blender)+ )++ obj.location = location+ obj.keyframe_insert(data_path="location", frame=point.frame + 1)++ return keypoint_objects+++def create_skeleton_bones(*, keypoint_objects: dict[str, bpy.types.Object]) -> None:+ """+ Create edge connections between related keypoints to form a skeleton++ Args:+ keypoint_objects: Dictionary of keypoint objects+ """+ # Define bone connections for mediapipe body+ connections = [+ # Face+ ("nose", "left_eye_inner"),+ ("left_eye_inner", "left_eye"),+ ("left_eye", "left_eye_outer"),+ ("left_eye_outer", "left_ear"),+ ("nose", "right_eye_inner"),+ ("right_eye_inner", "right_eye"),+ ("right_eye", "right_eye_outer"),+ ("right_eye_outer", "right_ear"),+ ("mouth_left", "mouth_right"),++ # Arms+ ("left_shoulder", "left_elbow"),+ ("left_elbow", "left_wrist"),+ ("left_wrist", "left_pinky"),+ ("left_wrist", "left_index"),+ ("left_wrist", "left_thumb"),+ ("right_shoulder", "right_elbow"),+ ("right_elbow", "right_wrist"),+ ("right_wrist", "right_pinky"),+ ("right_wrist", "right_index"),+ ("right_wrist", "right_thumb"),++ # Torso+ ("left_shoulder", "right_shoulder"),+ ("left_shoulder", "left_hip"),+ ("right_shoulder", "right_hip"),+ ("left_hip", "right_hip"),++ # Legs+ ("left_hip", "left_knee"),+ ("left_knee", "left_ankle"),+ ("left_ankle", "left_heel"),+ ("left_ankle", "left_foot_index"),+ ("left_heel", "left_foot_index"),+ ("right_hip", "right_knee"),+ ("right_knee", "right_ankle"),+ ("right_ankle", "right_heel"),+ ("right_ankle", "right_foot_index"),+ ("right_heel", "right_foot_index"),+ ]++ # Create mesh edges for skeleton visualization+ vertices = []+ edges = []+ vertex_map: dict[str, int] = {}++ # Build vertex list from unique keypoints in connections+ for start_name, end_name in connections:+ if start_name not in keypoint_objects or end_name not in keypoint_objects:+ continue++ if start_name not in vertex_map:+ vertex_map[start_name] = len(vertices)+ vertices.append(keypoint_objects[start_name].location)++ if end_name not in vertex_map:+ vertex_map[end_name] = len(vertices)+ vertices.append(keypoint_objects[end_name].location)++ edges.append((vertex_map[start_name], vertex_map[end_name]))++ if not vertices:+ return++ # Create mesh+ mesh = bpy.data.meshes.new(name="skeleton_mesh")+ mesh.from_pydata(vertices, edges, [])+ mesh.update()++ # Create object+ skeleton_obj = bpy.data.objects.new("skeleton", mesh)+ bpy.context.collection.objects.link(skeleton_obj)++ # Add vertex parent constraints for each vertex to follow its keypoint+ for keypoint_name, vertex_index in vertex_map.items():+ if keypoint_name not in keypoint_objects:+ continue++ # Use hooks to connect vertices to keypoint objects+ hook_modifier = skeleton_obj.modifiers.new(+ name=f"hook_{keypoint_name}",+ type='HOOK'+ )+ hook_modifier.object = keypoint_objects[keypoint_name]+ hook_modifier.vertex_indices_set([vertex_index])+++def setup_scene(*, num_frames: int) -> None:+ """+ Configure scene settings for the animation++ Args:+ num_frames: Total number of frames+ """+ scene = bpy.context.scene+ scene.frame_start = 1+ scene.frame_end = num_frames+ scene.frame_set(1)++ # Set viewport shading+ for area in bpy.context.screen.areas:+ if area.type == 'VIEW_3D':+ for space in area.spaces:+ if space.type == 'VIEW_3D':+ space.shading.type = 'SOLID'+ space.overlay.show_floor = True+ space.overlay.show_axis_x = True+ space.overlay.show_axis_y = True+++def main(*, csv_filepath: str, trajectory_type: str = "3d_xyz", create_skeleton: bool = True) -> None:+ """+ Main function to load mediapipe trajectory data into Blender++ Args:+ csv_filepath: Path to the CSV file+ trajectory_type: Which trajectory to use ("3d_xyz" or "rigid_3d_xyz")+ create_skeleton: Whether to create bone connections+ """+ print("=" * 60)+ print("MEDIAPIPE TRAJECTORY LOADER")+ print("=" * 60)++ # Clear existing scene+ print("Clearing scene...")+ clear_scene()++ # Read CSV data+ print(f"Reading CSV: {csv_filepath}")+ points_by_keypoint = read_mediapipe_csv(filepath=csv_filepath)++ # Get frame range+ all_frames = set()+ for points in points_by_keypoint.values():+ all_frames.update(p.frame for p in points)++ if not all_frames:+ raise ValueError("No frames found in data")++ min_frame = min(all_frames)+ max_frame = max(all_frames)+ num_frames = max_frame - min_frame + 1++ print(f"Found {len(points_by_keypoint)} keypoints")+ print(f"Frames: {min_frame} to {max_frame} ({num_frames} total)")+ print(f"Using trajectory: {trajectory_type}")++ # Create and animate keypoints+ print("Creating animated keypoints...")+ keypoint_objects = animate_keypoints(+ points_by_keypoint=points_by_keypoint,+ scale_factor=1,+ trajectory_filter=trajectory_type+ )++ if not keypoint_objects:+ raise RuntimeError(f"No keypoints created for trajectory type: {trajectory_type}")++ print(f"Created {len(keypoint_objects)} keypoint objects")++ # Create skeleton connections+ if create_skeleton:+ print("Creating skeleton connections...")+ create_skeleton_bones(keypoint_objects=keypoint_objects)++ # Setup scene+ setup_scene(num_frames=num_frames)++ print("=" * 60)+ print("โ LOAD COMPLETE")+ print("Press SPACE to play animation")+ print("=" * 60)+++# ============================================================================+# USAGE+# ============================================================================++if __name__ == "__main__" or __name__ =='<run_path>':+ # UPDATE THIS PATH+ CSV_FILE = r"C:\Users\jonma\freemocap_data\recording_sessions\freemocap_test_data\output_data\freemocap_data_by_frame.csv"+ try:+ main(+ csv_filepath=CSV_FILE,+ trajectory_type="3d_xyz", # or "rigid_3d_xyz"+ create_skeleton=True+ )+ except Exception as e:+ print(f"ERROR: {e}")+ import traceback+ traceback.print_exc()+ raise\ No newline at end of filediff --git a/freemocap/freemocap_app/freemocap_app_lifespan/__init__.py b/freemocap/core/image_overlay/__init__.pysimilarity index 100%rename from freemocap/freemocap_app/freemocap_app_lifespan/__init__.pyrename to freemocap/core/image_overlay/__init__.pydiff --git a/freemocap/core/image_overlay/charuco_overlay_data.py b/freemocap/core/image_overlay/charuco_overlay_data.pynew file mode 100644index 00000000..18db04b1--- /dev/null+++ b/freemocap/core/image_overlay/charuco_overlay_data.py@@ -0,0 +1,113 @@+from typing import Literal++from pydantic import BaseModel, Field+from skellycam.core.types.type_overloads import CameraIdString+from skellytracker.trackers.charuco_tracker.charuco_observation import CharucoObservation+++class CharucoPointModel(BaseModel):+ """A single detected Charuco corner point."""+ id: int = Field(description="Charuco corner ID")+ x: float = Field(description="X coordinate in image space")+ y: float = Field(description="Y coordinate in image space")+++class ArucoMarkerModel(BaseModel):+ """A single detected ArUco marker with 4 corners."""+ id: int = Field(description="ArUco marker ID")+ corners: list[tuple[float, float]] = Field(+ min_length=4,+ max_length=4+ )+++class CharucoMetadataModel(BaseModel):+ """Metadata about the charuco detection."""+ n_charuco_detected: int = Field(description="Number of Charuco corners detected")+ n_charuco_total: int = Field(description="Total number of Charuco corners on board")+ n_aruco_detected: int = Field(description="Number of ArUco markers detected")+ n_aruco_total: int = Field(description="Total number of ArUco markers on board")+ has_pose: bool = Field(description="Whether board pose was successfully estimated")+ image_width: int = Field(description="Width of the image in pixels")+ image_height: int = Field(description="Height of the image in pixels")+++class CharucoOverlayData(BaseModel):+ """Complete message for transmitting charuco observation over websocket."""+ message_type: Literal["charuco_overlay"] = "charuco_overlay"+ camera_id: CameraIdString = Field(description="ID of the camera that produced this observation")+ frame_number: int = Field(description="Frame number of this observation")+ charuco_corners: list[CharucoPointModel] = Field(+ default_factory=list,+ description="List of detected Charuco corner points"+ )+ aruco_markers: list[ArucoMarkerModel] = Field(+ default_factory=list,+ description="List of detected ArUco markers"+ )+ metadata: CharucoMetadataModel = Field(description="Detection metadata and statistics")++ @classmethod+ def from_charuco_observation(+ cls,+ *,+ camera_id: CameraIdString,+ observation: CharucoObservation,+ scale: float = .5, ):+ """+ Convert CharucoObservation to Pydantic message model for websocket transmission.++ Args:+ camera_id: ID of the camera that produced this observation+ observation: The CharucoObservation to serialize++ Returns:+ CharucoObservationMessage ready for JSON serialization+ """++ # Build Charuco corner models+ charuco_corners: list[CharucoPointModel] = []+ if not observation.charuco_empty:+ for corner_id, corner_coords in observation.charuco_corners_dict.items():+ charuco_corners.append(+ CharucoPointModel(+ id=int(corner_id),+ x=float(corner_coords[0]) * scale,+ y=float(corner_coords[1]) * scale,+ )+ )++ # Build ArUco marker models+ aruco_markers: list[ArucoMarkerModel] = []+ if not observation.aruco_empty:+ for marker_id, marker_corners in observation.aruco_corners_dict.items():+ aruco_markers.append(+ ArucoMarkerModel(+ id=int(marker_id),+ corners=[+ (float(marker_corners[i][0] * scale),+ float(marker_corners[i][1] * scale))+ for i in range(4)+ ],+ )+ )++ # Build metadata model+ metadata = CharucoMetadataModel(+ n_charuco_detected=0 if observation.charuco_empty else len(observation.detected_charuco_corner_ids),+ n_charuco_total=len(observation.all_charuco_ids),+ n_aruco_detected=0 if observation.aruco_empty else len(observation.detected_aruco_marker_ids),+ n_aruco_total=len(observation.all_aruco_ids),+ has_pose=observation.charuco_board_translation_vector is not None,+ image_width=observation.image_size[0],+ image_height=observation.image_size[1],+ )++ # Build complete message+ return cls(+ camera_id=camera_id,+ frame_number=observation.frame_number,+ charuco_corners=charuco_corners,+ aruco_markers=aruco_markers,+ metadata=metadata,+ )diff --git a/freemocap/core/image_overlay/mediapipe_overlay_data.py b/freemocap/core/image_overlay/mediapipe_overlay_data.pynew file mode 100644index 00000000..38fa48ac--- /dev/null+++ b/freemocap/core/image_overlay/mediapipe_overlay_data.py@@ -0,0 +1,171 @@+from typing import Literal+from pydantic import BaseModel, Field++from skellycam.core.types.type_overloads import CameraIdString+from skellytracker.trackers.mediapipe_tracker.mediapipe_observation import MediapipeObservation+++class MediapipePointModel(BaseModel):+ """A single detected Mediapipe landmark point."""+ name: str = Field(description="Landmark name")+ x: float = Field(description="X coordinate in image space")+ y: float = Field(description="Y coordinate in image space")+ z: float = Field(description="Z coordinate (normalized depth)")+ visibility: float = Field(description="Visibility confidence 0-1", ge=0, le=1)+++class MediapipeMetadataModel(BaseModel):+ """Metadata about the mediapipe detection."""+ n_body_detected: int = Field(description="Number of body landmarks detected")+ n_right_hand_detected: int = Field(description="Number of right hand landmarks detected")+ n_left_hand_detected: int = Field(description="Number of left hand landmarks detected")+ n_face_detected: int = Field(description="Number of face landmarks detected")+ image_width: int = Field(description="Width of the image in pixels")+ image_height: int = Field(description="Height of the image in pixels")+++class MediapipeOverlayData(BaseModel):+ """Complete message for transmitting mediapipe observation over websocket."""+ message_type: Literal["mediapipe_overlay"] = "mediapipe_overlay"+ camera_id: CameraIdString = Field(description="ID of the camera that produced this observation")+ frame_number: int = Field(description="Frame number of this observation")+ body_points: list[MediapipePointModel] = Field(+ default_factory=list,+ description="List of detected body landmark points"+ )+ right_hand_points: list[MediapipePointModel] = Field(+ default_factory=list,+ description="List of detected right hand landmark points"+ )+ left_hand_points: list[MediapipePointModel] = Field(+ default_factory=list,+ description="List of detected left hand landmark points"+ )+ face_points: list[MediapipePointModel] = Field(+ default_factory=list,+ description="List of detected face landmark points"+ )+ metadata: MediapipeMetadataModel = Field(description="Detection metadata and statistics")++ @classmethod+ def from_mediapipe_observation(+ cls,+ *,+ camera_id: CameraIdString,+ observation: MediapipeObservation,+ scale: float =.5,+ include_face: bool = True,+ face_type: str = "contour", # "contour" or "tesselation"+ ):+ """+ Convert MediapipeObservation to Pydantic message model for websocket transmission.++ Args:+ camera_id: ID of the camera that produced this observation+ observation: The MediapipeObservation to serialize+ scale: Scale factor for coordinates (default 1.0)+ include_face: Whether to include face landmarks+ face_type: Type of face landmarks to include ("contour" or "tesselation")++ Returns:+ MediapipeOverlayData ready for JSON serialization+ """++ # Get all points with proper scaling+ all_points = observation.all_points(dimensions=3, face_type=face_type, scale_by=scale)++ # Build body points+ body_points: list[MediapipePointModel] = []+ if observation.pose_landmarks is not None:+ for name in observation.body_landmark_names:+ if name in all_points:+ x, y, z = all_points[name]+ # Get visibility from the original landmark+ landmark_idx = observation.body_landmark_names.index(name)+ visibility = observation.pose_landmarks.landmark[landmark_idx].visibility if observation.pose_landmarks else 0.0++ body_points.append(+ MediapipePointModel(+ name=name,+ x=float(x),+ y=float(y),+ z=float(z),+ visibility=float(visibility),+ )+ )++ # Build right hand points+ right_hand_points: list[MediapipePointModel] = []+ if observation.right_hand_landmarks is not None:+ for name in observation.right_hand_landmark_names:+ if name in all_points:+ x, y, z = all_points[name]+ right_hand_points.append(+ MediapipePointModel(+ name=name.replace("right_hand.", ""), # Remove prefix+ x=float(x),+ y=float(y),+ z=float(z),+ visibility=1.0, # Hand landmarks don't have visibility in MediaPipe+ )+ )++ # Build left hand points+ left_hand_points: list[MediapipePointModel] = []+ if observation.left_hand_landmarks is not None:+ for name in observation.left_hand_landmark_names:+ if name in all_points:+ x, y, z = all_points[name]+ left_hand_points.append(+ MediapipePointModel(+ name=name.replace("left_hand.", ""), # Remove prefix+ x=float(x),+ y=float(y),+ z=float(z),+ visibility=1.0, # Hand landmarks don't have visibility in MediaPipe+ )+ )++ # Build face points (if requested)+ face_points: list[MediapipePointModel] = []+ if include_face and observation.face_landmarks is not None:+ face_landmark_names = (+ observation.face_contour_landmark_names+ if face_type == "contour"+ else [f"face_{i:04d}" for i in range(observation.num_face_tesselation_points)]+ )++ for name in face_landmark_names:+ if name in all_points:+ x, y, z = all_points[name]+ face_points.append(+ MediapipePointModel(+ name=name,+ x=float(x),+ y=float(y),+ z=float(z),+ visibility=1.0, # Face landmarks don't have visibility+ )+ )++ # Build metadata+ metadata = MediapipeMetadataModel(+ n_body_detected=len(body_points),+ n_right_hand_detected=len(right_hand_points),+ n_left_hand_detected=len(left_hand_points),+ n_face_detected=len(face_points),+ image_width=observation.image_size[0],+ image_height=observation.image_size[1],+ )++ # Build complete message+ return cls(+ camera_id=camera_id,+ frame_number=observation.frame_number,+ body_points=body_points,+ right_hand_points=right_hand_points,+ left_hand_points=left_hand_points,+ face_points=face_points,+ metadata=metadata,+ )+diff --git a/freemocap/old/__init__.py b/freemocap/core/pipeline/__init__.pysimilarity index 100%rename from freemocap/old/__init__.pyrename to freemocap/core/pipeline/__init__.pydiff --git a/freemocap/core/pipeline/frontend_payload.py b/freemocap/core/pipeline/frontend_payload.pynew file mode 100644index 00000000..a8823219--- /dev/null+++ b/freemocap/core/pipeline/frontend_payload.py@@ -0,0 +1,74 @@+import logging++from pydantic import BaseModel, ConfigDict+from skellycam.core.types.type_overloads import CameraIdString++from freemocap.core.image_overlay.charuco_overlay_data import CharucoOverlayData+from freemocap.core.image_overlay.mediapipe_overlay_data import MediapipeOverlayData+from freemocap.core.types.type_overloads import TrackedPointNameString+from freemocap.pubsub.pubsub_topics import AggregationNodeOutputMessage+from skellyforge.data_models.trajectory_3d import Point3d++logger = logging.getLogger(__name__)++# Union type for all possible overlay data types+ObservationOverlayData = CharucoOverlayData | MediapipeOverlayData+++class FrontendPayload(BaseModel):+ """Complete payload for frontend visualization"""+ model_config = ConfigDict(+ arbitrary_types_allowed=True,+ validate_assignment=False+ )++ frame_number: int+ # Now supports multiple observation types+ observation_overlays: dict[CameraIdString, ObservationOverlayData]+ tracked_points3d: dict[TrackedPointNameString, Point3d] = {}++ @classmethod+ def from_aggregation_output(+ cls,+ aggregation_output: AggregationNodeOutputMessage,+ ) -> "FrontendPayload":+ """Create frontend payload from aggregation node output"""++ # Combine all observation types into single dict+ observation_overlays: dict[CameraIdString, ObservationOverlayData] = {}++ # Add charuco overlays if present+ if hasattr(aggregation_output, 'charuco_overlay_data'):+ observation_overlays.update(aggregation_output.charuco_overlay_data)++ # Add mediapipe overlays if present+ if hasattr(aggregation_output, 'mediapipe_overlay_data'):+ observation_overlays.update(aggregation_output.mediapipe_overlay_data)++ # Add other overlay types as they're implemented+ # if hasattr(aggregation_output, 'rtmpose_overlay_data'):+ # observation_overlays.update(aggregation_output.rtmpose_overlay_data)++ return cls(+ frame_number=aggregation_output.frame_number,+ observation_overlays=observation_overlays,+ tracked_points3d=aggregation_output.tracked_points3d+ )++ def to_websocket_dict(self) -> dict:+ """+ Convert to dictionary suitable for JSON serialization over websocket.+ """+ payload = {+ "frame_number": self.frame_number,+ "observation_overlays": {+ camera_id: overlay.model_dump()+ for camera_id, overlay in self.observation_overlays.items()+ },+ "tracked_points3d": {+ name: point.model_dump()+ for name, point in self.tracked_points3d.items()+ }+ }++ return payload\ No newline at end of filediff --git a/freemocap/core/pipeline/pipeline_configs.py b/freemocap/core/pipeline/pipeline_configs.pynew file mode 100644index 00000000..e500be41--- /dev/null+++ b/freemocap/core/pipeline/pipeline_configs.py@@ -0,0 +1,52 @@+from abc import ABC++from pydantic import BaseModel, Field, ConfigDict+from skellycam.core.camera.config.camera_config import CameraConfigs+from skellycam.core.types.type_overloads import CameraIdString++from skellytracker.trackers.mediapipe_tracker.mediapipe_detector import MediapipeDetectorConfig+from skellytracker.trackers.charuco_tracker.charuco_detector import CharucoDetectorConfig++++class PipelineConfigABC(BaseModel, ABC):+ pass+++class CalibrationpipelineConfig(BaseModel):+ # model_config = ConfigDict(extra="forbid")+ calibration_recording_folder: str | None = Field(default=None, alias="calibrationRecordingFolder")+ charuco_board_x_squares: int = Field(gt=0, default=5, alias="charucoBoardXSquares")+ charuco_board_y_squares: int = Field(gt=0, default=3, alias="charucoBoardYSquares")+ charuco_square_length: float = Field(gt=0, default=1, alias="charucoSquareLength")+ # min_shared_views_per_camera: int = Field(gt=0, default=200, alias="minSharedViewsPerCamera")+ # auto_stop_on_min_view_count: bool = Field(default=True, alias="autoStopOnMinViewCount")+ # auto_process_recording: bool = Field(default=True, alias="autoProcessRecording")++ @property+ def detector_config(self) -> CharucoDetectorConfig:+ return CharucoDetectorConfig(+ squares_x=self.charuco_board_x_squares,+ squares_y=self.charuco_board_y_squares,+ square_length=self.charuco_square_length,+ )+class MocapPipelineTaskConfig(BaseModel):+ @property+ def detector_config(self) -> MediapipeDetectorConfig:+ return MediapipeDetectorConfig()++class RealtimePipelineConfig(BaseModel):+ camera_configs: CameraConfigs+ calibration_task_config: CalibrationpipelineConfig = Field(default_factory=CalibrationpipelineConfig)+ mocap_task_config: MocapPipelineTaskConfig = Field(default_factory=MocapPipelineTaskConfig)++ @property+ def camera_ids(self) -> list[CameraIdString]:+ return list(self.camera_configs.keys())++ @classmethod+ def from_camera_configs(cls, *, camera_configs: CameraConfigs) -> "RealtimePipelineConfig":+ return cls(+ camera_configs=camera_configs,++ )diff --git a/freemocap/core/pipeline/pipeline_ipc.py b/freemocap/core/pipeline/pipeline_ipc.pynew file mode 100644index 00000000..6caee26d--- /dev/null+++ b/freemocap/core/pipeline/pipeline_ipc.py@@ -0,0 +1,52 @@+import multiprocessing+import uuid+from dataclasses import dataclass, field++from skellycam.core.ipc.pubsub.pubsub_topics import SetShmTopic++from freemocap.core.types.type_overloads import PipelineIdString+from freemocap.pubsub.pubsub_manager import PubSubTopicManager, create_pipeline_pubsub_manager+from freemocap.system.logging_configuration.handlers.websocket_log_queue_handler import get_websocket_log_queue+from freemocap.utilities.check_main_processs_heartbeat import check_main_process_heartbeat+++@dataclass+class PipelineIPC:+ pipeline_id: PipelineIdString+ pubsub: PubSubTopicManager+ ws_queue: multiprocessing.Queue+ global_kill_flag: multiprocessing.Value+ heartbeat_timestamp: multiprocessing.Value+ pipeline_shutdown_flag: multiprocessing.Value = field(default_factory=lambda: multiprocessing.Value('b', False))++ @classmethod+ def create(cls,+ global_kill_flag: multiprocessing.Value,+ heartbeat_timestamp: multiprocessing.Value,+ pipeline_id: PipelineIdString | None = None):+ if pipeline_id is None:+ pipeline_id = str(uuid.uuid4())[:6]+ pubsub = create_pipeline_pubsub_manager(pipeline_id=pipeline_id)+ return cls(+ pipeline_id=pipeline_id,+ pubsub=pubsub,+ global_kill_flag=global_kill_flag,+ heartbeat_timestamp=heartbeat_timestamp,+ ws_queue=get_websocket_log_queue(),+ )++ @property+ def should_continue(self) -> bool:+ return (not self.global_kill_flag.value+ and not self.pipeline_shutdown_flag.value+ and check_main_process_heartbeat(global_kill_flag=self.global_kill_flag,+ heartbeat_timestamp=self.heartbeat_timestamp, ))++ def shutdown_pipeline(self):+ self.pipeline_shutdown_flag.value = True+ self.pubsub.close()++ def kill_everything(self):+ self.shutdown_pipeline()+ self.global_kill_flag.value = True+diff --git a/freemocap/old/core_processes/__init__.py b/freemocap/core/pipeline/posthoc_pipelines/__init__.pysimilarity index 100%rename from freemocap/old/core_processes/__init__.pyrename to freemocap/core/pipeline/posthoc_pipelines/__init__.pydiff --git a/freemocap/old/core_processes/capture_volume_calibration/__init__.py b/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/__init__.pysimilarity index 100%rename from freemocap/old/core_processes/capture_volume_calibration/__init__.pyrename to freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/__init__.pydiff --git a/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/__init__.py b/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/calibration_helpers/__init__.pysimilarity index 100%rename from freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/__init__.pyrename to freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/calibration_helpers/__init__.pydiff --git a/freemocap/core/pipelines/calibration_pipeline/camera_math_models.py b/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/calibration_helpers/camera_math_models.pysimilarity index 91%rename from freemocap/core/pipelines/calibration_pipeline/camera_math_models.pyrename to freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/calibration_helpers/camera_math_models.pyindex c5c782c5..f28fcafd 100644--- a/freemocap/core/pipelines/calibration_pipeline/camera_math_models.py+++ b/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/calibration_helpers/camera_math_models.py@@ -4,7 +4,8 @@ from numpydantic import NDArray, Shapefrom pydantic import BaseModel, model_validatorfrom scipy.spatial.transform import Rotation as R-from freemocap.core.pipelines.calibration_pipeline.calibration_numpy_types import QuaternionArray, RotationVectorArray, \+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.calibration_helpers.calibration_numpy_types import QuaternionArray, \+ RotationVectorArray, \RotationMatrixArray, TranslationVectorArray, CameraExtrinsicsMatrix, CameraDistortionCoefficientsArray, \CameraMatrixArray@@ -93,10 +94,11 @@ class TransformationMatrix(BaseModel):def from_extrinsics(cls, extrinsics_matrix: CameraExtrinsicsMatrix, reference_frame: str):rotation_matrix = np.squeeze(extrinsics_matrix[:3, :3])translation_vector = np.squeeze(extrinsics_matrix[:3, 3])- return cls.from_rotation_translation(rotation_vector=RotationVector(vector=np.squeeze(cv2.Rodrigues(rotation_matrix)[0]),- reference_frame=reference_frame),- translation_vector=TranslationVector(vector=translation_vector,- reference_frame=reference_frame))+ return cls.from_rotation_translation(+ rotation_vector=RotationVector(vector=np.squeeze(cv2.Rodrigues(rotation_matrix)[0]),+ reference_frame=reference_frame),+ translation_vector=TranslationVector(vector=translation_vector,+ reference_frame=reference_frame))@classmethoddef from_rotation_translation(cls,@@ -136,13 +138,13 @@ class TransformationMatrix(BaseModel):@propertydef rotation_vector(self) -> RotationVector:- return RotationVector(vector=np.squeeze(cv2.Rodrigues(self.rotation_matrix)[0]), reference_frame=self.reference_frame)+ return RotationVector(vector=np.squeeze(cv2.Rodrigues(self.rotation_matrix)[0]),+ reference_frame=self.reference_frame)@propertydef extrinsics_matrix(self) -> CameraExtrinsicsMatrix:return self.matrix[:3, :]-def get_inverse(self):inverse_rotation_matrix = self.rotation_matrix.Tinverse_translation_vector = -inverse_rotation_matrix @ self.translation_vector.vector@@ -160,7 +162,6 @@ class TransformationMatrix(BaseModel):# Perform matrix multiplication and use self's reference framereturn TransformationMatrix(matrix=self.matrix @ other.matrix, reference_frame=self.reference_frame)-def __str__(self) -> str:return (f"\treference_frame={self.reference_frame},\n"f"\tmatrix=\n"@@ -186,12 +187,13 @@ class CameraDistortionCoefficients(BaseModel):`s` values refer to thin prism distortion coefficients`ฯ` values refer to x/y values of the 'tilted sensor' model- NOTE - RECOMMEND USING 5 VALUES, things get weird with more than 5+ NOTE - RECOMMEND USING 4 or 5 VALUES, things get weird with more than 5"""coefficients: CameraDistortionCoefficientsArray@model_validator(mode="after")def validate(self):+ self.coefficients = np.squeeze(self.coefficients)if len(self.coefficients) not in [4, 5, 8, 12, 14]:raise ValueError("Invalid number of distortion coefficients. Must be 4, 5, 8, 12, or 14.")return selfdiff --git a/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/calibration_helpers/charuco_groundplane_utils.py b/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/calibration_helpers/charuco_groundplane_utils.pynew file mode 100644index 00000000..ec1b55f7--- /dev/null+++ b/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/calibration_helpers/charuco_groundplane_utils.py@@ -0,0 +1,130 @@+import numpy as np+import pandas as pd+++class CharucoVisibilityError(RuntimeError):+ """Raised when no frame satisfies the โall-corners-visible & stationaryโ criteria."""+++class CharucoVelocityError(RuntimeError):+ """Raised when the velocity of the ChArUco corners is too high to be considered stationary."""+++def get_charuco_x_and_y_idx(number_of_squares_width: int, number_of_squares_height: int):+ """+ For a given board definition, get the corner marker indexes needed to make the x and y vectors+ """++ num_cols = number_of_squares_width - 1 # corner columns+ num_rows = number_of_squares_height - 1 # corner rows++ idx_x = num_cols * (num_rows - 1)+ idx_y = num_cols - 1++ return idx_x, idx_y+++def get_unit_vector(vector: np.ndarray) -> np.ndarray:+ return vector / np.linalg.norm(vector)+++def compute_basis_vectors_of_new_reference(+ charuco_frame: np.ndarray, number_of_squares_width: int, number_of_squares_height: int+) -> tuple[np.ndarray, np.ndarray, np.ndarray]:+ origin = charuco_frame[0]++ idx_x, idx_y = get_charuco_x_and_y_idx(+ number_of_squares_width=number_of_squares_width, number_of_squares_height=number_of_squares_height+ )++ x_vec = charuco_frame[idx_x] - origin+ y_vec = charuco_frame[idx_y] - origin++ x_hat = get_unit_vector(x_vec)+ y_hat_raw = get_unit_vector(y_vec)+ z_hat = get_unit_vector(np.cross(x_hat, y_hat_raw))+ y_hat = get_unit_vector(np.cross(z_hat, x_hat))++ return x_hat, y_hat, z_hat+++def find_still_frame(points_velocity: np.ndarray, max_allowed_velocity: float = 1.0) -> int:+ visible_frames = ~np.isnan(points_velocity).any(axis=1)+ if not np.any(visible_frames):+ raise CharucoVisibilityError(+ "No frame found where all three required ChArUco corners are on the ground and visible."+ )++ max_velocity_per_frame = np.nanmax(points_velocity[visible_frames], axis=1)+ if np.nanmin(max_velocity_per_frame) > max_allowed_velocity:+ raise CharucoVelocityError(+ f"All frames have ChArUco corner velocity > {max_allowed_velocity:.2f} mm/s โ check that the board is stationary."+ )++ best_visible_index = int(np.nanargmin(max_velocity_per_frame))+ best_velocity_index = np.where(visible_frames)[0][+ best_visible_index+ ] # maps back to the original array (which we sliced earlier to get rid of rows with nans)+ return best_velocity_index+++def find_good_frame(+ charuco_data3d_fr_id_xyz: np.ndarray,+ number_of_squares_width: int,+ number_of_squares_height: int,+ frame_to_use: int = 0,+ search_range: int = 120,+):+ if frame_to_use == 0:+ slice_to_search = slice(0, search_range)+ elif frame_to_use == -1:+ slice_to_search = slice(-search_range, None)+ elif frame_to_use > 0:+ start_frame = max(0, frame_to_use - search_range)+ end_frame = min(charuco_data3d_fr_id_xyz.shape[0], frame_to_use + search_range)+ slice_to_search = slice(start_frame, end_frame)+ else:+ raise ValueError(f"Invalid value for frame_to_use: {frame_to_use}")++ idx_x, idx_y = get_charuco_x_and_y_idx(+ number_of_squares_width=number_of_squares_width, number_of_squares_height=number_of_squares_height+ )++ charuco_corners = charuco_data3d_fr_id_xyz[slice_to_search, [0, idx_y, idx_x]]+ charuco_corners_velocity = np.linalg.norm(np.diff(charuco_corners, axis=0), axis=2)+ best_velocity_frame = find_still_frame(points_velocity=charuco_corners_velocity)++ frame_offset = slice_to_search.start or 0+ best_position_frame = best_velocity_frame + frame_offset + 1+ return best_position_frame+++def interpolate_skeleton_data(skeleton_data: np.ndarray, method_to_use='linear', order=3) -> np.ndarray:+ """ Takes in a 3d skeleton numpy array from freemocap and interpolates missing NaN values"""+ num_frames = skeleton_data.shape[0]+ num_markers = skeleton_data.shape[1]++ freemocap_interpolated_data = np.empty((num_frames, num_markers, 3))++ for marker in range(num_markers):+ this_marker_skel3d_data = skeleton_data[:, marker, :]+ df = pd.DataFrame(this_marker_skel3d_data)+ df2 = df.interpolate(method=method_to_use, axis=0,+ order=order) # use pandas interpolation methods to fill in missing data+ # df.interpolate(method=method_to_use, order = 5)+ this_marker_interpolated_skel3d_array = np.array(df2)+ # replace the remaining NaN values (the ones that often happen at the start of the recording)+ this_marker_interpolated_skel3d_array = np.where(np.isfinite(this_marker_interpolated_skel3d_array),+ this_marker_interpolated_skel3d_array,+ np.nanmean(this_marker_interpolated_skel3d_array))++ freemocap_interpolated_data[:, marker, :] = this_marker_interpolated_skel3d_array++ return freemocap_interpolated_data+++def skellyforge_data(raw_charuco_data: np.ndarray):+ interpolated_data = interpolate_skeleton_data(+ skeleton_data=raw_charuco_data+ )+ return interpolated_datadiff --git a/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/calibration_helpers/charuco_observation_aggregator.py b/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/calibration_helpers/charuco_observation_aggregator.pynew file mode 100644index 00000000..6b93e209--- /dev/null+++ b/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/calibration_helpers/charuco_observation_aggregator.py@@ -0,0 +1,388 @@+import logging+from pathlib import Path++import cv2+import numpy as np+from pydantic import BaseModel, Field+from skellycam.core.types.type_overloads import CameraIdString+from skellytracker.trackers.charuco_tracker.charuco_observation import CharucoObservation++from freemocap.core.pipeline.pipeline_configs import CalibrationpipelineConfig+from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.freemocap_anipose import \+ AniposeCameraGroup, AniposeCharucoBoard, AniposeCamera+from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.point_triangulator import PointTriangulator+from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.charuco_groundplane_utils import \+ interpolate_skeleton_data, find_good_frame, CharucoVisibilityError, CharucoVelocityError, \+ compute_basis_vectors_of_new_reference, skellyforge_data+from freemocap.core.pipeline.posthoc_pipelines.posthoc_mocap_pipeline.mocap_helpers.charuco_model_from_observations import \+ charuco_model_from_observations+from freemocap.core.pipeline.posthoc_pipelines.video_helper import VideoMetadata+from freemocap.core.types.type_overloads import VideoIdString++from freemocap.system.default_paths import get_default_freemocap_base_folder_path++from skellycam.core.recorders.videos.recording_info import RecordingInfo+from skellytracker.trackers.base_tracker.base_tracker_abcs import BaseRecorder++from skellyforge.skellymodels.managers.board import Board+logger = logging.getLogger(__name__)++CharucoObservations = dict[CameraIdString, CharucoObservation | None]+++def get_calibrations_folder_path() -> Path:+ """Get the main calibrations folder path."""+ return Path(get_default_freemocap_base_folder_path()) / "calibrations"+++def create_camera_calibration_file_name(recording_name: str) -> str:+ """Create a standardized camera calibration filename."""+ return f"{recording_name}_camera_calibration.toml"++LAST_SUCCESSFUL_CAMERA_CALIBRATION_STRING = "last_successful_camera_calibration"+def get_last_successful_calibration_toml_path() -> Path:+ """Get the path for the last successful calibration TOML file."""+ return get_calibrations_folder_path() / f"{LAST_SUCCESSFUL_CAMERA_CALIBRATION_STRING}.toml"++++class CharucoObservationAggregator(BaseModel):+ anipose_camera_ordering: list[CameraIdString]+ # anipose handles camera rows by the ordering of cameras in CameraGroup - so we need to use that ordering when we pass the camera rows to anipose+ individual_camera_rows: dict[CameraIdString, list] = Field(default_factory=dict)+ @classmethod+ def from_charuco_observation_payload(cls,+ charuco_observations_by_camera: CharucoObservations,+ anipose_camera_ordering: list[CameraIdString]):+ if set(charuco_observations_by_camera.keys()) != set(anipose_camera_ordering):+ raise ValueError("individual_camera_rows and anipose_camera_ordering must have the same camera ids")+ camera_rows = {}+ nan_row: list = []+ for camera_id, charuco_observation in charuco_observations_by_camera.items():+ if charuco_observation is None:+ raise ValueError("Cannot create CharucoObservationAggregator from payload with None observations - should use nan-filled CharucoObservation instead")+ anipose_camera_row = charuco_observation.to_anipose_camera_row()+ if anipose_camera_row is None:+ raise ValueError("Cannot create CharucoObservationAggregator from payload with None observations - should use nan-filled CharucoObservation instead")+ camera_rows[camera_id] = [anipose_camera_row]++ return cls(individual_camera_rows=camera_rows, anipose_camera_ordering=anipose_camera_ordering)++ @property+ def all_camera_rows(self):+ return [self.individual_camera_rows[anipose_camera_id] for anipose_camera_id in self.anipose_camera_ordering]++ def add_observations(self, charuco_observations_by_camera: CharucoObservations):+ for camera_id, charuco_observation in charuco_observations_by_camera.items():+ if charuco_observation is None:+ raise ValueError("Cannot add None observations to CharucoObservationAggregator - should use nan-filled CharucoObservation instead")+ anipose_camera_row = charuco_observation.to_anipose_camera_row()+ if anipose_camera_row is None:+ raise ValueError("Cannot add None observations to CharucoObservationAggregator - should use nan-filled CharucoObservation instead")+ self.individual_camera_rows[camera_id].append(anipose_camera_row)+++class GroundPlaneSuccess:+ def __init__(self, success: bool, error: str | None = None):+ self.success = success+ self.error = error+++def anipose_calibration_from_charuco_observations(+ charuco_observations_by_frame: list[dict[CameraIdString, CharucoObservation]],+ calibration_pipeline_config:CalibrationpipelineConfig,+ video_metadata: dict[VideoIdString, VideoMetadata],+ recording_info: RecordingInfo,+ pin_camera_0_to_origin: bool = True,+ use_charuco_as_groundplane: bool = True,+ init_intrinsics: bool = True,+ init_extrinsics: bool = True,+ verbose: bool = True, ) -> Path:++ anipose_cameras: list[AniposeCamera] = [+ AniposeCamera(name=video_id,+ size=(video_metadata.height, video_metadata.width)) for video_id, video_metadata in+ video_metadata.items()+ ]+ anipose_camera_group = AniposeCameraGroup(cameras=anipose_cameras)++ anipose_charuco_board = AniposeCharucoBoard(squaresX=calibration_pipeline_config.charuco_board_x_squares,+ squaresY=calibration_pipeline_config.charuco_board_y_squares,+ square_length=calibration_pipeline_config.charuco_square_length,+ marker_length=calibration_pipeline_config.charuco_square_length * .8)+ logger.info(+ f"Starting Anipose calibration with {len(charuco_observations_by_frame)} frames of charuco observations")+ # Aggregate all observations++ charuco_observation_aggregator: CharucoObservationAggregator | None = None+ for charuco_observations_by_camera in charuco_observations_by_frame:+ if charuco_observation_aggregator is None:+ charuco_observation_aggregator = CharucoObservationAggregator.from_charuco_observation_payload(+ charuco_observations_by_camera=charuco_observations_by_camera,+ anipose_camera_ordering=[camera.name for camera in anipose_camera_group.cameras]+ )+ charuco_observation_aggregator.add_observations(charuco_observations_by_camera)++ if charuco_observation_aggregator is None:+ raise ValueError("No charuco observations were provided for calibration")++ # Perform calibration on aggregated rows+ all_camera_rows = charuco_observation_aggregator.all_camera_rows+ logger.info(f"Aggregated charuco observations for {len(all_camera_rows)} cameras")+ error, merged, charuco_frame_numbers = anipose_camera_group.calibrate_rows(+ all_camera_rows,+ anipose_charuco_board,+ init_intrinsics=init_intrinsics,+ init_extrinsics=init_extrinsics,+ verbose=verbose,+ )++ logger.info(f"Anipose calibration completed successfully!")++ logger.info(f"Calibration error: {error}")++ # Add metadata+ anipose_camera_group.metadata["groundplane_calibration"] = False+ anipose_camera_group.metadata["recording_info"] = recording_info.model_dump()+++ groundplane_success: GroundPlaneSuccess | None = None++ # Apply camera 0 pinning if requested+ if pin_camera_0_to_origin:+ anipose_camera_group = pin_camera_zero_to_origin(camera_group=anipose_camera_group)+ logger.info("Pinned camera 0 to origin")++ # Apply groundplane correction if requested+ if use_charuco_as_groundplane:+ observation_recorders_by_video = {video_id: BaseRecorder() for video_id in+ charuco_observations_by_frame[0].keys()}+ for frame_number, charuco_observations_by_camera in enumerate(charuco_observations_by_frame):+ if not all(+ [isinstance(output, CharucoObservation) for output in charuco_observations_by_camera.values()]):+ raise ValueError(+ f"Non-CharucoObservation found in frame {frame_number} observations: {charuco_observations_by_camera}")+ for video_id, recorder in observation_recorders_by_video.items():+ recorder.add_observation(observation=charuco_observations_by_camera[video_id])+++ anipose_camera_group, groundplane_success = set_charuco_board_as_groundplane(+ observation_recorders=observation_recorders_by_video,+ anipose_camera_group=anipose_camera_group,+ anipose_charuco_board=anipose_charuco_board,+ recording_folder_path=Path(recording_info.full_recording_path)+ )+ if groundplane_success.success:+ anipose_camera_group.metadata["groundplane_calibration"] = True+ logger.info("Successfully set charuco board as groundplane")+ else:+ logger.warning(f"Failed to set groundplane: {groundplane_success.error}")++ # Calculate real-world camera positions and orientations+ get_real_world_matrices(camera_group=anipose_camera_group)++ # Create calibration filename+ calibration_file_name = create_camera_calibration_file_name(recording_name=recording_info.recording_name)++ # Save to recording folder+ recording_folder_calibration_toml_path = Path(recording_info.full_recording_path)/calibration_file_name+ anipose_camera_group.dump(recording_folder_calibration_toml_path)+ logger.info(f"Saved calibration to: {recording_folder_calibration_toml_path}")++ # Save to main calibrations folder+ calibration_folder_calibration_toml_path = Path(get_calibrations_folder_path()) / calibration_file_name+ anipose_camera_group.dump(calibration_folder_calibration_toml_path)+ logger.info(f"Saved calibration to: {calibration_folder_calibration_toml_path}")++ # Save as last successful calibration+ anipose_camera_group.dump(get_last_successful_calibration_toml_path())+ logger.info(f"Saved as last successful calibration: {get_last_successful_calibration_toml_path()}")+ return recording_folder_calibration_toml_path+++def pin_camera_zero_to_origin(camera_group: AniposeCameraGroup) -> AniposeCameraGroup:+ """+ Re-express all camera extrinsics relative to camera 0.++ This function performs two operations:+ 1. Rotates all camera coordinate systems so that camera 0's orientation becomes the new world frame.+ 2. Shifts the world origin to camera 0's position, making it the new coordinate origin (0, 0, 0).++ The result is that:+ - Camera 0 ends up with an identity rotation and zero translation.+ - All other cameras are expressed relative to camera 0's original position and orientation.+ """+ rvecs_new = align_rotations_to_cam0(camera_group=camera_group)+ camera_group.set_rotations(rvecs_new)+ tvecs_new = shift_origin_to_cam0(camera_group=camera_group)+ camera_group.set_translations(tvecs_new)+ return camera_group+++def align_rotations_to_cam0(camera_group: AniposeCameraGroup) -> np.ndarray:+ """Align all camera rotations to camera 0's coordinate frame."""+ rvecs = camera_group.get_rotations()+ R0, _ = cv2.Rodrigues(rvecs[0])++ rvecs_new = np.empty_like(rvecs)+ for i in range(rvecs.shape[0]):+ Ri, _ = cv2.Rodrigues(rvecs[i])+ Ri_new, _ = cv2.Rodrigues(Ri @ R0.T)+ rvecs_new[i] = Ri_new.flatten()+ return rvecs_new+++def shift_origin_to_cam0(camera_group: AniposeCameraGroup) -> np.ndarray:+ """Shift world origin to camera 0's position."""+ tvecs = camera_group.get_translations()+ rvecs = camera_group.get_rotations()++ camera_0_translation = tvecs[0, :]+ camera_0_rotation = rvecs[0, :]++ R0, _ = cv2.Rodrigues(camera_0_rotation)+ delta_to_origin_world = -R0.T @ camera_0_translation++ new_tvecs = np.zeros_like(tvecs)+ for cam_i in range(tvecs.shape[0]):+ Ri, _ = cv2.Rodrigues(rvecs[cam_i, :])+ delta_to_origin_camera_i = Ri @ delta_to_origin_world+ new_tvecs[cam_i, :] = tvecs[cam_i, :] + delta_to_origin_camera_i+ return new_tvecs+++def set_charuco_board_as_groundplane(+ observation_recorders: dict[VideoIdString, BaseRecorder],+ anipose_camera_group: AniposeCameraGroup,+ anipose_charuco_board: AniposeCharucoBoard,+ recording_folder_path: Path | None = None+) -> tuple[AniposeCameraGroup, GroundPlaneSuccess]:+ """Set the charuco board plane as the world groundplane."""+ logger.info("Getting 2D Charuco data")+ data2d_by_video: dict[VideoIdString, np.ndarray] = {}+ if len(observation_recorders) == 0:+ raise ValueError("No observation recorders provided to process.")++ for video_id, recorder in observation_recorders.items():+ if not all([isinstance(observation, CharucoObservation) for observation in recorder.observations]):+ raise TypeError(f"Recorder for video ID {video_id} contains non-Charuco observations.")+ data2d_fr_id_xyc = recorder.to_array.copy()+ logger.info(f"Processing video ID: {video_id} with 2D data shape: {data2d_fr_id_xyc.shape}")+ data2d_by_video[video_id] = data2d_fr_id_xyc[..., :2]+++ charuco2d_cam_fr_id_xy = np.stack(list(data2d_by_video.values()), axis=0) # shape: (num_cameras, num_frames, num_tracked_points, 2)+ if charuco2d_cam_fr_id_xy is None:+ error_message = "Charuco 2d data was not retrieved successfully. Check for an error during calibration."+ logger.error(error_message)+ raise ValueError(error_message)++ logger.info(f"Charuco 2d data retrieved successfully with shape (cams, frames, markers, XY): {charuco2d_cam_fr_id_xy.shape}")+ charuco2d_cam_fr_id_xy = charuco2d_cam_fr_id_xy.astype(np.float64)+ num_cameras, num_frames, num_tracked_points, _ = charuco2d_cam_fr_id_xy.shape+ charuco_2d_flat = charuco2d_cam_fr_id_xy.reshape(num_cameras, -1, 2)++ logger.info("Getting 3d Charuco data")+ charuco_3d_flat = anipose_camera_group.triangulate(charuco_2d_flat)+ charuco3d_fr_id_xyz = charuco_3d_flat.reshape(num_frames, num_tracked_points, 3)+ logger.info(f"Charuco 3d data reconstructed with shape: {charuco3d_fr_id_xyz.shape}")++ charuco_3d_xyz_interpolated = interpolate_skeleton_data(+ skeleton_data=charuco3d_fr_id_xyz+ )++ try:+ charuco_still_frame_idx = find_good_frame(+ charuco_data3d_fr_id_xyz=charuco3d_fr_id_xyz,+ number_of_squares_width=anipose_charuco_board.squaresX,+ number_of_squares_height=anipose_charuco_board.squaresY,+ )+ except CharucoVisibilityError as e:+ logger.warning("Ground-plane alignment skipped โ reverting to original calibration: %s", e, exc_info=True)+ return anipose_camera_group, GroundPlaneSuccess(success=False, error=str(e))+ except CharucoVelocityError as e:+ logger.warning("Ground-plane alignment skipped โ reverting to original calibration: %s", e, exc_info=True)+ return anipose_camera_group, GroundPlaneSuccess(success=False, error=str(e))++ charuco_frame = charuco_3d_xyz_interpolated[charuco_still_frame_idx]++ x_hat, y_hat, z_hat = compute_basis_vectors_of_new_reference(+ charuco_frame,+ number_of_squares_width=anipose_charuco_board.squaresX,+ number_of_squares_height=anipose_charuco_board.squaresY+ )++ charuco_origin_in_world = charuco_frame[0]+ rmat_charuco_to_world = np.column_stack([x_hat, y_hat, z_hat])++ rvecs_new, tvecs_new = adjust_world_reference_frame_to_charuco(+ camera_group=anipose_camera_group,+ charuco_origin_in_world=charuco_origin_in_world,+ rmat_charuco_to_world=rmat_charuco_to_world+ )++ anipose_camera_group.set_rotations(rvecs_new)+ anipose_camera_group.set_translations(tvecs_new)++ logger.info("Anipose camera calibration data adjusted to set charuco board as ground plane")++ # Recalculate 3D charuco data in new coordinate system+ charuco_3d_flat = anipose_camera_group.triangulate(charuco_2d_flat)+ charuco3d_fr_id_xyz = charuco_3d_flat.reshape(num_frames, num_tracked_points, 3)+ charuco_3d_xyz_interpolated = skellyforge_data(raw_charuco_data=charuco3d_fr_id_xyz)++ # Save charuco 3D data if recording folder is provided+ if recording_folder_path is not None:+ charuco_save_path = recording_folder_path / "output_data" / "charuco_3d_xyz.npy"+ charuco_save_path.parent.mkdir(parents=True, exist_ok=True)+ np.save(charuco_save_path, charuco_3d_xyz_interpolated)+ logger.info(f"Charuco 3d data saved to {charuco_save_path}")++ return anipose_camera_group, GroundPlaneSuccess(success=True)+++def adjust_world_reference_frame_to_charuco(+ camera_group: AniposeCameraGroup,+ charuco_origin_in_world: np.ndarray,+ rmat_charuco_to_world: np.ndarray+) -> tuple[np.ndarray, np.ndarray]:+ """Adjust camera extrinsics to use charuco board as world reference frame."""+ tvecs = camera_group.get_translations()+ rvecs = camera_group.get_rotations()++ tvecs_new = np.zeros_like(tvecs)+ rvecs_new = np.zeros_like(rvecs)++ for i in range(tvecs.shape[0]):+ rmat_world_to_cam_i, _ = cv2.Rodrigues(rvecs[i])+ t_delta = rmat_world_to_cam_i @ charuco_origin_in_world+ tvecs_new[i] = t_delta + tvecs[i]++ new_rmat = rmat_world_to_cam_i @ rmat_charuco_to_world+ new_rvec, _ = cv2.Rodrigues(new_rmat)+ rvecs_new[i] = new_rvec.flatten()++ return rvecs_new, tvecs_new+++def get_real_world_matrices(camera_group: AniposeCameraGroup) -> tuple[list, list]:+ """Calculate real-world positions and orientations of cameras."""+ rvecs = camera_group.get_rotations()+ tvecs = camera_group.get_translations()++ positions = []+ orientations = []++ for i in range(tvecs.shape[0]):+ rmat_world_to_cam_i, _ = cv2.Rodrigues(rvecs[i])++ rmat_cam_to_world = rmat_world_to_cam_i.T+ t_world = -rmat_cam_to_world @ tvecs[i]++ positions.append(t_world.astype(float).tolist())+ orientations.append(rmat_cam_to_world.astype(float).tolist())++ camera_group.set_world_positions(positions)+ camera_group.set_world_orientations(orientations)++ return positions, orientationsdiff --git a/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/calibration_helpers/freemocap_anipose.py b/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/calibration_helpers/freemocap_anipose.pynew file mode 100644index 00000000..512ca5b5--- /dev/null+++ b/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/calibration_helpers/freemocap_anipose.py@@ -0,0 +1,2406 @@+# Most of this was copied (with permission) from the original `aniposelib` package (https://github.com/lambdaloop/aniposelib), and we're adapting it to our needs here. M+# ore info on Anipoise: https://anipose.readthedocs.io/en/latest/++import itertools+import logging+import multiprocessing+import queue+import time+from collections import defaultdict, Counter+from copy import copy+from pathlib import Path+from typing import List++import cv2+import numpy as np+import toml+from aniposelib.boards import extract_points, extract_rtvecs, get_video_params, merge_rows, CharucoBoard+from aniposelib.utils import get_rtvec, make_M+from numba import jit+from scipy import optimize+from scipy import signal+from scipy.cluster.hierarchy import linkage, fcluster+from scipy.cluster.vq import whiten+from scipy.linalg import inv as inverse+from scipy.sparse import dok_matrix+# from skellytracker.process_folder_of_videos import process_list_of_videos+# from skellytracker.trackers.charuco_tracker.charuco_model_info import CharucoModelInfo, CharucoTrackingParams+from tqdm import trange++numba_logger = logging.getLogger("numba")+numba_logger.setLevel(logging.WARNING)++logger = logging.getLogger(__name__)++ARUCO_DICTS = {+ (4, 50): cv2.aruco.DICT_4X4_50,+ (5, 50): cv2.aruco.DICT_5X5_50,+ (6, 50): cv2.aruco.DICT_6X6_50,+ (7, 50): cv2.aruco.DICT_7X7_50,+ (4, 100): cv2.aruco.DICT_4X4_100,+ (5, 100): cv2.aruco.DICT_5X5_100,+ (6, 100): cv2.aruco.DICT_6X6_100,+ (7, 100): cv2.aruco.DICT_7X7_100,+ (4, 250): cv2.aruco.DICT_4X4_250,+ (5, 250): cv2.aruco.DICT_5X5_250,+ (6, 250): cv2.aruco.DICT_6X6_250,+ (7, 250): cv2.aruco.DICT_7X7_250,+ (4, 1000): cv2.aruco.DICT_4X4_1000,+ (5, 1000): cv2.aruco.DICT_5X5_1000,+ (6, 1000): cv2.aruco.DICT_6X6_1000,+ (7, 1000): cv2.aruco.DICT_7X7_1000,+}+++# @jit(nopython=True, parallel=False)+def triangulate_simple(points, camera_mats):+ num_cams = len(camera_mats)+ A = np.zeros((num_cams * 2, 4))+ for i in range(num_cams):+ x, y = points[i]+ mat = camera_mats[i]+ A[(i * 2): (i * 2 + 1)] = x * mat[2] - mat[0]+ A[(i * 2 + 1): (i * 2 + 2)] = y * mat[2] - mat[1]+ u, s, vh = np.linalg.svd(A, full_matrices=True)+ p3d = vh[-1]+ p3d = p3d[:3] / p3d[3]+ return p3d+++def get_error_dict(errors_full, min_points=10):+ n_cams = errors_full.shape[0]+ errors_norm = np.linalg.norm(errors_full, axis=2)++ good = ~np.isnan(errors_full[:, :, 0])++ error_dict = dict()++ for i in range(n_cams):+ for j in range(i + 1, n_cams):+ subset = good[i] & good[j]+ err_subset = errors_norm[:, subset][[i, j]]+ err_subset_mean = np.mean(err_subset, axis=0)+ if np.sum(subset) > min_points:+ percents = np.percentile(err_subset_mean, [15, 75])+ # percents = np.percentile(err_subset, [25, 75])+ error_dict[(i, j)] = (err_subset.shape[1], percents)+ return error_dict+++def check_errors(cgroup, imgp):+ p3ds = cgroup.triangulate(imgp)+ errors_full = cgroup.reprojection_error(p3ds, imgp, mean=False)+ return get_error_dict(errors_full)+++def subset_extra(extra, ixs):+ if extra is None:+ return None++ new_extra = {+ "objp": extra["objp"][ixs],+ "ids": extra["ids"][ixs],+ "rvecs": extra["rvecs"][:, ixs],+ "tvecs": extra["tvecs"][:, ixs],+ }+ return new_extra+++def resample_points_extra(imgp, extra, n_samp=25):+ n_cams, n_points, _ = imgp.shape+ ids = remap_ids(extra["ids"])+ n_ids = np.max(ids) + 1+ good = ~np.isnan(imgp[:, :, 0])+ ixs = np.arange(n_points)++ cam_counts = np.zeros((n_ids, n_cams), dtype="int64")+ for idnum in range(n_ids):+ cam_counts[idnum] = np.sum(good[:, ids == idnum], axis=1)+ cam_counts_random = cam_counts + np.random.random(size=cam_counts.shape)+ best_boards = np.argsort(-cam_counts_random, axis=0)++ cam_totals = np.zeros(n_cams, dtype="int64")++ include = set()+ for cam_num in range(n_cams):+ for board_id in best_boards[:, cam_num]:+ include.update(ixs[ids == board_id])+ cam_totals += cam_counts[board_id]+ if cam_totals[cam_num] >= n_samp or cam_counts_random[board_id, cam_num] < 1:+ break++ final_ixs = sorted(include)+ newp = imgp[:, final_ixs]+ extra = subset_extra(extra, final_ixs)+ return newp, extra+++def resample_points(imgp, extra=None, n_samp=25):+ # if extra is not None:+ # return resample_points_extra(imgp, extra, n_samp)++ n_cams = imgp.shape[0]+ good = ~np.isnan(imgp[:, :, 0])+ ixs = np.arange(imgp.shape[1])++ num_cams = np.sum(~np.isnan(imgp[:, :, 0]), axis=0)++ include = set()++ for i in range(n_cams):+ for j in range(i + 1, n_cams):+ subset = good[i] & good[j]+ n_good = np.sum(subset)+ if n_good > 0:+ ## pick points, prioritizing points seen by more cameras+ arr = np.copy(num_cams[subset]).astype("float64")+ arr += np.random.random(size=arr.shape)+ picked_ix = np.argsort(-arr)[:n_samp]+ picked = ixs[subset][picked_ix]+ include.update(picked)++ final_ixs = sorted(include)+ newp = imgp[:, final_ixs]+ extra = subset_extra(extra, final_ixs)+ return newp, extra+++def medfilt_data(values, size=15):+ padsize = size + 5+ vpad = np.pad(values, (padsize, padsize), mode="reflect")+ vpadf = signal.medfilt(vpad, kernel_size=size)+ return vpadf[padsize:-padsize]+++def nan_helper(y):+ return np.isnan(y), lambda z: z.nonzero()[0]+++def interpolate_data(vals):+ nans, ix = nan_helper(vals)+ out = np.copy(vals)+ try:+ out[nans] = np.interp(ix(nans), ix(~nans), vals[~nans])+ except ValueError:+ out[:] = 0+ return out+++def remap_ids(ids):+ unique_ids = np.unique(ids)+ ids_out = np.copy(ids)+ for i, num in enumerate(unique_ids):+ ids_out[ids == num] = i+ return ids_out+++def transform_points(points, rvecs, tvecs):+ """Rotate points by given rotation vectors and translate.+ Rodrigues' rotation formula is used.+ """+ theta = np.linalg.norm(rvecs, axis=1)[:, np.newaxis]+ with np.errstate(invalid="ignore"):+ v = rvecs / theta+ v = np.nan_to_num(v)+ dot = np.sum(points * v, axis=1)[:, np.newaxis]+ cos_theta = np.cos(theta)+ sin_theta = np.sin(theta)++ rotated = cos_theta * points + sin_theta * np.cross(v, points) + dot * (1 - cos_theta) * v++ return rotated + tvecs+++def get_connections(xs: np.ndarray, cam_names: list | None = None, both: bool = True) -> dict[tuple, int]:+ """Get connection counts between camera pairs."""+ from collections import defaultdict++ n_cams = xs.shape[0]+ n_points = xs.shape[1]++ if cam_names is None:+ cam_names = [str(i) for i in range(n_cams)]++ connections = defaultdict(int)++ for rnum in range(n_points):+ ixs = np.where(~np.isnan(xs[:, rnum, 0]))[0]+ keys = [cam_names[ix] for ix in ixs]+ for i in range(len(keys)):+ for j in range(i + 1, len(keys)):+ a = keys[i]+ b = keys[j]+ connections[(a, b)] += 1+ if both:+ connections[(b, a)] += 1++ return connections+++def get_calibration_graph(rtvecs, cam_names=None):+ n_cams = rtvecs.shape[0]+ n_points = rtvecs.shape[1]++ if cam_names is None:+ cam_names = np.arange(n_cams)++ connections = get_connections(rtvecs, np.arange(n_cams))++ components = dict(zip(np.arange(n_cams), range(n_cams)))+ edges = set(connections.items())++ graph = defaultdict(list)++ for edgenum in range(n_cams - 1):+ if len(edges) == 0:+ component_names = dict()+ for k, v in list(components.items()):+ component_names[cam_names[k]] = v+ raise ValueError(+ """+Could not build calibration graph.+Some group of cameras could not be paired by simultaneous calibration board detections.+Check which cameras have different group numbers below to see the missing edges.+{}""".format(+ component_names+ )+ )++ (a, b), weight = max(edges, key=lambda x: x[1])+ graph[a].append(b)+ graph[b].append(a)++ match = components[a]+ replace = components[b]+ for k, v in components.items():+ if match == v:+ components[k] = replace++ for e in edges.copy():+ (a, b), w = e+ if components[a] == components[b]:+ edges.remove(e)++ return graph+++def find_calibration_pairs(graph, source=None):+ pairs = []+ explored = set()++ if source is None:+ source = sorted(graph.keys())[0]++ q = queue.deque()+ q.append(source)++ while len(q) > 0:+ item = q.pop()+ explored.add(item)++ for new in graph[item]:+ if new not in explored:+ q.append(new)+ pairs.append((item, new))+ return pairs+++def compute_camera_matrices(rtvecs: np.ndarray, pairs: list[tuple[int, int]]) -> dict[int, np.ndarray]:+ """+ Compute camera extrinsics from calibration pairs.++ Args:+ rtvecs: Rotation/translation vectors+ pairs: List of (source, target) camera pairs++ Returns:+ Dictionary mapping camera index to 4x4 transformation matrix+ """+ logger.debug(f"Computing camera matrices for {len(pairs)} pairs")++ extrinsics = dict()+ source = pairs[0][0]+ extrinsics[source] = np.identity(4)+ logger.debug(f"Camera {source} set as origin (identity transform)")++ for i, (a, b) in enumerate(pairs):+ logger.debug(f"Pair {i + 1}/{len(pairs)}: Computing transform from {a} to {b}")++ if a not in extrinsics:+ logger.error(f"Camera {a} not yet in extrinsics! Pairs may be ordered incorrectly.")+ raise ValueError(f"Camera {a} must be computed before camera {b}")++ try:+ ext = get_transform(rtvecs, b, a)+ extrinsics[b] = np.matmul(ext, extrinsics[a])+ logger.debug(f"Camera {b} extrinsics computed successfully")+ except Exception as e:+ logger.error(f"Failed to compute transform from {a} to {b}: {e}")+ raise++ logger.info(f"Computed extrinsics for {len(extrinsics)} cameras")+ return extrinsics+++def get_transform(rtvecs: np.ndarray, left: int, right: int) -> np.ndarray:+ """+ Calculate transform between two cameras with improved convergence.+ """+ logger.debug(f"Computing transform between camera {left} and camera {right}")++ L = []+ valid_frames = 0++ for dix in range(rtvecs.shape[1]):+ d = rtvecs[:, dix]+ good = ~np.isnan(d[:, 0])++ if good[left] and good[right]:+ valid_frames += 1+ M_left = make_M(d[left, 0:3], d[left, 3:6])+ M_right = make_M(d[right, 0:3], d[right, 3:6])+ M = np.matmul(M_left, inverse(M_right))+ L.append(M)++ logger.info(f"Camera pair ({left}, {right}): Found {valid_frames} frames with valid observations")++ if len(L) == 0:+ raise ValueError(f"No valid transformation matrices found between cameras {left} and {right}")++ logger.debug(f"Selecting best matrices from {len(L)} candidates")+ L_best = select_matrices(L)+ logger.info(f"Selected {len(L_best)} matrices after clustering (removed {len(L) - len(L_best)} outliers)")++ logger.debug("Computing initial mean transform")+ M_mean = mean_transform(L_best)++ # Progressive refinement with decreasing thresholds+ # Start more permissive and gradually tighten+ thresholds = [0.5, 0.3, 0.15, 0.1]++ for i, error_threshold in enumerate(thresholds):+ logger.debug(f"Robust refinement {i + 1}/{len(thresholds)} with error threshold {error_threshold}")++ M_mean_new = mean_transform_robust(+ L,+ M_mean,+ error=error_threshold,+ max_iterations=3,+ convergence_threshold=0.001+ )++ # Check if transform changed significantly+ diff = np.max(np.abs(M_mean_new - M_mean))+ logger.debug(f"Transform difference after refinement: {diff:.6f}")++ # If change is too large, refinement may be unstable - use previous result+ if diff > 10.0: # ~10 radians or 10mm is likely unstable+ logger.warning(f"Large transform change ({diff:.2f}) detected, refinement may be unstable")+ logger.warning(f"Stopping refinement and using previous result")+ break++ M_mean = M_mean_new++ logger.info(f"Final transform computed for camera pair ({left}, {right})")+ return M_mean+++def get_most_common(vals):+ Z = linkage(whiten(vals), "ward")+ n_clust = max(len(vals) / 10, 3)+ clusts = fcluster(Z, t=n_clust, criterion="maxclust")+ cc = Counter(clusts[clusts >= 0])+ most = cc.most_common(n=1)+ top = most[0][0]+ good = clusts == top+ return good+++def select_matrices(Ms):+ Ms = np.array(Ms)+ rvecs = [cv2.Rodrigues(M[:3, :3])[0][:, 0] for M in Ms]+ tvecs = np.array([M[:3, 3] for M in Ms])+ best = get_most_common(np.hstack([rvecs, tvecs]))+ Ms_best = Ms[best]+ return Ms_best+++def mean_transform(M_list: list[np.ndarray]) -> np.ndarray:+ """+ Compute mean transformation from list of transformation matrices.++ Args:+ M_list: List of 4x4 transformation matrices++ Returns:+ Mean transformation matrix+ """+ if len(M_list) == 0:+ raise ValueError("Cannot compute mean transform from empty matrix list")++ logger.debug(f"Computing mean of {len(M_list)} transformation matrices")++ rvecs = []+ tvecs = []++ for i, M in enumerate(M_list):+ try:+ rvec = cv2.Rodrigues(M[:3, :3])[0][:, 0]+ tvec = M[:3, 3]++ # Validate shapes+ if rvec.shape != (3,):+ logger.error(f"Matrix {i}: Invalid rvec shape {rvec.shape}, expected (3,)")+ continue+ if tvec.shape != (3,):+ logger.error(f"Matrix {i}: Invalid tvec shape {tvec.shape}, expected (3,)")+ continue++ rvecs.append(rvec)+ tvecs.append(tvec)++ except Exception as e:+ logger.warning(f"Matrix {i}: Failed to extract rvec/tvec - {e}")+ continue++ if len(rvecs) == 0:+ raise ValueError("No valid rvecs could be extracted from transformation matrices")++ rvec = np.mean(rvecs, axis=0)+ tvec = np.mean(tvecs, axis=0)++ # Final validation+ if rvec.shape != (3,):+ raise ValueError(f"Invalid mean rvec shape {rvec.shape}, expected (3,). Input had {len(rvecs)} valid vectors")+ if tvec.shape != (3,):+ raise ValueError(f"Invalid mean tvec shape {tvec.shape}, expected (3,). Input had {len(tvecs)} valid vectors")++ # Check for NaN+ if np.any(np.isnan(rvec)):+ logger.error(f"NaN in mean rvec: {rvec}")+ raise ValueError("Mean rvec contains NaN values")+ if np.any(np.isnan(tvec)):+ logger.error(f"NaN in mean tvec: {tvec}")+ raise ValueError("Mean tvec contains NaN values")++ logger.debug(f"Mean rvec: {rvec}, mean tvec: {tvec}")++ return make_M(rvec, tvec)+++def mean_transform_robust(+ M_list: list[np.ndarray],+ approx: np.ndarray | None = None,+ error: float = 0.3,+ max_iterations: int = 5,+ convergence_threshold: float = 0.01+) -> np.ndarray:+ """+ Compute robust mean by iteratively filtering outliers.++ Args:+ M_list: List of transformation matrices+ approx: Initial approximation for comparison+ error: Maximum acceptable rotation error+ max_iterations: Maximum refinement iterations+ convergence_threshold: Stop if change is below this threshold++ Returns:+ Robust mean transformation+ """+ if len(M_list) == 0:+ raise ValueError("Cannot compute robust mean from empty matrix list")++ if approx is None:+ logger.debug("No approximation provided, using all matrices")+ return mean_transform(M_list)++ logger.debug(f"Filtering matrices with error threshold {error}")+ M_current = approx++ for iteration in range(max_iterations):+ M_list_robust = []+ errors = []++ for i, M in enumerate(M_list):+ rot_error = (M - M_current)[:3, :3]+ m = np.max(np.abs(rot_error))+ errors.append(m)++ if m < error:+ M_list_robust.append(M)++ logger.info(f"Iteration {iteration + 1}: Kept {len(M_list_robust)}/{len(M_list)} matrices")++ if len(errors) > 0:+ logger.debug(f"Error statistics: min={min(errors):.6f}, max={max(errors):.6f}, mean={np.mean(errors):.6f}")++ # CRITICAL: If all matrices filtered out, use relaxed threshold+ if len(M_list_robust) == 0:+ logger.warning(f"All matrices filtered with threshold {error}. Relaxing to use best 50%")+ # Use top 50% of matrices by error+ sorted_indices = np.argsort(errors)+ n_keep = max(len(M_list) // 2, 3) # Keep at least 3 or 50%+ M_list_robust = [M_list[i] for i in sorted_indices[:n_keep]]+ logger.info(f"Using {len(M_list_robust)} best matrices after relaxation")++ # Compute new mean+ M_new = mean_transform(M_list_robust)++ # Check convergence+ diff = np.max(np.abs(M_new - M_current))+ logger.debug(f"Transform difference: {diff:.6f}")++ if diff < convergence_threshold or iteration == max_iterations - 1:+ logger.info(f"Converged after {iteration + 1} iterations (diff={diff:.6f})")+ return M_new++ M_current = M_new++ logger.warning(f"Did not converge after {max_iterations} iterations. Using last result.")+ return M_current+++def get_initial_extrinsics(rtvecs: np.ndarray, cam_names: list | None = None) -> tuple[np.ndarray, np.ndarray]:+ """+ Compute initial camera extrinsics from pose observations.++ Args:+ rtvecs: Array of rotation/translation vectors (n_cams, n_frames, 6)+ cam_names: Optional camera names for logging++ Returns:+ Tuple of (rvecs, tvecs) for all cameras+ """+ n_cams = rtvecs.shape[0]+ n_frames = rtvecs.shape[1]++ logger.info(f"Computing initial extrinsics for {n_cams} cameras from {n_frames} frames")++ # Log observation statistics+ for cam_idx in range(n_cams):+ valid_obs = np.sum(~np.isnan(rtvecs[cam_idx, :, 0]))+ cam_name = cam_names[cam_idx] if cam_names else str(cam_idx)+ logger.info(f"Camera {cam_name}: {valid_obs}/{n_frames} valid observations ({100 * valid_obs / n_frames:.1f}%)")++ logger.debug("Building calibration graph from camera connections")+ graph = get_calibration_graph(rtvecs, cam_names)+ logger.info(f"Calibration graph: {dict(graph)}")++ logger.debug("Finding calibration pairs")+ pairs = find_calibration_pairs(graph, source=0)+ logger.info(f"Calibration pairs: {pairs}")++ if len(pairs) != n_cams - 1:+ logger.error(f"Expected {n_cams - 1} pairs, got {len(pairs)}. Graph may be disconnected!")++ logger.debug("Computing camera transformation matrices")+ extrinsics = compute_camera_matrices(rtvecs, pairs)++ # Extract rvecs and tvecs+ rvecs = []+ tvecs = []+ for cnum in range(n_cams):+ cam_name = cam_names[cnum] if cam_names else str(cnum)++ if cnum not in extrinsics:+ logger.error(f"Camera {cam_name} (index {cnum}) not in extrinsics dict!")+ raise ValueError(f"Missing extrinsics for camera {cnum}")++ try:+ rvec, tvec = get_rtvec(extrinsics[cnum])+ logger.debug(f"Camera {cam_name}: rvec={rvec}, tvec={tvec}")+ rvecs.append(rvec)+ tvecs.append(tvec)+ except Exception as e:+ logger.error(f"Camera {cam_name}: Failed to extract rvec/tvec - {e}")+ raise++ rvecs = np.array(rvecs)+ tvecs = np.array(tvecs)++ logger.info(f"Successfully computed extrinsics: rvecs shape={rvecs.shape}, tvecs shape={tvecs.shape}")++ # Log summary statistics+ rvec_norms = np.linalg.norm(rvecs, axis=1)+ tvec_norms = np.linalg.norm(tvecs, axis=1)+ logger.info(f"Rotation magnitudes: {rvec_norms}")+ logger.info(f"Translation magnitudes: {tvec_norms}")++ return rvecs, tvecs+++class AniposeCamera:+ def __init__(+ self,+ matrix=np.eye(3),+ dist=np.zeros(5),+ size=None,+ rvec=np.zeros(3),+ tvec=np.zeros(3),+ world_orientation=np.eye(3),+ world_position=np.zeros(3),+ name=None,+ extra_dist=False,+ ):+ self.set_camera_matrix(matrix)+ self.set_distortions(dist)+ self.set_size(size)+ self.set_rotation(rvec)+ self.set_translation(tvec)+ self.set_world_orientation(world_orientation)+ self.set_world_position(world_position)+ self.set_name(name)+ self.extra_dist = extra_dist++ def get_dict(self):+ return {+ "name": self.get_name(),+ "size": list(self.get_size()),+ "matrix": self.get_camera_matrix().tolist(),+ "distortions": self.get_distortions().tolist(),+ "rotation": self.get_rotation().tolist(),+ "translation": self.get_translation().tolist(),+ "world_orientation": self.get_world_orientation().tolist(),+ "world_position": self.get_world_position().tolist()+ }++ def load_dict(self, d):+ self.set_camera_matrix(d["matrix"])+ self.set_rotation(d["rotation"])+ self.set_translation(d["translation"])+ self.set_distortions(d["distortions"])+ self.set_name(d["name"])+ self.set_size(d["size"])++ self.set_world_orientation(d.get("world_orientation", np.eye(3)))+ self.set_world_position(d.get("world_position", np.zeros(3)))++ def from_dict(d):+ cam = AniposeCamera()+ cam.load_dict(d)+ return cam++ def get_camera_matrix(self):+ return self.matrix++ def get_distortions(self):+ return self.dist++ def set_camera_matrix(self, matrix):+ self.matrix = np.array(matrix, dtype="float64")++ def set_focal_length(self, fx, fy=None):+ if fy is None:+ fy = fx+ self.matrix[0, 0] = fx+ self.matrix[1, 1] = fy++ def get_focal_length(self, both=False):+ fx = self.matrix[0, 0]+ fy = self.matrix[1, 1]+ if both:+ return (fx, fy)+ else:+ return (fx + fy) / 2.0++ def set_distortions(self, dist):+ self.dist = np.array(dist, dtype="float64").ravel()++ def set_rotation(self, rvec):+ self.rvec = np.array(rvec, dtype="float64").ravel()++ def get_rotation(self):+ return self.rvec++ def set_translation(self, tvec):+ self.tvec = np.array(tvec, dtype="float64").ravel()++ def get_translation(self):+ return self.tvec++ def set_world_orientation(self, world_orientation):+ self.world_orientation = np.asarray(world_orientation, dtype="float64").reshape(3, 3)++ def get_world_orientation(self):+ return self.world_orientation++ def set_world_position(self, world_position):+ self.world_position = np.array(world_position, dtype="float64").ravel()++ def get_world_position(self):+ return self.world_position++ def get_extrinsics_mat(self):+ return make_M(self.rvec, self.tvec)++ def get_name(self):+ return self.name++ def set_name(self, name):+ self.name = str(name)++ def set_size(self, size):+ """set size as (width, height)"""+ self.size = size++ def get_size(self):+ """get size as (width, height)"""+ return self.size++ def resize_camera(self, scale):+ """resize the camera by scale factor, updating intrinsics to match"""+ size = self.get_size()+ new_size = size[0] * scale, size[1] * scale+ matrix = self.get_camera_matrix()+ new_matrix = matrix * scale+ new_matrix[2, 2] = 1+ self.set_size(new_size)+ self.set_camera_matrix(new_matrix)++ def get_params(self):+ params = np.zeros(8 + self.extra_dist, dtype="float64")+ params[0:3] = self.get_rotation()+ params[3:6] = self.get_translation()+ params[6] = self.get_focal_length()+ dist = self.get_distortions()+ params[7] = dist[0]+ if self.extra_dist:+ params[8] = dist[1]+ return params++ def set_params(self, params):+ self.set_rotation(params[0:3])+ self.set_translation(params[3:6])+ self.set_focal_length(params[6])++ dist = np.zeros(5, dtype="float64")+ dist[0] = params[7]+ if self.extra_dist:+ dist[1] = params[8]+ self.set_distortions(dist)++ def distort_points(self, points):+ shape = points.shape+ points = points.reshape(-1, 1, 2)+ new_points = np.dstack([points, np.ones((points.shape[0], 1, 1))])+ out, _ = cv2.projectPoints(+ new_points,+ np.zeros(3),+ np.zeros(3),+ self.matrix.astype("float64"),+ self.dist.astype("float64"),+ )+ return out.reshape(shape)++ def undistort_points(self, points):+ shape = points.shape+ points = points.reshape(-1, 1, 2)+ out = cv2.undistortPoints(points, self.matrix.astype("float64"), self.dist.astype("float64"))+ return out.reshape(shape)++ def project(self, points):+ points = points.reshape(-1, 1, 3)+ out, _ = cv2.projectPoints(+ points,+ self.rvec,+ self.tvec,+ self.matrix.astype("float64"),+ self.dist.astype("float64"),+ )+ return out++ def single_camera_reprojection_error(self, p3d, p2d):+ projecting_3d_points_onto_2d_image_plane_og = self.project(p3d)+ projecting_3d_points_onto_2d_image_plane = projecting_3d_points_onto_2d_image_plane_og.reshape(p2d.shape)+ return p2d - projecting_3d_points_onto_2d_image_plane++ def copy(self):+ return AniposeCamera(+ matrix=self.get_camera_matrix().copy(),+ dist=self.get_distortions().copy(),+ size=self.get_size(),+ rvec=self.get_rotation().copy(),+ tvec=self.get_translation().copy(),+ name=self.get_name(),+ extra_dist=self.extra_dist,+ world_orientation=self.get_world_orientation().copy(),+ world_position=self.get_world_position().copy()+ )++++class AniposeCameraGroup:+ def __init__(self, cameras:list[AniposeCamera], metadata={}):+ self.cameras = cameras+ self.metadata = metadata+ self.charuco_2d_data = None++ def subset_cameras(self, indices):+ cams = [self.cameras[ix].copy() for ix in indices]+ return AniposeCameraGroup(cams, self.metadata)++ def subset_cameras_names(self, names):+ cur_names = self.get_names()+ cur_names_dict = dict(zip(cur_names, range(len(cur_names))))+ indices = []+ for name in names:+ if name not in cur_names_dict:+ raise IndexError("name {} not part of camera names: {}".format(name, cur_names))+ indices.append(cur_names_dict[name])+ return self.subset_cameras(indices)++ def project(self, points):+ """Given an Nx3 array of points, this returns an CxNx2 array of 2D points,+ where C is the number of cameras"""+ points = points.reshape(-1, 1, 3)+ n_points = points.shape[0]+ n_cams = len(self.cameras)++ out = np.empty((n_cams, n_points, 2), dtype="float64")+ for cnum, cam in enumerate(self.cameras):+ out[cnum] = cam.project(points).reshape(n_points, 2)++ return out++ def triangulate(self, points, undistort=True, progress=False, kill_event: multiprocessing.Event = None):+ """Given an CxNx2 array, this returns an Nx3 array of points,+ where N is the number of points and C is the number of cameras"""++ assert points.shape[0] == len(+ self.cameras+ ), "Invalid points shape, first dim should be equal to" " number of cameras ({}), but shape is {}".format(+ len(self.cameras), points.shape+ )++ one_point = False+ if len(points.shape) == 2:+ points = points.reshape(-1, 1, 2)+ one_point = True++ if undistort:+ new_points = np.empty(points.shape)+ for cnum, cam in enumerate(self.cameras):+ # must copy in order to satisfy opencv underneath+ sub = np.copy(points[cnum])+ new_points[cnum] = cam.undistort_points(sub)+ points = new_points++ n_cams, n_points, _ = points.shape++ out = np.empty((n_points, 3))+ out[:] = np.nan++ cam_mats = np.array([cam.get_extrinsics_mat() for cam in self.cameras])++ if progress:+ iterator = trange(n_points, ncols=70)+ else:+ iterator = range(n_points)++ for ip in iterator:+ subp = points[:, ip, :]+ good = ~np.isnan(subp[:, 0])+ if np.sum(good) >= 2:+ out[ip] = triangulate_simple(subp[good], cam_mats[good])++ if kill_event is not None and kill_event.is_set():+ return None++ if one_point:+ out = out[0]++ return out++ def triangulate_possible(+ self,+ points,+ undistort=True,+ min_cams=2,+ progress=False,+ threshold=0.5,+ kill_event: multiprocessing.Event = None,+ ):+ """Given an CxNxPx2 array, this returns an Nx3 array of points+ by triangulating all possible points and picking the ones with+ best reprojection error+ where:+ C: number of cameras+ N: number of points+ P: number of possible options per point+ """++ assert points.shape[0] == len(+ self.cameras+ ), "Invalid points shape, first dim should be equal to" " number of cameras ({}), but shape is {}".format(+ len(self.cameras), points.shape+ )++ n_cams, n_points, n_possible, _ = points.shape++ cam_nums, point_nums, possible_nums = np.where(~np.isnan(points[:, :, :, 0]))++ all_iters = defaultdict(dict)++ for cam_num, point_num, possible_num in zip(cam_nums, point_nums, possible_nums):+ if cam_num not in all_iters[point_num]:+ all_iters[point_num][cam_num] = []+ all_iters[point_num][cam_num].append((cam_num, possible_num))++ for point_num in all_iters.keys():+ for cam_num in all_iters[point_num].keys():+ all_iters[point_num][cam_num].append(None)++ out = np.full((n_points, 3), np.nan, dtype="float64")+ picked_vals = np.zeros((n_cams, n_points, n_possible), dtype="bool")+ errors = np.zeros(n_points, dtype="float64")+ points_2d = np.full((n_cams, n_points, 2), np.nan, dtype="float64")++ if progress:+ iterator = trange(n_points, ncols=70)+ else:+ iterator = range(n_points)++ for point_ix in iterator:+ best_point = None+ best_error = 200++ n_cams_max = len(all_iters[point_ix])++ for picked in itertools.product(*all_iters[point_ix].values()):+ picked = [p for p in picked if p is not None]+ if len(picked) < min_cams and len(picked) != n_cams_max:+ continue++ if kill_event is not None and kill_event.is_set():+ return None++ cnums = [p[0] for p in picked]+ xnums = [p[1] for p in picked]++ pts = points[cnums, point_ix, xnums]+ cc = self.subset_cameras(cnums)++ p3d = cc.triangulate(pts, undistort=undistort)+ err = cc.reprojection_error(p3d, pts, mean=True)++ if err < best_error:+ best_point = {+ "error": err,+ "point": p3d[:3],+ "points": pts,+ "picked": picked,+ "joint_ix": point_ix,+ }+ best_error = err+ if best_error < threshold:+ break++ if best_point is not None:+ out[point_ix] = best_point["point"]+ picked = best_point["picked"]+ cnums = [p[0] for p in picked]+ xnums = [p[1] for p in picked]+ picked_vals[cnums, point_ix, xnums] = True+ errors[point_ix] = best_point["error"]+ points_2d[cnums, point_ix] = best_point["points"]++ # return out, picked_vals, points_2d, errors #original code from OG anipose+ return out # simplify output so that `triangulate_ransac` can be used exactly the same way as `triangulate`++ def triangulate_ransac(+ self, points, undistort=True, min_cams=2, progress=False, kill_event: multiprocessing.Event = None+ ):+ """Given an CxNx2 array, this returns an Nx3 array of points,+ where N is the number of points and C is the number of cameras"""++ assert points.shape[0] == len(+ self.cameras+ ), "Invalid points shape, first dim should be equal to" " number of cameras ({}), but shape is {}".format(+ len(self.cameras), points.shape+ )++ n_cams, n_points, _ = points.shape++ points_ransac = points.reshape(n_cams, n_points, 1, 2)++ return self.triangulate_possible(+ points_ransac, undistort=undistort, min_cams=min_cams, progress=progress, kill_event=kill_event+ )++ @jit(parallel=True, forceobj=True)+ def reprojection_error(self, points_3d, points_2d, mean=False):+ """Given an Nx3 array of 3D points and an CxNx2 array of 2D points,+ where N is the number of points and C is the number of cameras,+ this returns an CxNx2 array of errors.+ Optionally mean=True, this averages the errors and returns array of length N of errors"""++ one_point = False+ if len(points_3d.shape) == 1 and len(points_2d.shape) == 2:+ points_3d = points_3d.reshape(1, 3)+ points_2d = points_2d.reshape(-1, 1, 2)+ one_point = True++ n_cams, n_points, _ = points_2d.shape+ assert points_3d.shape == (+ n_points,+ 3,+ ), "shapes of 2D and 3D points are not consistent: " "2D={}, 3D={}".format(points_2d.shape, points_3d.shape)++ errors = np.empty((n_cams, n_points, 2))++ for camera_number, cam in enumerate(self.cameras):+ errors[camera_number] = cam.single_camera_reprojection_error(points_3d, points_2d[camera_number])++ if mean:+ errors_norm = np.linalg.norm(errors, axis=2)+ good = ~np.isnan(errors_norm)+ errors_norm[~good] = 0+ denom = np.sum(good, axis=0).astype("float64")+ denom[denom < 1.5] = np.nan+ errors = np.sum(errors_norm, axis=0) / denom++ if one_point:+ if mean:+ errors = float(errors[0])+ else:+ errors = errors.reshape(-1, 2)++ return errors++ def bundle_adjust_iter(+ self,+ p2ds,+ extra=None,+ n_iters=10,+ start_mu=15,+ end_mu=1,+ max_nfev=200,+ ftol=1e-4,+ n_samp_iter=100,+ n_samp_full=1000,+ error_threshold=0.3,+ verbose=False,+ ):+ """Given an CxNx2 array of 2D points,+ where N is the number of points and C is the number of cameras,+ this performs iterative bundle adjustsment to fine-tune the parameters of the cameras.+ That is, it performs bundle adjustment multiple times, adjusting the weights given to points+ to reduce the influence of outliers.+ This is inspired by the algorithm for Fast Global Registration by Zhou, Park, and Koltun+ """+ error_list = []++ assert p2ds.shape[0] == len(+ self.cameras+ ), "Invalid points shape, first dim should be equal to" " number of cameras ({}), but shape is {}".format(+ len(self.cameras), p2ds.shape+ )++ p2ds_full = p2ds+ extra_full = extra++ p2ds, extra = resample_points(p2ds_full, extra_full, n_samp=n_samp_full)+ error = self.average_error(p2ds, median=True)++ if verbose:+ print("error: ", error)++ mus = np.exp(np.linspace(np.log(start_mu), np.log(end_mu), num=n_iters))++ if verbose:+ print("n_samples: {}".format(n_samp_iter))++ for i in range(n_iters):+ p2ds, extra = resample_points(p2ds_full, extra_full, n_samp=n_samp_full)+ p3ds = self.triangulate(p2ds)+ errors_full = self.reprojection_error(p3ds, p2ds, mean=False)+ errors_norm = self.reprojection_error(p3ds, p2ds, mean=True)++ error_dict = get_error_dict(errors_full)+ max_error = 0+ min_error = 0+ for k, v in error_dict.items():+ num, percents = v+ max_error = max(percents[-1], max_error)+ min_error = max(percents[0], min_error)+ mu = max(min(max_error, mus[i]), min_error)++ good = errors_norm < mu+ extra_good = subset_extra(extra, good)+ p2ds_samp, extra_samp = resample_points(p2ds[:, good], extra_good, n_samp=n_samp_iter)++ error = np.median(errors_norm)+ error_list.append(error)++ if error < error_threshold:+ break++ if verbose:+ print(error_dict)+ print("error: {:.2f}, mu: {:.1f}, ratio: {:.3f}".format(error, mu, np.mean(good)))+ print(f"previous error scores: [magenta] {error_list}[/magenta]")++ self.bundle_adjust(+ p2ds_samp,+ extra_samp,+ loss="linear",+ ftol=ftol,+ max_nfev=max_nfev,+ verbose=verbose,+ )++ p2ds, extra = resample_points(p2ds_full, extra_full, n_samp=n_samp_full)+ p3ds = self.triangulate(p2ds)+ errors_full = self.reprojection_error(p3ds, p2ds, mean=False)+ errors_norm = self.reprojection_error(p3ds, p2ds, mean=True)+ error_dict = get_error_dict(errors_full)+ if verbose:+ print(error_dict)++ max_error = 0+ min_error = 0+ for k, v in error_dict.items():+ num, percents = v+ max_error = max(percents[-1], max_error)+ min_error = max(percents[0], min_error)+ mu = max(max(max_error, end_mu), min_error)++ good = errors_norm < mu+ extra_good = subset_extra(extra, good)+ self.bundle_adjust(+ p2ds[:, good],+ extra_good,+ loss="linear",+ ftol=ftol,+ max_nfev=max(200, max_nfev),+ verbose=verbose,+ )++ error = self.average_error(p2ds, median=True)++ p3ds = self.triangulate(p2ds)+ errors_full = self.reprojection_error(p3ds, p2ds, mean=False)+ error_dict = get_error_dict(errors_full)+ if verbose:+ print(error_dict)++ if verbose:+ print("error: ", error)++ return error++ def bundle_adjust(+ self,+ p2ds,+ extra=None,+ loss="linear",+ threshold=50,+ ftol=1e-4,+ max_nfev=1000,+ weights=None,+ start_params=None,+ verbose=True,+ ):+ """Given an CxNx2 array of 2D points,+ where N is the number of points and C is the number of cameras,+ this performs bundle adjustsment to fine-tune the parameters of the cameras"""++ assert p2ds.shape[0] == len(+ self.cameras+ ), "Invalid points shape, first dim should be equal to" " number of cameras ({}), but shape is {}".format(+ len(self.cameras), p2ds.shape+ )++ if extra is not None:+ extra["ids_map"] = remap_ids(extra["ids"])++ x0, n_cam_params = self._initialize_params_bundle(p2ds, extra)++ if start_params is not None:+ x0 = start_params+ n_cam_params = len(self.cameras[0].get_params())++ error_fun = self._error_fun_bundle++ jac_sparse = self._jac_sparsity_bundle(p2ds, n_cam_params, extra)++ f_scale = threshold+ opt = optimize.least_squares(+ error_fun,+ x0,+ jac_sparsity=jac_sparse,+ f_scale=f_scale,+ x_scale="jac",+ loss=loss,+ ftol=ftol,+ method="trf",+ tr_solver="lsmr",+ verbose=2 * verbose,+ max_nfev=max_nfev,+ args=(p2ds, n_cam_params, extra),+ )+ best_params = opt.x++ for i, cam in enumerate(self.cameras):+ a = i * n_cam_params+ b = (i + 1) * n_cam_params+ cam.set_params(best_params[a:b])++ error = self.average_error(p2ds)+ return error++ @jit(parallel=True, forceobj=True)+ def _error_fun_bundle(self, params, p2ds, n_cam_params, extra):+ """Error function for bundle adjustment"""+ good = ~np.isnan(p2ds)+ n_cams = len(self.cameras)++ for i in range(n_cams):+ cam = self.cameras[i]+ a = i * n_cam_params+ b = (i + 1) * n_cam_params+ cam.set_params(params[a:b])++ n_cams = len(self.cameras)+ sub = n_cam_params * n_cams+ n3d = p2ds.shape[1] * 3+ p3ds_test = params[sub: sub + n3d].reshape(-1, 3)+ errors = self.reprojection_error(p3ds_test, p2ds)+ errors_reproj = errors[good]++ if extra is not None:+ ids = extra["ids_map"]+ objp = extra["objp"]+ min_scale = np.min(objp[objp > 0])+ n_boards = int(np.max(ids)) + 1+ a = sub + n3d+ rvecs = params[a: a + n_boards * 3].reshape(-1, 3)+ tvecs = params[a + n_boards * 3: a + n_boards * 6].reshape(-1, 3)+ expected = transform_points(objp, rvecs[ids], tvecs[ids])+ errors_obj = 2 * (p3ds_test - expected).ravel() / min_scale+ else:+ errors_obj = np.array([])++ return np.hstack([errors_reproj, errors_obj])++ def _jac_sparsity_bundle(self, p2ds, n_cam_params, extra):+ """Given an CxNx2 array of 2D points,+ where N is the number of points and C is the number of cameras,+ compute the sparsity structure of the jacobian for bundle adjustment"""++ point_indices = np.zeros(p2ds.shape, dtype="int32")+ cam_indices = np.zeros(p2ds.shape, dtype="int32")++ for i in range(p2ds.shape[1]):+ point_indices[:, i] = i++ for j in range(p2ds.shape[0]):+ cam_indices[j] = j++ good = ~np.isnan(p2ds)++ if extra is not None:+ ids = extra["ids_map"]+ n_boards = int(np.max(ids)) + 1+ total_board_params = n_boards * (3 + 3) # rvecs + tvecs+ else:+ n_boards = 0+ total_board_params = 0++ n_cams = p2ds.shape[0]+ n_points = p2ds.shape[1]+ total_params_reproj = n_cams * n_cam_params + n_points * 3+ n_params = total_params_reproj + total_board_params++ n_good_values = np.sum(good)+ if extra is not None:+ n_errors = n_good_values + n_points * 3+ else:+ n_errors = n_good_values++ A_sparse = dok_matrix((n_errors, n_params), dtype="int16")++ cam_indices_good = cam_indices[good]+ point_indices_good = point_indices[good]++ # -- reprojection error --+ ix = np.arange(n_good_values)++ ## update camera params based on point error+ for i in range(n_cam_params):+ A_sparse[ix, cam_indices_good * n_cam_params + i] = 1++ ## update point position based on point error+ for i in range(3):+ A_sparse[ix, n_cams * n_cam_params + point_indices_good * 3 + i] = 1++ # -- match for the object points--+ if extra is not None:+ point_ix = np.arange(n_points)++ ## update all the camera parameters+ # A_sparse[n_good_values:n_good_values+n_points*3,+ # 0:n_cams*n_cam_params] = 1++ ## update board rotation and translation based on error from expected+ for i in range(3):+ for j in range(3):+ A_sparse[+ n_good_values + point_ix * 3 + i,+ total_params_reproj + ids * 3 + j,+ ] = 1+ A_sparse[+ n_good_values + point_ix * 3 + i,+ total_params_reproj + n_boards * 3 + ids * 3 + j,+ ] = 1++ ## update point position based on error from expected+ for i in range(3):+ A_sparse[+ n_good_values + point_ix * 3 + i,+ n_cams * n_cam_params + point_ix * 3 + i,+ ] = 1++ return A_sparse++ def _initialize_params_bundle(self, p2ds, extra):+ """Given an CxNx2 array of 2D points,+ where N is the number of points and C is the number of cameras,+ initializes the parameters for bundle adjustment"""++ cam_params = np.hstack([cam.get_params() for cam in self.cameras])+ n_cam_params = len(cam_params) // len(self.cameras)++ total_cam_params = len(cam_params)++ n_cams, n_points, _ = p2ds.shape+ assert n_cams == len(self.cameras), (+ "number of cameras in CameraGroup does not " "match number of cameras in 2D points given"+ )++ p3ds = self.triangulate(p2ds)++ if extra is not None:+ ids = extra["ids_map"]+ n_boards = int(np.max(ids[~np.isnan(ids)])) + 1+ total_board_params = n_boards * (3 + 3) # rvecs + tvecs++ # initialize to 0+ rvecs = np.zeros((n_boards, 3), dtype="float64")+ tvecs = np.zeros((n_boards, 3), dtype="float64")++ if "rvecs" in extra and "tvecs" in extra:+ rvecs_all = extra["rvecs"]+ tvecs_all = extra["tvecs"]+ for board_num in range(n_boards):+ point_id = np.where(ids == board_num)[0][0]+ cam_ids_possible = np.where(~np.isnan(p2ds[:, point_id, 0]))[0]+ cam_id = np.random.choice(cam_ids_possible)+ M_cam = self.cameras[cam_id].get_extrinsics_mat()+ M_board_cam = make_M(rvecs_all[cam_id, point_id], tvecs_all[cam_id, point_id])+ M_board = np.matmul(inverse(M_cam), M_board_cam)+ rvec, tvec = get_rtvec(M_board)+ rvecs[board_num] = rvec+ tvecs[board_num] = tvec++ else:+ total_board_params = 0++ x0 = np.zeros(total_cam_params + p3ds.size + total_board_params)+ x0[:total_cam_params] = cam_params+ x0[total_cam_params: total_cam_params + p3ds.size] = p3ds.ravel()++ if extra is not None:+ start_board = total_cam_params + p3ds.size+ x0[start_board: start_board + n_boards * 3] = rvecs.ravel()+ x0[start_board + n_boards * 3: start_board + n_boards * 6] = tvecs.ravel()++ return x0, n_cam_params++ def optim_points(+ self,+ points,+ p3ds,+ constraints=[],+ constraints_weak=[],+ scale_smooth=4,+ scale_length=2,+ scale_length_weak=0.5,+ reproj_error_threshold=15,+ reproj_loss="soft_l1",+ n_deriv_smooth=1,+ scores=None,+ verbose=False,+ ):+ """+ Take in an array of 2D points of shape CxNxJx2,+ an array of 3D points of shape NxJx3,+ and an array of constraints of shape Kx2, where+ C: number of camera+ N: number of frames+ J: number of joints+ K: number of constraints++ This function creates an optimized array of 3D points of shape NxJx3.++ Example constraints:+ constraints = [[0, 1], [1, 2], [2, 3]]+ (meaning that lengths of segments 0->1, 1->2, 2->3 are all constant)++ """+ assert points.shape[0] == len(+ self.cameras+ ), "Invalid points shape, first dim should be equal to" " number of cameras ({}), but shape is {}".format(+ len(self.cameras), points.shape+ )++ n_cams, n_frames, n_joints, _ = points.shape+ constraints = np.array(constraints)+ constraints_weak = np.array(constraints_weak)++ p3ds_intp = np.apply_along_axis(interpolate_data, 0, p3ds)++ p3ds_med = np.apply_along_axis(medfilt_data, 0, p3ds_intp, size=7)++ default_smooth = 1.0 / np.mean(np.abs(np.diff(p3ds_med, axis=0)))+ scale_smooth_full = scale_smooth * default_smooth++ t1 = time.time()++ x0 = self._initialize_params_triangulation(p3ds_intp, constraints, constraints_weak)++ x0[~np.isfinite(x0)] = 0++ jac = self._jac_sparsity_triangulation(points, constraints, constraints_weak, n_deriv_smooth)++ opt2 = optimize.least_squares(+ self._error_fun_triangulation,+ x0=x0,+ jac_sparsity=jac,+ loss="linear",+ ftol=1e-3,+ verbose=2 * verbose,+ args=(+ points,+ constraints,+ constraints_weak,+ scores,+ scale_smooth_full,+ scale_length,+ scale_length_weak,+ reproj_error_threshold,+ reproj_loss,+ n_deriv_smooth,+ ),+ )++ p3ds_new2 = opt2.x[: p3ds.size].reshape(p3ds.shape)++ t2 = time.time()++ if verbose:+ print("optimization took {:.2f} seconds".format(t2 - t1))++ return p3ds_new2++ def optim_points_possible(+ self,+ points,+ p3ds,+ constraints=[],+ constraints_weak=[],+ scale_smooth=4,+ scale_length=2,+ scale_length_weak=0.5,+ reproj_error_threshold=15,+ reproj_loss="soft_l1",+ n_deriv_smooth=1,+ scores=None,+ verbose=False,+ ):+ """+ Take in an array of 2D points of shape CxNxJxPx2,+ an array of 3D points of shape NxJx3,+ and an array of constraints of shape Kx2, where+ C: number of camera+ N: number of frames+ J: number of joints+ P: number of possible options per point+ K: number of constraints++ This function creates an optimized array of 3D points of shape NxJx3.++ Example constraints:+ constraints = [[0, 1], [1, 2], [2, 3]]+ (meaning that lengths of segments 0->1, 1->2, 2->3 are all constant)++ """+ assert points.shape[0] == len(+ self.cameras+ ), "Invalid points shape, first dim should be equal to" " number of cameras ({}), but shape is {}".format(+ len(self.cameras), points.shape+ )++ n_cams, n_frames, n_joints, n_possible, _ = points.shape+ constraints = np.array(constraints)+ constraints_weak = np.array(constraints_weak)++ p3ds_intp = np.apply_along_axis(interpolate_data, 0, p3ds)++ p3ds_med = np.apply_along_axis(medfilt_data, 0, p3ds_intp, size=7)++ default_smooth = 1.0 / np.mean(np.abs(np.diff(p3ds_med, axis=0)))+ scale_smooth_full = scale_smooth * default_smooth++ t1 = time.time()++ x0 = self._initialize_params_triangulation_possible(+ p3ds_intp,+ points,+ constraints=constraints,+ constraints_weak=constraints_weak,+ )++ print("getting jacobian...")+ jac = self._jac_sparsity_triangulation_possible(+ points,+ constraints=constraints,+ constraints_weak=constraints_weak,+ n_deriv_smooth=n_deriv_smooth,+ )++ beta = 5++ print("starting optimization...")+ opt2 = optimize.least_squares(+ self._error_fun_triangulation_possible,+ x0=x0,+ jac_sparsity=jac,+ loss="linear",+ ftol=1e-3,+ verbose=2 * verbose,+ args=(+ points,+ beta,+ constraints,+ constraints_weak,+ scores,+ scale_smooth_full,+ scale_length,+ scale_length_weak,+ reproj_error_threshold,+ reproj_loss,+ n_deriv_smooth,+ ),+ )+ params = opt2.x++ p3ds_new2 = params[: p3ds.size].reshape(p3ds.shape)++ bad = np.isnan(points[:, :, :, :, 0])+ all_bad = np.all(bad, axis=3)++ n_params_norm = p3ds.size + len(constraints) + len(constraints_weak)++ alphas = np.zeros((n_cams, n_frames, n_joints, n_possible), dtype="float64")+ alphas[~bad] = params[n_params_norm:]++ alphas_exp = np.exp(beta * alphas)+ alphas_exp[bad] = 0+ alphas_sum = np.sum(alphas_exp, axis=3)+ alphas_sum[all_bad] = 1+ alphas_norm = alphas_exp / alphas_sum[:, :, :, None]+ alphas_norm[bad] = np.nan++ t2 = time.time()++ if verbose:+ print("optimization took {:.2f} seconds".format(t2 - t1))++ return p3ds_new2, alphas_norm++ def triangulate_optim(self, points, init_ransac=False, init_progress=False, **kwargs):+ """+ Take in an array of 2D points of shape CxNxJx2, and an array of constraints of shape Kx2, where+ C: number of camera+ N: number of frames+ J: number of joints+ K: number of constraints++ This function creates an optimized array of 3D points of shape NxJx3.++ Example constraints:+ constraints = [[0, 1], [1, 2], [2, 3]]+ (meaning that lengths of segments 0->1, 1->2, 2->3 are all constant)++ """++ assert points.shape[0] == len(+ self.cameras+ ), "Invalid points shape, first dim should be equal to" " number of cameras ({}), but shape is {}".format(+ len(self.cameras), points.shape+ )++ n_cams, n_frames, n_joints, _ = points.shape+ # constraints = np.array(constraints)+ # constraints_weak = np.array(constraints_weak)++ points_shaped = points.reshape(n_cams, n_frames * n_joints, 2)+ if init_ransac:+ p3ds, picked, p2ds, errors = self.triangulate_ransac(points_shaped, progress=init_progress)+ points = p2ds.reshape(points.shape)+ else:+ p3ds = self.triangulate(points_shaped, progress=init_progress)+ p3ds = p3ds.reshape((n_frames, n_joints, 3))++ c = np.isfinite(p3ds[:, :, 0])+ if np.sum(c) < 20:+ print("warning: not enough 3D points to calculate_center_of_mass optimization")+ return p3ds++ return self.optim_points(points, p3ds, **kwargs)++ @jit(forceobj=True, parallel=True)+ def _error_fun_triangulation(+ self,+ params,+ p2ds,+ constraints=[],+ constraints_weak=[],+ scores=None,+ scale_smooth=10000,+ scale_length=1,+ scale_length_weak=0.2,+ reproj_error_threshold=100,+ reproj_loss="soft_l1",+ n_deriv_smooth=1,+ ):+ n_cams, n_frames, n_joints, _ = p2ds.shape++ n_3d = n_frames * n_joints * 3+ n_constraints = len(constraints)+ n_constraints_weak = len(constraints_weak)++ # load params+ p3ds = params[:n_3d].reshape((n_frames, n_joints, 3))+ joint_lengths = np.array(params[n_3d: n_3d + n_constraints])+ joint_lengths_weak = np.array(params[n_3d + n_constraints:])++ # reprojection errors+ p3ds_flat = p3ds.reshape(-1, 3)+ p2ds_flat = p2ds.reshape((n_cams, -1, 2))+ errors = self.reprojection_error(p3ds_flat, p2ds_flat)+ if scores is not None:+ scores_flat = scores.reshape((n_cams, -1))+ errors = errors * scores_flat[:, :, None]+ errors_reproj = errors[~np.isnan(p2ds_flat)]++ rp = reproj_error_threshold+ errors_reproj = np.abs(errors_reproj)+ if reproj_loss == "huber":+ bad = errors_reproj > rp+ errors_reproj[bad] = rp * (2 * np.sqrt(errors_reproj[bad] / rp) - 1)+ elif reproj_loss == "linear":+ pass+ elif reproj_loss == "soft_l1":+ errors_reproj = rp * 2 * (np.sqrt(1 + errors_reproj / rp) - 1)++ # temporal constraint+ errors_smooth = np.diff(p3ds, n=n_deriv_smooth, axis=0).ravel() * scale_smooth++ # joint length constraint+ errors_lengths = np.empty((n_constraints, n_frames), dtype="float64")+ for cix, (a, b) in enumerate(constraints):+ lengths = np.linalg.norm(p3ds[:, a] - p3ds[:, b], axis=1)+ expected = joint_lengths[cix]+ errors_lengths[cix] = 100 * (lengths - expected) / expected+ errors_lengths = errors_lengths.ravel() * scale_length++ errors_lengths_weak = np.empty((n_constraints_weak, n_frames), dtype="float64")+ for cix, (a, b) in enumerate(constraints_weak):+ lengths = np.linalg.norm(p3ds[:, a] - p3ds[:, b], axis=1)+ expected = joint_lengths_weak[cix]+ errors_lengths_weak[cix] = 100 * (lengths - expected) / expected+ errors_lengths_weak = errors_lengths_weak.ravel() * scale_length_weak++ return np.hstack([errors_reproj, errors_smooth, errors_lengths, errors_lengths_weak])++ def _error_fun_triangulation_possible(self, params, p2ds, beta=2, constraints=[], constraints_weak=[], *args):+ # extract alphas from end of params+ # soft argmax for picking the appropriate points from p2ds+ # pass the points to error_fun_triangulate_possible for residuals+ # add errors to keep the alphas in check+ # return all the errors++ n_cams, n_frames, n_joints, n_possible, _ = p2ds.shape++ n_3d = n_frames * n_joints * 3+ n_constraints = len(constraints)+ n_constraints_weak = len(constraints_weak)+ n_params_norm = n_3d + n_constraints + n_constraints_weak++ # load params+ bad = np.isnan(p2ds[:, :, :, :, 0])+ all_bad = np.all(bad, axis=3)++ alphas = np.zeros((n_cams, n_frames, n_joints, n_possible), dtype="float64")+ alphas[~bad] = params[n_params_norm:]+ params_rest = np.array(params[:n_params_norm])++ # get normalized alphas+ alphas_exp = np.exp(beta * alphas)+ alphas_exp[bad] = 0+ alphas_sum = np.sum(alphas_exp, axis=3)+ alphas_sum[all_bad] = 1+ alphas_norm = alphas_exp / alphas_sum[:, :, :, None]++ # extract the 2D points using soft argmax+ p2ds_test = np.copy(p2ds)+ p2ds_test[bad] = 0+ p2ds_adj = np.sum(alphas_norm[:, :, :, :, None] * p2ds_test, axis=3)+ p2ds_adj[all_bad] = np.nan++ errors = self._error_fun_triangulation(params_rest, p2ds_adj, constraints, constraints_weak, *args)++ alphas_test = alphas_norm[~all_bad]+ errors_alphas = (1 - np.std(alphas_test, axis=1)) * 10++ return np.hstack([errors, errors_alphas])++ def _initialize_params_triangulation(self, p3ds, constraints=[], constraints_weak=[]):+ joint_lengths = np.empty(len(constraints), dtype="float64")+ joint_lengths_weak = np.empty(len(constraints_weak), dtype="float64")++ for cix, (a, b) in enumerate(constraints):+ lengths = np.linalg.norm(p3ds[:, a] - p3ds[:, b], axis=1)+ joint_lengths[cix] = np.median(lengths)++ for cix, (a, b) in enumerate(constraints_weak):+ lengths = np.linalg.norm(p3ds[:, a] - p3ds[:, b], axis=1)+ joint_lengths_weak[cix] = np.median(lengths)++ all_lengths = np.hstack([joint_lengths, joint_lengths_weak])+ med = np.median(all_lengths)+ if med == 0:+ med = 1e-3++ mad = np.median(np.abs(all_lengths - med))++ joint_lengths[joint_lengths == 0] = med+ joint_lengths_weak[joint_lengths_weak == 0] = med+ joint_lengths[joint_lengths > med + mad * 5] = med+ joint_lengths_weak[joint_lengths_weak > med + mad * 5] = med++ return np.hstack([p3ds.ravel(), joint_lengths, joint_lengths_weak])++ def _initialize_params_triangulation_possible(self, p3ds, p2ds, **kwargs):+ # initialize params using above function+ # initialize alphas to 1 for first one and 0 for other possible++ n_cams, n_frames, n_joints, n_possible, _ = p2ds.shape+ good = ~np.isnan(p2ds[:, :, :, :, 0])++ alphas = np.zeros((n_cams, n_frames, n_joints, n_possible), dtype="float64")+ alphas[:, :, :, 0] = 0++ params = self._initialize_params_triangulation(p3ds, **kwargs)+ params_full = np.hstack([params, alphas[good]])++ return params_full++ def _jac_sparsity_triangulation(self, p2ds, constraints=[], constraints_weak=[], n_deriv_smooth=1):+ n_cams, n_frames, n_joints, _ = p2ds.shape+ n_constraints = len(constraints)+ n_constraints_weak = len(constraints_weak)++ p2ds_flat = p2ds.reshape((n_cams, -1, 2))++ point_indices = np.zeros(p2ds_flat.shape, dtype="int32")+ for i in range(p2ds_flat.shape[1]):+ point_indices[:, i] = i++ point_indices_3d = np.arange(n_frames * n_joints).reshape((n_frames, n_joints))++ good = ~np.isnan(p2ds_flat)+ n_errors_reproj = np.sum(good)+ n_errors_smooth = (n_frames - n_deriv_smooth) * n_joints * 3+ n_errors_lengths = n_constraints * n_frames+ n_errors_lengths_weak = n_constraints_weak * n_frames++ n_errors = n_errors_reproj + n_errors_smooth + n_errors_lengths + n_errors_lengths_weak++ n_3d = n_frames * n_joints * 3+ n_params = n_3d + n_constraints + n_constraints_weak++ point_indices_good = point_indices[good]++ A_sparse = dok_matrix((n_errors, n_params), dtype="int16")++ # constraints for reprojection errors+ ix_reproj = np.arange(n_errors_reproj)+ for k in range(3):+ A_sparse[ix_reproj, point_indices_good * 3 + k] = 1++ # sparse constraints for smoothness in time+ frames = np.arange(n_frames - n_deriv_smooth)+ for j in range(n_joints):+ for n in range(n_deriv_smooth + 1):+ pa = point_indices_3d[frames, j]+ pb = point_indices_3d[frames + n, j]+ for k in range(3):+ A_sparse[n_errors_reproj + pa * 3 + k, pb * 3 + k] = 1++ ## -- strong constraints --+ # joint lengths should change with joint lengths errors+ start = n_errors_reproj + n_errors_smooth+ frames = np.arange(n_frames)+ for cix, (a, b) in enumerate(constraints):+ A_sparse[start + cix * n_frames + frames, n_3d + cix] = 1++ # points should change accordingly to match joint lengths too+ frames = np.arange(n_frames)+ for cix, (a, b) in enumerate(constraints):+ pa = point_indices_3d[frames, a]+ pb = point_indices_3d[frames, b]+ for k in range(3):+ A_sparse[start + cix * n_frames + frames, pa * 3 + k] = 1+ A_sparse[start + cix * n_frames + frames, pb * 3 + k] = 1++ ## -- weak constraints --+ # joint lengths should change with joint lengths errors+ start = n_errors_reproj + n_errors_smooth + n_errors_lengths+ frames = np.arange(n_frames)+ for cix, (a, b) in enumerate(constraints_weak):+ A_sparse[start + cix * n_frames + frames, n_3d + n_constraints + cix] = 1++ # points should change accordingly to match joint lengths too+ frames = np.arange(n_frames)+ for cix, (a, b) in enumerate(constraints_weak):+ pa = point_indices_3d[frames, a]+ pb = point_indices_3d[frames, b]+ for k in range(3):+ A_sparse[start + cix * n_frames + frames, pa * 3 + k] = 1+ A_sparse[start + cix * n_frames + frames, pb * 3 + k] = 1++ return A_sparse++ def _jac_sparsity_triangulation_possible(self, p2ds_full, **kwargs):+ # initialize sparse jacobian using above function+ # extend to include alphas from parameters+ ## TODO: this initialization is really slow for some reason++ n_cams, n_frames, n_joints, n_possible, _ = p2ds_full.shape+ good_full = ~np.isnan(p2ds_full[:, :, :, :, 0])+ any_good = np.any(good_full, axis=3)++ n_alphas = np.sum(good_full)+ n_errors_alphas = np.sum(any_good)++ p2ds = p2ds_full[:, :, :, 0]+ A_sparse = self._jac_sparsity_triangulation(p2ds, **kwargs)++ n_errors, n_params = A_sparse.shape++ B_sparse = dok_matrix((n_errors + n_errors_alphas, n_params + n_alphas), dtype="int16")+ for r, c in zip(*A_sparse.nonzero()):+ B_sparse[r, c] = A_sparse[r, c]++ point_indices_2d = np.arange(n_cams * n_frames * n_joints).reshape(n_cams, n_frames, n_joints)+ point_indices_2d_rep = np.repeat(point_indices_2d[:, :, :, None], 2, axis=3)+ point_indices_2d_good = point_indices_2d_rep[~np.isnan(p2ds)]+ point_indices_good = point_indices_2d[any_good]++ alpha_indices = np.zeros((n_cams, n_frames, n_joints, n_possible), dtype="int64")+ for pnum in range(n_possible):+ alpha_indices[:, :, :, pnum] = point_indices_2d++ alpha_indices_good = alpha_indices[good_full]++ # alphas should change according to the reprojection error for each corresponding point+ point_indices_2d_good_find = defaultdict(list)+ for ix, p in enumerate(point_indices_2d_good):+ point_indices_2d_good_find[p].append(ix)++ for ix, alpha_index in enumerate(alpha_indices_good):+ B_sparse[point_indices_2d_good_find[alpha_index], n_params + ix] = 1++ # alphas should change according to the alpha errors+ point_indices_good_find = dict()+ for ix, p in enumerate(point_indices_good):+ point_indices_good_find[p] = ix++ for ix, alpha_index in enumerate(alpha_indices_good):+ if alpha_index in point_indices_good_find:+ err_ix = n_errors + point_indices_good_find[alpha_index]+ B_sparse[err_ix, n_params + ix] = 1++ return B_sparse++ def copy(self):+ cameras = [cam.copy() for cam in self.cameras]+ metadata = copy(self.metadata)+ return AniposeCameraGroup(cameras, metadata)++ def set_rotations(self, rvecs):+ for cam, rvec in zip(self.cameras, rvecs):+ cam.set_rotation(rvec)++ def set_translations(self, tvecs):+ for cam, tvec in zip(self.cameras, tvecs):+ cam.set_translation(tvec)++ def set_world_positions(self, positions):+ for cam, position, in zip(self.cameras, positions):+ cam.set_world_position(position)++ def set_world_orientations(self, orientations):+ for cam, orientation in zip(self.cameras, orientations):+ cam.set_world_orientation(orientation)++ def get_world_positions(self):+ return np.stack([cam.get_world_position() for cam in self.cameras])++ def get_world_orientations(self):+ return np.stack([cam.get_world_orientation() for cam in self.cameras])++ def get_rotations(self):+ rvecs = []+ for cam in self.cameras:+ rvec = cam.get_rotation()+ rvecs.append(rvec)+ return np.array(rvecs)++ def get_translations(self):+ tvecs = []+ for cam in self.cameras:+ tvec = cam.get_translation()+ tvecs.append(tvec)+ return np.array(tvecs)++ def get_names(self):+ return [cam.get_name() for cam in self.cameras]++ def set_names(self, names):+ for cam, name in zip(self.cameras, names):+ cam.set_name(name)++ def average_error(self, p2ds, median=False):+ p3ds = self.triangulate(p2ds)+ errors = self.reprojection_error(p3ds, p2ds, mean=True)+ if median:+ return np.median(errors)+ else:+ return np.mean(errors)++ def calibrate_rows(+ self,+ all_rows: list[list[dict]],+ board,+ init_intrinsics: bool = True,+ init_extrinsics: bool = True,+ verbose: bool = True,+ ) -> tuple[float, list, list]:+ """+ Calibrate cameras from charuco board observations.++ Args:+ all_rows: List of observation rows per camera+ board: Charuco board definition+ init_intrinsics: Whether to initialize camera intrinsics+ init_extrinsics: Whether to initialize camera extrinsics+ verbose: Enable verbose logging++ Returns:+ Tuple of (error, merged_rows, charuco_frame_numbers)+ """+ n_cameras = len(self.cameras)+ n_rows_list = len(all_rows)++ logger.info("=" * 80)+ logger.info("STARTING CAMERA CALIBRATION")+ logger.info("=" * 80)++ assert n_rows_list == n_cameras, \+ f"Number of camera detections ({n_rows_list}) does not match number of cameras ({n_cameras})"++ # Log observation statistics per camera+ logger.info(f"Calibrating {n_cameras} cameras")+ for cam_idx, (rows, camera) in enumerate(zip(all_rows, self.cameras)):+ logger.info(f"Camera {cam_idx} ({camera.get_name()}): {len(rows)} frames with detections")++ size = camera.get_size()+ assert size is not None, \+ f"Camera with name {camera.get_name()} has no specified frame size"+ logger.debug(f" Camera size: {size}")++ # Initialize intrinsics+ if init_intrinsics:+ logger.info("Initializing camera intrinsics...")+ for cam_idx, (rows, camera) in enumerate(zip(all_rows, self.cameras)):+ logger.debug(f" Camera {cam_idx}: Extracting calibration points")+ objp, imgp = board.get_all_calibration_points(rows)++ logger.debug(f" Found {len(objp)} object point sets and {len(imgp)} image point sets")++ mixed = [(o, i) for (o, i) in zip(objp, imgp) if len(o) >= 7]++ if len(mixed) == 0:+ logger.error(f" Camera {cam_idx}: No valid calibration points (need at least 7 points)")+ raise ValueError(f"No valid calibration points for camera {cam_idx}")++ logger.info(f" Camera {cam_idx}: Using {len(mixed)} frames for intrinsics (min 7 points each)")++ objp, imgp = zip(*mixed)++ try:+ matrix = cv2.initCameraMatrix2D(objp, imgp, tuple(camera.get_size()))+ camera.set_camera_matrix(matrix)+ logger.debug(f" Camera {cam_idx}: Initialized camera matrix:\n{matrix}")+ except Exception as e:+ logger.error(f" Camera {cam_idx}: Failed to initialize camera matrix - {e}")+ raise++ logger.info("โ Camera intrinsics initialized successfully")++ # Estimate poses+ logger.info("Estimating board poses for all cameras...")+ for i, (row, cam) in enumerate(zip(all_rows, self.cameras)):+ logger.debug(f" Camera {i}: Estimating poses for {len(row)} frames")+ all_rows[i] = board.estimate_pose_rows(cam, row)+ logger.info("โ Board poses estimated")++ # Extract frame numbers+ charuco_frames = [f["framenum"][1] for f in all_rows[0]]+ logger.debug(f"Frame numbers from camera 0: {charuco_frames[:10]}..." if len(+ charuco_frames) > 10 else f"Frame numbers: {charuco_frames}")++ # Merge observations across cameras+ logger.info("Merging observations across cameras...")+ merged = merge_rows(all_rows)+ logger.info(f"โ Merged {len(merged)} multi-camera observations")++ # Extract points for calibration+ logger.info("Extracting calibration points (minimum 2 cameras per point)...")+ imgp, extra = extract_points(merged, board, min_cameras=2)+ logger.info(f"โ Extracted points: shape={imgp.shape}")+ logger.debug(f" Extra data keys: {extra.keys() if extra else 'None'}")++ # Initialize extrinsics+ if init_extrinsics:+ logger.info("Initializing camera extrinsics...")++ logger.debug("Extracting rotation/translation vectors from observations")+ rtvecs = extract_rtvecs(merged)+ logger.info(f" Extracted rtvecs: shape={rtvecs.shape}")++ # Log connections between cameras+ if verbose:+ logger.info("Camera pair connections (shared observations):")+ connections = get_connections(rtvecs, self.get_names())++ # Sort by camera pair for readable output+ for (cam_a, cam_b), count in sorted(connections.items()):+ if cam_a < cam_b: # Only show each pair once+ logger.info(f" {cam_a} <-> {cam_b}: {count} frames")++ logger.debug("Computing initial extrinsics from observations")+ try:+ rvecs, tvecs = get_initial_extrinsics(rtvecs, cam_names=self.get_names())+ self.set_rotations(rvecs)+ self.set_translations(tvecs)+ logger.info("โ Initial extrinsics computed successfully")+ except Exception as e:+ logger.error(f"Failed to compute initial extrinsics: {e}")+ logger.error("This usually means insufficient shared observations between cameras")+ raise++ # Bundle adjustment+ logger.info("Starting iterative bundle adjustment...")+ logger.info(f" Input points shape: {imgp.shape}")+ logger.info(f" Error threshold: 1.0")++ try:+ error = self.bundle_adjust_iter(imgp, extra, verbose=verbose, error_threshold=1)+ logger.info(f"โ Bundle adjustment completed successfully")+ logger.info(f" Final reprojection error: {error:.4f}")+ except Exception as e:+ logger.error(f"Bundle adjustment failed: {e}")+ raise++ logger.info("=" * 80)+ logger.info(f"CALIBRATION COMPLETE - Final error: {error:.4f}")+ logger.info("=" * 80)++ return error, merged, charuco_frames++ def get_rows_videos(self, videos: List[List[str]], board: "AniposeCharucoBoard", verbose: bool = True):+ num_corners = board.total_size+ self._get_charuco_2d_data(videos=videos, board=board)++ if self.charuco_2d_data is None:+ raise ValueError(+ "Charuco 2D data has not been initialized. Call _get_charuco_2d_data() first, or check for errors in the video processing.")++ all_rows = []++ num_cameras, num_frames, _, _ = self.charuco_2d_data.shape+ for camera_number in range(num_cameras):+ camera_rows = []+ for frame in range(num_frames):+ filled = self.charuco_2d_data[camera_number, frame, :, :]+ filled = filled.astype(np.float32)+ filled = np.reshape(filled, (num_corners, 1, 2)) # Add empty column anipose expects+ mask = (~np.isnan(filled[:, :, 0])) & (~np.isnan(filled[:, :, 1]))+ non_empty_ids = np.where(mask)[0]+ corners = filled[non_empty_ids, :, :]+ non_empty_ids = non_empty_ids.reshape(-1, 1) # Add empty column anipose expects+ if corners.shape[0] != 0:+ row = {+ "framenum": (0, frame),+ "corners": corners,+ "ids": non_empty_ids,+ "filled": filled,+ }+ camera_rows.append(row)+ all_rows.append(camera_rows)+ if verbose:+ print(f"Charuco detection results:")+ for i, rows in enumerate(all_rows):+ print(f"\tCamera {i} has {len(rows)} frames with detected corners.")++ return all_rows++ def _get_charuco_2d_data(self, videos: List[List[str]], board: "AniposeCharucoBoard"):+ """+ Processes a list of a list of videos to extract Charuco 2D data.++ Should be called once during the initial calibration, and then referenced with self.charuco_2d_data+ """+ # video_paths = [Path(video[0]) for video in videos]+ # charuco_2d_data = process_list_of_videos(+ # model_info=CharucoModelInfo(),+ # tracking_params=CharucoTrackingParams(+ # charuco_squares_x_in=board.squaresX,+ # charuco_squares_y_in=board.squaresY,+ # charuco_dict_id=ARUCO_DICTS[(board.marker_bits, board.dict_size)]+ # ),+ # video_paths=video_paths,+ # num_processes=min(len(videos), multiprocessing.cpu_count() - 1),+ # )+ #+ # self.charuco_2d_data = charuco_2d_data+ pass++ def set_camera_sizes_videos(self, videos):+ for cix, (cam, cam_videos) in enumerate(zip(self.cameras, videos)):+ rows_cam = []+ for vnum, vidname in enumerate(cam_videos):+ params = get_video_params(vidname)+ size = (params["width"], params["height"])+ cam.set_size(size)++ def calibrate_videos(+ self,+ videos,+ board: "AniposeCharucoBoard",+ init_intrinsics=True,+ init_extrinsics=True,+ verbose=True,+ **kwargs,+ ):+ """Takes as input a list of list of video filenames, one list of each camera.+ Also takes a board which specifies what should be detected in the videos"""++ all_rows = self.get_rows_videos(videos, board, verbose=verbose)+ if init_extrinsics:+ self.set_camera_sizes_videos(videos)++ error, merged, charuco_frames = self.calibrate_rows(+ all_rows,+ board,+ init_intrinsics=init_intrinsics,+ init_extrinsics=init_extrinsics,+ verbose=verbose,+ )+ return error, merged, charuco_frames++ def get_dicts(self):+ out = []+ for cam in self.cameras:+ out.append(cam.get_dict())+ return out++ @staticmethod+ def from_dicts(cameras_dicts):+ cameras = []+ for d in cameras_dicts:+ cam = AniposeCamera.from_dict(d)+ cameras.append(cam)+ return AniposeCameraGroup(cameras)++ @staticmethod+ def from_names(names, fisheye=False):+ cameras = []+ for name in names:+ cam = AniposeCamera(name=name)+ cameras.append(cam)+ return AniposeCameraGroup(cameras)++ def load_dicts(self, arr):+ for cam, d in zip(self.cameras, arr):+ cam.load_dict(d)++ def dump(self, fname):+ dicts = self.get_dicts()+ names = [camera_dict['name'] for camera_dict in dicts]+ master_dict = dict(zip(names, dicts))+ master_dict["metadata"] = self.metadata+ with open(fname, "w") as f:+ toml.dump(master_dict, f)++ @staticmethod+ def load(fname: str):+ if not Path(fname).is_file():+ raise FileNotFoundError(f"File {fname} not found.")+ master_dict = toml.load(fname)+ keys = sorted(master_dict.keys())+ items = [master_dict[k] for k in keys if k != "metadata"]+ cgroup = AniposeCameraGroup.from_dicts(items)+ if "metadata" in master_dict:+ cgroup.metadata = master_dict["metadata"]+ return cgroup++ def resize_cameras(self, scale):+ for cam in self.cameras:+ cam.resize_camera(scale)++ @jit(parallel=True, forceobj=True)+ def calculate_mean_reprojection_error(self, errors):+ errors_norm = np.linalg.norm(errors, axis=2)+ good = ~np.isnan(errors_norm)+ errors_norm[~good] = 0+ denom = np.sum(good, axis=0).astype("float64")+ denom[denom < 1.5] = np.nan+ errors = np.sum(errors_norm, axis=0) / denom+ return errors++++class AniposeCharucoBoard(CharucoBoard):+ def __init__(+ self,+ squaresX: int = 5,+ squaresY: int = 7,+ square_length: float = 1.0,+ marker_length: float = 0.8,+ marker_bits=4,+ dict_size=250,+ ):+ super().__init__(+ squaresX,+ squaresY,+ square_length,+ marker_length,+ marker_bits,+ dict_size,+ )+ self.squaresX = squaresX+ self.squaresY = squaresY+ self.square_length = square_length+ self.marker_length = marker_length+ self.marker_bits = marker_bits+ self.dict_size = dict_size++ dkey = (marker_bits, dict_size)+ self.dictionary = cv2.aruco.getPredefinedDictionary(ARUCO_DICTS[dkey])++ self.board = cv2.aruco.CharucoBoard(+ size=[squaresX, squaresY],+ squareLength=square_length,+ markerLength=marker_length,+ dictionary=self.dictionary,+ )++ total_size = (squaresX - 1) * (squaresY - 1)++ objp = np.zeros((total_size, 3), np.float64)+ objp[:, :2] = np.mgrid[0: (squaresX - 1), 0: (squaresY - 1)].T.reshape(-1, 2)+ objp *= square_length+ self.objPoints = objp++ self.empty_detection = np.zeros((total_size, 1, 2)) * np.nan+ self.total_size = total_size++ def detect_markers(self, image, camera=None, refine=True):+ if len(image.shape) == 3:+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)+ else:+ gray = image++ params = cv2.aruco.DetectorParameters()+ params.cornerRefinementMethod = cv2.aruco.CORNER_REFINE_CONTOUR+ params.adaptiveThreshWinSizeMin = 100+ params.adaptiveThreshWinSizeMax = 700+ params.adaptiveThreshWinSizeStep = 50+ params.adaptiveThreshConstant = 0++ try:+ corners, ids, rejectedImgPoints = cv2.aruco.detectMarkers(gray, self.dictionary, parameters=params)+ except Exception:+ ids = None++ if ids is None:+ return [], []++ if camera is None:+ K = D = None+ else:+ K = camera.get_camera_matrix()+ D = camera.get_distortions()++ if refine:+ detectedCorners, detectedIds, rejectedCorners, recoveredIdxs = cv2.aruco.refineDetectedMarkers(+ gray, self.board, corners, ids, rejectedImgPoints, K, D, parameters=params+ )+ else:+ detectedCorners, detectedIds = corners, ids++ return detectedCorners, detectedIds++ def detect_image(self, image, camera=None):+ if len(image.shape) == 3:+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)+ else:+ gray = image++ corners, ids = self.detect_markers(image, camera, refine=True)+ if len(corners) > 0:+ ret, detectedCorners, detectedIds = cv2.aruco.interpolateCornersCharuco(corners, ids, gray, self.board)+ if detectedIds is None:+ detectedCorners = detectedIds = np.float64([])+ else:+ detectedCorners = detectedIds = np.float64([])++ return detectedCorners, detectedIds++ def estimate_pose_points(self, camera: AniposeCamera, corners: np.ndarray | None, ids: np.ndarray | None) -> tuple[+ np.ndarray | None, np.ndarray | None]:+ if corners is None or ids is None or len(corners) < 5:+ return None, None++ n_corners = corners.size // 2+ corners = np.reshape(corners, (n_corners, 1, 2))++ # Ensure corners are float32 for OpenCV+ corners = corners.astype(np.float32)++ # Ensure ids are the correct dtype as well+ ids = ids.astype(np.int32) if ids.dtype != np.int32 else ids++ K = camera.get_camera_matrix()+ D = camera.get_distortions()++ ret, rvec, tvec = cv2.aruco.estimatePoseCharucoBoard(corners, ids, self.board, K, D, None, None)++ return rvec, tvecdiff --git a/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/calibration_helpers/point_triangulator.py b/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/calibration_helpers/point_triangulator.pynew file mode 100644index 00000000..cc35410c--- /dev/null+++ b/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/calibration_helpers/point_triangulator.py@@ -0,0 +1,422 @@+from dataclasses import dataclass, field+from pathlib import Path++import cv2+import numpy as np+from skellycam.core.types.type_overloads import CameraIdString++from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.camera_math_models import \+ CameraDistortionCoefficients, \+ CameraMatrix+from freemocap.pubsub.pubsub_topics import CameraNodeOutputMessage+++def _triangulate_batch(+ points2d: np.ndarray,+ projection_matrices: np.ndarray,+) -> np.ndarray:+ """+ Vectorized triangulation using Direct Linear Transform (DLT) method.++ DLT constructs a homogeneous linear system AX=0 where each camera contributes 2 rows:++ For N cameras observing point X=[X,Y,Z,1]แต:++ Camera 0: [xโยทPโ - Pโ] [X]+ [yโยทPโ - Pโ] [Y]+ Camera 1: [xโยทPโ - Pโ] ร [Z] = 0+ [yโยทPโ - Pโ] [1]+ โฎ โฎ+ Camera N: [xโยทPโ - Pโ]+ [yโยทPโ - Pโ]++ Matrix A is (2N ร 4), where Pโ, Pโ, Pโ are rows of projection matrix P.++ Solution via SVD: A = UฮฃVแต, take last row of V (min singular value), normalize by w:+ [X, Y, Z, w]แต โ (X/w, Y/w, Z/w)++ :param points2d: Shape (M, N, 2) - M points observed by N cameras (pixel coordinates)+ :param projection_matrices: Shape (N, 3, 4) - full projection matrices P = K[R|t]+ :param preallocated_arrays: Optional pre-allocated arrays (auto-resizes if needed)+ :return: Shape (M, 3) - triangulated 3D positions in world coordinates+ """+ num_points = points2d.shape[0]+ num_cameras = projection_matrices.shape[0]++ A_matrices = np.zeros((num_points, num_cameras * 2, 4), dtype=np.float64)+ points3d_output = np.empty((num_points, 3), dtype=np.float64)++ # Zero out A_matrices in case we're reusing pre-allocated array+ A_matrices.fill(0.0)++ # Build all A matrices at once+ for cam_idx in range(num_cameras):+ x = points2d[:, cam_idx, 0] # All points, this camera, x coord+ y = points2d[:, cam_idx, 1] # All points, this camera, y coord+ mat = projection_matrices[cam_idx]++ # Vectorized construction+ A_matrices[:, cam_idx * 2] = x[:, None] * mat[2] - mat[0]+ A_matrices[:, cam_idx * 2 + 1] = y[:, None] * mat[2] - mat[1]++ # Batch SVD on all matrices at once+ _, _, vh = np.linalg.svd(A_matrices, full_matrices=False)++ # Extract last row of vh for each point+ points3d_h = vh[:, -1, :] # Shape: (num_points, 4)++ # Normalize by w and write directly to output array+ points3d_output[:] = points3d_h[:, :3] / points3d_h[:, 3:4]++ return points3d_output+++@dataclass+class CameraCalibrationData:+ """Camera calibration parameters for a single camera."""++ name: str+ image_size: tuple[int, int] # (width, height)+ matrix: CameraMatrix+ distortion: CameraDistortionCoefficients+ rotation_vector: np.ndarray # 3x1 Rodrigues rotation vector+ translation: np.ndarray # 3x1 XYZ translation vector+ world_position: np.ndarray = field(init=False)+ world_orientation: np.ndarray = field(init=False)++ @classmethod+ def from_dict(cls, camera_id: str, data: dict) -> "CameraCalibrationData":+ """Create from dictionary (e.g., loaded from TOML)."""+ if 'image_size' in data:+ image_size_list = data["image_size"]+ elif 'size' in data:+ image_size_list = data["size"]+ else:+ raise KeyError("Camera calibration data must contain 'size' or 'image_size' key")++ if len(image_size_list) != 2:+ raise ValueError(f"Expected size to have 2 elements, got {len(image_size_list)}")++ return cls(+ name=camera_id,+ image_size=(int(image_size_list[0]), int(image_size_list[1])),+ matrix=CameraMatrix(matrix=np.asarray(data["matrix"])),+ distortion=CameraDistortionCoefficients(coefficients=data["distortions"]),+ rotation_vector=np.array(data["rotation"], dtype=np.float64),+ translation=np.array(data["translation"], dtype=np.float64),+ )++ def __post_init__(self) -> None:+ """Validate shapes and compute world coordinates after initialization."""+ if self.matrix.matrix.shape != (3, 3):+ raise ValueError(f"Expected matrix shape (3, 3), got {self.matrix.matrix.shape}")+ if self.distortion.coefficients.shape != (5,):+ raise ValueError(f"Expected distortion shape (5,), got {self.distortion.coefficients.shape}")+ if self.rotation_vector.shape != (3,):+ raise ValueError(f"Expected rotation_vector shape (3,), got {self.rotation_vector.shape}")+ if self.translation.shape != (3,):+ raise ValueError(f"Expected translation shape (3,), got {self.translation.shape}")++ rotation_matrix = self.rotation_matrix+ object.__setattr__(self, 'world_position', -rotation_matrix.T @ self.translation)+ object.__setattr__(self, 'world_orientation', rotation_matrix.T)++ @property+ def rotation_matrix(self) -> np.ndarray:+ """Convert Rodrigues rotation vector to 3x3 rotation matrix."""+ return cv2.Rodrigues(self.rotation_vector)[0]++ @property+ def extrinsics_matrix(self) -> np.ndarray:+ """Extrinsic matrix [R|t] of shape (3, 4)."""+ extrinsics = np.zeros((3, 4), dtype=np.float64)+ extrinsics[:, :3] = self.rotation_matrix+ extrinsics[:, 3] = self.translation+ return extrinsics++ @property+ def projection_matrix(self) -> np.ndarray:+ """Full projection matrix P = K[R|t] of shape (3, 4)."""+ return self.matrix.matrix @ self.extrinsics_matrix++ def undistort_points(self, points: np.ndarray) -> np.ndarray:+ """+ Undistort 2D points and normalize to camera coordinates.++ :param points: Shape (N, 2) or (N, 1, 2) - distorted pixel coordinates+ :return: Shape (N, 2) - undistorted normalized coordinates+ """+ original_shape = points.shape+ points = points.reshape(-1, 1, 2)+ undistorted = cv2.undistortPoints(+ points,+ self.matrix.matrix.astype(np.float64),+ self.distortion.coefficients.astype(np.float64)+ )+ return undistorted.reshape(original_shape)++ def project_3d_to_2d(self, points3d: np.ndarray) -> np.ndarray:+ """+ Project 3D points to 2D image coordinates (with distortion).++ :param points3d: Shape (N, 3) - 3D world coordinates+ :return: Shape (N, 2) - 2D pixel coordinates+ """+ points3d = points3d.reshape(-1, 1, 3)+ projected, _ = cv2.projectPoints(+ points3d,+ self.rotation_vector,+ self.translation,+ self.matrix.matrix,+ self.distortion.coefficients+ )+ return np.squeeze(projected, axis=1)+++@dataclass+class PointTriangulator:+ """+ Fast triangulator for high-framerate multi-camera 3D reconstruction.++ Supports both array-based (fast) and dictionary-based (convenient) APIs.+ """++ camera_calibrations: dict[str, CameraCalibrationData]+ projection_matrices: np.ndarray = field(init=False)+ camera_names: list[str] = field(init=False)+ num_cameras: int = field(init=False)++ @classmethod+ def from_toml(cls, toml_path: str | Path) -> "PointTriangulator":+ """+ Load camera calibrations from TOML file.++ :param toml_path: Path to calibration TOML file+ :return: Initialized Triangulator+ """+ import toml++ calibration_data = toml.load(toml_path)+ calibration_data.pop("metadata", None)++ camera_calibrations = {+ camera_id: CameraCalibrationData.from_dict(camera_id, data)+ for camera_id, data in calibration_data.items()+ }++ return cls(camera_calibrations=camera_calibrations)++ def __post_init__(self) -> None:+ """Validate and prepare projection matrices after initialization."""+ if not self.camera_calibrations:+ raise ValueError("camera_calibrations cannot be empty")++ self.num_cameras = len(self.camera_calibrations)+ self.camera_names = list(self.camera_calibrations.keys())++ projection_matrices = np.array(+ [cam.projection_matrix for cam in self.camera_calibrations.values()],+ dtype=np.float64+ )++ if projection_matrices.shape != (self.num_cameras, 3, 4):+ raise ValueError(+ f"Expected projection matrices shape ({self.num_cameras}, 3, 4), "+ f"got {projection_matrices.shape}"+ )++ object.__setattr__(+ self,+ 'projection_matrices',+ np.ascontiguousarray(projection_matrices, dtype=np.float64)+ )++ def triangulate_camera_node_outputs(+ self,+ camera_node_outputs: dict[CameraIdString, CameraNodeOutputMessage],+ undistort_points: bool = True,+ compute_reprojection_error: bool = False+ ) -> tuple[np.ndarray, np.ndarray | None]:+ """+ Triangulate 3D points from camera node outputs containing charuco observations.++ :param camera_node_outputs: Dictionary mapping camera IDs to their output messages+ :param undistort_points: If True, undistort points before triangulation+ :param compute_reprojection_error: Whether to compute reprojection errors+ :return: Tuple of (points3d, mean_errors)+ - points3d: Shape (M, 3) - triangulated 3D points for each charuco corner+ - mean_errors: Shape (M,) - mean reprojection error per point (pixels), or None+ """+ points2d_list: list[np.ndarray] = []++ for camera_name in self.camera_names:+ if camera_name not in camera_node_outputs:+ raise ValueError(f"Camera '{camera_name}' not found in camera_node_outputs")++ camera_output = camera_node_outputs[camera_name]++ if camera_output.observation is None:+ raise ValueError(f"Camera '{camera_name}' has no charuco_observation")++ points2d_camera = camera_output.observation.to_2d_array()+ points2d_list.append(points2d_camera)++ points2d_stacked = np.stack(points2d_list, axis=0)+ points2d = np.transpose(points2d_stacked, (1, 0, 2))++ return self.triangulate_points(+ points2d=points2d,+ undistort_points=undistort_points,+ compute_reprojection_error=compute_reprojection_error+ )++ def triangulate_points(+ self,+ points2d: np.ndarray,+ undistort_points: bool = False,+ compute_reprojection_error: bool = True+ ) -> tuple[np.ndarray, np.ndarray | None]:+ """+ Fast array-based triangulation for batch processing.++ :param points2d: Shape (M, N, 2) - M points observed by N cameras (pixel coordinates)+ :param preallocated_arrays: Optional pre-allocated arrays (auto-resizes if needed)+ :param undistort_points: If True, undistort points before triangulation+ :param compute_reprojection_error: Whether to compute reprojection errors+ :return: Tuple of (points3d, mean_errors)+ - points3d: Shape (M, 3) - triangulated 3D points+ - mean_errors: Shape (M,) - mean reprojection error per point (pixels), or None+ """+ if points2d.ndim != 3 or points2d.shape[2] != 2:+ raise ValueError(f"points2d must have shape (M, N, 2), got {points2d.shape}")++ if points2d.shape[1] != self.num_cameras:+ raise ValueError(+ f"points2d has {points2d.shape[1]} cameras but triangulator "+ f"has {self.num_cameras} cameras"+ )++ points2d = np.ascontiguousarray(points2d, dtype=np.float64)++ if undistort_points:+ for cam_idx, cam_calib in enumerate(self.camera_calibrations.values()):+ points2d[:, cam_idx] = cam_calib.undistort_points(points2d[:, cam_idx])++ points3d = _triangulate_batch(+ points2d,+ self.projection_matrices,+ )++ mean_errors = None+ if compute_reprojection_error:+ mean_errors = self._compute_reprojection_errors(points3d, points2d)++ return points3d, mean_errors++ def _compute_reprojection_errors(+ self,+ points3d: np.ndarray,+ points2d: np.ndarray+ ) -> np.ndarray:+ """+ Compute reprojection errors using OpenCV's projection (handles distortion).++ :param points3d: Shape (M, 3) - triangulated 3D points+ :param points2d: Shape (M, N, 2) - original 2D observations+ :return: Shape (M,) - mean reprojection error per point across all cameras+ """+ num_points = points3d.shape[0]+ errors = np.zeros(num_points, dtype=np.float64)++ for point_idx in range(num_points):+ point_errors = []++ for cam_idx, (cam_name, cam_calib) in enumerate(self.camera_calibrations.items()):+ projected = cam_calib.project_3d_to_2d(points3d[point_idx:point_idx + 1])+ diff = projected[0] - points2d[point_idx, cam_idx]+ error = np.linalg.norm(diff)+ point_errors.append(error)++ errors[point_idx] = np.mean(point_errors)++ return errors++ def triangulate_dict(+ self,+ points2d_by_camera: dict[str, dict[str, tuple[float, float]]],+ min_cameras: int = 2,+ compute_reprojection_error: bool = False+ ) -> dict[str, tuple[float, float, float] | dict]:+ """+ Dictionary-based triangulation (backward compatible API).++ :param points2d_by_camera: {camera_name: {point_name: (x, y)}}+ :param min_cameras: Minimum number of cameras required to triangulate a point+ :param compute_reprojection_error: If True, return dict with 'point' and 'error' keys+ :return: {point_name: (x, y, z)} or {point_name: {'point': (x,y,z), 'error': float}}+ """+ if not points2d_by_camera:+ return {}++ first_camera = next(iter(points2d_by_camera.values()))+ point_names = list(first_camera.keys())++ for cam_name, points in points2d_by_camera.items():+ if list(points.keys()) != point_names:+ raise ValueError(f"Camera {cam_name} has different point names")++ results = {}++ for point_name in point_names:+ observations = []+ valid_camera_indices = []++ for cam_idx, cam_name in enumerate(self.camera_names):+ if cam_name not in points2d_by_camera:+ continue++ point2d = points2d_by_camera[cam_name].get(point_name)+ if point2d is None:+ continue++ if np.isnan(point2d).any():+ continue++ observations.append(point2d)+ valid_camera_indices.append(cam_idx)++ if len(observations) < min_cameras:+ results[point_name] = (np.nan, np.nan, np.nan)+ continue++ points2d_array = np.array([observations], dtype=np.float64)+ valid_projection_matrices = self.projection_matrices[valid_camera_indices]++ point3d = _triangulate_batch(points2d_array, valid_projection_matrices)[0]++ if compute_reprojection_error:+ errors = []+ for cam_idx, obs in zip(valid_camera_indices, observations):+ cam_name = self.camera_names[cam_idx]+ cam_calib = self.camera_calibrations[cam_name]+ projected = cam_calib.project_3d_to_2d(point3d.reshape(1, 3))+ error = np.linalg.norm(projected[0] - np.array(obs))+ errors.append(error)++ results[point_name] = {+ 'point': tuple(point3d),+ 'error': float(np.mean(errors))+ }+ else:+ results[point_name] = tuple(point3d)++ return results+++def benchmark_triangulator() -> None:+ # TODO : implement benchmark+ pass+++if __name__ == "__main__":+ benchmark_triangulator()diff --git a/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/calibration_video_node.py b/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/calibration_video_node.pynew file mode 100644index 00000000..8e4f623f--- /dev/null+++ b/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/calibration_video_node.py@@ -0,0 +1,116 @@+import logging+import multiprocessing+from dataclasses import dataclass+from pathlib import Path+import cv2+from pydantic import BaseModel, ConfigDict+from skellycam.core.types.type_overloads import WorkerType+from skellytracker.trackers.charuco_tracker.charuco_detector import CharucoDetector++from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.posthoc_calibration_pipeline import \+ CalibrationpipelineConfig+from freemocap.core.pipeline.pipeline_ipc import PipelineIPC+from freemocap.core.types.type_overloads import PipelineIdString, VideoIdString+from freemocap.pubsub.pubsub_topics import VideoNodeOutputTopic, VideoNodeOutputMessage++logger = logging.getLogger(__name__)++++class VideoNodeState(BaseModel):+ model_config = ConfigDict(+ validate_assignment=True,+ frozen=True+ )+ pipeline_id: PipelineIdString+ alive: bool+ last_seen_frame_number: int | None = None+ calibration_task_state: object | None = None+ mocap_task_state: object = None # TODO - this+++@dataclass+class CalibrationVideoNode:+ video_id:VideoIdString+ video_path:Path+ calibration_pipeline_config: CalibrationpipelineConfig+ shutdown_self_flag: multiprocessing.Value+ worker: WorkerType++ @classmethod+ def create(cls,+ video_id:VideoIdString,+ video_path:Path,+ subprocess_registry: list[multiprocessing.Process],+ calibration_pipeline_config: CalibrationpipelineConfig,+ ipc: PipelineIPC):+ shutdown_self_flag = multiprocessing.Value('b', False)+ worker = multiprocessing.Process(target=cls._run,+ name=f"VideoProcessingNode-{video_path.stem}",+ kwargs=dict(video_id=video_id,+ video_path=video_path,+ ipc=ipc,+ calibration_pipeline_config=calibration_pipeline_config,+ shutdown_self_flag=shutdown_self_flag,+ ),+ )+ subprocess_registry.append(worker)+ return cls(video_id=video_id,+ video_path=video_path,+ shutdown_self_flag=shutdown_self_flag,+ calibration_pipeline_config=calibration_pipeline_config,+ worker=worker+ )++ @staticmethod+ def _run(video_id:VideoIdString,+ video_path:Path,+ ipc: PipelineIPC,+ calibration_pipeline_config: CalibrationpipelineConfig,+ shutdown_self_flag: multiprocessing.Value,+ ):+ if multiprocessing.parent_process():+ # Configure logging if multiprocessing (i.e. if there is a parent process)+ from freemocap.system.logging_configuration.configure_logging import configure_logging+ from freemocap import LOG_LEVEL+ configure_logging(LOG_LEVEL, ws_queue=ipc.ws_queue)++ logger.info(f"Starting video processing node for video: {video_path.stem}")++ video_reader = cv2.VideoCapture(str(video_path))+ success, image = video_reader.read()+ frame_number = 0+ charuco_detector = CharucoDetector.create(config=calibration_pipeline_config.detector_config)+ try:+ while success and not shutdown_self_flag.value and ipc.should_continue:++ charuco_observation = charuco_detector.detect(+ frame_number=frame_number,+ image=image)++ ipc.pubsub.publish(+ topic_type=VideoNodeOutputTopic,+ message=VideoNodeOutputMessage(+ video_id=video_id,+ frame_number=frame_number,+ observation=charuco_observation,+ ),+ )+ success, image = video_reader.read()+ frame_number += 1+ except Exception as e:+ logger.exception(f"Exception in video node for video: {video_path.stem} - {e}")+ ipc.kill_everything()+ raise e+ finally:+ logger.debug(f"Shutting down video processing node for video: {video_path.stem}")+ video_reader.release()++ def start(self):+ logger.debug(f"Starting {self.__class__.__name__} for video: {self.video_path.stem}")+ self.worker.start()++ def shutdown(self):+ logger.debug(f"Stopping {self.__class__.__name__} for video: {self.video_path.stem}")+ self.shutdown_self_flag.value = True+ self.worker.join()diff --git a/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/posthoc_calibration_aggregation_node.py b/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/posthoc_calibration_aggregation_node.pynew file mode 100644index 00000000..fe969509--- /dev/null+++ b/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/posthoc_calibration_aggregation_node.py@@ -0,0 +1,183 @@+import logging+import multiprocessing+from dataclasses import dataclass+from pathlib import Path++from pydantic import BaseModel, ConfigDict+from skellycam.core.recorders.videos.recording_info import RecordingInfo+from skellycam.core.types.type_overloads import TopicSubscriptionQueue, CameraIdString++from skellytracker.trackers.base_tracker.base_tracker_abcs import BaseRecorder+from skellytracker.trackers.charuco_tracker.charuco_observation import CharucoObservation++from freemocap.core.pipeline.pipeline_configs import RealtimePipelineConfig+from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.posthoc_calibration_pipeline import \+ CalibrationpipelineConfig+from freemocap.core.pipeline.pipeline_ipc import PipelineIPC+from freemocap.core.pipeline.posthoc_pipelines.posthoc_mocap_pipeline.mocap_helpers.charuco_model_from_observations import \+ charuco_model_from_observations+from freemocap.core.pipeline.posthoc_pipelines.video_helper import VideoMetadata+from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.charuco_observation_aggregator import \+ anipose_calibration_from_charuco_observations, get_last_successful_calibration_toml_path++from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.shared_view_accumulator import CharucoObservations+from freemocap.core.types.type_overloads import PipelineIdString, FrameNumberInt, VideoIdString+from freemocap.pubsub.pubsub_topics import VideoNodeOutputMessage, VideoNodeOutputTopic+from freemocap.utilities.wait_functions import wait_1ms++logger = logging.getLogger(__name__)+++class PosthocAgregationNodeState(BaseModel):+ model_config = ConfigDict(+ validate_assignment=True,+ frozen=True+ )+ pipeline_id: PipelineIdString+ config: RealtimePipelineConfig+ alive: bool+ last_seen_frame_number: int | None = None+ calibration_task_state: object | None = None+ mocap_task_state: object = None # TODO - this+++@dataclass+class PosthocCalibrationAggregationNode:+ shutdown_self_flag: multiprocessing.Value+ worker: multiprocessing.Process++ @classmethod+ def create(cls,+ calibration_pipeline_config: CalibrationpipelineConfig,+ video_metadata: dict[VideoIdString, VideoMetadata],+ pipeline_id: PipelineIdString,+ recording_info: RecordingInfo,+ subprocess_registry: list[multiprocessing.Process],+ ipc: PipelineIPC):+ shutdown_self_flag = multiprocessing.Value('b', False)+ worker = multiprocessing.Process(target=cls._run,+ name=f"Pipeline-{pipeline_id}-PosthocAggregationNode",+ kwargs=dict(calibration_pipeline_config=calibration_pipeline_config,+ pipeline_id=pipeline_id,+ recording_info=recording_info,+ video_metadata=video_metadata,+ ipc=ipc,+ shutdown_self_flag=shutdown_self_flag,+ video_node_subscription=ipc.pubsub.topics[+ VideoNodeOutputTopic].get_subscription(),+ ),+ )+ subprocess_registry.append(worker)+ return cls(shutdown_self_flag=shutdown_self_flag,+ worker=worker+ )++ @staticmethod+ def _run(calibration_pipeline_config: CalibrationpipelineConfig,+ recording_info: RecordingInfo,+ pipeline_id: PipelineIdString,+ video_metadata: dict[VideoIdString, VideoMetadata],+ ipc: PipelineIPC,+ shutdown_self_flag: multiprocessing.Value,+ video_node_subscription: TopicSubscriptionQueue,+ ):+ if multiprocessing.parent_process():+ # Configure logging if multiprocessing (i.e. if there is a parent process)+ from freemocap.system.logging_configuration.configure_logging import configure_logging+ from freemocap import LOG_LEVEL+ configure_logging(LOG_LEVEL, ws_queue=ipc.ws_queue)++ start_frame = set(vm.start_frame for vm in video_metadata.values())+ end_frame = set(vm.end_frame for vm in video_metadata.values())+ if len(start_frame) != 1 or len(end_frame) != 1:+ raise ValueError(f"Mismatch in start/end frames across videos in pipeline {pipeline_id}: "+ f"start_frames={start_frame}, end_frames={end_frame}")+ start_frame = start_frame.pop()+ end_frame = end_frame.pop()+ frame_numbers = set(range(start_frame, end_frame))+ video_ids = list(video_metadata.keys())++ logger.debug(f"PosthocCalibrationAggregationNode for pipeline id: '{pipeline_id}' starting main loop")+ try:++ video_outputs_by_frame: dict[FrameNumberInt, dict[VideoIdString, VideoNodeOutputMessage | None]] = {+ frame_number: {video_id: None for video_id in video_ids}+ for frame_number in frame_numbers+ }+ got_all_outputs_by_frame = {frame_number: False for frame_number in frame_numbers}++ if not len(video_outputs_by_frame) == len(frame_numbers):+ raise ValueError(f"Mismatch between video outputs by frame and recording info frame count - "+ f"{len(video_outputs_by_frame)} vs {len(frame_numbers)}")++ while not shutdown_self_flag.value and ipc.should_continue:+ wait_1ms()+ if not video_node_subscription.empty():+ video_node_output_message: VideoNodeOutputMessage = video_node_subscription.get()++ if not video_node_output_message.video_id in video_ids:+ raise ValueError(+ f"Video ID {video_node_output_message.video_id} not in recording info for pipeline {pipeline_id} - {recording_info.recording_name}")+ video_outputs_by_frame[video_node_output_message.frame_number][+ video_node_output_message.video_id] = video_node_output_message+ if all([isinstance(value, VideoNodeOutputMessage) for value in+ video_outputs_by_frame[video_node_output_message.frame_number].values()]):+ logger.info(f"Received all video node outputs for frame {video_node_output_message.frame_number} in pipeline {pipeline_id}")+ got_all_outputs_by_frame[video_node_output_message.frame_number] = True++ if all(list(got_all_outputs_by_frame.values())):+ break+ logger.info(f"All video node outputs received for pipeline {pipeline_id}, starting calibration")+ charuco_observations_by_frame: list[ dict[CameraIdString, CharucoObservation]] = []+ for frame_outputs in video_outputs_by_frame.values():+ if not all([isinstance(output, VideoNodeOutputMessage) for output in frame_outputs.values()]):+ raise ValueError(+ f"Missing video node outputs for frame in pipeline {pipeline_id}: {frame_outputs}")+ charuco_observations_by_frame.append({+ video_id: output.observation+ for video_id, output in frame_outputs.items()+ })+++ calibration_toml_path = anipose_calibration_from_charuco_observations(+ charuco_observations_by_frame=charuco_observations_by_frame,+ calibration_pipeline_config=calibration_pipeline_config,+ recording_info=recording_info,+ video_metadata=video_metadata,+ # use_charuco_as_groundplane=True,+ )+ observation_recorders_by_video = {video_id: BaseRecorder() for video_id in+ charuco_observations_by_frame[0].keys()}+ for frame_number, charuco_observations_by_camera in enumerate(charuco_observations_by_frame):+ if not all(+ [isinstance(output, CharucoObservation) for output in charuco_observations_by_camera.values()]):+ raise ValueError(+ f"Non-CharucoObservation found in frame {frame_number} observations: {charuco_observations_by_camera}")+ for video_id, recorder in observation_recorders_by_video.items():+ recorder.add_observation(observation=charuco_observations_by_camera[video_id])++ charuco_board_model = charuco_model_from_observations(+ observation_recorders=observation_recorders_by_video,+ calibration_toml_path=get_last_successful_calibration_toml_path(),+ output_data_folder=Path(recording_info.full_recording_path) / "output_data",+ )++ logger.success(+ f"Posthoc calibration completed for pipeline {pipeline_id}! Calibration file saved to {recording_info.full_recording_path}")+++ except Exception as e:+ logger.error(f"Exception in PosthocAggregationNode for recording: {recording_info.recording_name}: {e}", exc_info=True)+ ipc.kill_everything()+ raise+ finally:+ logger.debug(f"Shutting down aggregation process for recording: {recording_info.recording_name}")++ def start(self):+ logger.debug(f"Starting PosthocAggregationNode worker")+ self.worker.start()++ def shutdown(self):+ logger.debug(f"Stopping PosthocAggregationNode worker")+ self.shutdown_self_flag.value = True+ self.worker.join()diff --git a/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/posthoc_calibration_pipeline.py b/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/posthoc_calibration_pipeline.pynew file mode 100644index 00000000..88c0ec5f--- /dev/null+++ b/freemocap/core/pipeline/posthoc_pipelines/posthoc_calibration_pipeline/posthoc_calibration_pipeline.py@@ -0,0 +1,120 @@+import logging+import multiprocessing+import uuid++from pydantic import BaseModel, ConfigDict++from freemocap.core.pipeline.pipeline_configs import CalibrationpipelineConfig+from freemocap.core.pipeline.pipeline_ipc import PipelineIPC+from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.posthoc_calibration_aggregation_node import PosthocCalibrationAggregationNode+from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_video_node import VideoNodeState, CalibrationVideoNode+from freemocap.core.pipeline.posthoc_pipelines.video_helper import VideoGroupHelper+from freemocap.core.pipeline.realtime_pipeline.realtime_aggregation_node import RealtimeAggregationNodeState+from freemocap.core.types.type_overloads import PipelineIdString, VideoIdString++from skellycam.core.recorders.videos.recording_info import RecordingInfo++logger = logging.getLogger(__name__)+++class PosthocPipelineState(BaseModel):+ """Serializable representation of a processing pipeline state."""+ model_config = ConfigDict(+ validate_assignment=True,+ frozen=True+ )+ id: PipelineIdString+ video_node_states: dict[VideoIdString, VideoNodeState]+ aggregation_node_state: RealtimeAggregationNodeState+ alive: bool++class PosthocCalibrationProcessingPipeline(BaseModel):+ model_config = ConfigDict(+ arbitrary_types_allowed=True,+ validate_assignment=True,+ extra="forbid",+ )+ id: PipelineIdString+ recording_info:RecordingInfo+ calibration_pipeline_config: CalibrationpipelineConfig+ video_nodes: dict[VideoIdString, CalibrationVideoNode]+ aggregation_node: PosthocCalibrationAggregationNode+ ipc: PipelineIPC+ started: bool = False++ @property+ def alive(self) -> bool:+ return all([video_node.worker.is_alive() for video_node in+ self.video_nodes.values()]) and self.aggregation_node.worker.is_alive()++ @property+ def video_ids(self) -> list[VideoIdString]:+ return list(self.video_nodes.keys())++ @classmethod+ def from_config(cls,+ recording_info:RecordingInfo,+ heartbeat_timestamp: multiprocessing.Value,+ subprocess_registry: list[multiprocessing.Process],+ calibration_pipeline_config: CalibrationpipelineConfig,+ global_kill_flag: multiprocessing.Value,+ ):+ #validate with video_group object+ video_group = VideoGroupHelper.from_recording_path(recording_path=recording_info.full_recording_path)+ pipeline_id = str(uuid.uuid4())[:6]+ ipc = PipelineIPC.create(global_kill_flag=global_kill_flag,+ heartbeat_timestamp=heartbeat_timestamp+ )+ video_nodes = {video_id: CalibrationVideoNode.create(video_id=video_id,+ video_path=video_helper.video_path, #recreate in node worker+ subprocess_registry=subprocess_registry,+ calibration_pipeline_config=calibration_pipeline_config,+ ipc=ipc)+ for video_id, video_helper in video_group.videos.items()}+ aggregation_node = PosthocCalibrationAggregationNode.create(subprocess_registry=subprocess_registry,+ calibration_pipeline_config=calibration_pipeline_config,+ video_metadata=video_group.video_metadata_by_id,+ ipc=ipc,+ recording_info=recording_info,+ pipeline_id=pipeline_id+ )+ video_group.close() # close here, videos reopened in video nodes+ return cls(video_nodes=video_nodes,+ aggregation_node=aggregation_node,+ ipc=ipc,+ calibration_pipeline_config=calibration_pipeline_config,+ id=pipeline_id,+ recording_info=recording_info+ )++ def start(self) -> None:+ self.started = True+ logger.debug(f"Starting Pipeline (id:{self.id} with for recording: {self.recording_info.recording_name}")+ try:+ logger.debug("Starting video nodes...")+ [node.start() for node in self.video_nodes.values()]+ except Exception as e:+ logger.error(f"Failed to start video nodes: {type(e).__name__} - {e}")+ logger.exception(e)+ raise++ try:+ logger.debug("Starting aggregation node...")+ self.aggregation_node.start()+ logger.debug(f"Aggregation node worker started: alive={self.aggregation_node.worker.is_alive()}")+ except Exception as e:+ logger.error(f"Failed to start aggregation node: {type(e).__name__} - {e}")+ logger.exception(e)+ raise+++ logger.info(f"All pipeline workers started successfully")++ def shutdown(self):+ logger.debug(f"Shutting down {self.__class__.__name__}...")++ self.ipc.shutdown_pipeline()+ for video_id, video_node in self.video_nodes.items():+ video_node.shutdown()+ self.aggregation_node.shutdown()+diff --git a/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/anipose_stuff/__init__.py b/freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/__init__.pysimilarity index 100%rename from freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/anipose_stuff/__init__.pyrename to freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/__init__.pydiff --git a/freemocap/old/core_processes/capture_volume_calibration/charuco_stuff/__init__.py b/freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/mocap_helpers/__init__.pysimilarity index 100%rename from freemocap/old/core_processes/capture_volume_calibration/charuco_stuff/__init__.pyrename to freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/mocap_helpers/__init__.pydiff --git a/freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/mocap_helpers/charuco_model_from_observations.py b/freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/mocap_helpers/charuco_model_from_observations.pynew file mode 100644index 00000000..df07de8c--- /dev/null+++ b/freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/mocap_helpers/charuco_model_from_observations.py@@ -0,0 +1,92 @@+import logging+from pathlib import Path++import numpy as np+from skellyforge.post_processing.filters.apply_filter import filter_trajectory+from skellyforge.post_processing.filters.filter_config import FilterConfig+from skellyforge.post_processing.interpolation.apply_interpolation import interpolate_trajectory+from skellyforge.post_processing.interpolation.interpolation_config import InterpolationConfig+from skellyforge.skellymodels.models.tracking_model_info import MediapipeModelInfo, CharucoBoard5x3ModelInfo+from skellyforge.skellymodels.managers.board import Board+from skellyforge.data_models.trajectory_3d import Trajectory3d++from skellytracker.trackers.base_tracker.base_tracker_abcs import BaseRecorder+from skellytracker.trackers.charuco_tracker.charuco_observation import CharucoObservation++from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.freemocap_anipose import \+ AniposeCameraGroup+from freemocap.core.pipeline.posthoc_pipelines.posthoc_mocap_pipeline.mocap_helpers.triangulate_trajectory_array import \+ TriangulationConfig, triangulate_dict+from freemocap.core.types.type_overloads import VideoIdString++logger = logging.getLogger(__name__)+++def charuco_model_from_observations(observation_recorders: dict[VideoIdString, BaseRecorder],+ output_data_folder: Path | str,+ calibration_toml_path: Path | str|None,+ anipose_camera_group: AniposeCameraGroup | None = None,+ triangulation_config: TriangulationConfig | None = None,+ interp_config: InterpolationConfig | None = None,+ filter_config: FilterConfig | None = None,+ ) -> Board:+ if triangulation_config is None:+ triangulation_config = TriangulationConfig()+ if interp_config is None:+ interp_config = InterpolationConfig()+ if filter_config is None:+ filter_config = FilterConfig()++ if anipose_camera_group is not None and calibration_toml_path is not None:+ raise ValueError("Provide either anipose_camera_group or calibration_toml_path, not both.")+ if anipose_camera_group is None and calibration_toml_path is None:+ raise ValueError("Must provide either anipose_camera_group or calibration_toml_path.")+ if calibration_toml_path is not None:+ anipose_camera_group = AniposeCameraGroup.load(str(calibration_toml_path))++ Path(output_data_folder).mkdir(parents=True,+ exist_ok=True)++ data2d_by_video: dict[VideoIdString, np.ndarray] = {}+ if len(observation_recorders) == 0:+ raise ValueError("No observation recorders provided to process.")++ for video_id, recorder in observation_recorders.items():+ if not all([isinstance(observation, CharucoObservation) for observation in recorder.observations]):+ raise TypeError(f"Recorder for video ID {video_id} contains non-Charuco observations.")+ data2d_fr_id_xyc = recorder.to_array.copy()+ logger.info(f"Processing video ID: {video_id} with 2D data shape: {data2d_fr_id_xyc.shape}")+ data2d_by_video[video_id] = data2d_fr_id_xyc[..., :2]+++ raw_trajectory_3d: Trajectory3d = triangulate_dict(+ data2d_fr_mar_xy_by_camera=data2d_by_video,+ camera_group=anipose_camera_group,+ config=triangulation_config,+ )++ interpolated_trajectory_3d: Trajectory3d = interpolate_trajectory(+ trajectory=raw_trajectory_3d,+ config=interp_config+ )++ filtered_trajectory_3d: Trajectory3d = filter_trajectory(+ trajectory=interpolated_trajectory_3d,+ config=filter_config+ )++ charuco_model = Board.from_tracked_points_numpy_array(+ # name/model info are hardcoded - but ideally we'll make a some sort of config that we'll pull from to choose these+ name="charuco_board_5x3",+ model_info=CharucoBoard5x3ModelInfo(),+ tracked_points_numpy_array=filtered_trajectory_3d.triangulated_data,+ )+++ charuco_model.save_out_numpy_data(output_data_folder)+ charuco_model.save_out_csv_data(output_data_folder)+ charuco_model.save_out_all_data_csv(output_data_folder)+ charuco_model.save_out_all_data_parquet(output_data_folder)+ charuco_model.save_out_all_xyz_numpy_data(output_data_folder)++ return charuco_modeldiff --git a/freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/mocap_helpers/skeleton_from_mediapipe_observations.py b/freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/mocap_helpers/skeleton_from_mediapipe_observations.pynew file mode 100644index 00000000..ba39aca4--- /dev/null+++ b/freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/mocap_helpers/skeleton_from_mediapipe_observations.py@@ -0,0 +1,92 @@+import logging+from pathlib import Path++import numpy as np+from skellyforge.data_models.trajectory_3d import Trajectory3d+from skellyforge.post_processing.filters.apply_filter import filter_trajectory+from skellyforge.post_processing.filters.filter_config import FilterConfig+from skellyforge.post_processing.interpolation.apply_interpolation import interpolate_trajectory+from skellyforge.post_processing.interpolation.interpolation_config import InterpolationConfig+from skellyforge.skellymodels.managers.human import Human+from skellyforge.skellymodels.models.tracking_model_info import MediapipeModelInfo+from skellytracker.trackers.base_tracker.base_tracker_abcs import BaseRecorder++from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.freemocap_anipose import \+ AniposeCameraGroup+from freemocap.core.pipeline.posthoc_pipelines.posthoc_mocap_pipeline.mocap_helpers.triangulate_trajectory_array import \+ TriangulationConfig, triangulate_dict+from freemocap.core.types.type_overloads import VideoIdString++logger = logging.getLogger(__name__)++def skeleton_from_mediapipe_observation_recorders(observation_recorders:dict[VideoIdString, BaseRecorder],+ path_to_calibration_toml: Path | str,+ path_to_output_data_folder: Path | str,+ triangulation_config: TriangulationConfig|None = None,+ interp_config: InterpolationConfig|None = None,+ filter_config: FilterConfig|None = None,+ ) -> Human:++ if triangulation_config is None:+ triangulation_config = TriangulationConfig()+ if interp_config is None:+ interp_config = InterpolationConfig()+ if filter_config is None:+ filter_config = FilterConfig()++ Path(path_to_output_data_folder).mkdir(parents=True,+ exist_ok=True)++ data2d_by_video: dict[VideoIdString, np.ndarray] = {}+ if len(observation_recorders) == 0:+ raise ValueError("No observation recorders provided to process.")++ for video_id, recorder in observation_recorders.items():+ data2d_fr_id_xyc = recorder.to_array.copy()+ logger.info(f"Processing video ID: {video_id} with 2D data shape: {data2d_fr_id_xyc.shape}")+ data2d_by_video[video_id] = data2d_fr_id_xyc[..., :2]++ camera_group=AniposeCameraGroup.load(str(path_to_calibration_toml))++ raw_trajectory_3d: Trajectory3d = triangulate_dict(+ data2d_fr_mar_xy_by_camera=data2d_by_video,+ camera_group=camera_group,+ config=triangulation_config,+ )++ interpolated_trajectory_3d: Trajectory3d = interpolate_trajectory(+ trajectory=raw_trajectory_3d,+ config=interp_config+ )++ filtered_trajectory_3d: Trajectory3d = filter_trajectory(+ trajectory=interpolated_trajectory_3d,+ config=filter_config+ )++ skeleton: Human = Human.from_tracked_points_numpy_array(+ # name/model info are hardcoded - but ideally we'll make a some sort of config that we'll pull from to choose these+ name="human",+ model_info=MediapipeModelInfo(),+ tracked_points_numpy_array=filtered_trajectory_3d.triangulated_data,+ )++ try:+ skeleton.put_skeleton_on_ground()+ except Exception as e:+ logger.warning(f"Could not put skeleton on ground: {e}")++ try:+ skeleton.fix_hands_to_wrist()+ except Exception as e:+ logger.warning(f"Could not fix hands to wrist: {e}")++ skeleton.calculate()++ skeleton.save_out_numpy_data(path_to_output_data_folder)+ skeleton.save_out_csv_data(path_to_output_data_folder)+ skeleton.save_out_all_data_csv(path_to_output_data_folder)+ skeleton.save_out_all_data_parquet(path_to_output_data_folder)+ skeleton.save_out_all_xyz_numpy_data(path_to_output_data_folder)++ return skeletondiff --git a/freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/mocap_helpers/triangulate_trajectory_array.py b/freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/mocap_helpers/triangulate_trajectory_array.pynew file mode 100644index 00000000..e2c5e94f--- /dev/null+++ b/freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/mocap_helpers/triangulate_trajectory_array.py@@ -0,0 +1,261 @@+import logging+from typing import Any++import numpy as np+from pydantic import BaseModel+from skellyforge.data_models.trajectory_3d import Observation3d, Trajectory3d+from skellyforge.data_models.type_overloads import CameraIdString, FrameObservationsByCamera, Trajectory2dGroup++from skellytracker.trackers.base_tracker.base_tracker_abcs import BaseObservation+from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.freemocap_anipose import \+ AniposeCameraGroup++logger = logging.getLogger(__name__)+++class TriangulationConfig(BaseModel):+ use_ransac: bool = False+++def triangulate_array(+ data2d_cam_id_xy: np.ndarray, # shape: cameras ร frames ร points ร 2+ camera_group: AniposeCameraGroup,+ config: TriangulationConfig,+ calculate_reprojection_error: bool = False,+) -> tuple[np.ndarray, np.ndarray, np.ndarray]:+ number_of_cameras = data2d_cam_id_xy.shape[0]+ number_of_frames = data2d_cam_id_xy.shape[1]+ number_of_tracked_points = data2d_cam_id_xy.shape[2]+ number_of_spatial_dimensions = data2d_cam_id_xy.shape[3]++ if number_of_spatial_dimensions == 3:+ # if provided 3d, ignore z dimension+ data2d_cam_id_xy = data2d_cam_id_xy[..., :2]++ data2d_flat = data2d_cam_id_xy.reshape(number_of_cameras, -1, 2)+++ # Triangulate 2D points to 3D+ if config.use_ransac:+ logger.info("Using RANSAC triangulation method")+ triangulated_data_flat = camera_group.triangulate_ransac(+ data2d_flat, progress=True, kill_event=None+ )+ else:+ triangulated_data_flat = camera_group.triangulate(+ data2d_flat, progress=False, kill_event=None+ )++ if triangulated_data_flat is None:+ raise ValueError("Triangulation stopped due to kill event")++ # Reshape to frames ร points ร xyz+ triangulated3d_fr_id_xyz = triangulated_data_flat.reshape(+ number_of_frames, number_of_tracked_points, 3+ )++ if not calculate_reprojection_error:+ return triangulated3d_fr_id_xyz, np.array([]), np.array([])+ # Calculate reprojection errors+ reprojection_error_full = camera_group.reprojection_error(+ triangulated_data_flat, data2d_flat+ )+ reprojection_error_flat = camera_group.calculate_mean_reprojection_error(+ reprojection_error_full+ )++ # Reshape reprojection errors+ reprojection_error_by_camera = np.linalg.norm(+ reprojection_error_full, axis=2+ ).reshape(number_of_cameras, number_of_frames, number_of_tracked_points)+ reprojection_error = reprojection_error_flat.reshape(+ number_of_frames, number_of_tracked_points+ )++ return triangulated3d_fr_id_xyz, reprojection_error, reprojection_error_by_camera+++def triangulate_frame_observations(frame_number: int,+ frame_observations_by_camera: FrameObservationsByCamera,+ anipose_camera_group: AniposeCameraGroup,+ config: TriangulationConfig=TriangulationConfig(),+ calculate_reprojection_error: bool = False+ ) -> Observation3d:+ anipose_camera_group = subset_camera_names(data_dict=frame_observations_by_camera, anipose_camera_group=anipose_camera_group)++ ordered_frame_observations = preserve_camera_group_order(data_by_camera=frame_observations_by_camera,+ camera_group=anipose_camera_group)++ if not all([isinstance(obs, BaseObservation) for obs in ordered_frame_observations.values()]):+ raise TypeError("All values in frame_observations_by_camera must be BaseObservation instances")+ data2d_stack_list = [obs.to_2d_array() for obs in ordered_frame_observations.values()]+ if not len(set(data.shape for data in data2d_stack_list)) == 1:+ raise ValueError(f"2d data from each camera must be the same shape- got: {[data.shape for data in data2d_stack_list]}")+ data2d_cam_id_xy = np.stack(data2d_stack_list, axis=0)++ if len(frame_observations_by_camera) != data2d_cam_id_xy.shape[0]:+ logger.error(+ f"Expected {len(frame_observations_by_camera)} cameras but got {data2d_cam_id_xy.shape[0]} cameras"+ )+ raise ValueError(+ "Input data must have the same number of cameras as the camera group"+ )+ # add singleton frame dimension+ data2d_cam_fr_id_xyz = data2d_cam_id_xy.reshape((data2d_cam_id_xy.shape[0], 1, data2d_cam_id_xy.shape[1], data2d_cam_id_xy.shape[2]))+ triangulated_data, _, _ = triangulate_array(+ data2d_cam_id_xy=data2d_cam_fr_id_xyz,+ camera_group=anipose_camera_group,+ config=config,+ calculate_reprojection_error=calculate_reprojection_error,+ )+ return Observation3d(+ frame_number=frame_number,+ triangulated_data=np.squeeze(triangulated_data),+ names=list(frame_observations_by_camera.values())[0].to_tracked_points().keys(),+ # reprojection_error=reprojection_error,+ # reprojection_error_by_camera=reprojection_error_by_camera,+ )+++def triangulate_frame_groups(+ frame_groups: dict[int, FrameObservationsByCamera],+ camera_group: AniposeCameraGroup,+ config: TriangulationConfig,+) -> Trajectory3d:+ observations_3d = []+ frame_groups = dict(sorted(frame_groups.items()))+ for frame_number, frame_group in frame_groups.items():+ observations_3d.append(triangulate_frame_observations(+ frame_number, frame_group, camera_group, config+ ))+ return Trajectory3d.from_observations(list(frame_groups.values()))+++def triangulate_trajectories(+ trajectory_group: Trajectory2dGroup,+ camera_group: AniposeCameraGroup,+ config: TriangulationConfig,+):+ # TODO: move this validation into Trajectory2dGroup creation+ if len(set(trajectory.start_frame for trajectory in trajectory_group.values())) != 1:+ raise ValueError(+ "Input data must have the same start frame for all trajectories"+ )+ if len(set(trajectory.end_frame for trajectory in trajectory_group.values())) != 1:+ raise ValueError(+ "Input data must have the same end frame for all trajectories"+ )+ camera_group = subset_camera_names(data_dict=trajectory_group, anipose_camera_group=camera_group)+ ordered_trajectory_group = preserve_camera_group_order(data_by_camera=trajectory_group, camera_group=camera_group)++ data_2d = np.stack(+ [trajectory.points2d for trajectory in ordered_trajectory_group.values()],+ axis=0+ )++ if len(trajectory_group) != data_2d.shape[0]:+ logger.error(+ f"Expected {len(trajectory_group)} cameras but got {data_2d.shape[0]} cameras"+ )+ raise ValueError(+ "Input data must have the same number of cameras as the camera group"+ )++ triangulated_data, reprojection_error, reprojection_error_by_camera = triangulate_array(+ data_2d, camera_group, config+ )++ start_frame = list(trajectory_group.values())[0].start_frame+ end_frame = list(trajectory_group.values())[0].end_frame++ return Trajectory3d(+ start_frame=start_frame,+ end_frame=end_frame,+ triangulated_data=triangulated_data,+ reprojection_error=reprojection_error,+ reprojection_error_by_camera=reprojection_error_by_camera,+ )+++def triangulate_dict(+ data2d_fr_mar_xy_by_camera: dict[CameraIdString, np.ndarray],+ camera_group: AniposeCameraGroup,+ config: TriangulationConfig = TriangulationConfig(),+ start_frame: int | None = None,+ end_frame: int | None = None,+) -> Trajectory3d:+ camera_group = subset_camera_names(+ data_dict=data2d_fr_mar_xy_by_camera, anipose_camera_group=camera_group+ )++ ordered_data_dict:dict[CameraIdString,object] = preserve_camera_group_order(data_by_camera=data2d_fr_mar_xy_by_camera, camera_group=camera_group)+ stacked_2d_data_list = []+ for camera_id, data2d_fr_mar_xy in ordered_data_dict.items():+ if any([not isinstance(data2d_fr_mar_xy, np.ndarray) for data2d_fr_mar_xy in ordered_data_dict.values()]):+ raise TypeError("All values in data2d_fr_mar_xy_by_camera must be numpy arrays")+ if len(data2d_fr_mar_xy.shape) != 3:+ logger.error(+ f"Expected 3D array for camera {camera_id} but got array with shape {data2d_fr_mar_xy.shape}"+ )+ raise ValueError(+ "Input data arrays must have shape (frames, markers, 2)"+ )+ if data2d_fr_mar_xy.shape[2] != 2:+ logger.error(+ f"Expected last dimension of size 2 for camera {camera_id} but got size {data2d_fr_mar_xy.shape[2]}"+ )+ raise ValueError(+ "Input data arrays must have shape (frames, markers, 2)"+ )+ stacked_2d_data_list.append(data2d_fr_mar_xy)++ data2d_camera_fr_mar_xy = np.stack(stacked_2d_data_list,axis=0)+ logger.info(f"shape of combined_2d_data: {data2d_camera_fr_mar_xy.shape}")++ triangulated_data, reprojection_error, reprojection_error_by_camera = triangulate_array(+ data2d_camera_fr_mar_xy, camera_group, config+ )+ if start_frame is None:+ start_frame = 0+ if end_frame is None:+ end_frame = data2d_camera_fr_mar_xy.shape[1]+ return Trajectory3d(+ start_frame=start_frame,+ end_frame=end_frame,+ triangulated_data=triangulated_data,+ reprojection_error=reprojection_error,+ reprojection_error_by_camera=reprojection_error_by_camera,+ )+++def subset_camera_names(data_dict: dict[CameraIdString, Any], anipose_camera_group: AniposeCameraGroup)->AniposeCameraGroup:+ valid_calibration_names = []+ for camera in anipose_camera_group.cameras:+ for key in data_dict.keys():+ if camera.name in key:+ valid_calibration_names.append(camera.name)+ break+ if len(valid_calibration_names) != len(data_dict.keys()):+ raise ValueError(+ "Camera names in frame group do not match camera names in camera group. Make sure calibration matches input data."+ )+ if len(valid_calibration_names) == len(anipose_camera_group.cameras):+ return anipose_camera_group+ logger.warning(+ f"Frame group is missing cameras from camera group, triangulating with only cameras in frame group: {valid_calibration_names}"+ )+ return anipose_camera_group.subset_cameras_names(valid_calibration_names)+++def preserve_camera_group_order(data_by_camera: dict[CameraIdString, object], camera_group: AniposeCameraGroup) -> dict[+ CameraIdString, object]:+ ordered_data_dict = {}++ for camera in camera_group.cameras:+ for camrea_id, data in data_by_camera.items():+ if camera.name in camrea_id:+ ordered_data_dict[camrea_id] = data+ break+++ return ordered_data_dictdiff --git a/freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/mocap_video_node.py b/freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/mocap_video_node.pynew file mode 100644index 00000000..8d2a5df4--- /dev/null+++ b/freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/mocap_video_node.py@@ -0,0 +1,103 @@+import logging+import multiprocessing+from dataclasses import dataclass+from pathlib import Path+import cv2++from skellycam.core.types.type_overloads import WorkerType+from skellytracker.trackers.mediapipe_tracker.mediapipe_detector import MediapipeDetector++from freemocap.core.pipeline.pipeline_ipc import PipelineIPC+from freemocap.core.pipeline.posthoc_pipelines.posthoc_mocap_pipeline.posthoc_mocap_pipeline import \+ MocapPipelineTaskConfig++from freemocap.core.types.type_overloads import VideoIdString+from freemocap.pubsub.pubsub_topics import VideoNodeOutputTopic, VideoNodeOutputMessage++logger = logging.getLogger(__name__)+++@dataclass+class MocapVideoNode:+ video_id: VideoIdString+ video_path: Path+ mocap_task_config: MocapPipelineTaskConfig+ shutdown_self_flag: multiprocessing.Value+ worker: WorkerType++ @classmethod+ def create(cls,+ video_id: VideoIdString,+ video_path: Path,+ subprocess_registry: list[multiprocessing.Process],+ mocap_task_config: MocapPipelineTaskConfig,+ ipc: PipelineIPC):+ shutdown_self_flag = multiprocessing.Value('b', False)+ worker = multiprocessing.Process(target=cls._run,+ name=f"VideoProcessingNode-{video_path.stem}",+ kwargs=dict(+ video_id=video_id,+ video_path=video_path,+ ipc=ipc,+ mocap_task_config=mocap_task_config,+ shutdown_self_flag=shutdown_self_flag,+ ),+ )+ subprocess_registry.append(worker)+ return cls(video_id=video_id,+ video_path=video_path,+ shutdown_self_flag=shutdown_self_flag,+ mocap_task_config=mocap_task_config,+ worker=worker+ )++ @staticmethod+ def _run(video_id: VideoIdString,+ video_path: Path,+ ipc: PipelineIPC,+ mocap_task_config: MocapPipelineTaskConfig,+ shutdown_self_flag: multiprocessing.Value,+ ):+ if multiprocessing.parent_process():+ # Configure logging if multiprocessing (i.e. if there is a parent process)+ from freemocap.system.logging_configuration.configure_logging import configure_logging+ from freemocap import LOG_LEVEL+ configure_logging(LOG_LEVEL, ws_queue=ipc.ws_queue)++ video_reader = cv2.VideoCapture(str(video_path))+ success, image = video_reader.read()+ frame_number = 0+ logger.info(f"Starting video processing node for video: {video_path.stem}")+ mediapipe_detector = MediapipeDetector.create(config=mocap_task_config.detector_config)+ try:+ while success and not shutdown_self_flag.value and ipc.should_continue:+ mediapipe_observation = mediapipe_detector.detect(+ frame_number=frame_number,+ image=image)++ ipc.pubsub.publish(+ topic_type=VideoNodeOutputTopic,+ message=VideoNodeOutputMessage(+ video_id=video_id,+ frame_number=frame_number,+ observation=mediapipe_observation,+ ),+ )+ success, image = video_reader.read()+ frame_number+=1++ except Exception as e:+ logger.exception(f"Exception in video node for video: {video_path.stem} - {e}")+ ipc.kill_everything()+ raise e+ finally:+ logger.debug(f"Shutting down video processing node for video: {video_path.stem}")+ video_reader.release()+ def start(self):+ logger.debug(f"Starting {self.__class__.__name__} for video: {self.video_path.stem}")+ self.worker.start()++ def shutdown(self):+ logger.debug(f"Stopping {self.__class__.__name__} for video: {self.video_path.stem}")+ self.shutdown_self_flag.value = True+ self.worker.join()diff --git a/freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/posthoc_mocap_aggregation_node.py b/freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/posthoc_mocap_aggregation_node.pynew file mode 100644index 00000000..306848c0--- /dev/null+++ b/freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/posthoc_mocap_aggregation_node.py@@ -0,0 +1,167 @@+import logging+import multiprocessing+from dataclasses import dataclass+from pathlib import Path++from pydantic import BaseModel, ConfigDict++from skellycam.core.recorders.videos.recording_info import RecordingInfo+from skellycam.core.types.type_overloads import TopicSubscriptionQueue++from skellytracker.trackers.mediapipe_tracker.mediapipe_observation import MediapipeObservation+from skellytracker.trackers.base_tracker.base_tracker_abcs import BaseRecorder++from freemocap.core.pipeline.pipeline_configs import RealtimePipelineConfig+from freemocap.core.pipeline.pipeline_ipc import PipelineIPC+from freemocap.core.pipeline.posthoc_pipelines.posthoc_mocap_pipeline.posthoc_mocap_pipeline import \+ MocapPipelineTaskConfig+from freemocap.core.pipeline.posthoc_pipelines.posthoc_mocap_pipeline.mocap_helpers.skeleton_from_mediapipe_observations import \+ skeleton_from_mediapipe_observation_recorders+from freemocap.core.pipeline.posthoc_pipelines.video_helper import VideoMetadata+from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.charuco_observation_aggregator import \+ get_last_successful_calibration_toml_path+from freemocap.core.types.type_overloads import PipelineIdString, FrameNumberInt, VideoIdString+from freemocap.pubsub.pubsub_topics import VideoNodeOutputMessage, VideoNodeOutputTopic+from freemocap.utilities.wait_functions import wait_1ms++logger = logging.getLogger(__name__)++MediapipeObservations = dict[VideoIdString, MediapipeObservation]+++class PosthocAgregationNodeState(BaseModel):+ model_config = ConfigDict(+ validate_assignment=True,+ frozen=True+ )+ pipeline_id: PipelineIdString+ config: RealtimePipelineConfig+ alive: bool+ last_seen_frame_number: int | None = None+ mocap_task_state: object | None = None+ mocap_task_state: object = None # TODO - this+++@dataclass+class PosthocMocapAggregationNode:+ shutdown_self_flag: multiprocessing.Value+ worker: multiprocessing.Process++ @classmethod+ def create(cls,+ mocap_task_config: MocapPipelineTaskConfig,+ video_metadata: dict[VideoIdString, VideoMetadata],+ pipeline_id: PipelineIdString,+ recording_info: RecordingInfo,+ subprocess_registry: list[multiprocessing.Process],+ ipc: PipelineIPC):+ shutdown_self_flag = multiprocessing.Value('b', False)+ worker = multiprocessing.Process(target=cls._run,+ name=f"Pipeline-{pipeline_id}-PosthocAggregationNode",+ kwargs=dict(mocap_task_config=mocap_task_config,+ pipeline_id=pipeline_id,+ recording_info=recording_info,+ video_metadata=video_metadata,+ ipc=ipc,+ shutdown_self_flag=shutdown_self_flag,+ video_node_subscription=ipc.pubsub.topics[+ VideoNodeOutputTopic].get_subscription(),+ ),+ )+ subprocess_registry.append(worker)+ return cls(shutdown_self_flag=shutdown_self_flag,+ worker=worker+ )++ @staticmethod+ def _run(mocap_task_config: MocapPipelineTaskConfig,+ recording_info: RecordingInfo,+ pipeline_id: PipelineIdString,+ video_metadata: dict[VideoIdString, VideoMetadata],+ ipc: PipelineIPC,+ shutdown_self_flag: multiprocessing.Value,+ video_node_subscription: TopicSubscriptionQueue,+ ):+ if multiprocessing.parent_process():+ # Configure logging if multiprocessing (i.e. if there is a parent process)+ from freemocap.system.logging_configuration.configure_logging import configure_logging+ from freemocap import LOG_LEVEL+ configure_logging(LOG_LEVEL, ws_queue=ipc.ws_queue)++ start_frame = set(vm.start_frame for vm in video_metadata.values())+ end_frame = set(vm.end_frame for vm in video_metadata.values())+ if len(start_frame) != 1 or len(end_frame) != 1:+ raise ValueError(f"Mismatch in start/end frames across videos in pipeline {pipeline_id}: "+ f"start_frames={start_frame}, end_frames={end_frame}")+ start_frame = start_frame.pop()+ end_frame = end_frame.pop()+ frame_numbers = set(range(start_frame, end_frame))+ video_ids = list(video_metadata.keys())++ logger.debug(f"PosthocMocapAggregationNode for pipeline id: '{pipeline_id}' starting main loop")+ try:++ video_outputs_by_frame: dict[FrameNumberInt, dict[VideoIdString, VideoNodeOutputMessage | None]] = {+ frame_number: {video_id: None for video_id in video_ids}+ for frame_number in frame_numbers+ }+ got_all_outputs_by_frame = {frame_number: False for frame_number in frame_numbers}++ if not len(video_outputs_by_frame) == len(frame_numbers):+ raise ValueError(f"Mismatch between video outputs by frame and recording info frame count - "+ f"{len(video_outputs_by_frame)} vs {len(frame_numbers)}")++ while not shutdown_self_flag.value and ipc.should_continue:+ wait_1ms()+ if not video_node_subscription.empty():+ video_node_output_message: VideoNodeOutputMessage = video_node_subscription.get()++ if not video_node_output_message.video_id in video_ids:+ raise ValueError(+ f"Video ID {video_node_output_message.video_id} not in recording info for pipeline {pipeline_id} - {recording_info.recording_name}")+ video_outputs_by_frame[video_node_output_message.frame_number][+ video_node_output_message.video_id] = video_node_output_message+ if all([isinstance(value, VideoNodeOutputMessage) for value in+ video_outputs_by_frame[video_node_output_message.frame_number].values()]):+ logger.info(+ f"Received all video node outputs for frame {video_node_output_message.frame_number} in pipeline {pipeline_id}")+ got_all_outputs_by_frame[video_node_output_message.frame_number] = True++ if all(list(got_all_outputs_by_frame.values())):+ break+ logger.info(f"All video node outputs received for pipeline {pipeline_id}, starting calibration")+ observation_recorders_by_video = {video_id: BaseRecorder() for video_id in video_ids}+ for frame_number, frame_outputs_by_video in video_outputs_by_frame.items():+ if not all([isinstance(output, VideoNodeOutputMessage) for output in frame_outputs_by_video.values()]):+ raise ValueError(+ f"Missing video node outputs for frame in pipeline {pipeline_id}: {frame_number}")+ for video_id, recorder in observation_recorders_by_video.items():+ observation = frame_outputs_by_video[video_id].observation+ recorder.add_observation(observation=observation)++ skeleton = skeleton_from_mediapipe_observation_recorders(+ observation_recorders=observation_recorders_by_video,+ path_to_calibration_toml= get_last_successful_calibration_toml_path(),+ path_to_output_data_folder=Path(recording_info.full_recording_path)/'output_data',+ )++ logger.success(+ f"Posthoc calibration completed for pipeline {pipeline_id}! Mocap file saved to {recording_info.full_recording_path}")+++ except Exception as e:+ logger.error(f"Exception in PosthocAggregationNode for recording: {recording_info.recording_name}: {e}",+ exc_info=True)+ ipc.kill_everything()+ raise+ finally:+ logger.debug(f"Shutting down aggregation process for recording: {recording_info.recording_name}")++ def start(self):+ logger.debug(f"Starting PosthocAggregationNode worker")+ self.worker.start()++ def shutdown(self):+ logger.debug(f"Stopping PosthocAggregationNode worker")+ self.shutdown_self_flag.value = True+ self.worker.join()diff --git a/freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/posthoc_mocap_pipeline.py b/freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/posthoc_mocap_pipeline.pynew file mode 100644index 00000000..d2f582a4--- /dev/null+++ b/freemocap/core/pipeline/posthoc_pipelines/posthoc_mocap_pipeline/posthoc_mocap_pipeline.py@@ -0,0 +1,106 @@+import logging+import multiprocessing+import uuid++from pydantic import BaseModel, ConfigDict+from skellycam.core.recorders.videos.recording_info import RecordingInfo++from freemocap.core.pipeline.pipeline_configs import MocapPipelineTaskConfig+from freemocap.core.pipeline.pipeline_ipc import PipelineIPC+from freemocap.core.pipeline.posthoc_pipelines.posthoc_mocap_pipeline.mocap_video_node import MocapVideoNode+from freemocap.core.pipeline.posthoc_pipelines.posthoc_mocap_pipeline.posthoc_mocap_aggregation_node import \+ PosthocMocapAggregationNode+from freemocap.core.pipeline.posthoc_pipelines.video_helper import VideoGroupHelper+from freemocap.core.types.type_overloads import PipelineIdString, VideoIdString++logger = logging.getLogger(__name__)+++class PosthocMocapProcessingPipeline(BaseModel):+ model_config = ConfigDict(+ arbitrary_types_allowed=True,+ validate_assignment=True,+ extra="forbid",+ )+ id: PipelineIdString+ recording_info: RecordingInfo+ mocap_task_config: MocapPipelineTaskConfig+ video_nodes: dict[VideoIdString, MocapVideoNode]+ aggregation_node: PosthocMocapAggregationNode+ ipc: PipelineIPC+ started: bool = False++ @property+ def alive(self) -> bool:+ return all([video_node.worker.is_alive() for video_node in+ self.video_nodes.values()]) and self.aggregation_node.worker.is_alive()++ @property+ def video_ids(self) -> list[VideoIdString]:+ return list(self.video_nodes.keys())++ @classmethod+ def from_task_config(cls,+ recording_info: RecordingInfo,+ heartbeat_timestamp: multiprocessing.Value,+ subprocess_registry: list[multiprocessing.Process],+ mocap_task_config: MocapPipelineTaskConfig,+ global_kill_flag: multiprocessing.Value,+ ):+ # validate by creating video_group object+ video_group = VideoGroupHelper.from_recording_path(recording_path=recording_info.full_recording_path)+ pipeline_id = str(uuid.uuid4())[:6]+ ipc = PipelineIPC.create(global_kill_flag=global_kill_flag,+ heartbeat_timestamp=heartbeat_timestamp+ )+ video_nodes = {video_id: MocapVideoNode.create(video_id=video_id,+ video_path=video_helper.video_path, # recreate in node worker+ subprocess_registry=subprocess_registry,+ mocap_task_config=mocap_task_config,+ ipc=ipc)+ for video_id, video_helper in video_group.videos.items()}+ aggregation_node = PosthocMocapAggregationNode.create(subprocess_registry=subprocess_registry,+ mocap_task_config=mocap_task_config,+ video_metadata=video_group.video_metadata_by_id,+ ipc=ipc,+ recording_info=recording_info,+ pipeline_id=pipeline_id+ )+ video_group.close() # close here, videos reopened in video nodes+ return cls(video_nodes=video_nodes,+ aggregation_node=aggregation_node,+ ipc=ipc,+ mocap_task_config=mocap_task_config,+ id=pipeline_id,+ recording_info=recording_info+ )++ def start(self) -> None:+ self.started = True+ logger.debug(f"Starting Pipeline (id:{self.id} with for recording: {self.recording_info.recording_name}")+ try:+ logger.debug("Starting video nodes...")+ [node.start() for node in self.video_nodes.values()]+ except Exception as e:+ logger.error(f"Failed to start video nodes: {type(e).__name__} - {e}")+ logger.exception(e)+ raise++ try:+ logger.debug("Starting aggregation node...")+ self.aggregation_node.start()+ logger.debug(f"Aggregation node worker started: alive={self.aggregation_node.worker.is_alive()}")+ except Exception as e:+ logger.error(f"Failed to start aggregation node: {type(e).__name__} - {e}")+ logger.exception(e)+ raise++ logger.info(f"All pipeline workers started successfully")++ def shutdown(self):+ logger.debug(f"Shutting down {self.__class__.__name__}...")++ self.ipc.shutdown_pipeline()+ for video_id, video_node in self.video_nodes.items():+ video_node.shutdown()+ self.aggregation_node.shutdown()diff --git a/freemocap/core/pipeline/posthoc_pipelines/posthoc_pipeline_manager.py b/freemocap/core/pipeline/posthoc_pipelines/posthoc_pipeline_manager.pynew file mode 100644index 00000000..f53230cb--- /dev/null+++ b/freemocap/core/pipeline/posthoc_pipelines/posthoc_pipeline_manager.py@@ -0,0 +1,69 @@+import logging+import multiprocessing+from dataclasses import dataclass, field++from fastapi import FastAPI+from skellycam.core.recorders.videos.recording_info import RecordingInfo++from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.posthoc_calibration_pipeline import \+ CalibrationpipelineConfig, PosthocCalibrationProcessingPipeline+from freemocap.core.pipeline.posthoc_pipelines.posthoc_mocap_pipeline.posthoc_mocap_pipeline import MocapPipelineTaskConfig, \+ PosthocMocapProcessingPipeline+from freemocap.core.types.type_overloads import PipelineIdString++logger = logging.getLogger(__name__)+++@dataclass+class PosthocPipelineManager:+ global_kill_flag: multiprocessing.Value+ heartbeat_timestamp: multiprocessing.Value+ subprocess_registry: list[multiprocessing.Process]+ lock: multiprocessing.Lock = field(default_factory=multiprocessing.Lock)+ posthoc_pipelines: dict[PipelineIdString, PosthocCalibrationProcessingPipeline|PosthocMocapProcessingPipeline] = field(default_factory=dict)++ @classmethod+ def from_fastapi_app(cls, fastapi_app: FastAPI):+ return cls(global_kill_flag=fastapi_app.state.global_kill_flag,+ heartbeat_timestamp=fastapi_app.state.heartbeat_timestamp,+ subprocess_registry=fastapi_app.state.subprocess_registry)++ async def create_posthoc_calibration_pipeline(self,+ recording_info: RecordingInfo,+ calibration_pipeline_config: CalibrationpipelineConfig) -> PosthocCalibrationProcessingPipeline:+ with self.lock:+ pipeline = PosthocCalibrationProcessingPipeline.from_config(+ calibration_pipeline_config=calibration_pipeline_config,+ recording_info=recording_info,+ heartbeat_timestamp=self.heartbeat_timestamp,+ subprocess_registry=self.subprocess_registry,+ global_kill_flag=self.global_kill_flag,+ )+ pipeline.start()+ self.posthoc_pipelines[pipeline.id] = pipeline+ logger.info(+ f"Post-hoc pipeline with ID: {pipeline.id} for recording '{recording_info.recording_name}' created successfully")+ return pipeline++ async def create_posthoc_mocap_pipeline(self, recording_info:RecordingInfo, mocap_task_config:MocapPipelineTaskConfig):+ with self.lock:+ pipeline = PosthocMocapProcessingPipeline.from_task_config(+ mocap_task_config=mocap_task_config,+ recording_info=recording_info,+ heartbeat_timestamp=self.heartbeat_timestamp,+ subprocess_registry=self.subprocess_registry,+ global_kill_flag=self.global_kill_flag,+ )+ pipeline.start()+ self.posthoc_pipelines[pipeline.id] = pipeline+ logger.info(+ f"Post-hoc pipeline with ID: {pipeline.id} for recording '{recording_info.recording_name}' created successfully")+ return pipeline++ def close_all_posthoc_pipelines(self):+ with self.lock:+ for pipeline in self.posthoc_pipelines.values():+ pipeline.shutdown()+ self.posthoc_pipelines.clear()+ logger.info("All pipelines closed successfully")+diff --git a/freemocap/core/pipeline/posthoc_pipelines/video_helper.py b/freemocap/core/pipeline/posthoc_pipelines/video_helper.pynew file mode 100644index 00000000..c39a1b34--- /dev/null+++ b/freemocap/core/pipeline/posthoc_pipelines/video_helper.py@@ -0,0 +1,403 @@+"""+Simplified VideoHelper with OpenCV best practices.+Includes smart frame reading and caching.+"""++from pathlib import Path+from collections import OrderedDict+import cv2+import numpy as np+from pydantic import BaseModel, Field, ConfigDict, model_validator++from freemocap.core.types.type_overloads import VideoIdString++# Module level constants+DEFAULT_CACHE_SIZE_MB = 500+SEQUENTIAL_READ_THRESHOLD = 5 # If reading within 5 frames ahead, use sequential+++class VideoMetadata(BaseModel):+ """Video metadata container"""+ width: int+ height: int+ fps: float+ frame_count: int+ fourcc: str+ duration_seconds: float+ start_frame: int = 0+ end_frame: int++ @model_validator(mode="before")+ def validate_frames(cls, values):+ start_frame = values.get("start_frame", 0)+ values["end_frame"] = values.get("end_frame", values.get("frame_count"))+ end_frame = values["end_frame"]+ frame_count = end_frame - start_frame if end_frame is not None else values.get("frame_count")+ if end_frame is not None:+ if not (0 <= start_frame < end_frame <= frame_count):+ raise ValueError(f"Invalid start_frame or end_frame values: start_frame={start_frame}, end_frame={end_frame}, frame_count={frame_count}")+ if not (end_frame - start_frame) == frame_count:+ raise ValueError(f"Subset frame count does not match frame_count: {end_frame - start_frame} != {frame_count}")++ return values++++class FrameCache(BaseModel):+ """LRU cache for video frames with memory management"""++ model_config = ConfigDict(arbitrary_types_allowed=True)++ max_size_mb: int = DEFAULT_CACHE_SIZE_MB+ frame_cache: OrderedDict[int, np.ndarray] = Field(default_factory=OrderedDict)+ current_bytes: int = Field(default=0)++ @property+ def _max_bytes(self) -> int:+ return self.max_size_mb * 1024 * 1024++ def get(self, frame_number: int) -> np.ndarray | None:+ if frame_number not in self.frame_cache:+ return None+ # Move to end (most recently used)+ self.frame_cache.move_to_end(frame_number)+ return self.frame_cache[frame_number].copy()++ def put(self, frame_number: int, frame: np.ndarray) -> None:+ frame_bytes = frame.nbytes++ # If frame already exists, update it+ if frame_number in self.frame_cache:+ old_bytes = self.frame_cache[frame_number].nbytes+ self.current_bytes -= old_bytes+ self.frame_cache.move_to_end(frame_number)++ # Evict frames if necessary based on size only+ while self.frame_cache and self.current_bytes + frame_bytes > self._max_bytes:+ evicted_frame_num, evicted_frame = self.frame_cache.popitem(last=False)+ self.current_bytes -= evicted_frame.nbytes++ # Add new frame+ self.frame_cache[frame_number] = frame.copy()+ self.current_bytes += frame_bytes++ def clear(self) -> None:+ self.frame_cache.clear()+ self.current_bytes = 0+++class VideoHelper(BaseModel):+ """Video helper with caching and optimized frame reading"""++ model_config = ConfigDict(arbitrary_types_allowed=True)++ video_path: Path+ video_reader: cv2.VideoCapture = Field(exclude=True)+ metadata: VideoMetadata+ cache: FrameCache = Field(default_factory=lambda: FrameCache())++ # Reading optimization state+ last_read_frame: int = Field(default=-1)+ sequential_threshold: int = Field(default=SEQUENTIAL_READ_THRESHOLD)+ @property+ def has_frames(self) -> bool:+ """Check if video has frames."""+ return self.metadata.frame_count > 0 and self.last_read_frame < self.metadata.frame_count - 1++ @classmethod+ def from_video_path(+ cls,+ video_path: Path,+ *,+ cache_size_mb: int = DEFAULT_CACHE_SIZE_MB+ ) -> "VideoHelper":+ """+ Create a VideoHelper instance.++ Args:+ video_path: Path to the video file+ cache_size_mb: Maximum cache size in megabytes+ """+ if not video_path.exists():+ raise FileNotFoundError(f"Video file not found: {video_path}")++ # Open video capture+ video_reader = cv2.VideoCapture(str(video_path))+ if not video_reader.isOpened():+ raise RuntimeError(f"Failed to open video file: {video_path}")++ # Extract metadata+ width = int(video_reader.get(cv2.CAP_PROP_FRAME_WIDTH))+ height = int(video_reader.get(cv2.CAP_PROP_FRAME_HEIGHT))+ fps = video_reader.get(cv2.CAP_PROP_FPS)+ frame_count = int(video_reader.get(cv2.CAP_PROP_FRAME_COUNT))+ fourcc_code = int(video_reader.get(cv2.CAP_PROP_FOURCC))++ # Convert fourcc to string+ fourcc = "".join([chr((fourcc_code >> 8 * i) & 0xFF) for i in range(4)])++ # Calculate duration+ duration_seconds = frame_count / fps if fps > 0 else 0.0++ metadata = VideoMetadata(+ width=width,+ height=height,+ fps=fps,+ frame_count=frame_count,+ fourcc=fourcc,+ duration_seconds=duration_seconds+ )++ # Create cache+ cache = FrameCache(max_size_mb=cache_size_mb)++ return cls(+ video_path=video_path,+ video_reader=video_reader,+ metadata=metadata,+ cache=cache+ )++ def read_next_frame(self) -> np.ndarray| None:+ """+ Read the next frame in sequence. If the last read frame is -1, reads frame 0. If the last read frame is the last frame, returns None.+++ Returns:+ Frame as numpy array+ """+ next_frame_number = self.last_read_frame + 1+ if next_frame_number >= self.metadata.frame_count:+ return None+ return self.read_frame_number(next_frame_number)+ def read_frame_number(self, frame_number: int) -> np.ndarray:+ """+ Read a specific frame with caching and access pattern optimization.++ Args:+ frame_number: Frame index to read (0-based)++ Returns:+ Frame as numpy array+ """+ # Validate frame number+ if not 0 <= frame_number < self.metadata.frame_count:+ raise ValueError(+ f"Frame {frame_number} out of bounds [0, {self.metadata.frame_count})"+ )++ # Check cache first+ cached_frame = self.cache.get(frame_number)+ if cached_frame is not None:+ return cached_frame++ # Determine read strategy and read frame+ if self._should_use_sequential_read(frame_number):+ frame = self._read_sequential(frame_number)+ else:+ frame = self._read_random_access(frame_number)++ if frame is None:+ raise RuntimeError(f"Failed to read frame {frame_number}")++ # Cache the frame+ self.cache.put(frame_number, frame)+ self.last_read_frame = frame_number++ return frame++ def _should_use_sequential_read(self, frame_number: int) -> bool:+ """Check if sequential reading would be more efficient."""+ if self.last_read_frame < 0:+ return False++ # If we're reading nearby frames forward, use sequential+ distance = frame_number - self.last_read_frame+ return 0 < distance <= self.sequential_threshold++ def _read_sequential(self, frame_number: int) -> np.ndarray:+ """Read frame using sequential access (grab/retrieve)."""+ # Skip frames using grab() which is faster than read()+ frames_to_skip = frame_number - self.last_read_frame - 1+ for _ in range(frames_to_skip):+ if not self.video_reader.grab():+ raise RuntimeError(f"Failed to grab frame while seeking to {frame_number}")++ # Retrieve the target frame+ ret, frame = self.video_reader.retrieve()+ if not ret or frame is None:+ raise RuntimeError(f"Failed to retrieve frame {frame_number}")++ return frame++ def _read_random_access(self, frame_number: int) -> np.ndarray:+ """Read frame using random access (set position then read)."""+ # Set position and read+ self.video_reader.set(cv2.CAP_PROP_POS_FRAMES, frame_number)+ ret, frame = self.video_reader.read()++ if not ret or frame is None:+ raise RuntimeError(f"Failed to read frame {frame_number}")++ return frame++ def read_frame_batch(self, frame_numbers: list[int]) -> list[np.ndarray]:+ """+ Read multiple frames efficiently.++ Args:+ frame_numbers: List of frame indices to read++ Returns:+ List of frames in the same order as requested+ """+ # Check cache and determine what needs reading+ results = {}+ frames_to_read = []++ for fn in frame_numbers:+ cached = self.cache.get(fn)+ if cached is not None:+ results[fn] = cached+ else:+ frames_to_read.append(fn)++ if frames_to_read:+ # Sort for optimal reading+ frames_to_read.sort()++ # Read missing frames+ for fn in frames_to_read:+ frame = self.read_frame_number(fn)+ results[fn] = frame++ # Return in original order+ return [results[fn] for fn in frame_numbers]++ def get_frame_timestamp(self, frame_number: int) -> float:+ """Get timestamp in seconds for a given frame number."""+ if self.metadata.fps <= 0:+ raise RuntimeError("Invalid FPS value")+ return frame_number / self.metadata.fps++ def get_frame_at_timestamp(self, timestamp_seconds: float) -> np.ndarray:+ """Read frame at specific timestamp."""+ if self.metadata.fps <= 0:+ raise RuntimeError("Invalid FPS value")+ frame_number = int(timestamp_seconds * self.metadata.fps)+ return self.read_frame_number(frame_number)++ def extract_frames_interval(+ self,+ start_frame: int,+ end_frame: int,+ step: int = 1+ ) -> list[np.ndarray]:+ """+ Extract frames from an interval efficiently.++ Args:+ start_frame: Starting frame index+ end_frame: Ending frame index (exclusive)+ step: Step size between frames++ Returns:+ List of extracted frames+ """+ frame_numbers = list(range(start_frame, end_frame, step))+ return self.read_frame_batch(frame_numbers)++ def close(self) -> None:+ """Clean up resources."""+ self.video_reader.release()+ self.cache.clear()++ def __enter__(self) -> "VideoHelper":+ """Context manager entry."""+ return self++ def __exit__(self, exc_type, exc_val, exc_tb) -> None:+ """Context manager exit."""+ self.close()+++class VideoGroupHelper(BaseModel):+ model_config = ConfigDict(+ arbitrary_types_allowed=True,+ validate_assignment=True,+ extra="forbid",+ frozen=True+ )+ videos: dict[VideoIdString, VideoHelper]+ video_metadata_by_id: dict[VideoIdString, VideoMetadata]++ @property+ def video_ids(self) -> list[VideoIdString]:+ return list(self.videos.keys())++ @model_validator(mode="after")+ def validate_videos(self):+ if len(self.videos) == 0:+ raise ValueError("VideoGroup must contain at least one video.")+ if len(set(video.metadata.frame_count for video in self.videos.values())) != 1:+ raise ValueError("All videos in VideoGroup must have the same frame count.")+ return self++ @classmethod+ def from_video_paths(cls, video_paths: list[VideoIdString], close_videos:bool=True) -> "VideoGroupHelper":+ video_paths = sorted(video_paths) # sort to ensure consistent ordering++ videos: dict[VideoIdString, VideoHelper] = {}++ for video_number, video_path in enumerate(video_paths):+ video_name = Path(video_path).name+ # camera_id = extract_camera_id(video_name)+ # TODO - Just using video order index as video ID for now, need revisit this later to couple this to Camera Id somehow. Its a tricky problem.+ videos[str(video_number)] = VideoHelper.from_video_path(Path(video_path))++ instance = cls(videos=videos,+ video_metadata_by_id={vid_id: vid.metadata for vid_id, vid in videos.items()})+ #close videos+ if close_videos:+ instance.close()+ return instance++ @classmethod+ def from_video_folder_path(cls, video_folder_path: Path) -> "VideoGroupHelper":+ video_paths = sorted(+ [str(p) for p in video_folder_path.iterdir() if p.suffix.lower() in {'.mp4', '.avi', '.mov', '.mkv'}])++ return cls.from_video_paths(video_paths)++ @classmethod+ def from_recording_path(cls, recording_path: str,+ video_subfolder_name: str = 'synchronized_videos') -> "VideoGroupHelper":+ return cls.from_video_folder_path(Path(recording_path) / video_subfolder_name)++ def close(self):+ for video in self.videos.values():+ video.close()+# Example usage+if __name__ == "__main__":+ video_path = Path(r"C:\Users\jonma\Downloads\2025-07-01_ferret_757_EyeCameras_P33_EO5_1m_20s-2m_20s(2).mp4")++ # Using context manager for automatic cleanup+ with VideoHelper.from_video_path(+ video_path,+ cache_size_mb=1000+ ) as vh:+ # Read single frame+ frame = vh.read_frame_number(100)+ print(f"Frame shape: {frame.shape}")++ # Read batch of frames efficiently+ frames = vh.read_frame_batch([10, 50, 100, 150, 200])+ print(f"Read {len(frames)} frames")++ # Extract interval+ interval_frames = vh.extract_frames_interval(0, 100, step=10)+ print(f"Extracted {len(interval_frames)} frames from interval")++ # Get frame at timestamp+ frame_at_5s = vh.get_frame_at_timestamp(5.0)+ print(f"Frame at 5s shape: {frame_at_5s.shape}")\ No newline at end of filediff --git a/freemocap/old/core_processes/export_data/__init__.py b/freemocap/core/pipeline/realtime_pipeline/__init__.pysimilarity index 100%rename from freemocap/old/core_processes/export_data/__init__.pyrename to freemocap/core/pipeline/realtime_pipeline/__init__.pydiff --git a/freemocap/core/pipeline/realtime_pipeline/realtime_aggregation_node.py b/freemocap/core/pipeline/realtime_pipeline/realtime_aggregation_node.pynew file mode 100644index 00000000..98fe95b2--- /dev/null+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_aggregation_node.py@@ -0,0 +1,176 @@+import logging+import multiprocessing+from dataclasses import dataclass++import numpy as np+from pydantic import BaseModel, ConfigDict+from skellycam.core.ipc.shared_memory.camera_group_shared_memory import CameraGroupSharedMemory, \+ CameraGroupSharedMemoryDTO+from skellycam.core.types.type_overloads import CameraGroupIdString, CameraIdString, TopicSubscriptionQueue+from skellycam.utilities.wait_functions import wait_1ms++from freemocap.core.pipeline.pipeline_configs import RealtimePipelineConfig+from freemocap.core.pipeline.pipeline_ipc import PipelineIPC+from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.charuco_observation_aggregator import \+ get_last_successful_calibration_toml_path+from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.freemocap_anipose import \+ AniposeCameraGroup+from freemocap.core.pipeline.posthoc_pipelines.posthoc_mocap_pipeline.mocap_helpers.triangulate_trajectory_array import \+ triangulate_frame_observations+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.shared_view_accumulator import \+ SharedViewAccumulator+from freemocap.core.types.type_overloads import Point3d, PipelineIdString+from freemocap.pubsub.pubsub_topics import CameraNodeOutputMessage, PipelineConfigUpdateTopic, ProcessFrameNumberTopic, \+ ProcessFrameNumberMessage, AggregationNodeOutputMessage, AggregationNodeOutputTopic, CameraNodeOutputTopic, \+ PipelineConfigUpdateMessage, ShouldCalibrateTopic++logger = logging.getLogger(__name__)+++class RealtimeAggregationNodeState(BaseModel):+ model_config = ConfigDict(+ validate_assignment=True,+ frozen=True+ )+ pipeline_id: PipelineIdString+ config: RealtimePipelineConfig+ alive: bool+ last_seen_frame_number: int | None = None+ calibration_task_state: object | None = None+ mocap_task_state: object = None # TODO - this+++@dataclass+class RealtimeAggregationNode:+ shutdown_self_flag: multiprocessing.Value+ worker: multiprocessing.Process++ @classmethod+ def create(cls,+ config: RealtimePipelineConfig,+ camera_group_id: CameraGroupIdString,+ subprocess_registry: list[multiprocessing.Process],+ camera_group_shm_dto: CameraGroupSharedMemoryDTO,+ ipc: PipelineIPC):+ shutdown_self_flag = multiprocessing.Value('b', False)+ worker = multiprocessing.Process(target=cls._run,+ name=f"CameraGroup-{camera_group_id}-AggregationNode",+ kwargs=dict(config=config,+ camera_group_id=camera_group_id,+ ipc=ipc,+ shutdown_self_flag=shutdown_self_flag,+ camera_group_shm_dto=camera_group_shm_dto,+ camera_node_subscription=ipc.pubsub.topics[+ CameraNodeOutputTopic].get_subscription(),+ pipeline_config_subscription=ipc.pubsub.topics[+ PipelineConfigUpdateTopic].get_subscription(),+ should_calibrate_subscription=ipc.pubsub.topics[+ ShouldCalibrateTopic].get_subscription(),+ ),++ )+ subprocess_registry.append(worker)+ return cls(shutdown_self_flag=shutdown_self_flag,+ worker=worker+ )++ @staticmethod+ def _run(config: RealtimePipelineConfig,+ camera_group_id: CameraGroupIdString,+ ipc: PipelineIPC,+ shutdown_self_flag: multiprocessing.Value,+ camera_group_shm_dto: CameraGroupSharedMemoryDTO,+ camera_node_subscription: TopicSubscriptionQueue,+ pipeline_config_subscription: TopicSubscriptionQueue,+ should_calibrate_subscription: TopicSubscriptionQueue+ ):+ if multiprocessing.parent_process():+ # Configure logging if multiprocessing (i.e. if there is a parent process)+ from freemocap.system.logging_configuration.configure_logging import configure_logging+ from freemocap import LOG_LEVEL+ configure_logging(LOG_LEVEL, ws_queue=ipc.ws_queue)++ logger.debug("AggregationNode - starting main loop")+ try:+ logger.debug(f"Starting aggregation process for camera group {camera_group_id}")+ camera_node_outputs: dict[CameraIdString, CameraNodeOutputMessage | None] = {camera_id: None for camera_id+ in+ config.camera_configs.keys()}+ camera_group_shm = CameraGroupSharedMemory.recreate(shm_dto=camera_group_shm_dto,+ read_only=True)+ shared_view_accumulator = SharedViewAccumulator.create(camera_ids=config.camera_ids)+ latest_requested_frame: int = -1+ last_received_frame: int = -1+ anipose_camera_group = AniposeCameraGroup.load(str(get_last_successful_calibration_toml_path()))+ while ipc.should_continue and not shutdown_self_flag.value:+ wait_1ms()++ # Check for updated Pipeline Config+ while not pipeline_config_subscription.empty():+ pipeline_config_message: PipelineConfigUpdateMessage = pipeline_config_subscription.get()+ config = pipeline_config_message.pipeline_config+ logger.info(f"AggregationNode for camera group {camera_group_id} received updated config")++ # Check if we should request a new frame to process+ if camera_group_shm.latest_multiframe_number > latest_requested_frame and last_received_frame >= latest_requested_frame:+ ipc.pubsub.topics[ProcessFrameNumberTopic].publish(+ ProcessFrameNumberMessage(frame_number=camera_group_shm.latest_multiframe_number))+ latest_requested_frame = camera_group_shm.latest_multiframe_number++ # Check for Camera Node Output+ if not camera_node_subscription.empty():+ camera_node_output_message: CameraNodeOutputMessage = camera_node_subscription.get()+ camera_id = camera_node_output_message.camera_id+ if not camera_id in config.camera_configs.keys():+ raise ValueError(+ f"Camera ID {camera_id} not in camera IDs {list(config.camera_configs.keys())}")+ camera_node_outputs[camera_id] = camera_node_output_message++ # Check if ready to process a frame output+ if all([isinstance(camera_node_output_message, CameraNodeOutputMessage) for camera_node_output_message+ in+ camera_node_outputs.values()]):+ if not all([camera_node_output_message.frame_number == latest_requested_frame for+ camera_node_output_message in camera_node_outputs.values()]):+ logger.warning(+ f"Frame numbers from tracker results do not match expected ({latest_requested_frame}) - got {[camera_node_output_message.frame_number for camera_node_output_message in camera_node_outputs.values()]}")+ last_received_frame = latest_requested_frame++ # shared_view_accumulator.receive_camera_node_output(+ # camera_node_output_by_camera=camera_node_outputs,+ # multi_frame_number=latest_requested_frame)++ triangulated = triangulate_frame_observations(frame_number=latest_requested_frame,+ frame_observations_by_camera={camera_id: camera_node_outputs[camera_id].observation+ for camera_id in camera_node_outputs.keys()},+ anipose_camera_group=anipose_camera_group,+ )++ aggregation_output: AggregationNodeOutputMessage = AggregationNodeOutputMessage(+ frame_number=latest_requested_frame,+ pipeline_id=ipc.pipeline_id,+ camera_group_id=camera_group_id,+ pipeline_config=config,+ camera_node_outputs=camera_node_outputs,+ tracked_points3d=triangulated.to_point_dictionary()+ )+ ipc.pubsub.topics[AggregationNodeOutputTopic].publish(aggregation_output)+ camera_node_outputs = {camera_id: None for camera_id in camera_node_outputs.keys()}+++ except Exception as e:+ logger.error(f"Exception in AggregationNode for camera group {camera_group_id}: {e}", exc_info=True)+ ipc.kill_everything()+ raise+ finally:+ logger.debug(f"Shutting down aggregation process for camera group {camera_group_id}")++ def start(self):+ logger.debug(f"Starting AggregationNode worker")+ self.worker.start()++ def shutdown(self):+ logger.debug(f"Stopping AggregationNode worker")+ self.shutdown_self_flag.value = True+ self.worker.join()+ logger.debug(f"AggregationNode worker stopped")diff --git a/freemocap/core/pipeline/realtime_pipeline/realtime_camera_node.py b/freemocap/core/pipeline/realtime_pipeline/realtime_camera_node.pynew file mode 100644index 00000000..19b5b510--- /dev/null+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_camera_node.py@@ -0,0 +1,152 @@+import logging+import multiprocessing+import time+from dataclasses import dataclass++import cv2+import numpy as np+from pydantic import BaseModel, ConfigDict+from skellycam.core.ipc.shared_memory.camera_shared_memory_ring_buffer import CameraSharedMemoryRingBuffer+from skellycam.core.ipc.shared_memory.ring_buffer_shared_memory import SharedMemoryRingBufferDTO+from skellycam.core.types.type_overloads import CameraIdString, WorkerType, TopicSubscriptionQueue+from skellycam.utilities.wait_functions import wait_1ms+from skellytracker.trackers.charuco_tracker.charuco_detector import CharucoDetector+from skellytracker.trackers.mediapipe_tracker.mediapipe_detector import MediapipeDetector++from freemocap.core.pipeline.pipeline_configs import RealtimePipelineConfig+from freemocap.core.pipeline.pipeline_ipc import PipelineIPC+from freemocap.core.types.type_overloads import PipelineIdString+from freemocap.pubsub.pubsub_topics import ProcessFrameNumberTopic, PipelineConfigUpdateTopic, CameraNodeOutputTopic, \+ PipelineConfigUpdateMessage, ProcessFrameNumberMessage, CameraNodeOutputMessage++logger = logging.getLogger(__name__)+++class CameraNodeState(BaseModel):+ model_config = ConfigDict(+ validate_assignment=True,+ frozen=True+ )+ pipeline_id: PipelineIdString+ alive: bool+ last_seen_frame_number: int | None = None+ calibration_task_state: object | None = None+ mocap_task_state: object = None # TODO - this+++@dataclass+class RealtimeCameraNode:+ camera_id: CameraIdString+ shutdown_self_flag: multiprocessing.Value+ worker: WorkerType++ @classmethod+ def create(cls,+ camera_id: CameraIdString,+ camera_shm_dto: SharedMemoryRingBufferDTO,+ subprocess_registry: list[multiprocessing.Process],+ config: RealtimePipelineConfig,+ ipc: PipelineIPC):+ shutdown_self_flag = multiprocessing.Value('b', False)+ worker = multiprocessing.Process(target=cls._run,+ name=f"CameraProcessingNode-{camera_id}",+ kwargs=dict(camera_id=camera_id,+ ipc=ipc,+ config=config,+ shutdown_self_flag=shutdown_self_flag,+ camera_shm_dto=camera_shm_dto,+ process_frame_number_subscription=ipc.pubsub.get_subscription(+ ProcessFrameNumberTopic),+ pipeline_config_subscription=ipc.pubsub.get_subscription(+ PipelineConfigUpdateTopic),+ ),+ )+ subprocess_registry.append(worker)+ return cls(camera_id=camera_id,+ shutdown_self_flag=shutdown_self_flag,+ worker=worker+ )++ @staticmethod+ def _run(camera_id: CameraIdString,+ ipc: PipelineIPC,+ config: RealtimePipelineConfig,+ process_frame_number_subscription: TopicSubscriptionQueue,+ pipeline_config_subscription: TopicSubscriptionQueue,+ shutdown_self_flag: multiprocessing.Value,+ camera_shm_dto: SharedMemoryRingBufferDTO,+ ):+ if multiprocessing.parent_process():+ # Configure logging if multiprocessing (i.e. if there is a parent process)+ from freemocap.system.logging_configuration.configure_logging import configure_logging+ from freemocap import LOG_LEVEL+ configure_logging(LOG_LEVEL, ws_queue=ipc.ws_queue)++ logger.debug(f"Initializing camera processing node for camera {camera_id} - creating shared memory ring buffer")+ camera_shm = CameraSharedMemoryRingBuffer.recreate(dto=camera_shm_dto,+ read_only=False)+ charuco_detector = CharucoDetector.create(config=config.calibration_task_config.detector_config)+ mediapipe_detector = MediapipeDetector.create()+ try:+ logger.trace(f"Starting camera processing node for camera {camera_id}")+ frame_rec_array: np.recarray | None = None+ while ipc.should_continue and not shutdown_self_flag.value:+ wait_1ms()+ # Check trackers config updates+ while not pipeline_config_subscription.empty():+ new_pipeline_config_message: PipelineConfigUpdateMessage = pipeline_config_subscription.get()+ logger.debug(f"Received new skelly trackers for camera {camera_id}: {new_pipeline_config_message}")+ config = new_pipeline_config_message.pipeline_config++ # Check for new frame to process+ if not process_frame_number_subscription.empty():+ process_frame_number_message: ProcessFrameNumberMessage = process_frame_number_subscription.get()++ # Process the frame+ tik = time.perf_counter_ns()+ frame_rec_array = camera_shm.get_data_by_index(index=process_frame_number_message.frame_number,+ rec_array=frame_rec_array)+ if frame_rec_array.frame_metadata.camera_config.rotation != -1:+ rotated_image = cv2.rotate(+ src=frame_rec_array.image[0],+ rotateCode=frame_rec_array.frame_metadata.camera_config.rotation[0]+ )+ else:+ rotated_image = frame_rec_array.image[0]+ observation = mediapipe_detector.detect(+ frame_number=frame_rec_array.frame_metadata.frame_number[0],+ image=rotated_image, )+ # observation = charuco_detector.detect(+ # frame_number=frame_rec_array.frame_metadata.frame_number[0],+ # image=rotated_image, )++ # tok = time.perf_counter_ns()++ ipc.pubsub.publish(+ topic_type=CameraNodeOutputTopic,+ message=CameraNodeOutputMessage(+ camera_id=frame_rec_array.frame_metadata.camera_config.camera_id[0],+ frame_number=frame_rec_array.frame_metadata.frame_number[0],+ observation=observation,+ ),+ )+ tok2 = time.perf_counter_ns()+ # logger.debug(+ # f"Camera {camera_id} processed frame {frame_rec_array.frame_metadata.frame_number[0]} in "+ # f"{(tok - tik) / 1e6:.2f} ms, published observation in {(tok2 - tok) / 1e6:.2f} ms")+ except Exception as e:+ logger.exception(f"Exception in camera node for camera {camera_id}: {e}")+ ipc.kill_everything()+ raise e+ finally:+ logger.debug(f"Shutting down camera processing node for camera {camera_id}")++ def start(self):+ logger.debug(f"Starting {self.__class__.__name__} for camera {self.camera_id}")+ self.worker.start()++ def shutdown(self):+ logger.debug(f"Stopping {self.__class__.__name__} for camera {self.camera_id}")+ self.shutdown_self_flag.value = True+ self.worker.join()+ logger.debug(f"{self.__class__.__name__} for camera {self.camera_id} stopped")diff --git a/freemocap/core/pipeline/realtime_pipeline/realtime_pipeline.py b/freemocap/core/pipeline/realtime_pipeline/realtime_pipeline.pynew file mode 100644index 00000000..366fab5a--- /dev/null+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_pipeline.py@@ -0,0 +1,192 @@+import logging+import multiprocessing+import time+import uuid+from dataclasses import dataclass++from pydantic import BaseModel, ConfigDict+from skellycam.core.camera.config.camera_config import CameraConfigs+from skellycam.core.camera_group.camera_group import CameraGroup+from skellycam.core.recorders.videos.recording_info import RecordingInfo+from skellycam.core.types.type_overloads import CameraIdString, CameraGroupIdString++from freemocap.core.pipeline.realtime_pipeline.realtime_aggregation_node import RealtimeAggregationNode, RealtimeAggregationNodeState+from freemocap.core.pipeline.realtime_pipeline.realtime_camera_node import RealtimeCameraNode, CameraNodeState+from freemocap.core.pipeline.frontend_payload import FrontendPayload+from freemocap.core.pipeline.pipeline_configs import RealtimePipelineConfig+from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.posthoc_calibration_pipeline import \+ CalibrationpipelineConfig+from freemocap.core.pipeline.pipeline_ipc import PipelineIPC+from freemocap.core.types.type_overloads import PipelineIdString, TopicSubscriptionQueue, FrameNumberInt+from freemocap.pubsub.pubsub_topics import AggregationNodeOutputTopic, AggregationNodeOutputMessage, \+ PipelineConfigUpdateMessage, \+ PipelineConfigUpdateTopic, ShouldCalibrateMessage, ShouldCalibrateTopic++logger = logging.getLogger(__name__)+++class RealtimePipelineState(BaseModel):+ """Serializable representation of a processing pipeline state."""+ model_config = ConfigDict(+ validate_assignment=True,+ frozen=True+ )+ id: PipelineIdString+ camera_group_id: CameraGroupIdString+ camera_node_states: dict[CameraIdString, CameraNodeState]+ aggregation_node_state: RealtimeAggregationNodeState+ alive: bool+++++@dataclass+class RealtimeProcessingPipeline:+ id: PipelineIdString+ camera_group: CameraGroup+ config: RealtimePipelineConfig+ camera_nodes: dict[CameraIdString, RealtimeCameraNode]+ aggregation_node: RealtimeAggregationNode+ aggregation_node_subscription: TopicSubscriptionQueue+ ipc: PipelineIPC+ started: bool = False++ @property+ def alive(self) -> bool:+ return all([camera_node.worker.is_alive() for camera_node in+ self.camera_nodes.values()]) and self.aggregation_node.worker.is_alive()++ @property+ def camera_group_id(self) -> CameraGroupIdString:+ return self.camera_group.id++ @property+ def camera_ids(self) -> list[CameraIdString]:+ return list(self.camera_nodes.keys())++ @property+ def camera_configs(self) -> CameraConfigs:+ return self.camera_group.configs++ @classmethod+ def from_config(cls,+ camera_group: CameraGroup,+ heartbeat_timestamp: multiprocessing.Value,+ subprocess_registry: list[multiprocessing.Process],+ pipeline_config: RealtimePipelineConfig,+ ):++ ipc = PipelineIPC.create(global_kill_flag=camera_group.ipc.global_kill_flag,+ heartbeat_timestamp=heartbeat_timestamp+ )+ camera_nodes = {camera_id: RealtimeCameraNode.create(camera_id=camera_id,+ subprocess_registry=subprocess_registry,+ camera_shm_dto=camera_group.shm.to_dto().camera_shm_dtos[camera_id],+ config=pipeline_config,+ ipc=ipc)+ for camera_id, config in camera_group.configs.items()}+ aggregation_node = RealtimeAggregationNode.create(camera_group_id=camera_group.id,+ subprocess_registry=subprocess_registry,+ camera_group_shm_dto=camera_group.shm.to_dto(),+ config=pipeline_config,+ ipc=ipc,+ )++ return cls(camera_nodes=camera_nodes,+ aggregation_node=aggregation_node,+ ipc=ipc,+ config=pipeline_config,+ aggregation_node_subscription=ipc.pubsub.topics[+ AggregationNodeOutputTopic].get_subscription(),+ camera_group=camera_group,+ id=str(uuid.uuid4())[:6],+ )++ def start(self) -> None:+ self.started = True+ logger.debug(+ f"Starting Pipeline (id:{self.id} with camera group (id:{self.camera_group_id} for camera ids: {list(self.camera_nodes.keys())}...")+ if not self.camera_group.started:+ try:+ logger.debug("Starting camera group...")+ self.camera_group.start()+ except Exception as e:+ logger.error(f"Failed to start camera group: {type(e).__name__} - {e}")+ logger.exception(e)+ raise++ try:+ logger.debug("Starting aggregation node...")+ self.aggregation_node.start()+ logger.debug(f"Aggregation node worker started: alive={self.aggregation_node.worker.is_alive()}")+ except Exception as e:+ logger.error(f"Failed to start aggregation node: {type(e).__name__} - {e}")+ logger.exception(e)+ raise++ for camera_id, camera_node in self.camera_nodes.items():+ try:+ logger.debug(f"Starting camera node {camera_id}...")+ camera_node.start()+ logger.debug(f"Camera node {camera_id} worker started: alive={camera_node.worker.is_alive()}")+ except Exception as e:+ logger.error(f"Failed to start camera node {camera_id}: {type(e).__name__} - {e}")+ logger.exception(e)+ raise++ logger.info(f"All pipeline workers started successfully")++ def shutdown(self):+ logger.debug(f"Shutting down {self.__class__.__name__}...")++ self.ipc.shutdown_pipeline()+ for camera_id, camera_node in self.camera_nodes.items():+ camera_node.shutdown()+ self.aggregation_node.shutdown()++ async def update_camera_configs(self, camera_configs: CameraConfigs) -> CameraConfigs:+ return await self.camera_group.update_camera_settings(requested_configs=camera_configs)++ def get_latest_frontend_payload(self, if_newer_than: FrameNumberInt) -> tuple[bytes, FrontendPayload | None] | None:+ if not self.alive:+ if self.camera_group.alive:+ _, _, frames_bytearray = self.camera_group.get_latest_frontend_payload(if_newer_than=if_newer_than)+ if frames_bytearray is not None:+ return (frames_bytearray,+ None)+ return None+ aggregation_output: AggregationNodeOutputMessage | None = None+ while not self.aggregation_node_subscription.empty():+ aggregation_output = self.aggregation_node_subscription.get()+ if aggregation_output is None:+ return None+ frames_bytearray = self.camera_group.get_frontend_payload_by_frame_number(+ frame_number=aggregation_output.frame_number,+ )++ return (frames_bytearray,+ FrontendPayload.from_aggregation_output(aggregation_output=aggregation_output))++ def update_pipeline_config(self, new_config: RealtimePipelineConfig) -> None:+ self.config = new_config+ self.ipc.pubsub.topics[PipelineConfigUpdateTopic].publish(+ PipelineConfigUpdateMessage(pipeline_config=self.config)+ )++ async def start_calibration_recording(self, recording_info: RecordingInfo, config: CalibrationpipelineConfig):+ # TODO - I don't love this method of getting the config and path here, wanna fix it later+ config.calibration_recording_folder = recording_info.full_recording_path+ logger.info(f"Starting calibration recording: {recording_info.full_recording_path} with config: {config.model_dump_json(indent=2)}")+ self.config.calibration_task_config = config+ self.ipc.pubsub.topics[PipelineConfigUpdateTopic].publish(+ PipelineConfigUpdateMessage(pipeline_config=self.config))+ await self.camera_group.start_recording(recording_info=recording_info)+ logger.info("Calibration recording started.")++ async def stop_calibration_recording(self):+ logger.info("Stopping calibration recording...")+ # TODO - I don't love this method of getting the config and path here, wanna fix it later+ await self.camera_group.stop_recording()+ time.sleep(1) # give it a sec to wrap up+ logger.info(f"Calibration recording stopped - sending calibration start message - config: {self.config.calibration_task_config.model_dump_json(indent=2)}")+ self.ipc.pubsub.topics[ShouldCalibrateTopic].publish(ShouldCalibrateMessage())diff --git a/freemocap/core/pipeline/realtime_pipeline/realtime_pipeline_manager.py b/freemocap/core/pipeline/realtime_pipeline/realtime_pipeline_manager.pynew file mode 100644index 00000000..7cc4fb78--- /dev/null+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_pipeline_manager.py@@ -0,0 +1,127 @@+import logging+import multiprocessing+from copy import deepcopy+from dataclasses import dataclass, field++from skellycam.core.recorders.videos.recording_info import RecordingInfo+from skellycam.core.types.type_overloads import CameraIdString+from skellycam.core.camera_group.camera_group import CameraGroup++from freemocap.core.pipeline.frontend_payload import FrontendPayload+from freemocap.core.pipeline.pipeline_configs import RealtimePipelineConfig+from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.posthoc_calibration_pipeline import \+ CalibrationpipelineConfig+from freemocap.core.pipeline.realtime_pipeline.realtime_pipeline import RealtimeProcessingPipeline+from freemocap.core.types.type_overloads import PipelineIdString, FrameNumberInt+from fastapi import FastAPI+logger = logging.getLogger(__name__)+++@dataclass+class RealtimePipelineManager:+ global_kill_flag: multiprocessing.Value+ heartbeat_timestamp: multiprocessing.Value+ subprocess_registry: list[multiprocessing.Process]+ lock: multiprocessing.Lock = field(default_factory=multiprocessing.Lock)+ realtime_pipelines: dict[PipelineIdString, RealtimeProcessingPipeline] = field(default_factory=dict)++ @classmethod+ def from_fastapi_app(cls, fastapi_app:FastAPI) -> 'RealtimePipelineManager':+ return cls(global_kill_flag=fastapi_app.state.global_kill_flag,+ heartbeat_timestamp=fastapi_app.state.heartbeat_timestamp,+ subprocess_registry=fastapi_app.state.subprocess_registry)++ async def create_realtime_pipeline(self,+ camera_group: CameraGroup,+ pipeline_config: RealtimePipelineConfig) -> RealtimeProcessingPipeline:+ with self.lock:+ # get existing pipeline for the provided camera configs, if it exists+ for pipeline in self.realtime_pipelines.values():+ if set(pipeline.camera_ids) == set(pipeline_config.camera_ids):+ logger.info(+ f"Found existing pipeline with ID: {pipeline.id} for camera group ID: {pipeline.camera_group_id}")+ await pipeline.update_camera_configs(camera_configs=pipeline_config.camera_configs)+ return pipeline+ pipeline = RealtimeProcessingPipeline.from_config(pipeline_config=pipeline_config,+ heartbeat_timestamp=self.heartbeat_timestamp,+ camera_group=camera_group,+ subprocess_registry=self.subprocess_registry)+ pipeline.start()+ self.realtime_pipelines[pipeline.id] = pipeline+ logger.info(f"Created pipeline with ID: {pipeline.id} for camera group ID: {pipeline.camera_group_id}")+ return pipeline++ async def update_realtime_pipeline(self,+ pipeline_config: RealtimePipelineConfig) -> RealtimeProcessingPipeline:+ with self.lock:+ # get existing pipeline for the provided camera configs, if it exists+ for pipeline in self.realtime_pipelines.values():+ if set(pipeline.camera_ids) == set(pipeline_config.camera_ids):+ logger.info(+ f"Found existing pipeline with ID: {pipeline.id} for camera group ID: {pipeline.camera_group_id}")+ await pipeline.update_camera_configs(camera_configs=pipeline_config.camera_configs)+ return pipeline+ raise RuntimeError("No existing pipeline found for the provided camera configs.")++ def close_all_realtime_pipelines(self):+ with self.lock:+ for pipeline in self.realtime_pipelines.values():+ pipeline.shutdown()+ self.realtime_pipelines.clear()+ logger.info("All pipelines closed successfully")++ def get_latest_frontend_payloads(self, if_newer_than: FrameNumberInt) -> dict[+ PipelineIdString, tuple[bytes | None, FrontendPayload | None]]:+ latest_outputs = {}+ with self.lock:+ for pipeline_id, pipeline in self.realtime_pipelines.items():+ output = pipeline.get_latest_frontend_payload(if_newer_than=if_newer_than)+ if not output is None:+ latest_outputs[pipeline_id] = output+ return latest_outputs++ def pause_unpause_pipelines(self):+ with self.lock:+ for pipeline in self.realtime_pipelines.values():+ pipeline.camera_group.pause_unpause()++ async def start_recording_all(self, recording_info: RecordingInfo):+ with self.lock:+ for pipeline in self.realtime_pipelines.values():+ await pipeline.camera_group.start_recording(recording_info=recording_info)++ async def stop_recording_all(self) -> list[RecordingInfo]:+ with self.lock:+ recording_infos= []+ for pipeline in self.realtime_pipelines.values():+ recording_infos.append( await pipeline.camera_group.stop_recording())+ return recording_infos++ def update_calibration_task_config(self, calibration_task_config: CalibrationpipelineConfig):+ with self.lock:+ for pipeline in self.realtime_pipelines.values():+ new_config = deepcopy(pipeline.config)+ new_config.calibration_task_config = calibration_task_config+ pipeline.update_pipeline_config(new_config=new_config)++ def get_pipeline_by_camera_ids(self, camera_ids: list[CameraIdString]) -> RealtimeProcessingPipeline | None:+ with self.lock:+ for pipeline in self.realtime_pipelines.values():+ if set(pipeline.camera_ids) == set(camera_ids):+ return pipeline+ return None++ async def create_or_update_realtime_calibration_pipeline(self, calibration_task_config: CalibrationpipelineConfig) -> RealtimeProcessingPipeline:+ with self.lock:+ # TODO - update specific pipelines by id, for now update all pipelines+ for pipeline in self.realtime_pipelines.values():+ new_config = deepcopy(pipeline.config)+ new_config.calibration_task_config = calibration_task_config+ pipeline.update_pipeline_config(new_config=new_config)+ return pipeline+ raise RuntimeError("No existing pipeline found for the provided camera configs.")++ async def stop_calibration_recording(self, calibration_task_config: CalibrationpipelineConfig):+ pass++diff --git a/freemocap/old/core_processes/export_data/blender_stuff/__init__.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/__init__.pysimilarity index 100%rename from freemocap/old/core_processes/export_data/blender_stuff/__init__.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/__init__.pydiff --git a/freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/__init__.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/__init__.pysimilarity index 100%rename from freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/__init__.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/__init__.pydiff --git a/freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/methods/__init__.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/__init__.pysimilarity index 100%rename from freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/methods/__init__.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/__init__.pydiff --git a/freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/methods/ajc_addon/__init__.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/anipose_flavored_stuff/__init__.pysimilarity index 100%rename from freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/methods/ajc_addon/__init__.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/anipose_flavored_stuff/__init__.pydiff --git a/freemocap/core/pipelines/calibration_pipeline/multi_camera_calibration/anipose_calibration_optimizer.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/anipose_flavored_stuff/anipose_calibration_optimizer.pysimilarity index 96%rename from freemocap/core/pipelines/calibration_pipeline/multi_camera_calibration/anipose_calibration_optimizer.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/anipose_flavored_stuff/anipose_calibration_optimizer.pyindex b4671c17..94859f21 100644--- a/freemocap/core/pipelines/calibration_pipeline/multi_camera_calibration/anipose_calibration_optimizer.py+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/anipose_flavored_stuff/anipose_calibration_optimizer.py@@ -2,23 +2,24 @@ import loggingimport cv2import numpy as np+from freemocap.zzold.core_processes.capture_volume_calibration.anipose_camera_calibration.run_anipose_calibration_algorithm import \+ anipose_triangulate_simple, remap_idsfrom numba import jitfrom pydantic import BaseModelfrom scipy import optimizefrom scipy.linalg import inv as inversefrom scipy.sparse import dok_matrix-from skellycam import CameraIdfrom tqdm import trange-from freemocap.old.core_processes.capture_volume_calibration.anipose_camera_calibration.run_anipose_calibration_algorithm import \- anipose_triangulate_simple, remap_ids-from freemocap.core.pipelines.calibration_pipeline.calibration_numpy_types import ImagePoints2D, \- ObjectPoints3D, ExtrinsicsParameters, IntrinsicsParameters, ReprojectionErrorByPoint, ImagePoints2DByCamera, PointIds, \- RotationVectorsByCamera, TranslationVectorsByCamera-from freemocap.core.pipelines.calibration_pipeline.multi_camera_calibration.calibration_utilities import \+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.anipose_flavored_stuff.calibration_utilities import \calculate_error_bounds, transform_points, construct_camera_extrinsics_matrix, \get_rotation_and_translation_vector_from_extrinsics_matrix, get_error_dict-from freemocap.core.pipelines.calibration_pipeline.single_camera_calibrator import SingleCameraCalibrator+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.calibration_helpers.calibration_numpy_types import ImagePoints2D, \+ ObjectPoints3D, ExtrinsicsParameters, IntrinsicsParameters, ReprojectionErrorByPoint, ImagePoints2DByCamera, \+ PointIds, \+ RotationVectorsByCamera, TranslationVectorsByCamera+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.calibration_helpers.single_camera_calibrator import \+ SingleCameraCalibratorlogger = logging.getLogger(__name__)@@ -95,7 +96,8 @@ class SingleCameraCalibrationHelper(BaseModel):return projected_2d_points- def single_camera_reprojection_error(self, points3d: ObjectPoints3D, points2d: ImagePoints2D) -> ReprojectionErrorByPoint:+ def single_camera_reprojection_error(self, points3d: ObjectPoints3D,+ points2d: ImagePoints2D) -> ReprojectionErrorByPoint:projected_points3d = self.project_3d_to_2d(points3d)projecting_3d_points_onto_2d_image_plane = projected_points3d.reshape(points2d.shape)return points2d - projecting_3d_points_onto_2d_image_plane@@ -112,14 +114,17 @@ class MultiCameraCalibrationInputData(BaseModel):def from_single_camera_helpers(cls, camera_helpers: dict[CameraId, SingleCameraCalibrationHelper]):pixel_points2d = [camera_helper.calibrator.image_points_views for camera_helper in camera_helpers.values()]object_points3d = [camera_helper.calibrator.object_points_views for camera_helper in camera_helpers.values()]- rotation_vectors = np.array([camera_helper.calibrator.rotation_vector for camera_helper in camera_helpers.values()])- translation_vectors = np.array([camera_helper.calibrator.translation_vector for camera_helper in camera_helpers.values()])+ rotation_vectors = np.array(+ [camera_helper.calibrator.rotation_vector for camera_helper in camera_helpers.values()])+ translation_vectors = np.array(+ [camera_helper.calibrator.translation_vector for camera_helper in camera_helpers.values()])return cls(pixel_points2d=pixel_points2d,object_points3d=object_points3d,points_ids=points_ids,rotation_vectors=rotation_vectors,translation_vectors=translation_vectors)+class MultiCameraCalibrationOptimizer(BaseModel):camera_helpers: dict[CameraId, SingleCameraCalibrationHelper]@@ -152,8 +157,6 @@ class MultiCameraCalibrationOptimizer(BaseModel):maximum_number_function_evals=self.max_number_function_evals,)--# Initializeerror_list = []@@ -507,8 +510,6 @@ class MultiCameraCalibrationOptimizer(BaseModel):ids = remap_ids(calibration_input_data.ids)--n_boards = int(np.max(ids)) + 1total_board_params = n_boards * (3 + 3) # rotation_vectors + translation_vectorsdiff --git a/freemocap/core/pipelines/calibration_pipeline/multi_camera_calibration/calibration_utilities.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/anipose_flavored_stuff/calibration_utilities.pysimilarity index 95%rename from freemocap/core/pipelines/calibration_pipeline/multi_camera_calibration/calibration_utilities.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/anipose_flavored_stuff/calibration_utilities.pyindex 78a1ab98..eda43b74 100644--- a/freemocap/core/pipelines/calibration_pipeline/multi_camera_calibration/calibration_utilities.py+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/anipose_flavored_stuff/calibration_utilities.py@@ -1,7 +1,8 @@import cv2import numpy as np-from freemocap.core.pipelines.calibration_pipeline.calibration_numpy_types import RotationVectorArray, \+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.calibration_helpers.calibration_numpy_types import \+ RotationVectorArray, \TranslationVectorArray, ObjectPoints3Ddiff --git a/freemocap/core/pipelines/calibration_pipeline/multi_camera_calibration/triangulation_method.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/anipose_flavored_stuff/triangulation_method.pysimilarity index 94%rename from freemocap/core/pipelines/calibration_pipeline/multi_camera_calibration/triangulation_method.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/anipose_flavored_stuff/triangulation_method.pyindex 5c58f298..d2068fd6 100644--- a/freemocap/core/pipelines/calibration_pipeline/multi_camera_calibration/triangulation_method.py+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/anipose_flavored_stuff/triangulation_method.py@@ -4,7 +4,7 @@ from numba import jit@jit(nopython=True, parallel=False)def triangulate_simple(points2d: np.ndarray,- camera_matrices: np.ndarray) -> np.ndarray:+ camera_matrices: np.ndarray) -> np.ndarray:"""Triangulate 3D point from 2D points and camera matrices using the Direct Linear Transform (DLT) method.diff --git a/freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/methods/ajc_addon/install/__init__.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/__init__.pysimilarity index 100%rename from freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/methods/ajc_addon/install/__init__.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/__init__.pydiff --git a/freemocap/core/pipelines/calibration_pipeline/calculate_sparse_jacobian.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calculate_sparse_jacobian.pysimilarity index 91%rename from freemocap/core/pipelines/calibration_pipeline/calculate_sparse_jacobian.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calculate_sparse_jacobian.pyindex 80a85e37..80e2d6ef 100644--- a/freemocap/core/pipelines/calibration_pipeline/calculate_sparse_jacobian.py+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calculate_sparse_jacobian.py@@ -1,10 +1,11 @@import numpy as npfrom scipy.sparse import dok_matrix, csr_matrix+def calculate_jacobian_sparsity(- pixel_points2d: np.ndarray,- ids: np.ndarray,- num_camera_params: int+ pixel_points2d: np.ndarray,+ ids: np.ndarray,+ num_camera_params: int) -> csr_matrix:"""Calculate the sparsity pattern of the Jacobian matrix for bundle adjustment.@@ -55,7 +56,8 @@ def calculate_jacobian_sparsity(# Update point positions based on reprojection errorfor coord_index in range(3):- jacobian_sparsity[np.arange(num_valid_points), num_cameras * num_camera_params + valid_point_indices * 3 + coord_index] = True+ jacobian_sparsity[+ np.arange(num_valid_points), num_cameras * num_camera_params + valid_point_indices * 3 + coord_index] = True# Update board parameters based on object points errorfor coord_index in range(3):@@ -77,4 +79,4 @@ def calculate_jacobian_sparsity(] = True# Convert to csr_matrix for efficiency in future operations- return jacobian_sparsity.tocsr()\ No newline at end of file+ return jacobian_sparsity.tocsr()diff --git a/freemocap/old/core_processes/export_data/generate_jupyter_notebook/__init__.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calibration_display_helpers/__init__.pysimilarity index 100%rename from freemocap/old/core_processes/export_data/generate_jupyter_notebook/__init__.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calibration_display_helpers/__init__.pydiff --git a/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calibration_display_helpers/charuco_3d_models.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calibration_display_helpers/charuco_3d_models.pynew file mode 100644index 00000000..8f6ccd18--- /dev/null+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calibration_display_helpers/charuco_3d_models.py@@ -0,0 +1,356 @@+from typing import Literal, Any++import numpy as np+from numpydantic import NDArray, Shape+from pydantic import BaseModel, ConfigDict, Field, field_serializer, model_serializer+from skellycam.core.types.type_overloads import CameraIdString+++class Color(BaseModel):+ """RGB color with alpha channel (0-1 range for Three.js compatibility)"""+ model_config = ConfigDict(frozen=True)++ r: float = Field(ge=0.0, le=1.0)+ g: float = Field(ge=0.0, le=1.0)+ b: float = Field(ge=0.0, le=1.0)+ a: float = Field(default=1.0, ge=0.0, le=1.0)++ @classmethod+ def from_hex(cls, hex_color: str) -> "Color":+ """Create color from hex string like '#FF5733' or 'FF5733'"""+ hex_color = hex_color.lstrip('#')+ if len(hex_color) == 6:+ r, g, b = int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)+ return cls(r=r / 255.0, g=g / 255.0, b=b / 255.0)+ raise ValueError(f"Invalid hex color: {hex_color}")++ @classmethod+ def from_rgb_255(cls, r: int, g: int, b: int, a: float = 1.0) -> "Color":+ """Create color from 0-255 RGB values"""+ return cls(r=r / 255.0, g=g / 255.0, b=b / 255.0, a=a)++ def to_hex(self) -> str:+ """Convert to hex string for Three.js"""+ r = int(self.r * 255)+ g = int(self.g * 255)+ b = int(self.b * 255)+ return f"#{r:02x}{g:02x}{b:02x}"++ @model_serializer+ def _serialize(self) -> str:+ """Serialize directly to hex string"""+ return self.to_hex()+++class Point3d(BaseModel):+ """3D point in space - serializes to [x, y, z] array"""+ model_config = ConfigDict(frozen=True)++ x: float+ y: float+ z: float++ @classmethod+ def from_array(cls, array: np.ndarray) -> "Point3d":+ """Create from numpy array [x, y, z]"""+ if array.shape != (3,):+ raise ValueError(f"Expected array of shape (3,), got {array.shape}")+ return cls(x=float(array[0]), y=float(array[1]), z=float(array[2]))++ def to_array(self) -> np.ndarray:+ """Convert to numpy array"""+ return np.array([self.x, self.y, self.z], dtype=np.float32)++ @model_serializer+ def _serialize(self) -> list[float]:+ """Serialize directly to [x, y, z] list"""+ return [self.x, self.y, self.z]+++class Sphere3d(BaseModel):+ """Sphere for rendering in Three.js"""+ model_config = ConfigDict(frozen=True)++ id: str+ position: Point3d+ radius: float = Field(gt=0.0)+ color: Color+ opacity: float = Field(default=1.0, ge=0.0, le=1.0)+ label: str | None = None+++class Line3d(BaseModel):+ """Line connecting two points for rendering in Three.js"""+ model_config = ConfigDict(frozen=True)++ id: str+ start: Point3d+ end: Point3d+ color: Color+ thickness: float = Field(default=1.0, gt=0.0)+ opacity: float = Field(default=1.0, ge=0.0, le=1.0)+ dashed: bool = False+++class CoordinateFrame3d(BaseModel):+ """Coordinate frame showing X, Y, Z axes"""+ model_config = ConfigDict(frozen=True)++ id: str+ origin: Point3d+ x_axis: Point3d+ y_axis: Point3d+ z_axis: Point3d+ scale: float = Field(default=1.0, gt=0.0)+ label: str | None = None+++class BoardPose3d(BaseModel):+ """Pose of the Charuco board in 3D space"""+ model_config = ConfigDict(+ arbitrary_types_allowed=True,+ frozen=True+ )++ rotation_vector: NDArray[Shape["3"], np.float32]+ translation_vector: NDArray[Shape["3"], np.float32]+ coordinate_frame: CoordinateFrame3d | None = None++ @field_serializer('rotation_vector', 'translation_vector')+ def _serialize_vectors(self, value: np.ndarray) -> list[float]:+ """Serialize numpy arrays to lists"""+ return value.tolist()++ @classmethod+ def create_with_frame(+ cls,+ rotation_vector: np.ndarray,+ translation_vector: np.ndarray,+ frame_id: str,+ frame_scale: float = 0.1,+ label: str | None = None+ ) -> "BoardPose3d":+ """Create board pose with coordinate frame for visualization"""+ import cv2++ rotation_matrix, _ = cv2.Rodrigues(rotation_vector)+ origin = Point3d.from_array(translation_vector)++ x_end = origin.to_array() + rotation_matrix[:, 0] * frame_scale+ y_end = origin.to_array() + rotation_matrix[:, 1] * frame_scale+ z_end = origin.to_array() + rotation_matrix[:, 2] * frame_scale++ coordinate_frame = CoordinateFrame3d(+ id=frame_id,+ origin=origin,+ x_axis=Point3d.from_array(x_end),+ y_axis=Point3d.from_array(y_end),+ z_axis=Point3d.from_array(z_end),+ scale=frame_scale,+ label=label+ )++ return cls(+ rotation_vector=rotation_vector,+ translation_vector=translation_vector,+ coordinate_frame=coordinate_frame+ )+++class ArucoMarker3d(BaseModel):+ """3D representation of an ArUco marker with 4 corner spheres"""+ model_config = ConfigDict(frozen=True)++ marker_id: int+ corner_spheres: list[Sphere3d] = Field(min_length=4, max_length=4)+ edge_lines: list[Line3d] = Field(min_length=4, max_length=4)+ center_sphere: Sphere3d | None = None+++class Charuco3dData(BaseModel):+ """Complete 3D visualization data for Charuco board detection"""+ model_config = ConfigDict(+ arbitrary_types_allowed=True,+ frozen=True+ )++ camera_id: CameraIdString+ frame_number: int+ coordinate_system: Literal["camera", "world"]++ charuco_corner_spheres: dict[int, Sphere3d]+ charuco_corner_connections: list[Line3d]+ aruco_markers: dict[int, ArucoMarker3d]+ board_pose: BoardPose3d | None = None++ all_corner_count: int+ detected_corner_count: int+ detection_quality: float = Field(ge=0.0, le=1.0)++ @classmethod+ def from_charuco_observation(+ cls,+ camera_id: CameraIdString,+ frame_number: int,+ charuco_observation: "CharucoObservation", # type: ignore+ coordinate_system: Literal["camera", "world"] = "camera",+ charuco_corner_radius: float = 0.005,+ aruco_corner_radius: float = 0.003,+ charuco_color: Color | None = None,+ aruco_color: Color | None = None,+ connection_color: Color | None = None,+ ) -> "Charuco3dData":+ """Create visualization data from CharucoObservation"""++ if charuco_color is None:+ charuco_color = Color.from_hex("#00FF00")+ if aruco_color is None:+ aruco_color = Color.from_hex("#FF0000")+ if connection_color is None:+ connection_color = Color.from_hex("#FFFFFF")++ if coordinate_system == "camera":+ if charuco_observation.detected_charuco_corners_in_camera_coordinates is None:+ raise ValueError(+ "Camera coordinates not computed. Call compute_board_pose_and_camera_coordinates first.")+ corner_coords = charuco_observation.detected_charuco_corners_in_camera_coordinates+ aruco_coords = charuco_observation.detected_aruco_markers_in_camera_coordinates+ else:+ corner_coords = charuco_observation.detected_charuco_corners_in_object_coordinates+ aruco_coords = None++ charuco_corner_spheres: dict[int, Sphere3d] = {}+ if (corner_coords is not None and+ charuco_observation.detected_charuco_corner_ids is not None):+ for i, corner_id in enumerate(charuco_observation.detected_charuco_corner_ids):+ corner_id_int = int(corner_id)+ position = Point3d.from_array(corner_coords[i])+ charuco_corner_spheres[corner_id_int] = Sphere3d(+ id=f"charuco_corner_{corner_id_int}",+ position=position,+ radius=charuco_corner_radius,+ color=charuco_color,+ label=f"C{corner_id_int}"+ )++ charuco_corner_connections: list[Line3d] = []++ aruco_markers: dict[int, ArucoMarker3d] = {}+ if (aruco_coords is not None and+ charuco_observation.detected_aruco_marker_ids is not None):+ for i, marker_id in enumerate(charuco_observation.detected_aruco_marker_ids):+ marker_id_int = int(marker_id)+ marker_corners = aruco_coords[i]++ corner_spheres = [+ Sphere3d(+ id=f"aruco_{marker_id_int}_corner_{j}",+ position=Point3d.from_array(marker_corners[j]),+ radius=aruco_corner_radius,+ color=aruco_color,+ label=None+ )+ for j in range(4)+ ]++ edge_lines = [+ Line3d(+ id=f"aruco_{marker_id_int}_edge_{j}",+ start=Point3d.from_array(marker_corners[j]),+ end=Point3d.from_array(marker_corners[(j + 1) % 4]),+ color=aruco_color,+ thickness=2.0+ )+ for j in range(4)+ ]++ center = np.mean(marker_corners, axis=0)+ center_sphere = Sphere3d(+ id=f"aruco_{marker_id_int}_center",+ position=Point3d.from_array(center),+ radius=aruco_corner_radius * 1.5,+ color=aruco_color,+ opacity=0.5,+ label=f"A{marker_id_int}"+ )++ aruco_markers[marker_id_int] = ArucoMarker3d(+ marker_id=marker_id_int,+ corner_spheres=corner_spheres,+ edge_lines=edge_lines,+ center_sphere=center_sphere+ )++ board_pose = None+ if charuco_observation.has_board_pose:+ board_pose = BoardPose3d.create_with_frame(+ rotation_vector=charuco_observation.charuco_board_rotation_vector,+ translation_vector=charuco_observation.charuco_board_translation_vector,+ frame_id=f"board_frame_{camera_id}",+ frame_scale=0.1,+ label=f"Board ({camera_id})"+ )++ all_corner_count = len(charuco_observation.all_charuco_ids)+ detected_corner_count = len(charuco_corner_spheres)+ detection_quality = detected_corner_count / all_corner_count if all_corner_count > 0 else 0.0++ return cls(+ camera_id=camera_id,+ frame_number=frame_number,+ coordinate_system=coordinate_system,+ charuco_corner_spheres=charuco_corner_spheres,+ charuco_corner_connections=charuco_corner_connections,+ aruco_markers=aruco_markers,+ board_pose=board_pose,+ all_corner_count=all_corner_count,+ detected_corner_count=detected_corner_count,+ detection_quality=detection_quality+ )+++class MultiCameraCharuco3dData(BaseModel):+ """Aggregated 3D data from multiple cameras"""+ model_config = ConfigDict(frozen=True)++ frame_number: int+ camera_data: dict[CameraIdString, Charuco3dData]+ world_data: Charuco3dData | None = None++ def get_all_spheres(self) -> list[Sphere3d]:+ """Get all spheres across all cameras for batch rendering"""+ spheres = []+ for cam_data in self.camera_data.values():+ spheres.extend(cam_data.charuco_corner_spheres.values())+ for marker in cam_data.aruco_markers.values():+ spheres.extend(marker.corner_spheres)+ if marker.center_sphere:+ spheres.append(marker.center_sphere)+ if self.world_data:+ spheres.extend(self.world_data.charuco_corner_spheres.values())+ return spheres++ def get_all_lines(self) -> list[Line3d]:+ """Get all lines across all cameras for batch rendering"""+ lines = []+ for cam_data in self.camera_data.values():+ lines.extend(cam_data.charuco_corner_connections)+ for marker in cam_data.aruco_markers.values():+ lines.extend(marker.edge_lines)+ if self.world_data:+ lines.extend(self.world_data.charuco_corner_connections)+ return lines++ @model_serializer+ def _serialize(self) -> dict[str, Any]:+ """Custom serialization to flatten structure for efficient websocket transmission"""+ return {+ "frame_number": self.frame_number,+ "cameras": {+ camera_id: cam_data.model_dump()+ for camera_id, cam_data in self.camera_data.items()+ },+ "all_spheres": [sphere.model_dump() for sphere in self.get_all_spheres()],+ "all_lines": [line.model_dump() for line in self.get_all_lines()],+ "world": self.world_data.model_dump() if self.world_data else None+ }diff --git a/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calibration_display_helpers/charuco_image_overlay_render.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calibration_display_helpers/charuco_image_overlay_render.pynew file mode 100644index 00000000..70ff79d5--- /dev/null+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calibration_display_helpers/charuco_image_overlay_render.py@@ -0,0 +1,89 @@+import logging++import numpy as np+from skellycam.core.types.type_overloads import CameraIdString+from skellytracker.trackers.charuco_tracker.charuco_observation import CharucoObservation++from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.calibration_helpers.calibration_display_helpers.charuco_python_converter import \+ charuco_observation_to_overlay_data, charuco_observation_to_metadata+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.calibration_helpers.calibration_display_helpers.charuco_topology_python import \+ create_charuco_topology+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.calibration_helpers.calibration_display_helpers.image_overlay_system import \+ OverlayRenderer++logger = logging.getLogger(__name__)+++class CameraOverlayRenderer:+ """Manages overlay rendering for a single camera using the overlay system."""++ def __init__(+ self,+ *,+ camera_id: CameraIdString,+ image_width: int,+ image_height: int,+ ):+ self.camera_id = camera_id+ self.image_width = image_width+ self.image_height = image_height++ # Create topology based on pipeline config+ self.topology = create_charuco_topology(+ width=self.image_width,+ height=self.image_height,+ show_charuco_corners=True,+ show_charuco_ids=True,+ show_aruco_markers=True,+ show_aruco_ids=True,+ show_board_outline=False, # Can make configurable+ max_charuco_corners=100,+ max_aruco_markers=30,+ )++ # Create renderer+ self.renderer = OverlayRenderer(topology=self.topology)++ logger.info(+ f"Initialized overlay renderer for camera {camera_id} "+ f"({image_width}x{image_height})"+ )++ def annotate_image(+ self,+ *,+ image: np.ndarray,+ charuco_observation: CharucoObservation,+ total_frames: int | None = None,+ ) -> np.ndarray:+ """+ Annotate image with charuco detection overlay.++ Args:+ image: OpenCV image (BGR numpy array)+ charuco_observation: Detection results+ total_frames: Total number of frames for progress display++ Returns:+ Annotated image (BGR numpy array)+ """+ try:+ # Convert observation to overlay format+ points = charuco_observation_to_overlay_data(charuco_observation)+ metadata = charuco_observation_to_metadata(+ charuco_observation,+ total_frames=total_frames+ )++ # Render overlay+ return self.renderer.composite_on_image(+ image=image,+ points=points,+ metadata=metadata+ )++ except Exception as e:+ logger.warning(+ f"Failed to annotate image for camera {self.camera_id}: {e}"+ )+ return image # Return original image if annotation failsdiff --git a/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calibration_display_helpers/charuco_python_converter.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calibration_display_helpers/charuco_python_converter.pynew file mode 100644index 00000000..84e210d1--- /dev/null+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calibration_display_helpers/charuco_python_converter.py@@ -0,0 +1,126 @@+"""+Convert CharucoObservation to overlay-compatible data format.+"""++from typing import Any++import numpy as np+from skellytracker.trackers.charuco_tracker.charuco_observation import CharucoObservation+++def charuco_observation_to_overlay_data(+ observation: CharucoObservation+) -> dict[str, dict[str, np.ndarray]]:+ """+ Convert CharucoObservation to overlay points format.++ Returns nested dict: {data_type: {point_name: [x, y]}}++ Structure:+ - 'charuco': Charuco corner points (charuco_0, charuco_1, ...)+ - 'aruco': ArUco marker corners (aruco_0_corner_0, aruco_0_corner_1, ...)+ """+ points: dict[str, dict[str, np.ndarray]] = {+ 'charuco': {},+ 'aruco': {}+ }++ # Add detected Charuco corners+ if not observation.charuco_empty:+ for corner_id, corner_coords in observation.charuco_corners_dict.items():+ points['charuco'][f'charuco_{corner_id}'] = corner_coords++ # Add detected ArUco marker corners+ if not observation.aruco_empty:+ for marker_id, marker_corners in observation.aruco_corners_dict.items():+ # ArUco markers have 4 corners+ for corner_idx in range(4):+ corner_name = f'aruco_{marker_id}_corner_{corner_idx}'+ points['aruco'][corner_name] = marker_corners[corner_idx]++ return points+++def charuco_observation_to_metadata(+ observation: CharucoObservation,+ total_frames: int | None = None+) -> dict[str, Any]:+ """+ Extract metadata from CharucoObservation for display.+ """+ metadata: dict[str, Any] = {+ 'frame_idx': observation.frame_number,+ 'total_frames': total_frames or 0,+ 'n_charuco_detected': 0 if observation.charuco_empty else len(observation.detected_charuco_corner_ids),+ 'n_charuco_total': len(observation.all_charuco_ids),+ 'n_aruco_detected': 0 if observation.aruco_empty else len(observation.detected_aruco_marker_ids),+ 'n_aruco_total': len(observation.all_aruco_ids),+ 'image_width': observation.image_size[0],+ 'image_height': observation.image_size[1],+ }++ # Add pose info if available+ if observation.charuco_board_translation_vector is not None:+ metadata['has_pose'] = True+ metadata['translation'] = observation.charuco_board_translation_vector.tolist()+ metadata['rotation'] = observation.charuco_board_rotation_vector.tolist()+ else:+ metadata['has_pose'] = False++ return metadata+++def stream_charuco_observations(+ observations: list[CharucoObservation]+) -> tuple[list[dict[str, dict[str, np.ndarray]]], list[dict[str, Any]]]:+ """+ Convert a list of observations to overlay format for batch processing.++ Returns:+ tuple of (points_list, metadata_list)+ """+ points_list = []+ metadata_list = []++ total_frames = len(observations)++ for obs in observations:+ points = charuco_observation_to_overlay_data(obs)+ metadata = charuco_observation_to_metadata(obs, total_frames)++ points_list.append(points)+ metadata_list.append(metadata)++ return points_list, metadata_list+++# Example usage with your existing code:+"""+from .image_overlay_system import overlay_image+from create_charuco_topology import create_charuco_topology++# Setup topology once+topology = create_charuco_topology(+ width=1920,+ height=1080,+ show_charuco_corners=True,+ show_charuco_ids=True,+ show_aruco_markers=True,+ show_aruco_ids=True+)++# For each frame+observation: CharucoObservation = ... # Your detection result++# Convert to overlay format+points = charuco_observation_to_overlay_data(observation)+metadata = charuco_observation_to_metadata(observation, total_frames=1000)++# Render+annotated_frame = overlay_image(+ image=frame,+ topology=topology,+ points=points,+ metadata=metadata+)+"""diff --git a/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calibration_display_helpers/charuco_topology_python.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calibration_display_helpers/charuco_topology_python.pynew file mode 100644index 00000000..b081f629--- /dev/null+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calibration_display_helpers/charuco_topology_python.py@@ -0,0 +1,258 @@+"""+Create Charuco board overlay topology with configurable visualization options.+"""++import numpy as np++from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.calibration_helpers.calibration_display_helpers.image_overlay_system import (+ OverlayTopology,+ ComputedPoint,+ PointElement,+ LineElement,+ TextElement,+ PointStyle,+ LineStyle,+ TextStyle,+)+++def create_charuco_topology(+ *,+ width: int,+ height: int,+ show_charuco_corners: bool = True,+ show_charuco_ids: bool = True,+ show_aruco_markers: bool = True,+ show_aruco_ids: bool = True,+ show_board_outline: bool = True,+ max_charuco_corners: int = 100,+ max_aruco_markers: int = 30,+) -> OverlayTopology:+ """+ Create a Charuco board overlay topology.++ Args:+ width: Image width in pixels+ height: Image height in pixels+ show_charuco_corners: Show detected Charuco corner points+ show_charuco_ids: Show Charuco corner ID labels+ show_aruco_markers: Show detected ArUco marker outlines+ show_aruco_ids: Show ArUco marker ID labels+ show_board_outline: Connect detected corners to show board outline+ max_charuco_corners: Maximum number of Charuco corners to support+ max_aruco_markers: Maximum number of ArUco markers to support++ Returns:+ Configured OverlayTopology instance+ """+ topology = OverlayTopology(+ name="charuco_board_tracking",+ width=width,+ height=height,+ required_points=[]+ )++ # === CHARUCO CORNERS ===++ if show_charuco_corners:+ charuco_style = PointStyle(+ radius=5,+ fill='rgb(0, 255, 0)', # Green+ stroke='rgb(0, 150, 0)',+ stroke_width=2,+ opacity=1.0+ )++ for corner_id in range(max_charuco_corners):+ topology.add(+ element=PointElement(+ name=f"charuco_corner_{corner_id}",+ point_name=('charuco', f'charuco_{corner_id}'),+ style=charuco_style,+ label=str(corner_id) if show_charuco_ids else None,+ label_offset=(8, -8),+ label_style=TextStyle(+ font_size=10,+ font_family='Arial, sans-serif',+ fill='rgb(0, 255, 0)',+ stroke='black',+ stroke_width=2,+ text_anchor='start'+ )+ )+ )++ # === ARUCO MARKERS ===++ if show_aruco_markers:+ aruco_line_style = LineStyle(+ stroke='rgb(255, 100, 0)', # Orange+ stroke_width=3,+ opacity=0.9+ )++ aruco_corner_style = PointStyle(+ radius=4,+ fill='rgb(255, 150, 0)',+ stroke='rgb(200, 80, 0)',+ stroke_width=1,+ opacity=1.0+ )++ for marker_id in range(max_aruco_markers):+ # Draw 4 corners+ for corner_idx in range(4):+ topology.add(+ element=PointElement(+ name=f"aruco_{marker_id}_corner_{corner_idx}",+ point_name=('aruco', f'aruco_{marker_id}_corner_{corner_idx}'),+ style=aruco_corner_style+ )+ )++ # Draw lines connecting corners (forming square)+ connections = [+ (0, 1), (1, 2), (2, 3), (3, 0)+ ]++ for idx, (corner_a, corner_b) in enumerate(connections):+ topology.add(+ element=LineElement(+ name=f"aruco_{marker_id}_line_{idx}",+ point_a=('aruco', f'aruco_{marker_id}_corner_{corner_a}'),+ point_b=('aruco', f'aruco_{marker_id}_corner_{corner_b}'),+ style=aruco_line_style+ )+ )++ # Add marker ID label at center+ if show_aruco_ids:+ def compute_aruco_center(points: dict[str, dict[str, np.ndarray]],+ mid: int = marker_id) -> np.ndarray:+ """Compute center of ArUco marker from its 4 corners."""+ if 'aruco' not in points:+ return np.array([np.nan, np.nan])++ corners = []+ for corner_idx in range(4):+ corner_name = f'aruco_{mid}_corner_{corner_idx}'+ if corner_name in points['aruco']:+ corners.append(points['aruco'][corner_name])++ if not corners:+ return np.array([np.nan, np.nan])++ stacked = np.stack(arrays=corners, axis=0)+ return np.nanmean(a=stacked, axis=0)++ topology.computed_points.append(+ ComputedPoint(+ data_type='computed',+ name=f'aruco_{marker_id}_center',+ computation=lambda pts, mid=marker_id: compute_aruco_center(pts, mid),+ description=f"Center of ArUco marker {marker_id}"+ )+ )++ topology.add(+ element=TextElement(+ name=f"aruco_{marker_id}_label",+ point_name=('computed', f'aruco_{marker_id}_center'),+ text=str(marker_id),+ offset=(0, 0),+ style=TextStyle(+ font_size=14,+ font_family='Arial, sans-serif',+ fill='rgb(255, 255, 255)',+ stroke='rgb(255, 100, 0)',+ stroke_width=3,+ font_weight='bold',+ text_anchor='start'+ )+ )+ )++ # === FRAME INFO ===++ topology.computed_points.append(+ ComputedPoint(+ data_type='computed',+ name='info_corner',+ computation=lambda pts: np.array([10.0, 25.0]),+ description="Top-left corner for info text"+ )+ )++ def format_charuco_info(metadata: dict[str, object]) -> str:+ """Generate dynamic frame info text."""+ frame_idx = metadata.get('frame_idx', 0)+ total_frames = metadata.get('total_frames', 0)+ n_charuco = metadata.get('n_charuco_detected', 0)+ n_charuco_total = metadata.get('n_charuco_total', 0)+ n_aruco = metadata.get('n_aruco_detected', 0)+ n_aruco_total = metadata.get('n_aruco_total', 0)+ has_pose = metadata.get('has_pose', False)+ pose_str = " | POSE โ" if has_pose else ""++ return (f"Frame: {frame_idx}/{total_frames} | "+ f"Charuco: {n_charuco}/{n_charuco_total} | "+ f"ArUco: {n_aruco}/{n_aruco_total}{pose_str}")++ topology.add(+ element=TextElement(+ name="frame_info",+ point_name=('computed', 'info_corner'),+ text=format_charuco_info,+ offset=(0, 0),+ style=TextStyle(+ font_size=16,+ font_family='Consolas, monospace',+ fill='white',+ stroke='black',+ stroke_width=2,+ text_anchor='start'+ )+ )+ )++ # === DETECTION STATUS ===++ topology.computed_points.append(+ ComputedPoint(+ data_type='computed',+ name='status_corner',+ computation=lambda pts: np.array([10.0, 55.0]),+ description="Status text position"+ )+ )++ def format_status(metadata: dict[str, object]) -> str:+ """Generate status message."""+ n_charuco = metadata.get('n_charuco_detected', 0)+ n_aruco = metadata.get('n_aruco_detected', 0)++ if n_charuco == 0 and n_aruco == 0:+ return "โ NO BOARD DETECTED"+ elif n_charuco < 4:+ return "โ INSUFFICIENT CORNERS"+ else:+ return "โ BOARD DETECTED"++ topology.add(+ element=TextElement(+ name="status_info",+ point_name=('computed', 'status_corner'),+ text=format_status,+ offset=(0, 0),+ style=TextStyle(+ font_size=14,+ font_family='Arial, sans-serif',+ fill='rgb(0, 255, 0)',+ stroke='black',+ stroke_width=2,+ text_anchor='start'+ )+ )+ )++ return topologydiff --git a/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calibration_display_helpers/image_overlay_system.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calibration_display_helpers/image_overlay_system.pynew file mode 100644index 00000000..15ebb5a7--- /dev/null+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calibration_display_helpers/image_overlay_system.py@@ -0,0 +1,514 @@+"""+OPTIMIZED overlay rendering system using OpenCV (much faster than PIL).+Key optimizations:+- Uses OpenCV drawing (no PIL conversions)+- Caches fonts and computed values+- Minimal allocations+- Vectorized operations where possible+"""++import json+from abc import ABC, abstractmethod+from typing import Any, Callable++import cv2+import numpy as np+from pydantic import BaseModel, Field, ConfigDict+++# ============================================================================+# STYLE CLASSES (unchanged)+# ============================================================================++class PointStyle(BaseModel):+ radius: int = 3+ fill: str = 'rgb(0, 255, 0)'+ stroke: str | None = None+ stroke_width: int | None = None+ opacity: float = 1.0+++class LineStyle(BaseModel):+ stroke: str = 'rgb(255, 55, 55)'+ stroke_width: int = 2+ opacity: float = 1.0+ stroke_dasharray: str | None = None+++class TextStyle(BaseModel):+ font_size: int = 12+ font_family: str = 'Arial, sans-serif'+ fill: str = 'white'+ stroke: str | None = 'black'+ stroke_width: int | None = 1+ font_weight: str = 'normal'+ text_anchor: str = 'start'+++# ============================================================================+# POINT REFERENCE SYSTEM (unchanged)+# ============================================================================++class PointReference(BaseModel):+ data_type: str+ name: str++ @classmethod+ def parse(cls, *, reference: str | tuple[str, str]) -> "PointReference":+ if isinstance(reference, PointReference):+ return reference+ elif isinstance(reference, tuple):+ return cls(data_type=reference[0], name=reference[1])+ elif isinstance(reference, str):+ if '.' in reference:+ parts = reference.split('.', maxsplit=1)+ elif '/' in reference:+ parts = reference.split('/', maxsplit=1)+ else:+ raise ValueError(f"Invalid point reference string: {reference}")+ if len(parts) != 2:+ raise ValueError(f"Invalid point reference: {reference}")+ return cls(data_type=parts[0], name=parts[1])+ else:+ raise ValueError(f"Invalid reference type: {type(reference)}")++ def get_point(self, *, points: dict[str, dict[str, np.ndarray]]) -> np.ndarray | None:+ data_type_dict = points.get(self.data_type)+ if data_type_dict is None:+ return None+ return data_type_dict.get(self.name)++ def __str__(self) -> str:+ return f"{self.data_type}.{self.name}"+++def is_valid_point(*, point: np.ndarray | None) -> bool:+ return point is not None and not np.isnan(point).any()+++# ============================================================================+# ELEMENT CLASSES - OPTIMIZED WITH CV2+# ============================================================================++class OverlayElement(BaseModel, ABC):+ model_config = ConfigDict(arbitrary_types_allowed=True)+ element_type: str+ name: str+ visible: bool = True++ @abstractmethod+ def render_cv2(+ self,+ *,+ image: np.ndarray,+ points: dict[str, dict[str, np.ndarray]],+ metadata: dict[str, Any],+ parse_rgb: Callable[[str], tuple[int, int, int]]+ ) -> None:+ """Render directly on OpenCV image (in-place)."""+ pass+++class PointElement(OverlayElement):+ element_type: str = 'point'+ point_ref: PointReference+ style: PointStyle = Field(default_factory=PointStyle)+ label: str | None = None+ label_offset: tuple[float, float] = (5, -5)+ label_style: TextStyle = Field(default_factory=TextStyle)++ def __init__(self, *, point_name: str | tuple[str, str] | PointReference, **kwargs: Any):+ point_ref = PointReference.parse(reference=point_name)+ super().__init__(point_ref=point_ref, **kwargs)++ def render_cv2(+ self,+ *,+ image: np.ndarray,+ points: dict[str, dict[str, np.ndarray]],+ metadata: dict[str, Any],+ parse_rgb: Callable[[str], tuple[int, int, int]]+ ) -> None:+ point = self.point_ref.get_point(points=points)+ if not is_valid_point(point=point):+ return++ x, y = int(point[0]), int(point[1])+ r = self.style.radius+ fill_color = parse_rgb(self.style.fill)++ # Draw filled circle+ cv2.circle(img=image, center=(x, y), radius=r, color=fill_color, thickness=-1)++ # Draw stroke if specified+ if self.style.stroke and self.style.stroke_width:+ stroke_color = parse_rgb(self.style.stroke)+ cv2.circle(img=image, center=(x, y), radius=r, color=stroke_color,+ thickness=self.style.stroke_width)++ # Draw label+ if self.label:+ label_x = int(x + self.label_offset[0])+ label_y = int(y + self.label_offset[1])++ font = cv2.FONT_HERSHEY_SIMPLEX+ font_scale = self.label_style.font_size / 30.0+ thickness = max(1, self.label_style.stroke_width or 1)++ # Draw stroke+ if self.label_style.stroke:+ stroke_color = parse_rgb(self.label_style.stroke)+ cv2.putText(img=image, text=self.label, org=(label_x, label_y),+ fontFace=font, fontScale=font_scale, color=stroke_color,+ thickness=thickness + 2, lineType=cv2.LINE_AA)++ # Draw text+ fill_color = parse_rgb(self.label_style.fill)+ cv2.putText(img=image, text=self.label, org=(label_x, label_y),+ fontFace=font, fontScale=font_scale, color=fill_color,+ thickness=thickness, lineType=cv2.LINE_AA)+++class LineElement(OverlayElement):+ element_type: str = 'line'+ point_a_ref: PointReference+ point_b_ref: PointReference+ style: LineStyle = Field(default_factory=LineStyle)++ def __init__(+ self,+ *,+ point_a: str | tuple[str, str] | PointReference,+ point_b: str | tuple[str, str] | PointReference,+ **kwargs: Any+ ):+ point_a_ref = PointReference.parse(reference=point_a)+ point_b_ref = PointReference.parse(reference=point_b)+ super().__init__(point_a_ref=point_a_ref, point_b_ref=point_b_ref, **kwargs)++ def render_cv2(+ self,+ *,+ image: np.ndarray,+ points: dict[str, dict[str, np.ndarray]],+ metadata: dict[str, Any],+ parse_rgb: Callable[[str], tuple[int, int, int]]+ ) -> None:+ pt_a = self.point_a_ref.get_point(points=points)+ pt_b = self.point_b_ref.get_point(points=points)++ if not (is_valid_point(point=pt_a) and is_valid_point(point=pt_b)):+ return++ p1 = (int(pt_a[0]), int(pt_a[1]))+ p2 = (int(pt_b[0]), int(pt_b[1]))+ color = parse_rgb(self.style.stroke)++ cv2.line(img=image, pt1=p1, pt2=p2, color=color,+ thickness=self.style.stroke_width, lineType=cv2.LINE_AA)+++class CircleElement(OverlayElement):+ element_type: str = 'circle'+ center_ref: PointReference+ radius: float+ style: PointStyle = Field(default_factory=PointStyle)++ def __init__(self, *, center_point: str | tuple[str, str] | PointReference, **kwargs: Any):+ center_ref = PointReference.parse(reference=center_point)+ super().__init__(center_ref=center_ref, **kwargs)++ def render_cv2(+ self,+ *,+ image: np.ndarray,+ points: dict[str, dict[str, np.ndarray]],+ metadata: dict[str, Any],+ parse_rgb: Callable[[str], tuple[int, int, int]]+ ) -> None:+ center = self.center_ref.get_point(points=points)+ if not is_valid_point(point=center):+ return++ cx, cy = int(center[0]), int(center[1])+ r = int(self.radius)+ fill_color = parse_rgb(self.style.fill)++ cv2.circle(img=image, center=(cx, cy), radius=r, color=fill_color, thickness=-1)++ if self.style.stroke and self.style.stroke_width:+ stroke_color = parse_rgb(self.style.stroke)+ cv2.circle(img=image, center=(cx, cy), radius=r, color=stroke_color,+ thickness=self.style.stroke_width)+++class CrosshairElement(OverlayElement):+ element_type: str = 'crosshair'+ center_ref: PointReference+ size: float = 10+ style: LineStyle = Field(default_factory=LineStyle)++ def __init__(self, *, center_point: str | tuple[str, str] | PointReference, **kwargs: Any):+ center_ref = PointReference.parse(reference=center_point)+ super().__init__(center_ref=center_ref, **kwargs)++ def render_cv2(+ self,+ *,+ image: np.ndarray,+ points: dict[str, dict[str, np.ndarray]],+ metadata: dict[str, Any],+ parse_rgb: Callable[[str], tuple[int, int, int]]+ ) -> None:+ center = self.center_ref.get_point(points=points)+ if not is_valid_point(point=center):+ return++ cx, cy = int(center[0]), int(center[1])+ size = int(self.size)+ color = parse_rgb(self.style.stroke)++ cv2.line(img=image, pt1=(cx - size, cy), pt2=(cx + size, cy),+ color=color, thickness=self.style.stroke_width, lineType=cv2.LINE_AA)+ cv2.line(img=image, pt1=(cx, cy - size), pt2=(cx, cy + size),+ color=color, thickness=self.style.stroke_width, lineType=cv2.LINE_AA)+++class TextElement(OverlayElement):+ element_type: str = 'text'+ point_ref: PointReference+ text: str | Callable[[dict[str, Any]], str]+ offset: tuple[float, float] = (0, 0)+ style: TextStyle = Field(default_factory=TextStyle)++ def __init__(self, *, point_name: str | tuple[str, str] | PointReference, **kwargs: Any):+ point_ref = PointReference.parse(reference=point_name)+ super().__init__(point_ref=point_ref, **kwargs)++ def render_cv2(+ self,+ *,+ image: np.ndarray,+ points: dict[str, dict[str, np.ndarray]],+ metadata: dict[str, Any],+ parse_rgb: Callable[[str], tuple[int, int, int]]+ ) -> None:+ point = self.point_ref.get_point(points=points)+ if not is_valid_point(point=point):+ return++ x = int(point[0] + self.offset[0])+ y = int(point[1] + self.offset[1])++ # Get text+ if callable(self.text):+ text_to_render = self.text(metadata)+ else:+ text_to_render = self.text++ font = cv2.FONT_HERSHEY_SIMPLEX+ font_scale = self.style.font_size / 30.0+ thickness = max(1, self.style.stroke_width or 1)++ # Draw stroke (simplified - just one extra layer)+ if self.style.stroke:+ stroke_color = parse_rgb(self.style.stroke)+ cv2.putText(img=image, text=text_to_render, org=(x, y),+ fontFace=font, fontScale=font_scale, color=stroke_color,+ thickness=thickness + 2, lineType=cv2.LINE_AA)++ # Draw text+ fill_color = parse_rgb(self.style.fill)+ cv2.putText(img=image, text=text_to_render, org=(x, y),+ fontFace=font, fontScale=font_scale, color=fill_color,+ thickness=thickness, lineType=cv2.LINE_AA)+++class EllipseElement(OverlayElement):+ element_type: str = 'ellipse'+ params_ref: PointReference+ n_points: int = 100+ style: LineStyle = Field(default_factory=LineStyle)+ _ellipse_cache: dict[tuple, np.ndarray] = {}++ def __init__(self, *, params_point: str | tuple[str, str] | PointReference, **kwargs: Any):+ params_ref = PointReference.parse(reference=params_point)+ super().__init__(params_ref=params_ref, **kwargs)++ def render_cv2(+ self,+ *,+ image: np.ndarray,+ points: dict[str, dict[str, np.ndarray]],+ metadata: dict[str, Any],+ parse_rgb: Callable[[str], tuple[int, int, int]]+ ) -> None:+ params = self.params_ref.get_point(points=points)+ if params is None or len(params) != 5 or np.isnan(params).any():+ return++ cx, cy, semi_major, semi_minor, rotation = params+ center = (int(cx), int(cy))+ axes = (int(semi_major), int(semi_minor))+ angle = int(np.degrees(rotation))+ color = parse_rgb(self.style.stroke)++ cv2.ellipse(img=image, center=center, axes=axes, angle=angle,+ startAngle=0, endAngle=360, color=color,+ thickness=self.style.stroke_width, lineType=cv2.LINE_AA)+++# ============================================================================+# TOPOLOGY (unchanged structure)+# ============================================================================++class ComputedPoint(BaseModel):+ model_config = ConfigDict(arbitrary_types_allowed=True)+ data_type: str+ name: str+ computation: Callable[[dict[str, dict[str, np.ndarray]]], np.ndarray]+ description: str = ""+++class OverlayTopology(BaseModel):+ model_config = ConfigDict(arbitrary_types_allowed=True)+ name: str+ required_points: list[tuple[str, str]] = Field(default_factory=list)+ computed_points: list[ComputedPoint] = Field(default_factory=list)+ elements: list[OverlayElement] = Field(default_factory=list)+ width: int = 640+ height: int = 480++ def add(self, *, element: OverlayElement) -> "OverlayTopology":+ self.elements.append(element)+ return self++ def to_json_dict(self) -> dict[str, Any]:+ return {+ 'name': self.name,+ 'required_points': self.required_points,+ 'width': self.width,+ 'height': self.height,+ 'elements': [json.loads(elem.model_dump_json()) for elem in self.elements]+ }++ def to_json(self) -> str:+ return json.dumps(self.to_json_dict(), indent=2)++ def save_json(self, *, filepath: str) -> None:+ with open(filepath, 'w') as f:+ f.write(self.to_json())+++# ============================================================================+# OPTIMIZED RENDERER+# ============================================================================++class OverlayRenderer(BaseModel):+ """OPTIMIZED: Uses OpenCV directly, no PIL conversions."""+ model_config = ConfigDict(arbitrary_types_allowed=True)++ topology: OverlayTopology+ color_map: dict[str, tuple[int, int, int]] = Field(default_factory=dict, init=False)++ def model_post_init(self, __context: Any) -> None:+ """Initialize color map (BGR for OpenCV)."""+ self.color_map = {+ 'red': (0, 0, 255), 'green': (0, 255, 0),+ 'blue': (255, 0, 0), 'yellow': (0, 255, 255),+ 'lime': (0, 255, 0), 'white': (255, 255, 255),+ 'black': (0, 0, 0), 'cyan': (255, 255, 0),+ 'magenta': (255, 0, 255), 'orange': (0, 165, 255),+ }++ def _parse_rgb(self, color: str) -> tuple[int, int, int]:+ """Parse color to BGR tuple for OpenCV."""+ color = color.strip().lower()++ if color.startswith('rgb(') and color.endswith(')'):+ values = color[4:-1].split(',')+ r, g, b = [int(v.strip()) for v in values]+ return (b, g, r) # BGR for OpenCV++ return self.color_map.get(color, (255, 255, 255))++ def _compute_all_points(+ self,+ *,+ points: dict[str, dict[str, np.ndarray]]+ ) -> dict[str, dict[str, np.ndarray]]:+ """Compute derived points WITHOUT deep copy."""+ # OPTIMIZED: Share dictionaries when possible+ all_points = points.copy() # Shallow copy is sufficient++ # Compute derived points+ for computed in self.topology.computed_points:+ try:+ result = computed.computation(all_points)++ if computed.data_type not in all_points:+ all_points[computed.data_type] = {}++ all_points[computed.data_type][computed.name] = result+ except Exception:+ # Silently skip failed computations+ pass++ return all_points++ def composite_on_image(+ self,+ *,+ image: np.ndarray,+ points: dict[str, dict[str, np.ndarray]],+ metadata: dict[str, Any] | None = None+ ) -> np.ndarray:+ """+ OPTIMIZED: Draw directly on image copy using OpenCV.++ Args:+ image: OpenCV BGR image+ points: Nested dict of points+ metadata: Optional metadata++ Returns:+ Annotated BGR image+ """+ if metadata is None:+ metadata = {}++ # OPTIMIZED: Single copy, no conversions+ output = image.copy()++ all_points = self._compute_all_points(points=points)++ # Render all elements directly+ for element in self.topology.elements:+ if element.visible:+ element.render_cv2(+ image=output,+ points=all_points,+ metadata=metadata,+ parse_rgb=self._parse_rgb+ )++ return output+++# ============================================================================+# CONVENIENCE FUNCTION+# ============================================================================++def overlay_image(+ *,+ image: np.ndarray,+ topology: OverlayTopology,+ points: dict[str, dict[str, np.ndarray]],+ metadata: dict[str, Any] | None = None+) -> np.ndarray:+ """Convenience function to render overlay on image."""+ return OverlayRenderer(topology=topology).composite_on_image(+ image=image,+ points=points,+ metadata=metadata+ )diff --git a/freemocap/core/pipelines/calibration_pipeline/calibration_numpy_types.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calibration_numpy_types.pysimilarity index 61%rename from freemocap/core/pipelines/calibration_pipeline/calibration_numpy_types.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calibration_numpy_types.pyindex 4ffaf1e9..eba1efb0 100644--- a/freemocap/core/pipelines/calibration_pipeline/calibration_numpy_types.py+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/calibration_numpy_types.py@@ -5,7 +5,8 @@ ReprojectionError = floatImagePoint2D = NDArray[Shape["2 pixelx_pixely"], np.float64]ImagePoints2D = NDArray[Shape["* n_points, 2 pixelx_pixely"], np.float64]-ImagePoints2DByCamera = NDArray[Shape["* n_cams, * n_points, 2 pixelx_pixely"], np.float64] # e.g. Image coordinates of a point in 3d space projected onto each camera+ImagePoints2DByCamera = NDArray[Shape[+ "* n_cams, * n_points, 2 pixelx_pixely"], np.float64] # e.g. Image coordinates of a point in 3d space projected onto each cameraObjectPoint3D = NDArray[Shape["3 xyz"], np.float64]ObjectPoints3D = NDArray[Shape["* n_points, 3 xyz"], np.float64]@@ -22,18 +23,19 @@ CameraMatrixArray = NDArray[Shape["3 rows, 3 columns"], np.float64]CameraExtrinsicsMatrix = NDArray[Shape["3 rows, 4 columns"], np.float64]CameraMatrixByCamera = NDArray[Shape["* n_cams, 3 rows, 3 columns"], np.float64]CameraExtrinsicsMatrixByCamera = NDArray[Shape["* n_cams, 4 rows, 4 columns"], np.float64]-TransformationMatrixArray = NDArray[Shape["4 rows, 4 columns"], np.float64] # 4x4 matrix that transforms points from the camera coordinate system to the world coordinate system. 3x3 in the upper left is the rotation matrix, and the rightmost column is the translation vector. The bottom row is [0, 0, 0, 1] (where the 1 is the homogeneous coordinate, which makes the matrix invertible and provides the scale factor for the translation vector to put it in spatial coordinates--CameraDistortionCoefficientsArray = NDArray[Shape["4-14 k1_k2_p1_p2_k3_k4_k5_k6"], np.float64] # Can be 4,5,8,12, or 14 elements+TransformationMatrixArray = NDArray[Shape[+ "4 rows, 4 columns"], np.float64] # 4x4 matrix that transforms points from the camera coordinate system to the world coordinate system. 3x3 in the upper left is the rotation matrix, and the rightmost column is the translation vector. The bottom row is [0, 0, 0, 1] (where the 1 is the homogeneous coordinate, which makes the matrix invertible and provides the scale factor for the translation vector to put it in spatial coordinates+CameraDistortionCoefficientsArray = NDArray[+ Shape["4-14 k1_k2_p1_p2_k3_k4_k5_k6"], np.float64] # Can be 4,5,8,12, or 14 elementsExtrinsicsParameters = NDArray[Shape["6 translation_rotation"], np.float64] # 3 for rotation, 3 for translation-IntrinsicsParameters = NDArray[Shape["*, ..."], np.float64] # focal length, variable number of distortion coefficients (2, 4, 5, 8, 12, or 14)+IntrinsicsParameters = NDArray[+ Shape["*, ..."], np.float64] # focal length, variable number of distortion coefficients (2, 4, 5, 8, 12, or 14)ExtrinsicsParametersByCamera = NDArray[Shape["* n_cams, 6 translation_rotation"], np.float64]IntrinsicsParametersByCamera = NDArray[Shape["* n_cams, * focal_length_distortion"], np.float64]JacobianMatrixArray = NDArray[Shape["* m_n_error_function_returns, * n_parameters"], np.float64]--SparseBundleOptimizerGuess1D = NDArray[Shape["* n_parameters"], np.float64]\ No newline at end of file+SparseBundleOptimizerGuess1D = NDArray[Shape["* n_parameters"], np.float64]diff --git a/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/charuco_view_optimizer.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/charuco_view_optimizer.pynew file mode 100644index 00000000..f1d8dfef--- /dev/null+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/charuco_view_optimizer.py@@ -0,0 +1,372 @@+import logging+from typing import Protocol++import numpy as np+from pydantic import BaseModel, Field+from scipy.spatial.distance import cdist+from sklearn.cluster import KMeans++logger = logging.getLogger(__name__)+++class ObservationProtocol(Protocol):+ """Protocol for observations that can be optimized."""+ detected_charuco_corners_image_coordinates: np.ndarray+ frame_number: int+++class CharucoViewSelectionConfig(BaseModel):+ """Configuration for view selection optimization."""+ target_view_count: int = Field(default=30, ge=1, le=200)+ initial_view_count: int = Field(default=15, ge=5, le=50)+ grid_size: tuple[int, int] = Field(default=(3, 3))+ min_coverage_per_cell: float = Field(default=0.5, ge=0.0, le=1.0)+ coverage_weight: float = Field(default=0.6, ge=0.0, le=1.0)+ diversity_weight: float = Field(default=0.4, ge=0.0, le=1.0)+++class CharucoViewOptimizer:+ """+ Two-stage view optimizer for camera calibration:++ Stage 1: Select initial subset using coverage + spatial diversity (no pose info needed)+ Stage 2: Select optimal subset using coverage + pose diversity (requires pose estimates)++ Workflow:+ 1. Call select_initial_views() -> get indices for quick calibration+ 2. Calibrate camera using initial views (external)+ 3. Estimate poses for ALL views using calibration (external)+ 4. Call select_final_views() with pose data -> get optimal subset+ 5. Perform final calibration on optimal subset (external)++ References:+ - OpenCV recommends 20-40 images for calibration+ - Above 100 images provides diminishing returns with exponential computation cost+ """++ def __init__(+ self,+ image_size: tuple[int, int],+ config: CharucoViewSelectionConfig = CharucoViewSelectionConfig()+ ):+ self.image_size = image_size+ self.config = config+ self.width = image_size[0]+ self.height = image_size[1]++ def select_initial_views(+ self,+ observations: list[ObservationProtocol]+ ) -> list[int]:+ """+ Stage 1: Select initial subset for bootstrapping calibration.++ Uses only coverage and spatial diversity (no pose information required).+ This subset should be used for a quick initial calibration to obtain+ camera parameters for pose estimation.++ Args:+ observations: All available observations++ Returns:+ Indices of observations for initial calibration++ Raises:+ ValueError: If no observations provided+ """+ if len(observations) == 0:+ raise ValueError("No observations provided")++ target = self.config.initial_view_count++ if len(observations) <= target:+ logger.info(f"Using all {len(observations)} views for initial calibration")+ return list(range(len(observations)))++ logger.info(f"Selecting {target} initial views from {len(observations)} for bootstrapping")++ coverage_scores = self._compute_coverage_scores(observations=observations)+ diversity_scores = self._compute_spatial_diversity_scores(observations=observations)++ combined_scores = (+ self.config.coverage_weight * coverage_scores ++ self.config.diversity_weight * diversity_scores+ )++ selected_indices = np.argsort(combined_scores)[-target:]+ selected_indices = sorted(selected_indices.tolist())++ logger.info(f"Selected {len(selected_indices)} initial views")+ return selected_indices++ def select_final_views(+ self,+ observations: list[ObservationProtocol],+ rotation_vectors: list[np.ndarray],+ translation_vectors: list[np.ndarray]+ ) -> list[int]:+ """+ Stage 2: Select optimal final subset using pose information.++ Uses coverage + pose-based diversity for optimal view selection.+ Requires pose estimates for ALL observations (from initial calibration).++ Args:+ observations: All available observations+ rotation_vectors: Rotation vectors for all observations (from pose estimation)+ translation_vectors: Translation vectors for all observations (from pose estimation)++ Returns:+ Indices of observations for final calibration++ Raises:+ ValueError: If inputs are invalid or mismatched lengths+ """+ if len(observations) == 0:+ raise ValueError("No observations provided")++ if len(rotation_vectors) != len(observations):+ raise ValueError(+ f"Rotation vectors length ({len(rotation_vectors)}) "+ f"must match observations length ({len(observations)})"+ )++ if len(translation_vectors) != len(observations):+ raise ValueError(+ f"Translation vectors length ({len(translation_vectors)}) "+ f"must match observations length ({len(observations)})"+ )++ target = self.config.target_view_count++ if len(observations) <= target:+ logger.info(f"Using all {len(observations)} views for final calibration")+ return list(range(len(observations)))++ logger.info(f"Selecting {target} optimal views from {len(observations)}")++ coverage_scores = self._compute_coverage_scores(observations=observations)+ diversity_scores = self._compute_pose_diversity_scores(+ rotation_vectors=rotation_vectors,+ translation_vectors=translation_vectors+ )++ combined_scores = (+ self.config.coverage_weight * coverage_scores ++ self.config.diversity_weight * diversity_scores+ )++ selected_indices = np.argsort(combined_scores)[-target:]+ selected_indices = sorted(selected_indices.tolist())++ logger.info(+ f"Selected {len(selected_indices)} final views - "+ f"mean coverage: {coverage_scores[selected_indices].mean():.3f}, "+ f"mean diversity: {diversity_scores[selected_indices].mean():.3f}"+ )++ return selected_indices++ def _compute_coverage_scores(+ self,+ observations: list[ObservationProtocol]+ ) -> np.ndarray:+ """+ Compute spatial coverage score for each observation.++ Score based on:+ 1. Number of grid cells covered+ 2. Uniformity of coverage across cells+ 3. Edge/corner coverage bonus+ """+ grid_rows, grid_cols = self.config.grid_size+ cell_height = self.height / grid_rows+ cell_width = self.width / grid_cols++ scores = np.zeros(len(observations))++ for idx, obs in enumerate(observations):+ points = obs.detected_charuco_corners_image_coordinates+ if len(points) == 0:+ scores[idx] = 0.0+ continue++ grid_coverage = np.zeros((grid_rows, grid_cols), dtype=bool)++ for point in points:+ x, y = point[0], point[1]+ grid_row = int(min(y / cell_height, grid_rows - 1))+ grid_col = int(min(x / cell_width, grid_cols - 1))+ grid_coverage[grid_row, grid_col] = True++ coverage_ratio = grid_coverage.sum() / (grid_rows * grid_cols)++ edge_bonus = self._compute_edge_coverage_bonus(+ points=points,+ grid_coverage=grid_coverage,+ grid_rows=grid_rows,+ grid_cols=grid_cols+ )++ density_bonus = min(len(points) / 50.0, 1.0) * 0.2++ scores[idx] = coverage_ratio + edge_bonus + density_bonus++ if scores.max() > 0:+ scores = scores / scores.max()++ return scores++ def _compute_edge_coverage_bonus(+ self,+ points: np.ndarray,+ grid_coverage: np.ndarray,+ grid_rows: int,+ grid_cols: int+ ) -> float:+ """Compute bonus for covering edge and corner regions."""+ top_edge = grid_coverage[0, :].any()+ bottom_edge = grid_coverage[-1, :].any()+ left_edge = grid_coverage[:, 0].any()+ right_edge = grid_coverage[:, -1].any()++ edge_coverage_count = sum([top_edge, bottom_edge, left_edge, right_edge])++ corners_covered = 0+ corner_regions = [+ (0, 0), (0, grid_cols - 1),+ (grid_rows - 1, 0), (grid_rows - 1, grid_cols - 1)+ ]+ for row, col in corner_regions:+ if grid_coverage[row, col]:+ corners_covered += 1++ edge_bonus = (edge_coverage_count / 4.0) * 0.15+ corner_bonus = (corners_covered / 4.0) * 0.15++ return edge_bonus + corner_bonus++ def _compute_pose_diversity_scores(+ self,+ rotation_vectors: list[np.ndarray],+ translation_vectors: list[np.ndarray]+ ) -> np.ndarray:+ """+ Compute diversity scores based on pose clustering.++ Views with unique poses get higher scores.+ """+ if len(rotation_vectors) == 0:+ raise ValueError("No rotation vectors provided")++ pose_features = []+ for rvec, tvec in zip(rotation_vectors, translation_vectors):+ rvec_norm = rvec.flatten() / (np.linalg.norm(rvec) + 1e-8)+ tvec_norm = tvec.flatten() / (np.linalg.norm(tvec) + 1e-8)+ pose_features.append(np.concatenate([rvec_norm, tvec_norm]))++ pose_features_array = np.array(pose_features)++ n_clusters = min(self.config.target_view_count, len(pose_features_array))+ if n_clusters < 2:+ return np.ones(len(pose_features_array))++ try:+ kmeans = KMeans(n_clusters=n_clusters, random_state=42, n_init=10)+ cluster_labels = kmeans.fit_predict(pose_features_array)+ except Exception as e:+ logger.warning(f"Pose clustering failed: {e}, using uniform scores")+ return np.ones(len(pose_features_array))++ scores = np.zeros(len(pose_features_array))++ for cluster_id in range(n_clusters):+ cluster_mask = cluster_labels == cluster_id+ cluster_size = cluster_mask.sum()++ if cluster_size == 0:+ continue++ cluster_center = kmeans.cluster_centers_[cluster_id]+ cluster_points = pose_features_array[cluster_mask]++ distances = cdist(cluster_points, cluster_center.reshape(1, -1)).flatten()++ if distances.max() > 0:+ normalized_distances = 1.0 - (distances / distances.max())+ else:+ normalized_distances = np.ones(len(distances))++ cluster_weight = 1.0 / np.sqrt(cluster_size)++ scores[cluster_mask] = normalized_distances * cluster_weight++ if scores.max() > 0:+ scores = scores / scores.max()++ return scores++ def _compute_spatial_diversity_scores(+ self,+ observations: list[ObservationProtocol]+ ) -> np.ndarray:+ """+ Compute diversity based on spatial distribution of points.++ Used in stage 1 when pose information is not available.+ """+ scores = np.zeros(len(observations))++ for idx, obs in enumerate(observations):+ points = obs.detected_charuco_corners_image_coordinates+ if len(points) < 2:+ scores[idx] = 0.0+ continue++ x_coords = points[:, 0]+ y_coords = points[:, 1]++ x_spread = np.std(x_coords) / self.width+ y_spread = np.std(y_coords) / self.height++ scores[idx] = (x_spread + y_spread) / 2.0++ if scores.max() > 0:+ scores = scores / scores.max()++ return scores++ def compute_coverage_heatmap(+ self,+ observations: list[ObservationProtocol],+ selected_indices: list[int] | None = None+ ) -> np.ndarray:+ """+ Compute a heatmap showing coverage across the image.++ Args:+ observations: All observations+ selected_indices: Indices to visualize (if None, uses all observations)++ Returns:+ Heatmap array of shape (grid_rows, grid_cols)+ """+ grid_rows, grid_cols = self.config.grid_size+ cell_height = self.height / grid_rows+ cell_width = self.width / grid_cols++ heatmap = np.zeros((grid_rows, grid_cols))++ indices_to_use = selected_indices if selected_indices is not None else range(len(observations))++ for idx in indices_to_use:+ obs = observations[idx]+ points = obs.detected_charuco_corners_image_coordinates++ for point in points:+ x, y = point[0], point[1]+ grid_row = int(min(y / cell_height, grid_rows - 1))+ grid_col = int(min(x / cell_width, grid_cols - 1))+ heatmap[grid_row, grid_col] += 1++ return heatmapdiff --git a/freemocap/core/pipelines/calibration_pipeline/least_squares_optimizer.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/least_squares_optimizer.pysimilarity index 78%rename from freemocap/core/pipelines/calibration_pipeline/least_squares_optimizer.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/least_squares_optimizer.pyindex dd0eb0eb..ffd417f7 100644--- a/freemocap/core/pipelines/calibration_pipeline/least_squares_optimizer.py+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/least_squares_optimizer.py@@ -3,35 +3,37 @@ from pydantic import BaseModelfrom pydantic import model_validatorfrom scipy import optimizefrom scipy.sparse import dok_matrix-from skellycam import CameraId+from skellycam.core.types.type_overloads import CameraIdStringfrom typing_extensions import Self-from freemocap.core.pipelines.calibration_pipeline.calibration_numpy_types import \+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.calibration_helpers.calibration_numpy_types import \ImagePoints2D, ImagePoint2D, CameraExtrinsicsMatrix-from freemocap.core.pipelines.calibration_pipeline.camera_math_models import TransformationMatrix-from freemocap.core.pipelines.calibration_pipeline.shared_view_accumulator import MultiCameraTargetView, MultiFrameNumber-from freemocap.core.pipelines.calibration_pipeline.single_camera_calibrator import CameraIntrinsicsEstimate-from freemocap.core.pipelines.calibration_pipeline.triangulate_points import undistort_points, \+from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.camera_math_models import TransformationMatrix+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.calibration_helpers.single_camera_calibrator import \+ CameraIntrinsicsEstimate+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.calibration_helpers.triangulate_points import undistort_points, \calculate_reprojection_error, triangulate_point+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.shared_view_accumulator import MultiCameraTargetView, \+ MultiFrameNumberclass SparseBundleOptimizer(BaseModel):- principal_camera_id: CameraId- initial_guess: dict[CameraId, CameraExtrinsicsMatrix]- image_points_by_camera: dict[CameraId, list[ImagePoint2D]]- camera_intrinsics: dict[CameraId, CameraIntrinsicsEstimate]- image_sizes: dict[CameraId, tuple[int, int]]+ principal_camera_id: CameraIdString+ initial_guess: dict[CameraIdString, CameraExtrinsicsMatrix]+ image_points_by_camera: dict[CameraIdString, list[ImagePoint2D]]+ camera_intrinsics: dict[CameraIdString, CameraIntrinsicsEstimate]+ image_sizes: dict[CameraIdString, tuple[int, int]]@classmethoddef create(cls,- principal_camera_id: CameraId,- camera_extrinsics_by_camera_id: dict[CameraId, CameraExtrinsicsMatrix],+ principal_camera_id: CameraIdString,+ camera_extrinsics_by_camera_id: dict[CameraIdString, CameraExtrinsicsMatrix],multi_camera_target_views: dict[MultiFrameNumber, MultiCameraTargetView],- camera_intrinsics: dict[CameraId, CameraIntrinsicsEstimate],- image_sizes: dict[CameraId, tuple[int, int]]+ camera_intrinsics: dict[CameraIdString, CameraIntrinsicsEstimate],+ image_sizes: dict[CameraIdString, tuple[int, int]]) -> "SparseBundleOptimizer":- image_points_by_camera: dict[CameraId, list[ImagePoint2D]] = {camera_id: [] for camera_id in- camera_intrinsics.keys()}+ image_points_by_camera: dict[CameraIdString, list[ImagePoint2D]] = {camera_id: [] for camera_id in+ camera_intrinsics.keys()}for frame_number, target_view in multi_camera_target_views.items():for camera_id, image_points in target_view.image_points_by_camera.items():image_points_by_camera[camera_id].extend(image_points)@@ -91,7 +93,7 @@ class SparseBundleOptimizer(BaseModel):jac="3-point", # TODO- could prob use `callable` and calc the jacobian dynamicallyf_scale=50.0, # TODO - Not sure where this number comes fromx_scale="jac",- loss="cauchy",#"linear", # TODO - try `soft_l1` or `cauchy`+ loss="cauchy", # "linear", # TODO - try `soft_l1` or `cauchy`# ftol=1e-4,method="trf",verbose=2,@@ -106,17 +108,17 @@ class SparseBundleOptimizer(BaseModel):def error_function(self,current_guess: list[float],- camera_intrinsics: dict[CameraId, CameraIntrinsicsEstimate],- image_points_by_camera: dict[CameraId, ImagePoints2D],- principal_camera_id: CameraId,- image_sizes: dict[CameraId, tuple[int, int]]+ camera_intrinsics: dict[CameraIdString, CameraIntrinsicsEstimate],+ image_points_by_camera: dict[CameraIdString, ImagePoints2D],+ principal_camera_id: CameraIdString,+ image_sizes: dict[CameraIdString, tuple[int, int]]) -> list[float]:# reform 'current_guess' into camera extrinsics matriciescamera_ids = list(self.camera_intrinsics.keys())- camera_transforms: dict[CameraId, TransformationMatrix] = {}- camera_extrinsics: dict[CameraId, CameraExtrinsicsMatrix] = {}- undistored_image_points: dict[CameraId, ImagePoints2D] = {}+ camera_transforms: dict[CameraIdString, TransformationMatrix] = {}+ camera_extrinsics: dict[CameraIdString, CameraExtrinsicsMatrix] = {}+ undistored_image_points: dict[CameraIdString, ImagePoints2D] = {}for camera_index, camera_id in enumerate(camera_ids):# split the 1d vector by camera based on `self.number_of_parameters_per_camera`starting_index = camera_index * self.number_of_parameters_per_cameradiff --git a/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/multi_camera_calibrator.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/multi_camera_calibrator.pynew file mode 100644index 00000000..28b5dcaf--- /dev/null+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/multi_camera_calibrator.py@@ -0,0 +1,470 @@+import logging++import cv2+import numpy as np+from pydantic import BaseModel+from skellycam.core.types.type_overloads import CameraIdString++from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.camera_math_models import (+ TransformationMatrix,+ RotationVector,+ TranslationVector,+)+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.calibration_helpers.single_camera_calibrator import (+ CameraIntrinsicsEstimate,+ SingleCameraCalibrator,+)+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.pyceres_bundle_adjuster import PyCeresBundleAdjuster+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.scipy_bundle_adjuster import ScipyBundleAdjuster+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.shared_view_accumulator import (+ SharedViewAccumulator,+ CameraPair,+)+from freemocap.pubsub.pubsub_topics import CameraNodeOutputMessage++logger = logging.getLogger(__name__)+++class MultiCameraCalibrationEstimate(BaseModel):+ principal_camera_id: CameraIdString+ camera_transforms_by_camera_id: dict[CameraIdString, TransformationMatrix]+++class MultiCameraCalibrator(BaseModel):+ principal_camera_id: CameraIdString+ camera_id_to_index: dict[CameraIdString, int]+ multi_cam_output_accumulator: SharedViewAccumulator++ single_camera_calibrators: dict[CameraIdString, SingleCameraCalibrator] | None = None+ multi_camera_calibration_estimate: MultiCameraCalibrationEstimate | None = None+ bundle_adjuster: ScipyBundleAdjuster | PyCeresBundleAdjuster | None = None+ minimum_views_to_reconstruct: int | None = 100++ @classmethod+ def from_camera_ids(+ cls,+ camera_ids: list[CameraIdString],+ principal_camera_id: CameraIdString | None = None,+ ) -> "MultiCameraCalibrator":+ return cls(+ principal_camera_id=principal_camera_id if principal_camera_id is not None else min(camera_ids),+ camera_id_to_index={camera_id: index for index, camera_id in enumerate(camera_ids)},+ multi_cam_output_accumulator=SharedViewAccumulator.create(camera_ids=camera_ids),+ )++ @property+ def has_calibration(self) -> bool:+ if self.single_camera_calibrators is None or self.multi_camera_calibration_estimate is None:+ return False+ return all(+ single_camera_calibrator.has_calibration+ for single_camera_calibrator in self.single_camera_calibrators.values()+ ) and self.multi_camera_calibration_estimate is not None++ @property+ def camera_intrinsics(self) -> dict[CameraIdString, CameraIntrinsicsEstimate]:+ if self.single_camera_calibrators is None:+ raise ValueError("Single camera calibrators not initialized")+ return {+ camera_id: single_camera_calibrator.camera_intrinsics_estimate+ for camera_id, single_camera_calibrator in self.single_camera_calibrators.items()+ }++ @property+ def ready_to_calibrate(self) -> bool:+ if not self.single_camera_calibrators:+ return False+ return self.all_cameras_have_min_shared_views()++ def receive_camera_node_output(+ self,+ multi_frame_number: int,+ camera_node_output_by_camera: dict[CameraIdString, CameraNodeOutputMessage],+ ) -> None:+ # Log multi-camera output+ self.multi_cam_output_accumulator.receive_camera_node_output(+ multi_frame_number=multi_frame_number,+ camera_node_output_by_camera=camera_node_output_by_camera,+ )++ # Add views to single camera calibrators+ if self.single_camera_calibrators is None:+ self.initialize_single_camera_calibrators(camera_node_output_by_camera=camera_node_output_by_camera)++ for camera_id, calibrator in self.single_camera_calibrators.items():+ obs = camera_node_output_by_camera[camera_id].observation+ if obs and obs.charuco_board_visible:+ calibrator.add_observation(observation=obs)++ def initialize_single_camera_calibrators(+ self,+ camera_node_output_by_camera: dict[CameraIdString, CameraNodeOutputMessage],+ ) -> None:+ logger.info(f"Initializing single camera calibrators for {len(camera_node_output_by_camera)} cameras")+ self.single_camera_calibrators = {}++ for camera_id, node_output in camera_node_output_by_camera.items():+ logger.debug(f"Creating calibrator for camera {camera_id}")+ self.single_camera_calibrators[camera_id] = SingleCameraCalibrator.create_initial(+ camera_id=camera_id,+ image_size=node_output.observation.image_size,+ all_aruco_marker_ids=node_output.observation.all_aruco_ids,+ all_aruco_corners_in_object_coordinates=node_output.observation.all_aruco_corners_in_object_coordinates,+ all_charuco_corner_ids=node_output.observation.all_charuco_ids,+ all_charuco_corners_in_object_coordinates=node_output.observation.all_charuco_corners_in_object_coordinates,+ )++ def all_cameras_have_min_shared_views(self) -> bool:+ if self.minimum_views_to_reconstruct is None:+ raise ValueError("minimum_views_to_reconstruct is not set")+ return self.multi_cam_output_accumulator.all_cameras_have_min_shared_views(+ min_shared_views=self.minimum_views_to_reconstruct+ )++ def calibrate(self) -> MultiCameraCalibrationEstimate:+ """Calibrate multi-camera system using OpenCV's stereoCalibrate."""+ if self.single_camera_calibrators is None:+ raise ValueError("Single camera calibrators not initialized")++ logger.info(f"Starting multi-camera calibration for cameras: {list(self.single_camera_calibrators.keys())}")+ logger.info(f"Principal camera: {self.principal_camera_id}")+ shared_view_counts = self.multi_cam_output_accumulator.get_shared_view_count_per_camera()+ logger.info(f"Shared view counts: {shared_view_counts}")++ # Step 1: Calibrate each camera individually+ logger.info("=" * 80)+ logger.info("STEP 1: Individual camera calibration")+ logger.info("=" * 80)+ for calibrator in self.single_camera_calibrators.values():+ logger.info(f"Calibrating camera {calibrator.camera_id}...")+ calibrator.calibrate()+ logger.info(+ f"Camera {calibrator.camera_id} calibration complete: "+ f"reprojection error = {calibrator.mean_reprojection_error:.3f} pixels"+ )++ # Step 2: Compute stereo calibration for each camera pair+ logger.info("=" * 80)+ logger.info("STEP 2: Stereo calibration for camera pairs")+ logger.info("=" * 80)+ camera_pair_transforms = self._calculate_camera_pair_transforms_with_stereo_calibrate()++ # Step 3: Build transforms to principal camera+ logger.info("=" * 80)+ logger.info("STEP 3: Computing transforms to principal camera")+ logger.info("=" * 80)+ camera_transforms = self._calculate_camera_to_principal_camera_transforms(+ camera_pair_secondary_camera_transform_estimates=camera_pair_transforms+ )++ self.multi_camera_calibration_estimate = MultiCameraCalibrationEstimate(+ principal_camera_id=self.principal_camera_id,+ camera_transforms_by_camera_id=camera_transforms,+ )++ logger.success(+ "Initial multi-camera calibration complete. "+ "Use run_bundle_adjustment() for optional refinement."+ )++ return self.multi_camera_calibration_estimate++ def run_bundle_adjustment(self) -> MultiCameraCalibrationEstimate:+ """Refine calibration using scipy bundle adjustment."""+ if self.multi_camera_calibration_estimate is None:+ raise ValueError("Must run calibrate() first before bundle adjustment")++ if self.single_camera_calibrators is None:+ raise ValueError("No single camera calibrators available")++ logger.info("=" * 80)+ logger.info("BUNDLE ADJUSTMENT REFINEMENT")+ logger.info("=" * 80)++ # Get camera intrinsics+ camera_intrinsics = {}+ for camera_id, calibrator in self.single_camera_calibrators.items():+ camera_intrinsics[camera_id] = (+ calibrator.camera_matrix,+ calibrator.distortion_coefficients,+ )+ logger.debug(+ f"Camera {camera_id} intrinsics: "+ f"fx={calibrator.camera_matrix.focal_length_x:.2f}, "+ f"fy={calibrator.camera_matrix.focal_length_y:.2f}"+ )++ # Get charuco corners in world coordinates+ first_calibrator = next(iter(self.single_camera_calibrators.values()))+ charuco_corners_3d = first_calibrator.all_charuco_corners_in_object_coordinates+ logger.info(f"Using {len(charuco_corners_3d)} charuco corners as 3D reference points")++ # Create bundle adjuster+ logger.info("Creating scipy bundle adjuster...")+ self.bundle_adjuster = ScipyBundleAdjuster.create(+ principal_camera_id=self.principal_camera_id,+ camera_transforms=self.multi_camera_calibration_estimate.camera_transforms_by_camera_id,+ camera_intrinsics=camera_intrinsics,+ charuco_corners_3d=charuco_corners_3d,+ )++ # Get multi-camera views+ multi_camera_views = self.multi_cam_output_accumulator.multi_camera_views_by_frame+ logger.info(f"Running optimization on {len(multi_camera_views)} multi-camera views...")++ # Run optimization+ optimized_transforms = self.bundle_adjuster.optimize(multi_camera_views=multi_camera_views)++ # Update estimate+ self.multi_camera_calibration_estimate = MultiCameraCalibrationEstimate(+ principal_camera_id=self.principal_camera_id,+ camera_transforms_by_camera_id=optimized_transforms,+ )++ logger.success("Bundle adjustment complete!")+ return self.multi_camera_calibration_estimate++ def _calculate_camera_pair_transforms_with_stereo_calibrate(+ self,+ ) -> dict[CameraPair, TransformationMatrix]:+ """Calculate camera pair transforms using OpenCV's stereoCalibrate."""+ if self.single_camera_calibrators is None:+ raise ValueError("Single camera calibrators not initialized")++ camera_pair_transforms = {}++ for base_camera_id, shared_views_dict in self.multi_cam_output_accumulator.camera_shared_views.items():+ for camera_pair, shared_views in shared_views_dict.items():+ if camera_pair in camera_pair_transforms:+ logger.debug(f"Skipping already-calculated pair: {camera_pair}")+ continue++ base_camera_id = camera_pair.base_camera_id+ other_camera_id = camera_pair.other_camera_id++ logger.info(f"Computing stereo calibration: {base_camera_id} โ {other_camera_id}")+ logger.debug(f" Using {len(shared_views)} shared views")++ # Extract matched observations+ object_points_list = []+ base_image_points_list = []+ other_image_points_list = []++ for view in shared_views:+ base_obs = view.base_camera_observation+ other_obs = view.other_camera_observation++ # Find common corner IDs between the two observations+ base_corner_ids = set(base_obs.detected_charuco_corner_ids)+ other_corner_ids = set(other_obs.detected_charuco_corner_ids)+ common_corner_ids = base_corner_ids & other_corner_ids++ if len(common_corner_ids) < 6:+ logger.debug(+ f" Skipping frame {view.multi_frame_number}: "+ f"only {len(common_corner_ids)} common corners"+ )+ continue++ # Build matched point arrays+ common_corner_ids_sorted = sorted(common_corner_ids)++ object_points = []+ base_image_points = []+ other_image_points = []++ for corner_id in common_corner_ids_sorted:+ # Get 3D object point+ object_points.append(+ self.single_camera_calibrators[base_camera_id]+ .all_charuco_corners_in_object_coordinates[corner_id]+ )++ # Get 2D image points+ base_idx = np.where(base_obs.detected_charuco_corner_ids == corner_id)[0][0]+ other_idx = np.where(other_obs.detected_charuco_corner_ids == corner_id)[0][0]++ base_image_points.append(base_obs.detected_charuco_corners_image_coordinates[base_idx])+ other_image_points.append(other_obs.detected_charuco_corners_image_coordinates[other_idx])++ object_points_list.append(np.array(object_points, dtype=np.float32))+ base_image_points_list.append(np.array(base_image_points, dtype=np.float32))+ other_image_points_list.append(np.array(other_image_points, dtype=np.float32))++ if len(object_points_list) < 10:+ raise ValueError(+ f"Insufficient matched views for stereo calibration between "+ f"{base_camera_id} and {other_camera_id}: only {len(object_points_list)} views"+ )++ logger.info(f" Using {len(object_points_list)} matched views for stereo calibration")++ # Get intrinsics+ base_calibrator = self.single_camera_calibrators[base_camera_id]+ other_calibrator = self.single_camera_calibrators[other_camera_id]++ # Run stereoCalibrate+ logger.debug(" Running cv2.stereoCalibrate...")+ (+ rms_error,+ camera_matrix_1,+ dist_coeffs_1,+ camera_matrix_2,+ dist_coeffs_2,+ R,+ T,+ E,+ F,+ ) = cv2.stereoCalibrate(+ objectPoints=object_points_list,+ imagePoints1=base_image_points_list,+ imagePoints2=other_image_points_list,+ cameraMatrix1=base_calibrator.camera_matrix.matrix.copy(),+ distCoeffs1=base_calibrator.distortion_coefficients.coefficients.copy(),+ cameraMatrix2=other_calibrator.camera_matrix.matrix.copy(),+ distCoeffs2=other_calibrator.distortion_coefficients.coefficients.copy(),+ imageSize=base_calibrator.image_size,+ flags=cv2.CALIB_FIX_INTRINSIC, # Don't re-optimize intrinsics+ criteria=(cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 1e-6),+ )++ logger.info(f" Stereo calibration RMS error: {rms_error:.4f} pixels")+ logger.debug(f" Rotation matrix norm: {np.linalg.norm(R):.4f}")+ logger.debug(f" Translation vector norm: {np.linalg.norm(T):.4f}")++ # Convert R, T to TransformationMatrix (other_camera -> base_camera)+ rotation_vector = RotationVector(+ vector=np.squeeze(cv2.Rodrigues(R)[0]),+ reference_frame=f"camera-{base_camera_id}",+ )+ translation_vector = TranslationVector(+ vector=np.squeeze(T),+ reference_frame=f"camera-{base_camera_id}",+ )++ transform = TransformationMatrix.from_rotation_translation(+ rotation_vector=rotation_vector,+ translation_vector=translation_vector,+ )++ camera_pair_transforms[camera_pair] = transform+ logger.debug(f" Transform computed successfully")++ logger.info(f"Computed {len(camera_pair_transforms)} stereo calibrations")+ return camera_pair_transforms++ def _calculate_camera_to_principal_camera_transforms(+ self,+ camera_pair_secondary_camera_transform_estimates: dict[CameraPair, TransformationMatrix],+ ) -> dict[CameraIdString, TransformationMatrix]:+ """Build transforms from all cameras to principal camera using pairwise transforms."""+ if self.single_camera_calibrators is None:+ raise ValueError("Single camera calibrators not initialized")++ # Start with principal camera at identity+ transform_to_principal_camera_by_camera = {+ self.principal_camera_id: TransformationMatrix(+ matrix=np.eye(4, dtype=np.float64),+ reference_frame=f"camera-{self.principal_camera_id}",+ )+ }++ # Initialize other cameras as None+ for camera_id in self.single_camera_calibrators.keys():+ if camera_id != self.principal_camera_id:+ transform_to_principal_camera_by_camera[camera_id] = None++ logger.info(f"Building transform graph from principal camera: {self.principal_camera_id}")++ # Iteratively resolve transforms using available pairs+ iteration = 0+ while any(transform is None for transform in transform_to_principal_camera_by_camera.values()):+ iteration += 1+ unresolved = [+ camera_id+ for camera_id, transform in transform_to_principal_camera_by_camera.items()+ if transform is None+ ]+ logger.debug(f"Iteration {iteration}: {len(unresolved)} unresolved cameras: {unresolved}")++ progress_made = False++ for camera_pair, pair_transform in camera_pair_secondary_camera_transform_estimates.items():+ base_id = camera_pair.base_camera_id+ other_id = camera_pair.other_camera_id++ # Skip if other camera already resolved+ if transform_to_principal_camera_by_camera[other_id] is not None:+ continue++ # Case 1: base is principal camera+ if base_id == self.principal_camera_id:+ logger.debug(f" Resolved {other_id} directly from principal camera")+ transform_to_principal_camera_by_camera[other_id] = pair_transform+ progress_made = True++ # Case 2: other is principal camera+ elif other_id == self.principal_camera_id:+ logger.debug(f" Resolved {base_id} as inverse from principal camera")+ transform_to_principal_camera_by_camera[base_id] = pair_transform.get_inverse()+ progress_made = True++ # Case 3: base is resolved, other is not+ elif transform_to_principal_camera_by_camera[base_id] is not None:+ base_to_principal = transform_to_principal_camera_by_camera[base_id]+ logger.debug(f" Resolved {other_id} via {base_id}")+ transform_to_principal_camera_by_camera[other_id] = base_to_principal @ pair_transform+ progress_made = True++ # Case 4: other is resolved, base is not+ elif transform_to_principal_camera_by_camera[other_id] is not None:+ other_to_principal = transform_to_principal_camera_by_camera[other_id]+ logger.debug(f" Resolved {base_id} via {other_id} (inverse)")+ transform_to_principal_camera_by_camera[base_id] = (+ other_to_principal @ pair_transform.get_inverse()+ )+ progress_made = True++ if not progress_made:+ unresolved_cameras = [+ cid for cid, t in transform_to_principal_camera_by_camera.items() if t is None+ ]+ raise RuntimeError(+ f"Cannot resolve transforms for cameras {unresolved_cameras}. "+ f"Camera network may not be fully connected to principal camera."+ )++ logger.success(f"All camera transforms resolved in {iteration} iterations")++ # Log final transforms+ for camera_id, transform in transform_to_principal_camera_by_camera.items():+ if camera_id == self.principal_camera_id:+ logger.info(f" Camera {camera_id}: [Principal camera - identity]")+ else:+ t = transform.translation_vector.vector+ logger.info(+ f" Camera {camera_id}: translation=[{t[0]:.3f}, {t[1]:.3f}, {t[2]:.3f}]"+ )++ return transform_to_principal_camera_by_camera+++if __name__ == "__main__":+ import pickle+ from pathlib import Path++ pickle_path = r"C:\Users\jonma\github_repos\freemocap_organization\freemocap\freemocap\saved_mc_calib.pkl"+ if not Path(pickle_path).exists():+ raise FileNotFoundError(f"File not found: {pickle_path}")++ logger.info(f"Loading calibrator from: {pickle_path}")+ loaded: MultiCameraCalibrator = pickle.load(open(pickle_path, "rb"))++ # Run calibration+ logger.info("Starting calibration process...")+ loaded.calibrate()++ logger.info("Running bundle adjustment refinement...")+ refined_estimate = loaded.run_bundle_adjustment()++ logger.success("Calibration pipeline complete!")diff --git a/freemocap/core/pipelines/calibration_pipeline/positional_6dof.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/positional_6dof.pysimilarity index 75%rename from freemocap/core/pipelines/calibration_pipeline/positional_6dof.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/positional_6dof.pyindex a70c1028..e0e60d59 100644--- a/freemocap/core/pipelines/calibration_pipeline/positional_6dof.py+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/positional_6dof.py@@ -3,19 +3,20 @@ import numpy as npfrom numpydantic import NDArray, Shapefrom pydantic import BaseModel-from freemocap.core.pipelines.calibration_pipeline.calibration_numpy_types import \+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.calibration_helpers.calibration_numpy_types import \TransformationMatrixArray, TranslationVectorArray, RotationVectorArrayclass Positional6DoF(BaseModel):- translation: TranslationVectorArray= np.zeros(3)+ translation: TranslationVectorArray = np.zeros(3)rotation: RotationVectorArray = np.zeros(3)@propertydef transformation_matrix(self) -> TransformationMatrixArray:return self.get_transformation_matrix()- def get_transformation_matrix(self, return_jacobian:bool=False) -> TransformationMatrixArray | tuple[TransformationMatrixArray, NDArray[Shape['3, 9'], np.float32]]:+ def get_transformation_matrix(self, return_jacobian: bool = False) -> TransformationMatrixArray | tuple[+ TransformationMatrixArray, NDArray[Shape['3, 9'], np.float32]]:"""Returns the transformation matrix for this 6DoF pose in the form of a 4x4 matrix (homogeneous coordinates)the left upper 3x3 matrix is the rotation matrix, and the rightmost column is the translation vector.@@ -35,4 +36,4 @@ class Positional6DoF(BaseModel):if __name__ == "__main__":positional_6dof = Positional6DoF()print(positional_6dof.transformation_matrix)- print(positional_6dof.model_dump_json(indent=2))\ No newline at end of file+ print(positional_6dof.model_dump_json(indent=2))diff --git a/freemocap/core/pipelines/calibration_pipeline/single_camera_calibration_estimate.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/single_camera_calibration_estimate.pysimilarity index 69%rename from freemocap/core/pipelines/calibration_pipeline/single_camera_calibration_estimate.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/single_camera_calibration_estimate.pyindex b8c50c8b..fc7dc313 100644--- a/freemocap/core/pipelines/calibration_pipeline/single_camera_calibration_estimate.py+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/single_camera_calibration_estimate.py@@ -1,21 +1,20 @@from pydantic import BaseModelfrom pydantic import Field-from skellycam import CameraId+from skellycam.core.types.type_overloads import CameraIdString-from freemocap.core.pipelines.calibration_pipeline.calibration_numpy_types import \+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.calibration_helpers.calibration_numpy_types import \TransformationMatrixArray, CameraMatrixArray, CameraDistortionCoefficientsArray-from freemocap.core.pipelines.calibration_pipeline.positional_6dof import Positional6DoF+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.calibration_helpers.positional_6dof import Positional6DoFclass SingleCameraCalibrationEstimate(BaseModel):- camera_id: CameraId+ camera_id: CameraIdStringcamera_matrix: CameraMatrixArraydistortion_coefficients: CameraDistortionCoefficientsArraypositional_6dof: Positional6DoF = Field(default_factory=Positional6DoF)-@propertydef focal_length(self):fx = self.camera_matrix[0, 0]@@ -31,4 +30,3 @@ class SingleCameraCalibrationEstimate(BaseModel):def extrinsic_matrix(self) -> TransformationMatrixArray:return self.positional_6dof.transformation_matrix-diff --git a/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/single_camera_calibrator.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/single_camera_calibrator.pynew file mode 100644index 00000000..178cb462--- /dev/null+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/single_camera_calibrator.py@@ -0,0 +1,538 @@+import logging++import cv2+import numpy as np+from pydantic import BaseModel, Field+from skellycam.core.types.type_overloads import CameraIdString+from skellytracker.trackers.charuco_tracker.charuco_observation import (+ CharucoObservations,+ CharucoObservation,+ AllCharucoCorners3DByIdInObjectCoordinates,+ AllArucoCorners3DByIdInObjectCoordinates,+)++from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.calibration_helpers.calibration_numpy_types import (+ ObjectPoints3D,+ ImagePoints2D,+)+from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.camera_math_models import (+ RotationVector,+ TranslationVector,+ TransformationMatrix,+ CameraDistortionCoefficients,+ CameraMatrix,+)+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.calibration_helpers.charuco_view_optimizer import (+ CharucoViewOptimizer,+ CharucoViewSelectionConfig,+)++logger = logging.getLogger(__name__)++DEFAULT_INTRINSICS_COEFFICIENTS_COUNT = 4+MIN_CHARUCO_CORNERS = 6+MIN_OBSERVATIONS_TO_CALIBRATE = 100+DEFAULT_TARGET_VIEW_COUNT = 25+INITIAL_VIEW_COUNT = 25+++class CameraIntrinsicsEstimate(BaseModel):+ camera_id: CameraIdString+ camera_matrix: CameraMatrix+ distortion_coefficients: CameraDistortionCoefficients+++class SingleCameraCalibrator(BaseModel):+ """+ SingleCameraCalibrator class for estimating camera calibration parameters.++ This calibrator stores ALL observations but can calibrate using a subset.+ The subset is determined by frame_numbers passed to update_calibration_estimate().+ """++ camera_id: CameraIdString+ image_size: tuple[int, ...]++ all_charuco_corner_ids: list[int]+ all_charuco_corners_in_object_coordinates: AllCharucoCorners3DByIdInObjectCoordinates++ all_aruco_marker_ids: list[int]+ all_aruco_corners_in_object_coordinates: AllArucoCorners3DByIdInObjectCoordinates++ distortion_coefficients: CameraDistortionCoefficients+ camera_matrix: CameraMatrix++ # Store ALL observations - never modified by optimization+ charuco_observations: CharucoObservations = Field(default_factory=CharucoObservations)++ # Calibration results - updated by update_calibration_estimate()+ board_rotation_vectors: list[RotationVector] = []+ board_translation_vectors: list[TranslationVector] = []+ reprojection_error_per_point_by_view: list[list[float]] = []+ reprojection_error_by_view: list[float] = []+ mean_reprojection_error: float | None = None+ camera_calibration_residual: float | None = None++ # Selected frame number for single-camera calibration (optimized coverage and diversity)+ selected_frame_numbers: list[int] = []++ @property+ def camera_intrinsics_estimate(self) -> CameraIntrinsicsEstimate:+ return CameraIntrinsicsEstimate(+ camera_id=self.camera_id,+ camera_matrix=self.camera_matrix,+ distortion_coefficients=self.distortion_coefficients,+ )++ @property+ def has_calibration(self) -> bool:+ return self.mean_reprojection_error is not None++ @property+ def ready_to_calibrate(self) -> bool:+ return len(self.charuco_observations) >= MIN_OBSERVATIONS_TO_CALIBRATE++ @property+ def charuco_transformation_matrices(self) -> list[TransformationMatrix]:+ return [+ TransformationMatrix.from_rotation_translation(+ rotation_vector=rotation_vector,+ translation_vector=translation_vector,+ )+ for rotation_vector, translation_vector in zip(+ self.board_rotation_vectors, self.board_translation_vectors+ )+ ]++ @classmethod+ def from_charuco_observations(+ cls,+ camera_id: CameraIdString,+ charuco_observations: CharucoObservations):+ calibrator = cls.from_charuco_observation(camera_id=camera_id,+ charuco_observation=charuco_observations[0])+ for observation in charuco_observations[1:]:+ calibrator.add_observation(observation=observation)+ return calibrator++ @classmethod+ def from_charuco_observation(+ cls,+ camera_id: CameraIdString,+ charuco_observation: CharucoObservation):++ return cls.create_initial(+ camera_id=camera_id,+ image_size=charuco_observation.image_size,+ all_aruco_marker_ids=charuco_observation.all_aruco_ids,+ all_aruco_corners_in_object_coordinates=charuco_observation.all_aruco_corners_in_object_coordinates,+ all_charuco_corner_ids=charuco_observation.all_charuco_ids,+ all_charuco_corners_in_object_coordinates=charuco_observation.all_charuco_corners_in_object_coordinates,+ )++ @classmethod+ def create_initial(+ cls,+ camera_id: CameraIdString,+ image_size: tuple[int, ...],+ all_aruco_marker_ids: list[int],+ all_aruco_corners_in_object_coordinates: AllArucoCorners3DByIdInObjectCoordinates,+ all_charuco_corner_ids: list[int],+ all_charuco_corners_in_object_coordinates: AllCharucoCorners3DByIdInObjectCoordinates,+ number_of_distortion_coefficients: int = DEFAULT_INTRINSICS_COEFFICIENTS_COUNT,+ ) -> "SingleCameraCalibrator":++ if len(all_charuco_corner_ids) != all_charuco_corners_in_object_coordinates.shape[0]:+ raise ValueError(+ "Number of charuco corner IDs must match the number of charuco corners."+ )+ if len(all_aruco_marker_ids) != len(all_aruco_corners_in_object_coordinates):+ raise ValueError(+ "Number of aruco marker IDs must match the number of aruco corners."+ )++ return cls(+ camera_id=camera_id,+ image_size=image_size,+ all_charuco_corner_ids=all_charuco_corner_ids,+ all_charuco_corners_in_object_coordinates=all_charuco_corners_in_object_coordinates,+ all_aruco_marker_ids=all_aruco_marker_ids,+ all_aruco_corners_in_object_coordinates=all_aruco_corners_in_object_coordinates,+ camera_matrix=CameraMatrix.from_image_size(image_size=image_size),+ distortion_coefficients=CameraDistortionCoefficients(+ coefficients=np.zeros(number_of_distortion_coefficients)+ ),+ )++ def add_observation(self, observation: CharucoObservation) -> None:+ if observation.frame_number in [obs.frame_number for obs in self.charuco_observations]:+ return+ if observation.charuco_empty or len(observation.detected_charuco_corner_ids) < MIN_CHARUCO_CORNERS:+ return+ self._validate_observation(observation=observation)++ self.charuco_observations.append(observation)++ def calibrate(self) -> None:+ """+ Calibrate single-camera intrinsics using optimized subset of observations.++ """+ logger.info(f"Calibrating camera {self.camera_id} with {len(self.charuco_observations)} observations...")++ self.selected_frame_numbers = self.select_optimal_frame_numbers()++ logger.info(f"Calibrating camera {self.camera_id} with {len(self.selected_frame_numbers)} optimized views...")+ self.update_calibration_estimate(frame_numbers=self.selected_frame_numbers,+ store_results_in_state=True)++ logger.success(+ f"Camera {self.camera_id} calibration complete! "+ f"Calibration error: {self.mean_reprojection_error:.3f} pixels"+ )++ def select_optimal_frame_numbers(+ self,+ target_count: int = DEFAULT_TARGET_VIEW_COUNT,+ initial_count: int = DEFAULT_TARGET_VIEW_COUNT,+ ) -> list[int]:+ """+ Select optimal frame numbers for calibration without modifying stored observations.++ Uses two-stage optimization:+ 1. Spatial optimization โ quick calibration โ pose estimation+ 2. Pose-based optimization โ return optimal frame numbers++ Args:+ target_count: Final number of views to select+ initial_count: Initial views for bootstrapping++ Returns:+ List of frame numbers to use for calibration+ """+ if len(self.charuco_observations) == 0:+ raise ValueError("No observations to optimize")++ original_count = len(self.charuco_observations)++ if original_count <= target_count:+ logger.info(+ f"Camera {self.camera_id}: Have {original_count} views, no optimization needed"+ )+ return [obs.frame_number for obs in self.charuco_observations]++ logger.info(+ f"Camera {self.camera_id}: Optimizing {original_count} views โ {target_count} views"+ )++ # STAGE 1: Select initial views spatially+ config = CharucoViewSelectionConfig(+ initial_view_count=initial_count,+ target_view_count=target_count,+ )+ optimizer = CharucoViewOptimizer(+ image_size=(int(self.image_size[0]), int(self.image_size[1])),+ config=config,+ )++ initial_indices = optimizer.select_initial_views(observations=self.charuco_observations)+ initial_frame_numbers = [self.charuco_observations[i].frame_number for i in initial_indices]++ logger.info(f"Camera {self.camera_id}: Selected {len(initial_frame_numbers)} initial views, calibrating...")++ # Quick calibration for pose estimation+ (residual,+ camera_matrix,+ distortion_coefficients,+ rotation_vectors,+ translation_vectors+ ) = self.update_calibration_estimate(frame_numbers=initial_frame_numbers, store_results_in_state=False)++ # STAGE 2: Estimate poses for ALL observations+ logger.info(f"Camera {self.camera_id}: Estimating poses for all {original_count} observations...")++ all_rvecs = []+ all_tvecs = []++ for obs in self.charuco_observations:+ if obs.charuco_empty or len(obs.detected_charuco_corner_ids) < MIN_CHARUCO_CORNERS:+ all_rvecs.append(np.zeros(3, dtype=np.float32))+ all_tvecs.append(np.zeros(3, dtype=np.float32))+ continue++ object_points = self.all_charuco_corners_in_object_coordinates[+ np.squeeze(obs.detected_charuco_corner_ids), :+ ]+ image_points = np.squeeze(obs.detected_charuco_corners_image_coordinates)++ try:+ success, rvec, tvec = cv2.solvePnP(+ objectPoints=object_points,+ imagePoints=image_points,+ cameraMatrix=camera_matrix,+ distCoeffs=distortion_coefficients,+ )+ if not success:+ raise ValueError(f"solvePnP failed for frame {obs.frame_number}")++ all_rvecs.append(np.squeeze(rvec))+ all_tvecs.append(np.squeeze(tvec))+ except (cv2.error, ValueError) as e:+ raise RuntimeError(f"Failed to estimate pose for frame {obs.frame_number}: {e}")++ # Select final views using pose information+ final_indices = optimizer.select_final_views(+ observations=self.charuco_observations,+ rotation_vectors=all_rvecs,+ translation_vectors=all_tvecs,+ )++ final_frame_numbers = [self.charuco_observations[i].frame_number for i in final_indices]++ logger.info(+ f"Camera {self.camera_id}: Optimization complete - "+ f"selected {len(final_frame_numbers)} final views"+ )++ return final_frame_numbers++ def update_calibration_estimate(+ self,+ frame_numbers: list[int] | None = None,+ store_results_in_state: bool = True # if false, don't update internal state+ ) -> tuple[float, np.ndarray, np.ndarray, list[RotationVector], list[TranslationVector]]:+ """+ Update calibration estimate using specified frame numbers.++ If frame_numbers is None, uses ALL observations.++ Args:+ frame_numbers: Specific frame numbers to use for calibration.+ If None, uses all available observations.+ """+ # Select observations to use+ if frame_numbers is None:+ observations_to_use = self.charuco_observations+ logger.info(f"Calibrating camera {self.camera_id} with ALL {len(observations_to_use)} observations")+ else:+ frame_number_set = set(frame_numbers)+ observations_to_use = [+ obs for obs in self.charuco_observations+ if obs.frame_number in frame_number_set+ ]++ if len(observations_to_use) != len(frame_numbers):+ raise ValueError(+ f"Requested {len(frame_numbers)} frame numbers but only found "+ f"{len(observations_to_use)} matching observations"+ )++ logger.debug(f"Calibrating camera {self.camera_id} with {len(observations_to_use)} selected views...")++ # Build object and image points from selected observations+ object_points_views: list[ObjectPoints3D] = []+ image_points_views: list[ImagePoints2D] = []++ for obs in observations_to_use:+ image_points_views.append(np.squeeze(obs.detected_charuco_corners_image_coordinates))+ object_points_views.append(+ self.all_charuco_corners_in_object_coordinates[+ np.squeeze(obs.detected_charuco_corner_ids), :+ ]+ )++ if len(object_points_views) < len(self.all_charuco_corner_ids):+ raise ValueError(+ f"Need at least {len(self.all_charuco_corner_ids)} observations, "+ f"have {len(object_points_views)}"+ )++ view_count = len(object_points_views)++ if view_count > 50 and frame_numbers is None:+ logger.warning(+ f"Camera {self.camera_id}: Using {view_count} views without optimization. "+ f"Consider calling select_optimal_frame_numbers() first."+ )++ # Run OpenCV calibration+ (+ camera_calibration_residual,+ camera_matrix_output,+ distortion_coefficients_output,+ rotation_vectors_output,+ translation_vectors_output,+ ) = cv2.calibrateCamera(+ objectPoints=object_points_views,+ imagePoints=image_points_views,+ imageSize=self.image_size,+ cameraMatrix=self.camera_matrix.matrix,+ distCoeffs=self.distortion_coefficients.coefficients,+ )++ if not camera_calibration_residual:+ raise ValueError("Camera calibration failed! Check input data.")++ # Store results+ board_rotation_vectors = [+ RotationVector(+ vector=np.squeeze(rotation_vector),+ reference_frame=f"camera-{self.camera_id}",+ )+ for rotation_vector in rotation_vectors_output+ ]+ board_translation_vectors = [+ TranslationVector(+ vector=np.squeeze(translation_vector),+ reference_frame=f"camera-{self.camera_id}",+ )+ for translation_vector in translation_vectors_output+ ]++ logger.debug(+ f"Camera {self.camera_id} calibration complete! "+ f"Residual: {camera_calibration_residual:.4f}"+ )++ if store_results_in_state:+ self.camera_calibration_residual = camera_calibration_residual+ self.camera_matrix = CameraMatrix(matrix=camera_matrix_output)+ self.distortion_coefficients = CameraDistortionCoefficients(+ coefficients=np.squeeze(distortion_coefficients_output)+ )+ self.board_rotation_vectors = board_rotation_vectors+ self.board_translation_vectors = board_translation_vectors+ self._update_reprojection_error(+ object_points_views=object_points_views,+ image_points_views=image_points_views,+ )+ return camera_calibration_residual, camera_matrix_output, distortion_coefficients_output, board_rotation_vectors, board_translation_vectors++ def get_board_pose(+ self,+ object_points: np.ndarray,+ image_points: np.ndarray+ ) -> tuple[np.ndarray, np.ndarray]:+ """+ Estimate board pose from object and image points.++ Args:+ object_points: Nx3 array of 3D points+ image_points: Nx2 array of 2D points++ Returns:+ Tuple of (rotation_vector, translation_vector)+ """+ if len(object_points) < 6:+ raise ValueError("Need at least 6 object points to estimate board pose")+ if not self.has_calibration:+ raise ValueError("Must calibrate camera first")+ if len(object_points) != len(image_points):+ raise ValueError("Object and image points must have same length")++ success, rotation_vector, translation_vector = cv2.solvePnP(+ objectPoints=object_points,+ imagePoints=image_points,+ cameraMatrix=self.camera_matrix.matrix,+ distCoeffs=self.distortion_coefficients.coefficients,+ )++ if not success:+ raise ValueError("Failed to estimate board pose")++ return rotation_vector, translation_vector++ def draw_board_axes(+ self,+ image: np.ndarray,+ observation: CharucoObservation+ ) -> np.ndarray:+ """+ Draw 3D axes on the board in the image.++ Args:+ image: Image to draw on+ observation: Observation containing board detection++ Returns:+ Image with axes drawn+ """+ if not self.has_calibration:+ raise ValueError("Must calibrate camera first")+ if observation.detected_charuco_corners_image_coordinates.shape[0] < 6:+ return image++ rotation_vector, translation_vector = self.get_board_pose(+ object_points=observation.detected_charuco_corners_in_object_coordinates,+ image_points=observation.detected_charuco_corners_image_coordinates,+ )++ axis_length = 5+ return cv2.drawFrameAxes(+ image,+ self.camera_matrix.matrix,+ self.distortion_coefficients.coefficients,+ rotation_vector,+ translation_vector,+ axis_length,+ )++ def _validate_observation(self, observation: CharucoObservation) -> None:+ """Validate observation matches calibrator configuration."""+ if observation.image_size != self.image_size:+ raise ValueError(+ f"Image size mismatch: expected {self.image_size}, got {observation.image_size}"+ )+ if any(+ corner_id not in self.all_charuco_corner_ids+ for corner_id in observation.detected_charuco_corner_ids+ ):+ raise ValueError(+ f"Invalid charuco corner ID detected: {observation.detected_charuco_corner_ids}"+ )++ def _update_reprojection_error(+ self,+ object_points_views: list[ObjectPoints3D],+ image_points_views: list[ImagePoints2D],+ ) -> None:+ """Compute reprojection error for calibrated views."""+ if len(image_points_views) != len(object_points_views):+ raise ValueError("Image and object points must have same length")+ if len(image_points_views) == 0:+ raise ValueError("No image points provided")+ if len(image_points_views) != len(self.board_rotation_vectors):+ raise ValueError(+ f"Number of views ({len(image_points_views)}) must match "+ f"number of rotation vectors ({len(self.board_rotation_vectors)})"+ )++ self.reprojection_error_per_point_by_view = []+ self.reprojection_error_by_view = []++ for view_index in range(len(image_points_views)):+ projected_image_points, jacobian = cv2.projectPoints(+ objectPoints=object_points_views[view_index],+ rvec=self.board_rotation_vectors[view_index].vector,+ tvec=self.board_translation_vectors[view_index].vector,+ cameraMatrix=self.camera_matrix.matrix,+ distCoeffs=self.distortion_coefficients.coefficients,+ aspectRatio=self.image_size[0] / self.image_size[1],+ )++ self.reprojection_error_per_point_by_view.append(+ np.abs(+ image_points_views[view_index]+ - np.squeeze(projected_image_points)+ )+ )++ self.reprojection_error_by_view.append(+ float(np.nanmean(self.reprojection_error_per_point_by_view[-1]))+ )++ self.mean_reprojection_error = float(np.nanmean(self.reprojection_error_by_view))++ logger.debug(+ f"Camera {self.camera_id} - Mean reprojection error: {self.mean_reprojection_error:.3f} pixels"+ )diff --git a/freemocap/core/pipelines/calibration_pipeline/triangulate_points.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/triangulate_points.pysimilarity index 65%rename from freemocap/core/pipelines/calibration_pipeline/triangulate_points.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/triangulate_points.pyindex be8fc5b2..77ea73db 100644--- a/freemocap/core/pipelines/calibration_pipeline/triangulate_points.py+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/calibration_helpers/triangulate_points.py@@ -1,11 +1,12 @@import cv2import numpy as np-from skellycam import CameraId+from skellycam.core.types.type_overloads import CameraIdString-from freemocap.core.pipelines.calibration_pipeline.calibration_numpy_types import ObjectPoint3D, \+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.calibration_helpers.calibration_numpy_types import ObjectPoint3D, \ImagePoints2D, ObjectPoints3D, ReprojectionError, CameraExtrinsicsMatrix, ImagePoint2D-from freemocap.core.pipelines.calibration_pipeline.camera_math_models import TransformationMatrix-from freemocap.core.pipelines.calibration_pipeline.single_camera_calibrator import CameraIntrinsicsEstimate+from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.camera_math_models import TransformationMatrix+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.calibration_helpers.single_camera_calibrator import \+ CameraIntrinsicsEstimatedef undistort_points(points2d: ImagePoints2D,@@ -24,7 +25,7 @@ def undistort_points(points2d: ImagePoints2D,:return: A NumPy array of the same shape as `points2d` containing the undistorted 2D points (in normalized image coordinates, I think?)."""undistorted_points2d = cv2.undistortPoints(src=points2d,- cameraMatrix= camera_intrinsics.camera_matrix.matrix,+ cameraMatrix=camera_intrinsics.camera_matrix.matrix,distCoeffs=camera_intrinsics.distortion_coefficients.coefficients,)@@ -32,42 +33,44 @@ def undistort_points(points2d: ImagePoints2D,# @jit(nopython=True, parallel=False)-def triangulate_point(image_point_by_camera: dict[CameraId, ImagePoint2D],- camera_extrinsics: dict[CameraId, CameraExtrinsicsMatrix]) -> ObjectPoint3D:+def triangulate_point(image_point_by_camera: dict[CameraIdString, ImagePoint2D],+ camera_extrinsics: dict[CameraIdString, CameraExtrinsicsMatrix]) -> ObjectPoint3D:_validate_triangulation_input(camera_extrinsics=camera_extrinsics,image_point_by_camera=image_point_by_camera)camera_ids = list(camera_extrinsics.keys())number_of_cameras = len(camera_ids)- A = np.zeros((number_of_cameras * 2, 4)) #SVD needs this to be a 2d array of shape (2n, 4), where n is the number of cameras+ A = np.zeros((number_of_cameras * 2,+ 4)) # SVD needs this to be a 2d array of shape (2n, 4), where n is the number of camerasfor camera_number, camera_id in enumerate(camera_ids):image_points_x = image_point_by_camera[camera_id][0]image_points_y = image_point_by_camera[camera_id][1]camera_matrix = camera_extrinsics[camera_id]A[(camera_number * 2): (camera_number * 2 + 1)] = image_points_x * camera_matrix[2] - camera_matrix[0]A[(camera_number * 2 + 1): (camera_number * 2 + 2)] = image_points_y * camera_matrix[2] - camera_matrix[1]- u, s, vh = np.linalg.svd(A, full_matrices=True) #SVD returns the singular values in descending order, so the last row of vh is the solution (i.e. the 3D point represented in homogeneous coordinates)+ u, s, vh = np.linalg.svd(A,+ full_matrices=True) # SVD returns the singular values in descending order, so the last row of vh is the solution (i.e. the 3D point represented in homogeneous coordinates)points_3d = vh[-1]points_3d = points_3d[:3] / points_3d[3]return points_3d-def _validate_triangulation_input(camera_extrinsics: dict[CameraId, CameraExtrinsicsMatrix],- image_point_by_camera: dict[CameraId, ImagePoint2D]):+def _validate_triangulation_input(camera_extrinsics: dict[CameraIdString, CameraExtrinsicsMatrix],+ image_point_by_camera: dict[CameraIdString, ImagePoint2D]):if len(image_point_by_camera) < 2:raise ValueError("Need at least two cameras to triangulate points.")if image_point_by_camera.keys() != camera_extrinsics.keys():raise ValueError("Camera IDs in image_point_by_camera and camera_extrinsics must match.")if not all([image_point_by_camera[camera_id].shape == (2,) for camera_id in image_point_by_camera.keys()]):raise ValueError("All image points must be 2D points.")- if not all([camera_extrinsics[camera_id].shape == (3, 4)for camera_id in camera_extrinsics.keys()]):+ if not all([camera_extrinsics[camera_id].shape == (3, 4) for camera_id in camera_extrinsics.keys()]):raise ValueError("All camera extrinsics must be 3x4 matrices.")def _validate_reprojection_error_input(object_points: ObjectPoints3D,- image_points_by_camera: dict[CameraId, ImagePoints2D],- camera_intrinsics: dict[CameraId, CameraIntrinsicsEstimate],- camera_transforms: dict[CameraId, TransformationMatrix],- image_sizes: dict[CameraId, tuple[int, int]]):+ image_points_by_camera: dict[CameraIdString, ImagePoints2D],+ camera_intrinsics: dict[CameraIdString, CameraIntrinsicsEstimate],+ camera_transforms: dict[CameraIdString, TransformationMatrix],+ image_sizes: dict[CameraIdString, tuple[int, int]]):if len(image_points_by_camera) < 2:raise ValueError("Need at least two cameras to triangulate points.")if any([image_sizes.keys() != camera_intrinsics.keys(),@@ -75,24 +78,24 @@ def _validate_reprojection_error_input(object_points: ObjectPoints3D,image_sizes.keys() != image_points_by_camera.keys()]):raise ValueError("Camera IDs in image_points_by_camera, camera_intrinsics, and camera_transforms must match.")for camera_id in image_points_by_camera.keys():- if not all ([point.shape == (2,) for point in image_points_by_camera[camera_id]]):+ if not all([point.shape == (2,) for point in image_points_by_camera[camera_id]]):raise ValueError("All image points must be 2D points.")-# @jit(nopython=True, parallel=False)def calculate_reprojection_error(object_points: ObjectPoints3D,- image_points_by_camera: dict[CameraId, ImagePoints2D],- camera_intrinsics: dict[CameraId, CameraIntrinsicsEstimate],- camera_transforms: dict[CameraId, TransformationMatrix],- image_sizes: dict[CameraId, tuple[int, int]]) -> tuple[list[ReprojectionError], dict[CameraId, list[ReprojectionError]]]:+ image_points_by_camera: dict[CameraIdString, ImagePoints2D],+ camera_intrinsics: dict[CameraIdString, CameraIntrinsicsEstimate],+ camera_transforms: dict[CameraIdString, TransformationMatrix],+ image_sizes: dict[CameraIdString, tuple[int, int]]) -> tuple[+ list[ReprojectionError], dict[CameraIdString, list[ReprojectionError]]]:# https://docs.opencv.org/4.10.0/d9/d0c/group__calib3d.html#ga1019495a2c8d1743ed5cc23fa0daff8c_validate_reprojection_error_input(object_points=object_points,- image_points_by_camera=image_points_by_camera,- camera_intrinsics=camera_intrinsics,- camera_transforms=camera_transforms,- image_sizes=image_sizes)- reprojection_error_per_point_by_camera: dict[CameraId, list[ReprojectionError]] = {}+ image_points_by_camera=image_points_by_camera,+ camera_intrinsics=camera_intrinsics,+ camera_transforms=camera_transforms,+ image_sizes=image_sizes)+ reprojection_error_per_point_by_camera: dict[CameraIdString, list[ReprojectionError]] = {}for camera_id in camera_intrinsics.keys():projected_image_points, jacobian = cv2.projectPoints(objectPoints=object_points,rvec=camera_transforms[camera_id].rotation_vector.vector,@@ -102,10 +105,12 @@ def calculate_reprojection_error(object_points: ObjectPoints3D,camera_id].camera_matrix.matrix,distCoeffs=camera_intrinsics[camera_id].distortion_coefficients.coefficients,- aspectRatio=image_sizes[camera_id][0] / image_sizes[camera_id][1]+ aspectRatio=image_sizes[camera_id][0] /+ image_sizes[camera_id][1])- reprojection_error_per_point_by_camera[camera_id]= np.abs(image_points_by_camera[camera_id] - np.squeeze(projected_image_points))+ reprojection_error_per_point_by_camera[camera_id] = np.abs(+ image_points_by_camera[camera_id] - np.squeeze(projected_image_points))mean_reprojection_error_per_point = []for point_index in range(len(object_points)):diff --git a/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/create_triangulator_from_multicam_calibrator.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/create_triangulator_from_multicam_calibrator.pynew file mode 100644index 00000000..bc656a36--- /dev/null+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/create_triangulator_from_multicam_calibrator.py@@ -0,0 +1,113 @@+import logging++import cv2+import numpy as np+from skellycam.core.types.type_overloads import CameraIdString++from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.calibration_helpers.multi_camera_calibrator import \+ MultiCameraCalibrator+from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.point_triangulator import PointTriangulator, CameraCalibrationData+from freemocap.pubsub.pubsub_topics import CameraNodeOutputMessage++logger = logging.getLogger(__name__)+++def create_triangulator_from_calibrator(+ multi_camera_calibrator: MultiCameraCalibrator+) -> PointTriangulator:+ """+ Convert MultiCameraCalibrator calibration results into PointTriangulator format.++ :param multi_camera_calibrator: Calibrated multi-camera system+ :return: Initialized PointTriangulator ready for fast triangulation+ :raises ValueError: If calibrator doesn't have calibration data+ """+ if not multi_camera_calibrator.has_calibration:+ raise ValueError(+ "MultiCameraCalibrator must be calibrated before creating triangulator. "+ "Call calibrate() first."+ )++ camera_calibrations: dict[str, CameraCalibrationData] = {}++ for camera_id, single_camera_calibrator in multi_camera_calibrator.single_camera_calibrators.items():+ # Get intrinsics from single camera calibrator+ intrinsics = single_camera_calibrator.camera_intrinsics_estimate+ camera_matrix = intrinsics.camera_matrix+ distortion_coeffs = intrinsics.distortion_coefficients++ # Get extrinsics from multi-camera calibration estimate+ transform = multi_camera_calibrator.multi_camera_calibration_estimate.camera_transforms_by_camera_id[camera_id]+ extrinsics = transform.extrinsics_matrix++ # Extract rotation vector and translation from extrinsics matrix [R|t]+ rotation_matrix = extrinsics[:3, :3]+ translation_vector = extrinsics[:3, 3]+ rotation_vector = cv2.Rodrigues(rotation_matrix)[0].ravel()++ # Get image size+ image_size = single_camera_calibrator.image_size++ # Create CameraCalibrationData+ camera_calibrations[camera_id] = CameraCalibrationData(+ name=camera_id,+ image_size=image_size,+ matrix=camera_matrix,+ distortion=distortion_coeffs,+ rotation_vector=rotation_vector,+ translation=translation_vector+ )++ return PointTriangulator(camera_calibrations=camera_calibrations)+++def triangulate_list(+ triangulator: PointTriangulator,+ camera_node_outputs_stream: list[dict[CameraIdString, CameraNodeOutputMessage]],+ undistort_points: bool = True,+ compute_reprojection_error: bool = False+) -> tuple[np.ndarray, np.ndarray | None]:+ """+ Efficiently triangulate a stream of multi-camera observations.++ :param triangulator: Initialized PointTriangulator+ :param camera_node_outputs_stream: List of frame observations across cameras+ :param undistort_points: Whether to undistort points before triangulation+ :param compute_reprojection_error: Whether to compute reprojection errors+ :return: Tuple of (all_points3d, all_errors)+ - all_points3d: Shape (F, M, 3) - F frames, M charuco corners, 3D coords+ - all_errors: Shape (F, M) - reprojection errors per point per frame, or None+ :raises ValueError: If stream is empty or cameras missing+ """+ if not camera_node_outputs_stream:+ raise ValueError("camera_node_outputs_stream cannot be empty")++ num_frames = len(camera_node_outputs_stream)++ # Get number of charuco corners from first valid observation+ first_frame = camera_node_outputs_stream[0]+ first_camera_output = next(iter(first_frame.values()))+ num_corners = first_camera_output.observation.to_2d_array().shape[0]++ # Pre-allocate output arrays+ all_points3d = np.empty((num_frames, num_corners, 3), dtype=np.float64)+ all_errors = np.empty((num_frames, num_corners), dtype=np.float64) if compute_reprojection_error else None++ # Process each frame+ for frame_idx, camera_node_outputs in enumerate(camera_node_outputs_stream):+ try:+ points3d, errors = triangulator.triangulate_camera_node_outputs(+ camera_node_outputs=camera_node_outputs,+ undistort_points=undistort_points,+ compute_reprojection_error=compute_reprojection_error+ )++ all_points3d[frame_idx] = points3d+ if compute_reprojection_error and errors is not None:+ all_errors[frame_idx] = errors++ except ValueError as e:+ logger.error(f"Triangulation failed for frame {frame_idx}: {e}")+ raise++ return all_points3d, all_errorsdiff --git a/freemocap/old/core_processes/post_process_skeleton_data/__init__.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/og_v1_capture_volume_calibration/__init__.pysimilarity index 100%rename from freemocap/old/core_processes/post_process_skeleton_data/__init__.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/og_v1_capture_volume_calibration/__init__.pydiff --git a/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/pyceres_bundle_adjuster.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/pyceres_bundle_adjuster.pynew file mode 100644index 00000000..6e82b78e--- /dev/null+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/pyceres_bundle_adjuster.py@@ -0,0 +1,275 @@+import logging++import cv2+import numpy as np+import pyceres+from pydantic import BaseModel, Field+from scipy.spatial.transform import Rotation+from skellycam.core.types.type_overloads import CameraIdString++from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.camera_math_models import (+ CameraMatrix,+ CameraDistortionCoefficients,+ TransformationMatrix,+)+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.shared_view_accumulator import MultiCameraTargetView++logger = logging.getLogger(__name__)+++class ReprojectionCost(pyceres.CostFunction):+ def __init__(+ self,+ observed_point: np.ndarray,+ point_3d: np.ndarray,+ fx: float,+ fy: float,+ cx: float,+ cy: float,+ ) -> None:+ super().__init__()+ self.observed_point = observed_point.astype(np.float64).copy()+ self.point_3d = point_3d.astype(np.float64).copy()+ self.fx = fx+ self.fy = fy+ self.cx = cx+ self.cy = cy++ self.set_num_residuals(2)+ # Separate rvec and tvec like the working code separates quat and trans!+ self.set_parameter_block_sizes([3, 3])++ def Evaluate(+ self,+ parameters: list[np.ndarray],+ residuals: np.ndarray,+ jacobians: list[np.ndarray] | None,+ ) -> bool:+ rvec = parameters[0]+ tvec = parameters[1]++ # Convert rotation vector to rotation matrix+ angle = np.linalg.norm(rvec)+ if angle < 1e-10:+ R = np.eye(3, dtype=np.float64)+ else:+ R = Rotation.from_rotvec(rvec).as_matrix()++ # Transform 3D point to camera coordinates+ X_cam = R @ self.point_3d + tvec++ # Check for points behind camera+ if X_cam[2] < 1e-6:+ residuals[0] = 1000.0+ residuals[1] = 1000.0+ return True++ # Project to normalized image coordinates (no distortion for now)+ x = X_cam[0] / X_cam[2]+ y = X_cam[1] / X_cam[2]++ # Apply camera matrix+ u = self.fx * x + self.cx+ v = self.fy * y + self.cy++ # Compute residuals+ residuals[0] = u - self.observed_point[0]+ residuals[1] = v - self.observed_point[1]++ return True+++class CameraParameters(BaseModel):+ camera_id: CameraIdString+ extrinsics: np.ndarray = Field(default_factory=lambda: np.zeros(6, dtype=np.float64))+ intrinsics: np.ndarray = Field(default_factory=lambda: np.zeros(9, dtype=np.float64))++ class Config:+ arbitrary_types_allowed = True++ @classmethod+ def from_calibration_data(+ cls,+ camera_id: CameraIdString,+ rotation_vector: np.ndarray,+ translation_vector: np.ndarray,+ camera_matrix: CameraMatrix,+ distortion_coeffs: CameraDistortionCoefficients,+ ) -> "CameraParameters":+ extrinsics = np.zeros(6, dtype=np.float64)+ extrinsics[0:3] = rotation_vector.flatten()+ extrinsics[3:6] = translation_vector.flatten()++ intrinsics = np.zeros(9, dtype=np.float64)+ intrinsics[0] = camera_matrix.focal_length_x+ intrinsics[1] = camera_matrix.focal_length_y+ intrinsics[2], intrinsics[3] = camera_matrix.principal_point++ dist = distortion_coeffs.coefficients if hasattr(distortion_coeffs, "coefficients") else distortion_coeffs+ num_dist = min(len(dist), 5)+ intrinsics[4: 4 + num_dist] = dist[0:num_dist]++ return cls(camera_id=camera_id, extrinsics=extrinsics, intrinsics=intrinsics)++ def to_transformation_matrix(self, reference_frame: str) -> TransformationMatrix:+ rotation_matrix = cv2.Rodrigues(self.extrinsics[0:3])[0]+ matrix = np.eye(4, dtype=np.float64)+ matrix[0:3, 0:3] = rotation_matrix+ matrix[0:3, 3] = self.extrinsics[3:6]+ return TransformationMatrix(matrix=matrix, reference_frame=reference_frame)++ def to_camera_matrix(self) -> np.ndarray:+ matrix = np.eye(3, dtype=np.float64)+ matrix[0, 0] = self.intrinsics[0]+ matrix[1, 1] = self.intrinsics[1]+ matrix[0, 2] = self.intrinsics[2]+ matrix[1, 2] = self.intrinsics[3]+ return matrix++ def to_distortion_coefficients(self) -> np.ndarray:+ return self.intrinsics[4:9]+++class PyCeresBundleAdjuster(BaseModel):+ principal_camera_id: CameraIdString+ camera_parameters: dict[CameraIdString, CameraParameters] = Field(default_factory=dict)+ point_3d_coords: dict[int, np.ndarray] = Field(default_factory=dict)++ class Config:+ arbitrary_types_allowed = True++ @classmethod+ def create(+ cls,+ principal_camera_id: CameraIdString,+ camera_transforms: dict[CameraIdString, TransformationMatrix],+ camera_intrinsics: dict[CameraIdString, tuple[CameraMatrix, CameraDistortionCoefficients]],+ charuco_corners_3d: np.ndarray,+ ) -> "PyCeresBundleAdjuster":+ camera_parameters = {}+ for camera_id, transform in camera_transforms.items():+ camera_matrix, dist_coeffs = camera_intrinsics[camera_id]+ rotation_vector = cv2.Rodrigues(transform.rotation_matrix)[0].flatten()+ translation = transform.translation_vector.vector.flatten()+ camera_parameters[camera_id] = CameraParameters.from_calibration_data(+ camera_id=camera_id,+ rotation_vector=rotation_vector,+ translation_vector=translation,+ camera_matrix=camera_matrix,+ distortion_coeffs=dist_coeffs,+ )++ point_3d_coords = {i: charuco_corners_3d[i].astype(np.float64).copy() for i in range(len(charuco_corners_3d))}+ return cls(+ principal_camera_id=principal_camera_id,+ camera_parameters=camera_parameters,+ point_3d_coords=point_3d_coords,+ )++ def optimize(+ self,+ multi_camera_views: dict[int, MultiCameraTargetView],+ ) -> dict[CameraIdString, TransformationMatrix]:+ logger.info("Starting PyCeres bundle adjustment optimization (FIXED STRUCTURE)...")++ # FOLLOW THE WORKING CODE'S PATTERN EXACTLY+ # 1. Create separate arrays for rotation and translation (like quat and trans)+ camera_ids = sorted(self.camera_parameters.keys())++ # Store rotation and translation SEPARATELY like the working code+ rvecs: list[np.ndarray] = []+ tvecs: list[np.ndarray] = []+ rvec_by_id: dict[CameraIdString, np.ndarray] = {}+ tvec_by_id: dict[CameraIdString, np.ndarray] = {}++ for camera_id in camera_ids:+ params = self.camera_parameters[camera_id]+ rvec = np.array(params.extrinsics[0:3], dtype=np.float64, order='C')+ tvec = np.array(params.extrinsics[3:6], dtype=np.float64, order='C')+ rvecs.append(rvec)+ tvecs.append(tvec)+ rvec_by_id[camera_id] = rvec+ tvec_by_id[camera_id] = tvec++ # Keep all cost functions alive+ cost_functions: list[ReprojectionCost] = []++ problem = pyceres.Problem()++ # Add parameter blocks separately like the working code+ for camera_id in camera_ids:+ problem.add_parameter_block(rvec_by_id[camera_id], 3)+ problem.add_parameter_block(tvec_by_id[camera_id], 3)++ # Fix the principal camera+ problem.set_parameter_block_constant(rvec_by_id[self.principal_camera_id])+ problem.set_parameter_block_constant(tvec_by_id[self.principal_camera_id])++ # Add residual blocks+ residual_count = 0+ for mc_view in multi_camera_views.values():+ for camera_id, camera_output in mc_view.camera_node_output_by_camera.items():+ if not camera_output.observation or camera_output.observation.charuco_empty:+ continue++ obs = camera_output.observation+ params = self.camera_parameters[camera_id]+ camera_matrix = params.to_camera_matrix()++ fx = float(camera_matrix[0, 0])+ fy = float(camera_matrix[1, 1])+ cx = float(camera_matrix[0, 2])+ cy = float(camera_matrix[1, 2])++ rvec = rvec_by_id[camera_id]+ tvec = tvec_by_id[camera_id]++ for corner_idx, corner_id in enumerate(obs.detected_charuco_corner_ids):+ corner_id_int = int(corner_id)+ if corner_id_int not in self.point_3d_coords:+ continue++ cost = ReprojectionCost(+ observed_point=obs.detected_charuco_corners_image_coordinates[corner_idx],+ point_3d=self.point_3d_coords[corner_id_int],+ fx=fx,+ fy=fy,+ cx=cx,+ cy=cy,+ )+ cost_functions.append(cost)+ # Pass BOTH parameter blocks like the working code!+ problem.add_residual_block(cost, None, [rvec, tvec])+ residual_count += 1++ logger.info(f"Added {residual_count} reprojection residuals")+ logger.info(f"Total parameter blocks: {problem.num_parameters()}")+ logger.info(f"Total residual blocks: {problem.num_residual_blocks()}")++ # Configure solver - match the working code exactly+ options = pyceres.SolverOptions()+ options.max_num_iterations = 100+ options.minimizer_progress_to_stdout = True+ options.linear_solver_type = pyceres.LinearSolverType.SPARSE_NORMAL_CHOLESKY+ options.function_tolerance = 1e-9 # Match working code+ options.gradient_tolerance = 1e-11 # Match working code+ options.parameter_tolerance = 1e-10 # Match working code++ # Solve+ summary = pyceres.SolverSummary()+ pyceres.solve(options, problem, summary)++ logger.info(f"Optimization complete: Cost {summary.initial_cost:.2f} -> {summary.final_cost:.2f}")+ logger.info(f"Iterations: {summary.num_successful_steps}")+ logger.info(f"Termination: {summary.termination_type}")++ # Copy optimized values back+ for camera_id in camera_ids:+ self.camera_parameters[camera_id].extrinsics[0:3] = rvec_by_id[camera_id]+ self.camera_parameters[camera_id].extrinsics[3:6] = tvec_by_id[camera_id]++ # Return optimized transforms+ return {+ cid: params.to_transformation_matrix(reference_frame=f"camera-{self.principal_camera_id}")+ for cid, params in self.camera_parameters.items()+ }diff --git a/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/scipy_bundle_adjuster.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/scipy_bundle_adjuster.pynew file mode 100644index 00000000..4c10385f--- /dev/null+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/scipy_bundle_adjuster.py@@ -0,0 +1,227 @@+import logging++import cv2+import numpy as np+from pydantic import BaseModel, Field+from scipy.optimize import least_squares+from skellycam.core.types.type_overloads import CameraIdString++from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.camera_math_models import (+ CameraMatrix,+ CameraDistortionCoefficients,+ TransformationMatrix,+)+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.shared_view_accumulator import MultiCameraTargetView++logger = logging.getLogger(__name__)+++class CameraParameters(BaseModel):+ camera_id: CameraIdString+ extrinsics: np.ndarray = Field(default_factory=lambda: np.zeros(6, dtype=np.float64))+ intrinsics: np.ndarray = Field(default_factory=lambda: np.zeros(9, dtype=np.float64))++ class Config:+ arbitrary_types_allowed = True++ @classmethod+ def from_calibration_data(+ cls,+ camera_id: CameraIdString,+ rotation_vector: np.ndarray,+ translation_vector: np.ndarray,+ camera_matrix: CameraMatrix,+ distortion_coeffs: CameraDistortionCoefficients,+ ) -> "CameraParameters":+ extrinsics = np.zeros(6, dtype=np.float64)+ extrinsics[0:3] = rotation_vector.flatten()+ extrinsics[3:6] = translation_vector.flatten()++ intrinsics = np.zeros(9, dtype=np.float64)+ intrinsics[0] = camera_matrix.focal_length_x+ intrinsics[1] = camera_matrix.focal_length_y+ intrinsics[2], intrinsics[3] = camera_matrix.principal_point++ dist = distortion_coeffs.coefficients if hasattr(distortion_coeffs, "coefficients") else distortion_coeffs+ num_dist = min(len(dist), 5)+ intrinsics[4: 4 + num_dist] = dist[0:num_dist]++ return cls(camera_id=camera_id, extrinsics=extrinsics, intrinsics=intrinsics)++ def to_transformation_matrix(self, reference_frame: str) -> TransformationMatrix:+ rotation_matrix = cv2.Rodrigues(self.extrinsics[0:3])[0]+ matrix = np.eye(4, dtype=np.float64)+ matrix[0:3, 0:3] = rotation_matrix+ matrix[0:3, 3] = self.extrinsics[3:6]+ return TransformationMatrix(matrix=matrix, reference_frame=reference_frame)++ def to_camera_matrix(self) -> np.ndarray:+ matrix = np.eye(3, dtype=np.float64)+ matrix[0, 0] = self.intrinsics[0]+ matrix[1, 1] = self.intrinsics[1]+ matrix[0, 2] = self.intrinsics[2]+ matrix[1, 2] = self.intrinsics[3]+ return matrix++ def to_distortion_coefficients(self) -> np.ndarray:+ return self.intrinsics[4:9]+++class ScipyBundleAdjuster(BaseModel):+ principal_camera_id: CameraIdString+ camera_parameters: dict[CameraIdString, CameraParameters] = Field(default_factory=dict)+ point_3d_coords: dict[int, np.ndarray] = Field(default_factory=dict)++ class Config:+ arbitrary_types_allowed = True++ @classmethod+ def create(+ cls,+ principal_camera_id: CameraIdString,+ camera_transforms: dict[CameraIdString, TransformationMatrix],+ camera_intrinsics: dict[CameraIdString, tuple[CameraMatrix, CameraDistortionCoefficients]],+ charuco_corners_3d: np.ndarray,+ ) -> "ScipyBundleAdjuster":+ camera_parameters = {}+ for camera_id, transform in camera_transforms.items():+ camera_matrix, dist_coeffs = camera_intrinsics[camera_id]+ rotation_vector = cv2.Rodrigues(transform.rotation_matrix)[0].flatten()+ translation = transform.translation_vector.vector.flatten()+ camera_parameters[camera_id] = CameraParameters.from_calibration_data(+ camera_id=camera_id,+ rotation_vector=rotation_vector,+ translation_vector=translation,+ camera_matrix=camera_matrix,+ distortion_coeffs=dist_coeffs,+ )++ point_3d_coords = {i: charuco_corners_3d[i].astype(np.float64).copy() for i in range(len(charuco_corners_3d))}+ return cls(+ principal_camera_id=principal_camera_id,+ camera_parameters=camera_parameters,+ point_3d_coords=point_3d_coords,+ )++ def _pack_parameters(self, camera_ids: list[CameraIdString],+ extrinsics_by_id: dict[CameraIdString, np.ndarray]) -> np.ndarray:+ """Pack all camera extrinsics into a single parameter vector."""+ params = []+ for camera_id in camera_ids:+ if camera_id != self.principal_camera_id: # Don't include fixed camera+ params.append(extrinsics_by_id[camera_id])+ return np.concatenate(params) if params else np.array([])++ def _unpack_parameters(self, params: np.ndarray, camera_ids: list[CameraIdString]) -> dict[+ CameraIdString, np.ndarray]:+ """Unpack parameter vector into camera extrinsics."""+ extrinsics_by_id = {}+ idx = 0+ for camera_id in camera_ids:+ if camera_id == self.principal_camera_id:+ # Principal camera is fixed+ extrinsics_by_id[camera_id] = self.camera_parameters[camera_id].extrinsics.copy()+ else:+ extrinsics_by_id[camera_id] = params[idx:idx + 6]+ idx += 6+ return extrinsics_by_id++ def _compute_residuals(+ self,+ params: np.ndarray,+ camera_ids: list[CameraIdString],+ intrinsics_by_id: dict[CameraIdString, tuple[np.ndarray, np.ndarray]],+ multi_camera_views: dict[int, MultiCameraTargetView],+ ) -> np.ndarray:+ """Compute reprojection residuals for all observations."""+ extrinsics_by_id = self._unpack_parameters(params, camera_ids)+ residuals = []++ for mc_view in multi_camera_views.values():+ for camera_id, camera_output in mc_view.camera_node_output_by_camera.items():+ if not camera_output.observation or camera_output.observation.charuco_empty:+ continue++ obs = camera_output.observation+ camera_matrix, dist_coeffs = intrinsics_by_id[camera_id]+ rvec = extrinsics_by_id[camera_id][0:3]+ tvec = extrinsics_by_id[camera_id][3:6]++ for corner_idx, corner_id in enumerate(obs.detected_charuco_corner_ids):+ corner_id_int = int(corner_id)+ if corner_id_int not in self.point_3d_coords:+ continue++ # Project point+ projected, _ = cv2.projectPoints(+ objectPoints=self.point_3d_coords[corner_id_int].reshape(1, 3),+ rvec=rvec.reshape(3, 1),+ tvec=tvec.reshape(3, 1),+ cameraMatrix=camera_matrix,+ distCoeffs=dist_coeffs,+ )++ # Compute residual+ observed = obs.detected_charuco_corners_image_coordinates[corner_idx]+ residuals.append(projected.squeeze()[0] - observed[0])+ residuals.append(projected.squeeze()[1] - observed[1])++ return np.array(residuals)++ def optimize(+ self,+ multi_camera_views: dict[int, MultiCameraTargetView],+ ) -> dict[CameraIdString, TransformationMatrix]:+ logger.info("Starting scipy bundle adjustment optimization...")++ # Extract parameters+ camera_ids = list(self.camera_parameters.keys())+ extrinsics_by_id: dict[CameraIdString, np.ndarray] = {}+ intrinsics_by_id: dict[CameraIdString, tuple[np.ndarray, np.ndarray]] = {}++ for camera_id in camera_ids:+ params = self.camera_parameters[camera_id]+ extrinsics_by_id[camera_id] = params.extrinsics.copy()+ camera_matrix = params.to_camera_matrix()+ dist_coeffs = params.to_distortion_coefficients()+ intrinsics_by_id[camera_id] = (camera_matrix, dist_coeffs)++ # Pack initial parameters+ x0 = self._pack_parameters(camera_ids, extrinsics_by_id)++ # Compute initial residuals+ initial_residuals = self._compute_residuals(x0, camera_ids, intrinsics_by_id, multi_camera_views)+ initial_cost = 0.5 * np.sum(initial_residuals ** 2)+ num_residuals = len(initial_residuals)++ logger.info(f"Initial cost: {initial_cost:.2f} ({num_residuals} residuals)")++ # Run optimization+ result = least_squares(+ fun=lambda params: self._compute_residuals(params, camera_ids, intrinsics_by_id, multi_camera_views),+ x0=x0,+ method='trf', # Trust Region Reflective - robust and good for large residual problems+ verbose=2,+ max_nfev=100, # Max function evaluations+ ftol=1e-6,+ gtol=1e-10,+ xtol=1e-8,+ )++ final_cost = 0.5 * np.sum(result.fun ** 2)+ logger.info(f"Optimization complete: Cost {initial_cost:.2f} -> {final_cost:.2f}")+ logger.info(f"Success: {result.success}, Message: {result.message}")+ logger.info(f"Function evaluations: {result.nfev}")++ # Unpack optimized parameters+ optimized_extrinsics = self._unpack_parameters(result.x, camera_ids)++ # Update camera parameters+ for camera_id in camera_ids:+ self.camera_parameters[camera_id].extrinsics[:] = optimized_extrinsics[camera_id]++ # Return optimized transforms+ return {+ cid: params.to_transformation_matrix(reference_frame=f"camera-{self.principal_camera_id}")+ for cid, params in self.camera_parameters.items()+ }diff --git a/freemocap/old/core_processes/process_motion_capture_videos/__init__.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/__init__.pysimilarity index 100%rename from freemocap/old/core_processes/process_motion_capture_videos/__init__.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/__init__.pydiff --git a/freemocap/old/core_processes/process_motion_capture_videos/processing_pipeline_functions/__init__.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/anipose_camera_calibration/__init__.pysimilarity index 100%rename from freemocap/old/core_processes/process_motion_capture_videos/processing_pipeline_functions/__init__.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/anipose_camera_calibration/__init__.pydiff --git a/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/anipose_camera_calibration/anipose_camera_calibrator.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/anipose_camera_calibration/anipose_camera_calibrator.pynew file mode 100644index 00000000..84ead59d--- /dev/null+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/anipose_camera_calibration/anipose_camera_calibrator.py@@ -0,0 +1,300 @@+import logging+from collections import namedtuple+from dataclasses import dataclass+from pathlib import Path+from typing import Callable, Union++import cv2+import numpy as np++from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.v1_capture_volume_calibration.anipose_camera_calibration import \+ freemocap_anipose+from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.charuco_groundplane_utils import \+ skellyforge_data, find_good_frame, CharucoVisibilityError, compute_basis_vectors_of_new_reference, \+ CharucoVelocityError+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.v1_capture_volume_calibration.charuco_stuff.charuco_board_definition import \+ CharucoBoardDefinition+from freemocap.utilities.get_video_paths import get_video_paths++logger = logging.getLogger(__name__)++Extrinsics = namedtuple("Extrinsics", ["rvecs", "tvecs"])+++@dataclass+class GroundPlaneSuccess:+ success: bool+ error: str = None+++class AniposeCameraCalibrator:+ def __init__(+ self,+ charuco_board_object: CharucoBoardDefinition,+ charuco_square_size: Union[int, float],+ calibration_recording_folder: Union[str, Path],+ progress_callback: Callable[[str], None] = lambda _: None++ ):+ self._charuco_board_object = charuco_board_object+ self._progress_callback = progress_callback++ if charuco_square_size == 1:+ warning_string = "Charuco square size is not set, so units of 3d reconstructed data will be in units of `however_long_the_black_edge_of_the_charuco_square_was`. Please input `charuco_square_size` in millimeters (or your preferred unity of length)"+ logger.warning(warning_string)+ self._progress_callback(warning_string)+ self._charuco_square_size = charuco_square_size+ self._recording_folder_path = Path(calibration_recording_folder)++ self._calibration_videos_folder_path = self._recording_folder_path / "synchronized_videos"+ self._get_video_paths()+ self._initialize_anipose_objects()++ @property+ def calibration_toml_path(self) -> Path:+ recording_name = self._recording_folder_path.stem+ toml_name = f"{recording_name}_camera_calibration.toml"+ return self._recording_folder_path / toml_name++ def _get_video_paths(self):+ self._list_of_video_paths = get_video_paths(path_to_video_folder=Path(self._calibration_videos_folder_path))+ if len(self._list_of_video_paths) == 0:+ error_message = f"No calibration videos found in folder: {str(self._calibration_videos_folder_path)}"+ logger.error(error_message)+ raise ValueError(error_message)+ if len(self._list_of_video_paths) < 2:+ error_message = f"At least two calibration videos are required for camera calibration, but only {len(self._list_of_video_paths)} video(s) were found in folder: {str(self._calibration_videos_folder_path)}"+ logger.error(error_message)+ raise ValueError(error_message)++ def _initialize_anipose_objects(self):+ list_of_camera_names = [this_video_path.stem for this_video_path in self._list_of_video_paths]+ self._anipose_camera_group_object = freemocap_anipose.CameraGroup.from_names(list_of_camera_names)++ # add metadata+ self._anipose_camera_group_object.metadata["charuco_square_size"] = self._charuco_square_size+ self._anipose_camera_group_object.metadata["charuco_board_object"] = str(self._charuco_board_object)+ self._anipose_camera_group_object.metadata["path_to_recorded_videos"] = str(+ self._calibration_videos_folder_path+ )+ self._anipose_camera_group_object.metadata["date_time_calibrated"] = str(np.datetime64("now"))++ self._anipose_charuco_board = freemocap_anipose.AniposeCharucoBoard(+ self._charuco_board_object.number_of_squares_width,+ self._charuco_board_object.number_of_squares_height,+ square_length=self._charuco_square_size, # mm+ marker_length=self._charuco_square_size * 0.8,+ marker_bits=4,+ dict_size=50,+ )++ def calibrate_camera_capture_volume(self,+ pin_camera_0_to_origin: bool = False,+ use_charuco_as_groundplane: bool = False) -> tuple[Path, GroundPlaneSuccess]:+ video_paths_list_of_list_of_strings = [[str(this_path)] for this_path in self._list_of_video_paths]++ self._anipose_camera_group_object.calibrate_videos(+ video_paths_list_of_list_of_strings, self._anipose_charuco_board+ )+ success_str = "Anipose Calibration Successful!"+ logger.info(success_str)+ self._progress_callback(success_str)+ self._anipose_camera_group_object.metadata["groundplane_calibration"] = False++ if pin_camera_0_to_origin:+ self._anipose_camera_group_object = self.pin_camera_zero_to_origin(self._anipose_camera_group_object)+ groundplane_success = None++ if use_charuco_as_groundplane:+ self._anipose_camera_group_object, groundplane_success = self.set_charuco_board_as_groundplane(+ self._anipose_camera_group_object)+ if groundplane_success.success:+ self._anipose_camera_group_object.metadata["groundplane_calibration"] = True++ self.get_real_world_matrices(self._anipose_camera_group_object)++ self._anipose_camera_group_object.dump(self.calibration_toml_path)+ logger.debug(+ f"anipose camera calibration data saved tor - {str(self.calibration_toml_path)}"+ )++ def pin_camera_zero_to_origin(self, cam_group: freemocap_anipose.CameraGroup):+ """+ Re-express all camera extrinsics relative to camera 0.++ This function performs two operations:+ 1. Rotates all camera coordinate systems so that camera 0's orientation becomes the new world frame.+ 2. Shifts the world origin to camera 0's position, making it the new coordinate origin (0, 0, 0).++ The result is that:+ - Camera 0 ends up with an identity rotation and zero translation.+ - All other cameras are expressed relative to camera 0's original position and orientation.++ Args:+ cam_group (freemocap_anipose.CameraGroup): A group of calibrated cameras whose extrinsics will be adjusted in place.+ """++ rvecs_new = self.align_rotations_to_cam0(cam_group=cam_group)+ cam_group.set_rotations(rvecs_new)+ tvecs_new = self.shift_origin_to_cam0(cam_group=cam_group)+ cam_group.set_translations(tvecs_new)+ return cam_group++ def align_rotations_to_cam0(self, cam_group: freemocap_anipose.CameraGroup):+ rvecs = cam_group.get_rotations()+ # get rotation of cam 0 to world+ R0, _ = cv2.Rodrigues(rvecs[0])++ rvecs_new = np.empty_like(rvecs)+ # rotates each cameras coordinate system into the new world space+ # R0 maps world -> cam0, so R0.T (which is also the inverse) maps cam0 -> world+ # R0 * R0^-1 = identity matrix, so this makes R0 the origin+ # then we map every other camera into the new world space+ for i in range(rvecs.shape[0]):+ Ri, _ = cv2.Rodrigues(rvecs[i])+ Ri_new, _ = cv2.Rodrigues(Ri @ R0.T)+ rvecs_new[i] = Ri_new.flatten()+ return rvecs_new++ def shift_origin_to_cam0(self, cam_group: freemocap_anipose.CameraGroup):+ # Get original translation and rotation vectors+ tvecs = cam_group.get_translations()+ rvecs = cam_group.get_rotations()++ # Extract camera 0's rotation and translation+ camera_0_translation = tvecs[0, :]+ camera_0_rotation = rvecs[0, :]++ # Get 3x3 rotation matrix for world -> cam 0+ R0, _ = cv2.Rodrigues(camera_0_rotation)++ # Get the vector that moves the world origin to cam 0 in the world frame+ delta_to_origin_world = - R0.T @ camera_0_translation++ # Create new translation vectors array+ new_tvecs = np.zeros_like(tvecs)++ # Apply offset to each camera's translation vector+ for cam_i in range(tvecs.shape[0]):+ Ri, _ = cv2.Rodrigues(rvecs[cam_i, :])+ # Transform the world offset into this camera's coordinate frame+ delta_to_origin_camera_i = Ri @ delta_to_origin_world+ # Update the translation vector+ new_tvecs[cam_i, :] = tvecs[cam_i, :] + delta_to_origin_camera_i+ return new_tvecs++ def set_charuco_board_as_groundplane(self, cam_group: freemocap_anipose.CameraGroup):+ # Get the camera group object+ logger.info("Getting 2d Charuco data")++ charuco_2d_xy: np.ndarray = cam_group.charuco_2d_data++ if charuco_2d_xy is None:+ error_message = "Charuco 2d data was not retrieved successfully. Check for an error during calibration."+ logger.error(error_message)+ raise ValueError(error_message)+ logger.info("Charuco 2d data retrieved successfully with shape: "+ f"{charuco_2d_xy.shape}")+ charuco_2d_xy = charuco_2d_xy.astype(np.float64)+ num_cameras, num_frames, num_tracked_points, _ = charuco_2d_xy.shape+ charuco_2d_flat = charuco_2d_xy.reshape(num_cameras, -1, 2)++ logger.info("Getting 3d Charuco data")+ charuco_3d_flat = self._anipose_camera_group_object.triangulate(+ charuco_2d_flat)+ charuco_3d_xyz = charuco_3d_flat.reshape(num_frames, num_tracked_points, 3)+ logger.info(f"Charuco 3d data reconstructed with shape: {charuco_3d_xyz.shape}")++ charuco_3d_xyz_interpolated = skellyforge_data(raw_charuco_data=charuco_3d_xyz)++ try:+ charuco_still_frame_idx = find_good_frame(charuco_data3d_fr_id_xyz=charuco_3d_xyz_interpolated,+ number_of_squares_width=self._charuco_board_object.number_of_squares_width,+ number_of_squares_height=self._charuco_board_object.number_of_squares_height, )+ except CharucoVisibilityError as e:+ logger.warning(+ "Ground-plane alignment skipped โ reverting to original calibration: %s",+ e,+ exc_info=True, )+ success = GroundPlaneSuccess(success=False, error=str(e))+ return cam_group, success+ except CharucoVelocityError as e:+ logger.warning(+ "Ground-plane alignment skipped โ reverting to original calibration: %s",+ e,+ exc_info=True, )+ success = GroundPlaneSuccess(success=False, error=str(e))+ return cam_group, success++ charuco_frame = charuco_3d_xyz_interpolated[charuco_still_frame_idx]++ x_hat, y_hat, z_hat = compute_basis_vectors_of_new_reference(charuco_frame,+ number_of_squares_width=self._charuco_board_object.number_of_squares_width,+ number_of_squares_height=self._charuco_board_object.number_of_squares_height)+ charuco_origin_in_world = charuco_frame[0]+ rmat_charuco_to_world = np.column_stack([x_hat, y_hat,+ z_hat]) # rotation matrix that transforms a point in the new world reference frame(defined by the charuco) into legacy world frame++ extrinsics = self.adjust_world_reference_frame_to_charuco(cam_group=cam_group,+ charuco_origin_in_world=charuco_origin_in_world,+ rmat_charuco_to_world=rmat_charuco_to_world)+ cam_group.set_rotations(extrinsics.rvecs)+ cam_group.set_translations(extrinsics.tvecs)+ success = GroundPlaneSuccess(success=True)+ logger.info("Anipose camera calibration data adjusted to set charuco board as ground plane")++ charuco_3d_flat = self._anipose_camera_group_object.triangulate(+ charuco_2d_flat)+ charuco_3d_xyz = charuco_3d_flat.reshape(num_frames, num_tracked_points, 3)+ logger.info(f"Charuco 3d data reconstructed with shape: {charuco_3d_xyz.shape}")++ charuco_3d_xyz_interpolated = skellyforge_data(raw_charuco_data=charuco_3d_xyz)++ charuco_save_path = self._recording_folder_path / "output_data" / "charuco_3d_xyz.npy"+ np.save(charuco_save_path,+ charuco_3d_xyz_interpolated) # NOTE - there may be a more robust way to get this path but this is the simplest for now+ logger.info(f"Charuco 3d data saved to {charuco_save_path}")++ return cam_group, success++ def adjust_world_reference_frame_to_charuco(self,+ cam_group: freemocap_anipose.CameraGroup,+ charuco_origin_in_world: np.ndarray,+ rmat_charuco_to_world: np.ndarray):++ tvecs = cam_group.get_translations()+ rvecs = cam_group.get_rotations()++ tvecs_new = np.zeros_like(tvecs)+ rvecs_new = np.zeros_like(rvecs)++ for i in range(tvecs.shape[0]):+ rmat_world_to_cam_i, _ = cv2.Rodrigues(rvecs[i])+ # Xcam = Rc->w*Xworld + tvec (base formula for this transformation)+ t_delta = rmat_world_to_cam_i @ charuco_origin_in_world # Rc->w*Xworld (rmat is Rc->w)+ tvecs_new[i] = t_delta + tvecs[i] # Rc->w*Xworld + tvec++ new_rmat = rmat_world_to_cam_i @ rmat_charuco_to_world # composes w' -> w (rotation matrix) with w -> c (rmat) to get w' -> c+ new_rvec, _ = cv2.Rodrigues(new_rmat)+ rvecs_new[i] = new_rvec.flatten()+ return Extrinsics(rvecs_new, tvecs_new)++ def get_real_world_matrices(self,+ cam_group: freemocap_anipose.CameraGroup):+ rvecs = cam_group.get_rotations()+ tvecs = cam_group.get_translations()++ positions = []+ orientations = []+ for i in range(tvecs.shape[0]):+ rmat_world_to_cam_i, _ = cv2.Rodrigues(rvecs[i])++ rmat_cam_to_world = rmat_world_to_cam_i.T+ t_world = -rmat_cam_to_world @ tvecs[i]+ positions.append(t_world.astype(float).tolist())+ orientations.append(rmat_cam_to_world.astype(float).tolist())++ cam_group.set_world_positions(positions)+ cam_group.set_world_orientations(orientations)++ return positions, orientationsdiff --git a/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/freemocap_anipose.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/anipose_camera_calibration/freemocap_anipose.pysimilarity index 95%rename from freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/freemocap_anipose.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/anipose_camera_calibration/freemocap_anipose.pyindex 3d0b8c8a..6aa8543c 100644--- a/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/freemocap_anipose.py+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/anipose_camera_calibration/freemocap_anipose.py@@ -4,11 +4,12 @@import itertoolsimport loggingimport multiprocessing-from pathlib import Pathimport queueimport timefrom collections import defaultdict, Counterfrom copy import copy+from pathlib import Path+from typing import Listimport cv2import numpy as np@@ -22,17 +23,34 @@ from scipy.cluster.hierarchy import linkage, fclusterfrom scipy.cluster.vq import whitenfrom scipy.linalg import inv as inversefrom scipy.sparse import dok_matrix+# from skellytracker.process_folder_of_videos import process_list_of_videos+# from skellytracker.trackers.charuco_tracker.charuco_model_info import CharucoModelInfo, CharucoTrackingParamsfrom tqdm import trange-from typing import List--from skellytracker.trackers.charuco_tracker.charuco_model_info import CharucoModelInfo, CharucoTrackingParams-from skellytracker.process_folder_of_videos import process_list_of_videosnumba_logger = logging.getLogger("numba")numba_logger.setLevel(logging.WARNING)logger = logging.getLogger(__name__)+ARUCO_DICTS = {+ (4, 50): cv2.aruco.DICT_4X4_50,+ (5, 50): cv2.aruco.DICT_5X5_50,+ (6, 50): cv2.aruco.DICT_6X6_50,+ (7, 50): cv2.aruco.DICT_7X7_50,+ (4, 100): cv2.aruco.DICT_4X4_100,+ (5, 100): cv2.aruco.DICT_5X5_100,+ (6, 100): cv2.aruco.DICT_6X6_100,+ (7, 100): cv2.aruco.DICT_7X7_100,+ (4, 250): cv2.aruco.DICT_4X4_250,+ (5, 250): cv2.aruco.DICT_5X5_250,+ (6, 250): cv2.aruco.DICT_6X6_250,+ (7, 250): cv2.aruco.DICT_7X7_250,+ (4, 1000): cv2.aruco.DICT_4X4_1000,+ (5, 1000): cv2.aruco.DICT_5X5_1000,+ (6, 1000): cv2.aruco.DICT_6X6_1000,+ (7, 1000): cv2.aruco.DICT_7X7_1000,+}+@jit(nopython=True, parallel=False)def triangulate_simple(points, camera_mats):@@ -381,6 +399,8 @@ class Camera:size=None,rvec=np.zeros(3),tvec=np.zeros(3),+ world_orientation=np.eye(3),+ world_position=np.zeros(3),name=None,extra_dist=False,):@@ -389,6 +409,8 @@ class Camera:self.set_size(size)self.set_rotation(rvec)self.set_translation(tvec)+ self.set_world_orientation(world_orientation)+ self.set_world_position(world_position)self.set_name(name)self.extra_dist = extra_dist@@ -400,6 +422,8 @@ class Camera:"distortions": self.get_distortions().tolist(),"rotation": self.get_rotation().tolist(),"translation": self.get_translation().tolist(),+ "world_orientation": self.get_world_orientation().tolist(),+ "world_position": self.get_world_position().tolist()}def load_dict(self, d):@@ -410,6 +434,9 @@ class Camera:self.set_name(d["name"])self.set_size(d["size"])+ self.set_world_orientation(d.get("world_orientation", np.eye(3)))+ self.set_world_position(d.get("world_position", np.zeros(3)))+def from_dict(d):cam = Camera()cam.load_dict(d)@@ -453,6 +480,18 @@ class Camera:def get_translation(self):return self.tvec+ def set_world_orientation(self, world_orientation):+ self.world_orientation = np.asarray(world_orientation, dtype="float64").reshape(3, 3)++ def get_world_orientation(self):+ return self.world_orientation++ def set_world_position(self, world_position):+ self.world_position = np.array(world_position, dtype="float64").ravel()++ def get_world_position(self):+ return self.world_position+def get_extrinsics_mat(self):return make_M(self.rvec, self.tvec)@@ -546,6 +585,8 @@ class Camera:tvec=self.get_translation().copy(),name=self.get_name(),extra_dist=self.extra_dist,+ world_orientation=self.get_world_orientation().copy(),+ world_position=self.get_world_position().copy())@@ -1770,6 +1811,20 @@ class CameraGroup:for cam, tvec in zip(self.cameras, tvecs):cam.set_translation(tvec)+ def set_world_positions(self, positions):+ for cam, position, in zip(self.cameras, positions):+ cam.set_world_position(position)++ def set_world_orientations(self, orientations):+ for cam, orientation in zip(self.cameras, orientations):+ cam.set_world_orientation(orientation)++ def get_world_positions(self):+ return np.stack([cam.get_world_position() for cam in self.cameras])++ def get_world_orientations(self):+ return np.stack([cam.get_world_orientation() for cam in self.cameras])+def get_rotations(self):rvecs = []for cam in self.cameras:@@ -1842,14 +1897,13 @@ class CameraGroup:return error, merged, charuco_frames- def get_rows_videos(self, videos: List[List[str]], board: "AniposeCharucoBoard", verbose=True):+ def get_rows_videos(self, videos: List[List[str]], board: "AniposeCharucoBoard", verbose: bool = True):num_corners = board.total_size- if board.total_size != 24:- raise ValueError("AniposeCharucoBoard only supports 24 corners, got {}".format(board.total_size))- self._get_charuco_2d_data(videos)+ self._get_charuco_2d_data(videos=videos, board=board)if self.charuco_2d_data is None:- raise ValueError("Charuco 2D data has not been initialized. Call _get_charuco_2d_data() first, or check for errors in the video processing.")+ raise ValueError(+ "Charuco 2D data has not been initialized. Call _get_charuco_2d_data() first, or check for errors in the video processing.")all_rows = []@@ -1857,14 +1911,13 @@ class CameraGroup:for camera_number in range(num_cameras):camera_rows = []for frame in range(num_frames):- # TODO: check each frame based on anipose's conditionsfilled = self.charuco_2d_data[camera_number, frame, :, :]filled = filled.astype(np.float32)filled = np.reshape(filled, (num_corners, 1, 2)) # Add empty column anipose expectsmask = (~np.isnan(filled[:, :, 0])) & (~np.isnan(filled[:, :, 1]))non_empty_ids = np.where(mask)[0]corners = filled[non_empty_ids, :, :]- non_empty_ids = non_empty_ids.reshape(-1, 1) # Add empty column anipose expects+ non_empty_ids = non_empty_ids.reshape(-1, 1) # Add empty column anipose expectsif corners.shape[0] != 0:row = {"framenum": (0, frame),@@ -1879,10 +1932,9 @@ class CameraGroup:for i, rows in enumerate(all_rows):print(f"\tCamera {i} has {len(rows)} frames with detected corners.")-return all_rows- def _get_charuco_2d_data(self, videos: List[List[str]]):+ def _get_charuco_2d_data(self, videos: List[List[str]], board: "AniposeCharucoBoard"):"""Processes a list of a list of videos to extract Charuco 2D data.@@ -1891,14 +1943,17 @@ class CameraGroup:video_paths = [Path(video[0]) for video in videos]charuco_2d_data = process_list_of_videos(model_info=CharucoModelInfo(),- tracking_params=CharucoTrackingParams(),+ tracking_params=CharucoTrackingParams(+ charuco_squares_x_in=board.squaresX,+ charuco_squares_y_in=board.squaresY,+ charuco_dict_id=ARUCO_DICTS[(board.marker_bits, board.dict_size)]+ ),video_paths=video_paths,num_processes=min(len(videos), multiprocessing.cpu_count() - 1),)self.charuco_2d_data = charuco_2d_data-def set_camera_sizes_videos(self, videos):for cix, (cam, cam_videos) in enumerate(zip(self.cameras, videos)):rows_cam = []@@ -1908,13 +1963,13 @@ class CameraGroup:cam.set_size(size)def calibrate_videos(- self,- videos: List[List[str]],- board: "AniposeCharucoBoard",- init_intrinsics=True,- init_extrinsics=True,- verbose=True,- **kwargs,+ self,+ videos,+ board: "AniposeCharucoBoard",+ init_intrinsics=True,+ init_extrinsics=True,+ verbose=True,+ **kwargs,):"""Takes as input a list of list of video filenames, one list of each camera.Also takes a board which specifies what should be detected in the videos"""@@ -2004,25 +2059,8 @@ class AniposeCharucoBoard(CharucoBoard):self.square_length = square_lengthself.marker_length = marker_lengthself.manually_verify = manually_verify-- ARUCO_DICTS = {- (4, 50): cv2.aruco.DICT_4X4_50,- (5, 50): cv2.aruco.DICT_5X5_50,- (6, 50): cv2.aruco.DICT_6X6_50,- (7, 50): cv2.aruco.DICT_7X7_50,- (4, 100): cv2.aruco.DICT_4X4_100,- (5, 100): cv2.aruco.DICT_5X5_100,- (6, 100): cv2.aruco.DICT_6X6_100,- (7, 100): cv2.aruco.DICT_7X7_100,- (4, 250): cv2.aruco.DICT_4X4_250,- (5, 250): cv2.aruco.DICT_5X5_250,- (6, 250): cv2.aruco.DICT_6X6_250,- (7, 250): cv2.aruco.DICT_7X7_250,- (4, 1000): cv2.aruco.DICT_4X4_1000,- (5, 1000): cv2.aruco.DICT_5X5_1000,- (6, 1000): cv2.aruco.DICT_6X6_1000,- (7, 1000): cv2.aruco.DICT_7X7_1000,- }+ self.marker_bits = marker_bits+ self.dict_size = dict_sizedkey = (marker_bits, dict_size)self.dictionary = cv2.aruco.getPredefinedDictionary(ARUCO_DICTS[dkey])diff --git a/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/get_anipose_calibration_object.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/anipose_camera_calibration/get_anipose_calibration_object.pysimilarity index 71%rename from freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/get_anipose_calibration_object.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/anipose_camera_calibration/get_anipose_calibration_object.pyindex 27984a5c..c04541b1 100644--- a/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/get_anipose_calibration_object.py+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/anipose_camera_calibration/get_anipose_calibration_object.py@@ -4,16 +4,17 @@ import shutilfrom pathlib import Pathfrom typing import Union-from freemocap.old.core_processes.capture_volume_calibration.anipose_camera_calibration.run_anipose_calibration_algorithm import \- AniposeCameraGroup+from freemocap.core_processes.capture_volume_calibration.anipose_camera_calibration import (+ freemocap_anipose,+)from freemocap.system.paths_and_filenames.path_getters import get_last_successful_calibration_toml_pathlogger = logging.getLogger(__name__)def load_most_recent_anipose_calibration_toml(- save_copy_of_calibration_to_this_path: Union[str, Path, None] = None-) -> AniposeCameraGroup:+ save_copy_of_calibration_to_this_path: Union[str, Path, None] = None+) -> freemocap_anipose.CameraGroup:most_recent_calibration_toml_path = get_last_successful_calibration_toml_path()logger.info(f"loading `most recent calibration from:{str(most_recent_calibration_toml_path)}")if save_copy_of_calibration_to_this_path is not None:@@ -25,7 +26,7 @@ def load_most_recent_anipose_calibration_toml()try:- camera_group = AniposeCameraGroup.load(str(most_recent_calibration_toml_path))+ camera_group = freemocap_anipose.CameraGroup.load(str(most_recent_calibration_toml_path))except Exception as e:logger.exception(e)raise@@ -33,19 +34,19 @@ def load_most_recent_anipose_calibration_toml(def load_anipose_calibration_toml_from_path(- camera_calibration_data_toml_path: Union[str, Path],- save_copy_of_calibration_to_this_path: Union[str, Path, None] = None,-) -> AniposeCameraGroup:+ camera_calibration_data_toml_path: Union[str, Path],+ save_copy_of_calibration_to_this_path: Union[str, Path, None] = None,+) -> freemocap_anipose.CameraGroup:logger.info(f"loading camera calibration file from:{str(camera_calibration_data_toml_path)}")try:- anipose_calibration_object = AniposeCameraGroup.load(str(camera_calibration_data_toml_path))+ anipose_calibration_object = freemocap_anipose.CameraGroup.load(str(camera_calibration_data_toml_path))if save_copy_of_calibration_to_this_path is not None:copy_toml_path = str(Path(save_copy_of_calibration_to_this_path) / Path(camera_calibration_data_toml_path).name)if Path(copy_toml_path).is_file() and not filecmp.cmp(- str(camera_calibration_data_toml_path), copy_toml_path+ str(camera_calibration_data_toml_path), copy_toml_path):logger.info(f"Saving copy of {camera_calibration_data_toml_path} to {save_copy_of_calibration_to_this_path}"@@ -59,11 +60,11 @@ def load_anipose_calibration_toml_from_path(def load_calibration_from_session_id(- session_calibration_file_path: Union[str, Path],-) -> AniposeCameraGroup:+ session_calibration_file_path: Union[str, Path],+) -> freemocap_anipose.CameraGroup:logger.info(f"loading camera calibration file from:{str(session_calibration_file_path)}")try:- return AniposeCameraGroup.load(str(session_calibration_file_path))+ return freemocap_anipose.CameraGroup.load(str(session_calibration_file_path))except Exception as e:logger.error(f"Failed to load anipose calibration info from {str(session_calibration_file_path)}")raise ediff --git a/freemocap/old/core_processes/capture_volume_calibration/by_camera_reprojection_filtering.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/by_camera_reprojection_filtering.pysimilarity index 82%rename from freemocap/old/core_processes/capture_volume_calibration/by_camera_reprojection_filtering.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/by_camera_reprojection_filtering.pyindex af1a6f15..b4cd5ab2 100644--- a/freemocap/old/core_processes/capture_volume_calibration/by_camera_reprojection_filtering.py+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/by_camera_reprojection_filtering.py@@ -3,24 +3,23 @@ from pathlib import Pathfrom typing import Tuple, Unionimport numpy as np-from matplotlib import pyplot as plt--from freemocap.old.core_processes.capture_volume_calibration.save_3d_data_to_npy import (+from freemocap.core_processes.capture_volume_calibration.save_3d_data_to_npy import (save_3d_data_to_npy,)-from freemocap.old.core_processes.capture_volume_calibration.triangulate_3d_data import triangulate_3d_data-from freemocap.old.data_layer.recording_models.post_processing_parameter_models import ProcessingParameterModel+from freemocap.core_processes.capture_volume_calibration.triangulate_3d_data import triangulate_3d_data+from freemocap.data_layer.recording_models.post_processing_parameter_models import ProcessingParameterModel+from matplotlib import pyplot as pltlogger = logging.getLogger(__name__)def run_reprojection_error_filtering(- image_data_numCams_numFrames_numTrackedPts_XYZ: np.ndarray,- raw_skel3d_frame_marker_xyz: np.ndarray,- skeleton_reprojection_error_cam_fr_mar: np.ndarray,- skeleton_reprojection_error_fr_mar: np.ndarray,- anipose_calibration_object,- processing_parameters: ProcessingParameterModel,+ image_data_numCams_numFrames_numTrackedPts_XYZ: np.ndarray,+ raw_skel3d_frame_marker_xyz: np.ndarray,+ skeleton_reprojection_error_cam_fr_mar: np.ndarray,+ skeleton_reprojection_error_fr_mar: np.ndarray,+ anipose_calibration_object,+ processing_parameters: ProcessingParameterModel,) -> np.ndarray:"""Runs reprojection error filtering on 3d data, saves the filtered 3d data and reprojection error data, and creates and saves a debug plot.@@ -35,7 +34,7 @@ def run_reprojection_error_filtering(:return: filtered 3d data"""if hasattr(- processing_parameters.tracking_model_info, "num_tracked_points_body"+ processing_parameters.tracking_model_info, "num_tracked_points_body"): # we don't want to reproject hand and face datanum_tracked_points = processing_parameters.tracking_model_info.num_tracked_points_bodyelse:@@ -67,25 +66,27 @@ def run_reprojection_error_filtering(plot_reprojection_error(raw_reprojection_error_frame_marker=skeleton_reprojection_error_fr_mar,filtered_reprojection_error_frame_marker=reprojection_filtered_skeleton_reprojection_error_fr_mar,- reprojection_error_threshold=float(np.nanpercentile(- skeleton_reprojection_error_cam_fr_mar,- processing_parameters.anipose_triangulate_3d_parameters_model.reprojection_error_confidence_cutoff,- )),+ reprojection_error_threshold=float(+ np.nanpercentile(+ skeleton_reprojection_error_cam_fr_mar,+ processing_parameters.anipose_triangulate_3d_parameters_model.reprojection_error_confidence_cutoff,+ )+ ),output_folder_path=processing_parameters.recording_info_model.raw_data_folder_path,)return reprojection_filtered_skel3d_frame_marker_xyzdef filter_by_reprojection_error(- reprojection_error_camera_frame_marker: np.ndarray,- reprojection_error_frame_marker: np.ndarray,- reprojection_error_confidence_threshold: float,- image_2d_data: np.ndarray,- raw_skel3d_frame_marker_xyz: np.ndarray,- anipose_calibration_object,- num_tracked_points: int,- use_triangulate_ransac: bool = False,- minimum_cameras_to_reproject: int = 3,+ reprojection_error_camera_frame_marker: np.ndarray,+ reprojection_error_frame_marker: np.ndarray,+ reprojection_error_confidence_threshold: float,+ image_2d_data: np.ndarray,+ raw_skel3d_frame_marker_xyz: np.ndarray,+ anipose_calibration_object,+ num_tracked_points: int,+ use_triangulate_ransac: bool = False,+ minimum_cameras_to_reproject: int = 3,) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:total_cameras = image_2d_data.shape[0]num_cameras_to_remove = 1@@ -168,16 +169,16 @@ def _nan_data_above_threshold(unique_frame_marker_list: list, retriangulated_datdef _get_data_to_reproject(- num_cameras_to_remove: int,- reprojection_error_threshold: float,- reprojError_cam_frame_marker: np.ndarray,- input_2d_data_camera_frame_marker_xy: np.ndarray,+ num_cameras_to_remove: int,+ reprojection_error_threshold: float,+ reprojError_cam_frame_marker: np.ndarray,+ input_2d_data_camera_frame_marker_xy: np.ndarray,) -> tuple[np.ndarray, list]:indices_above_threshold = np.nonzero(reprojError_cam_frame_marker > reprojection_error_threshold)logger.debug(f"SHAPE OF INDICES ABOVE THRESHOLD: {indices_above_threshold[0].shape}")total_frame_marker_combos = (- input_2d_data_camera_frame_marker_xy.shape[1] * input_2d_data_camera_frame_marker_xy.shape[2]+ input_2d_data_camera_frame_marker_xy.shape[1] * input_2d_data_camera_frame_marker_xy.shape[2])unique_frame_marker_list = _get_unique_frame_marker_list(indices_above_threshold=indices_above_threshold)logger.info(@@ -201,15 +202,15 @@ def _get_data_to_reproject(def _get_unique_frame_marker_list(- indices_above_threshold: np.ndarray,+ indices_above_threshold: np.ndarray,) -> list:return list(set(zip(indices_above_threshold[1], indices_above_threshold[2])))def _get_camera_frame_marker_lists_to_reproject(- reprojError_cam_frame_marker: np.ndarray,- frame_marker_list: list,- num_cameras_to_remove: int,+ reprojError_cam_frame_marker: np.ndarray,+ frame_marker_list: list,+ num_cameras_to_remove: int,) -> Tuple[list, list, list]:"""Generate the lists of cameras, frames, and markers to reproject based on the given input.@@ -233,14 +234,14 @@ def _get_camera_frame_marker_lists_to_reproject(def _set_unincluded_data_to_nans(- input_2d_data: np.ndarray,- frames_with_reprojection_error: list,- markers_with_reprojection_error: list,- cameras_to_remove: list[list[int]],+ input_2d_data: np.ndarray,+ frames_with_reprojection_error: list,+ markers_with_reprojection_error: list,+ cameras_to_remove: list[list[int]],) -> np.ndarray:data_to_reproject = input_2d_data.copy()for list_of_cameras, frame, marker in zip(- cameras_to_remove, frames_with_reprojection_error, markers_with_reprojection_error+ cameras_to_remove, frames_with_reprojection_error, markers_with_reprojection_error):for camera in list_of_cameras:data_to_reproject[camera, frame, marker, :] = np.nan@@ -248,10 +249,10 @@ def _set_unincluded_data_to_nans(def plot_reprojection_error(- raw_reprojection_error_frame_marker: np.ndarray,- filtered_reprojection_error_frame_marker: np.ndarray,- reprojection_error_threshold: float,- output_folder_path: Union[str, Path],+ raw_reprojection_error_frame_marker: np.ndarray,+ filtered_reprojection_error_frame_marker: np.ndarray,+ reprojection_error_threshold: float,+ output_folder_path: Union[str, Path],) -> None:title = "Mean Reprojection Error Per Frame"file_name = "debug_reprojection_error_filtering.png"diff --git a/freemocap/old/data_layer/__init__.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/charuco_stuff/__init__.pysimilarity index 100%rename from freemocap/old/data_layer/__init__.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/charuco_stuff/__init__.pydiff --git a/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/charuco_stuff/charuco_board_definition.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/charuco_stuff/charuco_board_definition.pynew file mode 100644index 00000000..46590ca6--- /dev/null+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/charuco_stuff/charuco_board_definition.py@@ -0,0 +1,51 @@+from dataclasses import dataclass+from typing import Dict++import cv2+++@dataclass+class CharucoBoardDefinition:+ name: str+ number_of_squares_width: int+ number_of_squares_height: int+ black_square_side_length: float = 1.0+ aruco_marker_length_proportional: float = 0.8+ aruco_marker_dict: Dict = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_50)++ def __post_init__(self):+ self.charuco_board = cv2.aruco.CharucoBoard(+ size=[self.number_of_squares_width, self.number_of_squares_height],+ squareLength=self.black_square_side_length,+ markerLength=self.aruco_marker_length_proportional,+ dictionary=self.aruco_marker_dict,+ )++ self.number_of_charuco_corners = (self.number_of_squares_width - 1) * (self.number_of_squares_height - 1)+++def charuco_7x5() -> CharucoBoardDefinition:+ return CharucoBoardDefinition(+ name="7x5 Charuco",+ number_of_squares_width=7,+ number_of_squares_height=5,+ black_square_side_length=1,+ aruco_marker_length_proportional=0.8,+ )+++def charuco_5x3() -> CharucoBoardDefinition:+ return CharucoBoardDefinition(+ name="5x3 Charuco",+ number_of_squares_width=5,+ number_of_squares_height=3,+ black_square_side_length=1,+ aruco_marker_length_proportional=0.8,+ )+++CHARUCO_BOARD_IMAGES_URL = "https://github.com/freemocap/freemocap/blob/main/freemocap/assets/charuco/"+CHARUCO_BOARDS = {+ "7x5 Charuco": charuco_7x5,+ "5x3 Charuco": charuco_5x3,+}diff --git a/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/run_anipose_capture_volume_calibration.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/run_anipose_capture_volume_calibration.pynew file mode 100644index 00000000..be90185f--- /dev/null+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/run_anipose_capture_volume_calibration.py@@ -0,0 +1,35 @@+import threading+from pathlib import Path+from typing import Callable, Union++from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.v1_capture_volume_calibration.anipose_camera_calibration.anipose_camera_calibrator import \+ GroundPlaneSuccess, AniposeCameraCalibrator+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.v1_capture_volume_calibration.charuco_stuff.charuco_board_definition import \+ CharucoBoardDefinition+++async def async_run_anipose_capture_volume_calibration(**kwargs):+ run_anipose_capture_volume_calibration(**kwargs)+++def run_anipose_capture_volume_calibration(+ charuco_board_definition: CharucoBoardDefinition,+ charuco_square_size: float,+ calibration_recording_folder: Union[str, Path],+ kill_event: threading.Event,+ pin_camera_0_to_origin: bool = True,+ use_charuco_as_groundplane: bool = True,+ progress_callback: Callable[[str], None] = lambda _: None,+) -> tuple[Path, GroundPlaneSuccess]:+ anipose_camera_calibrator = AniposeCameraCalibrator(+ charuco_board_object=charuco_board_definition,+ charuco_square_size=charuco_square_size,+ calibration_recording_folder=calibration_recording_folder,+ progress_callback=progress_callback,+ )+ toml_path, groundplane_success = anipose_camera_calibrator.calibrate_camera_capture_volume(+ pin_camera_0_to_origin=pin_camera_0_to_origin,+ use_charuco_as_groundplane=use_charuco_as_groundplane+ )++ return toml_path, groundplane_successdiff --git a/freemocap/old/core_processes/capture_volume_calibration/save_3d_data_to_npy.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/save_3d_data_to_npy.pysimilarity index 61%rename from freemocap/old/core_processes/capture_volume_calibration/save_3d_data_to_npy.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/save_3d_data_to_npy.pyindex c82ffc2f..5116e9c9 100644--- a/freemocap/old/core_processes/capture_volume_calibration/save_3d_data_to_npy.py+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/save_3d_data_to_npy.py@@ -3,7 +3,6 @@ from pathlib import Pathfrom typing import Unionimport numpy as np-from freemocap.system.paths_and_filenames.file_and_folder_names import (RAW_3D_NPY_FILE_NAME,FULL_REPROJECTION_ERROR_NPY_FILE_NAME,@@ -15,35 +14,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 dataif 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/old/core_processes/capture_volume_calibration/triangulate_3d_data.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/triangulate_3d_data.pysimilarity index 85%rename from freemocap/old/core_processes/capture_volume_calibration/triangulate_3d_data.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/triangulate_3d_data.pyindex caba1b63..cff78069 100644--- a/freemocap/old/core_processes/capture_volume_calibration/triangulate_3d_data.py+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/ooooold/v1_capture_volume_calibration/triangulate_3d_data.py@@ -3,10 +3,8 @@ import multiprocessingfrom pathlib import Pathimport numpy as np--from freemocap.old.core_processes.capture_volume_calibration.anipose_camera_calibration.run_anipose_calibration_algorithm import \- AniposeCameraGroup-from freemocap.old.core_processes.capture_volume_calibration.save_3d_data_to_npy import (+from freemocap.core_processes.capture_volume_calibration.anipose_camera_calibration.freemocap_anipose import CameraGroup+from freemocap.core_processes.capture_volume_calibration.save_3d_data_to_npy import (save_3d_data_to_npy,)@@ -14,10 +12,10 @@ logger = logging.getLogger(__name__)def triangulate_3d_data(- anipose_calibration_object: AniposeCameraGroup,- image_2d_data: np.ndarray,- use_triangulate_ransac: bool = False,- kill_event: multiprocessing.Event = None,+ anipose_calibration_object: CameraGroup,+ image_2d_data: np.ndarray,+ use_triangulate_ransac: bool = False,+ kill_event: multiprocessing.Event = None,) -> tuple[np.ndarray, np.ndarray, np.ndarray]:number_of_cameras = image_2d_data.shape[0]number_of_frames = image_2d_data.shape[1]@@ -51,8 +49,8 @@ def triangulate_3d_data(spatial_data3d_numFrames_numTrackedPoints_XYZ = data3d_flat.reshape(number_of_frames, number_of_tracked_points, 3)- data3d_reprojectionError_flat = anipose_calibration_object.calculate_reprojection_error(data3d_flat, data2d_flat, mean=True)- data3d_reprojectionError_full = anipose_calibration_object.calculate_reprojection_error(data3d_flat, data2d_flat, mean=False)+ data3d_reprojectionError_flat = anipose_calibration_object.reprojection_error(data3d_flat, data2d_flat, mean=True)+ data3d_reprojectionError_full = anipose_calibration_object.reprojection_error(data3d_flat, data2d_flat, mean=False)reprojectionError_cam_frame_marker = np.linalg.norm(data3d_reprojectionError_full, axis=2).reshape(number_of_cameras, number_of_frames, number_of_tracked_points)@@ -69,7 +67,7 @@ def triangulate_3d_data(if __name__ == "__main__":- from freemocap.old.core_processes.capture_volume_calibration.anipose_camera_calibration.get_anipose_calibration_object import (+ from freemocap.core_processes.capture_volume_calibration.anipose_camera_calibration.get_anipose_calibration_object import (load_anipose_calibration_toml_from_path,)import argparsediff --git a/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/shared_view_accumulator.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/shared_view_accumulator.pynew file mode 100644index 00000000..29c8e7bc--- /dev/null+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/calibration_task/shared_view_accumulator.py@@ -0,0 +1,188 @@+import logging++from pydantic import BaseModel, Field+from pydantic import model_validator+from skellycam.core.types.type_overloads import CameraIdString, FrameNumberInt+from skellytracker.trackers.charuco_tracker.charuco_observation import CharucoObservation++from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.calibration_task.ooooold.calibration_helpers.calibration_numpy_types import ImagePoint2D+from freemocap.pubsub.pubsub_topics import CameraNodeOutputMessage++CharucoObservations = dict[CameraIdString, CharucoObservation | None]++MultiFrameNumber = int+MINIMUM_CHARUCO_CORNERS_FOR_VISIBILITY: int = 6+logger = logging.getLogger(__name__)+++class CameraPair(BaseModel):+ base_camera_id: CameraIdString+ other_camera_id: CameraIdString++ @classmethod+ def from_ids(cls, *, base_camera_id: CameraIdString, other_camera_id: CameraIdString):+ return cls(base_camera_id=base_camera_id,+ other_camera_id=other_camera_id)++ @model_validator(mode='after')+ def validate(self):+ if self.base_camera_id == self.other_camera_id:+ raise ValueError("base_camera_id and other_camera_id must be different")+ return self++ def __eq__(self, other):+ if isinstance(other, CameraPair):+ return self.model_dump() == other.model_dump()+ return False++ def __hash__(self):+ return hash(self.model_dump_json())+++class CameraPairTargetView(BaseModel):+ multi_frame_number: MultiFrameNumber+ base_camera_id: CameraIdString+ other_camera_id: CameraIdString+ base_camera_observation: CharucoObservation+ other_camera_observation: CharucoObservation++ @model_validator(mode='after')+ def validate(self):+ if self.base_camera_id == self.other_camera_id:+ raise ValueError("base_camera_id and other_camera_id must be different")+ if self.base_camera_observation.frame_number != self.multi_frame_number:+ logger.warning(+ f"base_camera_observation frame_number {self.base_camera_observation.frame_number} does not match multi_frame_number {self.multi_frame_number}")+ if self.other_camera_observation.frame_number != self.multi_frame_number:+ logger.warning(+ f"other_camera_observation frame_number {self.other_camera_observation.frame_number} does not match multi_frame_number {self.multi_frame_number}")+ return self+++class MultiCameraTargetView(BaseModel):+ multi_frame_number: MultiFrameNumber+ camera_node_output_by_camera: dict[CameraIdString, CameraNodeOutputMessage]++ @model_validator(mode='after')+ def validate(self):+ if not all([output.frame_number == self.multi_frame_number for output in+ self.camera_node_output_by_camera.values()]):+ logger.warning(+ f"multi_frame_number {self.multi_frame_number} does not match all camera_node_output_by_camera multi_frame_numbers: {[output.frame_number for output in self.camera_node_output_by_camera.values()]}")+ return self++ @property+ def target_visibility_by_camera(self) -> dict[CameraIdString, bool]:+ visibility_by_camera = {}+ for camera_id, camera_node_output in self.camera_node_output_by_camera.items():+ visibility_by_camera[camera_id] = len(+ camera_node_output.observation.charuco_corners_dict) > MINIMUM_CHARUCO_CORNERS_FOR_VISIBILITY+ return visibility_by_camera++ @property+ def image_points_by_camera(self) -> dict[CameraIdString, list[ImagePoint2D]]:+ image_points_by_camera = {camera_id: [] for camera_id in self.camera_node_output_by_camera.keys()}+ for camera_id, camera_node_output in self.camera_node_output_by_camera.items():+ image_points_by_camera[camera_id].extend(+ list(camera_node_output.observation.detected_charuco_corners_in_full_array))++ return image_points_by_camera+++class SharedViewAccumulator(BaseModel):+ camera_ids: list[CameraIdString]+ multi_camera_views_by_frame: dict[FrameNumberInt, MultiCameraTargetView] = Field(default_factory=dict)+ camera_shared_views: dict[CameraIdString, dict[CameraPair, list[CameraPairTargetView]]]++ @classmethod+ def create(cls, camera_ids: list[CameraIdString]):+ camera_shared_views: dict[CameraIdString, dict[CameraPair, list[CameraPairTargetView]]] = {}+ for camera_id in camera_ids:+ for other_camera_id in camera_ids:+ if camera_id == other_camera_id:+ continue+ if camera_id not in camera_shared_views:+ camera_shared_views[camera_id] = {}+ pair = CameraPair.from_ids(base_camera_id=camera_id,+ other_camera_id=other_camera_id)+ camera_shared_views[camera_id][pair] = []+ return cls(camera_ids=camera_ids,+ camera_shared_views=camera_shared_views)++ def receive_camera_node_output(+ self,+ multi_frame_number: int,+ camera_node_output_by_camera: dict[CameraIdString, CameraNodeOutputMessage]+ ):+ if multi_frame_number in self.multi_camera_views_by_frame:+ raise RuntimeError(f"Received duplicate camera node outputs for frame {multi_frame_number}")++ if set(camera_node_output_by_camera.keys()) != set(self.camera_ids):+ raise ValueError(+ f"camera_node_output_by_camera keys {camera_node_output_by_camera.keys()} do not match expected camera ids {self.camera_ids}")++ self.multi_camera_views_by_frame[multi_frame_number] = MultiCameraTargetView(+ multi_frame_number=multi_frame_number,+ camera_node_output_by_camera=camera_node_output_by_camera+ )++ # accumulate shared target views for each camera pair+ for camera_id in self.camera_shared_views.keys():+ if not camera_node_output_by_camera[camera_id].observation.charuco_board_visible:+ continue+ this_camera_obs = camera_node_output_by_camera[camera_id].observation+ for other_camera_id in self.camera_shared_views.keys():+ if camera_id == other_camera_id:+ continue+ if not camera_node_output_by_camera[other_camera_id].observation.charuco_board_visible:+ continue+ other_camera_obs = camera_node_output_by_camera[other_camera_id].observation+ pair = CameraPair.from_ids(base_camera_id=camera_id,+ other_camera_id=other_camera_id)+ target_view = CameraPairTargetView(+ multi_frame_number=multi_frame_number,+ base_camera_id=pair.base_camera_id,+ other_camera_id=pair.other_camera_id,+ base_camera_observation=this_camera_obs,+ other_camera_observation=other_camera_obs+ )+ self.camera_shared_views[camera_id][pair].append(target_view)++ def get_shared_view_count_per_camera(self) -> dict[CameraIdString, int]:+ """+ Get the number of shared views for each camera id, i.e. the number of frames where the camera can see the target and at least one other camera can also see the target+ """+ # special case for single camera - all views with target visible are shared views+ if len(self.camera_ids) == 1:+ single_camera_id = self.camera_ids[0]+ visible_view_count = sum(1 for multi_camera_view in self.multi_camera_views_by_frame.values()+ if multi_camera_view.target_visibility_by_camera[single_camera_id])+ return {single_camera_id: visible_view_count}+ camera_shared_view_count = {camera_id: 0 for camera_id in self.camera_ids}+ for camera_id, pair_dict in self.camera_shared_views.items():+ for pair, target_views in pair_dict.items():+ camera_shared_view_count[camera_id] += len(target_views)++ return camera_shared_view_count++ def all_cameras_have_min_shared_views(self, min_shared_views: int = 500) -> bool:+ """+ find the total number of shared views for each camera id within the various camera pairs+ we don't need all possible pairs to have min_shared_views, just that each camera has min_shared_views with at least one other camera+ """+ return all([count >= min_shared_views for count in self.get_shared_view_count_per_camera().values()])++ def get_observations_by_camera(self, camera_id: CameraIdString) -> dict[FrameNumberInt, CharucoObservation]:+ """+ Get the charuco observations for a given camera id across all frames+ """+ observations_by_frame = {}+ for multi_frame_number, multi_camera_view in self.multi_camera_views_by_frame.items():+ camera_node_output = multi_camera_view.camera_node_output_by_camera[camera_id]+ observations_by_frame[multi_frame_number] = camera_node_output.observation+ return observations_by_frame+++if __name__ == "__main__":+ mca = SharedViewAccumulator.create(["CamA", "CamB", "CamC", "CamD"])+ print(mca.model_dump_json(indent=2))diff --git a/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/mocap_task/__init__.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/mocap_task/__init__.pynew file mode 100644index 00000000..d708065f--- /dev/null+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/mocap_task/__init__.py@@ -0,0 +1 @@+from .__mocap_pipeline import MocapPipeline, MocapPipelineConfigdiff --git a/freemocap/core/pipelines/mocap_pipeline/__mocap_pipeline.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/mocap_task/__mocap_pipeline.pysimilarity index 92%rename from freemocap/core/pipelines/mocap_pipeline/__mocap_pipeline.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/mocap_task/__mocap_pipeline.pyindex c26bd1d8..9303a9ab 100644--- a/freemocap/core/pipelines/mocap_pipeline/__mocap_pipeline.py+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/mocap_task/__mocap_pipeline.py@@ -4,7 +4,6 @@ from dataclasses import dataclassfrom multiprocessing import Queuefrom typing import Dict-from skellycam import CameraIdfrom skellycam.core.camera_group.camera.config.camera_config import CameraConfigsfrom skellycam.core.camera_group.shmorchestrator.shared_memory.single_slot_camera_group_shared_memory import \CameraSharedMemoryDTOs@@ -13,10 +12,11 @@ from skellytracker.trackers.mediapipe_tracker import MediapipeTrackerConfigfrom skellytracker.trackers.mediapipe_tracker.mediapipe_annotator import MediapipeImageAnnotator, \MediapipeAnnotatorConfig-from freemocap.core.pipelines.mocap_pipeline.mocap_aggregation_node import MocapAggregationNodeConfig, \+from freemocap.core.pipeline.processing_pipeline import BasePipelineConfig, PipelineImageAnnotator, \+ BaseProcessingPipeline+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.mocap_task.mocap_aggregation_node import MocapAggregationNodeConfig, \MocapPipelineOutputData, MocapAggregationProcessNode-from freemocap.core.pipelines.mocap_pipeline.mocap_camera_node import MocapPipelineCameraNodeConfig, MocapCameraNode-from freemocap.core.pipelines.processing_pipeline import BasePipelineConfig, PipelineImageAnnotator, BaseProcessingPipeline+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.mocap_task.mocap_camera_node import MocapPipelineCameraNodeConfig, MocapCameraNodelogger = logging.getLogger(__name__)diff --git a/freemocap/core/pipelines/mocap_pipeline/mocap_aggregation_node.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/mocap_task/mocap_aggregation_node.pysimilarity index 91%rename from freemocap/core/pipelines/mocap_pipeline/mocap_aggregation_node.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/mocap_task/mocap_aggregation_node.pyindex ed448dd1..b5507237 100644--- a/freemocap/core/pipelines/mocap_pipeline/mocap_aggregation_node.py+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/mocap_task/mocap_aggregation_node.py@@ -5,12 +5,11 @@ from dataclasses import dataclassfrom multiprocessing import Queue, Processfrom typing import Dict-from skellycam import CameraId--from freemocap.core.pipelines.mocap_pipeline.mocap_camera_node import MocapCameraNodeOutputData-from freemocap.core.pipelines.mocap_pipeline.point_trangulator import PointTriangulator-from freemocap.core.pipelines.processing_pipeline import BaseAggregationLayerOutputData, BasePipelineStageConfig, \- AggregationNode, BasePipelineOutputData+from freemocap.core.pipeline.realtime_pipeline.realtime_aggregation_node import RealtimeAggregationNode+from freemocap.core.pipeline.processing_pipeline import BaseAggregationLayerOutputData, BasePipelineStageConfig, \+ BasePipelineOutputData+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.mocap_task.mocap_camera_node import MocapCameraNodeOutputData+from freemocap.core.pipeline.realtime_pipeline.realtime_tasks.mocap_task.old_point_trangulator import PointTriangulatorlogger = logging.getLogger(__name__)@@ -30,7 +29,7 @@ class MocapPipelineOutputData(BasePipelineOutputData):aggregation_layer_output: MocapAggregationLayerOutputData-class MocapAggregationProcessNode(AggregationNode):+class MocapAggregationProcessNode(RealtimeAggregationNode):@classmethoddef create(cls,config: MocapAggregationNodeConfig,diff --git a/freemocap/core/pipelines/mocap_pipeline/mocap_camera_node.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/mocap_task/mocap_camera_node.pysimilarity index 96%rename from freemocap/core/pipelines/mocap_pipeline/mocap_camera_node.pyrename to freemocap/core/pipeline/realtime_pipeline/realtime_tasks/mocap_task/mocap_camera_node.pyindex 9640f91e..13ef195f 100644--- a/freemocap/core/pipelines/mocap_pipeline/mocap_camera_node.py+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/mocap_task/mocap_camera_node.py@@ -4,7 +4,6 @@ import timefrom dataclasses import dataclassfrom multiprocessing import Queue, Process-from skellycam import CameraIdfrom skellycam.core.camera_group.camera.config.camera_config import CameraConfigfrom skellycam.core.camera_group.shmorchestrator.shared_memory.single_slot_camera_shared_memory import \CameraSharedMemoryDTO, SingleSlotCameraSharedMemory@@ -12,7 +11,8 @@ from skellycam.core.frames.payloads.metadata.frame_metadata import FrameMetadatafrom skellytracker.trackers.mediapipe_tracker import MediapipeTrackerConfig, MediapipeTrackerfrom skellytracker.trackers.mediapipe_tracker.mediapipe_observation import MediapipeObservation-from freemocap.core.pipelines.processing_pipeline import BaseCameraNode, BasePipelineStageConfig, BaseCameraNodeOutputData+from freemocap.core.pipeline.processing_pipeline import BaseCameraNode, BasePipelineStageConfig, \+ BaseCameraNodeOutputDatalogger = logging.getLogger(__name__)@@ -24,8 +24,6 @@ class MocapPipelineCameraNodeConfig(BasePipelineStageConfig):param1: int = 1--@dataclassclass MocapCameraNodeOutputData(BaseCameraNodeOutputData):frame_metadata: FrameMetadata@@ -37,6 +35,7 @@ class MocapCameraNodeOutputData(BaseCameraNodeOutputData):mediapipe_observation=self.mediapipe_observation.to_serializable_dict(),)+@dataclassclass MocapCameraNode(BaseCameraNode):@classmethoddiff --git a/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/single_frame_triangulator.py b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/single_frame_triangulator.pynew file mode 100644index 00000000..2bb9c306--- /dev/null+++ b/freemocap/core/pipeline/realtime_pipeline/realtime_tasks/single_frame_triangulator.py@@ -0,0 +1,289 @@+import logging+from dataclasses import dataclass+from pathlib import Path+from typing import TYPE_CHECKING++import numpy as np+from numpy.typing import NDArray++from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.freemocap_anipose import (+ AniposeCameraGroup+)++from skellycam.core.types.type_overloads import CameraIdString+from skellytracker.trackers.base_tracker.base_tracker_abcs import CharucoObservation++logger = logging.getLogger(__name__)+++@dataclass+class TriangulatedObservationFrame:+ """Result of triangulating observations from multiple cameras."""+ frame_number: int+ points_3d: NDArray[np.float32] # Shape: (n_points, 3)+ reprojection_error: NDArray[np.float32] # Shape: (n_points,)+ reprojection_error_by_camera: NDArray[np.float32] # Shape: (n_cameras, n_points)+ valid_points: NDArray[np.bool_] # Shape: (n_points,) - mask of successfully triangulated points+ nan_mask: NDArray[np.bool_] # Shape: (n_points,) - mask of points with NaN in any camera+ observations_by_camera: dict[str, 'CharucoObservation'] # Original observations for reference+++@dataclass+class ObservationTriangulator:+ camera_group: AniposeCameraGroup+ use_ransac: bool = False+ min_cameras_for_triangulation: int = 2+ max_reprojection_error: float = 10.0+ min_cameras_with_detection: int = 2++ @property+ def camera_names(self) -> list[str]:+ return [cam.name for cam in self.camera_group.cameras]++ @property+ def n_cameras(self) -> int:+ return len(self.camera_group.cameras)++ @classmethod+ def create(+ cls,+ *,+ calibration_toml_path: str|Path,) -> 'ObservationTriangulator':+ camera_group = AniposeCameraGroup.load(str(calibration_toml_path))+ return cls(camera_group=camera_group)++++ def triangulate_observations(+ self,+ *,+ observations_by_camera: dict[CameraIdString, CharucoObservation],+ frame_number: int | None = None,+ ) -> TriangulatedObservationFrame:+ """+ Triangulate observations from multiple synchronized cameras.++ Args:+ observations_by_camera: Dict mapping camera_id to BaseObservation instance+ frame_number: Optional frame number (will use observation's frame_number if not provided)++ Returns:+ TriangulatedObservationFrame with 3D points and metrics++ Raises:+ ValueError: If insufficient cameras or mismatched observations+ """+ if len(observations_by_camera) < self.min_cameras_for_triangulation:+ raise ValueError(+ f"Need at least {self.min_cameras_for_triangulation} cameras, "+ f"got {len(observations_by_camera)}"+ )++ # Extract frame number from first observation if not provided+ if frame_number is None:+ frame_number = next(iter(observations_by_camera.values())).frame_number++ # Verify all observations are from same frame+ frame_numbers = {obs.frame_number for obs in observations_by_camera.values()}+ if len(frame_numbers) > 1:+ raise ValueError(+ f"Observations from different frames: {frame_numbers}. "+ "All observations must be synchronized."+ )+++ # Order according to calibration+ ordered_frames = self._order_observation_frames(observations_by_camera)++ # Stack 2D points and handle NaNs+ points_2d, nan_mask = self._stack_observations_with_nan_handling(ordered_frames)++ # Triangulate only points visible in enough cameras+ points_3d, reproj_error, reproj_error_by_cam = self._triangulate_with_nan_handling(+ points_2d=points_2d,+ nan_mask=nan_mask,+ )++ # Determine valid points+ valid_points = (~nan_mask) & (reproj_error < self.max_reprojection_error)++ return TriangulatedObservationFrame(+ frame_number=frame_number,+ points_3d=points_3d,+ reprojection_error=reproj_error,+ reprojection_error_by_camera=reproj_error_by_cam,+ valid_points=valid_points,+ nan_mask=nan_mask,+ observations_by_camera=observations_by_camera,+ )++ def _order_observation_frames(+ self,+ observations_by_camera: dict[CameraIdString, CharucoObservation],+ ) -> dict[CameraIdString, CharucoObservation]:+ """+ Order observation frames to match calibration camera order.++ Args:+ observations_by_camera: Unordered observation frames++ Returns:+ List of ObservationFrame2D ordered by calibration++ Raises:+ ValueError: If camera not found in calibration+ """+ ordered_observations: dict[CameraIdString, CharucoObservation | None] = {camera_id: None for camera_id in self.camera_names}+ found_cameras: set[CameraIdString] = set()++ for cam_name in self.camera_names:+ found = False+ for camera_id, observation in observations_by_camera.items():+ if cam_name in camera_id:+ if camera_id in found_cameras:+ raise ValueError(f"Duplicate camera data for {camera_id}")+ ordered_observations[camera_id] = observation+ found_cameras.add(camera_id)+ found = True+ break++ if not found:+ raise ValueError(+ f"Camera {cam_name} from calibration not found in observations. "+ f"Available cameras: {[camera_id for camera_id in observations_by_camera.keys()]} "+ f"Expected cameras: {self.camera_names}"+++ )++ if any(obs is None for obs in ordered_observations.values()):+ missing_cameras = [cam_id for cam_id, obs in ordered_observations.items() if obs is None]+ raise ValueError(f"Missing observations for cameras: {missing_cameras}")++ return ordered_observations++ def _stack_observations_with_nan_handling(+ self,+ ordered_frames: dict[CameraIdString,CharucoObservation],+ ) -> tuple[NDArray[np.float32], NDArray[np.bool_]]:+ """+ Stack 2D points from observations, handling NaNs for missing detections.++ Args:+ ordered_frames: Observation frames ordered by calibration++ Returns:+ Tuple of:+ - points_2d: Shape (n_cameras, n_points, 2) with NaNs preserved+ - nan_mask: Shape (n_points,) True where any camera has NaN++ Raises:+ ValueError: If observations have different numbers of points+ """+ # Get 2D points from each observation+ points_arrays = [frame.to_2d_array() for frame in ordered_frames.values()]++ # Verify all have same number of points+ n_points = points_arrays[0].shape[0]+ for i, points in enumerate(points_arrays[1:], 1):+ if points.shape[0] != n_points:+ raise ValueError(+ f"Camera {ordered_frames[i].camera_id} has {points.shape[0]} points, "+ f"expected {n_points} (from {ordered_frames[0].camera_id})"+ )++ # Stack into (n_cameras, n_points, 2)+ points_2d = np.stack(points_arrays, axis=0)++ # Find points that are NaN in any camera+ nan_mask_per_camera = np.any(np.isnan(points_2d), axis=2) # (n_cameras, n_points)++ # Count how many cameras see each point+ cameras_per_point = np.sum(~nan_mask_per_camera, axis=0) # (n_points,)++ # Mark points as invalid if not seen by enough cameras+ nan_mask = cameras_per_point < self.min_cameras_with_detection++ return points_2d, nan_mask++ def _triangulate_with_nan_handling(+ self,+ *,+ points_2d: NDArray[np.float32],+ nan_mask: NDArray[np.bool_],+ ) -> tuple[NDArray[np.float32], NDArray[np.float32], NDArray[np.float32]]:+ """+ Triangulate 2D points, handling NaN values appropriately.++ Args:+ points_2d: Shape (n_cameras, n_points, 2) potentially with NaNs+ nan_mask: Shape (n_points,) indicating invalid points++ Returns:+ Tuple of:+ - points_3d: Shape (n_points, 3) with NaNs for invalid points+ - reprojection_error: Shape (n_points,) with inf for invalid points+ - reprojection_error_by_camera: Shape (n_cameras, n_points)+ """+ n_cameras, n_points, _ = points_2d.shape++ # Initialize outputs+ points_3d = np.full((n_points, 3), np.nan, dtype=np.float32)+ reproj_error = np.full(n_points, np.inf, dtype=np.float32)+ reproj_error_by_camera = np.full((n_cameras, n_points), np.inf, dtype=np.float32)++ # Get indices of valid points+ valid_indices = np.where(~nan_mask)[0]++ if len(valid_indices) == 0:+ logger.warning("No valid points to triangulate")+ return points_3d, reproj_error, reproj_error_by_camera++ # Extract valid points for triangulation+ # For each valid point, we still need all camera views (even with NaNs)+ # Anipose should handle NaN values in the input+ points_2d_valid = points_2d[:, valid_indices, :]++ # Reshape for Anipose+ points_2d_flat = points_2d_valid.reshape(n_cameras, -1, 2)++ # Triangulate+ if self.use_ransac:+ points_3d_flat = self.camera_group.triangulate_ransac(+ points_2d_flat,+ progress=False,+ kill_event=None,+ )+ else:+ points_3d_flat = self.camera_group.triangulate(+ points_2d_flat,+ progress=False,+ kill_event=None,+ )++ if points_3d_flat is None:+ raise RuntimeError("Triangulation failed")++ # Calculate reprojection errors for valid points+ reproj_error_full = self.camera_group.reprojection_error(+ points_3d_flat, points_2d_flat+ )++ # Mean reprojection error per valid point+ reproj_error_valid = self.camera_group.calculate_mean_reprojection_error(+ reproj_error_full+ ).reshape(len(valid_indices))++ # Reprojection error by camera for valid points+ reproj_error_by_cam_valid = np.linalg.norm(+ reproj_error_full, axis=2+ ).reshape(n_cameras, len(valid_indices))++ # Place results back at correct indices+ points_3d[valid_indices] = points_3d_flat.reshape(len(valid_indices), 3)+ reproj_error[valid_indices] = reproj_error_valid+ reproj_error_by_camera[:, valid_indices] = reproj_error_by_cam_valid++ return points_3d, reproj_error, reproj_error_by_camera++diff --git a/freemocap/core/pipelines/calibration_pipeline/__calibration_pipeline.py b/freemocap/core/pipelines/calibration_pipeline/__calibration_pipeline.pydeleted file mode 100644index 2e12543c..00000000--- a/freemocap/core/pipelines/calibration_pipeline/__calibration_pipeline.py+++ /dev/null@@ -1,99 +0,0 @@-import logging-import multiprocessing-from dataclasses import dataclass-from multiprocessing import Queue-from typing import Dict--from skellycam import CameraId-from skellycam.core.camera_group.camera.config.camera_config import CameraConfigs-from skellycam.core.camera_group.shmorchestrator.shared_memory.single_slot_camera_group_shared_memory import \- CameraSharedMemoryDTOs-from skellycam.core.frames.payloads.multi_frame_payload import MultiFramePayload-from skellytracker.trackers.charuco_tracker import CharucoTrackerConfig-from skellytracker.trackers.charuco_tracker.charuco_annotator import CharucoImageAnnotator, CharucoAnnotatorConfig--from freemocap.core.pipelines.calibration_pipeline.calibration_aggregation_node import CalibrationAggregationNodeConfig, \- CalibrationAggregationProcessNode, CalibrationPipelineOutputData-from freemocap.core.pipelines.calibration_pipeline.calibration_camera_node import CalibrationPipelineCameraNodeConfig, \- CalibrationCameraNode-from freemocap.core.pipelines.processing_pipeline import BasePipelineConfig, BaseProcessingPipeline, PipelineImageAnnotator--logger = logging.getLogger(__name__)---class CalibrationPipelineConfig(BasePipelineConfig):- camera_node_configs: dict[CameraId, CalibrationPipelineCameraNodeConfig]- aggregation_node_config: CalibrationAggregationNodeConfig-- @classmethod- def create(cls, camera_configs: CameraConfigs, tracker_config: CharucoTrackerConfig):- return cls(camera_node_configs={camera_id: CalibrationPipelineCameraNodeConfig(camera_config=camera_config,- tracker_config=tracker_config)- for- camera_id, camera_config in camera_configs.items()},- aggregation_node_config=CalibrationAggregationNodeConfig())---class CalibrationPipelineImageAnnotator(PipelineImageAnnotator):- camera_node_annotators: dict[CameraId, CharucoImageAnnotator]-- @classmethod- def create(cls, configs: dict[CameraId, CharucoAnnotatorConfig]):- return cls(camera_node_annotators={camera_id: CharucoImageAnnotator.create(config=config)- for camera_id, config in configs.items()}- )-- def annotate_images(self, multiframe_payload: MultiFramePayload,- pipeline_output: CalibrationPipelineOutputData) -> MultiFramePayload:- for camera_id, annotator in self.camera_node_annotators.items():- multiframe_payload.frames[camera_id].image = annotator.annotate_image(- image=multiframe_payload.frames[camera_id].image,- latest_observation=pipeline_output.camera_node_output[camera_id].charuco_observation)- return multiframe_payload---@dataclass-class CalibrationPipeline(BaseProcessingPipeline):- config: CalibrationPipelineConfig- camera_nodes: Dict[CameraId, CalibrationCameraNode]- aggregation_node: CalibrationAggregationProcessNode- annotator: CalibrationPipelineImageAnnotator-- @classmethod- def create(cls,- config: CalibrationPipelineConfig,- camera_shm_dtos: CameraSharedMemoryDTOs,- shutdown_event: multiprocessing.Event,- use_thread: bool = True):- if not all(camera_id in camera_shm_dtos.keys() for camera_id in config.camera_node_configs.keys()):- raise ValueError("Camera IDs provided in config not in camera shared memory DTOS!")- camera_output_queues = {camera_id: Queue() for camera_id in camera_shm_dtos.keys()}- aggregation_output_queue = Queue()-- all_ready_events = {camera_id: multiprocessing.Event() for camera_id in camera_shm_dtos.keys()}- all_ready_events[-1] = multiprocessing.Event()- camera_nodes = {camera_id: CalibrationCameraNode.create(config=config,- camera_id=CameraId(camera_id),- camera_shm_dto=camera_shm_dtos[- camera_id],- output_queue=camera_output_queues[- camera_id],- all_ready_events=all_ready_events,- shutdown_event=shutdown_event,- use_thread=use_thread)- for camera_id, config in config.camera_node_configs.items()}- return cls(config=config,- camera_nodes=camera_nodes,- aggregation_node=CalibrationAggregationProcessNode.create(config=config.aggregation_node_config,- input_queues=camera_output_queues,- output_queue=aggregation_output_queue,- all_ready_events=all_ready_events,- shutdown_event=shutdown_event,- use_thread=use_thread),- # NOTE - this `annotator` is not the same annotator as the one that will be created in the tracker, but will be able to process its outputs- annotator=CalibrationPipelineImageAnnotator.create(- configs={camera_id: config.tracker_config.annotator_config for camera_id, config in- config.camera_node_configs.items()}),- all_ready_events=all_ready_events,- shutdown_event=shutdown_event,- )diff --git a/freemocap/core/pipelines/calibration_pipeline/__init__.py b/freemocap/core/pipelines/calibration_pipeline/__init__.pydeleted file mode 100644index 575fa182..00000000--- a/freemocap/core/pipelines/calibration_pipeline/__init__.py+++ /dev/null@@ -1 +0,0 @@-from .__calibration_pipeline import CalibrationPipeline, CalibrationPipelineConfig\ No newline at end of filediff --git a/freemocap/core/pipelines/calibration_pipeline/calibration_aggregation_node.py b/freemocap/core/pipelines/calibration_pipeline/calibration_aggregation_node.pydeleted file mode 100644index 6c8d245f..00000000--- a/freemocap/core/pipelines/calibration_pipeline/calibration_aggregation_node.py+++ /dev/null@@ -1,146 +0,0 @@-import logging-import multiprocessing-import time-from dataclasses import dataclass-from multiprocessing import Queue, Process-from threading import Thread-from typing import Dict--import numpy as np-from skellycam import CameraId--from freemocap.core.pipelines.calibration_pipeline.calibration_camera_node_output_data import CalibrationCameraNodeOutputData-from freemocap.core.pipelines.calibration_pipeline.multi_camera_calibrator import MultiCameraCalibrator, \- MultiCameraCalibrationEstimate-from freemocap.core.pipelines.processing_pipeline import BaseAggregationLayerOutputData, BasePipelineStageConfig, \- AggregationNode, BasePipelineOutputData--logger = logging.getLogger(__name__)---class CalibrationAggregationLayerOutputData(BaseAggregationLayerOutputData):- multi_camera_calibration_estimate: MultiCameraCalibrationEstimate | None = None- data: object = None---class CalibrationPipelineOutputData(BasePipelineOutputData):- camera_node_output: dict[CameraId, CalibrationCameraNodeOutputData]- aggregation_layer_output: CalibrationAggregationLayerOutputData---class CalibrationAggregationNodeConfig(BasePipelineStageConfig):- pass---@dataclass-class CalibrationAggregationProcessNode(AggregationNode):- @classmethod- def create(cls,- config: CalibrationAggregationNodeConfig,- input_queues: dict[CameraId, Queue],- output_queue: Queue,- all_ready_events: dict[CameraId | str, multiprocessing.Event],- shutdown_event: multiprocessing.Event,- use_thread: bool = False):-- if use_thread:- worker = Thread(target=cls._run,- kwargs=dict(config=config,- input_queues=input_queues,- output_queue=output_queue,- all_ready_events=all_ready_events,- shutdown_event=shutdown_event)- )- else:- worker = Process(target=cls._run,- kwargs=dict(config=config,- input_queues=input_queues,- output_queue=output_queue,- all_ready_events=all_ready_events,- shutdown_event=shutdown_event)- )- return cls(config=config,- process=worker,- input_queues=input_queues,- output_queue=output_queue,- shutdown_event=shutdown_event)-- @staticmethod- def _run(config: CalibrationAggregationNodeConfig,- input_queues: Dict[CameraId, Queue],- output_queue: Queue,- all_ready_events: dict[CameraId | str, multiprocessing.Event],- shutdown_event: multiprocessing.Event):- all_ready_events[-1].set()- logger.trace(f"Aggregation processing node ready!")- while not all([value.is_set() for value in all_ready_events.values()]):- time.sleep(0.001)- logger.trace(f"All processing nodes ready!")- camera_node_incoming_data: dict[CameraId, CalibrationCameraNodeOutputData | None] = {camera_id: None for- camera_id in- input_queues.keys()}-- multi_camera_calibrator = MultiCameraCalibrator.from_camera_ids(camera_ids=list(input_queues.keys()))- try:-- while not shutdown_event.is_set():-- if any([queue.empty() for queue in input_queues.values()]):- time.sleep(0.001)- continue-- for camera_id in input_queues.keys():- camera_node_output = input_queues[camera_id].get()- if not isinstance(camera_node_output, CalibrationCameraNodeOutputData):- raise ValueError(- f"Unexpected data type received from camera {camera_id}: {type(camera_node_output)}")- camera_node_incoming_data[camera_id] = camera_node_output-- frame_numbers = set(- [camera_node_output.frame_metadata.frame_number for camera_node_output in- camera_node_incoming_data.values()])- if len(frame_numbers) > 1:- raise ValueError(f"Frame numbers from camera nodes do not match! got {frame_numbers}")- multi_frame_number = frame_numbers.pop()-- if not multi_camera_calibrator.has_calibration:-- if multi_frame_number % 5 == 0:- # Accumulate shared views- multi_camera_calibrator.receive_camera_node_output(multi_frame_number=multi_frame_number,- camera_node_output_by_camera=camera_node_incoming_data)- if multi_camera_calibrator.all_cameras_have_min_shared_views() and not multi_camera_calibrator.has_calibration:- multi_camera_calibrator.calibrate()- else:- logger.info("Do triangulation and stuff with the calibration data")- radius = 1- frequency = 0.1-- points3d = {- camera_id: (- radius * np.cos(multi_frame_number * frequency) + camera_id,- camera_id,- radius * np.sin(multi_frame_number * frequency) + camera_id- )- for camera_id in input_queues.keys()- }- if multi_camera_calibrator.has_calibration:- for camera_id, transform in multi_camera_calibrator.multi_camera_calibration_estimate.camera_transforms_by_camera_id.items():- points3d[f"camera-{camera_id}"] = transform.translation_vector.vector-- output = CalibrationPipelineOutputData(- camera_node_output=camera_node_incoming_data, # type: ignore- aggregation_layer_output=CalibrationAggregationLayerOutputData(- multi_frame_number=multi_frame_number,- multi_camera_calibration_estimate=multi_camera_calibrator.multi_camera_calibration_estimate,- points3d=points3d,- )- )-- output_queue.put(output)- except Exception as e:- logger.exception(f"Error in aggregation processing node", exc_info=e)- raise- finally:- logger.trace(f"Shutting down aggregation processing node")- shutdown_event.set()diff --git a/freemocap/core/pipelines/calibration_pipeline/calibration_camera_node.py b/freemocap/core/pipelines/calibration_pipeline/calibration_camera_node.pydeleted file mode 100644index f182409c..00000000--- a/freemocap/core/pipelines/calibration_pipeline/calibration_camera_node.py+++ /dev/null@@ -1,115 +0,0 @@-import logging-import multiprocessing-import time-from dataclasses import dataclass-from multiprocessing import Queue-from threading import Thread--from skellycam import CameraId-from skellycam.core.camera_group.camera.config.camera_config import CameraConfig-from skellycam.core.camera_group.shmorchestrator.shared_memory.single_slot_camera_shared_memory import \- CameraSharedMemoryDTO, SingleSlotCameraSharedMemory-from skellycam.core.frames.payloads.metadata.frame_metadata import FrameMetadata-from skellytracker.trackers.charuco_tracker import CharucoTrackerConfig, CharucoTracker--from freemocap.core.pipelines.calibration_pipeline.calibration_camera_node_output_data import CalibrationCameraNodeOutputData-from freemocap.core.pipelines.calibration_pipeline.single_camera_calibrator import SingleCameraCalibrator-from freemocap.core.pipelines.processing_pipeline import BaseCameraNode, BasePipelineStageConfig--logger = logging.getLogger(__name__)---class CalibrationPipelineCameraNodeConfig(BasePipelineStageConfig):- camera_config: CameraConfig- tracker_config: CharucoTrackerConfig- param1: int = 1---@dataclass-class CalibrationCameraNode(BaseCameraNode):- @classmethod- def create(cls,- camera_id: CameraId,- config: CalibrationPipelineCameraNodeConfig,- camera_shm_dto: CameraSharedMemoryDTO,- output_queue: Queue,- all_ready_events: dict[CameraId, multiprocessing.Event],- shutdown_event: multiprocessing.Event,- use_thread: bool=False- ):- if use_thread:- worker = Thread(target=cls._run,- kwargs=dict(camera_id=camera_id,- config=config,- camera_shm_dto=camera_shm_dto,- output_queue=output_queue,- all_ready_events=all_ready_events,- shutdown_event=shutdown_event- )- )- else:- worker = multiprocessing.Process(target=cls._run,- kwargs=dict(camera_id=camera_id,- config=config,- camera_shm_dto=camera_shm_dto,- output_queue=output_queue,- all_ready_events=all_ready_events,- shutdown_event=shutdown_event- )- )- return cls(camera_id=camera_id,- config=config,- incoming_frame_shm=SingleSlotCameraSharedMemory.recreate(camera_config=config.camera_config,- camera_shm_dto=camera_shm_dto,- read_only=False),- process=worker,- all_ready_events=all_ready_events,- shutdown_event=shutdown_event- )-- @staticmethod- def _run(camera_id: CameraId,- config: CalibrationPipelineCameraNodeConfig,- camera_shm_dto: CameraSharedMemoryDTO,- output_queue: Queue,- all_ready_events: dict[CameraId, multiprocessing.Event],- shutdown_event: multiprocessing.Event,- ):- frame_intake_shm = SingleSlotCameraSharedMemory.recreate(- camera_config=config.camera_config,- camera_shm_dto=camera_shm_dto,- read_only=False)-- charuco_tracker = CharucoTracker.create(config=config.tracker_config)- camera_calibration_estimator: SingleCameraCalibrator | None = None- try:- logger.trace(f"Camera#{camera_id} processing node ready!")- all_ready_events[camera_id].set()- while not shutdown_event.is_set():- time.sleep(0.001)- if not all([event.is_set() for event in all_ready_events.values()]):- continue- if frame_intake_shm.new_frame_available:- tik = time.perf_counter_ns()- frame = frame_intake_shm.retrieve_frame()- time_to_retrieve = time.perf_counter_ns() - tik- tik = time.perf_counter_ns()- observation, raw_results = charuco_tracker.process_image(frame_number=frame.frame_number,- image=frame.image,- annotate_image=False)-- time_to_process = time.perf_counter_ns() - tik- output_queue.put(CalibrationCameraNodeOutputData(- frame_metadata=FrameMetadata.from_frame_metadata_array(frame.metadata),- charuco_observation=observation,- time_to_retrieve_frame_ns=time_to_retrieve,- time_to_process_frame_ns=time_to_process- ),- )- except Exception as e:- logger.exception(f"Error in camera processing node for camera {camera_id}", exc_info=e)- raise- finally:- logger.trace(f"Shutting down camera processing node for camera {camera_id}")- shutdown_event.set()- frame_intake_shm.close()diff --git a/freemocap/core/pipelines/calibration_pipeline/calibration_camera_node_output_data.py b/freemocap/core/pipelines/calibration_pipeline/calibration_camera_node_output_data.pydeleted file mode 100644index 3b87a55d..00000000--- a/freemocap/core/pipelines/calibration_pipeline/calibration_camera_node_output_data.py+++ /dev/null@@ -1,30 +0,0 @@-from skellycam.core.frames.payloads.metadata.frame_metadata import FrameMetadata-from skellytracker.trackers.charuco_tracker.charuco_observation import CharucoObservation, \- DetectedCharucoCornersImageCoordinates--from freemocap.core.pipelines.processing_pipeline import BaseCameraNodeOutputData---class CalibrationCameraNodeOutputData(BaseCameraNodeOutputData):- frame_metadata: FrameMetadata- charuco_observation: CharucoObservation-- @property- def can_see_target(self) -> bool:- return not self.charuco_observation.charuco_empty-- @property- def image_size(self):- return self.frame_metadata.image_size-- @property- def frame_number(self):- return self.frame_metadata.frame_number-- @property- def camera_id(self):- return self.frame_metadata.camera_id-- @property- def target_pixel_points(self) -> DetectedCharucoCornersImageCoordinates:- return self.charuco_observation.detected_charuco_corners_in_full_arraydiff --git a/freemocap/core/pipelines/calibration_pipeline/multi_camera_calibrator.py b/freemocap/core/pipelines/calibration_pipeline/multi_camera_calibrator.pydeleted file mode 100644index 8635d2a3..00000000--- a/freemocap/core/pipelines/calibration_pipeline/multi_camera_calibrator.py+++ /dev/null@@ -1,213 +0,0 @@-import logging--import numpy as np-from pydantic import BaseModel-from skellycam.core.types.type_overloads import CameraIdString--from freemocap.core.pipelines.calibration_pipeline.calibration_camera_node_output_data import \- CalibrationCameraNodeOutputData-from freemocap.core.pipelines.calibration_pipeline.camera_math_models import TransformationMatrix-from freemocap.core.pipelines.calibration_pipeline.least_squares_optimizer import SparseBundleOptimizer-from freemocap.core.pipelines.calibration_pipeline.shared_view_accumulator import SharedViewAccumulator-from freemocap.core.pipelines.calibration_pipeline.single_camera_calibrator import CameraIntrinsicsEstimate, \- SingleCameraCalibrator--logger = logging.getLogger(__name__)---class MultiCameraCalibrationEstimate(BaseModel):- principal_camera_id: CameraIdString- camera_transforms_by_camera_id: dict[CameraIdString, TransformationMatrix]----class MultiCameraCalibrator(BaseModel):- principal_camera_id: CameraIdString- camera_id_to_index: dict[CameraIdString, int]- shared_view_accumulator: SharedViewAccumulator-- single_camera_calibrators: dict[CameraIdString, SingleCameraCalibrator] | None = None- multi_camera_calibration_estimate: MultiCameraCalibrationEstimate | None = None- sparse_bundle_optimizer: SparseBundleOptimizer | None = None- minimum_views_to_reconstruct: int | None = 20-- @property- def has_calibration(self) -> bool:- if self.single_camera_calibrators is None or self.multi_camera_calibration_estimate is None:- return False- return all(single_camera_calibrator.has_calibration for single_camera_calibrator in- self.single_camera_calibrators.values()) and self.multi_camera_calibration_estimate is not None-- @property- def camera_intrinsics(self) -> dict[CameraIdString, CameraIntrinsicsEstimate]:- return {camera_id: single_camera_calibrator.camera_intrinsics_estimate for camera_id, single_camera_calibrator- in- self.single_camera_calibrators.items()}-- @classmethod- def from_camera_ids(cls, camera_ids: list[CameraIdString], principal_camera_id: CameraIdString|None = None):- return cls(principal_camera_id=principal_camera_id if principal_camera_id is not None else min(camera_ids),- camera_id_to_index={camera_id: index for index, camera_id in enumerate(camera_ids)},- shared_view_accumulator=SharedViewAccumulator.create(camera_ids=camera_ids),- )-- def receive_camera_node_output(self, multi_frame_number: int,- camera_node_output_by_camera: dict[CameraIdString, CalibrationCameraNodeOutputData]):-- if self.single_camera_calibrators is None:- self.initialize_single_camera_calibrators(camera_node_output_by_camera)- self.shared_view_accumulator.receive_camera_node_output(multi_frame_number=multi_frame_number,- camera_node_output_by_camera=camera_node_output_by_camera)-- logger.trace(f"Shared view accumulator: {self.shared_view_accumulator.get_shared_view_count_per_camera()}")-- def initialize_single_camera_calibrators(self, camera_node_output_by_camera: dict[- CameraIdString, CalibrationCameraNodeOutputData]):-- self.single_camera_calibrators: dict[CameraIdString, SingleCameraCalibrator] = {}- for camera_id, node_output in camera_node_output_by_camera.items():- self.single_camera_calibrators[camera_id] = SingleCameraCalibrator.create_initial(- camera_id=camera_id,- image_size=node_output.charuco_observation.image_size,- all_aruco_marker_ids=node_output.charuco_observation.all_aruco_ids,- all_aruco_corners_in_object_coordinates=node_output.charuco_observation.all_aruco_corners_in_object_coordinates,- all_charuco_corner_ids=node_output.charuco_observation.all_charuco_ids,- all_charuco_corners_in_object_coordinates=node_output.charuco_observation.all_charuco_corners_in_object_coordinates- )-- def all_cameras_have_min_shared_views(self, min_shared_views: int | None = None) -> bool:- return self.shared_view_accumulator.all_cameras_have_min_shared_views(- min_shared_views=self.minimum_views_to_reconstruct if min_shared_views is None else min_shared_views)-- def calibrate(self):- logger.debug(- f"Calibrating multi-camera system for cameras: {self.single_camera_calibrators.keys()}"- f" with principal camera: {self.principal_camera_id} and "- f"{self.shared_view_accumulator.get_shared_view_count_per_camera()} shared views")-- for camera_pair, shared_views in self.shared_view_accumulator.target_views_by_camera_pair.items():- logger.trace(f"Camera pair ({camera_pair}) has {len(shared_views)} shared views")- for view in shared_views:- camera_id = view.camera_pair.base_camera_id- other_camera_id = view.camera_pair.other_camera_id- self.single_camera_calibrators[camera_id].add_observation(- observation=view.camera_node_output_by_camera[camera_id].charuco_observation)- self.single_camera_calibrators[other_camera_id].add_observation(- observation=view.camera_node_output_by_camera[other_camera_id].charuco_observation)-- [calibrator.update_calibration_estimate() for calibrator in self.single_camera_calibrators.values()]-- return self.run_multi_camera_optimization()- # logger.success(- # f"Multi-camera calibration complete! \n {self.multi_camera_calibration_estimate.model_dump_json(indent=2)}")- # return self.multi_camera_calibration_estimate-- def run_multi_camera_optimization(self) -> MultiCameraCalibrationEstimate:- # Step 1: Calculate secondary camera transforms for each camera pair- camera_pair_secondary_camera_transform_estimates = self._calculate_camera_pair_transforms()-- logger.debug(- f"Camera pair secondary camera transform estimates: {camera_pair_secondary_camera_transform_estimates}")-- # Step 2: Calculate each camera's transform relative to the principal camera- transform_to_principal_camera_by_camera = self._calculate_camera_to_principal_camera_transforms(- camera_pair_secondary_camera_transform_estimates)-- self.sparse_bundle_optimizer = SparseBundleOptimizer.create(principal_camera_id=self.principal_camera_id,- camera_extrinsics_by_camera_id={- camera_id: transform.extrinsics_matrix- for camera_id, transform in transform_to_principal_camera_by_camera.items()},- camera_intrinsics=self.camera_intrinsics,- multi_camera_target_views=self.shared_view_accumulator.multi_camera_target_views,- image_sizes={camera_id: calibrator.image_size for- camera_id, calibrator in- self.single_camera_calibrators.items()}- )- optimization_result = self.sparse_bundle_optimizer.optimize()- camera_transforms = {}- for camera_index, camera_id in enumerate(self.single_camera_calibrators.keys()):- # split the 1d vector by camera based on `self.number_of_parameters_per_camera`- starting_index = camera_index * self.sparse_bundle_optimizer.number_of_parameters_per_camera- ending_index = (camera_index + 1) * self.number_of_parameters_per_camera- camera_transforms[camera_id] = TransformationMatrix.from_extrinsics(- extrinsics_matrix=np.array(optimization_result[starting_index:ending_index]).reshape(3, 4),- reference_frame=f"camera-{self.principal_camera_id}")- self.multi_camera_calibration_estimate = MultiCameraCalibrationEstimate(- principal_camera_id=self.principal_camera_id,- camera_transforms_by_camera_id=camera_transforms- )-- def _calculate_camera_to_principal_camera_transforms(self, camera_pair_secondary_camera_transform_estimates) -> \- dict[CameraIdString, TransformationMatrix]:- transform_to_principal_camera_by_camera = {self.principal_camera_id: TransformationMatrix(matrix=np.eye(4),- reference_frame=f"camera {self.principal_camera_id}")}- transform_to_principal_camera_by_camera.update(- {camera_id: None for camera_id in self.single_camera_calibrators.keys()- if camera_id != self.principal_camera_id})- # Use the camera pairs to determine other camera transforms relative to the principal camera- while any([transform is None for transform in transform_to_principal_camera_by_camera.values()]):- logger.debug(- f"Calculating camera transforms for cameras: {[camera_id for camera_id, transform in transform_to_principal_camera_by_camera.items() if transform is None]}")- for camera_pair, transform in camera_pair_secondary_camera_transform_estimates.items():- if transform_to_principal_camera_by_camera[camera_pair.other_camera_id] is not None:- continue- if camera_pair.base_camera_id == self.principal_camera_id:- # Directly use the transform if base is principal camera- transform_to_principal_camera_by_camera[camera_pair.other_camera_id] = transform- elif camera_pair.other_camera_id == self.principal_camera_id:- # Transform is inverse if other is principal camera- transform_to_principal_camera_by_camera[camera_pair.base_camera_id] = transform.get_inverse()- else:- # If neither camera in the pair is the principal camera, we need to transform the other camera's transform- if camera_pair.base_camera_id in transform_to_principal_camera_by_camera:- base_to_principal = transform_to_principal_camera_by_camera[camera_pair.base_camera_id]- transform_to_principal_camera_by_camera[- camera_pair.other_camera_id] = base_to_principal @ transform- elif camera_pair.other_camera_id in transform_to_principal_camera_by_camera:- other_to_principal = transform_to_principal_camera_by_camera[camera_pair.other_camera_id]- transform_to_principal_camera_by_camera[- camera_pair.base_camera_id] = other_to_principal @ transform.get_inverse()- logger.debug(- f"Camera ID to principal camera transform estimates: {transform_to_principal_camera_by_camera}")- return transform_to_principal_camera_by_camera-- def _calculate_camera_pair_transforms(self):- camera_pair_secondary_camera_transform_estimates = {}- for camera_pair in self.shared_view_accumulator.camera_pairs:- base_camera_id = camera_pair.base_camera_id- other_camera_id = camera_pair.other_camera_id-- charuco_transforms_in_base_camera_coordinates = self.single_camera_calibrators[- base_camera_id].charuco_transformation_matrices- charuco_transforms_in_other_camera_coordinates = self.single_camera_calibrators[- other_camera_id].charuco_transformation_matrices-- other_camera_to_base_camera_transforms = []- for base_camera_transform, other_camera_transform in zip(charuco_transforms_in_base_camera_coordinates,- charuco_transforms_in_other_camera_coordinates):- base_camera_to_board_transform = base_camera_transform.get_inverse()- other_camera_to_base_camera_transforms.append(base_camera_to_board_transform @ other_camera_transform)-- mean_transform = TransformationMatrix.mean_from_transformation_matrices(- other_camera_to_base_camera_transforms)- camera_pair_secondary_camera_transform_estimates[camera_pair] = mean_transform- return camera_pair_secondary_camera_transform_estimates---if __name__ == "__main__":- import pickle- from pathlib import Path-- pickle_path = r"C:\Users\jonma\github_repos\freemocap_organization\freemocap\freemocap\saved_mc_calib.pkl"- if not Path(pickle_path).exists():- raise FileNotFoundError(f"File not found: {pickle_path}")- loaded: MultiCameraCalibrator = pickle.load(open(pickle_path, "rb"))- loaded.run_multi_camera_optimization()-- ## save out state in debug console to re-run w/o camera streams- # import pickle- # from pathlib import Path- #- # pickle_path = r"C:\Users\jonma\github_repos\freemocap_organization\freemocap\freemocap\saved_mc_calib.pkl"- # with open(pickle_path, "wb") as f:- # pickle.dump(self, f)diff --git a/freemocap/core/pipelines/calibration_pipeline/shared_view_accumulator.py b/freemocap/core/pipelines/calibration_pipeline/shared_view_accumulator.pydeleted file mode 100644index ffa20a59..00000000--- a/freemocap/core/pipelines/calibration_pipeline/shared_view_accumulator.py+++ /dev/null@@ -1,141 +0,0 @@-import numpy as np-from pydantic import BaseModel, Field-from skellycam import CameraId-from pydantic import model_validator-from freemocap.core.pipelines.calibration_pipeline.calibration_camera_node_output_data import CalibrationCameraNodeOutputData-from freemocap.core.pipelines.calibration_pipeline.calibration_numpy_types import ImagePoint2D--MultiFrameNumber = int-class CameraPair(BaseModel):- base_camera_id: CameraId- other_camera_id: CameraId-- @classmethod- def from_ids(cls, base_camera_id: CameraId, other_camera_id: CameraId):- return cls(base_camera_id=min(base_camera_id, other_camera_id), other_camera_id=max(base_camera_id, other_camera_id))-- @model_validator(mode='after')- def validate(self):- if self.base_camera_id == self.other_camera_id:- raise ValueError("base_camera_id and other_camera_id must be different")- if not (self.base_camera_id < self.other_camera_id):- raise ValueError("base_camera_id must be less than other_camera_id")- return self--- def __eq__(self, other):- if isinstance(other, CameraPair):- return self.model_dump() == other.model_dump()- return False-- def __hash__(self):- # Use a frozenset to ensure hashability and use this model as a key in a dictionary- return hash(frozenset(self.model_dump().items()))--class CameraPairTargetView(BaseModel):- multi_frame_number: MultiFrameNumber- camera_pair: CameraPair- camera_node_output_by_camera: dict[CameraId, CalibrationCameraNodeOutputData]-- @model_validator(mode='after')- def validate(self):- if not self.camera_pair.base_camera_id in self.camera_node_output_by_camera:- raise ValueError(f"base_camera_id {self.camera_pair.base_camera_id} not in camera_node_output_by_camera keys {self.camera_node_output_by_camera.keys()}")- if not self.camera_pair.other_camera_id in self.camera_node_output_by_camera:- raise ValueError(f"other_camera_id {self.camera_pair.other_camera_id} not in camera_node_output_by_camera keys {self.camera_node_output_by_camera.keys()}")- return self---PointIndex = int-class MultiCameraTargetView(BaseModel):- multi_frame_number: MultiFrameNumber- camera_node_output_by_camera: dict[CameraId, CalibrationCameraNodeOutputData]-- @model_validator(mode='after')- def validate(self):- if len(self.camera_node_output_by_camera) < 2:- raise ValueError(f"camera_node_output_by_camera must have at least 2 cameras, got {len(self.camera_node_output_by_camera)}")- if not all([output.frame_number == self.multi_frame_number for output in self.camera_node_output_by_camera.values()]):- raise ValueError(f"multi_frame_number {self.multi_frame_number} does not match all camera_node_output_by_camera multi_frame_numbers")- return self-- @property- def image_points_by_camera(self) -> dict[CameraId, list[ImagePoint2D]]:- image_points_by_camera = {camera_id: [] for camera_id in self.camera_node_output_by_camera.keys()}- for camera_id, camera_node_output in self.camera_node_output_by_camera.items():- image_points_by_camera[camera_id].extend(list(camera_node_output.charuco_observation.detected_charuco_corners_in_full_array))-- return image_points_by_camera--class SharedViewAccumulator(BaseModel):- """- Keeps track of the data feeds from each camera, and keeps track of the frames where each can see the calibration target,- and counts the number of shared views each camera has with each other camera (i.e. frames where both cameras can see the target)- """- camera_ids: list[CameraId]- target_views_by_camera_pair: dict[CameraPair, list[CameraPairTargetView]] = Field(default_factory=dict)-- @property- def camera_pairs(self) -> list[CameraPair]:- return list(self.target_views_by_camera_pair.keys())-- @property- def multi_camera_target_views(self) -> dict[MultiFrameNumber, MultiCameraTargetView]:- mc_views = {}- for camera_pair, shared_views in self.target_views_by_camera_pair.items():- for shared_view in shared_views:- if not shared_view.multi_frame_number in mc_views:- mc_views[shared_view.multi_frame_number] = MultiCameraTargetView(multi_frame_number=shared_view.multi_frame_number,- camera_node_output_by_camera=shared_view.camera_node_output_by_camera)-- else:- mc_views[shared_view.multi_frame_number].camera_node_output_by_camera.update(shared_view.camera_node_output_by_camera)- return mc_views-- @classmethod- def create(cls, camera_ids: list[CameraId]):- camera_pairs = []- for i, camera_id in enumerate(camera_ids):- for other_camera_id in camera_ids[i+1:]:- camera_pairs.append(CameraPair.from_ids(camera_id, other_camera_id))- return cls(camera_ids=camera_ids, target_views_by_camera_pair={camera_pair: [] for camera_pair in camera_pairs})--- def receive_camera_node_output(self, multi_frame_number: int,- camera_node_output_by_camera: dict[CameraId, CalibrationCameraNodeOutputData]):-- for camera_id, camera_node_output in camera_node_output_by_camera.items():- if camera_node_output.can_see_target:- for other_camera_id in self.camera_ids:- if other_camera_id == camera_id:- continue- if camera_node_output_by_camera[other_camera_id].can_see_target:- camera_pair = CameraPair.from_ids(camera_id, other_camera_id)- if camera_pair not in self.target_views_by_camera_pair:- raise ValueError(f"camera_pair {camera_pair} not in target_views_by_camera_pair keys {self.target_views_by_camera_pair.keys()}")- if any([shared_view.multi_frame_number == multi_frame_number for shared_view in self.target_views_by_camera_pair[camera_pair]]):- continue- self.target_views_by_camera_pair[camera_pair].append(CameraPairTargetView(multi_frame_number=multi_frame_number,- camera_pair=camera_pair,- camera_node_output_by_camera={camera_id: camera_node_output,- other_camera_id: camera_node_output_by_camera[other_camera_id]}))--- def get_shared_view_count_per_camera(self) -> dict[CameraId, int]:- """- Get the number of shared views for each camera id, i.e. the number of frames where the camera can see the target and at least one other camera can also see the target- """- camera_shared_view_count = {camera_id: 0 for camera_id in self.camera_ids}- for camera_pair, shared_views in self.target_views_by_camera_pair.items():- camera_shared_view_count[camera_pair.base_camera_id] += len(shared_views)- camera_shared_view_count[camera_pair.other_camera_id] += len(shared_views)- return camera_shared_view_count-- def all_cameras_have_min_shared_views(self, min_shared_views: int = 10) -> bool:- """- find the total number of shared views for each camera id within the various camera pairs- we don't need all possible pairs to have min_shared_views, just that each camera has min_shared_views with at least one other camera- """-- return all([count >= min_shared_views for count in self.get_shared_view_count_per_camera().values()])-diff --git a/freemocap/core/pipelines/calibration_pipeline/single_camera_calibrator.py b/freemocap/core/pipelines/calibration_pipeline/single_camera_calibrator.pydeleted file mode 100644index b9e5dffb..00000000--- a/freemocap/core/pipelines/calibration_pipeline/single_camera_calibrator.py+++ /dev/null@@ -1,228 +0,0 @@-import logging--import cv2-import numpy as np-from pydantic import BaseModel, Field-from skellycam import CameraId-from skellytracker.trackers.charuco_tracker.charuco_observation import CharucoObservations, CharucoObservation, \- AllCharucoCorners3DByIdInObjectCoordinates, AllArucoCorners3DByIdInObjectCoordinates--from freemocap.core.pipelines.calibration_pipeline.calibration_numpy_types import ObjectPoints3D, \- ImagePoints2D-from freemocap.core.pipelines.calibration_pipeline.camera_math_models import RotationVector, TranslationVector, \- TransformationMatrix, CameraDistortionCoefficients, CameraMatrix--logger = logging.getLogger(__name__)--DEFAULT_INTRINSICS_COEFFICIENTS_COUNT = 5-MIN_CHARUCO_CORNERS = 6---class CameraIntrinsicsEstimate(BaseModel):- camera_id: CameraId- camera_matrix: CameraMatrix- distortion_coefficients: CameraDistortionCoefficients---class SingleCameraCalibrator(BaseModel):- """- SingleCameraCalibrator class for estimating camera calibration parameters.-- cv2.calibrateCamera docs: https://docs.opencv.org/4.10.0/d9/d0c/group__calib3d.html#ga687a1ab946686f0d85ae0363b5af1d7b- """-- camera_id: CameraId- image_size: tuple[int, ...]-- all_charuco_corner_ids: list[int]- all_charuco_corners_in_object_coordinates: AllCharucoCorners3DByIdInObjectCoordinates-- all_aruco_marker_ids: list[int]- all_aruco_corners_in_object_coordinates: AllArucoCorners3DByIdInObjectCoordinates-- distortion_coefficients: CameraDistortionCoefficients- camera_matrix: CameraMatrix-- charuco_observations: CharucoObservations = Field(default_factory=CharucoObservations)- object_points_views: list[ObjectPoints3D] = []- image_points_views: list[ImagePoints2D] = []- rotation_vectors: list[RotationVector] = []- translation_vectors: list[TranslationVector] = []-- reprojection_error_per_point_by_view: list[list[float]] = []- reprojection_error_by_view: list[float] = []- mean_reprojection_error: float | None = None-- camera_calibration_residual: float | None = None--- @property- def camera_intrinsics_estimate(self) -> CameraIntrinsicsEstimate:- return CameraIntrinsicsEstimate(camera_id=self.camera_id,- camera_matrix=self.camera_matrix,- distortion_coefficients=self.distortion_coefficients)-- @property- def has_calibration(self):- return self.mean_reprojection_error is not None-- @property- def charuco_transformation_matrices(self) -> list[TransformationMatrix]:- return [TransformationMatrix.from_rotation_translation(rotation_vector=rotation_vector,- translation_vector=translation_vector)- for rotation_vector, translation_vector in zip(self.rotation_vectors, self.translation_vectors)]-- @classmethod- def create_initial(cls,- camera_id: CameraId,- image_size: tuple[int, ...],- all_aruco_marker_ids: list[int],- all_aruco_corners_in_object_coordinates: list[np.ndarray[..., 3]],- all_charuco_corner_ids: list[int],- all_charuco_corners_in_object_coordinates: np.ndarray[..., 3],- number_of_distortion_coefficients: int = DEFAULT_INTRINSICS_COEFFICIENTS_COUNT):-- if len(all_charuco_corner_ids) != all_charuco_corners_in_object_coordinates.shape[0]:- raise ValueError("Number of charuco corner IDs must match the number of charuco corners.")- if len(all_aruco_marker_ids) != len(all_aruco_corners_in_object_coordinates):- raise ValueError("Number of aruco marker IDs must match the number of aruco corners.")-- return cls(camera_id=camera_id,- image_size=image_size,- all_charuco_corner_ids=all_charuco_corner_ids,- all_charuco_corners_in_object_coordinates=all_charuco_corners_in_object_coordinates,- all_aruco_marker_ids=all_aruco_marker_ids,- all_aruco_corners_in_object_coordinates=all_aruco_corners_in_object_coordinates,- camera_matrix=CameraMatrix.from_image_size(image_size=image_size),- distortion_coefficients=CameraDistortionCoefficients(- coefficients=np.zeros(number_of_distortion_coefficients))- )-- def add_observation(self, observation: CharucoObservation):- if observation.frame_number in [obs.frame_number for obs in self.charuco_observations]:- return- if observation.charuco_empty or len(observation.detected_charuco_corner_ids) < MIN_CHARUCO_CORNERS:- return- self._validate_observation(observation)-- self.charuco_observations.append(observation)- self.image_points_views.append(np.squeeze(observation.detected_charuco_corners_image_coordinates))- self.object_points_views.append(- self.all_charuco_corners_in_object_coordinates[np.squeeze(observation.detected_charuco_corner_ids), :])-- def update_calibration_estimate(self):-- if len(self.object_points_views) < len(self.all_charuco_corner_ids):- raise ValueError(f"You must have at least as many observations as charuco corners: "- f"#Current views: {len(self.object_points_views)}, "- f"#Charuco corners: {len(self.all_charuco_corner_ids)}")-- # https://docs.opencv.org/4.10.0/d9/d0c/group__calib3d.html#ga687a1ab946686f0d85ae0363b5af1d7b- (self.camera_calibration_residual,- camera_matrix_output,- distortion_coefficients_output,- rotation_vectors_output,- translation_vectors_output) = cv2.calibrateCamera(objectPoints=self.object_points_views,- imagePoints=self.image_points_views,- imageSize=self.image_size,- cameraMatrix=self.camera_matrix.matrix, # will edit in place- distCoeffs=self.distortion_coefficients.coefficients,- # will edit in place- )-- if not self.camera_calibration_residual:- raise ValueError(f"Camera Calibration failed! Check your input data:",- f"object_points_views: {self.object_points_views}",- f"image_points_views: {self.image_points_views}",- f"camera_matrix: {self.camera_matrix}",- f"distortion_coefficients: {self.distortion_coefficients}",- )- self.rotation_vectors = [RotationVector(vector=np.squeeze(rotation_vector),- reference_frame=f"camera-{self.camera_id}")- for rotation_vector in rotation_vectors_output]- self.translation_vectors = [TranslationVector(vector=np.squeeze(translation_vector),- reference_frame=f"camera-{self.camera_id}")- for translation_vector in translation_vectors_output]-- self._update_reprojection_error()-- def get_board_pose(self, object_points: np.ndarray[..., 3], image_points: np.ndarray[..., 2]) -> tuple[- np.ndarray[..., 3], np.ndarray[..., 3]]:- if len(object_points) < 6:- raise ValueError("You must have at least 4 object points to estimate the board pose.")- if len(self.camera_calibration_residuals) == 0:- raise ValueError("You must first calibrate the camera to get the board pose.")- if len(object_points) != len(image_points):- raise ValueError("The number of object and image points must be the same")- success, rotation_vector, translation_vector = cv2.solvePnP(objectPoints=object_points,- imagePoints=image_points,- cameraMatrix=self.camera_matrix.matrix,- distCoeffs=self.distortion_coefficients.coefficients, )- if not success:- raise ValueError(- f"Failed to estimate board pose for object points: {object_points} and image points: {image_points}")- return rotation_vector, translation_vector-- def draw_board_axes(self, image: np.ndarray, observation: CharucoObservation) -> np.ndarray:- if len(self.camera_calibration_residuals) == 0:- raise ValueError("You must first calibrate the camera to draw the board axes.")- if observation.detected_charuco_corners_image_coordinates.shape[0] < 6:- return image- rotation_vector, translation_vector = self.get_board_pose(- object_points=observation.detected_charuco_corners_in_object_coordinates,- image_points=observation.detected_charuco_corners_image_coordinates- )- axis_length = 5- return cv2.drawFrameAxes(image,- self.camera_matrix.matrix,- self.distortion_coefficients.coefficients,- rotation_vector,- translation_vector,- axis_length)-- def _validate_observation(self, observation: CharucoObservation):- if observation.image_size != self.image_size:- raise ValueError("Image size mismatch")- if any([corner_id not in self.all_charuco_corner_ids for corner_id in observation.detected_charuco_corner_ids]):- raise ValueError(- f"Invalid charuco corner ID detected: {observation.detected_charuco_corner_ids} not all in {self.all_charuco_corner_ids}")-- def _drop_suboptimal_views(self, ratio_to_keep: float = 0.5):- if len(self.reprojection_error_by_view) < 2:- return- sorted_indices = np.argsort(self.reprojection_error_by_view)- number_of_views_to_keep = int(len(sorted_indices) * ratio_to_keep)- self.object_points_views = [self.object_points_views[i] for i in sorted_indices[:number_of_views_to_keep]]- self.image_points_views = [self.image_points_views[i] for i in sorted_indices[:number_of_views_to_keep]]- self.rotation_vectors = [self.rotation_vectors[i] for i in sorted_indices[:number_of_views_to_keep]]- self.translation_vectors = [self.translation_vectors[i] for i in sorted_indices[:number_of_views_to_keep]]- self.reprojection_error_by_view = [self.reprojection_error_by_view[i] for i in- sorted_indices[:number_of_views_to_keep]]- self.charuco_observations = [self.charuco_observations[i] for i in sorted_indices[:number_of_views_to_keep]]-- def _update_reprojection_error(self):- # https://docs.opencv.org/4.10.0/d9/d0c/group__calib3d.html#ga1019495a2c8d1743ed5cc23fa0daff8c- if len(self.image_points_views) != len(self.object_points_views):- raise ValueError("The number of image and object points must be the same")- if len(self.image_points_views) == 0:- raise ValueError("No image points provided")- self.reprojection_error_per_point_by_view = []- self.reprojection_error_by_view = []- for view_index in range(len(self.image_points_views)):- projected_image_points, jacobian = cv2.projectPoints(objectPoints=self.object_points_views[view_index],- rvec=self.rotation_vectors[view_index].vector,- tvec=self.translation_vectors[view_index].vector,- cameraMatrix=self.camera_matrix.matrix,- distCoeffs=self.distortion_coefficients.coefficients,- aspectRatio=self.image_size[0] / self.image_size[1]- )-- self.reprojection_error_per_point_by_view.append(- np.abs(self.image_points_views[view_index] - np.squeeze(projected_image_points)))-- self.reprojection_error_by_view.append(float(np.nanmean(self.reprojection_error_per_point_by_view[-1])))-- self.mean_reprojection_error = float(np.nanmean(self.reprojection_error_by_view))-- logger.debug(- f"Camera {self.camera_id} - Mean reprojection error: {self.mean_reprojection_error:.3f} pixels, reprojection error by view: {self.reprojection_error_by_view}")diff --git a/freemocap/core/pipelines/freemocap_frontend_payload.py b/freemocap/core/pipelines/freemocap_frontend_payload.pydeleted file mode 100644index 64037411..00000000--- a/freemocap/core/pipelines/freemocap_frontend_payload.py+++ /dev/null@@ -1,47 +0,0 @@-from typing import Hashable--import numpy as np-from numpydantic import NDArray, Shape-from pydantic import BaseModel-from skellycam import CameraId-from skellycam.core.frames.payloads.frontend_image_payload import FrontendFramePayload-from skellycam.core.frames.payloads.multi_frame_payload import MultiFramePayload--from freemocap.core.pipelines.processing_pipeline import BasePipelineOutputData---class CharucoBoardPayload(BaseModel):- charuco_corners_in_object_coordinates: NDArray[Shape["* charuco_corners, 3 xyz"], np.float64]- charuco_ids: NDArray[Shape["* ch0aruco_corners, ..."], np.int32]- translation_vector: NDArray[Shape["3 xyz"], np.float64]- rotation_vector: NDArray[Shape["3 xyz"], np.float64]-- @classmethod- def create(cls,- charuco_corners_in_object_coordinates: NDArray[Shape["* charuco_corners, 3 xyz"], np.float64] | None,- charuco_ids: NDArray[Shape["* ch0aruco_corners, ..."], np.int32] | None,- translation_vector: NDArray[Shape["3 xyz"], np.float64] | None,- rotation_vector: NDArray[Shape["3 xyz"], np.float64] | None):- return cls(- charuco_corners_in_object_coordinates=charuco_corners_in_object_coordinates.tolist() if charuco_corners_in_object_coordinates is not None else None,- charuco_ids=charuco_ids.tolist() if charuco_ids is not None else None,- translation_vector=translation_vector.tolist() if translation_vector is not None else None,- rotation_vector=rotation_vector.tolist() if rotation_vector is not None else None- )---class FreemocapFrontendPayload(FrontendFramePayload):- latest_pipeline_output: BasePipelineOutputData | None- points3d: dict[Hashable, NDArray[Shape["3 xyz"], np.float64]] | None--- @classmethod- def create(cls,- multi_frame_payload: MultiFramePayload,- latest_pipeline_output: BasePipelineOutputData | None = None):-- return cls(- **FrontendFramePayload.from_multi_frame_payload(multi_frame_payload).model_dump(),- latest_pipeline_output=latest_pipeline_output,- points3d=latest_pipeline_output.aggregation_layer_output.points3d if latest_pipeline_output is not None else None- )diff --git a/freemocap/core/pipelines/mocap_pipeline/__init__.py b/freemocap/core/pipelines/mocap_pipeline/__init__.pydeleted file mode 100644index 9c499cbf..00000000--- a/freemocap/core/pipelines/mocap_pipeline/__init__.py+++ /dev/null@@ -1 +0,0 @@-from .__mocap_pipeline import MocapPipeline, MocapPipelineConfig\ No newline at end of filediff --git a/freemocap/core/pipelines/mocap_pipeline/point_trangulator.py b/freemocap/core/pipelines/mocap_pipeline/point_trangulator.pydeleted file mode 100644index 21824229..00000000--- a/freemocap/core/pipelines/mocap_pipeline/point_trangulator.py+++ /dev/null@@ -1,163 +0,0 @@-from dataclasses import dataclass--import cv2-import numpy as np-import toml-from skellycam import CameraId--from freemocap.system.paths_and_filenames.path_getters import get_last_successful_calibration_toml_path--MINIUMUM_CAMERAS_FOR_TRIANGULATION = 2--@dataclass-class CameraCalibrationData:- name: str- size: tuple[int, int]- matrix: np.ndarray # 3x3โข- distortion: np.ndarray # 1x5- rotation_vector: np.ndarray # 3x1 rodriques rotation vector- translation: np.ndarray # 3x1 XYZ translation vector-- @classmethod- def from_tuple(cls, data: tuple):- camera_id, data = data- matrix = np.array(data["matrix"])- distortion = np.array(data["distortions"])- rotation_vector = np.array(data["rotation"])- translation = np.array(data["translation"])- return cls(- name=camera_id,- size=data["size"],- matrix=matrix,- distortion=distortion,- rotation_vector=rotation_vector,- translation=translation,- )-- def __post_init__(self):- if self.matrix.shape != (3, 3):- raise ValueError(f"Expected matrix to be of shape (3, 3), got {self.matrix.shape}")- if self.distortion.shape != ( 5,):- raise ValueError(f"Expected distortion to be of shape (1, 5), got {self.distortion.shape}")- if self.rotation_vector.shape != (3,):- raise ValueError(f"Expected rotation vector to be of shape (3, 1), got {self.rotation_vector.shape}")- if self.translation.shape != (3, ):- raise ValueError(f"Expected translation to be of shape (3, 1), got {self.translation.shape}")-- @property- def rotation_matrix(self):- if self.rotation_vector is None:- return np.eye(3)- return cv2.Rodrigues(self.rotation_vector)[0]-- @property- def extrinsics_matrix(self):- extrinsics_matrix = np.zeros((3, 4))- extrinsics_matrix[:, :3] = self.rotation_matrix- extrinsics_matrix[:, 3] = self.translation- if extrinsics_matrix.shape != (3, 4):- raise ValueError(f"Expected extrinsic matrix to be of shape (3, 4), got {extrinsics_matrix.shape}")- return extrinsics_matrix-- def undistort_2d_points(self, points: np.ndarray):- shape = points.shape- points = points.reshape(-1, 1, 2)- out = cv2.undistortPoints(points, self.matrix.astype("float64"), self.distortion.astype("float64"))- return out.reshape(shape)-- def project_3d_to_2d(self, points):- points = points.reshape(-1, 1, 3)- projected_points_2d, _ = cv2.projectPoints(- points,- self.rotation_vector,- self.translation,- self.matrix,- self.distortion- )- projected_points_2d = np.squeeze(projected_points_2d)- if projected_points_2d.shape[1] != 2:- raise ValueError(f"Expected projected points to be of shape (n, 2), got {projected_points_2d.shape}")- return projected_points_2d--@dataclass-class PointTriangulator:- camera_calibrations: dict[CameraId, CameraCalibrationData]- @classmethod- def create(cls):- calibration_toml_path = get_last_successful_calibration_toml_path()- calibration_data = toml.load(calibration_toml_path)- calibration_data.pop("metadata")- #hacky use of enumerate to get camera id from (old style anipose) camera names- camera_calibrations = {CameraId(camera_id): CameraCalibrationData.from_tuple(data) for camera_id, data in enumerate(calibration_data.items()) if camera_id != "metadata"}- return cls(camera_calibrations=camera_calibrations)-- @property- def camera_calibrations_array(self) -> np.ndarray:- array = np.array([calibration.extrinsics_matrix for calibration in self.camera_calibrations.values()])- if not array.shape == (len(self.camera_calibrations), 3, 4):- raise ValueError(f"Expected extrinsics matrix to be of shape (num_cams, 3, 4), got {array.shape}")- return array-- def triangulate(self, points2d_by_camera: dict[CameraId, dict[str, tuple]], scale_by: float) -> dict[str, tuple]:- all_camera_extrinsics_matrix = self.camera_calibrations_array.copy()- point_names: list[str] = []- points3d: dict[str, tuple] = {name: (np.isnan, np.isnan, np.isnan) for name in point_names}-- for camera_id, points2d in points2d_by_camera.items():- if not point_names:- point_names = list(points2d.keys())- continue- if point_names != list(points2d.keys()):- raise ValueError(f"Expected point names to match, got {point_names} and {list(points2d.keys())}")-- for point_name in point_names:- point2d_views = [points2d[point_name] for points2d in points2d_by_camera.values()]- good_camera_matrices = []- good_points2d_views = []-- for index, point2d in enumerate(point2d_views):- if np.isnan(point2d).any():- continue- good_camera_matrices.append(all_camera_extrinsics_matrix[index])- good_points2d_views.append(point2d)-- if len(good_points2d_views) < MINIUMUM_CAMERAS_FOR_TRIANGULATION:- continue- good_point2d_views_array = np.array(good_points2d_views)- good_camera_extrinsics_matrix = np.array(good_camera_matrices)- _validate_input(good_point2d_views_array, good_camera_extrinsics_matrix)- points3d[point_name] = triangulate_simple(good_point2d_views_array, good_camera_extrinsics_matrix)- points3d[point_name] = tuple([point * scale_by for point in points3d[point_name]])-- return points3d--def _validate_input(points2d_by_camera: np.ndarray, camera_extrinsic_matricies: np.ndarray):- number_of_cameras, points_dimensions = points2d_by_camera.shape- if points_dimensions != 2:- raise ValueError(f"Expected points to be of shape (num_cams, 2), got {points2d_by_camera.shape}")- if number_of_cameras != camera_extrinsic_matricies.shape[0]:- raise ValueError(f"Expected number of cameras to match, got {number_of_cameras} and {camera_extrinsic_matricies.shape[0]}")- if camera_extrinsic_matricies.shape[1:] != (3, 4):- raise ValueError(f"Expected camera extrinsic matricies to be of shape (num_cams, 3, 4), got {camera_extrinsic_matricies.shape}")--# # @jit(nopython=True, parallel=False)-# def triangulate_simple(points2d_by_camera: np.ndarray, camera_extrinsic_matricies: np.ndarray) -> tuple:-# number_of_cameras, points_dimensions = points2d_by_camera.shape-# _validate_input(points2d_by_camera, camera_extrinsic_matricies)-# A = np.zeros((number_of_cameras * 2, 4))-# for camera_number in range(number_of_cameras):-# x, y = points2d_by_camera[camera_number]-# camera_matrix = camera_extrinsic_matricies[camera_number]-# A[(camera_number * 2) : (camera_number * 2 + 1)] = x * camera_matrix[2] - camera_matrix[0]-# A[(camera_number * 2 + 1) : (camera_number * 2 + 2)] = y * camera_matrix[2] - camera_matrix[1]-# u, s, vh = np.linalg.svd(A, full_matrices=True)-# points_3d = vh[-1]-# points_3d = points_3d[:3] / points_3d[3]-# return tuple(points_3d)--if __name__ == "__main__":- _point_triangulator = PointTriangulator.create()- _points2d_by_camera = np.array([[1, 2], [3, 4], [5, 6]])- _camera_extrinsic_matricies = np.array([[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], [[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]], [[25, 26, 27, 28], [29, 30, 31, 32], [33, 34, 35, 36]]])- triangulate_simple(_points2d_by_camera, _camera_extrinsic_matricies)- _point_triangulator.triangulate()\ No newline at end of filediff --git a/freemocap/core/pipelines/pipeline_ipc.py b/freemocap/core/pipelines/pipeline_ipc.pydeleted file mode 100644index 1bc23841..00000000--- a/freemocap/core/pipelines/pipeline_ipc.py+++ /dev/null@@ -1,39 +0,0 @@-import multiprocessing-import uuid-from dataclasses import dataclass, field--from freemocap.core.pubsub.pubsub_manager import PubSubTopicManager, create_pipeline_pubsub_manager-from freemocap.core.types.type_overloads import PipelineIdString--from skellycam.core.ipc.shared_memory.camera_group_shared_memory import CameraGroupSharedMemoryDTO--@dataclass-class PipelineIPC:- pubsub: PubSubTopicManager- pipeline_id: PipelineIdString- global_kill_flag: multiprocessing.Value- pipeline_kill_flag: multiprocessing.Value = field(default_factory=lambda: multiprocessing.Value('b', False))-- @classmethod- def create(cls,- global_kill_flag: multiprocessing.Value,- pipeline_id: PipelineIdString | None = None):- if pipeline_id is None:- pipeline_id = str(uuid.uuid4())[:6]- pubsub = create_pipeline_pubsub_manager(pipeline_id=pipeline_id)- return cls(- pipeline_id=pipeline_id,- pubsub=pubsub,- global_kill_flag=global_kill_flag,- )-- def should_continue(self) -> bool:- return not self.global_kill_flag.value and not self.pipeline_kill_flag.value-- def kill_pipeline(self):- self.pipeline_kill_flag.value = True- self.pubsub.close()-- def kill_everything(self):- self.kill_pipeline()- self.global_kill_flag.value = Truediff --git a/freemocap/core/pipelines/processing_pipeline.py b/freemocap/core/pipelines/processing_pipeline.pydeleted file mode 100644index c178ae41..00000000--- a/freemocap/core/pipelines/processing_pipeline.py+++ /dev/null@@ -1,432 +0,0 @@-import logging-import logging-import multiprocessing-import uuid-from abc import ABC-from copy import deepcopy-from dataclasses import dataclass-from enum import Enum, auto-from typing import Hashable--import numpy as np-from numpydantic import NDArray, Shape-from pydantic import BaseModel, ConfigDict-from skellycam.core.ipc.shared_memory.frame_payload_shared_memory_ring_buffer import FramePayloadSharedMemoryRingBuffer-from skellycam.core.ipc.shared_memory.ring_buffer_shared_memory import SharedMemoryRingBufferDTO-from skellycam.core.ipc.shared_memory.shared_memory_number import SharedMemoryNumber-from skellycam.core.ipc.shared_memory.shared_memory_element import SharedMemoryElementDTO-from skellycam.core.types.type_overloads import CameraIdString, WorkerType, WorkerStrategy, TopicSubscriptionQueue, \- CameraGroupIdString-from skellycam.utilities.wait_functions import wait_1ms-from skellytracker.trackers.base_tracker.base_tracker_abcs import BaseTracker, BaseImageAnnotator, \- BaseImageAnnotatorConfig-from skellytracker.trackers.base_tracker.base_tracker_abcs import TrackerTypeString--from freemocap.core.pipelines.pipeline_ipc import PipelineIPC-from freemocap.core.pubsub.pubsub_manager import TopicTypes-from freemocap.core.pubsub.pubsub_topics import SkellyTrackerConfigsMessage, ProcessFrameNumberMessage, \- CameraNodeOutputMessage, AggregationNodeOutputMessage-from freemocap.core.types.type_overloads import PipelineIdString--logger = logging.getLogger(__name__)---class ReadTypes(str, Enum):- LATEST = auto() # For realtime processing, i.e. drop frames to keep up to date- NEXT = auto() # For offline processing, i.e. make sure to process every frame---class BasePipelineData(BaseModel, ABC):- model_config = ConfigDict(- arbitrary_types_allowed=True,- )- pass---class BaseAggregationLayerOutputData(BasePipelineData):- multi_frame_number: int- points3d: dict[Hashable, NDArray[Shape["3"], np.float64]]---class BaseCameraNodeOutputData(BasePipelineData):- frame_metadata: np.recarray # dtype: FRAME_METADATA_DTYPE- time_to_retrieve_frame_ns: int- time_to_process_frame_ns: int---class BasePipelineOutputData(BasePipelineData):- camera_node_output: dict[CameraIdString, BaseCameraNodeOutputData]- aggregation_layer_output: BaseAggregationLayerOutputData-- @property- def multi_frame_number(self) -> int:- frame_numbers = [camera_node_output.frame_metadata.frame_number for camera_node_output in- self.camera_node_output.values()]- if len(set(frame_numbers)) > 1:- raise ValueError(f"Frame numbers from camera nodes do not match - got {frame_numbers}")- return frame_numbers[0]---@dataclass-class CameraNode:- camera_id: CameraIdString- shutdown_self_flag: multiprocessing.Value- worker: WorkerType-- @classmethod- def create(cls,- camera_id: CameraIdString,- camera_shm_dto: SharedMemoryRingBufferDTO,- worker_strategy: WorkerStrategy,- ipc: PipelineIPC):- shutdown_self_flag = multiprocessing.Value('b', False)- return cls(camera_id=camera_id,- shutdown_self_flag=shutdown_self_flag,- worker=worker_strategy.value(target=cls._run,- name=f"CameraProcessingNode-{camera_id}",- kwargs=dict(camera_id=camera_id,- camera_shm_dto=camera_shm_dto,- ipc=ipc,- shutdown_self_flag=shutdown_self_flag,- process_frame_number_subscription=ipc.pubsub.get_subscription(- TopicTypes.PROCESS_FRAME_NUMBER),- skelly_tracker_configs_subscription=ipc.pubsub.get_subscription(- TopicTypes.SKELLY_TRACKER_CONFIGS)- ),- daemon=True- ),- )-- @staticmethod- def _run(camera_id: CameraIdString,- mf_ring_shm_dto: SharedMemoryRingBufferDTO,- ipc: PipelineIPC,- process_frame_number_subscription: TopicSubscriptionQueue,- skelly_tracker_configs_subscription: TopicSubscriptionQueue,- shutdown_self_flag: multiprocessing.Value,- ):- if multiprocessing.parent_process():- # Configure logging if multiprocessing (i.e. if there is a parent process)- from freemocap.system.logging_configuration.configure_logging import configure_logging- from freemocap import LOG_LEVEL- configure_logging(LOG_LEVEL, ws_queue=ipc.pubsub.topics[TopicTypes.LOGS].publication)- logger.trace(f"Starting camera processing node for camera {camera_id}")- camera_shm = FramePayloadSharedMemoryRingBuffer.recreate(dto=mf_ring_shm_dto,- read_only=False)- trackers: list[BaseTracker] = []- frame_rec_array: np.recarray | None = None- while ipc.should_continue and not shutdown_self_flag.value:- wait_1ms()-- # Check trackers config updates- if not skelly_tracker_configs_subscription.empty():- skelly_tracker_configs_message = skelly_tracker_configs_subscription.get()- if not isinstance(skelly_tracker_configs_message, SkellyTrackerConfigsMessage):- raise ValueError(f"Expected SkellyTrackerConfigsMessage got {type(skelly_tracker_configs_message)}")- logger.debug(f"Received new skelly tracker s for camera {camera_id}: {skelly_tracker_configs_message}")-- # TODO - This method of updating trackers is sloppy and won't scale as we add more trackers, should make more sophisticated- tracker_configs = deepcopy(skelly_tracker_configs_message.tracker_configs)- # Create or update the tracker for this camera- delete_these = []- for existing_tracker in trackers:- for tracker_index, tracker_config in enumerate(tracker_configs):- if isinstance(existing_tracker.config, tracker_config):- existing_tracker.update_config(tracker_config)- delete_these.append(tracker_index)- # Remove trackers that were updated- for index in delete_these:- del tracker_configs[index]-- for tracker_config in tracker_configs:- from skellytracker.trackers.charuco_tracker import CharucoTracker, CharucoTrackerConfig- from skellytracker.trackers.mediapipe_tracker import MediapipeTracker, MediapipeTrackerConfig-- if isinstance(tracker_config, CharucoTrackerConfig):- trackers.append(CharucoTracker.create(config=tracker_config))- elif isinstance(tracker_config, MediapipeTrackerConfig):- trackers.append(MediapipeTracker.create(config=tracker_config))- else:- raise ValueError(f"Unknown tracker config type: {type(tracker_config)}")-- logger.debug(- f"Camera {camera_id}, created/updates trackers: {', '.join([tracker.__class__.__name__ for tracker in trackers])}")-- # Check for new frame to process- if not process_frame_number_subscription.empty():- process_frame_number_message = process_frame_number_subscription.get()- if not isinstance(process_frame_number_message, ProcessFrameNumberMessage):- raise ValueError(- f"Expected ProcessFrameNumberMessage for process frame number, got {type(process_frame_number_message)}")-- logger.debug(- f"Camera {camera_id} received request to process frame number {process_frame_number_message.frame_number}")-- # Process the frame- frame_rec_array = camera_shm.get_data_by_index(index=process_frame_number_message.frame_number,- frame_rec_array=frame_rec_array)- for tracker in trackers:- observation = tracker.process_image(frame_number=frame_rec_array.frame_metadata.frame_number,- image=frame_rec_array.image, )- if observation is not None:- # Publish the observation to the IPC- ipc.pubsub.topics[TopicTypes.CAMERA_NODE_OUTPUT].publish(- CameraNodeOutputMessage(frame_metadata=frame_rec_array.metadata,- tracker_name=tracker.__class__.__name__,- observation=observation))-- def start(self):- logger.debug(f"Starting {self.__class__.__name__} for camera {self.camera_id}")- self.worker.start()-- def stop(self):- logger.debug(f"Stopping {self.__class__.__name__} for camera {self.camera_id}")- self.shutdown_self_flag.value = True- self.worker.join()---@dataclass-class AggregationNode(ABC):- camera_group_id: CameraGroupIdString- shutdown_self_flag: multiprocessing.Value- worker: WorkerType-- @classmethod- def create(cls,- camera_group_id: CameraGroupIdString,- camera_ids: list[CameraIdString],- latest_multiframe_number_shm: SharedMemoryNumber,- ipc: PipelineIPC,- worker_strategy: WorkerStrategy):- shutdown_self_flag = multiprocessing.Value('b', False)- return cls(camera_group_id=camera_group_id,- shutdown_self_flag=shutdown_self_flag,- worker=worker_strategy.value(target=cls._run,- name=f"CameraGroup-{camera_group_id}-AggregationNode",- kwargs=dict(camera_group_id=camera_group_id,- camera_ids=camera_ids,- ipc=ipc,- shutdown_self_flag=shutdown_self_flag,- camera_node_subscription=ipc.pubsub.get_subscription(- TopicTypes.CAMERA_NODE_OUTPUT),- skellytracker_configs_subscription=ipc.pubsub.get_subscription(- TopicTypes.SKELLY_TRACKER_CONFIGS),- latest_multiframe_number_shm_dto=latest_multiframe_number_shm.to_dto(),- ),- daemon=True- ),- )-- @staticmethod- def _run(camera_group_id: CameraGroupIdString,- camera_ids: list[CameraIdString],- ipc: PipelineIPC,- shutdown_self_flag: multiprocessing.Value,- camera_node_subscription: TopicSubscriptionQueue,- skellytracker_configs_subscription: TopicSubscriptionQueue,- latest_multiframe_number_shm_dto: SharedMemoryElementDTO- ):- if multiprocessing.parent_process():- # Configure logging if multiprocessing (i.e. if there is a parent process)- from freemocap.system.logging_configuration.configure_logging import configure_logging- from freemocap import LOG_LEVEL- configure_logging(LOG_LEVEL, ws_queue=ipc.pubsub.topics[TopicTypes.LOGS].publication)- logger.debug(f"Starting aggregation process for camera group {camera_group_id}")- camera_node_outputs: dict[TrackerTypeString, dict[CameraIdString, CameraNodeOutputMessage | None] | None] = {}- latest_multiframe_number_shm = SharedMemoryNumber.recreate(dto=latest_multiframe_number_shm_dto,- read_only=True)- latest_requested_frame: int = -1- while ipc.should_continue and not shutdown_self_flag.value:- wait_1ms()- if latest_requested_frame < 0 or any(- [tracker_results is None for tracker_results in camera_node_outputs.values()]):- ipc.pubsub.topics[TopicTypes.PROCESS_FRAME_NUMBER].publish(- ProcessFrameNumberMessage(frame_number=latest_multiframe_number_shm.value))- # Check for Camera Node Output- if not camera_node_subscription.empty():- camera_node_output_message = camera_node_subscription.get()- if not isinstance(camera_node_output_message, CameraNodeOutputMessage):- raise ValueError(- f"Expected CameraNodeOutputMessage got {type(camera_node_output_message)}")-- # Process the camera node output and aggregate it- tracker_type = camera_node_output_message.tracker_type- camera_id = camera_node_output_message.camera_id- if not tracker_type in camera_node_outputs.keys() or camera_node_outputs[tracker_type] is None:- camera_node_outputs[tracker_type] = {camera_id: None for camera_id in camera_ids}- if not camera_id in camera_ids:- raise ValueError(- f"Camera ID {camera_id} not in camera IDs {camera_ids}")- camera_node_outputs[tracker_type][camera_id] = camera_node_output_message-- # Check if ready to process a frame output- for tracker_type, tracker_results in camera_node_outputs.items():- if all([camera_node_output_message is not None for camera_node_output_message in- tracker_results.values()]):- # All cameras have observations for this tracker and the frame number is greater than or equal to the latest requested frame- if not all([camera_node_output_message.frame_metadata.frame_number == latest_requested_frame for- camera_node_output_message in tracker_results.values()]):- logger.warning(- f"Frame numbers from tracker results do not match - got {[camera_node_output_message.frame_metadata.frame_number for camera_node_output_message in tracker_results.values()]}")-- camera_node_outputs[tracker_type] = None- aggregation_output: AggregationNodeOutputMessage = handle_aggregration_calculations(- tracker_type=tracker_type,- tracker_results=tracker_results- )- ipc.pubsub.topics[TopicTypes.AGGREGATION_NODE_OUTPUT].publish(aggregation_output)- logger.debug(- f"Published aggregation output for frame {latest_requested_frame} with points3d: {aggregation_output.tracked_points3d.keys()}")-- def start(self):- logger.debug(f"Starting {self.__class__.__name__}")- self.worker.start()-- def stop(self):- logger.debug(f"Stopping {self.__class__.__name__}")- self.shutdown_self_flag.value = True- self.worker.join()---def handle_aggregration_calculations(tracker_type: TrackerTypeString,- tracker_results: dict[- CameraIdString, CameraNodeOutputMessage]) -> AggregationNodeOutputMessage:- """ Calculate the aggregation output for a given tracker name and its results from camera nodes.- This function aggregates the 3D points from the tracker results and returns a BaseAggregationLayerOutputData object.- """- frame_number_set = {result.frame_metadata.frame_number for result in tracker_results.values()}- if len(frame_number_set) != 1:- logger.warning(f"Frame numbers from tracker results do not match - got {frame_number_set}")- frame_number = frame_number_set.pop()- points3d = {} # Do the aggregation logic here, e.g. averaging points from different cameras- return AggregationNodeOutputMessage(- frame_number=frame_number,- tracked_points3d=points3d)---class PipelineImageAnnotator(BaseModel, ABC):- camera_node_annotators: dict[CameraIdString, BaseImageAnnotator]-- @classmethod- def create(cls, configs: dict[CameraIdString, BaseImageAnnotatorConfig]):- raise NotImplementedError(- "You need to re-implement this method with your pipeline's version of the PipelineImageAnnotator ")-- def annotate_images(self, mf_rec_array: np.recarray,- pipeline_output: BasePipelineOutputData) -> np.recarray:- raise NotImplementedError(- "You need to re-implement this method with your pipeline's version of the PipelineImageAnnotator ")---from skellycam.core.camera_group.camera_group import CameraGroup---@dataclass-class ProcessingPipeline:- id: PipelineIdString- camera_nodes: dict[CameraIdString, CameraNode]- aggregation_node: AggregationNode- ipc: PipelineIPC-- @property- def alive(self) -> bool:- return all([camera_node.worker.is_alive() for camera_node in- self.camera_nodes.values()]) and self.aggregation_node.worker.is_alive()-- @classmethod- def from_camera_group(cls,- camera_group: CameraGroup,- camera_node_strategy: WorkerStrategy = WorkerStrategy.PROCESS,- aggregation_node_strategy: WorkerStrategy = WorkerStrategy.PROCESS, ):- ipc = PipelineIPC.create(global_kill_flag=camera_group.ipc.global_kill_flag,- )- camera_group_shm_dto = camera_group.shm.to_dto()- camera_nodes = {camera_id: CameraNode.create(camera_id=camera_id,- camera_shm_dto=camera_group_shm_dto.camera_shm_dtos[camera_id],- worker_strategy=camera_node_strategy,- ipc=ipc)- for camera_id, config in camera_group.configs.items()}- aggregation_process = AggregationNode.create(camera_group_id=camera_group.id,- camera_ids=list(camera_nodes.keys()),- latest_multiframe_number_shm=camera_group.shm.latest_multiframe_number,- ipc=ipc,- worker_strategy=aggregation_node_strategy,- )-- return cls(camera_nodes=camera_nodes,- aggregation_node=aggregation_process,- ipc=ipc,- id=str(uuid.uuid4())[:6]- )-- #- # async def process_multiframe_payload(self, multiframe_payload: MultiFramePayload, annotate_images: bool = True) -> \- # tuple[MultiFramePayload, BasePipelineOutputData]:- # self.intake_data(multiframe_payload)- # pipeline_output = await self.get_next_data_async()- # if not multiframe_payload.multi_frame_number == pipeline_output.multi_frame_number:- # raise ValueError(- # f"Frame number mismatch: {multiframe_payload.multi_frame_number} != {pipeline_output.multi_frame_number}")- # annotated_payload = self.annotate_images(multiframe_payload, pipeline_output)- # return annotated_payload, pipeline_output- #- # def intake_data(self, multiframe_payload: MultiFramePayload):- # if not self.ready_to_intake:- # raise ValueError("Pipeline not ready to intake data!")- # if not all(camera_id in self.camera_nodes.keys() for camera_id in multiframe_payload.camera_ids):- # raise ValueError("Data provided for camera IDs not in camera processes!")- # for camera_id, frame_payload in multiframe_payload.frames.items():- # if not frame_payload.frame_number == multiframe_payload.multi_frame_number:- # raise ValueError(- # f"Frame number mismatch: {frame_payload.frame_number} != {multiframe_payload.multi_frame_number}")- # self.camera_nodes[camera_id].intake_data(frame_payload)- #- # def get_next_data(self) -> BasePipelineOutputData | None:- # if self.aggregation_node.output_queue.empty():- # return None- # data = self.aggregation_node.output_queue.get()- # return data- #- # async def get_next_data_async(self) -> BasePipelineOutputData:- # while self.aggregation_node.output_queue.empty():- # await asyncio.sleep(0.001)- # data = self.aggregation_node.output_queue.get()- # return data- #- # def get_latest_data(self) -> BasePipelineOutputData | None:- # while not self.aggregation_node.output_queue.empty():- # self.latest_pipeline_data = self.aggregation_node.output_queue.get()- #- # return self.latest_pipeline_data- #- # def get_output_for_frame(self, target_frame_number: int) -> BasePipelineOutputData | None:- # while not self.aggregation_node.output_queue.empty():- # self.latest_pipeline_data: BasePipelineOutputData = self.aggregation_node.output_queue.get()- # print(f"Frame Annotator got data for frame {self.latest_pipeline_data.multi_frame_number}")- # if self.latest_pipeline_data.multi_frame_number > target_frame_number:- # raise ValueError(- # f"We missed the target frame number {target_frame_number} - current output is for frame {self.latest_pipeline_data.multi_frame_number}")- #- # if self.latest_pipeline_data.multi_frame_number == target_frame_number:- # return self.latest_pipeline_data- #- # def annotate_images(self, multiframe_payload: MultiFramePayload,- # pipeline_output: BasePipelineOutputData | None) -> MultiFramePayload:- # if pipeline_output is None:- # return multiframe_payload- # return self.annotator.annotate_images(multiframe_payload, pipeline_output)-- def start(self):- logger.debug(f"Starting {self.__class__.__name__} with camera processes {list(self.camera_nodes.keys())}...")- self.aggregation_node.start()- for camera_id, camera_node in self.camera_nodes.items():- camera_node.start()--- def shutdown(self):- logger.debug(f"Shutting down {self.__class__.__name__}...")-- self.ipc.global_kill_flag.value = True- self.aggregation_node.stop()- for camera_id, camera_process in self.camera_nodes.items():- camera_process.stop()diff --git a/freemocap/core/pubsub/pubsub_manager.py b/freemocap/core/pubsub/pubsub_manager.pydeleted file mode 100644index bac4195e..00000000--- a/freemocap/core/pubsub/pubsub_manager.py+++ /dev/null@@ -1,80 +0,0 @@-import logging-from enum import Enum, auto-from multiprocessing.process import parent_process--from pydantic import BaseModel, ConfigDict, Field-from skellycam.core.ipc.pubsub.pubsub_abcs import PubSubTopicABC-from skellycam.core.types.type_overloads import TopicSubscriptionQueue--from freemocap.core.pubsub.pubsub_topics import LogsTopic, ProcessFrameNumberTopic, SkellyTrackerConfigsTopic, \- CameraNodeOutputTopic, AggregationNodeOutputTopic-from freemocap.core.types.type_overloads import PipelineIdString--logger = logging.getLogger(__name__)---class TopicTypes(Enum):- PROCESS_FRAME_NUMBER = auto() # Imperative to process a particular frame number- SKELLY_TRACKER_CONFIGS = auto() # Skelly Tracker configuration updates- CAMERA_NODE_OUTPUT = auto() # Output from camera nodes- AGGREGATION_NODE_OUTPUT = auto() # Output from aggregation node- LOGS = auto()---class PubSubTopicManager(BaseModel):- topics: dict[TopicTypes, PubSubTopicABC] = Field(default_factory=lambda: {- TopicTypes.PROCESS_FRAME_NUMBER: ProcessFrameNumberTopic(),- TopicTypes.SKELLY_TRACKER_CONFIGS: SkellyTrackerConfigsTopic(),- TopicTypes.CAMERA_NODE_OUTPUT: CameraNodeOutputTopic(),- TopicTypes.AGGREGATION_NODE_OUTPUT: AggregationNodeOutputTopic(),- TopicTypes.LOGS: LogsTopic(),- })- model_config = ConfigDict(- arbitrary_types_allowed=True,- )-- def get_subscription(self, topic_type: TopicTypes) -> TopicSubscriptionQueue:- """- Get a subscription queue for a specific topic type.- Raises an error if the topic type is not recognized.- """- if parent_process() is not None:- raise RuntimeError("Subscriptions must be created in the main process and passed to children")--- if topic_type not in self.topics:- raise ValueError(f"Unknown topic type: {topic_type}")- sub= self.topics[topic_type].get_subscription()- logger.trace(f"Subscribed to topic {topic_type.name} with {len(self.topics[topic_type].subscriptions)} subscriptions")- return sub-- def close(self) -> None:- """- Close all topics in the manager.- """- logger.debug("Closing PubSubTopicManager...")- for topic in self.topics.values():- topic.close()- self.topics.clear()- logger.debug("PubSubTopicManager closed.")-----PIPELINE_PUB_SUB_MANAGERS: dict[PipelineIdString, PubSubTopicManager] = {}---def create_pipeline_pubsub_manager(pipeline_id: PipelineIdString) -> PubSubTopicManager:- """- Create a global PubSubManager instance, raises an error if called in a non-main process.- """- global PIPELINE_PUB_SUB_MANAGERS- if parent_process() is not None:- raise RuntimeError("PubSubManager can only be created in the main process.")- if PIPELINE_PUB_SUB_MANAGERS.get(pipeline_id) is not None:- logger.debug(f"Creating PubSubManager for group {pipeline_id}")- PIPELINE_PUB_SUB_MANAGERS.get(pipeline_id).close()- PIPELINE_PUB_SUB_MANAGERS[pipeline_id] = PubSubTopicManager()- return PIPELINE_PUB_SUB_MANAGERS[pipeline_id]--diff --git a/freemocap/core/pubsub/pubsub_topics.py b/freemocap/core/pubsub/pubsub_topics.pydeleted file mode 100644index 08c1ea82..00000000--- a/freemocap/core/pubsub/pubsub_topics.py+++ /dev/null@@ -1,108 +0,0 @@-from typing import Type--import numpy as np-from pydantic import Field-from skellycam.core.ipc.pubsub.pubsub_abcs import PubSubTopicABC, TopicMessageABC-from skellycam.core.types.type_overloads import TopicPublicationQueue, CameraGroupIdString, FrameNumberInt-from skellytracker.trackers.base_tracker.base_tracker_abcs import BaseTrackerConfig, BaseObservation, \- TrackedPointIdString-from skellytracker.trackers.base_tracker.base_tracker_abcs import TrackerTypeString--from freemocap.core.types.type_overloads import TrackedPoint3d-from freemocap.system.logging_configuration.handlers.websocket_log_queue_handler import LogRecordModel, \- get_websocket_log_queue---class ProcessFrameNumberMessage(TopicMessageABC):- """- Message containing the frame number of the current process.- This is used to synchronize frame processing across multiple processes.- """- frame_number: int = Field(ge=0, description="Imperative to process this frame number")---class SkellyTrackerConfigsMessage(TopicMessageABC):- """- Message containing SkellyTracker configurations.- This is used to update the SkellyTracker configurations across processes.- """- tracker_configs: list[BaseTrackerConfig] = Field(- default_factory=list,- description="List of SkellyTracker configurations to be applied."- )--class CameraNodeOutputMessage(TopicMessageABC):- """- Message containing the output data from a camera node.- This is used to pass processed camera data to the next stage in the pipeline.- """- frame_metadata: np.recarray = Field(- description="Metadata of the frame processed by the camera node.",)- tracker_name: TrackerTypeString = Field(- description="Name of the tracker used to process the observation.")- observation: BaseObservation = Field(- description="Observation object produced by a Skellytracker Tracker object.",- )-- @property- def camera_id(self) -> str:- """- Returns the camera ID associated with the frame metadata.- This is used to identify which camera produced the data.- """- return self.frame_metadata.camera_config.camera_id[0]-- @property- def tracker_type(self) -> TrackerTypeString:- """- Returns the type of tracker used to process the observation.- This is used to identify the tracker that produced the data.- """- return self.observation.tracker_type---class AggregationNodeOutputMessage(TopicMessageABC):- """- Message containing the output data from an aggregation node.- This is used to pass aggregated data to the next stage in the pipeline.- """- frame_number: FrameNumberInt- camera_group_id: CameraGroupIdString- tracker_name: TrackerTypeString- tracked_points3d: dict[TrackedPointIdString, TrackedPoint3d] = Field(- default_factory=dict,- description="Dictionary containing 3D data for tracked points, where keys are tracked point IDs and values are 3D coordinates.")---class CameraNodeOutputTopic(PubSubTopicABC):- """- Topic for publishing the output data from a camera node.- This is used to pass processed camera data to the next stage in the pipeline.- """- message_type: Type[CameraNodeOutputMessage] = CameraNodeOutputMessage--class AggregationNodeOutputTopic(PubSubTopicABC):- """- Topic for publishing the output data from an aggregation node.- This is used to pass aggregated data to the next stage in the pipeline.- """- message_type: Type[AggregationNodeOutputMessage] = AggregationNodeOutputMessage-class ProcessFrameNumberTopic(PubSubTopicABC):- """- Topic for publishing the frame number of the current process.- This is used to synchronize frame processing across multiple processes.- """- message_type: Type[ProcessFrameNumberMessage] = ProcessFrameNumberMessage---class SkellyTrackerConfigsTopic(PubSubTopicABC):- """- Topic for publishing SkellyTracker configurations.- This is used to update the SkellyTracker configurations across processes.- """- message_type: Type[SkellyTrackerConfigsMessage] = SkellyTrackerConfigsMessage---class LogsTopic(PubSubTopicABC):- message_type: Type[LogRecordModel] = LogRecordModel- publication: TopicPublicationQueue = Field(default_factory=get_websocket_log_queue)diff --git a/freemocap/core/types/__init__.py b/freemocap/core/types/__init__.pyindex 04fcf0dc..4019a2e0 100644--- a/freemocap/core/types/__init__.py+++ b/freemocap/core/types/__init__.py@@ -14,4 +14,3 @@ from freemocap.system.logging_configuration.log_levels import LogLevelsLOG_LEVEL = LogLevels.TRACEconfigure_logging(LOG_LEVEL)-diff --git a/freemocap/core/types/type_overloads.py b/freemocap/core/types/type_overloads.pyindex eaf9f038..00614c20 100644--- a/freemocap/core/types/type_overloads.py+++ b/freemocap/core/types/type_overloads.py@@ -1,4 +1,21 @@-from numpydantic import NDArray, Shape+import multiprocessing++from pydantic import BaseModel++PointIndex = intPipelineIdString = str+TrackedPointNameString = str+VideoIdString = str++TopicPublicationQueue = multiprocessing.Queue+TopicSubscriptionQueue = multiprocessing.Queue++TrackerTypeString = str # TODO - move this to `skellytracker.types` or something++FrameNumberInt = int+-TrackedPoint3d = NDArray[Shape["3 xyz"], float]\ No newline at end of file+class Point3d(BaseModel):+ x: float+ y: float+ z: floatdiff --git a/freemocap/freemocap_app/freemocap_app_lifespan/freemocap_app_lifespan.py b/freemocap/freemocap_app/freemocap_app_lifespan/freemocap_app_lifespan.pydeleted file mode 100644index 64b40941..00000000--- a/freemocap/freemocap_app/freemocap_app_lifespan/freemocap_app_lifespan.py+++ /dev/null@@ -1,33 +0,0 @@-import logging-from contextlib import asynccontextmanager-from pathlib import Path--from fastapi import FastAPI--import freemocap-from freemocap.api.server.server_constants import APP_URL-from freemocap.freemocap_app.freemocap_application import get_freemocap_app, FreemocapApplication-from freemocap.system.paths_and_filenames.path_getters import get_freemocap_data_folder_path--logger = logging.getLogger(__name__)---@asynccontextmanager-async def freemocap_application_lifespan(app: FastAPI):- # Startup actions- logger.api("FreeMoCap API starting...")- logger.info(f"FreeMoCap API base folder path: {get_freemocap_data_folder_path()}")- Path(get_freemocap_data_folder_path()).mkdir(parents=True, exist_ok=True)-- logger.info("Adding middleware...")- freemocap_app:FreemocapApplication = get_freemocap_app()- logger.success(f"FreeMoCap API (version:{freemocap.__version__}) started successfully ๐๐ธโจ")- logger.api(f"FreeMoCap API running on: \n\t\tSwagger API docs - {APP_URL}")-- # # Let the app do its thing- yield-- # Shutdown actions- logger.api("FreeMoCap API ending...")- freemocap_app.close()- logger.success("FreeMoCap API shutdown complete - Goodbye!๐")diff --git a/freemocap/freemocap_app/freemocap_app_lifespan/freemocap_app_setup.py b/freemocap/freemocap_app/freemocap_app_lifespan/freemocap_app_setup.pydeleted file mode 100644index 207f9d6a..00000000--- a/freemocap/freemocap_app/freemocap_app_lifespan/freemocap_app_setup.py+++ /dev/null@@ -1,63 +0,0 @@-import logging--from fastapi import FastAPI-from fastapi.openapi.utils import get_openapi-from fastapi.responses import RedirectResponse-from starlette.responses import FileResponse--import skellycam--import freemocap-from freemocap.api.routers import SKELLYCAM_ROUTERS, FREEMOCAP_ROUTERS-from skellycam.system.default_paths import SKELLYCAM_FAVICON_ICO_PATH--from freemocap.api.middleware.add_middleware import add_middleware-from freemocap.api.middleware.cors import cors-from freemocap.freemocap_app.freemocap_app_lifespan.freemocap_app_lifespan import freemocap_application_lifespan--logger = logging.getLogger(__name__)--def create_freemocap_fastapi_app() -> FastAPI:- logger.api("Creating FastAPI app")- app = FastAPI(lifespan=freemocap_application_lifespan)- cors(app)- register_routes(app)- add_middleware(app)- customize_swagger_ui(app)- return app--def register_routes(app: FastAPI):- @app.get("/")- async def read_root():- return RedirectResponse("/docs")-- @app.get('/favicon.ico', include_in_schema=False)- async def favicon():- return FileResponse(SKELLYCAM_FAVICON_ICO_PATH)-- for router in FREEMOCAP_ROUTERS:- app.include_router(router,prefix=f"/{freemocap.__package_name__}")- for router in SKELLYCAM_ROUTERS:- app.include_router(router, prefix=f"/{skellycam.__package_name__}")-- # Print all routes- logger.debug("All registered routes:")- for route in app.routes:- logger.debug(f"\tRoute: {route.path} (name: {route.name})")--def customize_swagger_ui(app: FastAPI):- def custom_openapi():- if app.openapi_schema:- return app.openapi_schema- openapi_schema = get_openapi(- title="Welcome to the SkellyCam API ๐๐ธโจ",- version=skellycam.__version__,- description=f"The FastAPI/Uvicorn/Swagger Backend UI for SkellyCam: {skellycam.__description__}",- routes=app.routes,- )- # TODO - add SkellyCam logo?-- app.openapi_schema = openapi_schema- return app.openapi_schema-- app.openapi = custom_openapidiff --git a/freemocap/freemocap_app/freemocap_application.py b/freemocap/freemocap_app/freemocap_application.pydeleted file mode 100644index 5d3cac1b..00000000--- a/freemocap/freemocap_app/freemocap_application.py+++ /dev/null@@ -1,86 +0,0 @@-import logging-import multiprocessing-from dataclasses import dataclass, field--from skellycam.core.camera_group.camera_group import CameraGroup-from skellycam.core.types.type_overloads import CameraGroupIdString-from skellycam.skellycam_app.skellycam_app import SkellycamApplication, create_skellycam_app--from freemocap.core.types.type_overloads import PipelineIdString-from freemocap.core.pipelines.processing_pipeline import ProcessingPipeline--logger = logging.getLogger(__name__)----@dataclass-class PipelineManager:- global_kill_flag: multiprocessing.Value- pipelines: dict[PipelineIdString, ProcessingPipeline] = field(default_factory=dict)-- def create_pipeline(self, camera_group:CameraGroup ) -> ProcessingPipeline:- pipeline = ProcessingPipeline.from_camera_group(camera_group=camera_group)- self.pipelines[pipeline.id] = pipeline- logger.info(f"Created pipeline with ID: {pipeline.id} for camera group ID: {camera_group.id}")- return pipeline-- def close_all_pipelines(self):- for pipeline in self.pipelines.values():- pipeline.shutdown()- self.pipelines.clear()- logger.info("All pipelines closed successfully")---@dataclass-class FreemocapApplication:- global_kill_flag: multiprocessing.Value- pipeline_shutdown_event: multiprocessing.Event- skellycam_app: SkellycamApplication- pipeline_manager: PipelineManager-- @classmethod- def create(cls, global_kill_flag: multiprocessing.Value):-- return cls(global_kill_flag=global_kill_flag,- pipeline_shutdown_event=multiprocessing.Event(),- skellycam_app=create_skellycam_app(global_kill_flag=global_kill_flag),- pipeline_manager=PipelineManager(global_kill_flag=global_kill_flag)- )-- @property- def should_continue(self) -> bool:- return not self.global_kill_flag.value-- def connect_pipeline(self, camera_group: CameraGroup) -> tuple[CameraGroupIdString, PipelineIdString]:- if len(self.skellycam_app.camera_group_manager.camera_groups) == 0:- raise ValueError("No camera groups available to create a processing pipeline! Start a camera group first.")- pipeline = self.pipeline_manager.create_pipeline(camera_group=camera_group)- return camera_group.id, pipeline.id-- def disconnect_pipeline(self):- self.pipeline_manager.close_all_pipelines()-- def close(self):- self.global_kill_flag.value = True- self.pipeline_shutdown_event.set()- self.pipeline_manager.close_all_pipelines()- self.skellycam_app.shutdown_skellycam() if self.skellycam_app else None---FREEMOCAP_APP: FreemocapApplication | None = None---def create_freemocap_app(global_kill_flag: multiprocessing.Value) -> FreemocapApplication:- global FREEMOCAP_APP- if FREEMOCAP_APP is None:- FREEMOCAP_APP = FreemocapApplication.create(global_kill_flag=global_kill_flag)- else:- raise ValueError("FreemocapApplication already exists!")- return FREEMOCAP_APP---def get_freemocap_app() -> FreemocapApplication:- global FREEMOCAP_APP- if FREEMOCAP_APP is None:- raise ValueError("FreemocapApplication does not exist!")- return FREEMOCAP_APPdiff --git a/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/anipose_camera_calibrator.py b/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/anipose_camera_calibrator.pydeleted file mode 100644index 47933c91..00000000--- a/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/anipose_camera_calibrator.py+++ /dev/null@@ -1,142 +0,0 @@-import logging-from pathlib import Path-from typing import Callable, Union--import numpy as np--import \- freemocap.old.core_processes.capture_volume_calibration.anipose_camera_calibration.anipose_stuff.anipose_charuco_board-from freemocap.old.core_processes.capture_volume_calibration.charuco_stuff.charuco_board_definition import (- CharucoBoardDefinition,-)-from freemocap.system.paths_and_filenames.path_getters import (- create_camera_calibration_file_name,- get_calibrations_folder_path,- get_last_successful_calibration_toml_path,-)-from freemocap.utilities.get_video_paths import get_video_paths--logger = logging.getLogger(__name__)---class AniposeCameraCalibrator:- def __init__(- self,- charuco_board_object: CharucoBoardDefinition,- charuco_square_size: Union[int, float],- calibration_videos_folder_path: Union[str, Path],- progress_callback: Callable[[str], None] = None,- ):- self._charuco_board_object = charuco_board_object- self._progress_callback = progress_callback-- if charuco_square_size == 1:- warning_string = "Charuco square size is not set, so units of 3d reconstructed data will be in units of `however_long_the_black_edge_of_the_charuco_square_was`. Please input `charuco_square_size` in millimeters (or your preferred unity of length)"- logger.warning(warning_string)- self._progress_callback(warning_string)- self._charuco_square_size = charuco_square_size- self._calibration_videos_folder_path = Path(calibration_videos_folder_path)- self._recording_folder_path = Path(self._calibration_videos_folder_path).parent- self._get_video_paths()- self._initialize_anipose_objects()-- def _get_video_paths(- self,- ):- self._list_of_video_paths = get_video_paths(path_to_video_folder=Path(self._calibration_videos_folder_path))-- def _initialize_anipose_objects(self):- list_of_camera_names = [this_video_path.stem for this_video_path in self._list_of_video_paths]- self._anipose_camera_group_object = freemocap_anipose.AniposeCameraGroup.from_names(list_of_camera_names)-- # add metadata- self._anipose_camera_group_object.metadata["charuco_square_size"] = self._charuco_square_size- self._anipose_camera_group_object.metadata["charuco_board_object"] = str(self._charuco_board_object)- self._anipose_camera_group_object.metadata["path_to_recorded_videos"] = str(- self._calibration_videos_folder_path- )- self._anipose_camera_group_object.metadata["date_time_calibrated"] = str(np.datetime64("now"))-- self._anipose_charuco_board = freemocap.old.core_processes.capture_volume_calibration.anipose_camera_calibration.anipose_stuff.anipose_charuco_board.AniposeCharucoBoard(- self._charuco_board_object.number_of_squares_width,- self._charuco_board_object.number_of_squares_height,- square_length=self._charuco_square_size, # mm- marker_length=self._charuco_square_size * 0.8,- marker_bits=4,- dict_size=250,- )-- def calibrate_camera_capture_volume(self, pin_camera_0_to_origin: bool = False) -> Path:- video_paths_list_of_list_of_strings = [[str(this_path)] for this_path in self._list_of_video_paths]-- (- error,- charuco_frame_data,- charuco_frame_numbers,- ) = self._anipose_camera_group_object.calibrate_videos(- video_paths_list_of_list_of_strings, self._anipose_charuco_board- )- success_str = "Anipose Calibration Successful!"- logger.info(success_str)- self._progress_callback(success_str)- if pin_camera_0_to_origin:- # translate cameras so camera0 is on `0,0,0`- self._anipose_camera_group_object = self.pin_camera_zero_to_origin(self._anipose_camera_group_object)- # self._anipose_camera_group_object = self.rotate_cameras_so_camera_zero_aligns_with_XYZ(self._anipose_camera_group_object)-- # save calibration info to files- calibration_toml_filename = create_camera_calibration_file_name(- recording_name=self._calibration_videos_folder_path.parent.stem- )-- calibration_folder_toml_path = Path(get_calibrations_folder_path()) / calibration_toml_filename-- self._anipose_camera_group_object.dump(calibration_folder_toml_path)- logger.debug(- f"anipose camera calibration data saved to Calibrations folder - {str(calibration_folder_toml_path)}"- )-- recording_folder_toml_path = Path(self._recording_folder_path) / calibration_toml_filename-- self._anipose_camera_group_object.dump(recording_folder_toml_path)- logger.debug(f"anipose camera calibration data saved to Recording folder - {str(recording_folder_toml_path)}")-- last_successful_calibration_toml_path = get_last_successful_calibration_toml_path()- self._anipose_camera_group_object.dump(last_successful_calibration_toml_path)-- logger.debug(- f"anipose camera calibration data also saved to 'Last Successful Calibration' - {last_successful_calibration_toml_path}"- )- self._progress_callback(- "Anipose camera calibration data saved to calibrations folder, recording folder, and `Last Successful Calibration` file"- )-- return calibration_folder_toml_path-- def pin_camera_zero_to_origin(self, _anipose_camera_group_object):- original_translation_vectors = _anipose_camera_group_object.get_translations()- camera_0_translation = original_translation_vectors[0, :]- altered_translation_vectors = np.zeros(original_translation_vectors.shape)- for this_camera_number in range(original_translation_vectors.shape[0]):- altered_translation_vectors[this_camera_number, :] = (- original_translation_vectors[this_camera_number, :] - camera_0_translation- )-- _anipose_camera_group_object.set_translations(altered_translation_vectors)- logger.debug(f"original translation vectors:\n {original_translation_vectors}")- logger.debug(f"altered translation vectors:\n {_anipose_camera_group_object.get_translations()}")- return _anipose_camera_group_object-- def rotate_cameras_so_camera_zero_aligns_with_XYZ(self, _anipose_camera_group_object):- logger.warning("this function does not work, dont use it lol ")- pass- # original_rotations_euler = _anipose_camera_group_object.get_rotations()- # original_translation_vectors = _anipose_camera_group_object.get_translations()- # camera_rotation_matrix_list = [- # Rotation.from_euler('xyz', original_rotations_euler[this_cam_num, :]).as_matrix() for- # this_cam_num in range(original_rotations_euler.shape[0])]- #- # rotated_translation_vectors = [camera_rotation_matrix_list[0] @ this_tx for this_tx in- # original_translation_vectors]- # _anipose_camera_group_object.set_rotations(rotated_translation_vectors)- # return _anipose_camera_group_objectdiff --git a/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/anipose_stuff/anipose_charuco_board.py b/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/anipose_stuff/anipose_charuco_board.pydeleted file mode 100644index 62d6aa8c..00000000--- a/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/anipose_stuff/anipose_charuco_board.py+++ /dev/null@@ -1,179 +0,0 @@-import cv2-import numpy as np-from aniposelib.boards import CharucoBoard---class AniposeCharucoBoard(CharucoBoard):- def __init__(- self,- squaresX,- squaresY,- square_length,- marker_length,- marker_bits=4,- dict_size=50,- aruco_dict=None,- manually_verify=False,- ):- self.squaresX = squaresX- self.squaresY = squaresY- self.square_length = square_length- self.marker_length = marker_length- self.manually_verify = manually_verify-- ARUCO_DICTS = {- (4, 50): cv2.aruco.DICT_4X4_50,- (5, 50): cv2.aruco.DICT_5X5_50,- (6, 50): cv2.aruco.DICT_6X6_50,- (7, 50): cv2.aruco.DICT_7X7_50,- (4, 100): cv2.aruco.DICT_4X4_100,- (5, 100): cv2.aruco.DICT_5X5_100,- (6, 100): cv2.aruco.DICT_6X6_100,- (7, 100): cv2.aruco.DICT_7X7_100,- (4, 250): cv2.aruco.DICT_4X4_250,- (5, 250): cv2.aruco.DICT_5X5_250,- (6, 250): cv2.aruco.DICT_6X6_250,- (7, 250): cv2.aruco.DICT_7X7_250,- (4, 1000): cv2.aruco.DICT_4X4_1000,- (5, 1000): cv2.aruco.DICT_5X5_1000,- (6, 1000): cv2.aruco.DICT_6X6_1000,- (7, 1000): cv2.aruco.DICT_7X7_1000,- }-- dkey = (marker_bits, dict_size)- self.dictionary = cv2.aruco.getPredefinedDictionary(ARUCO_DICTS[dkey])-- self.board = cv2.aruco.CharucoBoard(- size=[squaresX, squaresY],- squareLength=square_length,- markerLength=marker_length,- dictionary=self.dictionary,- )-- total_size = (squaresX - 1) * (squaresY - 1)-- objp = np.zeros((total_size, 3), np.float64)- objp[:, :2] = np.mgrid[0 : (squaresX - 1), 0 : (squaresY - 1)].T.reshape(-1, 2)- objp *= square_length- self.objPoints = objp-- self.empty_detection = np.zeros((total_size, 1, 2)) * np.nan- self.total_size = total_size-- def detect_markers(self, image, camera=None, refine=True):- if len(image.shape) == 3:- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)- else:- gray = image-- params = cv2.aruco.DetectorParameters()- params.cornerRefinementMethod = cv2.aruco.CORNER_REFINE_CONTOUR- params.adaptiveThreshWinSizeMin = 100- params.adaptiveThreshWinSizeMax = 700- params.adaptiveThreshWinSizeStep = 50- params.adaptiveThreshConstant = 0-- try:- corners, ids, rejectedImgPoints = cv2.aruco.detectMarkers(gray, self.dictionary, parameters=params)- except Exception:- ids = None-- if ids is None:- return [], []-- if camera is None:- K = D = None- else:- K = camera.get_camera_matrix()- D = camera.get_distortions()-- if refine:- detectedCorners, detectedIds, rejectedCorners, recoveredIdxs = cv2.aruco.refineDetectedMarkers(- gray, self.board, corners, ids, rejectedImgPoints, K, D, parameters=params- )- else:- detectedCorners, detectedIds = corners, ids-- return detectedCorners, detectedIds-- def detect_image(self, image, camera=None):- if len(image.shape) == 3:- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)- else:- gray = image-- corners, ids = self.detect_markers(image, camera, refine=True)- if len(corners) > 0:- ret, detectedCorners, detectedIds = cv2.aruco.interpolateCornersCharuco(corners, ids, gray, self.board)- if detectedIds is None:- detectedCorners = detectedIds = np.float64([])- else:- detectedCorners = detectedIds = np.float64([])-- if (- len(detectedCorners) > 0- and self.manually_verify- and not self.manually_verify_board_detection(gray, detectedCorners, detectedIds)- ):- detectedCorners = detectedIds = np.float64([])-- return detectedCorners, detectedIds-- def manually_verify_board_detection(self, image, corners, ids=None):- height, width = image.shape[:2]- image = cv2.aruco.drawDetectedCornersCharuco(image, corners, ids)- cv2.putText(- image,- "(a) Accept (d) Reject",- (int(width / 1.35), int(height / 16)),- cv2.FONT_HERSHEY_SIMPLEX,- 0.5,- 255,- 1,- cv2.LINE_AA,- )- cv2.imshow("verify_detection", image)- while 1:- key = cv2.waitKey(0) & 0xFF- if key == ord("a"):- cv2.putText(- image,- "Accepted!",- (int(width / 2.5), int(height / 1.05)),- cv2.FONT_HERSHEY_SIMPLEX,- 1,- 255,- 2,- cv2.LINE_AA,- )- cv2.imshow("verify_detection", image)- cv2.waitKey(100)- return True- elif key == ord("d"):- cv2.putText(- image,- "Rejected!",- (int(width / 2.5), int(height / 1.05)),- cv2.FONT_HERSHEY_SIMPLEX,- 1,- 255,- 2,- cv2.LINE_AA,- )- cv2.imshow("verify_detection", image)- cv2.waitKey(100)- return False-- def estimate_pose_points(self, camera, corners, ids):- if corners is None or ids is None or len(corners) < 5:- return None, None-- n_corners = corners.size // 2- corners = np.reshape(corners, (n_corners, 1, 2))-- K = camera.get_camera_matrix()- D = camera.get_distortions()-- ret, rvec, tvec = cv2.aruco.estimatePoseCharucoBoard(corners, ids, self.board, K, D, None, None)-- return rvec, tvecdiff --git a/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/anipose_stuff/anipose_functions.py b/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/anipose_stuff/anipose_functions.pydeleted file mode 100644index 66a48b45..00000000--- a/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/anipose_stuff/anipose_functions.py+++ /dev/null@@ -1,188 +0,0 @@-import queue-from collections import defaultdict, Counter--import cv2-import numpy as np-from scipy.cluster.hierarchy import linkage, fcluster-from scipy.cluster.vq import whiten-from scipy.linalg import inv as inverse---def get_connections(xs, cam_names=None, both=True):- n_cams = xs.shape[0]- n_points = xs.shape[1]-- if cam_names is None:- cam_names = np.arange(n_cams)-- connections = defaultdict(int)-- for rnum in range(n_points):- ixs = np.where(~np.isnan(xs[:, rnum, 0]))[0]- keys = [cam_names[ix] for ix in ixs]- for i in range(len(keys)):- for j in range(i + 1, len(keys)):- a = keys[i]- b = keys[j]- connections[(a, b)] += 1- if both:- connections[(b, a)] += 1-- return connections---def get_calibration_graph(rtvecs, cam_names=None):- n_cams = rtvecs.shape[0]- n_points = rtvecs.shape[1]-- if cam_names is None:- cam_names = np.arange(n_cams)-- connections = get_connections(rtvecs, np.arange(n_cams))-- components = dict(zip(np.arange(n_cams), range(n_cams)))- edges = set(connections.items())-- graph = defaultdict(list)-- for edgenum in range(n_cams - 1):- if len(edges) == 0:- component_names = dict()- for k, v in list(components.items()):- component_names[cam_names[k]] = v- raise ValueError(- """-Could not build calibration graph.-Some group of cameras could not be paired by simultaneous calibration board detections.-Check which cameras have different group numbers below to see the missing edges.-{}""".format(- component_names- )- )-- (a, b), weight = max(edges, key=lambda x: x[1])- graph[a].append(b)- graph[b].append(a)-- match = components[a]- replace = components[b]- for k, v in components.items():- if match == v:- components[k] = replace-- for e in edges.copy():- (a, b), w = e- if components[a] == components[b]:- edges.remove(e)-- return graph---def find_calibration_pairs(graph, source=None):- pairs = []- explored = set()-- if source is None:- source = sorted(graph.keys())[0]-- q = queue.deque()- q.append(source)-- while len(q) > 0:- item = q.pop()- explored.add(item)-- for new in graph[item]:- if new not in explored:- q.append(new)- pairs.append((item, new))- return pairs---def compute_camera_matrices(rtvecs, pairs):- extrinsics = dict()- source = pairs[0][0]- extrinsics[source] = np.identity(4)- for a, b in pairs:- ext = get_transform(rtvecs, b, a)- extrinsics[b] = np.matmul(ext, extrinsics[a])- return extrinsics---def get_transform(rtvecs, left, right):- L = []- for dix in range(rtvecs.shape[1]):- d = rtvecs[:, dix]- good = ~np.isnan(d[:, 0])-- if good[left] and good[right]:- M_left = make_M(d[left, 0:3], d[left, 3:6])- M_right = make_M(d[right, 0:3], d[right, 3:6])- M = np.matmul(M_left, inverse(M_right))- L.append(M)- L_best = select_matrices(L)- M_mean = mean_transform(L_best)- # M_mean = mean_transform_robust(L, M_mean, error=0.5)- # M_mean = mean_transform_robust(L, M_mean, error=0.2)- M_mean = mean_transform_robust(L, M_mean, error=0.1)- return M_mean---def get_most_common(vals):- Z = linkage(whiten(vals), "ward")- n_clust = max(len(vals) / 10, 3)- clusts = fcluster(Z, t=n_clust, criterion="maxclust")- cc = Counter(clusts[clusts >= 0])- most = cc.most_common(n=1)- top = most[0][0]- good = clusts == top- return good---def select_matrices(Ms):- Ms = np.array(Ms)- rvecs = [cv2.Rodrigues(M[:3, :3])[0][:, 0] for M in Ms]- tvecs = np.array([M[:3, 3] for M in Ms])- best = get_most_common(np.hstack([rvecs, tvecs]))- Ms_best = Ms[best]- return Ms_best---def mean_transform(M_list):- rvecs = [cv2.Rodrigues(M[:3, :3])[0][:, 0] for M in M_list]- tvecs = [M[:3, 3] for M in M_list]-- rvec = np.mean(rvecs, axis=0)- tvec = np.mean(tvecs, axis=0)-- return make_M(rvec, tvec)---def mean_transform_robust(M_list, approx=None, error=0.3):- if approx is None:- M_list_robust = M_list- else:- M_list_robust = []- for M in M_list:- rot_error = (M - approx)[:3, :3]- m = np.max(np.abs(rot_error))- if m < error:- M_list_robust.append(M)- return mean_transform(M_list_robust)---def get_initial_extrinsics(rtvecs, cam_names=None):- graph = get_calibration_graph(rtvecs, cam_names)- pairs = find_calibration_pairs(graph, source=0)- extrinsics = compute_camera_matrices(rtvecs, pairs)-- n_cams = rtvecs.shape[0]- rvecs = []- tvecs = []- for cnum in range(n_cams):- rvec, tvec = get_rtvec(extrinsics[cnum])- rvecs.append(rvec)- tvecs.append(tvec)- rvecs = np.array(rvecs)- tvecs = np.array(tvecs)- return rvecs, tvecsdiff --git a/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/anipose_stuff/anipose_triangulate_simple.py b/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/anipose_stuff/anipose_triangulate_simple.pydeleted file mode 100644index b28b04f6..00000000--- a/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/anipose_stuff/anipose_triangulate_simple.py+++ /dev/null@@ -1,3 +0,0 @@---diff --git a/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/anipose_stuff/fisheye_camera.py b/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/anipose_stuff/fisheye_camera.pydeleted file mode 100644index b4ca3f62..00000000--- a/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/anipose_stuff/fisheye_camera.py+++ /dev/null@@ -1,106 +0,0 @@-import cv2-import numpy as np--from freemocap.old.core_processes.capture_volume_calibration.anipose_camera_calibration.anipose_stuff import \- Camera---class FisheyeCamera(Camera):- def __init__(- self,- matrix=np.eye(3),- dist=np.zeros(4),- size=None,- rvec=np.zeros(3),- tvec=np.zeros(3),- name=None,- extra_dist=False,- ):- self.set_camera_matrix(matrix)- self.set_distortions(dist)- self.set_size(size)- self.set_rotation(rvec)- self.set_translation(tvec)- self.set_name(name)- self.extra_dist = extra_dist-- def from_dict(d):- cam = FisheyeCamera()- cam.load_dict(d)- return cam-- def get_dict(self):- d = super().get_dict()- d["fisheye"] = True- return d-- def distort_points(self, points):- shape = points.shape- points = points.reshape(-1, 1, 2)- new_points = np.dstack([points, np.ones((points.shape[0], 1, 1))])- out, _ = cv2.fisheye.projectPoints(- new_points,- np.zeros(3),- np.zeros(3),- self.matrix.astype("float64"),- self.dist.astype("float64"),- )- return out.reshape(shape)-- def undistort_points(self, points):- shape = points.shape- points = points.reshape(-1, 1, 2)- out = cv2.fisheye.undistortPoints(- points.astype("float64"),- self.matrix.astype("float64"),- self.dist.astype("float64"),- )- return out.reshape(shape)-- def project(self, points):- points = points.reshape(-1, 1, 3)- out, _ = cv2.fisheye.projectPoints(- points,- self.rvec,- self.tvec,- self.matrix.astype("float64"),- self.dist.astype("float64"),- )- return out-- def set_params(self, params):- self.set_rotation(params[0:3])- self.set_translation(params[3:6])- self.set_focal_length(params[6])-- dist = np.zeros(4, dtype="float64")- dist[0] = params[7]- if self.extra_dist:- dist[1] = params[8]- # dist[2] = params[9]- # dist[3] = params[10]- self.set_distortions(dist)-- def get_params(self):- params = np.zeros(8 + self.extra_dist, dtype="float64")- params[0:3] = self.get_rotation()- params[3:6] = self.get_translation()- params[6] = self.get_focal_length()- dist = self.get_distortions()- params[7] = dist[0]- if self.extra_dist:- params[8] = dist[1]- # params[9] = dist[2]- # params[10] = dist[3]- return params-- def copy(self):- return FisheyeCamera(- matrix=self.get_camera_matrix().copy(),- dist=self.get_distortions().copy(),- size=self.get_size(),- rvec=self.get_rotation().copy(),- tvec=self.get_translation().copy(),- name=self.get_name(),- extra_dist=self.extra_dist,- )diff --git a/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/run_anipose_calibration_algorithm.py b/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/run_anipose_calibration_algorithm.pydeleted file mode 100644index ceb22eba..00000000--- a/freemocap/old/core_processes/capture_volume_calibration/anipose_camera_calibration/run_anipose_calibration_algorithm.py+++ /dev/null@@ -1,853 +0,0 @@-# Most of this was copied (with permission) from the original `aniposelib` package (https://github.com/lambdaloop/aniposelib), and we're adapting it to our needs here. M-# ore info on Anipoise: https://anipose.readthedocs.io/en/latest/--import logging-from copy import deepcopy-from dataclasses import dataclass-from typing import Any--import cv2-import numpy as np-from numba import jit-from scipy import optimize-from scipy.linalg import inv as inverse-from scipy.sparse import dok_matrix-from skellycam import CameraId-from tqdm import trange--from freemocap.core.pipelines.calibration_pipeline.calibration_numpy_types import \- ImagePoints2DByCamera, CameraExtrinsicsMatrixByCamera--logger = logging.getLogger(__name__)---@jit(nopython=True, parallel=False)-def anipose_triangulate_simple(points2d_by_camera: ImagePoints2DByCamera,- camera_matrices_by_camera: CameraExtrinsicsMatrixByCamera) -> np.ndarray:- """- Triangulate 3D point from 2D points and camera matrices using the Direct Linear Transform (DLT) method.-- :param points2d_by_camera: A 2D array of shape (N, 2), where N is the number of cameras. Each row represents the- 2D coordinates (x, y) of the point in the image plane of each camera.- :param camera_matrices_by_camera: A 3D array of shape (N, 3, 4), where each element is a 3x4 camera projection matrix.- :return: A 1D array of shape (3,) representing the triangulated 3D point.- """-- num_cams = camera_matrices_by_camera.shape[0]- A = np.zeros((num_cams * 2, 4))-- for i in range(num_cams):- x, y = points2d_by_camera[i]- mat = camera_matrices_by_camera[i]- A[i * 2] = x * mat[2] - mat[0]- A[i * 2 + 1] = y * mat[2] - mat[1]-- _, _, vh = np.linalg.svd(A,- full_matrices=False) # CHECK - Ai said this could be set to False since " we only need the right singular vectors, which is more efficient." but we should check on this bc I don't know what that means lol-- points3d_xyzh = vh[-1]- points3d_xyzh /= points3d_xyzh[3] # Normalize the last element to 1-- return points3d_xyzh[:3] # Return only the first 3 elements (x, y, z)---@dataclass-class CalibrationInputData:- pixel_points2d: np.ndarray # Shape: (N_cams, N_points, 2), px, py pixel coordinates of object points- object_points3d: np.ndarray # Shape: (N_points, 3), x, y, z object points in 3D space (corresponding to pixel_points2d)- ids: np.ndarray # IDs of points (2d and 3d) for each camera- rotation_vectors: np.ndarray # Rotation vectors- translation_vectors: np.ndarray # Translation vectors-- def __post_init__(self):- number_of_points = self.pixel_points2d.shape[1]- if not self.pixel_points2d.ndim == 3 and self.pixel_points2d.shape[2] == 2:- raise ValueError(- f"Invalid pixel_points2d shape, expected shape to be (N_cams, N_points, 2), but got shape {self.pixel_points2d.shape}"- )-- if not self.object_points3d.shape[0] == number_of_points:- raise ValueError(- f"Invalid object_points3d shape, expected first dimension to be equal to "- f"number of points ({number_of_points}), but got shape {self.object_points3d.shape}"- )- if not self.ids.shape[0] == number_of_points:- raise ValueError(- f"Invalid ids shape, expected first dimension to be equal to "- f"number of points ({number_of_points}), but got shape {self.ids.shape}"- )- if not self.rotation_vectors.shape[0] == len(self.pixel_points2d):- raise ValueError(- f"Invalid rotation_vectors shape, expected first dimension to be equal to "- f"number of cameras ({len(self.pixel_points2d)}), but got shape {self.rotation_vectors.shape}"- )- if not self.translation_vectors.shape[0] == len(self.pixel_points2d):- raise ValueError(- f"Invalid translation_vectors shape, expected first dimension to be equal to "- f"number of cameras ({len(self.pixel_points2d)}), but got shape {self.translation_vectors.shape}"- )-- def resample_indicies(self, indicies: list[int]):- return CalibrationInputData(- pixel_points2d=self.pixel_points2d[:, indicies],- object_points3d=self.object_points3d[indicies],- ids=self.ids[indicies],- rotation_vectors=self.rotation_vectors[:, indicies],- translation_vectors=self.translation_vectors[:, indicies],- )---def calculate_error_bounds(error_dict: dict[tuple[int, int], tuple[int, np.ndarray]]) -> tuple[float, float]:- """Calculate the maximum and minimum error bounds from an error dictionary.-- Args:- error_dict (Dict[Tuple[int, int], Tuple[int, np.ndarray]]): Dictionary containing error statistics- for camera pairs, where the key is a tuple of camera indices and the value is a tuple of- (number of observations, percentiles).-- Returns:- Tuple[float, float]: A tuple of (max_error, min_error) based on the percentiles of error means.- """- max_error = 0.0- min_error = float('inf')- for _, (_, percents) in error_dict.items():- max_error = max(percents[-1], max_error)- min_error = min(percents[0], min_error)- return max_error, min_error---def transform_points(points, rotation_vectors, translation_vectors):- """Rotate points by given rotation vectors and translate.- Rodrigues' rotation formula is used.- """- theta = np.linalg.norm(rotation_vectors, axis=1)[:, np.newaxis]- with np.errstate(invalid="ignore"):- v = rotation_vectors / theta- v = np.nan_to_num(v)- dot = np.sum(points * v, axis=1)[:, np.newaxis]- cos_theta = np.cos(theta)- sin_theta = np.sin(theta)-- rotated = cos_theta * points + sin_theta * np.cross(v, points) + dot * (1 - cos_theta) * v-- return rotated + translation_vectors---def remap_ids(ids: np.ndarray | list[int]) -> np.ndarray:- """- Remap the unique identifiers in the input array to a consecutive range starting from zero.-- :param ids: An array-like structure containing the original identifiers.- :return: A NumPy array with the identifiers remapped to a consecutive range.- """- ids_array = np.asarray(ids)- unique_ids, remapped_ids = np.unique(ids_array, return_inverse=True)- return remapped_ids---def subset_extra_data(extra_data: dict[str, Any], indices: np.ndarray) -> dict[str, Any]:- """- Subset the extra data dictionary based on the selected indices.-- :param extra_data: The dictionary containing extra data.- :param indices: The indices to subset the data.- :return: A new dictionary with data subset according to the provided indices.- """- if not extra_data:- return extra_data- return {key: value[indices] for key, value in extra_data.items() if key in extra_data}---def resample_points_based_on_shared_views(calibration_input_data: CalibrationInputData,- number_of_samples_to_return: int = 25) -> CalibrationInputData:- """- Resample calibration input data prioritize 2d points seen by multiple cameras.- """- points2d = calibration_input_data.pixel_points2d- n_cams = points2d.shape[0]- points2d_valid = ~np.isnan(points2d[:, :, 0]) # Boolean array indicating valid (non-NaN) points- point_indices = np.arange(points2d.shape[1])- num_cams = np.sum(points2d_valid, axis=0) # Number of cameras observing each point-- included_points = set()-- # Iterate over each unique pair of cameras- for first_cam in range(n_cams):- for second_cam in range(first_cam + 1, n_cams):- # Determine which points are visible in both selected cameras- visible_in_both = points2d_valid[first_cam] & points2d_valid[second_cam]- n_good = np.sum(visible_in_both)-- if n_good > 0:- # Select points seen by the most cameras, adding a small random value for tie-breaking- visibility_scores = num_cams[visible_in_both].astype(np.float64)- visibility_scores += np.random.random(size=visibility_scores.shape)-- # Pick the top n_samp points based on visibility scores- picked_indices = np.argsort(-visibility_scores)[:number_of_samples_to_return]- selected_points = point_indices[visible_in_both][picked_indices]-- # Add selected points to the set of included points- included_points.update(selected_points)-- # Sort the final indices of included points for consistent ordering- final_indices = sorted(included_points)-- return calibration_input_data.resample_indicies(final_indices)---def construct_camera_extrinsics_matrix(rotation_vector: np.ndarray,- translation_vector: np.ndarray) -> np.ndarray:- if rotation_vector.shape != (3,) or translation_vector.shape != (3,):- raise ValueError("Rotation vector and translation vector must have shape (3,)")- extrinsics_matrix = np.zeros((4, 4))- rotmat, _ = cv2.Rodrigues(rotation_vector)- extrinsics_matrix[:3, :3] = rotmat- extrinsics_matrix[:3, 3] = translation_vector.flatten()- extrinsics_matrix[3, 3] = 1- return extrinsics_matrix---def get_rotation_and_translation_vector_from_extrinsics_matrix(extrinsics_matrix: np.ndarray) -> tuple[- np.ndarray, np.ndarray]:- if extrinsics_matrix.shape != (4, 4):- raise ValueError("Extrinsics matrix must be a 4x4 matrix")- rotation_vector = cv2.Rodrigues(extrinsics_matrix[:3, :3])[0].flatten()- translation_vector = extrinsics_matrix[:3, 3].flatten()- return rotation_vector, translation_vector---def get_error_dict(errors_full, min_points=10):- n_cams = errors_full.shape[0]- errors_norm = np.linalg.norm(errors_full, axis=2)-- good = ~np.isnan(errors_full[:, :, 0])-- error_dict = dict()-- for i in range(n_cams):- for j in range(i + 1, n_cams):- subset = good[i] & good[j]- err_subset = errors_norm[:, subset][[i, j]]- err_subset_mean = np.mean(err_subset, axis=0)- if np.sum(subset) > min_points:- percents = np.percentile(err_subset_mean, [15, 75])- # percents = np.percentile(err_subset, [25, 75])- error_dict[(i, j)] = (err_subset.shape[1], percents)- return error_dict---@dataclass-class AniposeCameraCalibrationEstimate:- name: str- camera_id: CameraId- size: tuple[int, int]- rotation_vector: np.ndarray- translation_vector: np.ndarray-- camera_matrix: np.ndarray = np.eye(3, dtype="float64")- distortion_coefficients: np.ndarray = np.zeros(5),-- @property- def focal_length(self):- fx = self.camera_matrix[0, 0]- fy = self.camera_matrix[1, 1]- return (fx + fy) / 2.0-- @focal_length.setter- def focal_length(self, fx: float, fy: float = None):- if fy is None:- fy = fx- self.camera_matrix[0, 0] = fx- self.camera_matrix[1, 1] = fy-- @property- def extrinsics_matrix(self) -> np.ndarray:- """- Returns the extrinsics matrix of the camera, which is a 4x4 matrix that transforms points from the camera coordinate system to the world coordinate system.- the left upper 3x3 matrix is the rotation matrix, and the rightmost column is the translation vector.- the bottom row is [0, 0, 0, 1] (where the 1 is the homogeneous coordinate, which makes the matrix invertible and provides the scale factor for the translation vector to put it in spatial coordinates)- """-- extrinsics_matrix = np.zeros((4, 4))-- extrinsics_matrix[:3, :3] = cv2.Rodrigues(self.rotation_vector)- extrinsics_matrix[:3, 3] = self.translation_vector.flatten()- extrinsics_matrix[3, 3] = 1- return extrinsics_matrix-- def get_optimizable_parameters(self):- """- Grabs the parametesr that will be optimed and organizes them in a numpy array- :return:- """- optimized_parameters = np.zeros(9, dtype="float64")- optimized_parameters[0:3] = self.rotation_vector- optimized_parameters[3:6] = self.translation_vector- optimized_parameters[6] = self.focal_length- optimized_parameters[7] = self.distortion_coefficients[0]- optimized_parameters[8] = self.distortion_coefficients[1]- return optimized_parameters-- def set_optimized_parameters(self, optimized_parameters: np.ndarray):- """- Sets camera parameters from optimized parameters--- :param optimized_parameters:- :return:- """-- self.rotation_vector = optimized_parameters[0:3]- self.translation_vector = optimized_parameters[3:6]- self.focal_length = optimized_parameters[6]-- distortion_coefficients = np.zeros(5)- distortion_coefficients[0] = optimized_parameters[7]- distortion_coefficients[1] = optimized_parameters[8]- self.distortion_coefficients = distortion_coefficients-- def undistort_points(self, points2d: np.ndarray) -> np.ndarray:- """- Undistorts 2D points using the camera's intrinsic parameters and distortion coefficients.-- This function adjusts the provided 2D points to account for lens distortion, returning- points that are mapped as they would appear in an ideal pinhole camera model. The process- ensures that the ray passing from the nodal point of the camera lens through the- undistorted 2D point intersects the corresponding 3D point in space accurately.-- :param points2d: A NumPy array of shape (N, 2) or (N, M, 2) representing the 2D points- to be undistorted. These are typically the distorted pixel coordinates- captured by the camera.- :return: A NumPy array of the same shape as `points2d` containing the undistorted 2D points.- """- shape = points2d.shape- points2d = points2d.reshape(-1, 1, 2)- undistorted_points2d = cv2.undistortPoints(points2d, self.camera_matrix.astype("float64"),- self.distortion_coefficients.astype("float64"))- return undistorted_points2d.reshape(shape)-- def project_3d_to_2d(self, points3d: np.ndarray) -> np.ndarray:- if not points3d.shape[-1] == 3:- raise ValueError("points3d must have shape (N, 3)")- points3d = points3d.reshape(-1, 1, 3)- projected_2d_points, _ = cv2.projectPoints(- points3d,- self.rotation_vector,- self.translation_vector,- self.camera_matrix.astype("float64"),- self.distortion_coefficients.astype("float64"),- )- if projected_2d_points.shape != (points3d.shape[0], 1, 2):- raise ValueError(f"projected_2d_points has incorrect shape: {projected_2d_points.shape}")-- return projected_2d_points-- def single_camera_reprojection_error(self, points3d: np.ndarray, points2d: np.ndarray) -> np.ndarray:-- projected_points3d = self.project_3d_to_2d(points3d)- projecting_3d_points_onto_2d_image_plane = projected_points3d.reshape(- points2d.shape) # ? Should this be np.squeeze(projected_points3d)?- return points2d - projecting_3d_points_onto_2d_image_plane---@dataclass-class AniposeCameraGroupCalibrator:- camera_calibration_estimates: dict[CameraId, AniposeCameraCalibrationEstimate]-- max_iterations: int = 10- starting_error_threshold: float = 15.0- ending_error_threshold: float = 1.0- max_number_function_evals: int = 200- function_tolerance: float = 1e-4- number_of_samples_per_iteration: int = 100- number_of_samples_full: int = 1000- error_threshold: float = 0.3-- def run_iterative_bundle_adjustment(- self,- calibration_input_data: CalibrationInputData,-- ) -> float:- """- Performs iterative bundle adjustment to refine camera parameters.- based on Anipose's iterative bundle adjustment method. (`bundle_adjust_iter`)- """- original_calibration_input_data = deepcopy(calibration_input_data)- original_points2d = original_calibration_input_data.pixel_points2d-- # Validate input shapes- if not original_points2d.shape[0] == len(self.camera_calibration_estimates):- raise ValueError(- f"Invalid points shape, expected first dimension to be equal to "- f"number of cameras ({len(self.camera_calibration_estimates)}), but got shape {original_points2d.shape}"- )-- # Initialize- error_list = []-- # log original error before resampling- original_error = self.get_mean_reprojection_error(original_points2d, median=True)- logger.info(- f"Starting iterative bundle adjustment..."- f"\n\tNumber of cameras: {len(self.camera_calibration_estimates)}"- f"\n\tNumber of points: {original_points2d.shape[1]}"- f"\n\tOriginal error: {original_error:.2f}")-- # Resample initial set of points to prioritize shared views- resampled_calibration_input_data = resample_points_based_on_shared_views(- original_calibration_input_data,- number_of_samples_to_return=self.number_of_samples_full- )- initial_error = self.get_mean_reprojection_error(resampled_calibration_input_data.pixel_points2d, median=True)-- logger.debug("Initial error after resampling: ", initial_error)-- # Calculate dynamic error thresholds for each iteration- error_thresholds = np.exp(- np.linspace(np.log(self.starting_error_threshold), np.log(self.ending_error_threshold),- num=self.max_iterations))-- logger.debug(f"Error thresholds we will use for each bundle adjustment iteration: {error_thresholds}")-- # Iterative bundle adjustment- dynamic_error_threshold = self.starting_error_threshold- for iteration in range(self.max_iterations):- resampled_calibration_input_data = resample_points_based_on_shared_views(- original_calibration_input_data, number_of_samples_to_return=self.number_of_samples_full- )-- # Triangulate 3D points from resampled 2D points- triangulated_points3d = self.triangulate(resampled_calibration_input_data.pixel_points2d)-- # Calculate reprojection errors- errors_full = self.calculate_reprojection_error(- triangulated_points3d, resampled_calibration_input_data.pixel_points2d, mean=False- )- normalized_errors = self.calculate_reprojection_error(- triangulated_points3d, resampled_calibration_input_data.pixel_points2d, mean=True- )-- # Compute error statistics- error_dict = get_error_dict(errors_full)- max_error, min_error = calculate_error_bounds(error_dict)- dynamic_error_threshold = max(min(max_error, error_thresholds[iteration]), min_error)-- # Determine good points based on current threshold- good_points_mask = normalized_errors < dynamic_error_threshold- good_points_indicies = np.where(good_points_mask)[0]- # Update error list and check for convergence- current_error = np.median(normalized_errors)- error_list.append(current_error)- if current_error < self.error_threshold:- logger.debug(f"Converged after {iteration + 1} iterations")- break-- logger.debug(f"Bundle Adjust Iteration {iteration + 1} -"- f"\n\tError: {current_error:.2f}, "- f"\n\tThreshold: {dynamic_error_threshold:.1f}, "- f"\n\tProportion of points that meet this threshold: {np.mean(good_points_mask):.3f}")- logger.debug("Error scores from prior iterations", error_list)-- # Perform bundle adjustment- self.bundle_adjust_points2d(- resampled_calibration_input_data.resample_indicies(list(good_points_indicies)),- loss="linear",- function_tolerance=self.function_tolerance,- maximum_number_function_evals=self.max_number_function_evals,- )-- # Final adjustments and error calculation- final_calibration_input_data = resample_points_based_on_shared_views(- calibration_input_data=original_calibration_input_data,- number_of_samples_to_return=self.number_of_samples_full- )- self.final_adjustments(calibration_input_data=final_calibration_input_data,- error_threshold=dynamic_error_threshold- )-- final_error = self.get_mean_reprojection_error(final_calibration_input_data.pixel_points2d, median=True)- print("Final error: ", final_error)-- return float(final_error)-- @jit(parallel=True, forceobj=True)- def calculate_reprojection_error(self,- points_3d: np.ndarray,- points_2d: np.ndarray,- mean=False):- """Given an Nx3 array of 3D points and an CxNx2 array of 2D points,- where N is the number of points and C is the number of cameras,- this returns an CxNx2 array of errors.- Optionally mean=True, this averages the errors and returns array of length N of errors"""- if not points_3d.shape[0] == points_2d.shape[1]:- raise ValueError(- f"Invalid points shape, first dim of 3D points should be equal to"- f" number of points in 2D points ({points_2d.shape[1]}), but shape is {points_3d.shape}"- )- if not points_2d.shape[0] == len(self.camera_calibration_estimates):- raise ValueError(- f"Invalid points shape, first dim of 2D points should be equal to"- f" number of cameras ({len(self.camera_calibration_estimates)}), but shape is {points_2d.shape}"- )- if not points_3d.shape[1] == 3:- raise ValueError(- f"Invalid points shape, second dim of 3D points should be 3, but shape is {points_3d.shape}")-- if not points_2d.shape[2] == 2:- raise ValueError(- f"Invalid points shape, third dim of 2D points should be 2, but shape is {points_2d.shape}")-- one_point = False- if len(points_3d.shape) == 1 and len(points_2d.shape) == 2:- points_3d = points_3d.reshape(1, 3)- points_2d = points_2d.reshape(-1, 1, 2)- one_point = True-- n_cams, n_points, _ = points_2d.shape- if not points_3d.shape == (n_points, 3,):- raise ValueError("shapes of 2D and 3D points are not consistent: " "2D={}, 3D={}".format(points_2d.shape,- points_3d.shape))-- errors = np.empty((n_cams, n_points, 2))-- for camera_number, cam in enumerate(self.camera_calibration_estimates.values()):- errors[camera_number] = cam.single_camera_reprojection_error(points_3d, points_2d[camera_number])-- if mean:- errors_norm = np.linalg.norm(errors, axis=2)- good = ~np.isnan(errors_norm)- errors_norm[~good] = 0- denom = np.sum(good, axis=0).astype("float64")- denom[denom < 1.5] = np.nan- errors = np.sum(errors_norm, axis=0) / denom-- if one_point:- if mean:- errors = float(errors[0])- else:- errors = errors.reshape(-1, 2)-- return errors-- def project_3d_to_2d(self, points3d: np.ndarray):- """Given an Nx3 array of points, this returns an CxNx2 array of 2D points,- where C is the number of cameras"""- points3d = points3d.reshape(-1, 1, 3)- n_points = points3d.shape[0]- n_cams = len(self.camera_calibration_estimates)-- projected_points2d = np.empty((n_cams, n_points, 2), dtype="float64")- for camera_number, camera in enumerate(self.camera_calibration_estimates.values()):- projected_points2d[camera_number] = camera.project_3d_to_2d(points3d).reshape(n_points, 2)-- # check shape- assert projected_points2d.shape == (n_cams, n_points,- 2), f"Invalid projected_points2d shape, should be {n_cams, n_points, 2}, but shape is {projected_points2d.shape}"-- return projected_points2d-- def triangulate(self, points2d, undistort=True, progress=False):- """Given an CxNx2 array, this returns an Nx3 array of points,- where N is the number of points and C is the number of cameras"""-- assert points2d.shape[0] == len(- self.camera_calibration_estimates- ), "Invalid points shape, first dim should be equal to" " number of cameras ({}), but shape is {}".format(- len(self.camera_calibration_estimates), points2d.shape- )-- one_point = False- if len(points2d.shape) == 2:- points2d = points2d.reshape(-1, 1, 2)- one_point = True-- if undistort:- new_points = np.empty(points2d.shape)- for camera_number, camera in enumerate(self.camera_calibration_estimates.values()):- # must copy in order to satisfy opencv underneath- sub = np.copy(points2d[camera_number])- new_points[camera_number] = camera.undistort_points(sub)- points2d = new_points-- n_cams, n_points, _ = points2d.shape-- triangulated_points3d = np.empty((n_points, 3))- triangulated_points3d[:] = np.nan-- camera_matricies = np.array([camera.extrinsics_matrix for camera in self.camera_calibration_estimates.values()])-- if progress:- points_iterator = trange(n_points, ncols=70)- else:- points_iterator = range(n_points)-- for point_index in points_iterator:- point_xy = points2d[:, point_index, :]- point_xy_no_nans = ~np.isnan(point_xy[:, 0])- if np.sum(point_xy_no_nans) >= 2:- triangulated_points3d[point_index] = anipose_triangulate_simple(point_xy[point_xy_no_nans],- camera_matricies[point_xy_no_nans])-- if one_point:- triangulated_points3d = triangulated_points3d[0]-- return triangulated_points3d-- def final_adjustments(self,- calibration_input_data: CalibrationInputData,- error_threshold: float) -> None:- """Perform final adjustments and bundle adjustment with a potentially updated threshold. """- triangulated_points3d = self.triangulate(calibration_input_data.pixel_points2d)- errors_full = self.calculate_reprojection_error(- triangulated_points3d, calibration_input_data.pixel_points2d, mean=False- )- normalized_errors = self.calculate_reprojection_error(- triangulated_points3d, calibration_input_data.pixel_points2d, mean=True- )- error_dict = get_error_dict(errors_full)-- logger.debug("Error dictionary after final adjustments", error_dict)-- max_error, min_error = calculate_error_bounds(error_dict)- dynamic_error_threshold = max(max(max_error, error_threshold), min_error)- good_points_mask = normalized_errors < dynamic_error_threshold- good_points_indicies = np.where(good_points_mask)[0]- self.bundle_adjust_points2d(- calibration_input_data.resample_indicies(list(good_points_indicies)),- loss="linear",- function_tolerance=self.function_tolerance,- maximum_number_function_evals=self.max_number_function_evals,- )-- def bundle_adjust_points2d(- self,- calibration_input_data: CalibrationInputData,- loss: str = "linear",- threshold: float = 50.0,- function_tolerance: float = 1e-4,- maximum_number_function_evals: int = 1000,- weights: np.ndarray | None = None,- start_params: np.ndarray | None = None,-- ) -> float:- """Perform bundle adjustment to fine-tune camera parameters"""- points2d = calibration_input_data.pixel_points2d- # Validate input shapes- if not points2d.ndim == 3 and points2d.shape[2] == 2:- raise ValueError("points2d must be a CxNx2 array")- if not points2d.shape[0] == len(self.camera_calibration_estimates):- raise ValueError(- f"Invalid points shape, expected first dimension to be equal to "- f"number of cameras ({len(self.camera_calibration_estimates)}), but got shape {points2d.shape}"- )-- # Initialize parameters for bundle adjustment- initial_params, num_camera_params = self._initalize_bundle_adjust_parameters(calibration_input_data)-- # Override initial parameters if start_params are provided- if start_params is not None:- initial_params = start_params- num_camera_params = len(self.camera_calibration_estimates[0].get_optimizable_parameters())-- # Define error function and sparsity pattern for optimization-- jac_sparsity = self._calculate_bundle_adjustment_jacobian_sparsity(calibration_input_data, num_camera_params)-- # Set up optimization options- optimization_result = optimize.least_squares(- fun=self._bundle_adjust_error_function,- x0=initial_params,- jac_sparsity=jac_sparsity,- f_scale=threshold,- x_scale="jac",- loss=loss,- ftol=function_tolerance,- method="trf",- tr_solver="lsmr",- verbose=2,- max_nfev=maximum_number_function_evals,- args=(points2d, num_camera_params),- )-- # Update camera parameters with optimized results- optimized_params = optimization_result.x- for i, camera in enumerate(self.camera_calibration_estimates.values()):- start_idx = i * num_camera_params- end_idx = (i + 1) * num_camera_params- camera.set_optimized_parameters(optimized_params[start_idx:end_idx])-- # Calculate and return the mean reprojection error- mean_error = self.get_mean_reprojection_error(points2d)- return float(mean_error)-- @jit(parallel=True, forceobj=True)- def _bundle_adjust_error_function(self,- optimizable_parameters: np.ndarray,- calibration_input_data: CalibrationInputData,- number_of_camera_parameters: int,- ):- """Error function for bundle adjustment"""- points2d = calibration_input_data.pixel_points2d- good = ~np.isnan(points2d)- n_cams = len(self.camera_calibration_estimates)-- for i, cam in enumerate(self.camera_calibration_estimates.values()):- cam = self.camera_calibration_estimates[i]- a = i * number_of_camera_parameters- b = (i + 1) * number_of_camera_parameters- cam.set_optimized_parameters(optimizable_parameters[a:b])-- n_cams = len(self.camera_calibration_estimates)- sub = number_of_camera_parameters * n_cams- n3d = points2d.shape[1] * 3- p3ds_test = optimizable_parameters[sub: sub + n3d].reshape(-1, 3)- errors = self.calculate_reprojection_error(p3ds_test, points2d)- errors_reproj = errors[good]-- ids = remap_ids(calibration_input_data.ids)- object_points3d = calibration_input_data.object_points3d- min_scale = np.min(object_points3d[object_points3d > 0])- n_boards = int(np.max(ids)) + 1- a = sub + n3d- rotation_vectors = optimizable_parameters[a: a + n_boards * 3].reshape(-1, 3)- translation_vectors = optimizable_parameters[a + n_boards * 3: a + n_boards * 6].reshape(-1, 3)- expected = transform_points(object_points3d, rotation_vectors[ids], translation_vectors[ids])- errors_obj = 2 * (p3ds_test - expected).ravel() / min_scale-- return np.hstack([errors_reproj, errors_obj])-- def _calculate_bundle_adjustment_jacobian_sparsity(self,- calibration_input_data: CalibrationInputData,- number_of_camear_parameters: int) -> dok_matrix:- """Given an CxNx2 array of 2D points,- where N is the number of points and C is the number of cameras,- compute the sparsity structure of the jacobian for bundle adjustment"""- points2d = calibration_input_data.pixel_points2d- point_indices = np.zeros(points2d.shape, dtype="int32")- cam_indices = np.zeros(points2d.shape, dtype="int32")-- for i in range(points2d.shape[1]):- point_indices[:, i] = i-- for j in range(points2d.shape[0]):- cam_indices[j] = j-- good = ~np.isnan(points2d)-- ids = remap_ids(calibration_input_data.ids)- n_boards = int(np.max(ids)) + 1- total_board_params = n_boards * (3 + 3) # rotation_vectors + translation_vectors-- n_cams = points2d.shape[0]- n_points = points2d.shape[1]- total_params_reproj = n_cams * number_of_camear_parameters + n_points * 3- n_params = total_params_reproj + total_board_params-- n_good_values = np.sum(good)-- n_errors = n_good_values + n_points * 3-- A_sparse = dok_matrix((n_errors, n_params), dtype="int16")-- cam_indices_good = cam_indices[good]- point_indices_good = point_indices[good]-- # -- reprojection error --- ix = np.arange(n_good_values)-- ## update camera params based on point error- for i in range(number_of_camear_parameters):- A_sparse[ix, cam_indices_good * number_of_camear_parameters + i] = 1-- ## update point position based on point error- for i in range(3):- A_sparse[ix, n_cams * number_of_camear_parameters + point_indices_good * 3 + i] = 1-- # -- match for the object points---- point_ix = np.arange(n_points)-- ## update all the camera parameters- # A_sparse[n_good_values:n_good_values+n_points*3,- # 0:n_cams*n_cam_params] = 1-- ## update board rotation and translation based on error from expected- for i in range(3):- for j in range(3):- A_sparse[- n_good_values + point_ix * 3 + i,- total_params_reproj + ids * 3 + j,- ] = 1- A_sparse[- n_good_values + point_ix * 3 + i,- total_params_reproj + n_boards * 3 + ids * 3 + j,- ] = 1-- ## update point position based on error from expected- for i in range(3):- A_sparse[- n_good_values + point_ix * 3 + i,- n_cams * number_of_camear_parameters + point_ix * 3 + i,- ] = 1-- return A_sparse-- def _initalize_bundle_adjust_parameters(self, calibration_input_data:CalibrationInputData):- """Given an CxNx2 array of 2D points,- where N is the number of points and C is the number of cameras,- initializes the parameters for bundle adjustment"""-- cam_params = np.hstack([cam.get_optimizable_parameters() for cam in self.camera_calibration_estimates.values()])- n_cam_params = len(cam_params) // len(self.camera_calibration_estimates)-- total_cam_params = len(cam_params)-- n_cams, n_points, _ = calibration_input_data.pixel_points2d.shape- assert n_cams == len(self.camera_calibration_estimates), (- "number of cameras in CameraGroup does not " "match number of cameras in 2D points given"- )-- points3d = self.triangulate(calibration_input_data.pixel_points2d)-- ids = remap_ids(calibration_input_data.ids)- n_boards = int(np.max(ids[~np.isnan(ids)])) + 1- total_board_params = n_boards * (3 + 3) # rotation_vectors + translation_vectors-- # initialize to 0- rotation_vectors = np.zeros((n_boards, 3), dtype="float64")- translation_vectors = np.zeros((n_boards, 3), dtype="float64")--- rotation_vectors_all = calibration_input_data.rotation_vectors- translation_vectors_all = calibration_input_data.translation_vectors- for board_num in range(n_boards):- point_id = np.where(ids == board_num)[0][0]- cam_ids_possible = np.where(~np.isnan(calibration_input_data.pixel_points2d[:, point_id, 0]))[0]- cam_id = np.random.choice(cam_ids_possible)- camera_extrinsics_matrix = self.camera_calibration_estimates[cam_id].extrinsics_matrix- M_board_cam = construct_camera_extrinsics_matrix(rotation_vectors_all[cam_id, point_id],- translation_vectors_all[cam_id, point_id])- M_board = np.matmul(inverse(camera_extrinsics_matrix), M_board_cam)- rotation_vector, translation_vector = get_rotation_and_translation_vector_from_extrinsics_matrix(- M_board)- rotation_vectors[board_num] = rotation_vector- translation_vectors[board_num] = translation_vector-- x0 = np.zeros(total_cam_params + points3d.size + total_board_params)- x0[:total_cam_params] = cam_params- x0[total_cam_params: total_cam_params + points3d.size] = points3d.ravel()-- start_board = total_cam_params + points3d.size- x0[start_board: start_board + n_boards * 3] = rotation_vectors.ravel()- x0[start_board + n_boards * 3: start_board + n_boards * 6] = translation_vectors.ravel()-- return x0, n_cam_params-- def get_mean_reprojection_error(self, points2d, median=False):- triangulated_points3d = self.triangulate(points2d)- errors = self.calculate_reprojection_error(triangulated_points3d, points2d, mean=True)- if median:- return np.median(errors)- else:- return np.mean(errors)diff --git a/freemocap/old/core_processes/capture_volume_calibration/charuco_stuff/charuco_board_definition.py b/freemocap/old/core_processes/capture_volume_calibration/charuco_stuff/charuco_board_definition.pydeleted file mode 100644index 83f983b7..00000000--- a/freemocap/old/core_processes/capture_volume_calibration/charuco_stuff/charuco_board_definition.py+++ /dev/null@@ -1,24 +0,0 @@-from dataclasses import dataclass-from typing import Dict--import cv2---@dataclass-class CharucoBoardDefinition:- aruco_marker_dict: Dict = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_250)-- number_of_squares_width: int = 7- number_of_squares_height: int = 5- black_square_side_length: int = 1- aruco_marker_length_proportional: float = 0.8-- def __post_init__(self):- self.charuco_board = cv2.aruco.CharucoBoard(- size=[self.number_of_squares_width, self.number_of_squares_height],- squareLength=self.black_square_side_length,- markerLength=self.aruco_marker_length_proportional,- dictionary=self.aruco_marker_dict,- )-- self.number_of_charuco_corners = (self.number_of_squares_width - 1) * (self.number_of_squares_height - 1)diff --git a/freemocap/old/core_processes/capture_volume_calibration/run_anipose_capture_volume_calibration.py b/freemocap/old/core_processes/capture_volume_calibration/run_anipose_capture_volume_calibration.pydeleted file mode 100644index 742c599b..00000000--- a/freemocap/old/core_processes/capture_volume_calibration/run_anipose_capture_volume_calibration.py+++ /dev/null@@ -1,31 +0,0 @@-from pathlib import Path-from typing import Callable, Union--from freemocap.old.core_processes.capture_volume_calibration.anipose_camera_calibration.anipose_camera_calibrator import (- AniposeCameraCalibrator,-)-from freemocap.old.core_processes.capture_volume_calibration.charuco_stuff.charuco_board_definition import (- CharucoBoardDefinition,-)---async def async_run_anipose_capture_volume_calibration(**kwargs):- run_anipose_capture_volume_calibration(**kwargs)---def run_anipose_capture_volume_calibration(- charuco_board_definition: CharucoBoardDefinition,- charuco_square_size: float,- calibration_videos_folder_path: Union[str, Path],- pin_camera_0_to_origin: bool = True,- progress_callback: Callable[[str], None] = None,-) -> Path:- anipose_camera_calibrator = AniposeCameraCalibrator(- charuco_board_definition,- charuco_square_size=charuco_square_size,- calibration_videos_folder_path=calibration_videos_folder_path,- progress_callback=progress_callback,- )- toml_path = anipose_camera_calibrator.calibrate_camera_capture_volume(pin_camera_0_to_origin=pin_camera_0_to_origin)-- return toml_pathdiff --git a/freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/export_to_blender.py b/freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/export_to_blender.pydeleted file mode 100644index 56ad52a9..00000000--- a/freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/export_to_blender.py+++ /dev/null@@ -1,37 +0,0 @@-import logging-from pathlib import Path-from typing import Union--from freemocap.old.core_processes.export_data.blender_stuff.export_to_blender.methods.ajc_addon.run_ajc_addon_main import (- run_ajc_blender_addon_subprocess,-)-from freemocap.old.core_processes.export_data.blender_stuff.get_best_guess_of_blender_path import (- get_best_guess_of_blender_path,-)--logger = logging.getLogger(__name__)---def export_to_blender(- recording_folder_path: Union[str, Path],- blender_file_path: Union[str, Path],- blender_exe_path: Union[str, Path],- method: str = "ajc27_blender_addon",-):- logger.info(- f"Exporting session data to a Blender scene at: {str(blender_file_path)} using Blender executable at {str(blender_exe_path)}"- )-- if method == "ajc27_blender_addon":- run_ajc_blender_addon_subprocess(- recording_folder_path=recording_folder_path,- blender_file_path=blender_file_path,- blender_exe_path=blender_exe_path,- )-- logger.info("Done with Blender Export :D")---if __name__ == "__main__":- recording_path = r"D:\Dropbox\FreeMoCapProject\FreeMocap_Data\old\sesh_2022-09-19_16_16_50_in_class_jsm"- export_to_blender(recording_path, recording_path, get_best_guess_of_blender_path())diff --git a/freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/methods/ajc_addon/get_numpy_path.py b/freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/methods/ajc_addon/get_numpy_path.pydeleted file mode 100644index 19a4b475..00000000--- a/freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/methods/ajc_addon/get_numpy_path.py+++ /dev/null@@ -1,9 +0,0 @@-def get_numpy_path():- import numpy-- return numpy.__file__---if __name__ == "__main__":- numpy_path = get_numpy_path()- print(numpy_path)diff --git a/freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/methods/ajc_addon/install/bpy_install_addon.py b/freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/methods/ajc_addon/install/bpy_install_addon.pydeleted file mode 100644index e86311e8..00000000--- a/freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/methods/ajc_addon/install/bpy_install_addon.py+++ /dev/null@@ -1,78 +0,0 @@-import os-import shutil-import tempfile-from pathlib import Path-from typing import Union--INSTALL_ADDON_SCRIPT_PATH = __file__---def create_zip_from_folder(addon_folder_path: Union[Path, str]) -> str:- try:- addon_folder_path = Path(addon_folder_path)- if not addon_folder_path.is_dir():- raise FileNotFoundError(f"Addon folder path `{addon_folder_path}` does not exist!")- # if not addon_folder_path.joinpath("__init__.py").is_file():- # raise FileNotFoundError(f"Addon folder path `{addon_folder_path}` does not contain an `__init__.py` file!")-- with tempfile.TemporaryDirectory() as tmp_dir:- tmp_path = Path(tmp_dir) / addon_folder_path.name- shutil.copytree(addon_folder_path, tmp_path)- zip_path = addon_folder_path.parent / f"{addon_folder_path.name}.zip"- shutil.make_archive(base_name=str(zip_path.with_suffix("")), format="zip", root_dir=tmp_path.parent)-- if not Path(zip_path).is_file():- raise FileNotFoundError(f"Failed to create zip file at : {zip_path}")- except Exception as e:- print("Failed to create zip file at")- print(e)- raise e- return str(zip_path)---def bpy_install_addon(addon_root_directory: str):- """- This gets called as a subprocess to install the addon to blender- """- import bpy-- addon_root_directory = Path(addon_root_directory)-- addon_name = Path(addon_root_directory).name-- print(f"\n\nInstalling blender addon named `{addon_name}` from root directory: `{addon_root_directory}`\n\n")- zip_file_path = create_zip_from_folder(addon_folder_path=addon_root_directory)- print(f"Created zip file at `{zip_file_path}`\n\n")-- print("\n\nInstalling addon from zip file...\n\n")- bpy.ops.preferences.addon_install(overwrite=True, target="DEFAULT", filepath=zip_file_path)-- print("\n\nSaving user preferences...\n\n")- bpy.ops.wm.save_userpref()- # print(f"\n\nEnabling addon `{addon_name}`...\n\n")- # bpy.ops.preferences.addon_enable(module=f'{addon_name}')- #- # installed_addons = bpy.context.preferences.addons.keys()- # # Check if the addon name is in the list of installed addons- #- # if addon_name not in (bpy.context.preferences.addons.keys()):- # raise Exception(f"Failed to install `{addon_name}`!!")- # else:- # print("SUCCESSFULLY INSTALLED `{addon_name}`!!")-- # Remove the temporary zipfile- os.remove(zip_file_path)---if __name__ == "__main__":- print(f"Running {__file__} as a subprocess to install the addon...")- import sys-- # take in cli args split by --, so this is the first arg- argument_variables = sys.argv- argv = sys.argv[sys.argv.index("--") + 1:]- addon_root_directory = argv[0]- addon_name = argv[1]- if not Path(addon_root_directory).exists():- raise FileNotFoundError(f"Addon root directory `{addon_root_directory}` does not exist!")- bpy_install_addon(addon_root_directory=addon_root_directory)diff --git a/freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/methods/ajc_addon/install/install_ajc_addon.py b/freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/methods/ajc_addon/install/install_ajc_addon.pydeleted file mode 100644index 1fa225aa..00000000--- a/freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/methods/ajc_addon/install/install_ajc_addon.py+++ /dev/null@@ -1,50 +0,0 @@-import subprocess-from importlib.metadata import distribution-from pathlib import Path--from freemocap.old.core_processes.export_data.blender_stuff.export_to_blender.methods.ajc_addon.install.bpy_install_addon import (- INSTALL_ADDON_SCRIPT_PATH,-)--# from ajc27_freemocap_blender_addon.main import ajc27_run_as_main_function--FREEMOCAP_BLENDER_ADDON_PACKAGE_NAME = "ajc27_freemocap_blender_addon"---def get_package_path(package_name: str):- try:- package_dist = distribution(package_name)- package_path = package_dist.locate_file("")- return package_path- except Exception:- print(f"{package_name} not found.")- return None---def install_ajc_addon(blender_exe_path: str, ajc_addon_main_file_path: str):- addon_root_directory = Path(ajc_addon_main_file_path).parent- addon_name = Path(addon_root_directory).name-- # Define your addon's name and root directory- subprocess_command = [- blender_exe_path,- "--background",- "--python",- INSTALL_ADDON_SCRIPT_PATH,- "--",- addon_root_directory,- addon_name,- ]- # use CLI to install the addon passing in the addon name and zip file path- subprocess.run(subprocess_command)---if __name__ == "__main__":- # ajc_addon_main_file_path = inspect.getfile(ajc27_run_as_main_function)- #- # blender_path_in = get_best_guess_of_blender_path()- #- # install_ajc_addon(- # blender_exe_path=blender_path_in, ajc_addon_main_file_path=inspect.getfile(ajc27_run_as_main_function)- # )- print("Done!")diff --git a/freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/methods/ajc_addon/run_ajc_addon_main.py b/freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/methods/ajc_addon/run_ajc_addon_main.pydeleted file mode 100644index e2877452..00000000--- a/freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/methods/ajc_addon/run_ajc_addon_main.py+++ /dev/null@@ -1,196 +0,0 @@-import inspect-import logging-import subprocess-from pathlib import Path-from typing import Union, List--from freemocap.old.core_processes.export_data.blender_stuff.export_to_blender.methods.ajc_addon.get_numpy_path import (- get_numpy_path,-)-from freemocap.old.core_processes.export_data.blender_stuff.export_to_blender.methods.ajc_addon.install.install_ajc_addon import (- install_ajc_addon,-)-from freemocap.old.core_processes.export_data.blender_stuff.export_to_blender.methods.ajc_addon.run_simple import run_simple-from freemocap.system.paths_and_filenames.file_and_folder_names import (- OLD_TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME,- OLD_SEGMENT_CENTER_OF_MASS_NPY_FILE_NAME,- OLD_REPROJECTION_ERROR_NPY_FILE_NAME,- REPROJECTION_ERROR_NPY_FILE_NAME,- SEGMENT_CENTER_OF_MASS_NPY_FILE_NAME,- TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME,-)--logger = logging.getLogger(__name__)---def run_subprocess(command_list: List[str], append_to_python_path: List[str] = None):- 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---def run_ajc_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-- # ajc_addon_main_file_path = inspect.getfile(run_as_main_function)- ajc_addon_main_file_path = Path(__file__)#inspect.getfile(run_as_main_function)- logger.debug(f"Running ajc27_freemocap_blender_addon as a subprocess using script at : {ajc_addon_main_file_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_ajc_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-- simple_run_script = inspect.getfile(run_simple)-- command_list = [- str(blender_exe_path),- "--background",- "--python",- simple_run_script,- "--",- 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])-- 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 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- """- 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_3d_xyz.npy")).exists():- raise FileNotFoundError(- f"Could not find required file: {output_data_path / (active_tracker + 'right_hand_3d_xyz.npy')}"- )-- if not (output_data_path / (active_tracker + "left_hand_3d_xyz.npy")).exists():- raise FileNotFoundError(- f"Could not find required file: {output_data_path / (active_tracker + 'left_hand_3d_xyz.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 / "center_of_mass" / (active_tracker + TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME)).exists():- if (- active_tracker != "mediapipe_"- or not (output_data_path / "center_of_mass" / OLD_TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME).exists()- ):- raise FileNotFoundError(- f"Could not find required file: {output_data_path / 'center_of_mass' / (active_tracker + TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME)}"- )-- if not (output_data_path / "center_of_mass" / (active_tracker + SEGMENT_CENTER_OF_MASS_NPY_FILE_NAME)).exists():- if (- active_tracker != "mediapipe_"- or not (output_data_path / "center_of_mass" / 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.old.core_processes.export_data.blender_stuff.get_best_guess_of_blender_path import (- 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()-- run_ajc_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/old/core_processes/export_data/blender_stuff/export_to_blender/methods/ajc_addon/run_simple.py b/freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/methods/ajc_addon/run_simple.pydeleted file mode 100644index f546665d..00000000--- a/freemocap/old/core_processes/export_data/blender_stuff/export_to_blender/methods/ajc_addon/run_simple.py+++ /dev/null@@ -1,20 +0,0 @@-import sys---def run_simple(recording_path_input: str, blender_file_save_path_input: str):- from ajc27_freemocap_blender_addon.main import ajc27_run_as_main_function-- ajc27_run_as_main_function(recording_path=str(recording_path_input),- blend_file_path=str(blender_file_save_path_input))---if __name__ == "__main__":- print(f"\n\n\n\nRunning {__file__} as a subprocess to install the addon...\n\n\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, blender_file_save_path_input=blender_file_save_path_input)-- print("\n\n\nDone!\n\n\n")diff --git a/freemocap/old/core_processes/export_data/blender_stuff/get_best_guess_of_blender_path.py b/freemocap/old/core_processes/export_data/blender_stuff/get_best_guess_of_blender_path.pydeleted file mode 100644index e24002c7..00000000--- a/freemocap/old/core_processes/export_data/blender_stuff/get_best_guess_of_blender_path.py+++ /dev/null@@ -1,90 +0,0 @@-import logging-import platform-from pathlib import Path-from typing import Union, Optional--logger = logging.getLogger(__name__)---def guess_blender_exe_path_from_path(base_path: Union[str, Path]) -> Optional[Path]:- base_path = Path(base_path)- try:- blender_folder_paths = [path for path in base_path.rglob("blender.exe")]- except OSError:- logger.info(f"Unable to access: {str(base_path)}")- return-- if blender_folder_paths:-- if len(blender_folder_paths) == 0:- return None-- best_guess = blender_folder_paths[-1]-- return best_guess---def get_best_guess_of_blender_path():- if platform.system() == "Windows":- # check all lettered drives and the user's home directory- paths_to_check = [- Path(f"{letter}:/Program Files/Blender Foundation") for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"- ]-- paths_to_check.append(Path.home() / "Blender Foundation")-- for base_path in paths_to_check:- blender_exe_path = guess_blender_exe_path_from_path(base_path)- if blender_exe_path is not None and blender_exe_path.is_file():- logger.info(f"Found `blender.exe` at: {str(blender_exe_path)}")-- return str(blender_exe_path)- else:- logger.warning(- "Could not find `blender.exe` in the expected locations. Please locate it manually (or install Blender, if it isn't installed)."- )- return None-- if platform.system() == "Darwin":- blender_app_path = Path("/Applications/Blender.app")-- if blender_app_path.exists():- logger.info(f"Mac machine detected - guessing that `blender` is installed at: {str(blender_app_path)}")-- blender_exe_path = blender_app_path / "Contents/MacOS/Blender"- return str(blender_exe_path)- else:- logger.warning(- "Could not find Blender executable in the applications folder. Please locate it manually (or install Blender, if it isn't installed)."- )- return None-- if platform.system() == "Linux":- blender_path_list = [- Path("/usr/bin"),- Path("/usr/sbin"),- Path("/usr/local/bin"),- Path("/usr/local/sbin"),- Path("/bin"),- Path("/sbin"),- Path("/snap/bin"),- ]- for path in blender_path_list:- blender_path = path / "blender"- if blender_path.exists():- logger.info(f"Linux machine detected - guessing that `blender` is installed at: {str(blender_path)}")-- return str(blender_path)-- logger.info(- "Could not find Blender executable in bin. Please locate it manually (or install Blender, if it isn't installed)."- )- return None-- else:- logger.info("Machine system not detected, please locate Blender path manually.")- return None---if __name__ == "__main__":- print(f" blender path: {get_best_guess_of_blender_path()}")diff --git a/freemocap/old/core_processes/export_data/generate_jupyter_notebook/freemocap_template.ipynb b/freemocap/old/core_processes/export_data/generate_jupyter_notebook/freemocap_template.ipynbdeleted file mode 100644index e1d0be29..00000000--- a/freemocap/old/core_processes/export_data/generate_jupyter_notebook/freemocap_template.ipynb+++ /dev/null@@ -1,324 +0,0 @@-{- "cells": [- {- "attachments": {},- "cell_type": "markdown",- "metadata": {},- "source": [- "## Load necessary libraries\n",- "\n",- "First, we are importing libraries (also known as \"packages\") that we will use throughout this notebook. In this case, we are using pathlib, numpy, and plotly. If they are not installed, we will install them.\n",- "\n",- "Pathlib provides methods to handle file and directory paths, numpy allows us to handle arrays, and plotly is the graphing library we will use for visualization.\n",- "\n",- "If any of these libraries are not installed, we install them directly from this notebook."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "from pathlib import Path\n",- "\n",- "try:\n",- " import numpy as np\n",- "except Exception as e:\n",- " print(e)\n",- " %pip install numpy\n",- " import numpy as np\n",- "\n",- "\n",- "try:\n",- " from plotly.subplots import make_subplots\n",- " import plotly.graph_objects as go\n",- "except Exception as e:\n",- " print(e)\n",- " %pip install plotly\n",- " from plotly.subplots import make_subplots\n",- " import plotly.graph_objects as go\n",- " "- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {},- "source": [- "## Define variables\n",- "\n",- "Next, we're defining a few things we'll need to use later:\n",- "\n",- "- `path_to_recording`: This is a path to the folder where the mocap data for this recording is stored\n",- "- `joint_to_plot`: We need to tell the program which joint we want to visualize. By default, we select the 'nose'.\n",- "- `mediapipe_indices`: These are the possible joints that can be visualized.\n",- "\n",- "You can select a different joint from `mediapipe_indices` to view the plot for that - for example, you could replace `joint_to_plot = 'nose'` with `joint_to_plot = 'left_elbow'` to view the trajectory visualization for the left elbow. \n",- "\n",- "We're also getting the path to two types of data we need - 'center of mass' and '3D body data'. We will be loading and using these datasets later on."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "tags": [- "parameters"- ]- },- "outputs": [],- "source": [- "path_to_recording = None"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "#pick a joint from the mediapipe indices list to plot\n",- "joint_to_plot = 'nose'"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "\n",- "mediapipe_indices = ['nose',\n",- " 'left_eye_inner',\n",- " 'left_eye',\n",- " 'left_eye_outer',\n",- " 'right_eye_inner',\n",- " 'right_eye',\n",- " 'right_eye_outer',\n",- " 'left_ear',\n",- " 'right_ear',\n",- " 'mouth_left',\n",- " 'mouth_right',\n",- " 'left_shoulder',\n",- " 'right_shoulder',\n",- " 'left_elbow',\n",- " 'right_elbow',\n",- " 'left_wrist',\n",- " 'right_wrist',\n",- " 'left_pinky',\n",- " 'right_pinky',\n",- " 'left_index',\n",- " 'right_index',\n",- " 'left_thumb',\n",- " 'right_thumb',\n",- " 'left_hip',\n",- " 'right_hip',\n",- " 'left_knee',\n",- " 'right_knee',\n",- " 'left_ankle',\n",- " 'right_ankle',\n",- " 'left_heel',\n",- " 'right_heel',\n",- " 'left_foot_index',\n",- " 'right_foot_index']\n",- "\n",- "joint_to_plot_index = mediapipe_indices.index(joint_to_plot)"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "path_to_recording = Path(path_to_recording)\n",- "path_to_center_of_mass_npy = path_to_recording/'output_data'/'center_of_mass'/'total_body_center_of_mass_xyz.npy'\n",- "path_to_freemocap_3d_body_data_npy = path_to_recording/'output_data'/'mediapipe_body_3d_xyz.npy'\n",- "\n",- "freemocap_3d_body_data = np.load(path_to_freemocap_3d_body_data_npy)\n",- "total_body_com_data = np.load(path_to_center_of_mass_npy)\n",- "\n",- "freemocap_3d_body_data_to_plot = freemocap_3d_body_data[:,joint_to_plot_index,:]\n"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {},- "source": [- "## Plotting\n",- "\n",- "After loading our data, we are going to create some plots to better visualize it. Specifically, we are plotting the trajectory of the total body center of mass and the trajectory of the chosen joint (`nose` by default, but you can replace that and rerun this notebook to plot a different trajectory).\n",- "\n",- "The first three plots (in column 1) represent the X, Y, and Z trajectories of the total body center of mass. The next three plots (in column 2) represent the X, Y, and Z trajectories of the chosen joint.\n",- "\n",- "Note: The X, Y, and Z values refer to the three dimensions in space.\n",- "\n",- "You can click and drag on the plots below to interact with them and zoom into certain areas. When hovering over the plot, you can see additional options in the top right to pan, zoom, reset, and download the plots. "- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "\n",- "fig = make_subplots(rows=3, cols=2, subplot_titles=('total body center of mass trajectory',f'{joint_to_plot} trajectory'))\n",- "\n",- "fig.add_trace(\n",- " go.Scatter(y = total_body_com_data[:,0]),\n",- " row=1, col=1\n",- ")\n",- "\n",- "fig.add_trace(\n",- " go.Scatter(y = total_body_com_data[:,1]),\n",- " row=2, col=1\n",- ")\n",- "\n",- "fig.add_trace(\n",- " go.Scatter(y = total_body_com_data[:,2]),\n",- " row=3, col=1\n",- ")\n",- "\n",- "fig.add_trace(\n",- " go.Scatter(y = freemocap_3d_body_data_to_plot[:,0]),\n",- " row=1, col=2\n",- ")\n",- "\n",- "fig.add_trace(\n",- " go.Scatter(y = freemocap_3d_body_data_to_plot[:,1]),\n",- " row=2, col=2\n",- ")\n",- "\n",- "fig.add_trace(\n",- " go.Scatter(y = freemocap_3d_body_data_to_plot[:,2]),\n",- " row=3, col=2\n",- ")\n",- "\n",- "#COM plot axes labels \n",- "fig['layout']['yaxis']['title']='X Axis (mm)'\n",- "fig['layout']['yaxis3']['title']='Y Axis (mm)'\n",- "fig['layout']['yaxis5']['title']='Z Axis (mm)'\n",- "fig['layout']['xaxis5']['title']='Frame #'\n",- "fig['layout']['xaxis6']['title']='Frame #'\n",- "\n",- "\n",- "\n",- "\n",- "fig.update_layout(height=600, width=800,showlegend=False)\n",- "fig.show()\n"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {},- "source": [- "## 3D Plotting\n",- "\n",- "Finally, we are creating a 3D plot of the skeleton movement, tracking all the joints in the `mediapipe_indices` list over time. \n",- "\n",- "The 'Play' button at the bottom allows you to watch the motion as if it were a video. Before pressing play, you can manually click and drag the plot around to orient the view of the plot. "- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "\n",- "def calculate_axes_means(skeleton_3d_data):\n",- " mx_skel = np.nanmean(skeleton_3d_data[:,0:33,0])\n",- " my_skel = np.nanmean(skeleton_3d_data[:,0:33,1])\n",- " mz_skel = np.nanmean(skeleton_3d_data[:,0:33,2])\n",- "\n",- " return mx_skel, my_skel, mz_skel\n",- "\n",- "ax_range = 1500\n",- "\n",- "mx_skel, my_skel, mz_skel = calculate_axes_means(freemocap_3d_body_data)\n",- "\n",- "# Create a list of frames\n",- "frames = [go.Frame(data=[go.Scatter3d(\n",- " x=freemocap_3d_body_data[i, :, 0],\n",- " y=freemocap_3d_body_data[i, :, 1],\n",- " z=freemocap_3d_body_data[i, :, 2],\n",- " mode='markers',\n",- " marker=dict(\n",- " size=2, # Adjust marker size as needed\n",- " )\n",- ")], name=str(i)) for i in range(freemocap_3d_body_data.shape[0])]\n",- "\n",- "# Define axis properties\n",- "axis = dict(\n",- " showbackground=True,\n",- " backgroundcolor=\"rgb(230, 230,230)\",\n",- " gridcolor=\"rgb(255, 255, 255)\",\n",- " zerolinecolor=\"rgb(255, 255, 255)\",\n",- ")\n",- "\n",- "# Create a figure\n",- "fig = go.Figure(\n",- " data=[go.Scatter3d(\n",- " x=freemocap_3d_body_data[0, :, 0],\n",- " y=freemocap_3d_body_data[0, :, 1],\n",- " z=freemocap_3d_body_data[0, :, 2],\n",- " mode='markers',\n",- " marker=dict(\n",- " size=2, # Adjust marker size as needed\n",- " )\n",- " )],\n",- " layout=go.Layout(\n",- " scene=dict(\n",- " xaxis=dict(axis, range=[mx_skel-ax_range, mx_skel+ax_range]), # Adjust range as needed\n",- " yaxis=dict(axis, range=[my_skel-ax_range, my_skel+ax_range]), # Adjust range as needed\n",- " zaxis=dict(axis, range=[mz_skel-ax_range, mz_skel+ax_range]), # Adjust range as needed\n",- " aspectmode='cube'\n",- " ),\n",- " updatemenus=[dict(\n",- " type='buttons',\n",- " showactive=False,\n",- " buttons=[dict(\n",- " label='Play',\n",- " method='animate',\n",- " args=[None, {\"frame\": {\"duration\": 30}}]\n",- " )]\n",- " )]\n",- " ),\n",- " frames=frames\n",- ")\n",- "\n",- "fig.show()"- ]- }- ],- "metadata": {- "kernelspec": {- "display_name": "validation_req_test",- "language": "python",- "name": "python3"- },- "language_info": {- "codemirror_mode": {- "name": "ipython",- "version": 3- },- "file_extension": ".py",- "mimetype": "text/x-python",- "name": "python",- "nbconvert_exporter": "python",- "pygments_lexer": "ipython3",- "version": "3.9.16"- },- "orig_nbformat": 4- },- "nbformat": 4,- "nbformat_minor": 2-}diff --git a/freemocap/old/core_processes/export_data/generate_jupyter_notebook/generate_jupyter_notebook.py b/freemocap/old/core_processes/export_data/generate_jupyter_notebook/generate_jupyter_notebook.pydeleted file mode 100644index 5930edae..00000000--- a/freemocap/old/core_processes/export_data/generate_jupyter_notebook/generate_jupyter_notebook.py+++ /dev/null@@ -1,30 +0,0 @@-import json-import logging-from pathlib import Path-from typing import Union--from freemocap.utilities.download_sample_data import get_sample_data_path--logger = logging.getLogger(__name__)---def generate_jupyter_notebook(path_to_recording: Union[str, Path]):- path_to_recording = Path(path_to_recording)- recording_name = Path(path_to_recording).name- path_to_template_notebook = Path(__file__).parent / "freemocap_template.ipynb"- path_to_output_notebook = Path(path_to_recording) / f"{recording_name}.ipynb"-- with open(path_to_template_notebook, "r") as file:- template_notebook = json.load(file)-- template_notebook["cells"][3]["source"] = [f'path_to_recording = "{str(path_to_recording)}"']-- with open(path_to_output_notebook, "w") as file:- json.dump(template_notebook, file)---if __name__ == "__main__":- path_to_recording = get_sample_data_path()- # path_to_recording = r"PATH/TO/RECORDING/FOLDER" #specify path to a specific recording here (other wise it will just download sample data)-- generate_jupyter_notebook(path_to_recording)diff --git a/freemocap/old/core_processes/post_process_skeleton_data/calculate_center_of_mass.py b/freemocap/old/core_processes/post_process_skeleton_data/calculate_center_of_mass.pydeleted file mode 100644index 16209827..00000000--- a/freemocap/old/core_processes/post_process_skeleton_data/calculate_center_of_mass.py+++ /dev/null@@ -1,141 +0,0 @@-import logging-from typing import Dict, Tuple--import numpy as np--from freemocap.old.data_layer.skeleton_models.segments import SegmentAnthropometry-from freemocap.old.data_layer.skeleton_models.skeleton import Skeleton--logger = logging.getLogger(__name__)---def calculate_all_segments_com(- segment_positions: Dict[str, Dict[str, np.ndarray]], center_of_mass_definitions: Dict[str, SegmentAnthropometry]-) -> Dict[str, np.ndarray]:- """- Calculates the center of mass (COM) for each segment based on provided segment positions- and anthropometric data.-- Parameters:- - segment_positions: A dictionary where each key is a segment name, and the value is another- dictionary with 'proximal' and 'distal' keys containing the respective marker positions- as numpy arrays.- - center_of_mass_definitions: A dictionary containing anthropometric information for each segment.- Each key is a segment name with a value that is a dictionary, which includes the- 'segment_com_length' key representing the percentage distance from the proximal marker- to the segment's COM.-- Returns:- - A dictionary where each key is a segment name, and the value is the calculated COM- position as a numpy array.- """-- segment_com_data = {}-- for segment_name, segment_info in center_of_mass_definitions.items():- proximal = segment_positions[segment_name]["proximal"]- distal = segment_positions[segment_name]["distal"]-- com_length = segment_info.segment_com_length-- segment_com = proximal + (distal - proximal) * com_length-- segment_com_data[segment_name] = segment_com-- return segment_com_data---def calculate_total_body_center_of_mass(- segment_center_of_mass_data: Dict[str, np.ndarray],- center_of_mass_definitions: Dict[str, SegmentAnthropometry],- num_frames: int,-) -> np.ndarray:- """- Calculates the total body center of mass for each frame based on segment COM positions and anthropometric data.-- Parameters:- - segment_com_data: A dictionary with segment names as keys and COM positions as values for each frame.- - center_of_mass_definitions: A dictionary containing segment mass percentages.- - num_frames: The number of frames in the data.-- Returns:- - A numpy array containing the position of the total body center of mass for each frame.- """- total_body_com = np.zeros((num_frames, 3))-- for segment_name, segment_info in center_of_mass_definitions.items():-- segment_com = segment_center_of_mass_data.get(segment_name)- if segment_com is None:- raise ValueError(f"Segment {segment_name} not found in segment center of mass data.")-- segment_mass_percentage = segment_info.segment_com_percentage-- total_body_com += segment_com * segment_mass_percentage-- return total_body_com---def get_all_segment_markers(skeleton: Skeleton) -> Dict[str, Dict[str, np.ndarray]]:- """- Retrieves the proximal and distal marker positions for all segments within a skeleton.-- Parameters:- - skeleton: The Skeleton instance containing segment information and marker data.-- Returns:- - A dictionary where each key is a segment name, and the value is another dictionary- with 'proximal' and 'distal' keys containing the respective marker positions as numpy arrays.- """- segment_positions = {}-- if skeleton.segments is None:- raise ValueError("Segments must be defined before getting segment markers.")-- for segment_name in skeleton.segments.keys():- segment_positions[segment_name] = skeleton.get_segment_markers(segment_name)-- return segment_positions---def merge_segment_com_data(segment_com_data: Dict[str, np.ndarray]) -> np.ndarray:- """- Merges the center of mass data from multiple segments into a single array.-- Parameters:- - segment_com_data: A dictionary where each key is a segment name and the value is the center of mass data for that segment.-- Returns:- - A numpy array containing the merged center of mass data.- """- com_data_list = list(segment_com_data.values())-- return np.stack(com_data_list, axis=1)---def calculate_center_of_mass_from_skeleton(skeleton: Skeleton) -> Tuple[np.ndarray, np.ndarray]:- """- Calculates the segment and total body center of mass for a skeleton based on anthropometric data.-- Parameters:- - skeleton: The Skeleton instance containing marker data and segment information.- - anthropometric_data: A dictionary containing segment mass percentages-- Returns:- - A tuple containing the segment center of mass data and the total body center of mass.- """- if skeleton.center_of_mass_definitions is None:- raise ValueError("Segment center of mass definitions must be defined before calculating center of mass.")-- if skeleton.segments is None:- raise ValueError("Segments must be defined before calculating center of mass.")-- segment_3d_positions = get_all_segment_markers(skeleton) # TODO: Should this be a method of the skeleton model?- segment_com_data = calculate_all_segments_com(segment_3d_positions, skeleton.center_of_mass_definitions)- total_body_com = calculate_total_body_center_of_mass(- segment_com_data, skeleton.center_of_mass_definitions, skeleton.num_frames- )-- merged_segment_com_data = merge_segment_com_data(segment_com_data)-- return merged_segment_com_data, total_body_comdiff --git a/freemocap/old/core_processes/post_process_skeleton_data/create_skeleton.py b/freemocap/old/core_processes/post_process_skeleton_data/create_skeleton.pydeleted file mode 100644index 24a45469..00000000--- a/freemocap/old/core_processes/post_process_skeleton_data/create_skeleton.py+++ /dev/null@@ -1,66 +0,0 @@-from typing import List, Dict, Optional--from freemocap.old.data_layer.skeleton_models.marker_info import MarkerInfo-from freemocap.old.data_layer.skeleton_models.segments import Segment, SegmentAnthropometry-from freemocap.old.data_layer.skeleton_models.skeleton import Skeleton---def create_marker_info(- marker_list: List[str], virtual_markers: Optional[Dict[str, Dict[str, List]]] = None-) -> MarkerInfo:- """- Creates a MarkerInfo instance from a list of actual marker names and optional virtual markers.-- Parameters:- - marker_list: A list of strings representing the names of actual markers.- - virtual_markers: A dictionary defining virtual markers and their related data. Each key is a virtual marker name,- and its value is another dictionary with 'marker_names' and 'marker_weights' as keys.-- Returns:- - An instance of MarkerInfo populated with actual and, if provided, virtual markers.- """- marker_hub = MarkerInfo.create(marker_list=marker_list)-- if virtual_markers:- marker_hub.add_virtual_markers(virtual_markers)- return marker_hub---def create_skeleton_model(- actual_markers: List[str],- num_tracked_points: int,- segment_connections: Optional[Dict[str, Segment]] = None,- virtual_markers: Optional[Dict[str, Dict[str, List]]] = None,- joint_hierarchy: Optional[Dict[str, List[str]]] = None,- center_of_mass_info: Optional[Dict[str, SegmentAnthropometry]] = None,-) -> Skeleton:- """- Creates a Skeleton model that includes both actual and optionally virtual markers- Optionally integrates segment connections, joint hierarchy, and anthro data if needed- Parameters:- - actual_markers: A list of strings representing the names of actual markers.- - num_tracked_points: The number of tracked points expected in the 3D data.- - segment_connections: Optional; A dictionary where each key is a segment name and its value is a dictionary- with information about that segment (e.g., 'proximal', 'distal' marker names).- - virtual_markers: Optional; a dictionary with information necessary to compute virtual markers.- - joint_hierarchy: Optional; a dictionary with joint names as keys and lists of connected marker names as values.- - center_of_mass_info: Optional; a dictionary containing segment mass percentages-- Returns:- - An instance of the Skeleton class that represents the complete skeletal model including markers, segments,- and optionally, joint hierarchy data.- """- marker_hub = create_marker_info(marker_list=actual_markers, virtual_markers=virtual_markers)-- skeleton_model = Skeleton(markers=marker_hub, num_tracked_points=num_tracked_points)-- if segment_connections:- skeleton_model.add_segments(segment_connections)-- if joint_hierarchy:- skeleton_model.add_joint_hierarchy(joint_hierarchy)-- if center_of_mass_info:- skeleton_model.add_center_of_mass_definitions(center_of_mass_info)-- return skeleton_modeldiff --git a/freemocap/old/core_processes/post_process_skeleton_data/enforce_rigid_bones.py b/freemocap/old/core_processes/post_process_skeleton_data/enforce_rigid_bones.pydeleted file mode 100644index 090b89b2..00000000--- a/freemocap/old/core_processes/post_process_skeleton_data/enforce_rigid_bones.py+++ /dev/null@@ -1,150 +0,0 @@-from copy import deepcopy-from typing import Dict, List, Union--import numpy as np--from freemocap.old.data_layer.skeleton_models.segments import Segment-from freemocap.old.data_layer.skeleton_models.skeleton import Skeleton---def calculate_bone_lengths_and_statistics(- marker_data: Dict[str, np.ndarray], segment_connections: Dict[str, Segment]-) -> Dict[str, Dict[str, Union[np.ndarray, float]]]:- """- Calculates bone lengths for each frame and their statistics (median and standard deviation)- based on marker positions and segment connections.-- Parameters:- - marker_data: A dictionary containing marker trajectories with marker names as keys and- 3D positions as values (numpy arrays).- - segment_connections: A dictionary defining the segments (bones) with segment names as keys- and dictionaries with 'proximal' and 'distal' markers as values.-- Returns:- - A dictionary with segment names as keys and dictionaries with lengths, median lengths,- and standard deviations as values.- """- bone_statistics = {}-- for segment_name, segment in segment_connections.items():- proximal_positions = marker_data[segment.proximal]- distal_positions = marker_data[segment.distal]-- lengths = np.linalg.norm(distal_positions - proximal_positions, axis=1)- valid_lengths = lengths[~np.isnan(lengths)]-- median_length = np.median(valid_lengths)- stdev_length = np.std(valid_lengths)-- bone_statistics[segment_name] = {"lengths": lengths, "median": median_length, "stdev": stdev_length}-- return bone_statistics---def enforce_rigid_bones(- marker_data: Dict[str, np.ndarray],- segment_connections: Dict[str, Segment],- bone_lengths_and_statistics: Dict[str, Dict[str, Union[np.ndarray, float]]],- joint_hierarchy: Dict[str, List[str]],-) -> Dict[str, np.ndarray]:- """- Enforces rigid bones by adjusting the distal joints of each segment to match the median length.-- Parameters:- - marker_data: The original marker positions.- - segment_connections: Information about how segments (bones) are connected.- - bone_lengths_and_statistics: The desired bone lengths and statistics for each segment.- - joint_hierarchy: The hierarchy of joints, indicating parent-child relationships.-- Returns:- - A dictionary of adjusted marker positions.- """- rigid_marker_data = deepcopy(marker_data)-- for segment_name, stats in bone_lengths_and_statistics.items():- desired_length = stats["median"]- lengths = stats["lengths"]-- segment = segment_connections[segment_name]- proximal_marker, distal_marker = segment.proximal, segment.distal-- for frame_index, current_length in enumerate(lengths):- if current_length != desired_length:- proximal_position = marker_data[proximal_marker][frame_index]- distal_position = marker_data[distal_marker][frame_index]- direction = distal_position - proximal_position- try:- direction /= np.linalg.norm(direction) # Normalize to unit vector- except ZeroDivisionError:- direction /= 1e-5 # Set to a small value if the direction is zero- adjustment = (desired_length - current_length) * direction-- rigid_marker_data[distal_marker][frame_index] += adjustment-- adjust_children(distal_marker, frame_index, adjustment, rigid_marker_data, joint_hierarchy)-- return rigid_marker_data---def adjust_children(- parent_marker: str,- frame_index: int,- adjustment: np.ndarray,- marker_data: Dict[str, np.ndarray],- joint_hierarchy: Dict[str, List[str]],-):- """- Recursively adjusts the positions of child markers based on the adjustment of the parent marker.- """- if parent_marker in joint_hierarchy:- for child_marker in joint_hierarchy[parent_marker]:- marker_data[child_marker][frame_index] += adjustment- adjust_children(child_marker, frame_index, adjustment, marker_data, joint_hierarchy)---def merge_rigid_marker_data(rigid_marker_data: Dict[str, np.ndarray]) -> np.ndarray:- """- Merges the center of mass data from multiple segments into a single array.-- Parameters:- - segment_com_data: A dictionary where each key is a segment name and the value is the center of mass data for that segment.-- Returns:- - A numpy array containing the merged center of mass data.- """- # TODO: We could use this more broadly as a skeleton method-- rigid_marker_data_list = list(rigid_marker_data.values())-- return np.stack(rigid_marker_data_list, axis=1)---def enforce_rigid_bones_from_skeleton(skeleton: Skeleton) -> np.ndarray:- """- Calculates bone lengths and statistics from skeleton data and enforces rigid bones.-- Parameters:- - skeleton: The Skeleton instance containing segment information, joint hierarchy, and marker data.-- Returns:- - A numpy array of adjusted marker positions.- """- # TODO: Should this be a method of Skeleton?- if not skeleton.segments:- raise ValueError("Segments must be defined before rigid bones can be enforced.")-- if not skeleton.joint_hierarchy:- raise ValueError("Joint hierarchy must be defined before rigid bones can be enforced.")-- bone_lengths_and_statistcs = calculate_bone_lengths_and_statistics(- marker_data=skeleton.marker_data, segment_connections=skeleton.segments- )-- rigid_marker_data = enforce_rigid_bones(- marker_data=skeleton.marker_data,- segment_connections=skeleton.segments,- bone_lengths_and_statistics=bone_lengths_and_statistcs,- joint_hierarchy=skeleton.joint_hierarchy,- )-- return merge_rigid_marker_data(rigid_marker_data=rigid_marker_data)diff --git a/freemocap/old/core_processes/post_process_skeleton_data/post_process_skeleton.py b/freemocap/old/core_processes/post_process_skeleton_data/post_process_skeleton.pydeleted file mode 100644index 0e314aa5..00000000--- a/freemocap/old/core_processes/post_process_skeleton_data/post_process_skeleton.py+++ /dev/null@@ -1,136 +0,0 @@-import logging-import multiprocessing-from pathlib import Path-from typing import Union--import numpy as np-from skellyforge.freemocap_utils.config import default_settings-from skellyforge.freemocap_utils.constants import (- TASK_FILTERING,- PARAM_CUTOFF_FREQUENCY,- PARAM_SAMPLING_RATE,- PARAM_ORDER,- PARAM_ROTATE_DATA,- TASK_SKELETON_ROTATION,- TASK_INTERPOLATION,- TASK_FINDING_GOOD_FRAME,-)-from skellyforge.freemocap_utils.postprocessing_widgets.task_worker_thread import TaskWorkerThread-from skellytracker.trackers.base_tracker.model_info import ModelInfo--from freemocap.old.data_layer.recording_models.post_processing_parameter_models import ProcessingParameterModel-# 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--logger = logging.getLogger(__name__)---class PostProcessedDataHandler:- def __init__(self):- self.processed_skeleton = None-- def data_callback(self, processed_skeleton: np.ndarray):- self.processed_skeleton = processed_skeleton---def save_numpy_array_to_disk(array_to_save: np.ndarray, file_name: str, save_directory: Union[str, Path]):- if not file_name.endswith(".npy"):- file_name += ".npy"- Path(save_directory).mkdir(parents=True, exist_ok=True)- np.save(- str(Path(save_directory) / file_name),- array_to_save,- )---def get_settings_from_parameter_tree(recording_processing_parameter_model: ProcessingParameterModel):- rec = recording_processing_parameter_model-- filter_sampling_rate = rec.post_processing_parameters_model.framerate- filter_cutoff_frequency = rec.post_processing_parameters_model.butterworth_filter_parameters.cutoff_frequency- filter_order = rec.post_processing_parameters_model.butterworth_filter_parameters.order- run_butterworth_filter = rec.post_processing_parameters_model.run_butterworth_filter-- return filter_sampling_rate, filter_cutoff_frequency, filter_order, run_butterworth_filter---def adjust_default_settings(filter_sampling_rate, filter_cutoff_frequency, filter_order):- adjusted_settings = default_settings.copy()-- adjusted_settings[TASK_FILTERING][PARAM_CUTOFF_FREQUENCY] = filter_cutoff_frequency- adjusted_settings[TASK_FILTERING][PARAM_SAMPLING_RATE] = filter_sampling_rate- adjusted_settings[TASK_FILTERING][PARAM_ORDER] = filter_order- adjusted_settings[TASK_SKELETON_ROTATION][PARAM_ROTATE_DATA] = False-- return adjusted_settings---def run_post_processing_worker(- raw_skel3d_frame_marker_xyz: np.ndarray,- settings_dictionary: dict,- landmark_names: list,- run_butterworth_filter: bool,-) -> np.ndarray:- def handle_thread_finished(results, post_processed_data_handler: PostProcessedDataHandler):- # TODO: skellyforge should handle getting the final task results regardless of what was run- if hasattr(results, TASK_FILTERING) and results[TASK_FILTERING] is not None:- processed_skeleton = results[TASK_FILTERING]["result"]- else:- processed_skeleton = results[TASK_INTERPOLATION]["result"]- post_processed_data_handler.data_callback(processed_skeleton=processed_skeleton)-- task_list = [TASK_INTERPOLATION, TASK_FILTERING, TASK_FINDING_GOOD_FRAME, TASK_SKELETON_ROTATION]-- if not run_butterworth_filter:- task_list.remove(TASK_FILTERING)-- post_processed_data_handler = PostProcessedDataHandler()-- logger.info("Starting post-processing worker thread")- logger.info(LOG_VIEW_PROGRESS_BAR_STRING)-- worker_thread = TaskWorkerThread(- raw_skeleton_data=raw_skel3d_frame_marker_xyz,- task_list=task_list,- settings=settings_dictionary,- all_tasks_finished_callback=lambda results: handle_thread_finished(results, post_processed_data_handler),- landmark_names=landmark_names,- )- worker_thread.start()- worker_thread.join()- logger.info("Done with gap filling, filtering, and aligning")-- return post_processed_data_handler.processed_skeleton---def post_process_data(- recording_processing_parameter_model: ProcessingParameterModel,- raw_skel3d_frame_marker_xyz: np.ndarray,- queue: multiprocessing.Queue,-) -> np.ndarray:- # if queue:- # handler = DirectQueueHandler(queue)- # handler.setFormatter(logging.Formatter(fmt=log_view_logging_format_string, datefmt="%Y-%m-%dT%H:%M:%S"))- # logger.addHandler(handler)- filter_sampling_rate, filter_cutoff_frequency, filter_order, run_butterworth_filter = (- get_settings_from_parameter_tree(recording_processing_parameter_model)- )- adjusted_settings = adjust_default_settings(filter_sampling_rate, filter_cutoff_frequency, filter_order)- processed_skeleton_array = run_post_processing_worker(- raw_skel3d_frame_marker_xyz=raw_skel3d_frame_marker_xyz,- settings_dictionary=adjusted_settings,- landmark_names=get_landmark_names(model_info=recording_processing_parameter_model.tracking_model_info),- run_butterworth_filter=run_butterworth_filter,- )-- return processed_skeleton_array---def get_landmark_names(model_info: ModelInfo) -> list:- if hasattr(model_info, "body_landmark_names"):- return model_info.body_landmark_names- elif hasattr(model_info, "landmark_names"):- return model_info.landmark_names- else:- raise AttributeError("Model does not have landmark names")diff --git a/freemocap/old/core_processes/post_process_skeleton_data/process_single_camera_skeleton_data.py b/freemocap/old/core_processes/post_process_skeleton_data/process_single_camera_skeleton_data.pydeleted file mode 100644index 73f038a1..00000000--- a/freemocap/old/core_processes/post_process_skeleton_data/process_single_camera_skeleton_data.py+++ /dev/null@@ -1,43 +0,0 @@-import logging-from pathlib import Path-from typing import Tuple, Union--import numpy as np--from freemocap.old.core_processes.capture_volume_calibration.save_3d_data_to_npy import (- save_3d_data_to_npy,-)-from freemocap.utilities.geometry.project_3d_data_to_z_plane import project_3d_data_to_z_plane--logger = logging.getLogger(__name__)---def process_single_camera_skeleton_data(- input_image_data_frame_marker_xyz: np.ndarray,- raw_data_folder_path: Union[str, Path],- file_prefix: str = "",- project_to_z_plane: bool = True,-) -> Tuple[np.ndarray, np.ndarray]:- skeleton_reprojection_error_fr_mar = np.zeros(input_image_data_frame_marker_xyz.shape[0:2])- skeleton_reprojection_error_cam_fr_mar = np.zeros(- (1, input_image_data_frame_marker_xyz.shape[0], input_image_data_frame_marker_xyz.shape[1])- )- if project_to_z_plane:- logger.info("Altering image-derived 3d data to resemble multi-camera reconstructed data.")-- raw_skel3d_frame_marker_xyz = project_3d_data_to_z_plane(- skel3d_frame_marker_xyz=input_image_data_frame_marker_xyz- )- else:- raw_skel3d_frame_marker_xyz = input_image_data_frame_marker_xyz-- save_3d_data_to_npy(- data3d_numFrames_numTrackedPoints_XYZ=raw_skel3d_frame_marker_xyz,- data3d_numFrames_numTrackedPoints_reprojectionError=skeleton_reprojection_error_fr_mar,- data3d_numCams_numFrames_numTrackedPoints_reprojectionError=skeleton_reprojection_error_cam_fr_mar,- path_to_folder_where_data_will_be_saved=raw_data_folder_path,- processing_level="raw",- file_prefix=file_prefix,- )-- return raw_skel3d_frame_marker_xyz, skeleton_reprojection_error_fr_mardiff --git a/freemocap/old/core_processes/post_process_skeleton_data/split_and_save.py b/freemocap/old/core_processes/post_process_skeleton_data/split_and_save.pydeleted file mode 100644index 61653655..00000000--- a/freemocap/old/core_processes/post_process_skeleton_data/split_and_save.py+++ /dev/null@@ -1,207 +0,0 @@-import logging-from pathlib import Path-from typing import Dict, List--import numpy as np-import pandas as pd-from skellytracker.trackers.base_tracker.model_info import ModelInfo--from freemocap.system.paths_and_filenames.file_and_folder_names import (- BODY_3D_DATAFRAME_CSV_FILE_NAME,- FACE_3D_DATAFRAME_CSV_FILE_NAME,- LEFT_HAND_3D_DATAFRAME_CSV_FILE_NAME,- RIGHT_HAND_3D_DATAFRAME_CSV_FILE_NAME,-)--logger = logging.getLogger(__name__)---# TODO: This is dependent on the ordering we currently use for mediapipe, maybe it should live in model_info-category_info = {- "body": BODY_3D_DATAFRAME_CSV_FILE_NAME,- "right_hand": RIGHT_HAND_3D_DATAFRAME_CSV_FILE_NAME,- "left_hand": LEFT_HAND_3D_DATAFRAME_CSV_FILE_NAME,- "face": FACE_3D_DATAFRAME_CSV_FILE_NAME,-}--DEFAULT_CATEGORY_NAME = "body"--# TODO: come up with a sensible way of splitting this for different types of trackers---def split_data(- skeleton_3d_data: np.ndarray,- model_info: ModelInfo,-) -> Dict[str, np.ndarray]:- """- Splits the skeleton data into separate arrays for each data category using the provided model info.- Examples categories are body, left_hand, right_hand, and face.-- Parameters:- - skeleton: The skeleton data to be split.- - model_info: The model info used in tracking.-- Returns:- - A dictionary where each key is a category and the value is the corresponding data array.- """-- split_data = {}-- # TODO: this function probably shouldn't exist, and its existence implies we should be separately tracking body, hands, and face-- current_index = 0- for category in category_info.keys():- tracked_points_name = "num_tracked_points_" + category- if hasattr(model_info, tracked_points_name):- prev_index = current_index- current_index += getattr(model_info, tracked_points_name)- split_data[category] = skeleton_3d_data[:, prev_index:current_index, :]-- if split_data == {}:- logger.debug("No data categories found in model info, defaulting to single 'body' category")- split_data[DEFAULT_CATEGORY_NAME] = skeleton_3d_data-- return split_data---def create_column_names(model_info: ModelInfo) -> Dict[str, List[str]]:- """- Creates a list of column names for the skeleton data based on the model info.-- Parameters:- - model_info: The model info used in tracking.-- Returns:- - A list of column names for the skeleton data.- """-- column_names = {}- for category in category_info.keys():- tracked_points_name = "num_tracked_points_" + category- landmark_names = category + "_landmark_names"- if hasattr(model_info, tracked_points_name):- category_column_names = []- if hasattr(model_info, landmark_names) and len(getattr(model_info, landmark_names)) == getattr(- model_info, tracked_points_name- ):- for name in getattr(model_info, landmark_names):- category_column_names.append(f"{category}_{name}_x")- category_column_names.append(f"{category}_{name}_y")- category_column_names.append(f"{category}_{name}_z")- else:- for i in range(getattr(model_info, tracked_points_name)):- category_column_names.append(f"{category}_{str(i).zfill(4)}_x")- category_column_names.append(f"{category}_{str(i).zfill(4)}_y")- category_column_names.append(f"{category}_{str(i).zfill(4)}_z")-- column_names[category] = category_column_names-- # cover the case where no data categories are found- if column_names == {}:- landmark_names = "landmark_names"- tracked_points_name = "num_tracked_points"- category_column_names = []- if (- hasattr(model_info, landmark_names)- and hasattr(model_info, tracked_points_name)- and len(getattr(model_info, landmark_names)) == getattr(model_info, tracked_points_name)- ):- for name in getattr(model_info, landmark_names):- category_column_names.append(f"{category}_{name}_x")- category_column_names.append(f"{category}_{name}_y")- category_column_names.append(f"{category}_{name}_z")- else:- for i in range(getattr(model_info, tracked_points_name)):- category_column_names.append(f"{category}_{str(i).zfill(4)}_x")- category_column_names.append(f"{category}_{str(i).zfill(4)}_y")- category_column_names.append(f"{category}_{str(i).zfill(4)}_z")-- column_names[DEFAULT_CATEGORY_NAME] = category_column_names-- return column_names---def save_split_csv(- output_data_folder_path: str,- split_data: Dict[str, np.ndarray],- column_names: Dict[str, List[str]],- model_info: ModelInfo,-) -> None:- """- Saves the split skeleton data to CSV files using column names.-- Parameters:- - split_data: A dictionary where each key is a category and the value is the corresponding data array.- - column_names: A dictionary where each key is a category and the value is a list of column names for the data.- """- if split_data == {}:- logger.debug("No data categories found in model info, skipping saving split csv files")- return-- number_of_frames = next(iter(split_data.values())).shape[0]-- file_prefix = model_info.name + "_"-- for category, data in split_data.items():- column_name_list = column_names[category]- if len(split_data) == 1:- tracked_points_name = "num_tracked_points"- else:- tracked_points_name = "num_tracked_points_" + category-- data_flat = data.reshape(number_of_frames, getattr(model_info, tracked_points_name) * 3)- dataframe = pd.DataFrame(data_flat, columns=column_name_list)- dataframe.to_csv(str(Path(output_data_folder_path) / (file_prefix + category_info[category])), index=False)-- logger.info(f"Saved split skeleton data csvs to {output_data_folder_path}")---def save_split_npy(output_data_folder_path: str, split_data: Dict[str, np.ndarray], file_prefix: str = "") -> None:- """- Saves the split skeleton data to numpy files.-- Parameters:- - split_data: A dictionary where each key is a category and the value is the corresponding data array.- """-- if split_data == {}:- logger.debug("No data categories found in model info, skipping saving split npy files")- return-- if file_prefix != "" and file_prefix[-1] != "_":- file_prefix += "_"-- for category, data in split_data.items():- np.save(str(Path(output_data_folder_path) / (file_prefix + category + "_3d_xyz.npy")), data)-- logger.info(f"Saved split skeleton data npys to {output_data_folder_path}")---def split_and_save(- skeleton_3d_data: np.ndarray,- model_info: ModelInfo,- output_data_folder_path: str,-) -> None:- """- Splits the skeleton data into separate arrays for each data category using the provided model info.- Examples categories are body, left_hand, right_hand, and face.- Then saves the split skeleton data to CSV files using column names.- Then saves the split skeleton data to numpy files.-- Parameters:- - skeleton: The skeleton data to be split.- - model_info: The model info used in tracking.- - output_data_folder_path: The path to save the split skeleton data to.- """-- split_data_dict = split_data(skeleton_3d_data=skeleton_3d_data, model_info=model_info)- column_names = create_column_names(model_info=model_info)- save_split_csv(- output_data_folder_path=output_data_folder_path,- split_data=split_data_dict,- column_names=column_names,- model_info=model_info,- )- save_split_npy(- output_data_folder_path=output_data_folder_path, split_data=split_data_dict, file_prefix=model_info.name- )diff --git a/freemocap/old/core_processes/process_motion_capture_videos/process_recording_folder.py b/freemocap/old/core_processes/process_motion_capture_videos/process_recording_folder.pydeleted file mode 100644index 32382de6..00000000--- a/freemocap/old/core_processes/process_motion_capture_videos/process_recording_folder.py+++ /dev/null@@ -1,160 +0,0 @@-import logging-import multiprocessing-from typing import Optional--from freemocap.old.core_processes.post_process_skeleton_data.post_process_skeleton import post_process_data-from freemocap.old.core_processes.process_motion_capture_videos.processing_pipeline_functions.anatomical_data_pipeline_functions import (- calculate_anatomical_data,-)-from freemocap.old.core_processes.process_motion_capture_videos.processing_pipeline_functions.data_saving_pipeline_functions import (- save_data,-)-from freemocap.old.core_processes.process_motion_capture_videos.processing_pipeline_functions.image_tracking_pipeline_functions import (- run_image_tracking_pipeline,-)-from freemocap.old.core_processes.process_motion_capture_videos.processing_pipeline_functions.pipeline_check import (- processing_pipeline_check,-)-from freemocap.old.core_processes.process_motion_capture_videos.processing_pipeline_functions.triangulation_pipeline_functions import (- get_triangulated_data,-)-from freemocap.old.data_layer.data_saver.data_saver import DataSaver-from freemocap.old.data_layer.recording_models.post_processing_parameter_models import ProcessingParameterModel-# from freemocap.system.logging.queue_logger import DirectQueueHandler-# from freemocap.system.logging.configure_logging import log_view_logging_format_string-from freemocap.utilities.geometry.rotate_by_90_degrees_around_x_axis import rotate_by_90_degrees_around_x_axis-from freemocap.utilities.kill_event_exception import KillEventException--logger = logging.getLogger(__name__)---def process_recording_folder(- recording_processing_parameter_model: ProcessingParameterModel,- kill_event: multiprocessing.Event = None,- logging_queue: Optional[multiprocessing.Queue] = None,- use_tqdm: bool = True,-) -> None:- """-- Parameters- ----------- recording_processing_parameter_model : ProcessingParameterModel- ProcessingParameterModel object (contains all the paths and parameters necessary to process a session folder)-- kill_event : multiprocessing.Event- Event to kill the process-- logging_queue : multiprocessing.Queue- Queue to communicate logging between processes-- use_tqdm : bool- Whether or not to use tqdm to show progress bar in terminal-- """- # if logging_queue:- # handler = DirectQueueHandler(logging_queue)- # handler.setFormatter(logging.Formatter(fmt=log_view_logging_format_string, datefmt="%Y-%m-%dT%H:%M:%S"))- # logger.addHandler(handler)-- try:- processing_pipeline_check(processing_parameters=recording_processing_parameter_model)- except FileNotFoundError as e:- logger.error(- "processing parameters are not valid for recording status"- f" ::: {e}")- if logging_queue:- logging_queue.put(e)- raise e-- try:- image_data_numCams_numFrames_numTrackedPts_XYZ = run_image_tracking_pipeline(- processing_parameters=recording_processing_parameter_model,- kill_event=kill_event,- queue=logging_queue,- use_tqdm=use_tqdm,- )- except (RuntimeError, ValueError) as e:- logger.error("2D skeleton detection failed, cannot continue processing")- if logging_queue:- logging_queue.put(e)- raise e-- if kill_event is not None and kill_event.is_set():- exception = KillEventException("Process was killed")- if logging_queue:- logging_queue.put(exception)- raise exception-- try:- raw_skel3d_frame_marker_xyz = get_triangulated_data(- image_data_numCams_numFrames_numTrackedPts_XYZ=image_data_numCams_numFrames_numTrackedPts_XYZ,- processing_parameters=recording_processing_parameter_model,- kill_event=kill_event,- queue=logging_queue,- )- except (RuntimeError, FileNotFoundError, ValueError) as e:- logger.error("Triangulation failed, cannot continue processing")- if logging_queue:- logging_queue.put(e)- raise e-- if kill_event is not None and kill_event.is_set():- exception = KillEventException("Process was killed")- if logging_queue:- logging_queue.put(exception)- raise exception-- try:- # TODO: move the rotate by 90 function into skellyforge to skip duplication of responsibility- rotated_raw_skel3d_frame_marker_xyz = rotate_by_90_degrees_around_x_axis(raw_skel3d_frame_marker_xyz)- # TODO: find out if skellyforge does all the error handling we need - if not add it to post_process_data- skel3d_frame_marker_xyz = post_process_data(- recording_processing_parameter_model=recording_processing_parameter_model,- raw_skel3d_frame_marker_xyz=rotated_raw_skel3d_frame_marker_xyz,- queue=logging_queue,- )- except (RuntimeError, ValueError, AttributeError) as e:- logger.error("Post processing failed, cannot continue processing")- if logging_queue:- logging_queue.put(e)- raise e-- if kill_event is not None and kill_event.is_set():- exception = KillEventException("Process was killed")- if logging_queue:- logging_queue.put(exception)- raise exception-- try:- anatomical_data_dict = calculate_anatomical_data(- processing_parameters=recording_processing_parameter_model,- skel3d_frame_marker_xyz=skel3d_frame_marker_xyz,- queue=logging_queue,- )- except (RuntimeError, ValueError, TypeError, KeyError, AttributeError) as e:- logger.error("Anatomical data calculation failed, cannot continue processing")- if logging_queue:- logging_queue.put(e)- raise e-- if kill_event is not None and kill_event.is_set():- exception = KillEventException("Process was killed")- if logging_queue:- logging_queue.put(exception)- raise exception-- # TODO: deprecate save_data function in favor of DataSaver- save_data(- skel3d_frame_marker_xyz=skel3d_frame_marker_xyz,- segment_COM_frame_imgPoint_XYZ=anatomical_data_dict["segment_COM"],- totalBodyCOM_frame_XYZ=anatomical_data_dict["total_body_COM"],- rigid_bones_data=anatomical_data_dict["rigid_bones_data"],- processing_parameters=recording_processing_parameter_model,- queue=logging_queue,- )- DataSaver(- recording_folder_path=recording_processing_parameter_model.recording_info_model.path,- model_info=recording_processing_parameter_model.tracking_model_info,- ).save_all()-- logger.info(f"Done processing {recording_processing_parameter_model.recording_info_model.path}")diff --git a/freemocap/old/core_processes/process_motion_capture_videos/process_recording_headless.py b/freemocap/old/core_processes/process_motion_capture_videos/process_recording_headless.pydeleted file mode 100644index 4961d289..00000000--- a/freemocap/old/core_processes/process_motion_capture_videos/process_recording_headless.py+++ /dev/null@@ -1,103 +0,0 @@-import logging-from pathlib import Path-from typing import Optional, Union--from freemocap.old.core_processes.export_data.blender_stuff.export_to_blender.export_to_blender import export_to_blender-from freemocap.old.core_processes.export_data.blender_stuff.get_best_guess_of_blender_path import (- get_best_guess_of_blender_path,-)-from freemocap.old.core_processes.process_motion_capture_videos.process_recording_folder import process_recording_folder-from freemocap.old.data_layer.generate_jupyter_notebook.generate_jupyter_notebook import generate_jupyter_notebook-from freemocap.old.data_layer.recording_models.post_processing_parameter_models import ProcessingParameterModel-from freemocap.old.data_layer.recording_models.recording_info_model import RecordingInfoModel-from freemocap.system.paths_and_filenames.file_and_folder_names import RECORDING_PARAMETERS_JSON_FILE_NAME-from freemocap.system.paths_and_filenames.path_getters import get_blender_file_path-from freemocap.utilities.download_sample_data import get_sample_data_path-from freemocap.utilities.get_video_paths import get_video_paths-from freemocap.utilities.save_dictionary_to_json import save_dictionary_to_json--logger = logging.getLogger(__name__)---def process_recording_headless(- recording_path: Union[str, Path],- path_to_camera_calibration_toml: Optional[Union[str, Path]] = None,- path_to_blender_executable: Optional[Union[str, Path]] = None,- recording_processing_parameter_model: Optional[ProcessingParameterModel] = None,- recording_info_model: Optional[RecordingInfoModel] = None,- run_blender: bool = True,- make_jupyter_notebook: bool = True,- use_tqdm: bool = True,-):- if path_to_blender_executable is None:- path_to_blender_executable = get_best_guess_of_blender_path()- if recording_processing_parameter_model is None:- recording_processing_parameter_model = ProcessingParameterModel()- rec = recording_processing_parameter_model-- if recording_info_model is None:- rec.recording_info_model = RecordingInfoModel(recording_folder_path=Path(recording_path))- else:- rec.recording_info_model = recording_info_model-- logger.info(- f"Processing recording:\n"- f"Recording path: {recording_path}\n"- f"Camera calibration toml path: {path_to_camera_calibration_toml}\n"- f"Blender executable path: {path_to_blender_executable}\n"- f"Recording processing parameter model: {rec.model_dump()}"- )-- rec.recording_info_model = RecordingInfoModel(recording_folder_path=Path(recording_path))-- if path_to_camera_calibration_toml:- rec.recording_info_model.calibration_toml_path = Path(path_to_camera_calibration_toml)-- if rec.recording_info_model.calibration_toml_path is None:- number_of_videos = len(get_video_paths(rec.recording_info_model.synchronized_videos_folder_path))- if number_of_videos > 1:- raise ValueError(- f"There are {number_of_videos} videos. Must provide a calibration toml file for multicamera recordings."- )-- recording_info_dict = rec.dict(exclude={"recording_info_model"})-- Path(rec.recording_info_model.output_data_folder_path).mkdir(parents=True, exist_ok=True)-- save_dictionary_to_json(- save_path=rec.recording_info_model.output_data_folder_path,- file_name=RECORDING_PARAMETERS_JSON_FILE_NAME,- dictionary=recording_info_dict,- )-- logger.info("Starting core processing pipeline...")- process_recording_folder(recording_processing_parameter_model=rec, use_tqdm=use_tqdm)-- if make_jupyter_notebook:- logger.info("Generating jupyter notebook...")- generate_jupyter_notebook(path_to_recording=recording_path)-- if path_to_blender_executable and run_blender:- blender_file_path = get_blender_file_path(recording_folder_path=recording_path)- logger.info(f"Exporting to {blender_file_path}")- export_to_blender(- recording_folder_path=recording_path,- blender_file_path=blender_file_path,- blender_exe_path=Path(path_to_blender_executable),- )- elif not run_blender:- logger.info("Skipping blender export")- else:- logger.warning("No blender executable provided. Blender file will not be exported.")---def find_calibration_toml_path(recording_path: Union[str, Path]) -> Path:- for file in Path(recording_path).glob("*calibration.toml"):- return Path(file)---if __name__ == "__main__":- recording_path = Path("PATH/TO/RECORDING/FOLDER")- blender_path = Path("PATH/TO/BLENDER/EXECUTABLE")-- process_recording_headless(recording_path=get_sample_data_path())diff --git a/freemocap/old/core_processes/process_motion_capture_videos/processing_pipeline_functions/anatomical_data_pipeline_functions.py b/freemocap/old/core_processes/process_motion_capture_videos/processing_pipeline_functions/anatomical_data_pipeline_functions.pydeleted file mode 100644index f23a6cbe..00000000--- a/freemocap/old/core_processes/process_motion_capture_videos/processing_pipeline_functions/anatomical_data_pipeline_functions.py+++ /dev/null@@ -1,60 +0,0 @@-import logging-import multiprocessing-from typing import Dict, Union--import numpy as np--from freemocap.old.core_processes.post_process_skeleton_data.calculate_center_of_mass import (- calculate_center_of_mass_from_skeleton,-)-from freemocap.old.core_processes.post_process_skeleton_data.create_skeleton import create_skeleton_model-from freemocap.old.core_processes.post_process_skeleton_data.enforce_rigid_bones import enforce_rigid_bones_from_skeleton-from freemocap.old.data_layer.recording_models.post_processing_parameter_models import ProcessingParameterModel--# from freemocap.system.logging.queue_logger import DirectQueueHandler-# from freemocap.system.logging.configure_logging import log_view_logging_format_string--logger = logging.getLogger(__name__)---def calculate_anatomical_data(- processing_parameters: ProcessingParameterModel,- skel3d_frame_marker_xyz: np.ndarray,- queue: multiprocessing.Queue,-) -> Dict[str, Union[np.ndarray, None]]:- # if queue:- # handler = DirectQueueHandler(queue)- # handler.setFormatter(logging.Formatter(fmt=log_view_logging_format_string, datefmt="%Y-%m-%dT%H:%M:%S"))- # logger.addHandler(handler)-- logger.info("Creating skeleton model...")- skeleton = create_skeleton_model(- actual_markers=processing_parameters.tracking_model_info.landmark_names,- segment_connections=processing_parameters.tracking_model_info.segment_connections,- virtual_markers=processing_parameters.tracking_model_info.virtual_markers_definitions,- joint_hierarchy=processing_parameters.tracking_model_info.joint_hierarchy,- center_of_mass_info=processing_parameters.tracking_model_info.center_of_mass_definitions,- num_tracked_points=processing_parameters.tracking_model_info.num_tracked_points,- )-- skeleton.integrate_freemocap_3d_data(skel3d_frame_marker_xyz)-- logger.info("Calculating center of mass...")- try:- segment_COM_frame_imgPoint_XYZ, totalBodyCOM_frame_XYZ = calculate_center_of_mass_from_skeleton(- skeleton=skeleton- )- except ValueError:- logger.warning("Center of mass cannot be calculated for this tracking model")- segment_COM_frame_imgPoint_XYZ = totalBodyCOM_frame_XYZ = None- except AttributeError as e:- raise e-- logger.info("Enforcing rigid bones...")- rigid_bones_data = enforce_rigid_bones_from_skeleton(skeleton=skeleton)-- return {- "segment_COM": segment_COM_frame_imgPoint_XYZ,- "total_body_COM": totalBodyCOM_frame_XYZ,- "rigid_bones_data": rigid_bones_data,- }diff --git a/freemocap/old/core_processes/process_motion_capture_videos/processing_pipeline_functions/data_saving_pipeline_functions.py b/freemocap/old/core_processes/process_motion_capture_videos/processing_pipeline_functions/data_saving_pipeline_functions.pydeleted file mode 100644index 0b2d405a..00000000--- a/freemocap/old/core_processes/process_motion_capture_videos/processing_pipeline_functions/data_saving_pipeline_functions.py+++ /dev/null@@ -1,81 +0,0 @@-import logging-import multiprocessing-from pathlib import Path-from typing import Optional--import numpy as np--from freemocap.old.core_processes.post_process_skeleton_data.post_process_skeleton import save_numpy_array_to_disk-from freemocap.old.core_processes.post_process_skeleton_data.split_and_save import split_and_save-from freemocap.old.data_layer.recording_models.post_processing_parameter_models import ProcessingParameterModel-# from freemocap.system.logging.queue_logger import DirectQueueHandler-# from freemocap.system.logging.configure_logging import log_view_logging_format_string-from freemocap.system.paths_and_filenames.file_and_folder_names import (- CENTER_OF_MASS_FOLDER_NAME,- DATA_3D_NPY_FILE_NAME,- RIGID_BONES_NPY_FILE_NAME,- SEGMENT_CENTER_OF_MASS_NPY_FILE_NAME,- TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME,-)--logger = logging.getLogger(__name__)---def save_data(- skel3d_frame_marker_xyz: np.ndarray,- segment_COM_frame_imgPoint_XYZ: Optional[np.ndarray],- totalBodyCOM_frame_XYZ: Optional[np.ndarray],- rigid_bones_data: Optional[np.ndarray],- processing_parameters: ProcessingParameterModel,- queue: multiprocessing.Queue,-):- # if queue:- # handler = DirectQueueHandler(queue)- # handler.setFormatter(logging.Formatter(fmt=log_view_logging_format_string, datefmt="%Y-%m-%dT%H:%M:%S"))- # logger.addHandler(handler)-- path_to_folder_where_we_will_save_this_data = processing_parameters.recording_info_model.output_data_folder_path-- logger.info("Saving post-processed data")- save_numpy_array_to_disk(- array_to_save=skel3d_frame_marker_xyz,- file_name=f"{processing_parameters.tracking_model_info.name}_{DATA_3D_NPY_FILE_NAME}",- save_directory=Path(path_to_folder_where_we_will_save_this_data),- )-- if segment_COM_frame_imgPoint_XYZ is not None:- logger.info("Saving segment center of mass data")- save_numpy_array_to_disk(- array_to_save=segment_COM_frame_imgPoint_XYZ,- file_name=f"{processing_parameters.tracking_model_info.name}_{SEGMENT_CENTER_OF_MASS_NPY_FILE_NAME}",- save_directory=Path(path_to_folder_where_we_will_save_this_data) / CENTER_OF_MASS_FOLDER_NAME,- )- else:- logger.debug("segment_COM_frame_imgPoint_XYZ is None, could not save")-- if totalBodyCOM_frame_XYZ is not None:- logger.info("Saving total body center of mass data")- save_numpy_array_to_disk(- array_to_save=totalBodyCOM_frame_XYZ,- file_name=f"{processing_parameters.tracking_model_info.name}_{TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME}",- save_directory=Path(path_to_folder_where_we_will_save_this_data) / CENTER_OF_MASS_FOLDER_NAME,- )- else:- logger.debug("totalBodyCOM_frame_XYZ is None, could not save")-- if rigid_bones_data is not None:- logger.info("Saving rigid bones data")- save_numpy_array_to_disk(- array_to_save=rigid_bones_data,- file_name=f"{processing_parameters.tracking_model_info.name}_{RIGID_BONES_NPY_FILE_NAME}",- save_directory=path_to_folder_where_we_will_save_this_data,- )- else:- logger.debug("rigid_bones_data is None, could not save")-- logger.info("Splitting and saving data...")- split_and_save(- skeleton_3d_data=skel3d_frame_marker_xyz,- model_info=processing_parameters.tracking_model_info,- output_data_folder_path=processing_parameters.recording_info_model.output_data_folder_path,- )diff --git a/freemocap/old/core_processes/process_motion_capture_videos/processing_pipeline_functions/image_tracking_pipeline_functions.py b/freemocap/old/core_processes/process_motion_capture_videos/processing_pipeline_functions/image_tracking_pipeline_functions.pydeleted file mode 100644index e56dd36b..00000000--- a/freemocap/old/core_processes/process_motion_capture_videos/processing_pipeline_functions/image_tracking_pipeline_functions.py+++ /dev/null@@ -1,96 +0,0 @@-import logging-import multiprocessing-from pathlib import Path--import numpy as np-from skellytracker.process_folder_of_videos import process_folder_of_videos-from skellytracker.trackers.base_tracker.base_tracking_params import (- BaseTrackingParams,-)-from skellytracker.trackers.base_tracker.model_info import ModelInfo--from freemocap.old.data_layer.recording_models.post_processing_parameter_models import (- ProcessingParameterModel,-)-# 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.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,-) -> np.ndarray:- # if queue:- # handler = DirectQueueHandler(queue)- # handler.setFormatter(logging.Formatter(fmt=log_view_logging_format_string, datefmt="%Y-%m-%dT%H:%M:%S"))- # logger.addHandler(handler)-- if not processing_parameters.tracking_parameters_model.run_image_tracking:- logger.info(- f"Skipping 2d skeleton detection and loading data from: {processing_parameters.recording_info_model.data_2d_npy_file_path}"- )- try:- image_data_numCams_numFrames_numTrackedPts_XYZ = np.load(- processing_parameters.recording_info_model.data_2d_npy_file_path- )- except Exception as e:- logger.error(e)- raise RuntimeError("Failed to load 2D data, cannot continue processing") from e- else:- logger.info("Detecting 2d skeletons...")- logger.info(LOG_VIEW_PROGRESS_BAR_STRING)- # 2d skeleton detection- image_data_numCams_numFrames_numTrackedPts_XYZ = run_image_tracking(- model_info=processing_parameters.tracking_model_info,- tracking_params=processing_parameters.tracking_parameters_model,- synchronized_videos_folder_path=Path(- 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,- kill_event=kill_event,- use_tqdm=use_tqdm,- )-- # TODO: check that skellytracker saved out data correctly- try:- test_image_tracking_data_shape(- synchronized_video_folder_path=processing_parameters.recording_info_model.synchronized_videos_folder_path,- image_tracking_data=image_data_numCams_numFrames_numTrackedPts_XYZ,- )- except (ValueError, AssertionError) as e:- logger.error(e)- raise ValueError("image tracking data is not valid, cannot continue processing")-- return image_data_numCams_numFrames_numTrackedPts_XYZ---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,-):- if hasattr(tracking_params, "use_yolo_crop_method") and tracking_params.use_yolo_crop_method:- model_info.tracker_name = "YOLOMediapipeComboTracker"- # TODO: this shouldn't be handled here-- image_data_numCams_numFrames_numTrackedPts_XYZ = process_folder_of_videos(- model_info=model_info,- tracking_params=tracking_params,- synchronized_video_path=synchronized_videos_folder_path,- output_folder_path=output_data_folder_path,- annotated_video_path=None,- num_processes=tracking_params.num_processes,- )-- return image_data_numCams_numFrames_numTrackedPts_XYZdiff --git a/freemocap/old/core_processes/process_motion_capture_videos/processing_pipeline_functions/pipeline_check.py b/freemocap/old/core_processes/process_motion_capture_videos/processing_pipeline_functions/pipeline_check.pydeleted file mode 100644index e7b9e6b5..00000000--- a/freemocap/old/core_processes/process_motion_capture_videos/processing_pipeline_functions/pipeline_check.py+++ /dev/null@@ -1,46 +0,0 @@-from freemocap.old.data_layer.recording_models.post_processing_parameter_models import ProcessingParameterModel-from freemocap.old.data_layer.recording_models.recording_info_model import RecordingInfoModel---def processing_pipeline_check(processing_parameters: ProcessingParameterModel) -> None:- """- Performs checks on the processing parameters to make sure they are valid with the existing data before running the pipeline.- Raises FileNotFoundError if any of the checks fail.- """- status_check_dict = processing_parameters.recording_info_model.status_check- if not status_check_dict["synchronized_videos_status_check"]:- raise FileNotFoundError(- f"Could not find synchronized_videos folder at {processing_parameters.recording_info_model.synchronized_videos_folder_path}\n"- "::: Synchronized videos are required to run the processing pipeline"- )-- if not processing_parameters.tracking_parameters_model.run_image_tracking:- if not status_check_dict["data2d_status_check"]:- raise FileNotFoundError(- f"No 2d data found at: {processing_parameters.recording_info_model.data_2d_npy_file_path}\n"- "::: 2d data is required if you have turned off `Run 2d image tracking?` in the processing parameters"- )-- if not processing_parameters.anipose_triangulate_3d_parameters_model.run_3d_triangulation:- if not status_check_dict["data3d_status_check"] and not status_check_dict["single_video_check"]:- raise FileNotFoundError(- f"No 3d data found at: {processing_parameters.recording_info_model.data_3d_npy_file_path}\n"- "::: 3d data is required if you have selected `Run 3d triangulation?` in the processing parameters"- " and have more than 1 video in your synchronized videos folder"- )- else:- if not status_check_dict["calibration_toml_check"] and not status_check_dict["single_video_check"]:- raise FileNotFoundError(- f"No calibration file found at: {processing_parameters.recording_info_model.calibration_toml_path}\n"- ":::A calibration.toml file is required if you have selected `Run 3d triangulation?` in the processing parameters"- " and have more than 1 video in your synchronized videos folder"- )---if __name__ == "__main__":- recording_info_model = RecordingInfoModel(- recording_folder_path="/Users/philipqueen/freemocap_data/recording_sessions/freemocap_sample_data"- )- processing_parameters = ProcessingParameterModel(recording_info_model=recording_info_model)-- processing_pipeline_check(processing_parameters=processing_parameters)diff --git a/freemocap/old/core_processes/process_motion_capture_videos/processing_pipeline_functions/triangulation_pipeline_functions.py b/freemocap/old/core_processes/process_motion_capture_videos/processing_pipeline_functions/triangulation_pipeline_functions.pydeleted file mode 100644index 24fd26ac..00000000--- a/freemocap/old/core_processes/process_motion_capture_videos/processing_pipeline_functions/triangulation_pipeline_functions.py+++ /dev/null@@ -1,108 +0,0 @@-import logging-import multiprocessing-from pathlib import Path-from typing import Optional--import numpy as np--from freemocap.old.core_processes.capture_volume_calibration.anipose_camera_calibration.get_anipose_calibration_object import (- load_anipose_calibration_toml_from_path,-)-from freemocap.old.core_processes.capture_volume_calibration.by_camera_reprojection_filtering import (- run_reprojection_error_filtering,-)-from freemocap.old.core_processes.capture_volume_calibration.save_3d_data_to_npy import (- save_3d_data_to_npy,-)-from freemocap.old.core_processes.capture_volume_calibration.triangulate_3d_data import triangulate_3d_data-from freemocap.old.core_processes.post_process_skeleton_data.process_single_camera_skeleton_data import (- process_single_camera_skeleton_data,-)-from freemocap.old.data_layer.recording_models.post_processing_parameter_models import ProcessingParameterModel-# from freemocap.system.logging.queue_logger import DirectQueueHandler-# from freemocap.system.logging.configure_logging import log_view_logging_format_string-from freemocap.system.paths_and_filenames.file_and_folder_names import LOG_VIEW_PROGRESS_BAR_STRING--logger = logging.getLogger(__name__)---def get_triangulated_data(- image_data_numCams_numFrames_numTrackedPts_XYZ: np.ndarray,- processing_parameters: ProcessingParameterModel,- kill_event: Optional[multiprocessing.Event] = None,- queue: Optional[multiprocessing.Queue] = None,-) -> np.ndarray:- # if queue:- # handler = DirectQueueHandler(queue)- # handler.setFormatter(logging.Formatter(fmt=log_view_logging_format_string, datefmt="%Y-%m-%dT%H:%M:%S"))- # logger.addHandler(handler)-- if image_data_numCams_numFrames_numTrackedPts_XYZ.shape[0] == 1:- logger.info("Skipping 3d triangulation for single camera data")- logger.info(LOG_VIEW_PROGRESS_BAR_STRING)-- (skel3d_frame_marker_xyz, skeleton_reprojection_error_fr_mar) = process_single_camera_skeleton_data(- input_image_data_frame_marker_xyz=image_data_numCams_numFrames_numTrackedPts_XYZ[0],- raw_data_folder_path=Path(processing_parameters.recording_info_model.raw_data_folder_path),- file_prefix=processing_parameters.tracking_model_info.name,- project_to_z_plane=processing_parameters.anipose_triangulate_3d_parameters_model.flatten_single_camera_data,- )- elif not processing_parameters.anipose_triangulate_3d_parameters_model.run_3d_triangulation:- logger.info(- f"Skipping 3d triangulation and loading data from: {processing_parameters.recording_info_model.raw_data_3d_npy_file_path}"- )- logger.info(LOG_VIEW_PROGRESS_BAR_STRING)- try:- skel3d_frame_marker_xyz = np.load(- processing_parameters.recording_info_model.raw_data_3d_npy_file_path- )- skeleton_reprojection_error_fr_mar = np.load(- processing_parameters.recording_info_model.reprojection_error_data_npy_file_path- )- except Exception as e:- logger.error(e)- raise RuntimeError("Failed to load 3D data, cannot continue processing") from e- else:- logger.info("Triangulating 3d skeletons...")- logger.info(LOG_VIEW_PROGRESS_BAR_STRING)-- if not processing_parameters.recording_info_model.calibration_toml_check:- raise FileNotFoundError(- f"No calibration file found at: {processing_parameters.recording_info_model.calibration_toml_path}"- )-- anipose_calibration_object = load_anipose_calibration_toml_from_path(- camera_calibration_data_toml_path=processing_parameters.recording_info_model.calibration_toml_path,- save_copy_of_calibration_to_this_path=processing_parameters.recording_info_model.path,- )- (- skel3d_frame_marker_xyz,- skeleton_reprojection_error_fr_mar,- skeleton_reprojection_error_cam_fr_mar,- ) = triangulate_3d_data(- anipose_calibration_object=anipose_calibration_object,- image_2d_data=image_data_numCams_numFrames_numTrackedPts_XYZ[:, :, :, :2],- use_triangulate_ransac=processing_parameters.anipose_triangulate_3d_parameters_model.use_triangulate_ransac_method,- kill_event=kill_event,- )- save_3d_data_to_npy(- data3d_numFrames_numTrackedPoints_XYZ=skel3d_frame_marker_xyz,- data3d_numFrames_numTrackedPoints_reprojectionError=skeleton_reprojection_error_fr_mar,- data3d_numCams_numFrames_numTrackedPoints_reprojectionError=skeleton_reprojection_error_cam_fr_mar,- path_to_folder_where_data_will_be_saved=processing_parameters.recording_info_model.raw_data_folder_path,- processing_level="raw",- file_prefix=processing_parameters.tracking_model_info.name,- )-- if processing_parameters.anipose_triangulate_3d_parameters_model.run_reprojection_error_filtering:- logger.info("Filtering 3d triangulation...")- skel3d_frame_marker_xyz = run_reprojection_error_filtering(- image_data_numCams_numFrames_numTrackedPts_XYZ=image_data_numCams_numFrames_numTrackedPts_XYZ,- raw_skel3d_frame_marker_xyz=skel3d_frame_marker_xyz,- skeleton_reprojection_error_fr_mar=skeleton_reprojection_error_fr_mar,- skeleton_reprojection_error_cam_fr_mar=skeleton_reprojection_error_cam_fr_mar,- anipose_calibration_object=anipose_calibration_object,- processing_parameters=processing_parameters,- )-- return skel3d_frame_marker_xyzdiff --git a/freemocap/old/data_layer/data_saver/data_loader.py b/freemocap/old/data_layer/data_saver/data_loader.pydeleted file mode 100644index ab513906..00000000--- a/freemocap/old/data_layer/data_saver/data_loader.py+++ /dev/null@@ -1,252 +0,0 @@-import logging-from pathlib import Path-from typing import Union, Dict, Any--import numpy as np-import pandas as pd-from skellytracker.trackers.base_tracker.model_info import ModelInfo-from skellytracker.trackers.mediapipe_tracker.mediapipe_model_info import (- MediapipeModelInfo,-)--from freemocap.old.data_layer.data_saver.data_models import FrameData, Timestamps, Point, SkeletonSchema-from freemocap.system.paths_and_filenames.file_and_folder_names import (- BODY_3D_DATAFRAME_CSV_FILE_NAME,- CENTER_OF_MASS_FOLDER_NAME,- DATA_3D_NPY_FILE_NAME,- RIGHT_HAND_3D_DATAFRAME_CSV_FILE_NAME,- LEFT_HAND_3D_DATAFRAME_CSV_FILE_NAME,- FACE_3D_DATAFRAME_CSV_FILE_NAME,- SEGMENT_CENTER_OF_MASS_NPY_FILE_NAME,- TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME,-)-from freemocap.system.paths_and_filenames.path_getters import (- get_output_data_folder_path,- get_timestamps_directory,-)--logger = logging.getLogger(__name__)---# TODO: Need to generalize this beyond mediapipe, and make COM data optional-mediapipe_model_info = MediapipeModelInfo()---class DataLoader:- def __init__(- self,- recording_folder_path: Union[str, Path],- include_hands: bool = True,- include_face: bool = True,- include_com: bool = True,- model_info: ModelInfo = mediapipe_model_info,- ):- self._recording_folder_path = Path(recording_folder_path)- self.include_hands = include_hands- self.include_face = include_face- self.include_com = include_com- self._model_info = model_info-- self._recording_name = self._recording_folder_path.name- self._output_folder_path = Path(get_output_data_folder_path(self._recording_folder_path))- self.number_of_frames = None-- self._set_file_prefix()- self._load_data()-- def _load_data(self):- self._load_timestamps()- self._load_data_frames()- self._load_full_npy_data()- self._load_center_of_mass_data()- # self._load_segment_lengths()- # self._load_skeleton_schema()- self._validate_data()-- def _load_data_frames(self):- self.body_dataframe = self._load_dataframe(self._file_prefix + BODY_3D_DATAFRAME_CSV_FILE_NAME)- self.number_of_frames = len(self.body_dataframe)- if self.include_hands:- try:- self.right_hand_dataframe = self._load_dataframe(self._file_prefix + RIGHT_HAND_3D_DATAFRAME_CSV_FILE_NAME)- self.left_hand_dataframe = self._load_dataframe(self._file_prefix + LEFT_HAND_3D_DATAFRAME_CSV_FILE_NAME)- except FileNotFoundError:- logger.warning("Unable to load hand data from file.")- self.right_hand_dataframe = None- self.left_hand_dataframe = None- self.include_hands = False- if self.include_face:- try:- self.face_dataframe = self._load_dataframe(self._file_prefix + FACE_3D_DATAFRAME_CSV_FILE_NAME)- except FileNotFoundError:- logger.warning("Unable to load face data from file.")- self.face_dataframe = None- self.include_face = False-- def _load_dataframe(self, filename):- return pd.read_csv(self._output_folder_path / filename)-- def _validate_data(self):- self._validate_dataframe(self.right_hand_dataframe, "right hand")- self._validate_dataframe(self.left_hand_dataframe, "left hand")- self._validate_dataframe(self.face_dataframe, "face")- self._validate_numpy_array(self.center_of_mass_xyz, "center of mass")- self._validate_numpy_array(self.segment_center_of_mass_segment_xyz, "segment center of mass")-- def _validate_dataframe(self, df, df_name):- if df is not None and len(df) != self.number_of_frames:- raise ValueError(- f"The number of frames in the {df_name} dataframe ({len(df)}) is different from the expected number of frames ({self.number_of_frames})."- )-- def _validate_numpy_array(self, np_array, np_array_name):- if np_array is not None and np_array.shape[0] != self.number_of_frames:- print(f"\n\n {np_array.shape} \n\n")- raise ValueError(- f"The number of frames in the {np_array_name} data ({np_array.shape[0]}) is different from the expected number of frames ({self.number_of_frames})."- )-- def _load_timestamps(self):- timestamps_directory = get_timestamps_directory(recording_directory=self._recording_folder_path)- if timestamps_directory is None:- logger.warning("No timestamps directory found. Skipping timestamps loading.")- return-- timestamps_by_camera = {}- for timestamps_npy in Path(timestamps_directory).glob("*.npy"):- camera_name = timestamps_npy.stem- timestamps_by_camera[camera_name] = np.load(str(timestamps_npy))-- self._timestamps_by_camera = timestamps_by_camera- timestamps = [timestamps for timestamps in timestamps_by_camera.values()]- self._timestamps_mean_per_frame = np.nanmean(np.asarray(timestamps), axis=0)-- def _load_center_of_mass_data(self):- """- Load additional data like center of mass and segment lengths.- """- try:- self.center_of_mass_xyz = np.load(- self._output_folder_path / CENTER_OF_MASS_FOLDER_NAME / (self._file_prefix + TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME)- )- self.segment_center_of_mass_segment_xyz = np.load(- self._output_folder_path / CENTER_OF_MASS_FOLDER_NAME / (self._file_prefix + SEGMENT_CENTER_OF_MASS_NPY_FILE_NAME)- )- except FileNotFoundError:- logger.warning("Unable to load center of mass data from file.")- self.center_of_mass_xyz = None- self.segment_center_of_mass_segment_xyz = None- self.include_com = False-- def _load_full_npy_data(self):- self.data_frame_name_xyz = np.load(self._output_folder_path / (self._file_prefix + DATA_3D_NPY_FILE_NAME))-- if not self.number_of_frames:- self.number_of_frames = self.data_frame_name_xyz.shape[0]-- def load_frame_data(self, frame_number: int) -> FrameData:- return FrameData(- timestamps=self.get_timestamps(frame_number), tracked_points=self.get_tracked_points(frame_number)- )-- def get_timestamps(self, frame_number):- try:- return Timestamps(- mean=self._timestamps_mean_per_frame[frame_number],- by_camera={- camera_name: timestamps[frame_number]- for camera_name, timestamps in self._timestamps_by_camera.items()- },- )- except AttributeError:- return Timestamps(mean=None)-- def get_tracked_points(self, frame_number) -> Dict[str, Point]:- right_hand_points = {}- left_hand_points = {}- face_points = {}- center_of_mass_points = {}-- body_points = self._process_dataframe(self.body_dataframe.iloc[frame_number, :])-- if self.include_com:- center_of_mass_points = self._get_center_of_mass_data(frame_number)-- if self.include_hands:- left_hand_points, right_hand_points = self._load_hand_data(frame_number)-- if self.include_face:- face_points = self._process_dataframe(self.face_dataframe.iloc[frame_number, :])-- all_points = {}- all_points.update(body_points)- all_points.update(center_of_mass_points)- all_points.update(right_hand_points)- all_points.update(left_hand_points)- all_points.update(face_points)-- return all_points-- def _load_hand_data(self, frame_number: int):- right_hand_points = self._process_dataframe(self.right_hand_dataframe.iloc[frame_number, :])- left_hand_points = self._process_dataframe(self.left_hand_dataframe.iloc[frame_number, :])- return left_hand_points, right_hand_points-- def _get_center_of_mass_data(self, frame_number: int):- """- Calculate the center of mass for a given frame number.- """- com_data = {}- com_data["full_body_com"] = Point(- x=self.center_of_mass_xyz[frame_number, 0],- y=self.center_of_mass_xyz[frame_number, 1],- z=self.center_of_mass_xyz[frame_number, 2],- )-- if self._model_info.center_of_mass_definitions is None:- raise ValueError("center of mass definitions are not provided.")-- for segment_number, segment_name in enumerate(self._model_info.center_of_mass_definitions.keys()):- com_data[segment_name] = Point(- x=self.segment_center_of_mass_segment_xyz[frame_number, segment_number, 0],- y=self.segment_center_of_mass_segment_xyz[frame_number, segment_number, 1],- z=self.segment_center_of_mass_segment_xyz[frame_number, segment_number, 2],- )-- return com_data-- def _process_dataframe(self, data_frame) -> Dict[str, Any]:- """- Process a single row from a dataframe and add it to the recording_data_by_frame_number dictionary.-- Args:- data_frame (DataFrame): the dataframe to process.- """- tracked_points = {}- column_names = list(data_frame.index)- for column_name in column_names:- point_name = column_name[:-2] # e.g. "nose" or "left_knee" or whatever- dimension = column_name[-1] # e.g. "x" or "y" or "z"-- value = data_frame[column_name]- if pd.isna(value): # Check if value is NaN- value = None # Replace NaN with None which is valid in JSON-- tracked_points.setdefault(point_name, {})[dimension] = value-- return tracked_points-- def get_data_by_frame(self):- recording_data_by_frame_number = {}- for frame_number in range(self.number_of_frames):- recording_data_by_frame_number[frame_number] = self.load_frame_data(frame_number).to_dict()- return recording_data_by_frame_number-- def _load_skeleton_schema(self): # TODO: replace this with updated Skeleton class- self.skeleton_schema = SkeletonSchema(schema_dict=MediapipeModelInfo.skeleton_schema)-- def _set_file_prefix(self) -> None:- self._file_prefix = self._model_info.name-- if self._file_prefix[-1] != "_":- self._file_prefix += "_"diff --git a/freemocap/old/data_layer/data_saver/data_models.py b/freemocap/old/data_layer/data_saver/data_models.pydeleted file mode 100644index 21a6a688..00000000--- a/freemocap/old/data_layer/data_saver/data_models.py+++ /dev/null@@ -1,127 +0,0 @@-import pprint-from typing import List, Dict, Tuple-from typing import Optional, Any--from pydantic import BaseModel, Field, model_validator-from skellytracker.trackers.mediapipe_tracker.mediapipe_model_info import (- MediapipeModelInfo,-)---class Point(BaseModel):- """- A point in 3D space at a particular time- """-- x: Optional[float] = Field(None, description="The X-coordinate of the point")- y: Optional[float] = Field(None, description="The Y-coordinate of the point")- z: Optional[float] = Field(None, description="The Z-coordinate of the point")---class VirtualMarkerDefinition(BaseModel):- """- A virtual marker, defined by combining multiple markers with weights to generate a new marker/point- """-- marker_names: List[str] = Field(- default_factory=list, description="The names of the markers that define this virtual marker"- )- marker_weights: List[float] = Field(- default_factory=list, description="The weights of the markers that define this virtual marker, must sum to 1"- )-- @model_validator(mode="before")- def check_weights(cls, values):- marker_weights = values.get("marker_weights")- if sum(marker_weights) != 1:- raise ValueError(f"Marker weights must sum to 1, got {marker_weights}")- return values---class SegmentSchema(BaseModel):- """- A schema for a segment of a skeleton, defined by a set of tracked points and connections between them- """-- point_names: List[str] = Field(- default_factory=list, description="The names of the tracked points that define this segment"- )- virtual_marker_definitions: Optional[Dict[str, VirtualMarkerDefinition]] = Field(- default_factory=dict, description="The virtual markers that define this segment"- )- connections: List[Tuple[int, int]] = Field(- default_factory=list, description="The connections between the tracked points"- )- parent: Optional[str] = Field(None, description="The name of the parent of this segment")---class SkeletonSchema(BaseModel):- body: SegmentSchema = Field(default_factory=SegmentSchema, description="The tracked points that define the body")- hands: Dict[str, SegmentSchema] = Field(- default_factory=dict, description="The tracked points that define the hands: keys - (left, right)"- )- face: SegmentSchema = Field(default_factory=SegmentSchema, description="The tracked points that define the face")-- def __init__(self, schema_dict: Dict[str, Dict[str, Any]]):- super().__init__()- self.body = SegmentSchema(**schema_dict["body"])- self.hands = {hand: SegmentSchema(**hand_schema) for hand, hand_schema in schema_dict["hands"].items()}- self.face = SegmentSchema(**schema_dict["face"])-- def dict(self):- d = {}- d["body"] = self.body.dict()- d["hands"] = {hand: hand_schema.dict() for hand, hand_schema in self.hands.items()}- d["face"] = self.face.dict()- return d---class Timestamps(BaseModel):- # TODO - Add Unix time and ISO format stuff and whatnot- mean: Optional[float] = Field(None, description="The mean timestamp for this frame")- by_camera: Dict[str, Any] = Field(- default_factory=dict, description="Timestamps for each camera on this frame (key is video name)"- )---class FrameData(BaseModel):- """- The data for a single frame- """-- timestamps: Timestamps = Field(default_factory=Timestamps, description="Timestamp data")- tracked_points: Dict[str, Point] = Field(default_factory=dict, description="The points being tracked")-- @property- def tracked_point_names(self):- return list(self.tracked_points.keys())-- @property- def timestamp(self):- return self.timestamps.mean-- def to_dict(self):- d = {}- d["timestamps"] = self.timestamps.dict()- d["tracked_points"] = {name: point.dict() for name, point in self.tracked_points.items()}- return d---class InfoDict(BaseModel):- """- A dictionary of information about this recording, such as the measured segement lengths and the segment connections that we can use to interpret the tracked points (i.e./e.g. how to connect the dots of skeleton)- """-- # segment_lengths: Dict[str, Any] = Field(default_factory=dict, description="The lengths of the segments of the body")- schemas: Optional[Dict[str, Any]] = Field(default_factory=dict, description="The segment connections for the tracked points")---if __name__ == "__main__":- # nested_dict = create_nested_dict(FramePacket)- # print(json.dumps(nested_dict, indent=4))-- print("=====================================\n\n===============================")-- skeleton_schema = SkeletonSchema(schema_dict=MediapipeModelInfo.skeleton_schema)-- pprint.pp(skeleton_schema.dict())diff --git a/freemocap/old/data_layer/data_saver/data_saver.py b/freemocap/old/data_layer/data_saver/data_saver.pydeleted file mode 100644index f934ec8a..00000000--- a/freemocap/old/data_layer/data_saver/data_saver.py+++ /dev/null@@ -1,127 +0,0 @@-import json-import logging-from pathlib import Path-from typing import Union--import numpy as np-import pandas as pd-from skellytracker.trackers.base_tracker.model_info import ModelInfo-from skellytracker.trackers.mediapipe_tracker.mediapipe_model_info import (- MediapipeModelInfo,-)--from freemocap.old.data_layer.data_saver.data_loader import DataLoader-from freemocap.old.data_layer.data_saver.data_models import InfoDict--logger = logging.getLogger(__name__)--from typing import Any, Dict--mediapipe_model_info = MediapipeModelInfo()---class DataSaver:- def __init__(- self,- recording_folder_path: Union[Path, str],- include_hands: bool = True,- include_face: bool = True,- model_info: ModelInfo = mediapipe_model_info,- ):- """- Initialize DataFrameManager with the given recording_folder_path.-- Args:- recording_folder_path (Union[Path, str]): path to the folder containing the recording data.- include_hands (bool): flag to include hands data in the processing.- include_face (bool): flag to include face data in the processing.- """- self.recording_folder_path = Path(recording_folder_path)- self._recording_name = self.recording_folder_path.name-- self._data_loader = DataLoader(- recording_folder_path=self.recording_folder_path,- include_hands=include_hands,- include_face=include_face,- model_info=model_info,- )-- self.recording_data_by_frame = None- self.number_of_frames = None-- def save_all(self):- """- Load all data, validate it, and create the recording_data_by_frame_number dictionary.-- Returns:- Dict[int, Dict]: a dictionary containing the processed data, indexed by frame number.- """-- self.recording_data_by_frame = self._data_loader.get_data_by_frame()-- self.save_to_json()- self.save_to_csv()- self.save_to_npy()-- def save_to_json(self, save_path: Union[str, Path] = None):- dict_to_save = {}- dict_to_save["info"] = self._get_info_dict().model_dump()- dict_to_save["data_by_frame"] = self.recording_data_by_frame-- if save_path is None:- save_path = Path(self.recording_folder_path) / f"{self._recording_name}_by_frame.json"-- logger.info(f"Saving recording data to {save_path}")-- save_path.write_text(json.dumps(dict_to_save, indent=4), encoding="utf-8")-- def save_to_csv(self, save_path: Union[str, Path] = None):- data_for_dataframe = []-- for frame_data in self.recording_data_by_frame.values():- data_for_dataframe.append(self._generate_frame_data_row(frame_data))-- # Create DataFrame and save to csv- df = pd.DataFrame(data_for_dataframe)-- if save_path is None:- save_path = self.recording_folder_path / f"{self._recording_name}_by_trajectory.csv"-- df.to_csv(save_path, index=False)- logger.info(f"Saved recording data to {save_path}")-- def save_to_npy(self, save_path: Union[str, Path] = None):- if save_path is None:- save_path = self.recording_folder_path / f"{self._recording_name}_frame_name_xyz.npy"- np.save(save_path, self._data_loader.data_frame_name_xyz)- logger.info(f"Saved recording data to {save_path}")-- def _generate_frame_data_row(self, frame_data: Dict[str, Any]) -> Dict:- """- Generate a data row for a given frame number.- """- frame_data_row = {}-- frame_data_row["timestamp"] = frame_data["timestamps"]["mean"]- frame_data_row["timestamp_by_camera"] = str(frame_data["timestamps"]["by_camera"])-- for key, tracked_point in frame_data["tracked_points"].items():- frame_data_row[f"{key}_x"] = tracked_point["x"]- frame_data_row[f"{key}_y"] = tracked_point["y"]- frame_data_row[f"{key}_z"] = tracked_point["z"]-- return frame_data_row-- def _get_info_dict(self):- return InfoDict(- # segment_lengths=self._data_loader.segment_lengths,- schemas=self._data_loader._model_info.segment_connections,- )---if __name__ == "__main__":- # recording_data_saver = DataSaver(recording_folder_path=get_sample_data_path())- recording_data_saver = DataSaver(- recording_folder_path=r"C:\Users\jonma\freemocap_data\recording_sessions\session_2023-04-14_15_29_45\recording_15_47_37_gmt-4"- )- recording_data_by_frame_number = recording_data_saver.save_all()diff --git a/freemocap/old/data_layer/generate_jupyter_notebook/__init__.py b/freemocap/old/data_layer/generate_jupyter_notebook/__init__.pydeleted file mode 100644index e69de29b..00000000diff --git a/freemocap/old/data_layer/generate_jupyter_notebook/freemocap_template.ipynb b/freemocap/old/data_layer/generate_jupyter_notebook/freemocap_template.ipynbdeleted file mode 100644index e1d0be29..00000000--- a/freemocap/old/data_layer/generate_jupyter_notebook/freemocap_template.ipynb+++ /dev/null@@ -1,324 +0,0 @@-{- "cells": [- {- "attachments": {},- "cell_type": "markdown",- "metadata": {},- "source": [- "## Load necessary libraries\n",- "\n",- "First, we are importing libraries (also known as \"packages\") that we will use throughout this notebook. In this case, we are using pathlib, numpy, and plotly. If they are not installed, we will install them.\n",- "\n",- "Pathlib provides methods to handle file and directory paths, numpy allows us to handle arrays, and plotly is the graphing library we will use for visualization.\n",- "\n",- "If any of these libraries are not installed, we install them directly from this notebook."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "from pathlib import Path\n",- "\n",- "try:\n",- " import numpy as np\n",- "except Exception as e:\n",- " print(e)\n",- " %pip install numpy\n",- " import numpy as np\n",- "\n",- "\n",- "try:\n",- " from plotly.subplots import make_subplots\n",- " import plotly.graph_objects as go\n",- "except Exception as e:\n",- " print(e)\n",- " %pip install plotly\n",- " from plotly.subplots import make_subplots\n",- " import plotly.graph_objects as go\n",- " "- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {},- "source": [- "## Define variables\n",- "\n",- "Next, we're defining a few things we'll need to use later:\n",- "\n",- "- `path_to_recording`: This is a path to the folder where the mocap data for this recording is stored\n",- "- `joint_to_plot`: We need to tell the program which joint we want to visualize. By default, we select the 'nose'.\n",- "- `mediapipe_indices`: These are the possible joints that can be visualized.\n",- "\n",- "You can select a different joint from `mediapipe_indices` to view the plot for that - for example, you could replace `joint_to_plot = 'nose'` with `joint_to_plot = 'left_elbow'` to view the trajectory visualization for the left elbow. \n",- "\n",- "We're also getting the path to two types of data we need - 'center of mass' and '3D body data'. We will be loading and using these datasets later on."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "tags": [- "parameters"- ]- },- "outputs": [],- "source": [- "path_to_recording = None"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "#pick a joint from the mediapipe indices list to plot\n",- "joint_to_plot = 'nose'"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "\n",- "mediapipe_indices = ['nose',\n",- " 'left_eye_inner',\n",- " 'left_eye',\n",- " 'left_eye_outer',\n",- " 'right_eye_inner',\n",- " 'right_eye',\n",- " 'right_eye_outer',\n",- " 'left_ear',\n",- " 'right_ear',\n",- " 'mouth_left',\n",- " 'mouth_right',\n",- " 'left_shoulder',\n",- " 'right_shoulder',\n",- " 'left_elbow',\n",- " 'right_elbow',\n",- " 'left_wrist',\n",- " 'right_wrist',\n",- " 'left_pinky',\n",- " 'right_pinky',\n",- " 'left_index',\n",- " 'right_index',\n",- " 'left_thumb',\n",- " 'right_thumb',\n",- " 'left_hip',\n",- " 'right_hip',\n",- " 'left_knee',\n",- " 'right_knee',\n",- " 'left_ankle',\n",- " 'right_ankle',\n",- " 'left_heel',\n",- " 'right_heel',\n",- " 'left_foot_index',\n",- " 'right_foot_index']\n",- "\n",- "joint_to_plot_index = mediapipe_indices.index(joint_to_plot)"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "tags": []- },- "outputs": [],- "source": [- "path_to_recording = Path(path_to_recording)\n",- "path_to_center_of_mass_npy = path_to_recording/'output_data'/'center_of_mass'/'total_body_center_of_mass_xyz.npy'\n",- "path_to_freemocap_3d_body_data_npy = path_to_recording/'output_data'/'mediapipe_body_3d_xyz.npy'\n",- "\n",- "freemocap_3d_body_data = np.load(path_to_freemocap_3d_body_data_npy)\n",- "total_body_com_data = np.load(path_to_center_of_mass_npy)\n",- "\n",- "freemocap_3d_body_data_to_plot = freemocap_3d_body_data[:,joint_to_plot_index,:]\n"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {},- "source": [- "## Plotting\n",- "\n",- "After loading our data, we are going to create some plots to better visualize it. Specifically, we are plotting the trajectory of the total body center of mass and the trajectory of the chosen joint (`nose` by default, but you can replace that and rerun this notebook to plot a different trajectory).\n",- "\n",- "The first three plots (in column 1) represent the X, Y, and Z trajectories of the total body center of mass. The next three plots (in column 2) represent the X, Y, and Z trajectories of the chosen joint.\n",- "\n",- "Note: The X, Y, and Z values refer to the three dimensions in space.\n",- "\n",- "You can click and drag on the plots below to interact with them and zoom into certain areas. When hovering over the plot, you can see additional options in the top right to pan, zoom, reset, and download the plots. "- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "\n",- "fig = make_subplots(rows=3, cols=2, subplot_titles=('total body center of mass trajectory',f'{joint_to_plot} trajectory'))\n",- "\n",- "fig.add_trace(\n",- " go.Scatter(y = total_body_com_data[:,0]),\n",- " row=1, col=1\n",- ")\n",- "\n",- "fig.add_trace(\n",- " go.Scatter(y = total_body_com_data[:,1]),\n",- " row=2, col=1\n",- ")\n",- "\n",- "fig.add_trace(\n",- " go.Scatter(y = total_body_com_data[:,2]),\n",- " row=3, col=1\n",- ")\n",- "\n",- "fig.add_trace(\n",- " go.Scatter(y = freemocap_3d_body_data_to_plot[:,0]),\n",- " row=1, col=2\n",- ")\n",- "\n",- "fig.add_trace(\n",- " go.Scatter(y = freemocap_3d_body_data_to_plot[:,1]),\n",- " row=2, col=2\n",- ")\n",- "\n",- "fig.add_trace(\n",- " go.Scatter(y = freemocap_3d_body_data_to_plot[:,2]),\n",- " row=3, col=2\n",- ")\n",- "\n",- "#COM plot axes labels \n",- "fig['layout']['yaxis']['title']='X Axis (mm)'\n",- "fig['layout']['yaxis3']['title']='Y Axis (mm)'\n",- "fig['layout']['yaxis5']['title']='Z Axis (mm)'\n",- "fig['layout']['xaxis5']['title']='Frame #'\n",- "fig['layout']['xaxis6']['title']='Frame #'\n",- "\n",- "\n",- "\n",- "\n",- "fig.update_layout(height=600, width=800,showlegend=False)\n",- "fig.show()\n"- ]- },- {- "attachments": {},- "cell_type": "markdown",- "metadata": {},- "source": [- "## 3D Plotting\n",- "\n",- "Finally, we are creating a 3D plot of the skeleton movement, tracking all the joints in the `mediapipe_indices` list over time. \n",- "\n",- "The 'Play' button at the bottom allows you to watch the motion as if it were a video. Before pressing play, you can manually click and drag the plot around to orient the view of the plot. "- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "\n",- "def calculate_axes_means(skeleton_3d_data):\n",- " mx_skel = np.nanmean(skeleton_3d_data[:,0:33,0])\n",- " my_skel = np.nanmean(skeleton_3d_data[:,0:33,1])\n",- " mz_skel = np.nanmean(skeleton_3d_data[:,0:33,2])\n",- "\n",- " return mx_skel, my_skel, mz_skel\n",- "\n",- "ax_range = 1500\n",- "\n",- "mx_skel, my_skel, mz_skel = calculate_axes_means(freemocap_3d_body_data)\n",- "\n",- "# Create a list of frames\n",- "frames = [go.Frame(data=[go.Scatter3d(\n",- " x=freemocap_3d_body_data[i, :, 0],\n",- " y=freemocap_3d_body_data[i, :, 1],\n",- " z=freemocap_3d_body_data[i, :, 2],\n",- " mode='markers',\n",- " marker=dict(\n",- " size=2, # Adjust marker size as needed\n",- " )\n",- ")], name=str(i)) for i in range(freemocap_3d_body_data.shape[0])]\n",- "\n",- "# Define axis properties\n",- "axis = dict(\n",- " showbackground=True,\n",- " backgroundcolor=\"rgb(230, 230,230)\",\n",- " gridcolor=\"rgb(255, 255, 255)\",\n",- " zerolinecolor=\"rgb(255, 255, 255)\",\n",- ")\n",- "\n",- "# Create a figure\n",- "fig = go.Figure(\n",- " data=[go.Scatter3d(\n",- " x=freemocap_3d_body_data[0, :, 0],\n",- " y=freemocap_3d_body_data[0, :, 1],\n",- " z=freemocap_3d_body_data[0, :, 2],\n",- " mode='markers',\n",- " marker=dict(\n",- " size=2, # Adjust marker size as needed\n",- " )\n",- " )],\n",- " layout=go.Layout(\n",- " scene=dict(\n",- " xaxis=dict(axis, range=[mx_skel-ax_range, mx_skel+ax_range]), # Adjust range as needed\n",- " yaxis=dict(axis, range=[my_skel-ax_range, my_skel+ax_range]), # Adjust range as needed\n",- " zaxis=dict(axis, range=[mz_skel-ax_range, mz_skel+ax_range]), # Adjust range as needed\n",- " aspectmode='cube'\n",- " ),\n",- " updatemenus=[dict(\n",- " type='buttons',\n",- " showactive=False,\n",- " buttons=[dict(\n",- " label='Play',\n",- " method='animate',\n",- " args=[None, {\"frame\": {\"duration\": 30}}]\n",- " )]\n",- " )]\n",- " ),\n",- " frames=frames\n",- ")\n",- "\n",- "fig.show()"- ]- }- ],- "metadata": {- "kernelspec": {- "display_name": "validation_req_test",- "language": "python",- "name": "python3"- },- "language_info": {- "codemirror_mode": {- "name": "ipython",- "version": 3- },- "file_extension": ".py",- "mimetype": "text/x-python",- "name": "python",- "nbconvert_exporter": "python",- "pygments_lexer": "ipython3",- "version": "3.9.16"- },- "orig_nbformat": 4- },- "nbformat": 4,- "nbformat_minor": 2-}diff --git a/freemocap/old/data_layer/generate_jupyter_notebook/generate_jupyter_notebook.py b/freemocap/old/data_layer/generate_jupyter_notebook/generate_jupyter_notebook.pydeleted file mode 100644index 5930edae..00000000--- a/freemocap/old/data_layer/generate_jupyter_notebook/generate_jupyter_notebook.py+++ /dev/null@@ -1,30 +0,0 @@-import json-import logging-from pathlib import Path-from typing import Union--from freemocap.utilities.download_sample_data import get_sample_data_path--logger = logging.getLogger(__name__)---def generate_jupyter_notebook(path_to_recording: Union[str, Path]):- path_to_recording = Path(path_to_recording)- recording_name = Path(path_to_recording).name- path_to_template_notebook = Path(__file__).parent / "freemocap_template.ipynb"- path_to_output_notebook = Path(path_to_recording) / f"{recording_name}.ipynb"-- with open(path_to_template_notebook, "r") as file:- template_notebook = json.load(file)-- template_notebook["cells"][3]["source"] = [f'path_to_recording = "{str(path_to_recording)}"']-- with open(path_to_output_notebook, "w") as file:- json.dump(template_notebook, file)---if __name__ == "__main__":- path_to_recording = get_sample_data_path()- # path_to_recording = r"PATH/TO/RECORDING/FOLDER" #specify path to a specific recording here (other wise it will just download sample data)-- generate_jupyter_notebook(path_to_recording)diff --git a/freemocap/old/data_layer/recording_models/__init__.py b/freemocap/old/data_layer/recording_models/__init__.pydeleted file mode 100644index e69de29b..00000000diff --git a/freemocap/old/data_layer/recording_models/post_processing_parameter_models.py b/freemocap/old/data_layer/recording_models/post_processing_parameter_models.pydeleted file mode 100644index 011e9387..00000000--- a/freemocap/old/data_layer/recording_models/post_processing_parameter_models.py+++ /dev/null@@ -1,43 +0,0 @@-import logging--from pydantic import BaseModel, ConfigDict-from skellytracker.trackers.base_tracker.base_tracking_params import BaseTrackingParams-from skellytracker.trackers.base_tracker.model_info import ModelInfo-from skellytracker.trackers.mediapipe_tracker.mediapipe_model_info import MediapipeTrackingParams, MediapipeModelInfo--from freemocap.old.data_layer.recording_models.recording_info_model import (- RecordingInfoModel,-)--logger = logging.getLogger(__name__)---class AniposeTriangulate3DParametersModel(BaseModel):- run_reprojection_error_filtering: bool = False- reprojection_error_confidence_cutoff: float = 90- minimum_cameras_to_reproject: int = 3- use_triangulate_ransac_method: bool = False- run_3d_triangulation: bool = True- flatten_single_camera_data: bool = True---class ButterworthFilterParametersModel(BaseModel):- sampling_rate: float = 30- cutoff_frequency: float = 7- order: int = 4---class PostProcessingParametersModel(BaseModel):- framerate: float = 30.0- butterworth_filter_parameters: ButterworthFilterParametersModel = ButterworthFilterParametersModel()- max_gap_to_fill: int = 10- run_butterworth_filter: bool = True---class ProcessingParameterModel(BaseModel):- model_config = ConfigDict(arbitrary_types_allowed=True)- recording_info_model: RecordingInfoModel = None- tracking_parameters_model: BaseTrackingParams = MediapipeTrackingParams()- anipose_triangulate_3d_parameters_model: AniposeTriangulate3DParametersModel = AniposeTriangulate3DParametersModel()- post_processing_parameters_model: PostProcessingParametersModel = PostProcessingParametersModel()- tracking_model_info: ModelInfo = MediapipeModelInfo()diff --git a/freemocap/old/data_layer/recording_models/recording_info_model.py b/freemocap/old/data_layer/recording_models/recording_info_model.pydeleted file mode 100644index 5c34650b..00000000--- a/freemocap/old/data_layer/recording_models/recording_info_model.py+++ /dev/null@@ -1,349 +0,0 @@-import logging-from pathlib import Path-from typing import Union, Dict--import numpy as np--from freemocap.system.paths_and_filenames.file_and_folder_names import (- CENTER_OF_MASS_FOLDER_NAME,- DATA_2D_NPY_FILE_NAME,- RAW_3D_NPY_FILE_NAME,- OUTPUT_DATA_FOLDER_NAME,- RAW_DATA_FOLDER_NAME,- TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME,- REPROJECTION_ERROR_NPY_FILE_NAME,- SYNCHRONIZED_VIDEOS_FOLDER_NAME,- ANNOTATED_VIDEOS_FOLDER_NAME,- DATA_3D_NPY_FILE_NAME,- OLD_DATA_2D_NPY_FILE_NAME,- OLD_DATA_3D_NPY_FILE_NAME,- OLD_RAW_3D_NPY_FILE_NAME,- OLD_REPROJECTION_ERROR_NPY_FILE_NAME,- OLD_TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME,-)-from freemocap.system.paths_and_filenames.path_getters import create_camera_calibration_file_name, get_blender_file_path-from freemocap.tests.test_image_tracking_data_shape import (- test_image_tracking_data_exists,- test_image_tracking_data_shape,-)-from freemocap.tests.test_skeleton_data_shape import test_skeleton_data_exists, test_skeleton_data_shape-from freemocap.tests.test_synchronized_video_frame_counts import test_synchronized_video_frame_counts-from freemocap.tests.test_total_body_center_of_mass_data_shape import (- test_total_body_center_of_mass_data_exists,- test_total_body_center_of_mass_data_shape,-)-from freemocap.utilities.get_number_of_frames_of_videos_in_a_folder import get_number_of_frames_of_videos_in_a_folder-from freemocap.utilities.get_video_paths import get_video_paths--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,- ]- ):- recording_folder_path = Path(recording_folder_path).parent-- self._path = Path(recording_folder_path)- self._name = self._path.name-- self._calibration_toml_path = str(- Path(self._path) / create_camera_calibration_file_name(recording_name=self._name)- )-- self._active_tracker = active_tracker-- self._recording_folder_status_checker = RecordingFolderStatusChecker(recording_info_model=self)-- @property- def active_tracker(self) -> str:- return self._active_tracker-- @active_tracker.setter- def active_tracker(self, tracker_name: str):- self._active_tracker = tracker_name-- @property- def file_prefix(self) -> str:- if self.active_tracker != "" and self.active_tracker[-1] != "_":- return self.active_tracker + "_"- else:- return self.active_tracker-- # TODO: Create setters for the path names that depend on tracker name, and an overall setter that sets them all at once- @property- def path(self) -> str:- return str(self._path)-- @property- def name(self) -> str:- return self._name-- @property- def status_check(self) -> Dict[str, Union[bool, str, float, dict]]:- return self._recording_folder_status_checker.status_check-- @property- def calibration_toml_path(self) -> str:- return self._calibration_toml_path-- @calibration_toml_path.setter- def calibration_toml_path(self, path: Union[Path, str]):- self._calibration_toml_path = str(path)-- @property- def output_data_folder_path(self) -> str:- return str(Path(self._path) / OUTPUT_DATA_FOLDER_NAME)-- @property- def raw_data_folder_path(self) -> str:- return str(Path(self.output_data_folder_path) / RAW_DATA_FOLDER_NAME)-- @property- def synchronized_videos_folder_path(self) -> str:- return str(Path(self._path) / SYNCHRONIZED_VIDEOS_FOLDER_NAME)-- @property- def annotated_videos_folder_path(self) -> str:- return str(Path(self._path) / ANNOTATED_VIDEOS_FOLDER_NAME)-- @property- def data_2d_npy_file_path(self):- data_2d_path = Path(self.raw_data_folder_path) / (self.file_prefix + DATA_2D_NPY_FILE_NAME)- old_data_2d_path = Path(self.raw_data_folder_path) / OLD_DATA_2D_NPY_FILE_NAME- if self.active_tracker == "mediapipe" and old_data_2d_path.exists() and not data_2d_path.exists():- return str(old_data_2d_path)- else:- return str(data_2d_path)-- @property- def data_3d_npy_file_path(self):- data_3d_path = Path(self._path) / OUTPUT_DATA_FOLDER_NAME / (self.file_prefix + DATA_3D_NPY_FILE_NAME)- old_data_3d_path = Path(self._path) / OUTPUT_DATA_FOLDER_NAME / OLD_DATA_3D_NPY_FILE_NAME- if self.active_tracker == "mediapipe" and old_data_3d_path.exists() and not data_3d_path.exists():- return str(old_data_3d_path)- else:- return str(data_3d_path)-- @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)- )- 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():- return str(old_raw_data_path)- else:- return str(raw_data_path)-- @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)- )- raw_reprojection_error_path = (- 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()- ):- return str(raw_reprojection_error_path)- else:- return str(reprojection_error_path)-- @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)- )- 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- )- 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)- else:- return str(total_body_com_path)-- @property- def blender_file_path(self):- return get_blender_file_path(str(self._path))-- @property- def blender_file_status_check(self):- return Path(self.blender_file_path).is_file()-- @property- def calibration_toml_check(self) -> bool:- return self._recording_folder_status_checker.check_calibration_toml_status()-- @property- def synchronized_videos_status_check(self) -> bool:- return self._recording_folder_status_checker.check_synchronized_videos_status()-- @property- def single_video_check(self) -> bool:- return self._recording_folder_status_checker.check_single_video()-- @property- def data2d_status_check(self) -> bool:- return self._recording_folder_status_checker.check_data2d_status()-- @property- def data3d_status_check(self) -> bool:- return self._recording_folder_status_checker.check_data3d_status()-- @property- def center_of_mass_data_status_check(self) -> bool:- return self._recording_folder_status_checker.check_center_of_mass_data_status()---class RecordingFolderStatusChecker:- def __init__(self, recording_info_model: RecordingInfoModel):- self.recording_info_model = recording_info_model-- @property- def status_check(self) -> Dict[str, Union[bool, str, float, dict]]:- return {- "synchronized_videos_status_check": self.check_synchronized_videos_status(),- "data2d_status_check": self.check_data2d_status(),- "data3d_status_check": self.check_data3d_status(),- "center_of_mass_data_status_check": self.check_center_of_mass_data_status(),- "blender_file_status_check": self.check_blender_file_status(),- "single_video_check": self.check_single_video(),- "calibration_toml_check": self.check_calibration_toml_status(),- "video_and_camera_info": {- "number_of_synchronized_videos": self.get_number_of_mp4s_in_synched_videos_directory(),- "number_of_frames_in_videos": self.get_number_of_frames_in_videos(),- # 'camera_rotation_and_translation': self.get_camera_rotation_and_translation_from_calibration_toml()- },- }-- def check_synchronized_videos_status(self) -> bool:- try:- test_synchronized_video_frame_counts(self.recording_info_model.synchronized_videos_folder_path)- return True- except AssertionError:- return False-- def check_single_video(self) -> bool:- if len(get_video_paths(path_to_video_folder=self.recording_info_model.synchronized_videos_folder_path)) == 1:- return True- else:- return False-- def check_data2d_status(self) -> bool:- try:- test_image_tracking_data_exists(- synchronized_video_folder_path=self.recording_info_model.synchronized_videos_folder_path,- image_tracking_data=self.recording_info_model.data_2d_npy_file_path,- )- test_image_tracking_data_shape(- synchronized_video_folder_path=self.recording_info_model.synchronized_videos_folder_path,- image_tracking_data=self.recording_info_model.data_2d_npy_file_path,- )- return True- except AssertionError:- return False-- def check_data3d_status(self) -> bool:- try:- test_skeleton_data_exists(- raw_skeleton_data=self.recording_info_model.data_3d_npy_file_path,- reprojection_error_data=self.recording_info_model.reprojection_error_data_npy_file_path,- )- test_skeleton_data_shape(- synchronized_video_folder_path=self.recording_info_model.synchronized_videos_folder_path,- raw_skeleton_data=self.recording_info_model.data_3d_npy_file_path,- reprojection_error_data=self.recording_info_model.reprojection_error_data_npy_file_path,- )- return True- except AssertionError:- return False-- def check_center_of_mass_data_status(self) -> bool:- try:- test_total_body_center_of_mass_data_exists(- total_body_center_of_mass_data=self.recording_info_model.total_body_center_of_mass_npy_file_path,- )- test_total_body_center_of_mass_data_shape(- synchronized_video_folder_path=self.recording_info_model.synchronized_videos_folder_path,- total_body_center_of_mass_data=self.recording_info_model.total_body_center_of_mass_npy_file_path,- )- return True- except AssertionError:- return False-- def check_blender_file_status(self) -> bool:- return Path(self.recording_info_model.blender_file_path).is_file()-- def check_calibration_toml_status(self) -> bool:- # TODO: check if adding a single video check here makes sense with the logic (i.e. will that ever give a misleading response)- toml_status = Path(self.recording_info_model.calibration_toml_path).is_file()- if not toml_status:- logger.debug(- "No calibration file found with session name, checking for other calibration files in recording session"- )- toml_status = self.check_for_calibration_toml_with_different_name()- return toml_status-- def get_number_of_mp4s_in_synched_videos_directory(self) -> int:- synchronized_directory_path = Path(self.recording_info_model.synchronized_videos_folder_path)-- if not synchronized_directory_path.exists():- return 0-- video_count = len(get_video_paths(synchronized_directory_path))-- logger.info(f"Number of `.mp4`'s in {synchronized_directory_path}: {video_count}")- return video_count-- def get_number_of_frames_in_videos(self) -> Dict[str, int]:- timestamps_directory_path = Path(self.recording_info_model.synchronized_videos_folder_path) / "timestamps"-- if timestamps_directory_path.exists():- frame_counts = {}-- for npy_file in timestamps_directory_path.iterdir():- if npy_file.is_file() and npy_file.suffix.lower() == ".npy":- video_npy = np.load(str(npy_file))- frame_counts[npy_file.name] = len(video_npy) - 1- else:- logger.debug("No 'timestamps' directory, finding frame counts from synchronized videos")- try:- frame_counts = get_number_of_frames_of_videos_in_a_folder(- self.recording_info_model.synchronized_videos_folder_path- )- except ValueError:- frame_counts = {}-- return frame_counts-- def check_for_calibration_toml_with_different_name(self) -> bool:- try:- for file in Path(self.recording_info_model.path).iterdir():- if file.is_file() and file.name.endswith("camera_calibration.toml"):- self.recording_info_model.calibration_toml_path = str(file)- logger.info(f"Found calibration file at: {self.recording_info_model.calibration_toml_path}")- return True- except Exception as e:- logger.warning(f"Error checking for calibration toml with different name: {e}")- return Falsediff --git a/freemocap/old/data_layer/skeleton_models/__init__.py b/freemocap/old/data_layer/skeleton_models/__init__.pydeleted file mode 100644index e69de29b..00000000diff --git a/freemocap/old/data_layer/skeleton_models/marker_info.py b/freemocap/old/data_layer/skeleton_models/marker_info.pydeleted file mode 100644index 11f7a21a..00000000--- a/freemocap/old/data_layer/skeleton_models/marker_info.py+++ /dev/null@@ -1,67 +0,0 @@-from typing import Dict, List, Optional, Union--from pydantic import BaseModel, model_validator, Field, field_validator---class VirtualMarkerInfo(BaseModel):- virtual_markers: Dict[str, Dict[str, List[Union[float, str]]]]-- @field_validator("virtual_markers")- @classmethod- def validate_virtual_marker(cls, virtual_marker: Dict[str, List[Union[float, str]]]):- for virtual_marker_name, virtual_marker_values in virtual_marker.items():- marker_names = virtual_marker_values.get("marker_names", []) # TODO: make sure this .get is valid- marker_weights = virtual_marker_values.get("marker_weights", [])-- if len(marker_names) != len(marker_weights):- raise ValueError(- f"The number of marker names must match the number of marker weights for {virtual_marker_name}. Currently there are {len(marker_names)} names and {len(marker_weights)} weights."- )-- if not isinstance(marker_names, list) or not all(isinstance(name, str) for name in marker_names):- raise ValueError(f"Marker names must be a list of strings for {marker_names}.")-- if not isinstance(marker_weights, list) or not all(- isinstance(weight, (int, float)) for weight in marker_weights- ):- raise ValueError(f"Marker weights must be a list of numbers for {virtual_marker_name}.")-- weight_sum = sum(marker_weights)- if not 0.99 <= weight_sum <= 1.01: # Allowing a tiny bit of floating-point leniency- raise ValueError(- f"Marker weights must sum to approximately 1 for {virtual_marker_name} Current sum is {weight_sum}."- )-- return virtual_marker---class MarkerInfo(BaseModel):- original_marker_names: List[str]- virtual_marker_definition: Optional[VirtualMarkerInfo] = None- all_markers_list: List[str] = Field(default_factory=list)-- @model_validator(mode="before")- def copy_markers_to_all(cls, values):- """Copy markers to all_markers_list at initialization."""- original_marker_names = values.get("original_marker_names")- if original_marker_names:- # Directly initializing all_markers_list with a copy of original_marker_names- values["all_markers_list"] = original_marker_names.copy()- return values-- def add_virtual_markers(self, virtual_markers_dict: Dict[str, Dict[str, List[Union[float, str]]]]):- """Add virtual markers and update all_markers_list."""- self.virtual_marker_definition = VirtualMarkerInfo(virtual_markers=virtual_markers_dict)- for virtual_marker_name in self.virtual_marker_definition.virtual_markers.keys():- if virtual_marker_name not in self.all_markers_list:- self.all_markers_list.append(virtual_marker_name)-- @property- def all_markers(self) -> List[str]:- """Publicly expose the combined list of markers."""- return self.all_markers_list-- @classmethod- def create(cls, marker_list: List[str]):- """Class method to create an instance with initial marker names."""- return cls(original_marker_names=marker_list)diff --git a/freemocap/old/data_layer/skeleton_models/segments.py b/freemocap/old/data_layer/skeleton_models/segments.pydeleted file mode 100644index 5c7ee99e..00000000--- a/freemocap/old/data_layer/skeleton_models/segments.py+++ /dev/null@@ -1,37 +0,0 @@-from typing import Dict--from pydantic import BaseModel, model_validator--from freemocap.old.data_layer.skeleton_models.marker_info import MarkerInfo---class Segment(BaseModel):- proximal: str- distal: str---class SegmentAnthropometry(BaseModel):- segment_com_length: float- segment_com_percentage: float---class Segments(BaseModel):- markers: MarkerInfo- segment_connections: Dict[str, Segment]-- @model_validator(mode="before")- def check_that_all_markers_exist(cls, values):- markers = values.get("markers").all_markers- segment_connections = values.get("segment_connections")-- for segment_name, segment_connection in segment_connections.items():- if segment_connection.get("proximal") not in markers:- raise ValueError(- f"The proximal marker {segment_connection.proximal} for {segment_name} is not in the list of markers or virtual markers."- )- if segment_connection.get("distal") not in markers:- raise ValueError(- f"The distal marker {segment_connection.distal} for {segment_name} is not in the list of markers or virtual markers."- )-- return valuesdiff --git a/freemocap/old/data_layer/skeleton_models/skeleton.py b/freemocap/old/data_layer/skeleton_models/skeleton.pydeleted file mode 100644index 9a02ec6a..00000000--- a/freemocap/old/data_layer/skeleton_models/skeleton.py+++ /dev/null@@ -1,133 +0,0 @@-import logging-from typing import Dict, List, Optional--import numpy as np-from pydantic import BaseModel, ConfigDict--from freemocap.old.data_layer.skeleton_models.marker_info import MarkerInfo-from freemocap.old.data_layer.skeleton_models.segments import Segment, Segments, SegmentAnthropometry--logger = logging.getLogger(__name__)---class Skeleton(BaseModel):- model_config = ConfigDict(arbitrary_types_allowed=True)- markers: MarkerInfo- num_tracked_points: int- segments: Optional[Dict[str, Segment]] = None- marker_data: Dict[str, np.ndarray] = {}- virtual_marker_data: Dict[str, np.ndarray] = {}- joint_hierarchy: Optional[Dict[str, List[str]]] = None- center_of_mass_definitions: Optional[Dict[str, SegmentAnthropometry]] = None- num_frames: Optional[int] = None-- def add_segments(self, segment_connections: Dict[str, Segment]) -> None:- """- Adds segment connection data to the skeleton model.-- Parameters:- - segment_connections: A dictionary where each key is a segment name and its value is a dictionary- with information about that segment (e.g., 'proximal', 'distal' marker names).- """- segments_model = Segments(- markers=self.markers,- segment_connections={name: segment for name, segment in segment_connections.items()},- )- self.segments = segments_model.segment_connections-- def add_joint_hierarchy(self, joint_hierarchy: Dict[str, List[str]]) -> None:- """- Adds joint hierarchy data to the skeleton model.-- Parameters:- - joint_hierarchy: A dictionary with joint names as keys and lists of connected marker names as values.- """- for joint_name, joint_connections in joint_hierarchy.items():- if joint_name not in self.markers.all_markers:- raise ValueError(f"The joint {joint_name} is not in the list of markers or virtual markers.")- for connected_marker in joint_connections:- if connected_marker not in self.markers.all_markers:- raise ValueError(- f"The connected marker {connected_marker} for {joint_name} is not in the list of markers or virtual markers."- )-- self.joint_hierarchy = joint_hierarchy-- def add_center_of_mass_definitions(self, center_of_mass_definitions: Dict[str, Dict[str, float]]) -> None:- """- Adds anthropometric center of mass definitions to the skeleton model.-- Parameters:- - center_of_mass_definitions: A dictionary containing segment mass percentages.- """- if self.segments is None:- raise ValueError("Segments must be defined before center of mass definitions can be added.")- for com_segment_name in center_of_mass_definitions.keys():- if com_segment_name not in self.segments.keys():- raise ValueError(f"Segment {com_segment_name} is not in the list of segments.")-- self.center_of_mass_definitions = {- name: SegmentAnthropometry(**values) for name, values in center_of_mass_definitions.items()- }-- def integrate_freemocap_3d_data(self, freemocap_3d_data: np.ndarray) -> None:- self.num_frames = freemocap_3d_data.shape[0]- num_markers_in_data = freemocap_3d_data.shape[1]- original_marker_names_list = self.markers.original_marker_names-- if num_markers_in_data != self.num_tracked_points:- raise ValueError(- f"The number of markers in the 3D data ({num_markers_in_data}) does not match "- f"the expected number of tracked points ({self.num_tracked_points})."- )-- self.marker_data = {- marker_name: freemocap_3d_data[:, i, :] for i, marker_name in enumerate(original_marker_names_list)- }-- try:- self.calculate_virtual_markers()- except ValueError:- logger.info(- "Freemocap data integrated without virtual markers, as no virtual marker definition was provided"- )-- def calculate_virtual_markers(self) -> None:- if not self.marker_data:- raise ValueError(- "3d marker data must be integrated before calculating virtual markers. Run `integrate_freemocap_3d_data()` first."- )-- if not self.markers.virtual_marker_definition:- raise ValueError(- "Virtual marker info must be defined before calculating virtual markers. Run `add_virtual_markers()` first."- )-- for vm_name, vm_info in self.markers.virtual_marker_definition.virtual_markers.items():- vm_positions = np.zeros((self.marker_data[next(iter(self.marker_data))].shape[0], 3))- for marker_name, weight in zip(vm_info["marker_names"], vm_info["marker_weights"]):- vm_positions += self.marker_data[str(marker_name)] * weight- self.virtual_marker_data[vm_name] = vm_positions-- self.marker_data.update(self.virtual_marker_data)-- def get_segment_markers(self, segment_name: str) -> Dict[str, np.ndarray]:- """Returns a dictionary with the positions of the proximal and distal markers for a segment."""- if not self.segments:- raise ValueError("Segments must be defined before getting segment markers.")-- if not self.trajectories:- raise ValueError("Trajectories must be defined before getting segment markers.")-- segment = self.segments.get(segment_name)- if not segment:- raise ValueError(f"Segment '{segment_name}' is not defined in the skeleton.")-- proximal_trajectories = self.trajectories.get(segment.proximal)- distal_trajectories = self.trajectories.get(segment.distal)-- return {"proximal": proximal_trajectories, "distal": distal_trajectories}-- @property- def trajectories(self) -> Dict[str, np.ndarray]:- return self.marker_datadiff --git a/freemocap/old/ipython_jupyter_notebooks/COM_Jumping_Analysis.ipynb b/freemocap/old/ipython_jupyter_notebooks/COM_Jumping_Analysis.ipynbdeleted file mode 100644index 77d7e424..00000000--- a/freemocap/old/ipython_jupyter_notebooks/COM_Jumping_Analysis.ipynb+++ /dev/null@@ -1,752 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "source": [- "# Jumping Notebook!"- ],- "metadata": {- "collapsed": false,- "id": "1cdfdca98234e968"- },- "id": "1cdfdca98234e968"- },- {- "cell_type": "markdown",- "source": [],- "metadata": {- "collapsed": false,- "id": "41378eca2319bd7a"- },- "id": "41378eca2319bd7a"- },- {- "cell_type": "code",- "execution_count": 1,- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "No module named 'numpy'\n",- "Collecting numpy\r\n",- " Downloading numpy-1.26.1-cp311-cp311-macosx_11_0_arm64.whl.metadata (115 kB)\r\n",- "\u001B[2K \u001B[90mโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ\u001B[0m \u001B[32m115.1/115.1 kB\u001B[0m \u001B[31m1.6 MB/s\u001B[0m eta \u001B[36m0:00:00\u001B[0ma \u001B[36m0:00:01\u001B[0m\r\n",- "\u001B[?25hDownloading numpy-1.26.1-cp311-cp311-macosx_11_0_arm64.whl (14.0 MB)\r\n",- "\u001B[2K \u001B[90mโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ\u001B[0m \u001B[32m14.0/14.0 MB\u001B[0m \u001B[31m5.1 MB/s\u001B[0m eta \u001B[36m0:00:00\u001B[0m00:01\u001B[0m00:01\u001B[0m\r\n",- "\u001B[?25hInstalling collected packages: numpy\r\n",- "Successfully installed numpy-1.26.1\r\n",- "Note: you may need to restart the kernel to use updated packages.\n",- "No module named 'scipy'\n",- "Collecting scipy\r\n",- " Downloading scipy-1.11.3-cp311-cp311-macosx_12_0_arm64.whl.metadata (165 kB)\r\n",- "\u001B[2K \u001B[90mโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ\u001B[0m \u001B[32m165.4/165.4 kB\u001B[0m \u001B[31m2.6 MB/s\u001B[0m eta \u001B[36m0:00:00\u001B[0ma \u001B[36m0:00:01\u001B[0m\r\n",- "\u001B[?25hRequirement already satisfied: numpy<1.28.0,>=1.21.6 in /opt/homebrew/Caskroom/miniconda/base/envs/freemocap_analysis/lib/python3.11/site-packages (from scipy) (1.26.1)\r\n",- "Downloading scipy-1.11.3-cp311-cp311-macosx_12_0_arm64.whl (29.7 MB)\r\n",- "\u001B[2K \u001B[90mโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ\u001B[0m \u001B[32m29.7/29.7 MB\u001B[0m \u001B[31m6.6 MB/s\u001B[0m eta \u001B[36m0:00:00\u001B[0m00:01\u001B[0m00:01\u001B[0m\r\n",- "\u001B[?25hInstalling collected packages: scipy\r\n",- "Successfully installed scipy-1.11.3\r\n",- "Note: you may need to restart the kernel to use updated packages.\n",- "No module named 'plotly'\n",- "Collecting plotly\r\n",- " Downloading plotly-5.18.0-py3-none-any.whl.metadata (7.0 kB)\r\n",- "Collecting tenacity>=6.2.0 (from plotly)\r\n",- " Downloading tenacity-8.2.3-py3-none-any.whl.metadata (1.0 kB)\r\n",- "Requirement already satisfied: packaging in /opt/homebrew/Caskroom/miniconda/base/envs/freemocap_analysis/lib/python3.11/site-packages (from plotly) (23.1)\r\n",- "Downloading plotly-5.18.0-py3-none-any.whl (15.6 MB)\r\n",- "\u001B[2K \u001B[90mโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ\u001B[0m \u001B[32m15.6/15.6 MB\u001B[0m \u001B[31m6.9 MB/s\u001B[0m eta \u001B[36m0:00:00\u001B[0m00:01\u001B[0m00:01\u001B[0m\r\n",- "\u001B[?25hDownloading tenacity-8.2.3-py3-none-any.whl (24 kB)\r\n",- "Installing collected packages: tenacity, plotly\r\n",- "Successfully installed plotly-5.18.0 tenacity-8.2.3\r\n",- "Note: you may need to restart the kernel to use updated packages.\n"- ]- }- ],- "source": [- "#Importing libraries\n",- "\n",- "\n",- "from pathlib import Path\n",- "\n",- "try:\n",- " import numpy as np\n",- "except Exception as e:\n",- " print(e)\n",- " %pip install numpy\n",- " import numpy as np\n",- "\n",- "try:\n",- " from scipy.signal import find_peaks\n",- "except Exception as e:\n",- " print(e)\n",- " %pip install scipy\n",- " from scipy.signal import find_peaks\n",- "\n",- "try:\n",- " from plotly.subplots import make_subplots\n",- " import plotly.graph_objects as go\n",- "except Exception as e:\n",- " print(e)\n",- " %pip install plotly\n",- " from plotly.subplots import make_subplots\n",- " import plotly.graph_objects as go"- ],- "metadata": {- "id": "21dd4017a36af8f4",- "ExecuteTime": {- "end_time": "2023-11-12T12:34:15.709645Z",- "start_time": "2023-11-12T12:33:48.548369Z"- }- },- "id": "21dd4017a36af8f4"- },- {- "cell_type": "code",- "execution_count": 2,- "outputs": [],- "source": [- "path_to_recording = r\"/Users/mdn/Documents/PROJECTS/FreeMoCap_data/2023-10-05_max_jump_recording_sessions_KK_ML/session_2023-10-05_15_59_45/recording_16_04_29_gmt-4__ML_max_jump\""- ],- "metadata": {- "id": "f6e8800a49f64c7e",- "ExecuteTime": {- "end_time": "2023-11-12T12:34:15.710397Z",- "start_time": "2023-11-12T12:34:15.707866Z"- }- },- "id": "f6e8800a49f64c7e"- },- {- "cell_type": "markdown",- "source": [- "### What does the \"shape\" of the data mean?\n",- "The shape of the data is the number of frames by the number of dimensions. In this case, the data is 3D, so the shape is (number of frames, 3)."- ],- "metadata": {- "collapsed": false,- "id": "a8200e75a3457e6"- },- "id": "a8200e75a3457e6"- },- {- "cell_type": "code",- "execution_count": 6,- "outputs": [],- "source": [- "\n",- "mediapipe_indices = ['nose',\n",- " 'left_eye_inner',\n",- " 'left_eye',\n",- " 'left_eye_outer',\n",- " 'right_eye_inner',\n",- " 'right_eye',\n",- " 'right_eye_outer',\n",- " 'left_ear',\n",- " 'right_ear',\n",- " 'mouth_left',\n",- " 'mouth_right',\n",- " 'left_shoulder',\n",- " 'right_shoulder',\n",- " 'left_elbow',\n",- " 'right_elbow',\n",- " 'left_wrist',\n",- " 'right_wrist',\n",- " 'left_pinky',\n",- " 'right_pinky',\n",- " 'left_index',\n",- " 'right_index',\n",- " 'left_thumb',\n",- " 'right_thumb',\n",- " 'left_hip',\n",- " 'right_hip',\n",- " 'left_knee',\n",- " 'right_knee',\n",- " 'left_ankle',\n",- " 'right_ankle',\n",- " 'left_heel',\n",- " 'right_heel',\n",- " 'left_foot_index',\n",- " 'right_foot_index']\n",- "\n",- "joint_to_plot_index = mediapipe_indices.index('nose') #You can choose what point you'd like to look at here by changing the string in the mediapipe_indices list."- ],- "metadata": {- "id": "55b9e432c98ab003",- "ExecuteTime": {- "end_time": "2023-11-12T12:37:14.600201Z",- "start_time": "2023-11-12T12:37:14.594506Z"- }- },- "id": "55b9e432c98ab003"- },- {- "cell_type": "code",- "execution_count": 7,- "outputs": [- {- "ename": "IndexError",- "evalue": "too many indices for array: array is 2-dimensional, but 3 were indexed",- "output_type": "error",- "traceback": [- "\u001B[0;31m---------------------------------------------------------------------------\u001B[0m",- "\u001B[0;31mIndexError\u001B[0m Traceback (most recent call last)",- "Cell \u001B[0;32mIn[7], line 9\u001B[0m\n\u001B[1;32m 6\u001B[0m freemocap_3d_body_data \u001B[38;5;241m=\u001B[39m np\u001B[38;5;241m.\u001B[39mload(path_to_center_of_mass_npy)\n\u001B[1;32m 7\u001B[0m total_body_com_data \u001B[38;5;241m=\u001B[39m np\u001B[38;5;241m.\u001B[39mload(path_to_freemocap_3d_body_data_npy)\n\u001B[0;32m----> 9\u001B[0m freemocap_3d_body_data_to_plot \u001B[38;5;241m=\u001B[39m freemocap_3d_body_data[:,joint_to_plot_index,:]\n",- "\u001B[0;31mIndexError\u001B[0m: too many indices for array: array is 2-dimensional, but 3 were indexed"- ]- }- ],- "source": [- "path_to_recording = Path(path_to_recording)\n",- "path_to_center_of_mass_npy = path_to_recording/'output_data'/'center_of_mass'/'total_body_center_of_mass_xyz.npy'\n",- "path_to_freemocap_3d_body_data_npy = path_to_recording/'output_data'/'mediapipe_body_3d_xyz.npy'\n",- "\n",- "\n",- "freemocap_3d_body_data = np.load(path_to_center_of_mass_npy)\n",- "total_body_com_data = np.load(path_to_freemocap_3d_body_data_npy)\n",- "\n",- "freemocap_3d_body_data_to_plot = freemocap_3d_body_data[:,joint_to_plot_index,:]"- ],- "metadata": {- "id": "deb5427474d3d920",- "ExecuteTime": {- "end_time": "2023-11-12T12:37:22.510130Z",- "start_time": "2023-11-12T12:37:22.473846Z"- }- },- "id": "deb5427474d3d920"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [],- "metadata": {- "id": "dcd3caa0780c1472",- "ExecuteTime": {- "start_time": "2023-11-12T12:37:22.487149Z"- }- },- "id": "dcd3caa0780c1472"- },- {- "cell_type": "markdown",- "source": [- "## 3D Plotting\n",- "\n",- "We are creating a 3D plot of the skeleton movement, tracking all the joints in the `mediapipe_indices` list over time. \n",- "\n",- "The 'Play' button at the bottom allows you to watch the motion as if it were a video. Before pressing play, you can manually click and drag the plot around to orient the view of the plot."- ],- "metadata": {- "collapsed": false,- "id": "748172036eafe524"- },- "id": "748172036eafe524"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "def calculate_axes_means(skeleton_3d_data):\n",- " mx_skel = np.nanmean(skeleton_3d_data[:,0:33,0])\n",- " my_skel = np.nanmean(skeleton_3d_data[:,0:33,1])\n",- " mz_skel = np.nanmean(skeleton_3d_data[:,0:33,2])\n",- "\n",- " return mx_skel, my_skel, mz_skel\n",- "\n",- "ax_range = 1500\n",- "\n",- "mx_skel, my_skel, mz_skel = calculate_axes_means(freemocap_3d_body_data)\n",- "\n",- "# Create a list of frames\n",- "frames = [go.Frame(data=[go.Scatter3d(\n",- " x=freemocap_3d_body_data[i, :, 0],\n",- " y=freemocap_3d_body_data[i, :, 1],\n",- " z=freemocap_3d_body_data[i, :, 2],\n",- " mode='markers',\n",- " marker=dict(\n",- " size=2, # Adjust marker size as needed\n",- " )\n",- ")], name=str(i)) for i in range(freemocap_3d_body_data.shape[0])]\n",- "\n",- "# Define axis properties\n",- "axis = dict(\n",- " showbackground=True,\n",- " backgroundcolor=\"rgb(230, 230,230)\",\n",- " gridcolor=\"rgb(255, 255, 255)\",\n",- " zerolinecolor=\"rgb(255, 255, 255)\",\n",- ")\n",- "\n",- "# Create a figure\n",- "fig = go.Figure(\n",- " data=[go.Scatter3d(\n",- " x=freemocap_3d_body_data[0, :, 0],\n",- " y=freemocap_3d_body_data[0, :, 1],\n",- " z=freemocap_3d_body_data[0, :, 2],\n",- " mode='markers',\n",- " marker=dict(\n",- " size=2, # Adjust marker size as needed\n",- " )\n",- " )],\n",- " layout=go.Layout(\n",- " scene=dict(\n",- " xaxis=dict(axis, range=[mx_skel-ax_range, mx_skel+ax_range]), # Adjust range as needed\n",- " yaxis=dict(axis, range=[my_skel-ax_range, my_skel+ax_range]), # Adjust range as needed\n",- " zaxis=dict(axis, range=[mz_skel-ax_range, mz_skel+ax_range]), # Adjust range as needed\n",- " aspectmode='cube'\n",- " ),\n",- " updatemenus=[dict(\n",- " type='buttons',\n",- " showactive=False,\n",- " buttons=[dict(\n",- " label='Play',\n",- " method='animate',\n",- " args=[None, {\"frame\": {\"duration\": 30}}]\n",- " )]\n",- " )]\n",- " ),\n",- " frames=frames\n",- ")\n",- "\n",- "fig.show()"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/",- "height": 542- },- "id": "363ed68144eaffc8",- "outputId": "aec20410-5fd4-4c8f-ada2-525e5c5b78d3",- "ExecuteTime": {- "start_time": "2023-11-12T12:37:22.489473Z"- }- },- "id": "363ed68144eaffc8"- },- {- "cell_type": "markdown",- "source": [- "## Now lets start analysing the data!"- ],- "metadata": {- "collapsed": false,- "id": "6953e7463574d038"- },- "id": "6953e7463574d038"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "\n",- "fig = make_subplots(rows=3, cols=1, subplot_titles=('Center of Mass X', 'Center of Mass Y', 'Center of Mass Z'))\n",- "\n",- "fig.add_trace(\n",- " go.Scatter(y=total_body_com_data[:, 0]),\n",- " row=1, col=1\n",- ")\n",- "\n",- "fig.add_trace(\n",- " go.Scatter(y=total_body_com_data[:, 1]),\n",- " row=2, col=1\n",- ")\n",- "\n",- "fig.add_trace(\n",- " go.Scatter(y=total_body_com_data[:, 2]),\n",- " row=3, col=1\n",- ")\n",- "\n",- "# COM plot axes labels\n",- "fig.update_yaxes(title_text=\"X Axis (mm)\", row=1, col=1)\n",- "fig.update_yaxes(title_text=\"Y Axis (mm)\", row=2, col=1)\n",- "fig.update_yaxes(title_text=\"Z Axis (mm)\", row=3, col=1)\n",- "fig.update_xaxes(title_text=\"Frame #\", row=3, col=1) # Assuming you only want x-axis title for the bottommost subplot\n",- "\n",- "fig.update_layout(height=600, width=800, showlegend=False)\n",- "fig.show()\n"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/",- "height": 617- },- "id": "a9b876fa14fbc378",- "outputId": "400b1c32-f8d3-44d0-a6c9-16e17e726391",- "ExecuteTime": {- "start_time": "2023-11-12T12:37:22.490925Z"- }- },- "id": "a9b876fa14fbc378"- },- {- "cell_type": "markdown",- "source": [- "## Lets calculate the kinetics of the COM in the Z direction (vertical)"- ],- "metadata": {- "collapsed": false,- "id": "e416eb5e7bf88e27"- },- "id": "e416eb5e7bf88e27"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "from scipy.signal import butter, filtfilt\n",- "\n",- "# First lets filter the position data to get it nice a clean\n",- "# We will use a low pass filter to smooth the data\n",- "position_com_z_data = total_body_com_data[:, 2]\n",- "\n",- "# Filter Function\n",- "def butterworth_filter(data, cutoff, frame_rate, order=4, filter_type='low'):\n",- " nyq = 0.5 * frame_rate\n",- " normal_cutoff = cutoff / nyq\n",- " b, a = butter(order, normal_cutoff, btype=filter_type, analog=False)\n",- "\n",- " # Adjust the padlen based on the length of the data\n",- " padlen = min(order * 3, len(data) - 1)\n",- "\n",- " y = filtfilt(b, a, data, padlen=padlen)\n",- " return y\n",- "\n",- "# Filter the data\n",- "position_com_z_data = butterworth_filter(position_com_z_data, 5, 30, order=4, filter_type='low')\n"- ],- "metadata": {- "id": "ef6bedc02a5d19c9",- "ExecuteTime": {- "start_time": "2023-11-12T12:37:22.492066Z"- }- },- "id": "ef6bedc02a5d19c9"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "\n",- "velocity_com_z_data = np.diff(position_com_z_data, axis=0)\n",- "acceleration_com_z_data = np.diff(velocity_com_z_data, axis=0)\n",- "\n",- "time = 1/30\n"- ],- "metadata": {- "id": "9042f15e6e3c0051",- "ExecuteTime": {- "start_time": "2023-11-12T12:37:22.493306Z"- }- },- "id": "9042f15e6e3c0051"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "# Function to normalize and scale data to fit between -1 and 1\n",- "def normalize_and_scale(data):\n",- " normalized_data = 2 * ((data - min(data)) / (max(data) - min(data))) - 1\n",- " return normalized_data\n",- "\n",- "# Apply the function to your data\n",- "scaled_position = normalize_and_scale(position_com_z_data)\n",- "scaled_velocity = normalize_and_scale(velocity_com_z_data)\n",- "scaled_acceleration = normalize_and_scale(acceleration_com_z_data)\n",- "\n",- "# Plot the data\n",- "fig = make_subplots(rows=4, cols=1, subplot_titles=('Z Position', 'Z Velocity', 'Z Acceleration', 'Superimposed'))\n",- "\n",- "fig.add_trace(\n",- " go.Scatter(y=position_com_z_data, name='Z Position', line=dict(color='red')),\n",- " row=1, col=1\n",- ")\n",- "\n",- "fig.add_trace(\n",- " go.Scatter(y=velocity_com_z_data, name='Z Velocity', line=dict(color='green')),\n",- " row=2, col=1\n",- ")\n",- "\n",- "fig.add_trace(\n",- " go.Scatter(y=acceleration_com_z_data, name='Z Acceleration', line=dict(color='blue')),\n",- " row=3, col=1\n",- ")\n",- "\n",- "# Add the scaled traces to the fourth subplot\n",- "fig.add_trace(\n",- " go.Scatter(y=scaled_position, name='Scaled Z Position', line=dict(color='red')),\n",- " row=4, col=1\n",- ")\n",- "fig.add_trace(\n",- " go.Scatter(y=scaled_velocity, name='Scaled Z Velocity', line=dict(color='green')),\n",- " row=4, col=1\n",- ")\n",- "fig.add_trace(\n",- " go.Scatter(y=scaled_acceleration, name='Scaled Z Acceleration', line=dict(color='blue')),\n",- " row=4, col=1\n",- ")\n",- "\n",- "# COM plot axes labels\n",- "fig.update_yaxes(title_text=\"Z Position\", row=1, col=1)\n",- "fig.update_yaxes(title_text=\"Z Velocity\", row=2, col=1)\n",- "fig.update_yaxes(title_text=\"Z Acceleration\", row=3, col=1)\n",- "fig.update_xaxes(title_text=\"Frame #\", row=4, col=1)\n",- "\n",- "fig.update_layout(height=800, width=800, showlegend=True)\n",- "fig.show()\n"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/",- "height": 817- },- "id": "d867e48cfa98abce",- "outputId": "fe8649af-652c-4622-d5b9-dcc4eab6f4d7",- "ExecuteTime": {- "start_time": "2023-11-12T12:37:22.494799Z"- }- },- "id": "d867e48cfa98abce"- },- {- "cell_type": "markdown",- "source": [- "## Lets look a little closer at the acceleration data."- ],- "metadata": {- "collapsed": false,- "id": "af56c1f276cf367a"- },- "id": "af56c1f276cf367a"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "liftoff_time_stamps = []\n",- "bottom_time_stamps = []\n",- "apex_time_stamps = []\n",- "\n",- "for t in range(velocity_com_z_data.size-2):\n",- " if (velocity_com_z_data[t+2]<velocity_com_z_data[t+1]\n",- " and velocity_com_z_data[t] < velocity_com_z_data[t+1]):\n",- " liftoff_time_stamps.append(t+1)\n",- "\n",- "for t in range(velocity_com_z_data.size-1):\n",- " if velocity_com_z_data[t+1] > 0 and velocity_com_z_data[t] <= 0:\n",- " bottom_time_stamps.append(t)\n",- " if velocity_com_z_data[t+1] < 0 and velocity_com_z_data[t] >= 0:\n",- " apex_time_stamps.append(t)\n",- "\n",- "print(f\"number of iterations at bottom: \", len(bottom_time_stamps))\n",- "print(f\"number of iterations at apex: \", len(apex_time_stamps))"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/"- },- "id": "e960df75d5a7c9b7",- "outputId": "0c262dd9-7010-4f98-c63e-1c698fc0ec45",- "ExecuteTime": {- "start_time": "2023-11-12T12:37:22.496192Z"- }- },- "id": "e960df75d5a7c9b7"- },- {- "cell_type": "code",- "source": [- "fig = go.Figure()\n",- "\n",- "# Add the velocity data\n",- "fig.add_trace(\n",- " go.Scatter(y=velocity_com_z_data, mode='lines', name='Velocity COM Z')\n",- ")\n",- "\n",- "fig.add_trace(\n",- " go.Scatter(x=liftoff_time_stamps, y=velocity_com_z_data[liftoff_time_stamps],\n",- " mode='markers', marker_symbol='star', marker_size=10,\n",- " marker_color='yellow', name='Lift Off')\n",- ")\n",- "\n",- "# Show the plot\n",- "fig.show()"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/",- "height": 542- },- "id": "MKT7Ebrk6mo-",- "outputId": "182871e2-b1be-4591-8f7e-1e1e40ac7c82",- "ExecuteTime": {- "start_time": "2023-11-12T12:37:22.496952Z"- }- },- "id": "MKT7Ebrk6mo-",- "execution_count": null,- "outputs": []- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "fig = go.Figure()\n",- "\n",- "# Add the acceleration data\n",- "fig.add_trace(\n",- " go.Scatter(y=acceleration_com_z_data, mode='lines', name='Acceleration COM Z')\n",- ")\n",- "\n",- "fig.add_trace(\n",- " go.Scatter(x=liftoff_time_stamps, y=acceleration_com_z_data[liftoff_time_stamps],\n",- " mode='markers', marker_symbol='star', marker_size=10,\n",- " marker_color='yellow', name='Lift Off')\n",- ")\n",- "\n",- "# Show the plot\n",- "fig.show()"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/",- "height": 542- },- "id": "65d1afedca8851f0",- "outputId": "1cad5eb7-f3aa-4cc3-c6c6-3c56ff0091f4",- "ExecuteTime": {- "start_time": "2023-11-12T12:37:22.497837Z"- }- },- "id": "65d1afedca8851f0"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "# Create the state space plot\n",- "fig = go.Figure()\n",- "\n",- "# Plot height_position vs height_velocity\n",- "fig.add_trace(\n",- " go.Scatter(x= velocity_com_z_data, y=position_com_z_data, mode='lines+markers', marker=dict(symbol='circle', size=6, opacity=0.5), name='Data')\n",- ")\n",- "\n",- "# Mark the start\n",- "fig.add_trace(\n",- " go.Scatter(x=[velocity_com_z_data[0]], y=[position_com_z_data[0]], mode='markers', marker=dict(symbol='triangle-down', color='red', size=10), name='Start')\n",- ")\n",- "\n",- "# Mark the bottom timestamps\n",- "fig.add_trace(\n",- " go.Scatter(x=velocity_com_z_data[bottom_time_stamps], y=position_com_z_data[bottom_time_stamps], mode='markers', marker=dict(symbol='circle', color='brown', size=10), name='Bottom')\n",- ")\n",- "\n",- "# Mark the apex timestamps\n",- "fig.add_trace(\n",- " go.Scatter(x=velocity_com_z_data[apex_time_stamps], y=position_com_z_data[apex_time_stamps], mode='markers', marker=dict(symbol='circle', color='magenta', size=10), name='Apex')\n",- ")\n",- "\n",- "# Mark the liftoff timestamps\n",- "fig.add_trace(\n",- " go.Scatter(x=velocity_com_z_data[liftoff_time_stamps], y=position_com_z_data[liftoff_time_stamps], mode='markers', marker=dict(symbol='circle', color='green', size=10), name='Lift Off')\n",- ")\n",- "\n",- "# Set axis labels\n",- "fig.update_layout(xaxis_title='velocity', yaxis_title='position')\n",- "fig.update_layout(height=1200, width=600, showlegend=True)\n",- "\n",- "# Show the plot\n",- "fig.show()\n"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/",- "height": 1000- },- "id": "335879ffef8f8362",- "outputId": "ae5b13c1-fc75-4b60-f4bb-993bf7f0a82a",- "ExecuteTime": {- "start_time": "2023-11-12T12:37:22.498587Z"- }- },- "id": "335879ffef8f8362"- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "fig = go.Figure()\n",- "\n",- "# Plot position_com_z_data vs velocity_com_z_data vs acceleration_com_z_data\n",- "fig.add_trace(\n",- " go.Scatter3d(\n",- " x=position_com_z_data,\n",- " y=velocity_com_z_data,\n",- " z=acceleration_com_z_data,\n",- " mode='lines+markers',\n",- " marker=dict(size=2, opacity=0.8),\n",- " name='State Space Data'\n",- " )\n",- ")\n",- "\n",- "# Set axis labels\n",- "fig.update_layout(\n",- " scene=dict(\n",- " xaxis_title='Position COM Z [??]',\n",- " yaxis_title='Velocity COM Z [??]',\n",- " zaxis_title='Acceleration COM Z [??]'\n",- " )\n",- ")\n",- "\n",- "# Show the plot\n",- "fig.show()"- ],- "metadata": {- "colab": {- "base_uri": "https://localhost:8080/",- "height": 542- },- "id": "9f9a49d6c214e75b",- "outputId": "3cac9972-2a93-4a84-db30-71b23bcacfcb",- "ExecuteTime": {- "start_time": "2023-11-12T12:37:22.499330Z"- }- },- "id": "9f9a49d6c214e75b"- }- ],- "metadata": {- "kernelspec": {- "display_name": "Python 3",- "language": "python",- "name": "python3"- },- "language_info": {- "codemirror_mode": {- "name": "ipython",- "version": 2- },- "file_extension": ".py",- "mimetype": "text/x-python",- "name": "python",- "nbconvert_exporter": "python",- "pygments_lexer": "ipython2",- "version": "2.7.6"- },- "colab": {- "provenance": []- }- },- "nbformat": 4,- "nbformat_minor": 5-}diff --git a/freemocap/old/ipython_jupyter_notebooks/__init__.py b/freemocap/old/ipython_jupyter_notebooks/__init__.pydeleted file mode 100644index e69de29b..00000000diff --git a/freemocap/old/ipython_jupyter_notebooks/batch_process_session_folders.ipynb b/freemocap/old/ipython_jupyter_notebooks/batch_process_session_folders.ipynbdeleted file mode 100644index 1bebf0dd..00000000--- a/freemocap/old/ipython_jupyter_notebooks/batch_process_session_folders.ipynb+++ /dev/null@@ -1,213 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "source": [- "# Batch Process multiple freemocap session folders\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "outputs": [],- "source": [- "#get paths to folder full of session folders\n",- "list_of_session_folders = list(path_to_folder_of_session_folders.glob('ses*'))\n",- "print(list_of_session_folders)"- ]- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "#import stuff\n",- "from pathlib import Path\n",- "\n",- "\n",- "from src.core_processes.batch_process_session_folders import process_session_folder\n",- "from src.core_processes.capture_volume_calibration.anipose_camera_calibration import freemocap_anipose\n"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- }- },- {- "cell_type": "markdown",- "source": [- "## input `Path to folder of session folders` HERE\n"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- }- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "\n",- "path_to_folder_of_session_folders = Path(\n",- " r'D:\\Dropbox\\Northeastern\\Courses\\Biol2299\\2022_09_Fall_Biol2299_Inquiries_NeuralControlOfRealWorldBehavior\\freemocap_bos_com_standing_data\\FreeMocap_Data')\n"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- }- },- {- "cell_type": "markdown",- "source": [- "## Input `path_to_camrera_calibration_toml` HERE"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- }- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "\n",- "path_to_camera_calibration_toml = Path(\n",- " r\"D:\\Dropbox\\Northeastern\\Courses\\Biol2299\\2022_09_Fall_Biol2299_Inquiries_NeuralControlOfRealWorldBehavior\\freemocap_bos_com_standing_data\\FreeMocap_Data\\sesh_2022-09-28_15_57_08_calibration\\sesh_2022-09-28_15_57_08_calibration_calibration.toml\"\n",- ")\n"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- }- },- {- "cell_type": "markdown",- "source": [- "## Input `path_to_blender_executable` HERE"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- }- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "path_to_blender_executable = Path(r\"C:\\Program Files\\Blender Foundation\\Blender 3.2\\blender.exe\")"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- }- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "# load anipose calibration object\n",- "anipose_calibration_object = freemocap_anipose.AniposeCameraGroup.load(str(path_to_camera_calibration_toml))"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- }- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "outputs": [],- "source": [- "for session_folder_path in list_of_session_folders:\n",- " print(f'-------------------------Processing {session_folder_path}-------------------------')\n",- " if Path(session_folder_path / \"synchronized_videos\").exists(): # freemocap version > v0.0.54 (aka `alpha`)\n",- " synchronized_videos_folder = Path(session_folder_path) / 'synchronized_videos'\n",- " if Path(session_folder_path / \"SyncedVideos\").exists(): # freemocap version <= v0.0.54 (aka `pre-alpha`)\n",- " synchronized_videos_folder = Path(session_folder_path) / 'SyncedVideos'\n",- " else:\n",- " print(f'No folder full of synchronized videos found for {session_folder_path}')\n",- " continue\n",- "\n",- " output_data_folder = Path(session_folder_path) / 'output_data'\n",- " output_data_folder.mkdir(exist_ok=True, parents=True)\n",- "\n",- " # process session folder via 'standard' freemocap pipeline\n",- " process_session_folder(synchronized_videos_folder=synchronized_videos_folder,\n",- " output_data_folder=output_data_folder,)\n",- "\n",- "print(\"Done!\")"- ]- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- }- }- ],- "metadata": {- "kernelspec": {- "display_name": "Python 3",- "language": "python",- "name": "python3"- },- "language_info": {- "codemirror_mode": {- "name": "ipython",- "version": 2- },- "file_extension": ".py",- "mimetype": "text/x-python",- "name": "python",- "nbconvert_exporter": "python",- "pygments_lexer": "ipython2",- "version": "2.7.6"- }- },- "nbformat": 4,- "nbformat_minor": 0-}diff --git a/freemocap/old/ipython_jupyter_notebooks/export_freemocap_npy_as_pandas_data_frame_csv.ipynb b/freemocap/old/ipython_jupyter_notebooks/export_freemocap_npy_as_pandas_data_frame_csv.ipynbdeleted file mode 100644index 3babc4e9..00000000--- a/freemocap/old/ipython_jupyter_notebooks/export_freemocap_npy_as_pandas_data_frame_csv.ipynb+++ /dev/null@@ -1,516 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "source": [- "\n",- "[](https://colab.research.google.com/github/freemocap/freemocap/blob/jon%2Fnpy_to_csv_ipynb/ipython_jupyter_notebooks/export_freemocap_npy_as_pandas_data_frame_csv.ipynb#scrollTo=xVLt0acPoAks]\n",- "\n",- "# convert standard `freemocap` `npy` output to `pandas.DataFrame` `csv` files\n",- "\n",- "## HOW TO USE\n",- " change the `mediapipe_3d_npy_path` entry down there to the path to the `mediapipe_3d_whatever.npy` file from the session you want to convert\n",- " this notebook will:\n",- " - save out individual `npy` files for the `body`, `hands` and `face` data\n",- " - 'tracked_points' aka 'landmarks' are in the 2nd dimension and follow the order listed here:\n",- " - body - https://google.github.io/mediapipe/solutions/pose.html#pose-landmark-model-blazepose-ghum-3d\n",- " - hands - https://google.github.io/mediapipe/solutions/hands.html#hand-landmark-model\n",- " - face - need to do some work to get that order in any kind of useable state\n",- " - save out individual `csv` files for the `body`, `hands` and `face` data (based on Pandas.DataFrame) with named columns showing the name of the `tracked_points`\n",- "\n",- "\n",- "- [ x ] load in `mediapipe_3d` data from a `freemocap` session\n",- "- [ x ] get tracked_point names from `mediapipe`\n",- "- [ x ] Create `pandas.DataFrame` objects for:\n",- " - [ / ] body_data\n",- " - [ x ] xyz data\n",- " - [ ] reprojection_error data\n",- " - [ x ] right_hand_data\n",- " - [ x ] left_hand_data\n",- " - [ / ] face_data\n",- " - [ x ] face mesh data (i.e. all data points)\n",- " - [ ] face contour data (i.e. only the 'contour' parts of the face"- ]- },- {- "cell_type": "code",- "execution_count": 26,- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "outputs": [],- "source": [- "from pathlib import Path\n",- "import pandas as pd\n",- "import numpy as np\n",- "from mediapipe.python.solutions import holistic as mp_holistic"- ]- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "# Path to the `npy` file containing the `medipipe3d` data for the `freemocap` session you want to export\n",- "mediapipe_3d_npy_path = Path(r\"C:\\Users\\jonma\\freemocap_data\\session_07-26-2022-08_07_30\\output_data_files\\mediapipe_3dData_numFrames_numTrackedPoints_spatialXYZ.npy\") #path to the relevant `mediapipe_3d.npy` file\n"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- }- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "\n",- "\n",- "mediapipe_3d_frame_trackedPoint_xyz = np.load(str(mediapipe_3d_npy_path))\n",- "\n",- "print(f'loaded npy data with shape: {mediapipe_3d_frame_trackedPoint_xyz.shape}')\n"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- }- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "pose_landmark_names = [landmark.name.lower() for landmark in mp_holistic.PoseLandmark]\n",- "hand_landmark_names = [landmark.name.lower() for landmark in mp_holistic.HandLandmark]\n",- "# face_landmark_names = [landmark.name.lower() for landmark in mp_holistic.PoseLandmark] #gonna have the clever for the face\n",- "print(f\"Body tracked point names: {pose_landmark_names}\")\n",- "print(hand_landmark_names)"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- }- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "#get number of points in body, hands, face\n",- "\n",- "number_of_body_points = len(pose_landmark_names)\n",- "number_of_hand_points = len(hand_landmark_names)\n",- "\n",- "first_body_marker_index = 0\n",- "last_body_marker_index = number_of_body_points-1\n",- "\n",- "first_right_hand_marker_index = last_body_marker_index + 1\n",- "last_right_hand_marker_index = number_of_body_points + number_of_hand_points-1\n",- "\n",- "first_left_hand_marker_index = last_right_hand_marker_index + 1\n",- "last_left_hand_marker_index = last_right_hand_marker_index+1 + number_of_hand_points-1\n",- "\n",- "first_face_marker_index = last_left_hand_marker_index + 1\n",- "last_face_marker_index = mediapipe_3d_frame_trackedPoint_xyz.shape[1]\n",- "\n",- "number_of_face_points = last_face_marker_index - first_face_marker_index\n",- "\n",- "print(f\"body tracked point indices: {first_body_marker_index}:{last_body_marker_index}\")\n",- "print(f\"right hand tracked point indices: {first_right_hand_marker_index}:{last_right_hand_marker_index}\")\n",- "print(f\"left hand tracked point indices: {first_left_hand_marker_index}:{last_left_hand_marker_index}\")\n",- "print(f\"face tracked point indices: {first_face_marker_index}:{last_face_marker_index}\")\n",- "\n",- "print(f\"number of body points: {last_body_marker_index-first_body_marker_index+1}\")\n",- "print(f\"number of right hand points: {last_right_hand_marker_index-first_right_hand_marker_index+1}\")\n",- "print(f\"number of left hand points: {last_left_hand_marker_index-first_left_hand_marker_index+1}\")\n",- "print(f\"number of face points: {last_face_marker_index-first_face_marker_index+1}\")\n",- "\n"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- }- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "body_3d_xyz = mediapipe_3d_frame_trackedPoint_xyz[:,first_body_marker_index:last_body_marker_index+1,:]\n",- "right_hand_3d_xyz = mediapipe_3d_frame_trackedPoint_xyz[:,first_right_hand_marker_index:last_right_hand_marker_index+1,:]\n",- "left_hand_3d_xyz = mediapipe_3d_frame_trackedPoint_xyz[:,first_left_hand_marker_index:last_left_hand_marker_index+1,:]\n",- "face_3d_xyz = mediapipe_3d_frame_trackedPoint_xyz[:,first_face_marker_index:last_face_marker_index+1,:]\n",- "\n",- "print(f\"body 3d xyz shape: {body_3d_xyz.shape}\")\n",- "print(f\"right hand 3d xyz shape: {right_hand_3d_xyz.shape}\")\n",- "print(f\"left hand 3d xyz shape: {left_hand_3d_xyz.shape}\")\n",- "print(f\"face 3d xyz shape: {face_3d_xyz.shape}\")"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- }- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "# save broken up npy files\n",- "np.save(str(mediapipe_3d_npy_path.parent / \"mediapipe_body_3d_xyz.npy\"), body_3d_xyz)\n",- "np.save(str(mediapipe_3d_npy_path.parent / \"mediapipe_right_hand_3d_xyz.npy\"), right_hand_3d_xyz)\n",- "np.save(str(mediapipe_3d_npy_path.parent / \"mediapipe_left_hand_3d_xyz.npy\"), left_hand_3d_xyz)\n",- "np.save(str(mediapipe_3d_npy_path.parent / \"mediapipe_face_3d_xyz.npy\"), face_3d_xyz)"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- }- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "# create pandas data frame headers\n",- "\n",- "body_3d_xyz_header = []\n",- "for landmark_name in pose_landmark_names:\n",- " body_3d_xyz_header.append(f\"{landmark_name}_x\")\n",- " body_3d_xyz_header.append(f\"{landmark_name}_y\")\n",- " body_3d_xyz_header.append(f\"{landmark_name}_z\")\n",- "\n",- "right_hand_3d_xyz_header = []\n",- "for landmark_name in hand_landmark_names:\n",- " right_hand_3d_xyz_header.append(f\"right_hand_{landmark_name}_x\")\n",- " right_hand_3d_xyz_header.append(f\"right_hand_{landmark_name}_y\")\n",- " right_hand_3d_xyz_header.append(f\"right_hand_{landmark_name}_z\")\n",- "\n",- "left_hand_3d_xyz_header = []\n",- "for landmark_name in hand_landmark_names:\n",- " left_hand_3d_xyz_header.append(f\"left_hand_{landmark_name}_x\")\n",- " left_hand_3d_xyz_header.append(f\"left_hand_{landmark_name}_y\")\n",- " left_hand_3d_xyz_header.append(f\"left_hand_{landmark_name}_z\")\n",- "\n",- "face_3d_xyz_header = []\n",- "for landmark_number in range(last_face_marker_index - first_face_marker_index):\n",- " face_3d_xyz_header.append(f\"face_{str(landmark_number).zfill(4)}_x\")\n",- " face_3d_xyz_header.append(f\"face_{str(landmark_number).zfill(4)}_y\")\n",- " face_3d_xyz_header.append(f\"face_{str(landmark_number).zfill(4)}_z\")\n",- "\n",- "# print(f\"body 3d xyz header: {body_3d_xyz_header}\")\n",- "# print(f\"right hand 3d xyz header: {right_hand_3d_xyz_header}\")\n",- "# print(f\"left hand 3d xyz header: {left_hand_3d_xyz_header}\")\n",- "# print(f\"face 3d xyz header: {face_3d_xyz_header}\")\n",- "\n",- "print(f\"length of body 3d xyz header: {len(body_3d_xyz_header)}, should be: {number_of_body_points*3}\")\n",- "print(f\"length of right hand 3d xyz header: {len(right_hand_3d_xyz_header)}, should be: {number_of_hand_points*3}\")\n",- "print(f\"length of left hand 3d xyz header: {len(left_hand_3d_xyz_header)}, should be: {number_of_hand_points*3}\")\n",- "print(f\"length of face 3d xyz header: {len(face_3d_xyz_header)}, should be: {number_of_face_points*3}\")"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- }- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [- "number_of_frames = mediapipe_3d_frame_trackedPoint_xyz.shape[0]\n",- "body_flat = body_3d_xyz.reshape(number_of_frames, number_of_body_points*3)\n",- "body_flat.shape\n",- "\n",- "body_dataframe = pd.DataFrame(body_flat, columns=body_3d_xyz_header)\n",- "body_dataframe.to_csv(str(mediapipe_3d_npy_path.parent / \"mediapipe_body_3d_xyz.csv\"), index=False)\n",- "\n",- "right_hand_flat = right_hand_3d_xyz.reshape(number_of_frames, number_of_hand_points*3)\n",- "right_hand_dataframe = pd.DataFrame(right_hand_flat, columns=right_hand_3d_xyz_header)\n",- "right_hand_dataframe.to_csv(str(mediapipe_3d_npy_path.parent / \"mediapipe_right_hand_3d_xyz.csv\"), index=False)\n",- "\n",- "left_hand_flat = left_hand_3d_xyz.reshape(number_of_frames, number_of_hand_points*3)\n",- "left_hand_dataframe = pd.DataFrame(left_hand_flat, columns=left_hand_3d_xyz_header)\n",- "left_hand_dataframe.to_csv(str(mediapipe_3d_npy_path.parent / \"mediapipe_left_hand_3d_xyz.csv\"), index=False)\n",- "\n",- "face_flat = face_3d_xyz.reshape(number_of_frames, number_of_face_points*3)\n",- "face_dataframe = pd.DataFrame(face_flat, columns=face_3d_xyz_header)\n",- "face_dataframe.to_csv(str(mediapipe_3d_npy_path.parent / \"mediapipe_face_3d_xyz.csv\"), index=False)\n"- ],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- }- },- {- "cell_type": "code",- "execution_count": null,- "outputs": [],- "source": [],- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- }- },- {- "cell_type": "code",- "execution_count": 27,- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "Body tracked point names: ['nose', 'left_eye_inner', 'left_eye', 'left_eye_outer', 'right_eye_inner', 'right_eye', 'right_eye_outer', 'left_ear', 'right_ear', 'mouth_left', 'mouth_right', 'left_shoulder', 'right_shoulder', 'left_elbow', 'right_elbow', 'left_wrist', 'right_wrist', 'left_pinky', 'right_pinky', 'left_index', 'right_index', 'left_thumb', 'right_thumb', 'left_hip', 'right_hip', 'left_knee', 'right_knee', 'left_ankle', 'right_ankle', 'left_heel', 'right_heel', 'left_foot_index', 'right_foot_index']\n",- "['wrist', 'thumb_cmc', 'thumb_mcp', 'thumb_ip', 'thumb_tip', 'index_finger_mcp', 'index_finger_pip', 'index_finger_dip', 'index_finger_tip', 'middle_finger_mcp', 'middle_finger_pip', 'middle_finger_dip', 'middle_finger_tip', 'ring_finger_mcp', 'ring_finger_pip', 'ring_finger_dip', 'ring_finger_tip', 'pinky_mcp', 'pinky_pip', 'pinky_dip', 'pinky_tip']\n"- ]- }- ],- "source": [- "pose_landmark_names = [landmark.name.lower() for landmark in mp_holistic.PoseLandmark]\n",- "hand_landmark_names = [landmark.name.lower() for landmark in mp_holistic.HandLandmark]\n",- "# face_landmark_names = [landmark.name.lower() for landmark in mp_holistic.PoseLandmark] #gonna have the clever for the face\n",- "print(f\"Body tracked point names: {pose_landmark_names}\")\n",- "print(hand_landmark_names)"- ]- },- {- "cell_type": "code",- "execution_count": 29,- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "body tracked point indices: 0:32\n",- "right hand tracked point indices: 33:53\n",- "left hand tracked point indices: 54:74\n",- "face tracked point indices: 75:553\n",- "number of body points: 33\n",- "number of right hand points: 21\n",- "number of left hand points: 21\n",- "number of face points: 479\n"- ]- }- ],- "source": [- "#get number of points in body, hands, face\n",- "\n",- "number_of_body_points = len(pose_landmark_names)\n",- "number_of_hand_points = len(hand_landmark_names)\n",- "\n",- "first_body_marker_index = 0\n",- "last_body_marker_index = number_of_body_points-1\n",- "\n",- "first_right_hand_marker_index = last_body_marker_index + 1\n",- "last_right_hand_marker_index = number_of_body_points + number_of_hand_points-1\n",- "\n",- "first_left_hand_marker_index = last_right_hand_marker_index + 1\n",- "last_left_hand_marker_index = last_right_hand_marker_index+1 + number_of_hand_points-1\n",- "\n",- "first_face_marker_index = last_left_hand_marker_index + 1\n",- "last_face_marker_index = mediapipe_3d_frame_trackedPoint_xyz.shape[1]\n",- "\n",- "number_of_face_points = last_face_marker_index - first_face_marker_index\n",- "\n",- "print(f\"body tracked point indices: {first_body_marker_index}:{last_body_marker_index}\")\n",- "print(f\"right hand tracked point indices: {first_right_hand_marker_index}:{last_right_hand_marker_index}\")\n",- "print(f\"left hand tracked point indices: {first_left_hand_marker_index}:{last_left_hand_marker_index}\")\n",- "print(f\"face tracked point indices: {first_face_marker_index}:{last_face_marker_index}\")\n",- "\n",- "print(f\"number of body points: {last_body_marker_index-first_body_marker_index+1}\")\n",- "print(f\"number of right hand points: {last_right_hand_marker_index-first_right_hand_marker_index+1}\")\n",- "print(f\"number of left hand points: {last_left_hand_marker_index-first_left_hand_marker_index+1}\")\n",- "print(f\"number of face points: {last_face_marker_index-first_face_marker_index+1}\")\n",- "\n"- ]- },- {- "cell_type": "code",- "execution_count": 30,- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "body 3d xyz shape: (375, 33, 3)\n",- "right hand 3d xyz shape: (375, 21, 3)\n",- "left hand 3d xyz shape: (375, 21, 3)\n",- "face 3d xyz shape: (375, 478, 3)\n"- ]- }- ],- "source": [- "body_3d_xyz = mediapipe_3d_frame_trackedPoint_xyz[:,first_body_marker_index:last_body_marker_index+1,:]\n",- "right_hand_3d_xyz = mediapipe_3d_frame_trackedPoint_xyz[:,first_right_hand_marker_index:last_right_hand_marker_index+1,:]\n",- "left_hand_3d_xyz = mediapipe_3d_frame_trackedPoint_xyz[:,first_left_hand_marker_index:last_left_hand_marker_index+1,:]\n",- "face_3d_xyz = mediapipe_3d_frame_trackedPoint_xyz[:,first_face_marker_index:last_face_marker_index+1,:]\n",- "\n",- "print(f\"body 3d xyz shape: {body_3d_xyz.shape}\")\n",- "print(f\"right hand 3d xyz shape: {right_hand_3d_xyz.shape}\")\n",- "print(f\"left hand 3d xyz shape: {left_hand_3d_xyz.shape}\")\n",- "print(f\"face 3d xyz shape: {face_3d_xyz.shape}\")"- ]- },- {- "cell_type": "code",- "execution_count": 31,- "metadata": {},- "outputs": [],- "source": [- "# save broken up npy files\n",- "np.save(str(mediapipe_3d_npy_path.parent / \"mediapipe_body_3d_xyz.npy\"), body_3d_xyz)\n",- "np.save(str(mediapipe_3d_npy_path.parent / \"mediapipe_right_hand_3d_xyz.npy\"), right_hand_3d_xyz)\n",- "np.save(str(mediapipe_3d_npy_path.parent / \"mediapipe_left_hand_3d_xyz.npy\"), left_hand_3d_xyz)\n",- "np.save(str(mediapipe_3d_npy_path.parent / \"mediapipe_face_3d_xyz.npy\"), face_3d_xyz)"- ]- },- {- "cell_type": "code",- "execution_count": 32,- "metadata": {},- "outputs": [- {- "name": "stdout",- "output_type": "stream",- "text": [- "length of body 3d xyz header: 99, should be: 99\n",- "length of right hand 3d xyz header: 63, should be: 63\n",- "length of left hand 3d xyz header: 63, should be: 63\n",- "length of face 3d xyz header: 1434, should be: 1434\n"- ]- }- ],- "source": [- "# create pandas data frame headers\n",- "\n",- "body_3d_xyz_header = []\n",- "for landmark_name in pose_landmark_names:\n",- " body_3d_xyz_header.append(f\"{landmark_name}_x\")\n",- " body_3d_xyz_header.append(f\"{landmark_name}_y\")\n",- " body_3d_xyz_header.append(f\"{landmark_name}_z\")\n",- "\n",- "right_hand_3d_xyz_header = []\n",- "for landmark_name in hand_landmark_names:\n",- " right_hand_3d_xyz_header.append(f\"right_hand_{landmark_name}_x\")\n",- " right_hand_3d_xyz_header.append(f\"right_hand_{landmark_name}_y\")\n",- " right_hand_3d_xyz_header.append(f\"right_hand_{landmark_name}_z\")\n",- "\n",- "left_hand_3d_xyz_header = []\n",- "for landmark_name in hand_landmark_names:\n",- " left_hand_3d_xyz_header.append(f\"left_hand_{landmark_name}_x\")\n",- " left_hand_3d_xyz_header.append(f\"left_hand_{landmark_name}_y\")\n",- " left_hand_3d_xyz_header.append(f\"left_hand_{landmark_name}_z\")\n",- "\n",- "face_3d_xyz_header = []\n",- "for landmark_number in range(last_face_marker_index - first_face_marker_index):\n",- " face_3d_xyz_header.append(f\"face_{str(landmark_number).zfill(4)}_x\")\n",- " face_3d_xyz_header.append(f\"face_{str(landmark_number).zfill(4)}_y\")\n",- " face_3d_xyz_header.append(f\"face_{str(landmark_number).zfill(4)}_z\")\n",- "\n",- "# print(f\"body 3d xyz header: {body_3d_xyz_header}\")\n",- "# print(f\"right hand 3d xyz header: {right_hand_3d_xyz_header}\")\n",- "# print(f\"left hand 3d xyz header: {left_hand_3d_xyz_header}\")\n",- "# print(f\"face 3d xyz header: {face_3d_xyz_header}\")\n",- "\n",- "print(f\"length of body 3d xyz header: {len(body_3d_xyz_header)}, should be: {number_of_body_points*3}\")\n",- "print(f\"length of right hand 3d xyz header: {len(right_hand_3d_xyz_header)}, should be: {number_of_hand_points*3}\")\n",- "print(f\"length of left hand 3d xyz header: {len(left_hand_3d_xyz_header)}, should be: {number_of_hand_points*3}\")\n",- "print(f\"length of face 3d xyz header: {len(face_3d_xyz_header)}, should be: {number_of_face_points*3}\")"- ]- },- {- "cell_type": "code",- "execution_count": 33,- "metadata": {},- "outputs": [],- "source": [- "number_of_frames = mediapipe_3d_frame_trackedPoint_xyz.shape[0]\n",- "body_flat = body_3d_xyz.reshape(number_of_frames, number_of_body_points*3)\n",- "body_flat.shape\n",- "\n",- "body_dataframe = pd.DataFrame(body_flat, columns=body_3d_xyz_header)\n",- "body_dataframe.to_csv(str(mediapipe_3d_npy_path.parent / \"mediapipe_body_3d_xyz.csv\"), index=False)\n",- "\n",- "right_hand_flat = right_hand_3d_xyz.reshape(number_of_frames, number_of_hand_points*3)\n",- "right_hand_dataframe = pd.DataFrame(right_hand_flat, columns=right_hand_3d_xyz_header)\n",- "right_hand_dataframe.to_csv(str(mediapipe_3d_npy_path.parent / \"mediapipe_right_hand_3d_xyz.csv\"), index=False)\n",- "\n",- "left_hand_flat = left_hand_3d_xyz.reshape(number_of_frames, number_of_hand_points*3)\n",- "left_hand_dataframe = pd.DataFrame(left_hand_flat, columns=left_hand_3d_xyz_header)\n",- "left_hand_dataframe.to_csv(str(mediapipe_3d_npy_path.parent / \"mediapipe_left_hand_3d_xyz.csv\"), index=False)\n",- "\n",- "face_flat = face_3d_xyz.reshape(number_of_frames, number_of_face_points*3)\n",- "face_dataframe = pd.DataFrame(face_flat, columns=face_3d_xyz_header)\n",- "face_dataframe.to_csv(str(mediapipe_3d_npy_path.parent / \"mediapipe_face_3d_xyz.csv\"), index=False)\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": []- }- ],- "metadata": {- "kernelspec": {- "display_name": "Python 3.9.12 ('fmc-endurance')",- "language": "python",- "name": "python3"- },- "language_info": {- "codemirror_mode": {- "name": "ipython",- "version": 3- },- "file_extension": ".py",- "mimetype": "text/x-python",- "name": "python",- "nbconvert_exporter": "python",- "pygments_lexer": "ipython3",- "version": "3.9.12"- },- "vscode": {- "interpreter": {- "hash": "faaa4718f81dea544b1eec21b9b5977abdad8a3ae32c87c23f8249d29cfa9e11"- }- }- },- "nbformat": 4,- "nbformat_minor": 0-}\ No newline at end of filediff --git a/freemocap/old/ipython_jupyter_notebooks/rotate_translate_skeleton.ipynb b/freemocap/old/ipython_jupyter_notebooks/rotate_translate_skeleton.ipynbdeleted file mode 100644index a82b5a52..00000000--- a/freemocap/old/ipython_jupyter_notebooks/rotate_translate_skeleton.ipynb+++ /dev/null@@ -1,333 +0,0 @@-{- "cells": [- {- "cell_type": "code",- "execution_count": 6,- "metadata": {- "collapsed": true,- "pycharm": {- "name": "#%%\n"- }- },- "outputs": [],- "source": [- "import numpy as np\n",- "import pandas as pd\n",- "from pathlib import Path\n",- "from mediapipe.python.solutions import holistic as mp_holistic"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "outputs": [],- "source": [- "#load original skeleton / center_of_mass data\n",- "session_path = Path(r\"D:\\Dropbox\\FreeMoCapProject\\FreeMocap_Data\\sesh_2022-11-09_20_38_23_neurons_demo\")\n",- "output_data_path = session_path / \"DataArrays\"\n",- "og_skeleton_npy_file_name = \"mediapipe_body_3d_xyz.npy\"\n",- "og_skeleton_npy_path = output_data_path / og_skeleton_npy_file_name\n",- "\n",- "original_skeleton_frame_marker_xyz = np.load(og_skeleton_npy_path) / 1000 #convert to meters (b/c that's Blender's unit, which is where we got the transformation matrix)\n",- "number_of_frames = original_skeleton_frame_marker_xyz.shape[0]\n",- "number_of_markers = original_skeleton_frame_marker_xyz.shape[1]\n",- "\n",- "# load center_of_mass data\n",- "og_center_of_mass_npy_file_name = \"totalBodyCOM_frame_XYZ.npy\"\n",- "original_center_of_mass_xyz = np.load(output_data_path / og_center_of_mass_npy_file_name) / 1000"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "outputs": [],- "source": [- "#to get this data,\n",- "# - open `.blend` file (or run `src/blender_stuff/load_npy_as_empties.py`),\n",- "# - rotate skeleton until it looks good, then ... \n",- "# - enter `bpy.data.objects['freemocap_origin_axes'].matrix_world` into console\n",- "# - copy the output into the `transformation_matrix` variable below (changing ()'s to []'s)\n",- "\n",- "transformation_matrix = \\\n",- "[[0.8891741633415222, -0.4202311933040619, -0.181038960814476, 0.07594677060842514],\n",- "[0.40811246633529663, 0.9072690606117249, -0.10152354836463928, 0.0],\n",- "[0.20691442489624023, 0.016387859359383583, 0.9782217741012573, 0.14920693635940552],\n",- "[0.0, 0.0, 0.0, 1.0]]"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "outputs": [],- "source": [- "transformed_skeleton_frame_marker_xyz = np.zeros_like(original_skeleton_frame_marker_xyz)\n",- "transformed_center_of_mass_frame_xyz = np.zeros((number_of_frames, 3))\n",- "\n",- "for frame_number in range(number_of_frames):\n",- " \n",- " transformed_com_xyzw = transformation_matrix @ np.append(original_center_of_mass_xyz[frame_number], 1)\n",- " transformed_center_of_mass_frame_xyz[frame_number] = transformed_com_xyzw[:3]\n",- "\n",- " for marker_number in range(number_of_markers):\n",- " point_xyz = original_skeleton_frame_marker_xyz[frame_number, marker_number, :]\n",- " point_xyzw = np.append(point_xyz, 1)\n",- " transformed_point_xyzw = transformation_matrix @ point_xyzw\n",- " transformed_point_xyz = transformed_point_xyzw[:3]\n",- " transformed_skeleton_frame_marker_xyz[frame_number, marker_number, : ] = transformed_point_xyz\n",- "\n",- "print(f\"transformed_skeleton_frame_marker_xyz.shape: {transformed_skeleton_frame_marker_xyz.shape}\")\n",- "\n",- "#convert back to mm\n",- "original_skeleton_frame_marker_xyz *= 1000\n",- "original_center_of_mass_xyz *= 1000\n",- "\n",- "transformed_skeleton_frame_marker_xyz*= 1000\n",- "transformed_center_of_mass_frame_xyz *= 1000\n",- "\n",- "\n",- "np.save(output_data_path / \"mediapipe_body_3d_xyz_transformed.npy\", transformed_skeleton_frame_marker_xyz)"- ]- },- {- "cell_type": "markdown",- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%% md\n"- }- },- "source": [- "# Now we test if it works by plotting COM projection onto XZ (ground) plane relative to the base of support (i.e. the right toe and heel markers)"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "outputs": [],- "source": [- "import matplotlib.pyplot as plt\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "outputs": [],- "source": [- "# get_relevant marker data out\n",- "mediapipe_body_landmark_names = [\n",- " landmark.name.lower() for landmark in mp_holistic.PoseLandmark\n",- "]\n",- "\n",- "# original data\n",- "original_right_heel_x = original_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"right_heel\"),0]\n",- "original_right_heel_y = original_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"right_heel\"),1]\n",- "original_right_heel_z = original_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"right_heel\"),2]\n",- "\n",- "original_right_toe_x = original_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"right_foot_index\"),0]\n",- "original_right_toe_y = original_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"right_foot_index\"),1]\n",- "original_right_toe_z = original_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"right_foot_index\"),2]\n",- "\n",- "original_left_heel_x = original_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"left_heel\"),0]\n",- "original_left_heel_y = original_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"left_heel\"),1]\n",- "original_left_heel_z = original_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"left_heel\"),2]\n",- "\n",- "original_left_toe_x = original_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"left_foot_index\"),0]\n",- "original_left_toe_y = original_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"left_foot_index\"),1]\n",- "original_left_toe_z = original_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"left_foot_index\"),2]\n",- "\n",- "\n",- "# transformed data\n",- "transformed_right_heel_x = transformed_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"right_heel\"),0]\n",- "transformed_right_heel_y = transformed_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"right_heel\"),1]\n",- "transformed_right_heel_z = transformed_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"right_heel\"),2]\n",- "\n",- "transformed_right_toe_x = transformed_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"right_foot_index\"),0]\n",- "transformed_right_toe_y = transformed_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"right_foot_index\"),1]\n",- "transformed_right_toe_z = transformed_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"right_foot_index\"),2]\n",- "\n",- "transformed_left_heel_x = transformed_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"left_heel\"),0]\n",- "transformed_left_heel_y = transformed_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"left_heel\"),1]\n",- "transformed_left_heel_z = transformed_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"left_heel\"),2]\n",- "\n",- "transformed_left_toe_x = transformed_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"left_foot_index\"),0]\n",- "transformed_left_toe_y = transformed_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"left_foot_index\"),1]\n",- "transformed_left_toe_z = transformed_skeleton_frame_marker_xyz[:, mediapipe_body_landmark_names.index(\"left_foot_index\"),2]\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "outputs": [],- "source": [- "\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "outputs": [],- "source": [- "# check via bos/com\n",- "#identify relevant frames\n",- "standing_on_right_foot_frame_start = 431 #watched the output `mp4` for frame numbers\n",- "standing_on_right_foot_frame_end = 470\n",- "frames_of_interest = np.arange(standing_on_right_foot_frame_start, standing_on_right_foot_frame_end)\n"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "outputs": [],- "source": [- "\n",- "def normalize_axes_2d(axis):\n",- " x_range = axis.get_xlim()[1] - axis.get_xlim()[0]\n",- " y_range = axis.get_ylim()[1] - axis.get_ylim()[0]\n",- " \n",- " if x_range > y_range:\n",- " axis.set_ylim(axis.get_ylim()[0], axis.get_ylim()[0] + x_range)\n",- " else:\n",- " axis.set_xlim(axis.get_xlim()[0], axis.get_xlim()[0] + y_range)\n",- " return axis\n",- "\n",- "figure = plt.figure(figsize=(10,10))\n",- "\n",- "## plot original data (Time series)\n",- "ax1 = figure.add_subplot(221)\n",- "ax1.set_title(\"Original data - timeseries\")\n",- "ax1.plot(original_right_heel_x, label=\"original right heel x\")\n",- "ax1.plot(original_right_heel_y, label=\"original right heel y\")\n",- "ax1.plot(original_right_heel_z, label=\"original right heel z\")\n",- "ax1.legend()\n",- "\n",- "\n",- "## plot original data (on XZ (ground) plane)\n",- "ax2 = figure.add_subplot(222)\n",- "ax2.set_title(\"Original data - center of mass vs base of support\")\n",- "ax2.plot(original_right_toe_x[frames_of_interest], original_right_toe_y[frames_of_interest], '.-', label=\"original right toe\", color=\"darkred\")\n",- "ax2.plot(original_right_heel_x[frames_of_interest], original_right_heel_y[frames_of_interest], 'o-', label=\"original right heel\", color=\"darkred\")\n",- "\n",- "ax2.plot(original_left_toe_x[frames_of_interest], original_left_toe_y[frames_of_interest], '.-', label=\"original left toe\", color=\"darkblue\")\n",- "ax2.plot(original_left_heel_x[frames_of_interest], original_left_heel_y[frames_of_interest], 'o-', label=\"original left heel\", color=\"darkblue\")\n",- "\n",- "ax2.plot(com_x[frames_of_interest], com_y[frames_of_interest], 'o-', label=\"center of mass\", color=\"xkcd:dark sea green\")\n",- "\n",- "ax2 = normalize_axes_2d(ax2)\n",- "ax2.legend()\n",- "\n",- "\n",- "## plot transformed data (Time series)\n",- "ax3 = figure.add_subplot(223)\n",- "ax3.set_title(\"Transformed data - timeseries\")\n",- "ax3.plot(transformed_right_heel_x, label=\"transformed right heel x\")\n",- "ax3.plot(transformed_right_heel_y, label=\"transformed right heel y\")\n",- "ax3.plot(transformed_right_heel_z, label=\"transformed right heel z\")\n",- "ax3.legend()\n",- "\n",- "## plot transformed data (on XZ (ground) plane)\n",- "ax4 = figure.add_subplot(224)\n",- "ax4.set_title(\"Transformed data - center of mass vs base of support\")\n",- "ax4.plot(transformed_right_toe_x[frames_of_interest], transformed_right_toe_y[frames_of_interest], '.-', label=\"transformed right toe\", color=\"darkred\")\n",- "ax4.plot(transformed_right_heel_x[frames_of_interest], transformed_right_heel_y[frames_of_interest], 'o-', label=\"transformed right heel\", color=\"darkred\")\n",- "\n",- "ax4.plot(transformed_left_toe_x[frames_of_interest], transformed_left_toe_y[frames_of_interest], '.-', label=\"transformed left toe\", color=\"darkblue\")\n",- "ax4.plot(transformed_left_heel_x[frames_of_interest], transformed_left_heel_y[frames_of_interest], 'o-', label=\"transformed left heel\", color=\"darkblue\")\n",- "\n",- "ax4.plot(transformed_center_of_mass_frame_xyz[frames_of_interest,0], transformed_center_of_mass_frame_xyz[frames_of_interest,1], 'o-', label=\"center of mass\", color=\"xkcd:dark sea green\")\n",- "\n",- "ax4 = normalize_axes_2d(ax4)\n",- "\n",- "ax4.legend()\n",- "\n",- "\n",- "plt.show()"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {- "collapsed": false,- "pycharm": {- "name": "#%%\n"- }- },- "outputs": [],- "source": []- }- ],- "metadata": {- "kernelspec": {- "display_name": "Python 3.9.12 ('freemocap-endurance')",- "language": "python",- "name": "python3"- },- "language_info": {- "codemirror_mode": {- "name": "ipython",- "version": 3- },- "file_extension": ".py",- "mimetype": "text/x-python",- "name": "python",- "nbconvert_exporter": "python",- "pygments_lexer": "ipython3",- "version": "3.9.12 (main, Apr 4 2022, 05:22:27) [MSC v.1916 64 bit (AMD64)]"- },- "vscode": {- "interpreter": {- "hash": "13279345b754ebd3bebf437090ccc748537e92f8f2c3ba4d096a903b73831ba1"- }- }- },- "nbformat": 4,- "nbformat_minor": 0-}diff --git a/freemocap/old/data_layer/data_saver/__init__.py b/freemocap/pubsub/__init__.pysimilarity index 100%rename from freemocap/old/data_layer/data_saver/__init__.pyrename to freemocap/pubsub/__init__.pydiff --git a/freemocap/pubsub/pubsub_abcs.py b/freemocap/pubsub/pubsub_abcs.pynew file mode 100644index 00000000..1d1d8c32--- /dev/null+++ b/freemocap/pubsub/pubsub_abcs.py@@ -0,0 +1,103 @@+import logging+from typing import TypeVar, Generic, Callable, ClassVar++from pydantic import BaseModel, Field, ConfigDict, create_model++from freemocap.core.types.type_overloads import TopicPublicationQueue, TopicSubscriptionQueue++logger = logging.getLogger(__name__)+++class TopicMessageABC(BaseModel):+ """Base for all message data models."""+ model_config = ConfigDict(+ arbitrary_types_allowed=True,+ frozen=True+ )+++# MessageType represents "any type that is a subclass of TopicMessageABC"+# This allows each topic to be strongly typed with its specific message type+# e.g., PubSubTopicABC[TestMessage] means "a topic that handles TestMessage"+MessageType = TypeVar('MessageType', bound=TopicMessageABC)+++class PubSubTopicABC(BaseModel, Generic[MessageType]):+ """Base pub/sub topic with default behavior."""+ topic_registry: ClassVar[set[type['PubSubTopicABC']]] = set()++ message_type: type[TopicMessageABC]+ publication: TopicPublicationQueue = Field(default_factory=TopicPublicationQueue)+ subscriptions: list[TopicSubscriptionQueue] = Field(default_factory=list)++ model_config = ConfigDict(arbitrary_types_allowed=True)++ def __init_subclass__(cls, **kwargs) -> None:+ """Auto-register when subclassed."""+ super().__init_subclass__(**kwargs)+ if not cls.__name__.startswith('_'): # Skip private/base classes+ PubSubTopicABC.topic_registry.add(cls)++ @classmethod+ def get_registered_topics(cls) -> set[type['PubSubTopicABC']]:+ return cls.topic_registry.copy()++ def get_subscription(self) -> TopicSubscriptionQueue:+ sub = TopicSubscriptionQueue()+ self.subscriptions.append(sub)+ return sub++ def publish(self, message: MessageType) -> None:+ if not isinstance(message, self.message_type):+ raise TypeError(f"Message must be of type {self.message_type.__name__}, got {type(message).__name__}")+ self.publication.put(message)+ for sub in self.subscriptions:+ sub.put(message)++ def close(self) -> None:+ if hasattr(self.publication, 'close'):+ self.publication.close()+ for sub in self.subscriptions:+ if hasattr(sub, 'close'):+ sub.close()+ self.subscriptions.clear()+++# ============================================================================+# Factory Function - Eliminates Boilerplate Using Pydantic's create_model+# ============================================================================++def create_topic(+ message_type: type[MessageType],+ publication_factory: Callable[[], TopicPublicationQueue] | None = None,+) -> type[PubSubTopicABC[MessageType]]:+ """+ Factory that creates a topic class for a message type.++ Uses Pydantic's create_model() to properly create the class.+ Returns a class (not instance) so it auto-registers via __init_subclass__.+ """+ topic_name = message_type.__name__.replace('Message', 'Topic')++ # Build field definitions for create_model+ # Format: field_name=(type, Field(...))+ field_definitions: dict[str, object] = {+ 'message_type': (type[MessageType], message_type),+ }++ # Add custom publication factory if provided+ if publication_factory is not None:+ field_definitions['publication'] = (+ TopicPublicationQueue,+ Field(default_factory=publication_factory)+ )++ # Use Pydantic's create_model - the proper v2 way!+ topic_class = create_model(+ topic_name,+ __base__=PubSubTopicABC,+ __module__=message_type.__module__,+ **field_definitions+ )++ return topic_classdiff --git a/freemocap/pubsub/pubsub_manager.py b/freemocap/pubsub/pubsub_manager.pynew file mode 100644index 00000000..2393b14e--- /dev/null+++ b/freemocap/pubsub/pubsub_manager.py@@ -0,0 +1,112 @@+# ============================================================================+# PubSubTopicManager - Auto-discovers and manages all registered topics+# ============================================================================++import logging+from multiprocessing import parent_process++from pydantic import BaseModel, Field, ConfigDict++from freemocap.core.types.type_overloads import TopicSubscriptionQueue, PipelineIdString+from freemocap.pubsub.pubsub_abcs import PubSubTopicABC, MessageType++logger = logging.getLogger(__name__)+++class PubSubTopicManager(BaseModel):+ """+ Manager for pub/sub topics. Auto-instantiates all registered topic classes.++ Usage:+ manager = PubSubTopicManager.create()+ sub = manager.get_subscription(ProcessFrameNumberTopic)+ manager.publish(ProcessFrameNumberTopic, message)+ """++ # Dict maps topic classes to their instances: {ProcessFrameNumberTopic: <instance>}+ topics: dict[type[PubSubTopicABC], PubSubTopicABC] = Field(default_factory=dict)++ model_config = ConfigDict(arbitrary_types_allowed=True)++ @classmethod+ def create(cls) -> "PubSubTopicManager":+ """Factory method: creates manager and auto-instantiates all registered topics."""+ manager = cls()+ for topic_cls in PubSubTopicABC.get_registered_topics():+ manager.topics[topic_cls] = topic_cls()+ logger.debug(f"Instantiated topic: {topic_cls.__name__}")+ return manager++ def get_subscription(self, topic_type: type[PubSubTopicABC]) -> TopicSubscriptionQueue:+ """+ Get a subscription queue for a topic.++ Args:+ topic_type: The topic CLASS (e.g., ProcessFrameNumberTopic)+ """+ if parent_process() is not None:+ raise RuntimeError("Subscriptions must be created in the main process and passed to children")++ if topic_type not in self.topics:+ raise ValueError(+ f"Unknown topic type: {topic_type.__name__}. "+ f"Available topics: {[t.__name__ for t in self.topics.keys()]}"+ )++ sub = self.topics[topic_type].get_subscription()+ logger.trace(+ f"Subscribed to topic {topic_type.__name__} "+ f"with {len(self.topics[topic_type].subscriptions)} subscriptions"+ )+ return sub++ def publish(+ self,+ topic_type: type[PubSubTopicABC[MessageType]],+ message: MessageType+ ) -> None:+ """+ Publish a message to a topic.++ Args:+ topic_type: The topic CLASS to publish to+ message: The message to publish+ """+ if topic_type not in self.topics:+ raise ValueError(+ f"Unknown topic type: {topic_type.__name__}. "+ f"Available topics: {[t.__name__ for t in self.topics.keys()]}"+ )++ self.topics[topic_type].publish(message)++ def close(self) -> None:+ """Close all topics in the manager."""+ logger.debug("Closing PubSubTopicManager...")+ for topic in self.topics.values():+ topic.close()+ self.topics.clear()+ logger.debug("PubSubTopicManager closed.")+++# ============================================================================+# Global pipeline manager registry+# ============================================================================++PIPELINE_PUB_SUB_MANAGERS: dict[PipelineIdString, PubSubTopicManager] = {}+++def create_pipeline_pubsub_manager(pipeline_id: PipelineIdString) -> PubSubTopicManager:+ """Create/replace manager for a pipeline. Must be called from main process."""+ global PIPELINE_PUB_SUB_MANAGERS++ if parent_process() is not None:+ raise RuntimeError("PubSubManager can only be created in the main process.")++ if PIPELINE_PUB_SUB_MANAGERS.get(pipeline_id) is not None:+ logger.debug(f"Closing existing PubSubManager for pipeline {pipeline_id}")+ PIPELINE_PUB_SUB_MANAGERS[pipeline_id].close()++ logger.debug(f"Creating PubSubManager for pipeline {pipeline_id}")+ PIPELINE_PUB_SUB_MANAGERS[pipeline_id] = PubSubTopicManager.create()+ return PIPELINE_PUB_SUB_MANAGERS[pipeline_id]diff --git a/freemocap/pubsub/pubsub_topics.py b/freemocap/pubsub/pubsub_topics.pynew file mode 100644index 00000000..5c845c5d--- /dev/null+++ b/freemocap/pubsub/pubsub_topics.py@@ -0,0 +1,104 @@+import logging++from pydantic import Field, model_validator+from skellycam.core.types.type_overloads import CameraGroupIdString, CameraIdString+from skellytracker.trackers.mediapipe_tracker.mediapipe_observation import MediapipeObservation+from skellytracker.trackers.charuco_tracker.charuco_observation import CharucoObservation+from skellytracker.trackers.base_tracker.base_tracker_abcs import BaseObservation+from freemocap.core.image_overlay.charuco_overlay_data import CharucoOverlayData+from freemocap.core.image_overlay.mediapipe_overlay_data import MediapipeOverlayData++from freemocap.core.pipeline.pipeline_configs import RealtimePipelineConfig+from freemocap.core.types.type_overloads import FrameNumberInt, PipelineIdString, VideoIdString, \+ TrackedPointNameString+from freemocap.pubsub.pubsub_abcs import TopicMessageABC, create_topic++from skellyforge.data_models.trajectory_3d import Point3d+logger = logging.getLogger(__name__)+++class ProcessFrameNumberMessage(TopicMessageABC):+ frame_number: int = Field(ge=0, description="Frame number to process")+++class PipelineConfigUpdateMessage(TopicMessageABC):+ pipeline_config: RealtimePipelineConfig+++class CameraNodeOutputMessage(TopicMessageABC):+ camera_id: CameraIdString+ frame_number: FrameNumberInt = Field(ge=0)+ observation: BaseObservation++class VideoNodeOutputMessage(TopicMessageABC):+ video_id: VideoIdString+ frame_number: FrameNumberInt = Field(ge=0)+ observation: BaseObservation++class AggregationNodeOutputMessage(TopicMessageABC):+ frame_number: FrameNumberInt = Field(ge=0)+ pipeline_id: PipelineIdString+ camera_group_id: CameraGroupIdString+ pipeline_config: RealtimePipelineConfig+ camera_node_outputs: dict[CameraIdString, CameraNodeOutputMessage]+ tracked_points3d: dict[TrackedPointNameString, Point3d] = Field(default_factory=dict)++ @model_validator(mode='after')+ def validate(self) -> 'AggregationNodeOutputMessage':+ # ensure that camera_node_outputs keys match camera IDs in pipeline_config+ expected_camera_ids = set(self.pipeline_config.camera_configs.keys())+ actual_camera_ids = set(self.camera_node_outputs.keys())+ if sorted(expected_camera_ids) != sorted(actual_camera_ids):+ raise ValueError(+ f"Camera IDs in camera_node_outputs {actual_camera_ids} do not match expected camera IDs from pipeline_config {expected_camera_ids}")+ # make sure camera_node_outputs all have the same frame_number as this message+ for cam_output in self.camera_node_outputs.values():+ if cam_output.frame_number != self.frame_number:+ logger.warning(+ f"CameraNodeOutputMessage for camera {cam_output.camera_id} has frame number {cam_output.frame_number} which does not match AggregationNodeOutputMessage frame number {self.frame_number}")+ return self++ @property+ def charuco_overlay_data(self) -> dict[CameraIdString, CharucoOverlayData]:+ overlay_data: dict[CameraIdString, CharucoOverlayData] = {}+ for camera_id, cam_output in self.camera_node_outputs.items():+ if cam_output.observation is not None and isinstance(cam_output.observation, CharucoObservation):+ overlay_data[camera_id] = CharucoOverlayData.from_charuco_observation(+ camera_id=camera_id,+ observation=cam_output.observation,+ )+ return overlay_data++ @property+ def mediapipe_overlay_data(self) -> dict[CameraIdString, MediapipeOverlayData]:+ overlay_data: dict[CameraIdString, MediapipeOverlayData] = {}+ for camera_id, cam_output in self.camera_node_outputs.items():+ if cam_output.observation is not None and isinstance(cam_output.observation, MediapipeObservation):+ overlay_data[camera_id] = MediapipeOverlayData.from_mediapipe_observation(+ camera_id=camera_id,+ observation=cam_output.observation,+ )+ return overlay_data++ @property+ def camera_ids(self) -> list[CameraIdString]:+ return list(self.camera_node_outputs.keys())+++class StartRealtimeCalibrationTrackingMessage(TopicMessageABC):+ """Message to signal that realtime calibration tracking should start."""+ pass+++class ShouldCalibrateMessage(TopicMessageABC):+ """Dummy message to signal that calibration should be performed."""+ pass+++ProcessFrameNumberTopic = create_topic(ProcessFrameNumberMessage)+ShouldCalibrateTopic = create_topic(ShouldCalibrateMessage)+PipelineConfigUpdateTopic = create_topic(PipelineConfigUpdateMessage)+CameraNodeOutputTopic = create_topic(CameraNodeOutputMessage)+VideoNodeOutputTopic = create_topic(VideoNodeOutputMessage)+AggregationNodeOutputTopic = create_topic(AggregationNodeOutputMessage)+StartRealtimeCalibrationTrackingTopic = create_topic(StartRealtimeCalibrationTrackingMessage)diff --git a/freemocap/run_freemocap_server.py b/freemocap/run_freemocap_server.pydeleted file mode 100644index d9773cd6..00000000--- a/freemocap/run_freemocap_server.py+++ /dev/null@@ -1,33 +0,0 @@-import logging-import multiprocessing-import sys-import time--from freemocap.api.server.server_manager import UvicornServerManager-from freemocap.api.server.server_singleton import create_server_manager-from freemocap.utilities.setup_windows_app_id import setup_app_id_for_windows--logger = logging.getLogger(__name__)---def run_freemocap_server(global_kill_flag: multiprocessing.Value):- server_manager:UvicornServerManager = create_server_manager(global_kill_flag=global_kill_flag)- server_manager.run_server()- while server_manager.is_running:- time.sleep(1)- if global_kill_flag.value:- server_manager.shutdown_server()- break-- logger.info("Server main process ended")---if __name__ == "__main__":-- multiprocessing.freeze_support()- if sys.platform == "win32":- setup_app_id_for_windows()- outer_global_kill_flag = multiprocessing.Value("b", False)- run_freemocap_server(outer_global_kill_flag)- outer_global_kill_flag.value = True- print("Done!")diff --git a/freemocap/system/default_paths.py b/freemocap/system/default_paths.pynew file mode 100644index 00000000..9913f322--- /dev/null+++ b/freemocap/system/default_paths.py@@ -0,0 +1,86 @@+import time+from datetime import datetime+from pathlib import Path++DEFAULT_FREEMOCAP_BASE_FOLDER_NAME = "freemocap_data"+SYNCHRONIZED_VIDEOS_FOLDER_NAME = "synchronized_videos"+LOGS_INFO_AND_SETTINGS_FOLDER_NAME = "logs_info_and_settings"+LOG_FILE_FOLDER_NAME = "logs"+TIMESTAMPS_FOLDER_NAME = "timestamps"++# Emoji strings+RED_X_EMOJI_STRING = "\U0000274C"+DIZZY_EMOJI_STRING = "\U0001F4AB"+SPARKLES_EMOJI_STRING = "\U00002728"+MAGNIFYING_GLASS_EMOJI_STRING = "\U0001F50D"+CAMERA_WITH_FLASH_EMOJI_STRING = "\U0001F4F8"+HAMMER_AND_WRENCH_EMOJI_STRING = "\U0001F6E0"+CLOCKWISE_VERTICAL_ARROWS_EMOJI_STRING = "\U0001F503"++SESSION_START_TIME_FORMAT_STRING = "ISO6201 format timestamp with GMT offset in hours"++FREEMOCAP_SVG_PATH = str(+ Path(__file__).parent.parent.parent / "shared" / "freemocap-logo" / "freemocap-logo.svg")+FREEMOCAP_FAVICON_ICO_PATH = str(+ Path(__file__).parent.parent.parent / "shared" / "freemocap-logo" / "freemocap-favicon.ico")+++def os_independent_home_dir() -> str:+ return str(Path.home())+++def get_default_freemocap_base_folder_path() -> str:+ return str(Path(os_independent_home_dir()) / DEFAULT_FREEMOCAP_BASE_FOLDER_NAME)+++def get_default_freemocap_recordings_path() -> str:+ return str(Path(get_default_freemocap_base_folder_path()) / "recordings")+++def get_default_recording_folder_path(tag: str = "") -> str:+ return str(Path(get_default_freemocap_base_folder_path()) / "recordings" / default_recording_name(string_tag=tag))+++def get_default_calibration_toml_path() -> str:+ calib_path = Path(+ get_default_freemocap_base_folder_path()) / "calibrations" / f"{default_recording_name()}_camera_calibration.toml"+ calib_path.parent.mkdir(exist_ok=True, parents=True)+ return str(calib_path)+++def get_log_file_path() -> str:+ log_folder_path = (+ Path(get_default_freemocap_base_folder_path()) / LOGS_INFO_AND_SETTINGS_FOLDER_NAME / LOG_FILE_FOLDER_NAME+ )+ log_folder_path.mkdir(exist_ok=True, parents=True)+ log_file_path = log_folder_path / create_log_file_name()+ return str(log_file_path)+++def get_gmt_offset_string() -> str:+ # from - https://stackoverflow.com/a/53860920/14662833+ gmt_offset_int = int(time.localtime().tm_gmtoff / 60 / 60)+ return f"{gmt_offset_int:+}"+++def create_log_file_name() -> str:+ return "log_" + get_iso6201_time_string() + ".log"+++def get_iso6201_time_string(timespec: str = "milliseconds", make_filename_friendly: bool = True) -> str:+ iso6201_timestamp = datetime.now().isoformat(timespec=timespec)+ gmt_offset_string = f"_gmt{get_gmt_offset_string()}"+ iso6201_timestamp_w_gmt = iso6201_timestamp + gmt_offset_string+ if make_filename_friendly:+ iso6201_timestamp_w_gmt = iso6201_timestamp_w_gmt.replace(":", "_")+ iso6201_timestamp_w_gmt = iso6201_timestamp_w_gmt.replace(".", "ms")+ return iso6201_timestamp_w_gmt+++def default_recording_name(string_tag: str = "") -> str:+ if len(string_tag) > 0:+ string_tag = f"_{string_tag}"+ else:+ string_tag = ""++ return time.strftime(get_iso6201_time_string(timespec="seconds") + string_tag)diff --git a/freemocap/system/logging_configuration/configure_logging.py b/freemocap/system/logging_configuration/configure_logging.pyindex dd44d49a..2882f83d 100644--- a/freemocap/system/logging_configuration/configure_logging.py+++ b/freemocap/system/logging_configuration/configure_logging.py@@ -10,7 +10,6 @@ from .logger_builder import LoggerBuildersuppress_noisy_package_logs()# Add custom log levels-logging.addLevelName(LogLevels.GUI.value, "GUI")logging.addLevelName(LogLevels.LOOP.value, "LOOP")logging.addLevelName(LogLevels.TRACE.value, "TRACE")logging.addLevelName(LogLevels.SUCCESS.value, "SUCCESS")@@ -32,7 +31,6 @@ def configure_logging(level: LogLevels, ws_queue: Optional[multiprocessing.Queuereturnws_queue = create_websocket_log_queue()- add_log_method(LogLevels.GUI, 'gui')add_log_method(LogLevels.LOOP, 'loop')add_log_method(LogLevels.TRACE, 'trace')add_log_method(LogLevels.API, 'api')diff --git a/freemocap/system/logging_configuration/filters/delta_time.py b/freemocap/system/logging_configuration/filters/delta_time.pyindex 960dca88..a44c519e 100644--- a/freemocap/system/logging_configuration/filters/delta_time.py+++ b/freemocap/system/logging_configuration/filters/delta_time.py@@ -13,4 +13,4 @@ class DeltaTimeFilter(logging.Filter):current_time = datetime.now().timestamp()record.delta_t = f"{(current_time - self.prev_time) * 1000:.3f}ms"self.prev_time = current_time- return True\ No newline at end of file+ return Truediff --git a/freemocap/system/logging_configuration/formatters/color_formatter.py b/freemocap/system/logging_configuration/formatters/color_formatter.pyindex dc8b57f8..fba38bb8 100644--- a/freemocap/system/logging_configuration/formatters/color_formatter.py+++ b/freemocap/system/logging_configuration/formatters/color_formatter.py@@ -1,5 +1,4 @@import logging-from copy import deepcopyfrom .custom_formatter import CustomFormatterfrom ..log_format_string import LOG_POINTER_STRING@@ -15,12 +14,14 @@ LOG_COLOR_CODES = {"WARNING": "\033[33m", # Yellow"ERROR": "\033[41m", # Red background}++class ColorFormatter(CustomFormatter):"""Adds ANSI colors to PID, TID, and log messages"""def format(self, record: logging.LogRecord) -> str:# Apply PID/TID colors- record = deepcopy(record)+record.pid_color = get_hashed_color(record.process)record.tid_color = get_hashed_color(record.thread)@@ -32,4 +33,4 @@ class ColorFormatter(CustomFormatter):formatted = super().format(record)formatted = f"{level_color}{formatted}\033[0m"# Add color to structural elements- return formatted.replace(LOG_POINTER_STRING, f"{level_color}{LOG_POINTER_STRING}\033[0m")\ No newline at end of file+ return formatted.replace(LOG_POINTER_STRING, f"{level_color}{LOG_POINTER_STRING}\033[0m")diff --git a/freemocap/system/logging_configuration/formatters/custom_formatter.py b/freemocap/system/logging_configuration/formatters/custom_formatter.pyindex 62ed6d67..f278cb73 100644--- a/freemocap/system/logging_configuration/formatters/custom_formatter.py+++ b/freemocap/system/logging_configuration/formatters/custom_formatter.py@@ -10,4 +10,4 @@ class CustomFormatter(logging.Formatter):self.format_string = format_stringdef formatTime(self, record: logging.LogRecord, datefmt: str = None) -> str:- return datetime.fromtimestamp(record.created).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3]\ No newline at end of file+ return datetime.fromtimestamp(record.created).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3]diff --git a/freemocap/system/logging_configuration/handlers/colored_console.py b/freemocap/system/logging_configuration/handlers/colored_console.pyindex 24dc2882..b6f7614a 100644--- a/freemocap/system/logging_configuration/handlers/colored_console.py+++ b/freemocap/system/logging_configuration/handlers/colored_console.py@@ -12,4 +12,4 @@ class ColoredConsoleHandler(logging.StreamHandler):def __init__(self, stream=sys.stdout):super().__init__(stream)self.setFormatter(ColorFormatter(COLOR_LOG_FORMAT_STRING))- self.addFilter(DeltaTimeFilter())\ No newline at end of file+ self.addFilter(DeltaTimeFilter())diff --git a/freemocap/system/logging_configuration/handlers/websocket_log_queue_handler.py b/freemocap/system/logging_configuration/handlers/websocket_log_queue_handler.pyindex fd9fe1c0..28e3b921 100644--- a/freemocap/system/logging_configuration/handlers/websocket_log_queue_handler.py+++ b/freemocap/system/logging_configuration/handlers/websocket_log_queue_handler.py@@ -1,46 +1,19 @@import loggingimport multiprocessing+from logging.handlers import QueueHandlerfrom multiprocessing import Queuefrom typing import Optional-from pydantic import BaseModel+from skellycam.system.logging_configuration.log_levels import LogLevels-from freemocap.system.logging_configuration.log_levels import LogLevelsfrom ..filters.delta_time import DeltaTimeFilterfrom ..formatters.custom_formatter import CustomFormatterfrom ..log_format_string import LOG_FORMAT_STRING+MIN_LOG_LEVEL_FOR_WEBSOCKET = LogLevels.TRACE.value-class LogRecordModel(BaseModel):- name: str- msg: str|None = None- args: list- levelname: str- levelno: int- pathname: str- filename: str- module: str- exc_info: str|None- exc_text: str|None- stack_info: str|None- lineno: int- funcName: str- created: float- msecs: float- relativeCreated: float- thread: int- threadName: str- processName: str- process: int- delta_t: str- message: str- asctime: str- formatted_message: str- type: str- message_type: str = "log_record"--class WebSocketQueueHandler(logging.Handler):+class WebSocketQueueHandler(QueueHandler):"""Formats logs and puts them in a queue for websocket distribution"""def __init__(self, queue: multiprocessing.Queue):@@ -50,26 +23,29 @@ class WebSocketQueueHandler(logging.Handler):self.setFormatter(CustomFormatter(LOG_FORMAT_STRING))def emit(self, record: logging.LogRecord):- if record.levelno > LogLevels.INFO.value:- log_record_dict = record.__dict__- log_record_dict["formatted_message"] = self.format(record)- log_record_dict['type'] = record.__class__.__name__- log_record_dict['exc_info'] = str(log_record_dict['exc_info']) if log_record_dict['exc_info'] else None- if not isinstance(log_record_dict['msg'], str):- log_record_dict['msg'] = str(log_record_dict['msg'])- self.queue.put(LogRecordModel(**log_record_dict).model_dump())+ if record.levelno > MIN_LOG_LEVEL_FOR_WEBSOCKET:+ try:+ # Prepare the record for pickling (handles exception info)+ prepared_record = self.prepare(record)+ print(f"---------------------\n--------------------\n------------WebSocketQueueHandler emitting record: {prepared_record.getMessage()}\n--------------------------\n--------------------\n------------")+ self.queue.put(prepared_record)+ except Exception:+ self.handleError(record)MAX_WEBSOCKET_LOG_QUEUE_SIZE = 1000WEBSOCKET_LOG_QUEUE: Optional[Queue] = None++def create_websocket_log_queue() -> Queue:global WEBSOCKET_LOG_QUEUEif WEBSOCKET_LOG_QUEUE is None:WEBSOCKET_LOG_QUEUE = Queue(maxsize=MAX_WEBSOCKET_LOG_QUEUE_SIZE)return WEBSOCKET_LOG_QUEUE+def get_websocket_log_queue() -> Queue:global WEBSOCKET_LOG_QUEUEif WEBSOCKET_LOG_QUEUE is None:raise ValueError("Websocket log queue not created yet")- return WEBSOCKET_LOG_QUEUE\ No newline at end of file+ return WEBSOCKET_LOG_QUEUEdiff --git a/freemocap/system/logging_configuration/log_format_string.py b/freemocap/system/logging_configuration/log_format_string.pyindex ba99e732..94ae0a86 100644--- a/freemocap/system/logging_configuration/log_format_string.py+++ b/freemocap/system/logging_configuration/log_format_string.py@@ -2,12 +2,12 @@ LOG_POINTER_STRING = "โ>>"LOG_FORMAT_STRING_WO_PID_TID = LOG_POINTER_STRING + (" %(message)s | "" %(levelname)s | "- " %(delta_t)s | "+ " %(delta_t)s | "" %(name)s.%(funcName)s():%(lineno)s | "" %(asctime)s | ")-LOG_FORMAT_STRING = LOG_FORMAT_STRING_WO_PID_TID + (+LOG_FORMAT_STRING = LOG_FORMAT_STRING_WO_PID_TID + (" PID:%(process)d:%(processName)s | "" TID:%(thread)d:%(threadName)s")diff --git a/freemocap/system/logging_configuration/log_levels.py b/freemocap/system/logging_configuration/log_levels.pyindex 52071963..d1a9d680 100644--- a/freemocap/system/logging_configuration/log_levels.py+++ b/freemocap/system/logging_configuration/log_levels.py@@ -4,8 +4,7 @@ from enum import Enumclass LogLevels(Enum):ALL = logging.NOTSET # 0 # All logs, including those from third-party libraries- LOOP = 3 # For logs that are printed in a loop- GUI = 4 # For logs that are printed in the GUI+ LOOP = 3 # For logs that are printed in a loop (ONLY FOR DEBUGGING, REMOVE BEFORE PRODUCTION)TRACE = 5 # Low level logs for deep debuggingDEBUG = logging.DEBUG # 10 # Detailed information for devs and curious folkINFO = logging.INFO # 20 # General information about the programdiff --git a/freemocap/system/logging_configuration/logger_builder.py b/freemocap/system/logging_configuration/logger_builder.pyindex bac33104..6fb3c1f5 100644--- a/freemocap/system/logging_configuration/logger_builder.py+++ b/freemocap/system/logging_configuration/logger_builder.py@@ -8,12 +8,13 @@ from .handlers.colored_console import ColoredConsoleHandlerfrom .handlers.websocket_log_queue_handler import WebSocketQueueHandlerfrom .log_format_string import LOG_FORMAT_STRINGfrom .log_levels import LogLevels-from ..paths_and_filenames.path_getters import get_log_file_path+from ..default_paths import get_log_file_path+class LoggerBuilder:def __init__(self,- level: LogLevels ,+ level: LogLevels,queue: Optional[Queue]):self.level = levelself.queue = queue@@ -35,7 +36,6 @@ class LoggerBuilder:root.addHandler(self._build_console_handler())-def _build_console_handler(self):handler = ColoredConsoleHandler()handler.setLevel(self.level.value)@@ -49,6 +49,7 @@ class LoggerBuilder:return handlerdef _build_websocket_handler(self):+ print("\n\n\n\nBuilding WebSocket log handler\n\n\n\n")handler = WebSocketQueueHandler(self.queue)handler.setLevel(self.level.value)return handler@@ -56,4 +57,3 @@ class LoggerBuilder:def configure(self):if len(logging.getLogger().handlers) == 0:self._configure_root_logger()-diff --git a/freemocap/system/logging_configuration/package_log_quieters.py b/freemocap/system/logging_configuration/package_log_quieters.pyindex aa50973f..dd991a35 100644--- a/freemocap/system/logging_configuration/package_log_quieters.py+++ b/freemocap/system/logging_configuration/package_log_quieters.py@@ -1,5 +1,6 @@import logging+def suppress_noisy_package_logs():# Suppress some external loggers that are too verbose for our context/tastelogging.getLogger("tzlocal").setLevel(logging.WARNING)@@ -12,4 +13,4 @@ def suppress_noisy_package_logs():logging.getLogger("httpcore").setLevel(logging.WARNING)logging.getLogger("urllib3").setLevel(logging.WARNING)logging.getLogger("comtypes").setLevel(logging.WARNING)-+ logging.getLogger("uvicorn").setLevel(logging.WARNING)diff --git a/freemocap/system/open_file.py b/freemocap/system/open_file.pydeleted file mode 100644index bb5fa1ce..00000000--- a/freemocap/system/open_file.py+++ /dev/null@@ -1,11 +0,0 @@-import os-import subprocess-import sys---def open_file(filename):- if sys.platform == "win32":- os.startfile(filename) # noqa- else:- opener = "open" if sys.platform == "darwin" else "xdg-open"- subprocess.call([opener, filename])diff --git a/freemocap/system/paths_and_filenames/__init__.py b/freemocap/system/paths_and_filenames/__init__.pydeleted file mode 100644index e69de29b..00000000diff --git a/freemocap/system/paths_and_filenames/file_and_folder_names.py b/freemocap/system/paths_and_filenames/file_and_folder_names.pydeleted file mode 100644index 1c0ad1ef..00000000--- a/freemocap/system/paths_and_filenames/file_and_folder_names.py+++ /dev/null@@ -1,75 +0,0 @@-import logging-from pathlib import Path--import freemocap--logger = logging.getLogger(__name__)--# directory names-BASE_FREEMOCAP_DATA_FOLDER_NAME = "freemocap_data"-RECORDING_SESSIONS_FOLDER_NAME = "recording_sessions"-CALIBRATIONS_FOLDER_NAME = "calibrations"-LOGS_INFO_AND_SETTINGS_FOLDER_NAME = "logs_info_and_settings"-LOG_FILE_FOLDER_NAME = "logs"-OUTPUT_DATA_FOLDER_NAME = "output_data"-SYNCHRONIZED_VIDEOS_FOLDER_NAME = "synchronized_videos"-ANNOTATED_VIDEOS_FOLDER_NAME = "annotated_videos"-RAW_DATA_FOLDER_NAME = "raw_data"-CENTER_OF_MASS_FOLDER_NAME = "center_of_mass"--# file names-MOST_RECENT_RECORDING_TOML_FILENAME = "most_recent_recording.toml"-LAST_SUCCESSFUL_CALIBRATION_TOML_FILENAME = "last_successful_calibration.toml"-GUI_STATE_JSON_FILENAME = "gui_state.json"-DATA_2D_NPY_FILE_NAME = "2dData_numCams_numFrames_numTrackedPoints_pixelXY.npy"--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_3d_xyz.csv"-LEFT_HAND_3D_DATAFRAME_CSV_FILE_NAME = "left_hand_3d_xyz.csv"-FACE_3D_DATAFRAME_CSV_FILE_NAME = "face_3d_xyz.csv"--TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME = "total_body_center_of_mass_xyz.npy"-SEGMENT_CENTER_OF_MASS_NPY_FILE_NAME = "segmentCOM_frame_joint_xyz.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"--RECORDING_PARAMETERS_JSON_FILE_NAME = "recording_parameters.json"--# Figshare info-FIGSHARE_SAMPLE_ZIP_FILE_URL = "https://figshare.com/ndownloader/files/45797067"-FIGSHARE_TEST_ZIP_FILE_URL = "https://figshare.com/ndownloader/files/45797073"-FREEMOCAP_TEST_DATA_RECORDING_NAME = "freemocap_test_data"-FREEMOCAP_SAMPLE_DATA_RECORDING_NAME = "freemocap_sample_data"--# logo-PATH_TO_FREEMOCAP_LOGO_SVG = str(Path(freemocap.__file__).parent / "assets/logo/freemocap-logo-black-border.svg")--# progress bars-LOG_VIEW_PROGRESS_BAR_STRING = "Log Progress"--# emoji strings-SKULL_EMOJI_STRING = "\U0001F480"-SPARKLES_EMOJI_STRING = "\U00002728"-DIZZY_EMOJI_STRING = "\U0001F4AB"-EYES_EMOJI_STRING = "\U0001F440"-CAMERA_WITH_FLASH_EMOJI_STRING = "\U0001F4F8"-HAMMER_AND_WRENCH_EMOJI_STRING = "\U0001F6E0"-ROBOT_EMOJI_STRING = "\U0001F916"-THREE_HEARTS_EMOJI_STRING = "\U0001F495"-WIND_EMOJI_STRING = "\U0001F32C"-GEAR_EMOJI_STRING = "\U00002699"-FOLDER_EMOJI_STRING = "\U0001F4C1"-DIRECTORY_EMOJI_STRING = "\U0001F4C1"-COOL_EMOJI_STRING = "\U0001F60E"diff --git a/freemocap/system/paths_and_filenames/path_getters.py b/freemocap/system/paths_and_filenames/path_getters.pydeleted file mode 100644index 341e8ecf..00000000--- a/freemocap/system/paths_and_filenames/path_getters.py+++ /dev/null@@ -1,303 +0,0 @@-import time-from datetime import datetime-from pathlib import Path-from typing import Optional, Union--import toml--from freemocap.system.paths_and_filenames.file_and_folder_names import (- LOGS_INFO_AND_SETTINGS_FOLDER_NAME,- LOG_FILE_FOLDER_NAME,- BASE_FREEMOCAP_DATA_FOLDER_NAME,- CALIBRATIONS_FOLDER_NAME,- RECORDING_SESSIONS_FOLDER_NAME,- MOST_RECENT_RECORDING_TOML_FILENAME,- LAST_SUCCESSFUL_CALIBRATION_TOML_FILENAME,- OUTPUT_DATA_FOLDER_NAME,- SYNCHRONIZED_VIDEOS_FOLDER_NAME,- RAW_DATA_FOLDER_NAME,- RAW_3D_NPY_FILE_NAME,- CENTER_OF_MASS_FOLDER_NAME,- TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME,- DATA_2D_NPY_FILE_NAME,- REPROJECTION_ERROR_NPY_FILE_NAME,- DATA_3D_NPY_FILE_NAME,- GUI_STATE_JSON_FILENAME,-)---import logging-logger = logging.getLogger(__name__)--def os_independent_home_dir():- return str(Path.home())---def get_log_file_path():- log_folder_path = Path(get_freemocap_data_folder_path()) / LOGS_INFO_AND_SETTINGS_FOLDER_NAME / LOG_FILE_FOLDER_NAME- log_folder_path.mkdir(exist_ok=True, parents=True)- log_file_path = log_folder_path / create_log_file_name()- return str(log_file_path)---def create_log_file_name():- return "log_" + time.strftime("%m-%d-%Y-%H_%M_%S") + ".log"---def create_camera_calibration_file_name(recording_name: str):- return f"{recording_name}_camera_calibration.toml"--def get_user_settings_path():- return str(Path(get_freemocap_data_folder_path()) / "user_settings.toml")--freemocap_data_folder_path = None---def get_freemocap_data_folder_path(create_folder: bool = True) -> str:- global freemocap_data_folder_path-- try:- if freemocap_data_folder_path is None:- freemocap_data_folder_path = Path(os_independent_home_dir(), BASE_FREEMOCAP_DATA_FOLDER_NAME)- # if Path(get_gui_state_json_path()).exists():- # gui_state = UserSettings.load_user_settings()- # else: # if GUI state isn't in new location, look in old location- # gui_state = UserSettings.load_user_settings()- # freemocap_data_folder_path = Path(gui_state.freemocap_data_folder_path)- except Exception as e: # TODO: figure out specific exceptions to catch- print(e) # Cannot log this due to circular import from logging config- finally:- if freemocap_data_folder_path is None:- freemocap_data_folder_path = Path(os_independent_home_dir(), BASE_FREEMOCAP_DATA_FOLDER_NAME)-- if create_folder:- freemocap_data_folder_path.mkdir(exist_ok=create_folder, parents=True)-- return str(freemocap_data_folder_path)---def get_calibrations_folder_path(create_folder: bool = True):- calibration_folder_path = Path(get_freemocap_data_folder_path()) / CALIBRATIONS_FOLDER_NAME-- if create_folder:- calibration_folder_path.mkdir(exist_ok=create_folder, parents=True)-- return str(calibration_folder_path)---def create_new_recording_folder_path(recording_name: str):- recording_folder_path = Path(create_new_session_folder()) / recording_name-- return str(recording_folder_path)---def get_gmt_offset_string():- # from - https://stackoverflow.com/a/53860920/14662833- gmt_offset_int = int(time.localtime().tm_gmtoff / 60 / 60)- return f"{gmt_offset_int:+}"---def get_iso6201_time_string(timespec: str = "milliseconds", make_filename_friendly: bool = True):- iso6201_timestamp = datetime.now().isoformat(timespec=timespec)- gmt_offset_string = f"_gmt{get_gmt_offset_string()}"- iso6201_timestamp_w_gmt = iso6201_timestamp + gmt_offset_string- if make_filename_friendly:- iso6201_timestamp_w_gmt = iso6201_timestamp_w_gmt.replace(":", "_")- iso6201_timestamp_w_gmt = iso6201_timestamp_w_gmt.replace(".", "ms")- return iso6201_timestamp_w_gmt---def create_new_default_recording_name():- full_time = get_iso6201_time_string(timespec="seconds")- just_hours_minutes_seconds = full_time.split("T")[1]- recording_name = "recording_" + just_hours_minutes_seconds- return recording_name---def session_time_tag_format():- return "%Y-%m-%d_%H_%M_%S"---def default_session_name(string_tag: Optional[str] = None):- if string_tag is not None:- string_tag = f"_{string_tag}"- else:- string_tag = ""-- session_name = time.strftime(f"session_{session_time_tag_format()}" + string_tag)- logger.debug(f"Creating default session name: {session_name}")-- return session_name---session_folder_path: Optional[Path] = None---def create_new_session_folder():- global session_folder_path- if session_folder_path is None:- session_folder_path = Path(get_recording_session_folder_path()) / default_session_name()- elif not session_folder_path.is_relative_to(get_freemocap_data_folder_path()):- session_folder_path = Path(get_recording_session_folder_path()) / default_session_name()-- return str(session_folder_path)---def get_recording_session_folder_path(create_folder: bool = True):- recording_session_folder_path = Path(get_freemocap_data_folder_path()) / RECORDING_SESSIONS_FOLDER_NAME-- if create_folder:- recording_session_folder_path.mkdir(exist_ok=create_folder, parents=True)-- return str(recording_session_folder_path)---def get_logs_info_and_settings_folder_path(create_folder: bool = True):- logs_info_and_settings_folder_path = Path(get_freemocap_data_folder_path()) / LOGS_INFO_AND_SETTINGS_FOLDER_NAME-- if create_folder:- logs_info_and_settings_folder_path.mkdir(exist_ok=create_folder, parents=True)-- return str(logs_info_and_settings_folder_path)---def get_css_stylesheet_path():- # return str(Path(__file__).parent.parent / "gui" / "qt" / "style_sheet" / "ElegantDark.qss")- # return str(Path(__file__).parent.parent / "gui" / "qt" / "style_sheet" / "FunkyTown.qss")- return str(Path(__file__).parent.parent.parent / "frontend" / "qt" / "style_sheet" / "css_qt_style_sheet.css")---def get_scss_stylesheet_path():- return str(Path(__file__).parent.parent.parent / "frontend" / "qt" / "style_sheet" / "scss_qt_style_sheet.scss")---def get_most_recent_recording_toml_path():- return str(Path(get_logs_info_and_settings_folder_path()) / MOST_RECENT_RECORDING_TOML_FILENAME)---def get_gui_state_json_path():- return str(Path(__file__).parent.parent / GUI_STATE_JSON_FILENAME)---def get_most_recent_recording_path(subfolder_str: Optional[str] = None) -> Optional[str]:- if not Path(get_most_recent_recording_toml_path()).exists():- logger.error(f"{MOST_RECENT_RECORDING_TOML_FILENAME} not found at {get_most_recent_recording_toml_path()}!!")- return None-- try:- most_recent_recording_dict = toml.load(str(get_most_recent_recording_toml_path()))- most_recent_recording_path = most_recent_recording_dict["most_recent_recording_path"]- except (ValueError, toml.TomlDecodeError, KeyError, FileNotFoundError) as e:- logger.exception(e)- return None-- if not Path(most_recent_recording_path).exists():- logger.error(f"Most recent recording path {most_recent_recording_path} not found!!")- return None-- if subfolder_str is not None:- try:- # check if folder is specified in toml file, otherwise return default- sub_folder_path = most_recent_recording_dict[subfolder_str]- except KeyError:- sub_folder_path = Path(most_recent_recording_path) / subfolder_str- return str(sub_folder_path)-- else:- return str(most_recent_recording_path)---def get_last_successful_calibration_toml_path():- return str(Path(get_logs_info_and_settings_folder_path()) / LAST_SUCCESSFUL_CALIBRATION_TOML_FILENAME)---def get_last_successful_calibration_name():- path = get_last_successful_calibration_toml_path()- if not Path(path).exists():- logger.error(f"{LAST_SUCCESSFUL_CALIBRATION_TOML_FILENAME} not found at {path}!!")- return None- # toml_dict = toml.load(path)-- # TODO: this function appears unfinished, and is currently unused. Either we need to parse the TOML or remove this.---def get_blender_file_name(recording_name: str):- return f"{recording_name}.blend"---def get_blender_file_path(recording_folder_path: Union[Path, str]):- return str(Path(recording_folder_path) / get_blender_file_name(recording_name=Path(recording_folder_path).name))---def get_output_data_folder_path(recording_folder_path: Union[str, Path]) -> str:- for subfolder_path in Path(recording_folder_path).iterdir():- if subfolder_path.name == OUTPUT_DATA_FOLDER_NAME:- return str(subfolder_path)-- raise Exception(f"Could not find a data folder in path {str(recording_folder_path)}")---def get_synchronized_videos_folder_path(recording_folder_path: Union[str, Path]) -> str:- for subfolder_path in Path(recording_folder_path).iterdir():- if subfolder_path.name == SYNCHRONIZED_VIDEOS_FOLDER_NAME:- return str(subfolder_path)-- raise Exception(f"Could not find a videos folder in path {str(recording_folder_path)}")---def get_timestamps_directory(recording_directory: Union[str, Path]) -> Optional[str]:- synchronized_videos_path = get_synchronized_videos_folder_path(recording_folder_path=recording_directory)- if "timestamps" in [path.name for path in Path(synchronized_videos_path).iterdir()]:- return str(Path(synchronized_videos_path) / "timestamps")- logger.warning(f"Could not find timestamps directory in {synchronized_videos_path}")---# TODO: figure out how to deal with different file prefixes for all of these below-def get_raw_skeleton_npy_file_name(data_folder_name: Union[str, Path]) -> str:- raw_data_subfolder_path = Path(data_folder_name) / RAW_DATA_FOLDER_NAME- if raw_data_subfolder_path.exists:- raw_data_npy_path_list = [path.name for path in raw_data_subfolder_path.glob("*.npy")]- if RAW_3D_NPY_FILE_NAME in raw_data_npy_path_list:- return str(raw_data_subfolder_path / RAW_3D_NPY_FILE_NAME)-- logger.debug(list(Path(data_folder_name).glob("*")))- logger.debug(list(Path(raw_data_subfolder_path).glob("*")))- raise Exception(f"Could not find a skeleton NPY file in path {str(data_folder_name)}")---def get_full_npy_file_path(output_data_folder: Union[str, Path]) -> str:- path = Path(output_data_folder) / DATA_3D_NPY_FILE_NAME- return str(path)---def get_total_body_center_of_mass_file_path(output_data_folder: Union[str, Path]) -> str:- center_of_mass_subfolder_path = Path(output_data_folder) / CENTER_OF_MASS_FOLDER_NAME- if center_of_mass_subfolder_path.exists:- center_of_mass_npy_path_list = [path.name for path in center_of_mass_subfolder_path.glob("*.npy")]-- if TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME in center_of_mass_npy_path_list:- return str(center_of_mass_subfolder_path / TOTAL_BODY_CENTER_OF_MASS_NPY_FILE_NAME)-- raise Exception(f"Could not find a total body center of mass npy file in path {str(output_data_folder)}")---def get_image_tracking_data_file_name(data_folder_name: Union[str, Path]) -> str:- raw_data_subfolder_path = Path(data_folder_name) / RAW_DATA_FOLDER_NAME- if raw_data_subfolder_path.exists:- raw_data_npy_path_list = [path.name for path in raw_data_subfolder_path.glob("*.npy")]-- if DATA_2D_NPY_FILE_NAME in raw_data_npy_path_list:- return str(raw_data_subfolder_path / DATA_2D_NPY_FILE_NAME)-- raise Exception(f"Could not find a 2d data file in path {str(data_folder_name)}")---def get_reprojection_error_file_path(data_folder_name: Union[str, Path]) -> str:- raw_data_subfolder_path = Path(data_folder_name) / RAW_DATA_FOLDER_NAME- if raw_data_subfolder_path.exists:- raw_data_npy_path_list = [path.name for path in raw_data_subfolder_path.glob("*.npy")]-- if REPROJECTION_ERROR_NPY_FILE_NAME in raw_data_npy_path_list:- return str(raw_data_subfolder_path / REPROJECTION_ERROR_NPY_FILE_NAME)-- raise Exception(f"Could not find reprojection error data file in path {str(data_folder_name)}")diff --git a/freemocap/system/user_data/__init__.py b/freemocap/system/user_data/__init__.pydeleted file mode 100644index e69de29b..00000000diff --git a/freemocap/system/user_data/pipedream_pings.py b/freemocap/system/user_data/pipedream_pings.pydeleted file mode 100644index 643a2c21..00000000--- a/freemocap/system/user_data/pipedream_pings.py+++ /dev/null@@ -1,30 +0,0 @@-import logging-import uuid--import requests--logger = logging.getLogger(__name__)---class PipedreamPings:- def __init__(- self,- ):- self._pipedream_url = "https://eowipinr6rcpbo0.m.pipedream.net"- self._pings_dict = {}- self.update_pings_dict(key="session_uuid", value=str(uuid.uuid4()))-- def update_pings_dict(self, key, value):- self._pings_dict[key] = value-- def send_pipedream_ping(self):- logger.info(- f"Sending anonymous ping to pipedream to let the devs know that someone is using this, which will allow "- f"us to secure more funding to support this project. This is the dictionary of info we're sending: \n "- f"{self._pings_dict} "- )-- try:- requests.post(self._pipedream_url, json=self._pings_dict, timeout=(5, 60))- except requests.RequestException:- logger.error("Failed to send anonymous ping to pipedream")diff --git a/freemocap/tests/conftest.py b/freemocap/tests/conftest.pyindex 1e7e169b..85da60c6 100644--- a/freemocap/tests/conftest.py+++ b/freemocap/tests/conftest.py@@ -1,70 +1,70 @@-import pytest--from freemocap.old.core_processes.process_motion_capture_videos.process_recording_headless import (- process_recording_headless,- find_calibration_toml_path,-)-from freemocap.old.data_layer.recording_models.recording_info_model import RecordingInfoModel-from freemocap.utilities.download_sample_data import (- download_sample_data,-)---class SessionInfo:- sample_session_folder_path: str- recording_info_model: RecordingInfoModel--def pytest_sessionstart():- SessionInfo.sample_session_folder_path = download_sample_data()- calibration_toml_path = find_calibration_toml_path(SessionInfo.sample_session_folder_path)- SessionInfo.recording_info_model = RecordingInfoModel(- recording_folder_path=SessionInfo.sample_session_folder_path, active_tracker="mediapipe"- )- # TODO: make this configurable to be able to take different trackers- process_recording_headless(- recording_path=SessionInfo.sample_session_folder_path,- path_to_camera_calibration_toml=calibration_toml_path,- recording_info_model=SessionInfo.recording_info_model,- run_blender=False,- make_jupyter_notebook=False,- use_tqdm=False,- )---def sample_session_path():- return SessionInfo.sample_session_folder_path---def synchronized_video_folder_path():- return SessionInfo.recording_info_model.synchronized_videos_folder_path---def data_folder_path():- return SessionInfo.recording_info_model.output_data_folder_path---def raw_skeleton_data():- return SessionInfo.recording_info_model.raw_data_3d_npy_file_path---def total_body_center_of_mass_data():- return SessionInfo.recording_info_model.total_body_center_of_mass_npy_file_path---def image_tracking_data():- return SessionInfo.recording_info_model.data_2d_npy_file_path---def reprojection_error_data():- return SessionInfo.recording_info_model.reprojection_error_data_npy_file_path---if __name__ == "__main__":- pytest_sessionstart()+# import pytest+#+# from freemocap.old.core_processes.process_motion_capture_videos.process_recording_headless import (+# process_recording_headless,+# find_calibration_toml_path,+# )+# from freemocap.old.data_layer.recording_models.recording_info_model import RecordingInfoModel+# from freemocap.utilities.download_sample_data import (+# download_sample_data,+# )+#+#+# class SessionInfo:+# sample_session_folder_path: str+# recording_info_model: RecordingInfoModel+#+# def pytest_sessionstart():+# SessionInfo.sample_session_folder_path = download_sample_data()+# calibration_toml_path = find_calibration_toml_path(SessionInfo.sample_session_folder_path)+# SessionInfo.recording_info_model = RecordingInfoModel(+# recording_folder_path=SessionInfo.sample_session_folder_path, active_tracker="mediapipe"+# )+# # TODO: make this configurable to be able to take different trackers+# process_recording_headless(+# recording_path=SessionInfo.sample_session_folder_path,+# path_to_camera_calibration_toml=calibration_toml_path,+# recording_info_model=SessionInfo.recording_info_model,+# run_blender=False,+# make_jupyter_notebook=False,+# use_tqdm=False,+# )+#+#+# @pytest.fixture+# def sample_session_path():+# return SessionInfo.sample_session_folder_path+#+#+# @pytest.fixture+# def synchronized_video_folder_path():+# return SessionInfo.recording_info_model.synchronized_videos_folder_path+#+#+# @pytest.fixture+# def data_folder_path():+# return SessionInfo.recording_info_model.output_data_folder_path+#+#+# @pytest.fixture+# def raw_skeleton_data():+# return SessionInfo.recording_info_model.raw_data_3d_npy_file_path+#+#+# @pytest.fixture+# def total_body_center_of_mass_data():+# return SessionInfo.recording_info_model.total_body_center_of_mass_npy_file_path+#+#+# @pytest.fixture+# def image_tracking_data():+# return SessionInfo.recording_info_model.data_2d_npy_file_path+#+#+# @pytest.fixture+# def reprojection_error_data():+# return SessionInfo.recording_info_model.reprojection_error_data_npy_file_path+#+#+# if __name__ == "__main__":+# pytest_sessionstart()diff --git a/freemocap/tests/test_by_camera_reprojection_filtering.py b/freemocap/tests/test_by_camera_reprojection_filtering.pyindex 150afd30..8278c1c7 100644--- a/freemocap/tests/test_by_camera_reprojection_filtering.py+++ b/freemocap/tests/test_by_camera_reprojection_filtering.py@@ -1,6 +1,6 @@import numpy as np-from freemocap.old.core_processes import (+from freemocap.zzold.core_processes import (_get_camera_frame_marker_lists_to_reproject,_set_unincluded_data_to_nans,)@@ -15,30 +15,30 @@ def test_get_camera_frame_marker_lists_to_reproject():num_cameras_to_remove = 1expected_output = ([[2], [1]], [0, 1], [1, 2])assert (- _get_camera_frame_marker_lists_to_reproject(- reprojError_cam_frame_marker, frame_marker_list, num_cameras_to_remove- )- == expected_output+ _get_camera_frame_marker_lists_to_reproject(+ reprojError_cam_frame_marker, frame_marker_list, num_cameras_to_remove+ )+ == expected_output)# test removing two camerasframe_marker_list = [(0, 1), (1, 2)]num_cameras_to_remove = 2expected_output = ([[2, 0], [1, 2]], [0, 1], [1, 2])assert (- _get_camera_frame_marker_lists_to_reproject(- reprojError_cam_frame_marker, frame_marker_list, num_cameras_to_remove- )- == expected_output+ _get_camera_frame_marker_lists_to_reproject(+ reprojError_cam_frame_marker, frame_marker_list, num_cameras_to_remove+ )+ == expected_output)# test removing all camerasframe_marker_list = [(0, 1), (1, 2)]num_cameras_to_remove = 3expected_output = ([[2, 0, 1], [1, 2, 0]], [0, 1], [1, 2])assert (- _get_camera_frame_marker_lists_to_reproject(- reprojError_cam_frame_marker, frame_marker_list, num_cameras_to_remove- )- == expected_output+ _get_camera_frame_marker_lists_to_reproject(+ reprojError_cam_frame_marker, frame_marker_list, num_cameras_to_remove+ )+ == expected_output)# test removing more cameras than dimensionsframe_marker_list = [(0, 1), (1, 2)]@@ -46,20 +46,20 @@ def test_get_camera_frame_marker_lists_to_reproject():# should just return all of the camera sorted by max reprojection error, no need to errorexpected_output = ([[2, 0, 1], [1, 2, 0]], [0, 1], [1, 2])assert (- _get_camera_frame_marker_lists_to_reproject(- reprojError_cam_frame_marker, frame_marker_list, num_cameras_to_remove- )- == expected_output+ _get_camera_frame_marker_lists_to_reproject(+ reprojError_cam_frame_marker, frame_marker_list, num_cameras_to_remove+ )+ == expected_output)# test providing no frames or markersframe_marker_list = []num_cameras_to_remove = 2expected_output = ([], [], [])assert (- _get_camera_frame_marker_lists_to_reproject(- reprojError_cam_frame_marker, frame_marker_list, num_cameras_to_remove- )- == expected_output+ _get_camera_frame_marker_lists_to_reproject(+ reprojError_cam_frame_marker, frame_marker_list, num_cameras_to_remove+ )+ == expected_output)@@ -69,8 +69,10 @@ def test_set_unincluded_data_to_nans():frames_with_reprojection_error = [1, 2]markers_with_reprojection_error = [3, 4]cameras_to_remove = [[0, 1], [2, 3]]- result = _set_unincluded_data_to_nans(data, frames_with_reprojection_error, markers_with_reprojection_error, cameras_to_remove)- for cameras, frame, marker in zip(cameras_to_remove, frames_with_reprojection_error, markers_with_reprojection_error):+ result = _set_unincluded_data_to_nans(data, frames_with_reprojection_error, markers_with_reprojection_error,+ cameras_to_remove)+ for cameras, frame, marker in zip(cameras_to_remove, frames_with_reprojection_error,+ markers_with_reprojection_error):for camera in cameras:np.testing.assert_array_equal(result[camera, frame, marker, :], np.full((2,), np.nan))@@ -80,9 +82,11 @@ def test_set_unincluded_data_to_nans():markers_with_reprojection_error = [3, 4]cameras_to_remove = [[0, 1], [2, 3]]original_data = data.copy()- result = _set_unincluded_data_to_nans(data, frames_with_reprojection_error, markers_with_reprojection_error, cameras_to_remove)+ result = _set_unincluded_data_to_nans(data, frames_with_reprojection_error, markers_with_reprojection_error,+ cameras_to_remove)mask = np.ones(data.shape, dtype=bool)- for cameras, frame, marker in zip(cameras_to_remove, frames_with_reprojection_error, markers_with_reprojection_error):+ for cameras, frame, marker in zip(cameras_to_remove, frames_with_reprojection_error,+ markers_with_reprojection_error):for camera in cameras:mask[camera, frame, marker, :] = Falsenp.testing.assert_array_equal(result[mask], original_data[mask])diff --git a/freemocap/tests/test_geometry_utilities.py b/freemocap/tests/test_geometry_utilities.pyindex 9ef8e529..159ef3b5 100644--- a/freemocap/tests/test_geometry_utilities.py+++ b/freemocap/tests/test_geometry_utilities.py@@ -25,7 +25,7 @@ def test_rotate_by_90_degrees_around_x_axis():with pytest.raises(ValueError) as exc_info:rotate_by_90_degrees_around_x_axis(raw_skel3d_frame_marker_xyz)assert (- str(exc_info.value) == "raw_skel3d_frame_marker_xyz must have shape (N, M, 3)"+ str(exc_info.value) == "raw_skel3d_frame_marker_xyz must have shape (N, M, 3)"), "Did not correctly handle an empty input array."# test zero inputdiff --git a/freemocap/tests/test_image_tracking_data_shape.py b/freemocap/tests/test_image_tracking_data_shape.pyindex a2a9167b..dd698f87 100644--- a/freemocap/tests/test_image_tracking_data_shape.py+++ b/freemocap/tests/test_image_tracking_data_shape.py@@ -12,8 +12,8 @@ from freemocap.utilities.get_video_paths import get_video_paths@pytest.mark.usefixtures("synchronized_video_folder_path", "image_tracking_data")def test_image_tracking_data_exists(- synchronized_video_folder_path: Union[str, Path],- image_tracking_data: Union[str, Path],+ synchronized_video_folder_path: Union[str, Path],+ image_tracking_data: Union[str, Path],):"""test that the `2d detection` process worked correctly by checking that there is an `.npy` file containing the 2d data in the `output_data_folder`@@ -24,8 +24,8 @@ def test_image_tracking_data_exists(@pytest.mark.usefixtures("synchronized_video_folder_path", "image_tracking_data")def test_image_tracking_data_shape(- synchronized_video_folder_path: Union[str, Path],- image_tracking_data: Union[str, Path, np.ndarray],+ synchronized_video_folder_path: Union[str, Path],+ image_tracking_data: Union[str, Path, np.ndarray],):"""test that the `2d detection` process worked correctly by checking:@@ -42,20 +42,20 @@ def test_image_tracking_data_shape(list_of_video_paths = get_video_paths(Path(synchronized_video_folder_path))number_of_videos = len(list_of_video_paths)assert (- image2d_camera_frame_marker_xyz.shape[0] == number_of_videos+ image2d_camera_frame_marker_xyz.shape[0] == number_of_videos), f"Number of videos in image_tracking_data does not match number of videos in synchronized videos folder"frame_counts = list(get_number_of_frames_of_videos_in_a_folder(synchronized_video_folder_path).values())assert (- len(set(frame_counts)) == 1+ len(set(frame_counts)) == 1), f"Videos in {synchronized_video_folder_path} have different frame counts: {frame_counts}"assert (- image2d_camera_frame_marker_xyz.shape[1] == frame_counts[0]+ image2d_camera_frame_marker_xyz.shape[1] == frame_counts[0]), f"Number of frames in image_tracking_data does not match number of frames of videos in {synchronized_video_folder_path}"# TODO - check number of tracked points vs 'expected' number of tracked pointsassert (- image2d_camera_frame_marker_xyz.shape[3] == 3+ image2d_camera_frame_marker_xyz.shape[3] == 3), f"Data has {image2d_camera_frame_marker_xyz.shape[3]} dimensions, expected 3 dimensions"diff --git a/freemocap/tests/test_pubsub.py b/freemocap/tests/test_pubsub.pynew file mode 100644index 00000000..89c3efe5--- /dev/null+++ b/freemocap/tests/test_pubsub.py@@ -0,0 +1,525 @@+from multiprocessing import Queue+from queue import Empty+from typing import Any++import pytest+from pydantic import Field++from freemocap.pubsub.pubsub_abcs import (+ TopicMessageABC,+ PubSubTopicABC,+ create_topic,+)+from freemocap.pubsub.pubsub_manager import (+ PubSubTopicManager,+ create_pipeline_pubsub_manager,+ PIPELINE_PUB_SUB_MANAGERS,+)+++# ============================================================================+# Test Fixtures - Message Types+# ============================================================================++class TestMessage(TopicMessageABC):+ """Simple test message."""+ value: int+++class TestMessageWithData(TopicMessageABC):+ """Test message with more fields."""+ name: str+ count: int = Field(ge=0)+ data: dict[str, Any] = Field(default_factory=dict)+++class AnotherTestMessage(TopicMessageABC):+ """Another message type for testing."""+ text: str+++# ============================================================================+# Test Fixtures - Topics+# ============================================================================+[email protected](autouse=True)+def clear_topic_registry() -> None:+ """Clear the topic registry before each test."""+ PubSubTopicABC.topic_registry.clear()+ PIPELINE_PUB_SUB_MANAGERS.clear()+ yield+ PubSubTopicABC.topic_registry.clear()+ PIPELINE_PUB_SUB_MANAGERS.clear()+++def test_topic_class() -> type[PubSubTopicABC[TestMessage]]:+ """Create a test topic class."""+ return create_topic(message_type=TestMessage)+++def test_topic_instance(test_topic_class: type[PubSubTopicABC[TestMessage]]) -> PubSubTopicABC[TestMessage]:+ """Create an instance of test topic."""+ return test_topic_class()+++# ============================================================================+# Tests for TopicMessageABC+# ============================================================================++def test_topic_message_creation() -> None:+ """Test basic message creation."""+ msg = TestMessage(value=42)+ assert msg.value == 42+++def test_topic_message_validation() -> None:+ """Test message validation."""+ # Should work+ msg = TestMessageWithData(name="test", count=5)+ assert msg.name == "test"+ assert msg.count == 5++ # Should fail validation (count must be >= 0)+ with pytest.raises(Exception): # Pydantic validation error+ TestMessageWithData(name="test", count=-1)+++# ============================================================================+# Tests for PubSubTopicABC - Registration+# ============================================================================++def test_topic_auto_registration() -> None:+ """Test that topics auto-register on subclassing."""+ initial_count = len(PubSubTopicABC.topic_registry)++ # Create a new topic+ TestTopic = create_topic(message_type=TestMessage)++ # Should be registered+ assert len(PubSubTopicABC.topic_registry) == initial_count + 1+ assert TestTopic in PubSubTopicABC.topic_registry+++def test_topic_private_classes_not_registered() -> None:+ """Test that private topic classes (starting with _) are not registered."""+ initial_count = len(PubSubTopicABC.topic_registry)++ class _PrivateTestTopic(PubSubTopicABC[TestMessage]):+ message_type: type[TestMessage] = TestMessage++ # Should NOT be registered+ assert len(PubSubTopicABC.topic_registry) == initial_count+ assert _PrivateTestTopic not in PubSubTopicABC.topic_registry+++def test_get_registered_topics() -> None:+ """Test getting registered topics returns a copy."""+ TestTopic1 = create_topic(message_type=TestMessage)+ TestTopic2 = create_topic(message_type=AnotherTestMessage)++ topics = PubSubTopicABC.get_registered_topics()++ assert TestTopic1 in topics+ assert TestTopic2 in topics++ # Should be a copy, not the original+ topics.clear()+ assert len(PubSubTopicABC.get_registered_topics()) == 2+++# ============================================================================+# Tests for PubSubTopicABC - Publishing & Subscribing+# ============================================================================++def test_topic_publish_and_subscribe(test_topic_instance: PubSubTopicABC[TestMessage]) -> None:+ """Test basic publish and subscribe."""+ # Get a subscription+ sub = test_topic_instance.get_subscription()++ # Publish a message+ msg = TestMessage(value=42)+ test_topic_instance.publish(message=msg)++ # Should receive the message+ received = sub.get(timeout=1)+ assert isinstance(received, TestMessage)+ assert received.value == 42+++def test_topic_multiple_subscriptions(test_topic_instance: PubSubTopicABC[TestMessage]) -> None:+ """Test multiple subscriptions receive the same message."""+ sub1 = test_topic_instance.get_subscription()+ sub2 = test_topic_instance.get_subscription()+ sub3 = test_topic_instance.get_subscription()++ msg = TestMessage(value=99)+ test_topic_instance.publish(message=msg)++ # All subscriptions should receive the message+ for sub in [sub1, sub2, sub3]:+ received = sub.get(timeout=1)+ assert received.value == 99+++def test_topic_publish_wrong_message_type(test_topic_instance: PubSubTopicABC[TestMessage]) -> None:+ """Test that publishing wrong message type raises TypeError."""+ wrong_msg = AnotherTestMessage(text="wrong")++ with pytest.raises(TypeError, match="Message must be of type TestMessage"):+ test_topic_instance.publish(message=wrong_msg) # type: ignore+++def test_topic_publication_queue(test_topic_instance: PubSubTopicABC[TestMessage]) -> None:+ """Test that messages are also put in the publication queue."""+ msg = TestMessage(value=123)+ test_topic_instance.publish(message=msg)++ # Should be in the publication queue+ received = test_topic_instance.publication.get(timeout=1)+ assert received.value == 123+++def test_topic_empty_subscriptions(test_topic_instance: PubSubTopicABC[TestMessage]) -> None:+ """Test that subscription queues are empty before publishing."""+ sub = test_topic_instance.get_subscription()++ # Should be empty+ with pytest.raises(Empty):+ sub.get(timeout=0.1)+++def test_topic_close(test_topic_instance: PubSubTopicABC[TestMessage]) -> None:+ """Test closing a topic."""+ sub1 = test_topic_instance.get_subscription()+ sub2 = test_topic_instance.get_subscription()++ assert len(test_topic_instance.subscriptions) == 2++ test_topic_instance.close()++ # Subscriptions should be cleared+ assert len(test_topic_instance.subscriptions) == 0+++# ============================================================================+# Tests for create_topic Factory+# ============================================================================++def test_create_topic_basic() -> None:+ """Test create_topic factory creates a valid topic class."""+ TestTopic = create_topic(message_type=TestMessage)++ # Should be a class, not an instance+ assert isinstance(TestTopic, type)++ # Should be subclass of PubSubTopicABC+ assert issubclass(TestTopic, PubSubTopicABC)++ # Should have correct message_type+ instance = TestTopic()+ assert instance.message_type == TestMessage+++def test_create_topic_naming() -> None:+ """Test that create_topic generates appropriate names."""+ TestTopic = create_topic(message_type=TestMessage)++ # Should replace 'Message' with 'Topic'+ assert TestTopic.__name__ == "TestTopic"+++def test_create_topic_with_custom_publication_factory() -> None:+ """Test create_topic with custom publication factory."""+ custom_queue_created = False++ def custom_factory():+ nonlocal custom_queue_created+ custom_queue_created = True+ return Queue()++ TestTopic = create_topic(+ message_type=TestMessage,+ publication_factory=custom_factory+ )++ # Creating an instance should use the custom factory+ instance = TestTopic()+ assert custom_queue_created+++# ============================================================================+# Tests for PubSubTopicManager+# ============================================================================++def test_manager_creation() -> None:+ """Test manager creation and auto-instantiation of topics."""+ # Create some topics+ TestTopic1 = create_topic(message_type=TestMessage)+ TestTopic2 = create_topic(message_type=AnotherTestMessage)++ # Create manager+ manager = PubSubTopicManager.create()++ # Should have instantiated all registered topics+ assert TestTopic1 in manager.topics+ assert TestTopic2 in manager.topics+ assert isinstance(manager.topics[TestTopic1], TestTopic1)+ assert isinstance(manager.topics[TestTopic2], TestTopic2)+++def test_manager_get_subscription() -> None:+ """Test getting subscriptions through manager."""+ TestTopic = create_topic(message_type=TestMessage)+ manager = PubSubTopicManager.create()++ # Get subscription+ sub = manager.get_subscription(topic_type=TestTopic)++ # Should be a valid queue+ assert sub is not None+++def test_manager_get_subscription_unknown_topic() -> None:+ """Test getting subscription for unknown topic raises error."""+ TestTopic = create_topic(message_type=TestMessage)+ manager = PubSubTopicManager.create()++ # Create a topic that's not registered with this manager+ class UnregisteredTopic(PubSubTopicABC[TestMessage]):+ message_type: type[TestMessage] = TestMessage++ # Remove it from registry to simulate unknown topic+ PubSubTopicABC.topic_registry.discard(UnregisteredTopic)++ with pytest.raises(ValueError, match="Unknown topic type"):+ manager.get_subscription(topic_type=UnregisteredTopic)+++def test_manager_publish() -> None:+ """Test publishing through manager."""+ TestTopic = create_topic(message_type=TestMessage)+ manager = PubSubTopicManager.create()++ sub = manager.get_subscription(topic_type=TestTopic)++ msg = TestMessage(value=777)+ manager.publish(topic_type=TestTopic, message=msg)++ received = sub.get(timeout=1)+ assert received.value == 777+++def test_manager_publish_unknown_topic() -> None:+ """Test publishing to unknown topic raises error."""+ TestTopic = create_topic(message_type=TestMessage)+ manager = PubSubTopicManager.create()++ class UnregisteredTopic(PubSubTopicABC[TestMessage]):+ message_type: type[TestMessage] = TestMessage++ PubSubTopicABC.topic_registry.discard(UnregisteredTopic)++ msg = TestMessage(value=1)++ with pytest.raises(ValueError, match="Unknown topic type"):+ manager.publish(topic_type=UnregisteredTopic, message=msg)+++def test_manager_close() -> None:+ """Test closing manager closes all topics."""+ TestTopic1 = create_topic(message_type=TestMessage)+ TestTopic2 = create_topic(message_type=AnotherTestMessage)+ manager = PubSubTopicManager.create()++ # Get some subscriptions to verify they exist+ sub1 = manager.get_subscription(topic_type=TestTopic1)+ sub2 = manager.get_subscription(topic_type=TestTopic2)++ assert len(manager.topics) == 2++ manager.close()++ # Topics should be cleared+ assert len(manager.topics) == 0+++# ============================================================================+# Tests for Pipeline Manager Registry+# ============================================================================++def test_create_pipeline_pubsub_manager() -> None:+ """Test creating pipeline-specific managers."""+ TestTopic = create_topic(message_type=TestMessage)++ pipeline_id = "test_pipeline_001"+ manager = create_pipeline_pubsub_manager(pipeline_id=pipeline_id)++ # Should be registered+ assert pipeline_id in PIPELINE_PUB_SUB_MANAGERS+ assert PIPELINE_PUB_SUB_MANAGERS[pipeline_id] is manager++ # Should have topics+ assert TestTopic in manager.topics+++def test_create_pipeline_pubsub_manager_replaces_existing() -> None:+ """Test that creating manager for same pipeline closes old one."""+ TestTopic = create_topic(message_type=TestMessage)++ pipeline_id = "test_pipeline_002"++ # Create first manager+ manager1 = create_pipeline_pubsub_manager(pipeline_id=pipeline_id)+ sub1 = manager1.get_subscription(topic_type=TestTopic)++ # Create second manager for same pipeline+ manager2 = create_pipeline_pubsub_manager(pipeline_id=pipeline_id)++ # Should be different instance+ assert manager2 is not manager1++ # First manager should be closed+ assert len(manager1.topics) == 0++ # Second manager should be active+ assert TestTopic in manager2.topics+++def test_multiple_pipeline_managers() -> None:+ """Test multiple pipeline managers can coexist."""+ TestTopic = create_topic(message_type=TestMessage)++ manager1 = create_pipeline_pubsub_manager(pipeline_id="pipeline_a")+ manager2 = create_pipeline_pubsub_manager(pipeline_id="pipeline_b")++ # Both should be registered+ assert "pipeline_a" in PIPELINE_PUB_SUB_MANAGERS+ assert "pipeline_b" in PIPELINE_PUB_SUB_MANAGERS++ # Both should be independent+ assert manager1 is not manager2++ # Both should have the topic+ assert TestTopic in manager1.topics+ assert TestTopic in manager2.topics+++# ============================================================================+# Integration Tests+# ============================================================================++def test_full_pubsub_workflow() -> None:+ """Test a complete pub/sub workflow."""+ # Create message types and topics+ TestTopic = create_topic(message_type=TestMessage)+ AnotherTopic = create_topic(message_type=AnotherTestMessage)++ # Create manager+ manager = PubSubTopicManager.create()++ # Get subscriptions+ sub1 = manager.get_subscription(topic_type=TestTopic)+ sub2 = manager.get_subscription(topic_type=TestTopic)+ sub_other = manager.get_subscription(topic_type=AnotherTopic)++ # Publish messages+ manager.publish(topic_type=TestTopic, message=TestMessage(value=100))+ manager.publish(topic_type=TestTopic, message=TestMessage(value=200))+ manager.publish(topic_type=AnotherTopic, message=AnotherTestMessage(text="hello"))++ # Verify subscriptions received correct messages+ assert sub1.get(timeout=1).value == 100+ assert sub1.get(timeout=1).value == 200++ assert sub2.get(timeout=1).value == 100+ assert sub2.get(timeout=1).value == 200++ assert sub_other.get(timeout=1).text == "hello"++ # Queues should now be empty+ with pytest.raises(Empty):+ sub1.get(timeout=0.1)+ with pytest.raises(Empty):+ sub_other.get(timeout=0.1)++ # Clean up+ manager.close()+++def test_multiple_message_types_isolated() -> None:+ """Test that different message types don't interfere."""+ TestTopic = create_topic(message_type=TestMessage)+ AnotherTopic = create_topic(message_type=AnotherTestMessage)++ manager = PubSubTopicManager.create()++ test_sub = manager.get_subscription(topic_type=TestTopic)+ another_sub = manager.get_subscription(topic_type=AnotherTopic)++ # Publish to different topics+ manager.publish(topic_type=TestTopic, message=TestMessage(value=42))+ manager.publish(topic_type=AnotherTopic, message=AnotherTestMessage(text="world"))++ # Each subscription should only receive its own messages+ test_msg = test_sub.get(timeout=1)+ assert isinstance(test_msg, TestMessage)+ assert test_msg.value == 42++ another_msg = another_sub.get(timeout=1)+ assert isinstance(another_msg, AnotherTestMessage)+ assert another_msg.text == "world"++ # Queues should be empty+ with pytest.raises(Empty):+ test_sub.get(timeout=0.1)+ with pytest.raises(Empty):+ another_sub.get(timeout=0.1)+++# ============================================================================+# Edge Cases & Error Handling+# ============================================================================++def test_publish_before_subscription() -> None:+ """Test that messages published before subscription are not received."""+ TestTopic = create_topic(message_type=TestMessage)+ manager = PubSubTopicManager.create()++ # Publish before subscribing+ manager.publish(topic_type=TestTopic, message=TestMessage(value=1))++ # Now subscribe+ sub = manager.get_subscription(topic_type=TestTopic)++ # Publish after subscribing+ manager.publish(topic_type=TestTopic, message=TestMessage(value=2))++ # Should only receive the second message+ received = sub.get(timeout=1)+ assert received.value == 2++ # Queue should be empty+ with pytest.raises(Empty):+ sub.get(timeout=0.1)+++def test_topic_instance_isolation() -> None:+ """Test that different instances of same topic class are isolated."""+ TestTopic = create_topic(message_type=TestMessage)++ instance1 = TestTopic()+ instance2 = TestTopic()++ sub1 = instance1.get_subscription()+ sub2 = instance2.get_subscription()++ # Publish to instance1+ instance1.publish(message=TestMessage(value=111))++ # Only sub1 should receive+ assert sub1.get(timeout=1).value == 111++ with pytest.raises(Empty):+ sub2.get(timeout=0.1)diff --git a/freemocap/tests/test_skeleton_data_shape.py b/freemocap/tests/test_skeleton_data_shape.pyindex 8807c338..aa08c35b 100644--- a/freemocap/tests/test_skeleton_data_shape.py+++ b/freemocap/tests/test_skeleton_data_shape.py@@ -11,8 +11,8 @@ from freemocap.utilities.get_number_of_frames_of_videos_in_a_folder import (@pytest.mark.usefixtures("raw_skeleton_data", "reprojection_error_data")def test_skeleton_data_exists(- raw_skeleton_data: Union[str, Path],- reprojection_error_data: Union[str, Path],+ raw_skeleton_data: Union[str, Path],+ reprojection_error_data: Union[str, Path],):"""test that the `3d detection` process worked correctly by checking that there is an `.npy` file containing the 3d data in the `output_data_folder`@@ -29,9 +29,9 @@ def test_skeleton_data_exists(@pytest.mark.usefixtures("synchronized_video_folder_path", "raw_skeleton_data", "reprojection_error_data")def test_skeleton_data_shape(- synchronized_video_folder_path: Union[str, Path],- raw_skeleton_data: Union[str, Path, np.ndarray],- reprojection_error_data: Union[str, Path, np.ndarray],+ synchronized_video_folder_path: Union[str, Path],+ raw_skeleton_data: Union[str, Path, np.ndarray],+ reprojection_error_data: Union[str, Path, np.ndarray],):"""test that the `3d detection` process worked correctly by checking:@@ -44,7 +44,7 @@ def test_skeleton_data_shape(skel3d_frame_marker_xyz = raw_skeleton_dataassert (- len(skel3d_frame_marker_xyz.shape) == 3+ len(skel3d_frame_marker_xyz.shape) == 3), f"3d skeleton data file should have 3 dimensions, but has shape {skel3d_frame_marker_xyz.shape}"if isinstance(reprojection_error_data, (str, Path)):@@ -53,12 +53,12 @@ def test_skeleton_data_shape(skeleton_reprojection_error_fr_mar = reprojection_error_dataassert (- len(skeleton_reprojection_error_fr_mar.shape) == 2+ len(skeleton_reprojection_error_fr_mar.shape) == 2), f"3d skeleton reprojection error data file should have 2 dimensions but has shape {skeleton_reprojection_error_fr_mar.shape}"frame_counts = list(get_number_of_frames_of_videos_in_a_folder(synchronized_video_folder_path).values())assert (- len(set(frame_counts)) == 1+ len(set(frame_counts)) == 1), f"Videos in {synchronized_video_folder_path} have different frame counts: {frame_counts}"number_of_frames = frame_counts[0]@@ -69,5 +69,5 @@ def test_skeleton_data_shape(# TODO - check number of tracked points vs 'expected' number of tracked pointsassert (- skel3d_frame_marker_xyz.shape[2] == 3+ skel3d_frame_marker_xyz.shape[2] == 3), f"3d skeleton data file should have 3 dimensions for X,Y,Z, but instead has {skel3d_frame_marker_xyz.shape[2]}"diff --git a/freemocap/tests/test_synchronized_video_frame_counts.py b/freemocap/tests/test_synchronized_video_frame_counts.pyindex e4bb44a1..371714e6 100644--- a/freemocap/tests/test_synchronized_video_frame_counts.py+++ b/freemocap/tests/test_synchronized_video_frame_counts.py@@ -21,5 +21,5 @@ def test_synchronized_video_frame_counts(synchronized_video_folder_path: Union[Pframe_counts = list(get_number_of_frames_of_videos_in_a_folder(synchronized_video_folder_path).values())assert (- len(set(frame_counts)) == 1+ len(set(frame_counts)) == 1), f"Videos in {synchronized_video_folder_path} have different frame counts: {frame_counts}"diff --git a/freemocap/tests/test_total_body_center_of_mass_data_shape.py b/freemocap/tests/test_total_body_center_of_mass_data_shape.pyindex d5a5ce4c..a3b148c6 100644--- a/freemocap/tests/test_total_body_center_of_mass_data_shape.py+++ b/freemocap/tests/test_total_body_center_of_mass_data_shape.py@@ -11,7 +11,7 @@ from freemocap.utilities.get_number_of_frames_of_videos_in_a_folder import (@pytest.mark.usefixtures("total_body_center_of_mass_data")def test_total_body_center_of_mass_data_exists(- total_body_center_of_mass_data: Union[str, Path],+ total_body_center_of_mass_data: Union[str, Path],):assert Path(total_body_center_of_mass_data@@ -20,8 +20,8 @@ def test_total_body_center_of_mass_data_exists(@pytest.mark.usefixtures("synchronized_video_folder_path", "total_body_center_of_mass_data")def test_total_body_center_of_mass_data_shape(- synchronized_video_folder_path: Union[str, Path],- total_body_center_of_mass_data: Union[str, Path, np.ndarray],+ synchronized_video_folder_path: Union[str, Path],+ total_body_center_of_mass_data: Union[str, Path, np.ndarray],):if isinstance(total_body_center_of_mass_data, (str, Path)):total_body_center_of_mass_fr_xyz = np.load(total_body_center_of_mass_data)@@ -30,16 +30,15 @@ def test_total_body_center_of_mass_data_shape(frame_counts = list(get_number_of_frames_of_videos_in_a_folder(synchronized_video_folder_path).values())assert (- len(set(frame_counts)) == 1+ len(set(frame_counts)) == 1), f"Videos in {synchronized_video_folder_path} have different frame counts: {frame_counts}"number_of_frames = frame_counts[0]assert (- total_body_center_of_mass_fr_xyz.shape[0] == number_of_frames+ total_body_center_of_mass_fr_xyz.shape[0] == number_of_frames), f"Number of frames in {total_body_center_of_mass_fr_xyz.shape} does not match number of frames of videos in {synchronized_video_folder_path}"assert (- total_body_center_of_mass_fr_xyz.shape[1] == 3+ total_body_center_of_mass_fr_xyz.shape[1] == 3), f"total body center of mass should have 3 dimensions (X,Y,Z) but has {total_body_center_of_mass_fr_xyz.shape[1]}"-diff --git a/freemocap/tests/test_triangulator.py b/freemocap/tests/test_triangulator.pynew file mode 100644index 00000000..970961de--- /dev/null+++ b/freemocap/tests/test_triangulator.py@@ -0,0 +1,712 @@+import tempfile+from pathlib import Path++import cv2+import numpy as np+import pytest+import toml++from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.camera_math_models import (+ CameraDistortionCoefficients,+ CameraMatrix,+)+from freemocap.core.pipeline.posthoc_pipelines.posthoc_calibration_pipeline.calibration_helpers.point_triangulator import CameraCalibrationData, PointTriangulator+++class SyntheticCameraSetup:+ """Helper class to generate synthetic multi-camera calibration data."""++ def __init__(+ self,+ num_cameras: int,+ image_width: int = 1920,+ image_height: int = 1080,+ focal_length: float = 1000.0,+ baseline: float = 0.5,+ noise_std: float = 0.0,+ ):+ self.num_cameras = num_cameras+ self.image_width = image_width+ self.image_height = image_height+ self.focal_length = focal_length+ self.baseline = baseline+ self.noise_std = noise_std++ self.camera_calibrations = self._create_cameras()++ def _create_cameras(self) -> dict[str, CameraCalibrationData]:+ """Create synthetic cameras in a standard stereo/multi-camera configuration."""+ cameras: dict[str, CameraCalibrationData] = {}++ for i in range(self.num_cameras):+ camera_id = f"cam_{i:02d}"++ # Arrange cameras horizontally along X-axis+ # Cameras are evenly spaced and all look in +Z direction+ if self.num_cameras == 1:+ x = 0.0+ else:+ # Spread cameras symmetrically around X=0+ x = (i - (self.num_cameras - 1) / 2) * self.baseline++ y = 0.0+ z = 0.0 # Cameras on the X-Y plane at Z=0++ camera_position = np.array([x, y, z], dtype=np.float64)++ # All cameras look in +Z direction (forward)+ # Standard camera orientation: X right, Y down, Z forward+ rotation_matrix = np.eye(3, dtype=np.float64)++ # Convert rotation matrix to OpenCV rotation vector+ rotation_vector = cv2.Rodrigues(rotation_matrix)[0].ravel()++ # Translation: position of world origin in camera coordinates+ # t = -R @ camera_position+ translation = -rotation_matrix @ camera_position++ # Camera intrinsics+ camera_matrix = CameraMatrix(+ matrix=np.array(+ [+ [self.focal_length, 0, self.image_width / 2],+ [0, self.focal_length, self.image_height / 2],+ [0, 0, 1],+ ],+ dtype=np.float64,+ )+ )++ # No distortion for simplicity+ distortion = CameraDistortionCoefficients(+ coefficients=np.zeros(5, dtype=np.float64)+ )++ cameras[camera_id] = CameraCalibrationData(+ name=camera_id,+ image_size=(self.image_width, self.image_height),+ matrix=camera_matrix,+ distortion=distortion,+ rotation_vector=rotation_vector,+ translation=translation,+ )++ return cameras++ def project_points(+ self, points3d: np.ndarray+ ) -> dict[str, np.ndarray]:+ """+ Project 3D points to 2D in all cameras.++ Args:+ points3d: Shape (N, 3) - 3D world coordinates++ Returns:+ Dictionary mapping camera_id to (N, 2) 2D pixel coordinates+ """+ points2d_by_camera: dict[str, np.ndarray] = {}++ for camera_id, camera in self.camera_calibrations.items():+ points2d = camera.project_3d_to_2d(points3d)++ # Add noise if specified+ if self.noise_std > 0:+ noise = np.random.normal(0, self.noise_std, points2d.shape)+ points2d = points2d + noise++ points2d_by_camera[camera_id] = points2d++ return points2d_by_camera++ def create_toml_file(self, output_path: Path) -> None:+ """Save calibration data to TOML file."""+ toml_data: dict = {}++ for camera_id, camera in self.camera_calibrations.items():+ toml_data[camera_id] = {+ "size": list(camera.image_size),+ "matrix": {"matrix": camera.matrix.matrix.tolist()},+ "distortions": {"coefficients": camera.distortion.coefficients.tolist()},+ "rotation": camera.rotation_vector.tolist(),+ "translation": camera.translation.tolist(),+ }++ with open(output_path, "w") as f:+ toml.dump(toml_data, f)+++def synthetic_setup_2_cameras() -> SyntheticCameraSetup:+ """Create a simple 2-camera stereo setup."""+ return SyntheticCameraSetup(num_cameras=2, baseline=0.5, noise_std=0.0)+++def synthetic_setup_4_cameras() -> SyntheticCameraSetup:+ """Create a 4-camera setup."""+ return SyntheticCameraSetup(num_cameras=4, baseline=0.3, noise_std=0.0)+++def synthetic_setup_with_noise() -> SyntheticCameraSetup:+ """Create a 3-camera setup with realistic noise."""+ return SyntheticCameraSetup(num_cameras=3, baseline=0.4, noise_std=0.5)+++def random_3d_points() -> np.ndarray:+ """Generate random 3D points in front of cameras."""+ np.random.seed(42)+ num_points = 20++ # Generate points in a reasonable volume IN FRONT of cameras (positive Z)+ # X and Y spread, Z from 1m to 5m in front+ points3d = np.random.uniform(+ low=[-0.5, -0.5, 1.0], high=[0.5, 0.5, 5.0], size=(num_points, 3)+ )++ return points3d.astype(np.float64)+++class TestPointTriangulator:+ """Test suite for PointTriangulator."""++ def test_create_from_dict(self, synthetic_setup_2_cameras: SyntheticCameraSetup) -> None:+ """Test creating triangulator from calibration dict."""+ triangulator = PointTriangulator(+ camera_calibrations=synthetic_setup_2_cameras.camera_calibrations+ )++ assert triangulator.num_cameras == 2+ assert len(triangulator.camera_names) == 2+ assert triangulator.projection_matrices.shape == (2, 3, 4)++ def test_create_from_toml(self, synthetic_setup_4_cameras: SyntheticCameraSetup) -> None:+ """Test loading triangulator from TOML file."""+ with tempfile.TemporaryDirectory() as tmpdir:+ toml_path = Path(tmpdir) / "calibration.toml"+ synthetic_setup_4_cameras.create_toml_file(toml_path)++ triangulator = PointTriangulator.from_toml(toml_path)++ assert triangulator.num_cameras == 4+ assert len(triangulator.camera_names) == 4+ assert all(+ name in triangulator.camera_calibrations+ for name in [f"cam_{i:02d}" for i in range(4)]+ )++ def test_triangulation_perfect_conditions(+ self, synthetic_setup_2_cameras: SyntheticCameraSetup, random_3d_points: np.ndarray+ ) -> None:+ """Test triangulation with perfect synthetic data (no noise)."""+ triangulator = PointTriangulator(+ camera_calibrations=synthetic_setup_2_cameras.camera_calibrations+ )++ # Project 3D points to 2D+ points2d_by_camera = synthetic_setup_2_cameras.project_points(random_3d_points)++ # Stack into (M, N, 2) format+ points2d = np.stack(+ [points2d_by_camera[cam_id] for cam_id in triangulator.camera_names], axis=1+ )++ # Triangulate+ triangulated_3d, errors = triangulator.triangulate_points(+ points2d=points2d, undistort_points=False, compute_reprojection_error=True+ )++ # Check shape+ assert triangulated_3d.shape == random_3d_points.shape+ assert errors is not None+ assert errors.shape == (random_3d_points.shape[0],)++ # Check accuracy - should be very accurate with no noise+ max_error = np.max(np.linalg.norm(triangulated_3d - random_3d_points, axis=1))+ assert max_error < 0.01, f"Max reconstruction error: {max_error:.6f}m"++ # Check reprojection errors are small+ assert np.max(errors) < 1.0, f"Max reprojection error: {np.max(errors):.3f} pixels"++ def test_triangulation_multiple_cameras(+ self, synthetic_setup_4_cameras: SyntheticCameraSetup, random_3d_points: np.ndarray+ ) -> None:+ """Test triangulation with 4 cameras improves accuracy."""+ triangulator = PointTriangulator(+ camera_calibrations=synthetic_setup_4_cameras.camera_calibrations+ )++ points2d_by_camera = synthetic_setup_4_cameras.project_points(random_3d_points)++ points2d = np.stack(+ [points2d_by_camera[cam_id] for cam_id in triangulator.camera_names], axis=1+ )++ triangulated_3d, errors = triangulator.triangulate_points(+ points2d=points2d, undistort_points=False, compute_reprojection_error=True+ )++ # More cameras should give better accuracy+ max_error = np.max(np.linalg.norm(triangulated_3d - random_3d_points, axis=1))+ assert max_error < 0.005, f"Max reconstruction error: {max_error:.6f}m"++ mean_reprojection_error = np.mean(errors)+ assert mean_reprojection_error < 0.5, f"Mean reprojection error: {mean_reprojection_error:.3f} pixels"++ def test_triangulation_with_noise(+ self, synthetic_setup_with_noise: SyntheticCameraSetup, random_3d_points: np.ndarray+ ) -> None:+ """Test triangulation with realistic pixel noise."""+ triangulator = PointTriangulator(+ camera_calibrations=synthetic_setup_with_noise.camera_calibrations+ )++ points2d_by_camera = synthetic_setup_with_noise.project_points(random_3d_points)++ points2d = np.stack(+ [points2d_by_camera[cam_id] for cam_id in triangulator.camera_names], axis=1+ )++ triangulated_3d, errors = triangulator.triangulate_points(+ points2d=points2d, undistort_points=False, compute_reprojection_error=True+ )++ # With noise, accuracy will be worse but still reasonable+ max_error = np.max(np.linalg.norm(triangulated_3d - random_3d_points, axis=1))+ assert max_error < 0.1, f"Max reconstruction error with noise: {max_error:.6f}m"++ # Reprojection errors should reflect the added noise+ mean_reprojection_error = np.mean(errors)+ assert mean_reprojection_error > 0.3, "Reprojection error should reflect added noise"+ assert mean_reprojection_error < 2.0, f"Mean reprojection error too high: {mean_reprojection_error:.3f} pixels"++ def test_triangulate_dict_api_manual_debug(+ self, synthetic_setup_2_cameras: SyntheticCameraSetup+ ) -> None:+ """Manually debug the dict triangulation to isolate the issue."""+ triangulator = PointTriangulator(+ camera_calibrations=synthetic_setup_2_cameras.camera_calibrations+ )++ # Single test point - NOT at origin to avoid degenerate case+ test_point_3d = np.array([[0.1, 0.2, 1.0]])++ # Project using each camera+ points2d_list: list[np.ndarray] = []+ for cam_id in triangulator.camera_names:+ camera = triangulator.camera_calibrations[cam_id]+ point_2d = camera.project_3d_to_2d(test_point_3d)+ points2d_list.append(point_2d)+ print(f"Camera {cam_id} projects {test_point_3d[0]} to {point_2d[0]}")++ # Test array API+ points2d_array = np.stack(points2d_list, axis=1)+ print(f"\nArray API input shape: {points2d_array.shape}")+ print(f"Array API input:\n{points2d_array}")++ result_array, _ = triangulator.triangulate_points(points2d=points2d_array)+ print(f"Array API result: {result_array[0]}")+ print(f"Array API error: {np.linalg.norm(result_array[0] - test_point_3d[0]):.6f}m")++ # Now manually do what dict API does+ points2d_by_camera_dict: dict[str, dict[str, tuple[float, float]]] = {}+ for idx, cam_id in enumerate(triangulator.camera_names):+ points2d_by_camera_dict[cam_id] = {+ "test_point": (float(points2d_list[idx][0, 0]), float(points2d_list[idx][0, 1]))+ }++ print(f"\nDict API input: {points2d_by_camera_dict}")++ result_dict = triangulator.triangulate_dict(+ points2d_by_camera=points2d_by_camera_dict,+ min_cameras=2+ )++ print(f"Dict API result: {result_dict['test_point']}")++ reconstructed = np.array(result_dict['test_point'])+ assert not np.any(np.isnan(reconstructed)), f"Dict API returned NaN: {reconstructed}"++ error = np.linalg.norm(reconstructed - test_point_3d[0])+ assert error < 0.01, f"Dict API error: {error:.6f}m"++ def test_triangulate_dict_api(+ self, synthetic_setup_2_cameras: SyntheticCameraSetup+ ) -> None:+ """Test dictionary-based triangulation API."""+ triangulator = PointTriangulator(+ camera_calibrations=synthetic_setup_2_cameras.camera_calibrations+ )++ # Create test points with names - all in front of cameras (positive Z)+ test_points_3d: dict[str, np.ndarray] = {+ "point_A": np.array([0.0, 0.0, 2.0]),+ "point_B": np.array([0.3, 0.2, 3.0]),+ "point_C": np.array([-0.2, -0.1, 2.5]),+ }++ # First verify that the array-based API works with the same points+ points2d_by_camera_for_array: dict[str, np.ndarray] = {}+ for camera_id in triangulator.camera_names:+ camera = synthetic_setup_2_cameras.camera_calibrations[camera_id]+ points3d_array = np.array([test_points_3d[name] for name in test_points_3d.keys()])+ points2d_array = camera.project_3d_to_2d(points3d_array)+ points2d_by_camera_for_array[camera_id] = points2d_array++ # Stack for array API+ points2d_stacked = np.stack(+ [points2d_by_camera_for_array[cam_id] for cam_id in triangulator.camera_names],+ axis=1+ )++ # Verify array API works+ array_result, _ = triangulator.triangulate_points(points2d=points2d_stacked)+ assert not np.any(np.isnan(array_result)), "Array API should not return NaN"++ # Now test dict API with the same data+ # IMPORTANT: Maintain consistent point name order across all cameras+ point_names_ordered = list(test_points_3d.keys())+ points2d_by_camera: dict[str, dict[str, tuple[float, float]]] = {}++ for camera_id in triangulator.camera_names:+ points2d_by_camera[camera_id] = {}+ for idx, point_name in enumerate(point_names_ordered):+ point_2d = points2d_by_camera_for_array[camera_id][idx]+ points2d_by_camera[camera_id][point_name] = (float(point_2d[0]), float(point_2d[1]))++ # Triangulate using dict API+ results = triangulator.triangulate_dict(+ points2d_by_camera=points2d_by_camera,+ min_cameras=2,+ compute_reprojection_error=False,+ )++ # Verify results+ assert len(results) == 3, f"Expected 3 results, got {len(results)}"++ for point_idx, (point_name, point_3d_original) in enumerate(test_points_3d.items()):+ assert point_name in results, f"Point {point_name} not in results"+ reconstructed = np.array(results[point_name])++ # Check that we got valid (non-NaN) results+ if np.any(np.isnan(reconstructed)):+ print(f"\nDEBUG INFO for {point_name}:")+ print(f" Reconstructed (dict API): {reconstructed}")+ print(f" Expected (array API): {array_result[point_idx]}")+ print(f" Original 3D: {point_3d_original}")+ print(f" 2D observations:")+ for cam_id in triangulator.camera_names:+ print(f" {cam_id}: {points2d_by_camera[cam_id][point_name]}")+ print(f" Camera names order: {triangulator.camera_names}")+ print(f" Points2d dict keys: {list(points2d_by_camera.keys())}")++ assert not np.any(np.isnan(reconstructed)), (+ f"Point {point_name} returned NaN: {reconstructed}\n"+ f"Array API gave: {array_result[point_idx]}"+ )++ error = np.linalg.norm(reconstructed - point_3d_original)+ assert error < 0.01, f"Point {point_name} reconstruction error: {error:.6f}m"++ def test_triangulate_dict_with_reprojection_error(+ self, synthetic_setup_2_cameras: SyntheticCameraSetup+ ) -> None:+ """Test dict API with reprojection error computation."""+ triangulator = PointTriangulator(+ camera_calibrations=synthetic_setup_2_cameras.camera_calibrations+ )++ test_point_3d = np.array([0.1, -0.05, 2.5])++ points2d_by_camera: dict[str, dict[str, tuple[float, float]]] = {}+ for camera_id in triangulator.camera_names:+ camera = synthetic_setup_2_cameras.camera_calibrations[camera_id]+ point_2d = camera.project_3d_to_2d(test_point_3d.reshape(1, 3))[0]+ points2d_by_camera[camera_id] = {+ "test_point": (float(point_2d[0]), float(point_2d[1]))+ }++ results = triangulator.triangulate_dict(+ points2d_by_camera=points2d_by_camera,+ min_cameras=2,+ compute_reprojection_error=True,+ )++ assert "test_point" in results+ assert isinstance(results["test_point"], dict)+ assert "point" in results["test_point"]+ assert "error" in results["test_point"]++ reconstructed = np.array(results["test_point"]["point"])+ error_3d = np.linalg.norm(reconstructed - test_point_3d)+ assert error_3d < 0.01++ reprojection_error = results["test_point"]["error"]+ assert reprojection_error < 1.0++ def test_triangulate_dict_missing_observations(+ self, synthetic_setup_4_cameras: SyntheticCameraSetup+ ) -> None:+ """Test dict API when some cameras don't observe all points."""+ triangulator = PointTriangulator(+ camera_calibrations=synthetic_setup_4_cameras.camera_calibrations+ )++ test_point_3d = np.array([0.0, 0.0, 2.0])++ # Only 3 out of 4 cameras observe the point+ cameras_to_use = list(triangulator.camera_names)[:3]++ points2d_by_camera: dict[str, dict[str, tuple[float, float]]] = {}+ for camera_id in cameras_to_use:+ camera = synthetic_setup_4_cameras.camera_calibrations[camera_id]+ point_2d = camera.project_3d_to_2d(test_point_3d.reshape(1, 3))[0]+ points2d_by_camera[camera_id] = {+ "visible_point": (float(point_2d[0]), float(point_2d[1]))+ }++ results = triangulator.triangulate_dict(+ points2d_by_camera=points2d_by_camera, min_cameras=2+ )++ assert "visible_point" in results+ reconstructed = np.array(results["visible_point"])+ error = np.linalg.norm(reconstructed - test_point_3d)+ assert error < 0.01++ def test_triangulate_dict_insufficient_cameras(+ self, synthetic_setup_4_cameras: SyntheticCameraSetup+ ) -> None:+ """Test dict API when point is only visible in one camera (should return NaN)."""+ triangulator = PointTriangulator(+ camera_calibrations=synthetic_setup_4_cameras.camera_calibrations+ )++ test_point_3d = np.array([0.0, 0.0, 3.0])++ # Only 1 camera observes the point (insufficient)+ camera_id = triangulator.camera_names[0]+ camera = synthetic_setup_4_cameras.camera_calibrations[camera_id]+ point_2d = camera.project_3d_to_2d(test_point_3d.reshape(1, 3))[0]++ points2d_by_camera: dict[str, dict[str, tuple[float, float]]] = {+ camera_id: {"insufficient_point": (float(point_2d[0]), float(point_2d[1]))}+ }++ results = triangulator.triangulate_dict(+ points2d_by_camera=points2d_by_camera, min_cameras=2+ )++ assert "insufficient_point" in results+ result_tuple = results["insufficient_point"]+ assert all(np.isnan(result_tuple))++ def test_triangulation_validates_input_shape(+ self, synthetic_setup_2_cameras: SyntheticCameraSetup+ ) -> None:+ """Test that triangulation validates input array shapes."""+ triangulator = PointTriangulator(+ camera_calibrations=synthetic_setup_2_cameras.camera_calibrations+ )++ # Wrong number of cameras+ wrong_camera_count = np.random.rand(10, 3, 2) # 3 cameras instead of 2+ with pytest.raises(ValueError, match="cameras but triangulator"):+ triangulator.triangulate_points(points2d=wrong_camera_count)++ # Wrong last dimension+ wrong_dim = np.random.rand(10, 2, 3) # Last dim should be 2, not 3+ with pytest.raises(ValueError, match="must have shape"):+ triangulator.triangulate_points(points2d=wrong_dim)++ def test_undistort_points_returns_normalized_coordinates(+ self, synthetic_setup_2_cameras: SyntheticCameraSetup, random_3d_points: np.ndarray+ ) -> None:+ """+ Test that undistort_points flag works correctly.++ NOTE: When undistort_points=True, cv2.undistortPoints returns NORMALIZED+ camera coordinates (not pixel coordinates), so the triangulation results+ will differ from using pixel coordinates directly.+ """+ triangulator = PointTriangulator(+ camera_calibrations=synthetic_setup_2_cameras.camera_calibrations+ )++ points2d_by_camera = synthetic_setup_2_cameras.project_points(random_3d_points)+ points2d = np.stack(+ [points2d_by_camera[cam_id] for cam_id in triangulator.camera_names], axis=1+ )++ # Triangulate with pixel coordinates (standard approach)+ triangulated_no_undistort, _ = triangulator.triangulate_points(+ points2d=points2d, undistort_points=False+ )++ # Verify this gives accurate results+ max_error = np.max(np.linalg.norm(triangulated_no_undistort - random_3d_points, axis=1))+ assert max_error < 0.01, "Standard triangulation should be accurate"++ # The undistort_points flag changes coordinate system, so we just verify it runs+ # without errors (actual correctness depends on using appropriate projection matrices)+ triangulated_with_undistort, _ = triangulator.triangulate_points(+ points2d=points2d, undistort_points=True+ )++ # Just verify we got valid output+ assert triangulated_with_undistort.shape == random_3d_points.shape+ assert not np.any(np.isnan(triangulated_with_undistort))++ def test_reprojection_error_computation(+ self, synthetic_setup_2_cameras: SyntheticCameraSetup, random_3d_points: np.ndarray+ ) -> None:+ """Test that reprojection error computation is accurate."""+ triangulator = PointTriangulator(+ camera_calibrations=synthetic_setup_2_cameras.camera_calibrations+ )++ points2d_by_camera = synthetic_setup_2_cameras.project_points(random_3d_points)+ points2d = np.stack(+ [points2d_by_camera[cam_id] for cam_id in triangulator.camera_names], axis=1+ )++ triangulated_3d, errors = triangulator.triangulate_points(+ points2d=points2d, compute_reprojection_error=True+ )++ # Manually compute reprojection for first point to verify+ point_3d = triangulated_3d[0]+ manual_errors: list[float] = []++ for camera_id, camera in triangulator.camera_calibrations.items():+ projected = camera.project_3d_to_2d(point_3d.reshape(1, 3))[0]+ cam_idx = triangulator.camera_names.index(camera_id)+ original = points2d[0, cam_idx]+ error = np.linalg.norm(projected - original)+ manual_errors.append(error)++ manual_mean_error = np.mean(manual_errors)++ # Should match computed error for first point+ assert np.abs(errors[0] - manual_mean_error) < 0.01++ def test_empty_triangulator_raises_error(self) -> None:+ """Test that creating triangulator with no cameras raises error."""+ with pytest.raises(ValueError, match="cannot be empty"):+ PointTriangulator(camera_calibrations={})++ def test_camera_calibration_data_world_coordinates(+ self, synthetic_setup_2_cameras: SyntheticCameraSetup+ ) -> None:+ """Test that world_position and world_orientation are computed correctly."""+ camera = list(synthetic_setup_2_cameras.camera_calibrations.values())[0]++ # World position should be non-zero (camera is not at origin)+ assert np.linalg.norm(camera.world_position) > 0.1++ # World orientation should be orthonormal+ assert np.allclose(+ camera.world_orientation @ camera.world_orientation.T, np.eye(3), atol=1e-6+ )++ def test_projection_and_unprojection_consistency(+ self, synthetic_setup_2_cameras: SyntheticCameraSetup+ ) -> None:+ """Test that project_3d_to_2d and triangulation are consistent."""+ triangulator = PointTriangulator(+ camera_calibrations=synthetic_setup_2_cameras.camera_calibrations+ )++ # Single test point in front of cameras+ original_3d = np.array([[0.05, 0.1, 2.0]])++ # Project to 2D+ points2d_list: list[np.ndarray] = []+ for camera in triangulator.camera_calibrations.values():+ point_2d = camera.project_3d_to_2d(original_3d)+ points2d_list.append(point_2d)++ points2d = np.stack(points2d_list, axis=1)++ # Triangulate back+ reconstructed_3d, _ = triangulator.triangulate_points(points2d=points2d)++ # Should match original+ error = np.linalg.norm(reconstructed_3d[0] - original_3d[0])+ assert error < 0.001, f"Round-trip error: {error:.6f}m"+++class TestCameraCalibrationData:+ """Test suite for CameraCalibrationData class."""++ def test_from_dict_with_image_size_key(self) -> None:+ """Test loading from dict with 'image_size' key."""+ data = {+ "image_size": [1920, 1080],+ "matrix": {"matrix": [[1000.0, 0.0, 960.0], [0.0, 1000.0, 540.0], [0.0, 0.0, 1.0]]},+ "distortions": {"coefficients": [0.0, 0.0, 0.0, 0.0, 0.0]},+ "rotation": [0.0, 0.0, 0.0],+ "translation": [0.0, 0.0, 0.0],+ }++ camera = CameraCalibrationData.from_dict(camera_id="test_cam", data=data)++ assert camera.name == "test_cam"+ assert camera.image_size == (1920, 1080)++ def test_from_dict_with_size_key(self) -> None:+ """Test loading from dict with 'size' key (legacy)."""+ data = {+ "size": [1280, 720],+ "matrix": {"matrix": [[800.0, 0.0, 640.0], [0.0, 800.0, 360.0], [0.0, 0.0, 1.0]]},+ "distortions": {"coefficients": [0.0, 0.0, 0.0, 0.0, 0.0]},+ "rotation": [0.0, 0.0, 0.0],+ "translation": [0.0, 0.0, 0.0],+ }++ camera = CameraCalibrationData.from_dict(camera_id="legacy_cam", data=data)++ assert camera.image_size == (1280, 720)++ def test_from_dict_missing_size_raises_error(self) -> None:+ """Test that missing size key raises error."""+ data = {+ "matrix": {"matrix": [[1000.0, 0.0, 960.0], [0.0, 1000.0, 540.0], [0.0, 0.0, 1.0]]},+ "distortions": {"coefficients": [0.0, 0.0, 0.0, 0.0, 0.0]},+ "rotation": [0.0, 0.0, 0.0],+ "translation": [0.0, 0.0, 0.0],+ }++ with pytest.raises(KeyError, match="image_size"):+ CameraCalibrationData.from_dict(camera_id="bad_cam", data=data)++ def test_projection_matrix_shape(+ self, synthetic_setup_2_cameras: SyntheticCameraSetup+ ) -> None:+ """Test that projection matrix has correct shape."""+ camera = list(synthetic_setup_2_cameras.camera_calibrations.values())[0]++ assert camera.projection_matrix.shape == (3, 4)+ assert camera.extrinsics_matrix.shape == (3, 4)++ def test_undistort_points_shape_preservation(+ self, synthetic_setup_2_cameras: SyntheticCameraSetup+ ) -> None:+ """Test that undistort_points preserves input shape."""+ camera = list(synthetic_setup_2_cameras.camera_calibrations.values())[0]++ # Test with different input shapes+ points_2d_flat = np.random.rand(10, 2) * 1000+ points_2d_opencv = np.random.rand(10, 1, 2) * 1000++ undistorted_flat = camera.undistort_points(points_2d_flat)+ undistorted_opencv = camera.undistort_points(points_2d_opencv)++ assert undistorted_flat.shape == (10, 2)+ assert undistorted_opencv.shape == (10, 1, 2)+++if __name__ == "__main__":+ pytest.main([__file__])diff --git a/freemocap/utilities/check_main_processs_heartbeat.py b/freemocap/utilities/check_main_processs_heartbeat.pynew file mode 100644index 00000000..18c89988--- /dev/null+++ b/freemocap/utilities/check_main_processs_heartbeat.py@@ -0,0 +1,31 @@+import multiprocessing+import os+import signal+import time++import logging+from typing import Final++logger = logging.getLogger(__name__)+HEARTBEAT_INTERVAL_SECONDS: Final[float] = 1.0+HEARTBEAT_TIMEOUT_SECONDS: Final[float] = 300.0+def check_main_process_heartbeat(*,+ heartbeat_timestamp: multiprocessing.Value,+ global_kill_flag: multiprocessing.Value) -> bool:+ """Check if main process is still alive based on heartbeat."""+ current_time: float = time.perf_counter()+ last_heartbeat: float = heartbeat_timestamp.value++ time_since_heartbeat: float = current_time - last_heartbeat++ if time_since_heartbeat > HEARTBEAT_TIMEOUT_SECONDS:+ logger.error(+ f"Main process heartbeat timeout! "+ f"Last heartbeat was {time_since_heartbeat:.1f}s ago "+ f"(timeout: {HEARTBEAT_TIMEOUT_SECONDS}s)"+ )+ global_kill_flag.value = True+ os.kill(os.getpid(), signal.SIGTERM)+ return False++ return True\ No newline at end of filediff --git a/freemocap/utilities/convert_pydantic_to_zod.py b/freemocap/utilities/convert_pydantic_to_zod.pyindex 1a9fd5a0..51289bb4 100644--- a/freemocap/utilities/convert_pydantic_to_zod.py+++ b/freemocap/utilities/convert_pydantic_to_zod.py@@ -2,7 +2,6 @@ import pydantic2zodfrom pydantic2zod.model import BuiltinType, ClassDecl-class Compiler(pydantic2zod.Compiler):def _modify_models(self, pydantic_models: list[ClassDecl]) -> list[ClassDecl]:@@ -18,4 +17,4 @@ class Compiler(pydantic2zod.Compiler):ts_src = Compiler().parse("skellycam.core.frames.payloads.frontend_image_payload").to_zod()-print(ts_src)\ No newline at end of file+print(ts_src)diff --git a/freemocap/utilities/create_nested_dict_from_pydantic.py b/freemocap/utilities/create_nested_dict_from_pydantic.pydeleted file mode 100644index 3456c84b..00000000--- a/freemocap/utilities/create_nested_dict_from_pydantic.py+++ /dev/null@@ -1,36 +0,0 @@-from ctypes import Union-from typing import get_origin, get_args--from pydantic import BaseModel---def create_nested_dict(pydantic_model):- if not issubclass(pydantic_model, BaseModel):- return str(pydantic_model)-- model_dict = {}- for name, field in pydantic_model.__annotations__.items():- origin = get_origin(field)- if origin is Union:- args = get_args(field)- if type(None) in args:- # Remove 'None' type from Union type- args = tuple(arg for arg in args if arg is not type(None)) # noqa: E721- if len(args) == 1:- field = args[0]- origin = get_origin(field)- if origin is dict or origin is list:- model_dict[name] = str(field)- else:- model_dict[name] = create_nested_dict(field)- return model_dict---if __name__ == "__main__":- from skellytracker.trackers.mediapipe_tracker.mediapipe_model_info import (- MediapipeModelInfo,- )- from freemocap.old.data_layer import SkeletonSchema-- skeleton_schema = SkeletonSchema(schema_dict=MediapipeModelInfo.skeleton_schema)- print(create_nested_dict(skeleton_schema))diff --git a/freemocap/utilities/download_sample_data.py b/freemocap/utilities/download_sample_data.pyindex 11175675..0fda2ba1 100644--- a/freemocap/utilities/download_sample_data.py+++ b/freemocap/utilities/download_sample_data.py@@ -4,7 +4,6 @@ import zipfilefrom pathlib import Pathimport requests-from freemocap.system.paths_and_filenames.file_and_folder_names import (FIGSHARE_SAMPLE_ZIP_FILE_URL,FREEMOCAP_SAMPLE_DATA_RECORDING_NAME,diff --git a/freemocap/utilities/extract_camera_id_from_video_path.py b/freemocap/utilities/extract_camera_id_from_video_path.pynew file mode 100644index 00000000..98c2c903--- /dev/null+++ b/freemocap/utilities/extract_camera_id_from_video_path.py@@ -0,0 +1,70 @@+import re+from pathlib import Path++from pydantic import BaseModel, ConfigDict, model_validator++from freemocap.core.pipeline.posthoc_pipelines.video_helper import VideoHelper, VideoMetadata+from freemocap.core.types.type_overloads import VideoIdString+++def extract_camera_id(filename: str) -> str | None:+ """+ Extract camera ID from filename using regex.++ Handles patterns like:+ - camera1, camera2, cam1, cam2+ - With various delimiters: . _ - or no delimiter+ - Case insensitive++ Args:+ filename: The filename to extract camera ID from++ Returns:+ The camera ID as a string, or None if not found+ """+ # Pattern explanation:+ # (?:camera|cam) - non-capturing group matching either "camera" or "cam"+ # [._\-]? - optional delimiter (dot, underscore, or hyphen)+ # (\d+) - capture group for one or more digits (the camera ID)+ pattern = r'(?:camera|cam)[._\-]?(\d+)'++ match = re.search(pattern, filename.lower())+ if match:+ return match.group(1)+ return None+++++# Test the extraction function+def test_camera_id_extraction():+ test_cases: list[tuple[str, str | None]] = [+ # Your examples+ ("2025-11-10_19-05-16_GMT-5_mocap.camera1.mp4", "1"),+ ("2025-11-10_19-05-16_GMT-5_mocap.camera2.mp4", "2"),++ # Various delimiter formats+ ("video_cam1.mp4", "1"),+ ("video-cam2.mp4", "2"),+ ("video.cam3.mp4", "3"),+ ("videocam4.mp4", "4"),+ ("CAMERA1.mp4", "1"),+ ("Camera_2.mp4", "2"),++ # Multi-digit camera IDs+ ("camera10.mp4", "10"),+ ("cam123.mp4", "123"),++ # Edge cases+ ("no_camera_here.mp4", None),+ ("just_a_video.mp4", None),+ ]++ for filename, expected in test_cases:+ result = extract_camera_id(filename)+ status = "โ" if result == expected else "โ"+ print(f"{status} {filename:40} -> {result} (expected: {expected})")+++if __name__ == "__main__":+ test_camera_id_extraction()diff --git a/freemocap/utilities/fix_opencv_conflict.py b/freemocap/utilities/fix_opencv_conflict.pyindex fe5b434a..94176a18 100644--- a/freemocap/utilities/fix_opencv_conflict.py+++ b/freemocap/utilities/fix_opencv_conflict.py@@ -4,6 +4,7 @@ from importlib.metadata import distributionslogger = logging.getLogger(__name__)+def fix_opencv_conflict():installed_packages = {dist.metadata["Name"] for dist in distributions()}if "opencv-python" in installed_packages and "opencv-contrib-python" in installed_packages:@@ -30,4 +31,4 @@ def fix_opencv_conflict():if __name__ == "__main__":- fix_opencv_conflict()\ No newline at end of file+ fix_opencv_conflict()diff --git a/freemocap/utilities/update_1_4_path_names.py b/freemocap/utilities/update_1_4_path_names.pyindex 3d271c4b..16b820b7 100644--- a/freemocap/utilities/update_1_4_path_names.py+++ b/freemocap/utilities/update_1_4_path_names.py@@ -29,7 +29,7 @@ def update_1_4_path_names(freemocap_data_folder_path: Optional[Union[str, Path]]def update_recording_folder(recording_folder: Path) -> None:if (- recording_folder.name == OUTPUT_DATA_FOLDER_NAME+ recording_folder.name == OUTPUT_DATA_FOLDER_NAME): # this covers cases where the recording folder isn't a subfolder of a sessionrename_skeleton_file_path(recording_folder)if (recording_folder / RAW_DATA_FOLDER_NAME).exists():diff --git a/freemocap/utilities/wait_functions.py b/freemocap/utilities/wait_functions.pynew file mode 100644index 00000000..6dafe68a--- /dev/null+++ b/freemocap/utilities/wait_functions.py@@ -0,0 +1,71 @@+import asyncio+import time+++def wait_1s():+ time.sleep(1.0)+++def wait_100ms():+ time.sleep(0.1)+++def wait_10ms():+ time.sleep(1e-2)+++def wait_30ms():+ """+ Once per frame-ish+ """+ wait_10ms()+ wait_10ms()+ wait_10ms()+++def wait_1ms():+ time.sleep(1e-3)+++def wait_100us():+ time.sleep(1e-4)+++def wait_10us():+ time.sleep(1e-5)+++def wait_1us():+ time.sleep(1e-6)+++async def await_1s():+ await asyncio.sleep(1.0)+++async def await_100ms():+ await asyncio.sleep(1e-1)+++async def await_10ms():+ await asyncio.sleep(1e-2)+++async def await_1ms():+ await asyncio.sleep(1e-3)+++if __name__ == "__main__":+ print("Testing wait functions")++ tic = time.perf_counter_ns()+ for i in range(1000):+ wait_1ms()+ toc = time.perf_counter_ns()+ print(f"WAITED 1ms {1000} times in {(toc - tic) / 1e9} s")++ tic = time.perf_counter_ns()+ for i in range(1000):+ wait_10ms()+ toc = time.perf_counter_ns()+ print(f"WAITED 10ms {1000} times in {(toc - tic) / 1e9} s")diff --git a/pyproject.toml b/pyproject.tomlindex e495bc4f..5c8a18ac 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -9,7 +9,7 @@ dependencies = [# "freemocap-blender-addon","ajc27_freemocap_blender_addon==v2024.12.1032","libsass>=0.23.0",- "opencv-contrib-python>=4.8.1.78",+ "opencv-contrib-python==4.10.*","pyinstaller>=6.11.0","requests>=2.32.3",# "skelly-synchronize",@@ -20,17 +20,14 @@ dependencies = ["pydantic>=2.10.4","numpydantic>=1.6.7",# "ltrt"- "mediapipe>=0.10.21",+ "scikit-learn>=1.7.2",+ "pyceres>=2.5",][tool.uv.sources]skellycam = { git = "https://github.com/freemocap/skellycam", branch = "jon/development" }skellytracker = { git = "https://github.com/freemocap/skellytracker", branch = "jon/development" }-skellyforge = { git = "https://github.com/freemocap/skellyforge" }-#skelly-viewer = { git = "https://github.com/freemocap/skellyviewer" }-#freemocap-blender-addon = { git = "https://github.com/freemocap/freemocap_blender_addon"}#, branch = "jon/development" }-#skelly-synchronize = { git = "https://github.com/freemocap/skelly_synchronize", branch = "jon/development" }-#ltrt = { git = "https://github.com/freemocap/LTRT" }+skellyforge = { git = "https://github.com/freemocap/skellyforge", branch = "jon/development" }[project.scripts]freemocap = "freemocap.__main__:main"diff --git a/shared/logo/freemocap_skelly_logo.ico b/shared/logo/freemocap-logo.icosimilarity index 100%rename from shared/logo/freemocap_skelly_logo.icorename to shared/logo/freemocap-logo.icodiff --git a/shared/logo/freemocap-logo.png b/shared/logo/freemocap-logo.pngnew file mode 100644index 00000000..965d70bdBinary files /dev/null and b/shared/logo/freemocap-logo.png differdiff --git a/shared/logo/freemocap-logo-black-border.svg b/shared/logo/freemocap-logo.svgsimilarity index 100%rename from shared/logo/freemocap-logo-black-border.svgrename to shared/logo/freemocap-logo.svgdiff --git a/uv.lock b/uv.lockindex 202ac4db..91460b3c 100644--- a/uv.lock+++ b/uv.lock@@ -57,6 +57,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/b9/92/f42ac9b51451f051be1edae7bb33171b270e671b7ad97a9bcd98f4ca4af0/aniposelib-0.7.2-py3-none-any.whl", hash = "sha256:07534e7ba3554770bd4f04c18526bba75559897df4abc7145c4c84e0596c3b01", size = 22824 },]+[[package]]+name = "annotated-doc"+version = "0.0.4"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/57/ba/046ceea27344560984e26a590f90bc7f4a75b06701f653222458922b558c/annotated_doc-0.0.4.tar.gz", hash = "sha256:fbcda96e87e9c92ad167c2e53839e57503ecfda18804ea28102353485033faa4", size = 7288 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/1e/d3/26bf1008eb3d2daa8ef4cacc7f3bfdc11818d111f7e2d0201bc6e3b49d45/annotated_doc-0.0.4-py3-none-any.whl", hash = "sha256:571ac1dc6991c450b25a9c2d84a3705e2ae7a53467b5d111c24fa8baabbed320", size = 5303 },+]+[[package]]name = "annotated-types"version = "0.7.0"@@ -68,25 +77,25 @@ wheels = [[[package]]name = "anyio"-version = "4.10.0"+version = "4.11.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "idna" },{ name = "sniffio" },{ name = "typing-extensions", marker = "python_full_version < '3.13'" },]-sdist = { url = "https://files.pythonhosted.org/packages/f1/b4/636b3b65173d3ce9a38ef5f0522789614e590dab6a8d505340a4efe4c567/anyio-4.10.0.tar.gz", hash = "sha256:3f3fae35c96039744587aa5b8371e7e8e603c0702999535961dd336026973ba6", size = 213252 }+sdist = { url = "https://files.pythonhosted.org/packages/c6/78/7d432127c41b50bccba979505f272c16cbcadcc33645d5fa3a738110ae75/anyio-4.11.0.tar.gz", hash = "sha256:82a8d0b81e318cc5ce71a5f1f8b5c4e63619620b63141ef8c995fa0db95a57c4", size = 219094 }wheels = [- { url = "https://files.pythonhosted.org/packages/6f/12/e5e0282d673bb9746bacfb6e2dba8719989d3660cdb2ea79aee9a9651afb/anyio-4.10.0-py3-none-any.whl", hash = "sha256:60e474ac86736bbfd6f210f7a61218939c318f43f9972497381f1c5e930ed3d1", size = 107213 },+ { url = "https://files.pythonhosted.org/packages/15/b3/9b1a8074496371342ec1e796a96f99c82c945a339cd81a8e73de28b4cf9e/anyio-4.11.0-py3-none-any.whl", hash = "sha256:0287e96f4d26d4149305414d4e3bc32f0dcd0862365a4bddea19d7a1ec38c4fc", size = 109097 },][[package]]name = "attrs"-version = "25.3.0"+version = "25.4.0"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/5a/b0/1367933a8532ee6ff8d63537de4f1177af4bff9f3e829baf7331f595bb24/attrs-25.3.0.tar.gz", hash = "sha256:75d7cefc7fb576747b2c81b4442d4d4a1ce0900973527c011d1030fd3bf4af1b", size = 812032 }+sdist = { url = "https://files.pythonhosted.org/packages/6b/5c/685e6633917e101e5dcb62b9dd76946cbb57c26e133bae9e0cd36033c0a9/attrs-25.4.0.tar.gz", hash = "sha256:16d5969b87f0859ef33a48b35d55ac1be6e42ae49d5e853b597db70c35c57e11", size = 934251 }wheels = [- { url = "https://files.pythonhosted.org/packages/77/06/bb80f5f86020c4551da315d78b3ab75e8228f89f0162f2c3a819e407941a/attrs-25.3.0-py3-none-any.whl", hash = "sha256:427318ce031701fea540783410126f03899a97ffc6f61596ad581ac2e40e3bc3", size = 63815 },+ { url = "https://files.pythonhosted.org/packages/3a/2a/7cc015f5b9f5db42b7d48157e23356022889fc354a2813c15934b7cb5c0e/attrs-25.4.0-py3-none-any.whl", hash = "sha256:adcf7e2a1fb3b36ac48d97835bb6d8ade15b8dcce26aba8bf1d14847b57a3373", size = 67615 },][[package]]@@ -106,121 +115,166 @@ wheels = [[[package]]name = "certifi"-version = "2025.8.3"+version = "2025.11.12"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/dc/67/960ebe6bf230a96cda2e0abcf73af550ec4f090005363542f0765df162e0/certifi-2025.8.3.tar.gz", hash = "sha256:e564105f78ded564e3ae7c923924435e1daa7463faeab5bb932bc53ffae63407", size = 162386 }+sdist = { url = "https://files.pythonhosted.org/packages/a2/8c/58f469717fa48465e4a50c014a0400602d3c437d7c0c468e17ada824da3a/certifi-2025.11.12.tar.gz", hash = "sha256:d8ab5478f2ecd78af242878415affce761ca6bc54a22a27e026d7c25357c3316", size = 160538 }wheels = [- { url = "https://files.pythonhosted.org/packages/e5/48/1549795ba7742c948d2ad169c1c8cdbae65bc450d6cd753d124b17c8cd32/certifi-2025.8.3-py3-none-any.whl", hash = "sha256:f6c12493cfb1b06ba2ff328595af9350c65d6644968e5d3a2ffd78699af217a5", size = 161216 },+ { url = "https://files.pythonhosted.org/packages/70/7d/9bc192684cea499815ff478dfcdc13835ddf401365057044fb721ec6bddb/certifi-2025.11.12-py3-none-any.whl", hash = "sha256:97de8790030bbd5c2d96b7ec782fc2f7820ef8dba6db909ccf95449f2d062d4b", size = 159438 },][[package]]name = "cffi"-version = "1.17.1"+version = "2.0.0"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "pycparser" },-]-sdist = { url = "https://files.pythonhosted.org/packages/fc/97/c783634659c2920c3fc70419e3af40972dbaf758daa229a7d6ea6135c90d/cffi-1.17.1.tar.gz", hash = "sha256:1c39c6016c32bc48dd54561950ebd6836e1670f2ae46128f67cf49e789c52824", size = 516621 }-wheels = [- { url = "https://files.pythonhosted.org/packages/6b/f4/927e3a8899e52a27fa57a48607ff7dc91a9ebe97399b357b85a0c7892e00/cffi-1.17.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:a45e3c6913c5b87b3ff120dcdc03f6131fa0065027d0ed7ee6190736a74cd401", size = 182264 },- { url = "https://files.pythonhosted.org/packages/6c/f5/6c3a8efe5f503175aaddcbea6ad0d2c96dad6f5abb205750d1b3df44ef29/cffi-1.17.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:30c5e0cb5ae493c04c8b42916e52ca38079f1b235c2f8ae5f4527b963c401caf", size = 178651 },- { url = "https://files.pythonhosted.org/packages/94/dd/a3f0118e688d1b1a57553da23b16bdade96d2f9bcda4d32e7d2838047ff7/cffi-1.17.1-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f75c7ab1f9e4aca5414ed4d8e5c0e303a34f4421f8a0d47a4d019ceff0ab6af4", size = 445259 },- { url = "https://files.pythonhosted.org/packages/2e/ea/70ce63780f096e16ce8588efe039d3c4f91deb1dc01e9c73a287939c79a6/cffi-1.17.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a1ed2dd2972641495a3ec98445e09766f077aee98a1c896dcb4ad0d303628e41", size = 469200 },- { url = "https://files.pythonhosted.org/packages/1c/a0/a4fa9f4f781bda074c3ddd57a572b060fa0df7655d2a4247bbe277200146/cffi-1.17.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:46bf43160c1a35f7ec506d254e5c890f3c03648a4dbac12d624e4490a7046cd1", size = 477235 },- { url = "https://files.pythonhosted.org/packages/62/12/ce8710b5b8affbcdd5c6e367217c242524ad17a02fe5beec3ee339f69f85/cffi-1.17.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a24ed04c8ffd54b0729c07cee15a81d964e6fee0e3d4d342a27b020d22959dc6", size = 459721 },- { url = "https://files.pythonhosted.org/packages/ff/6b/d45873c5e0242196f042d555526f92aa9e0c32355a1be1ff8c27f077fd37/cffi-1.17.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:610faea79c43e44c71e1ec53a554553fa22321b65fae24889706c0a84d4ad86d", size = 467242 },- { url = "https://files.pythonhosted.org/packages/1a/52/d9a0e523a572fbccf2955f5abe883cfa8bcc570d7faeee06336fbd50c9fc/cffi-1.17.1-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:a9b15d491f3ad5d692e11f6b71f7857e7835eb677955c00cc0aefcd0669adaf6", size = 477999 },- { url = "https://files.pythonhosted.org/packages/44/74/f2a2460684a1a2d00ca799ad880d54652841a780c4c97b87754f660c7603/cffi-1.17.1-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:de2ea4b5833625383e464549fec1bc395c1bdeeb5f25c4a3a82b5a8c756ec22f", size = 454242 },- { url = "https://files.pythonhosted.org/packages/f8/4a/34599cac7dfcd888ff54e801afe06a19c17787dfd94495ab0c8d35fe99fb/cffi-1.17.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:fc48c783f9c87e60831201f2cce7f3b2e4846bf4d8728eabe54d60700b318a0b", size = 478604 },- { url = "https://files.pythonhosted.org/packages/34/33/e1b8a1ba29025adbdcda5fb3a36f94c03d771c1b7b12f726ff7fef2ebe36/cffi-1.17.1-cp311-cp311-win32.whl", hash = "sha256:85a950a4ac9c359340d5963966e3e0a94a676bd6245a4b55bc43949eee26a655", size = 171727 },- { url = "https://files.pythonhosted.org/packages/3d/97/50228be003bb2802627d28ec0627837ac0bf35c90cf769812056f235b2d1/cffi-1.17.1-cp311-cp311-win_amd64.whl", hash = "sha256:caaf0640ef5f5517f49bc275eca1406b0ffa6aa184892812030f04c2abf589a0", size = 181400 },- { url = "https://files.pythonhosted.org/packages/5a/84/e94227139ee5fb4d600a7a4927f322e1d4aea6fdc50bd3fca8493caba23f/cffi-1.17.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:805b4371bf7197c329fcb3ead37e710d1bca9da5d583f5073b799d5c5bd1eee4", size = 183178 },- { url = "https://files.pythonhosted.org/packages/da/ee/fb72c2b48656111c4ef27f0f91da355e130a923473bf5ee75c5643d00cca/cffi-1.17.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:733e99bc2df47476e3848417c5a4540522f234dfd4ef3ab7fafdf555b082ec0c", size = 178840 },- { url = "https://files.pythonhosted.org/packages/cc/b6/db007700f67d151abadf508cbfd6a1884f57eab90b1bb985c4c8c02b0f28/cffi-1.17.1-cp312-cp312-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1257bdabf294dceb59f5e70c64a3e2f462c30c7ad68092d01bbbfb1c16b1ba36", size = 454803 },- { url = "https://files.pythonhosted.org/packages/1a/df/f8d151540d8c200eb1c6fba8cd0dfd40904f1b0682ea705c36e6c2e97ab3/cffi-1.17.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:da95af8214998d77a98cc14e3a3bd00aa191526343078b530ceb0bd710fb48a5", size = 478850 },- { url = "https://files.pythonhosted.org/packages/28/c0/b31116332a547fd2677ae5b78a2ef662dfc8023d67f41b2a83f7c2aa78b1/cffi-1.17.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d63afe322132c194cf832bfec0dc69a99fb9bb6bbd550f161a49e9e855cc78ff", size = 485729 },- { url = "https://files.pythonhosted.org/packages/91/2b/9a1ddfa5c7f13cab007a2c9cc295b70fbbda7cb10a286aa6810338e60ea1/cffi-1.17.1-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f79fc4fc25f1c8698ff97788206bb3c2598949bfe0fef03d299eb1b5356ada99", size = 471256 },- { url = "https://files.pythonhosted.org/packages/b2/d5/da47df7004cb17e4955df6a43d14b3b4ae77737dff8bf7f8f333196717bf/cffi-1.17.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b62ce867176a75d03a665bad002af8e6d54644fad99a3c70905c543130e39d93", size = 479424 },- { url = "https://files.pythonhosted.org/packages/0b/ac/2a28bcf513e93a219c8a4e8e125534f4f6db03e3179ba1c45e949b76212c/cffi-1.17.1-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:386c8bf53c502fff58903061338ce4f4950cbdcb23e2902d86c0f722b786bbe3", size = 484568 },- { url = "https://files.pythonhosted.org/packages/d4/38/ca8a4f639065f14ae0f1d9751e70447a261f1a30fa7547a828ae08142465/cffi-1.17.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:4ceb10419a9adf4460ea14cfd6bc43d08701f0835e979bf821052f1805850fe8", size = 488736 },- { url = "https://files.pythonhosted.org/packages/86/c5/28b2d6f799ec0bdecf44dced2ec5ed43e0eb63097b0f58c293583b406582/cffi-1.17.1-cp312-cp312-win32.whl", hash = "sha256:a08d7e755f8ed21095a310a693525137cfe756ce62d066e53f502a83dc550f65", size = 172448 },- { url = "https://files.pythonhosted.org/packages/50/b9/db34c4755a7bd1cb2d1603ac3863f22bcecbd1ba29e5ee841a4bc510b294/cffi-1.17.1-cp312-cp312-win_amd64.whl", hash = "sha256:51392eae71afec0d0c8fb1a53b204dbb3bcabcb3c9b807eedf3e1e6ccf2de903", size = 181976 },- { url = "https://files.pythonhosted.org/packages/8d/f8/dd6c246b148639254dad4d6803eb6a54e8c85c6e11ec9df2cffa87571dbe/cffi-1.17.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f3a2b4222ce6b60e2e8b337bb9596923045681d71e5a082783484d845390938e", size = 182989 },- { url = "https://files.pythonhosted.org/packages/8b/f1/672d303ddf17c24fc83afd712316fda78dc6fce1cd53011b839483e1ecc8/cffi-1.17.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:0984a4925a435b1da406122d4d7968dd861c1385afe3b45ba82b750f229811e2", size = 178802 },- { url = "https://files.pythonhosted.org/packages/0e/2d/eab2e858a91fdff70533cab61dcff4a1f55ec60425832ddfdc9cd36bc8af/cffi-1.17.1-cp313-cp313-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d01b12eeeb4427d3110de311e1774046ad344f5b1a7403101878976ecd7a10f3", size = 454792 },- { url = "https://files.pythonhosted.org/packages/75/b2/fbaec7c4455c604e29388d55599b99ebcc250a60050610fadde58932b7ee/cffi-1.17.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:706510fe141c86a69c8ddc029c7910003a17353970cff3b904ff0686a5927683", size = 478893 },- { url = "https://files.pythonhosted.org/packages/4f/b7/6e4a2162178bf1935c336d4da8a9352cccab4d3a5d7914065490f08c0690/cffi-1.17.1-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:de55b766c7aa2e2a3092c51e0483d700341182f08e67c63630d5b6f200bb28e5", size = 485810 },- { url = "https://files.pythonhosted.org/packages/c7/8a/1d0e4a9c26e54746dc08c2c6c037889124d4f59dffd853a659fa545f1b40/cffi-1.17.1-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c59d6e989d07460165cc5ad3c61f9fd8f1b4796eacbd81cee78957842b834af4", size = 471200 },- { url = "https://files.pythonhosted.org/packages/26/9f/1aab65a6c0db35f43c4d1b4f580e8df53914310afc10ae0397d29d697af4/cffi-1.17.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dd398dbc6773384a17fe0d3e7eeb8d1a21c2200473ee6806bb5e6a8e62bb73dd", size = 479447 },- { url = "https://files.pythonhosted.org/packages/5f/e4/fb8b3dd8dc0e98edf1135ff067ae070bb32ef9d509d6cb0f538cd6f7483f/cffi-1.17.1-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:3edc8d958eb099c634dace3c7e16560ae474aa3803a5df240542b305d14e14ed", size = 484358 },- { url = "https://files.pythonhosted.org/packages/f1/47/d7145bf2dc04684935d57d67dff9d6d795b2ba2796806bb109864be3a151/cffi-1.17.1-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:72e72408cad3d5419375fc87d289076ee319835bdfa2caad331e377589aebba9", size = 488469 },- { url = "https://files.pythonhosted.org/packages/bf/ee/f94057fa6426481d663b88637a9a10e859e492c73d0384514a17d78ee205/cffi-1.17.1-cp313-cp313-win32.whl", hash = "sha256:e03eab0a8677fa80d646b5ddece1cbeaf556c313dcfac435ba11f107ba117b5d", size = 172475 },- { url = "https://files.pythonhosted.org/packages/7c/fc/6a8cb64e5f0324877d503c854da15d76c1e50eb722e320b15345c4d0c6de/cffi-1.17.1-cp313-cp313-win_amd64.whl", hash = "sha256:f6a16c31041f09ead72d69f583767292f750d24913dadacf5756b966aacb3f1a", size = 182009 },+ { name = "pycparser", marker = "implementation_name != 'PyPy'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/eb/56/b1ba7935a17738ae8453301356628e8147c79dbb825bcbc73dc7401f9846/cffi-2.0.0.tar.gz", hash = "sha256:44d1b5909021139fe36001ae048dbdde8214afa20200eda0f64c068cac5d5529", size = 523588 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/12/4a/3dfd5f7850cbf0d06dc84ba9aa00db766b52ca38d8b86e3a38314d52498c/cffi-2.0.0-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:b4c854ef3adc177950a8dfc81a86f5115d2abd545751a304c5bcf2c2c7283cfe", size = 184344 },+ { url = "https://files.pythonhosted.org/packages/4f/8b/f0e4c441227ba756aafbe78f117485b25bb26b1c059d01f137fa6d14896b/cffi-2.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:2de9a304e27f7596cd03d16f1b7c72219bd944e99cc52b84d0145aefb07cbd3c", size = 180560 },+ { url = "https://files.pythonhosted.org/packages/b1/b7/1200d354378ef52ec227395d95c2576330fd22a869f7a70e88e1447eb234/cffi-2.0.0-cp311-cp311-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:baf5215e0ab74c16e2dd324e8ec067ef59e41125d3eade2b863d294fd5035c92", size = 209613 },+ { url = "https://files.pythonhosted.org/packages/b8/56/6033f5e86e8cc9bb629f0077ba71679508bdf54a9a5e112a3c0b91870332/cffi-2.0.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:730cacb21e1bdff3ce90babf007d0a0917cc3e6492f336c2f0134101e0944f93", size = 216476 },+ { url = "https://files.pythonhosted.org/packages/dc/7f/55fecd70f7ece178db2f26128ec41430d8720f2d12ca97bf8f0a628207d5/cffi-2.0.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:6824f87845e3396029f3820c206e459ccc91760e8fa24422f8b0c3d1731cbec5", size = 203374 },+ { url = "https://files.pythonhosted.org/packages/84/ef/a7b77c8bdc0f77adc3b46888f1ad54be8f3b7821697a7b89126e829e676a/cffi-2.0.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:9de40a7b0323d889cf8d23d1ef214f565ab154443c42737dfe52ff82cf857664", size = 202597 },+ { url = "https://files.pythonhosted.org/packages/d7/91/500d892b2bf36529a75b77958edfcd5ad8e2ce4064ce2ecfeab2125d72d1/cffi-2.0.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8941aaadaf67246224cee8c3803777eed332a19d909b47e29c9842ef1e79ac26", size = 215574 },+ { url = "https://files.pythonhosted.org/packages/44/64/58f6255b62b101093d5df22dcb752596066c7e89dd725e0afaed242a61be/cffi-2.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:a05d0c237b3349096d3981b727493e22147f934b20f6f125a3eba8f994bec4a9", size = 218971 },+ { url = "https://files.pythonhosted.org/packages/ab/49/fa72cebe2fd8a55fbe14956f9970fe8eb1ac59e5df042f603ef7c8ba0adc/cffi-2.0.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:94698a9c5f91f9d138526b48fe26a199609544591f859c870d477351dc7b2414", size = 211972 },+ { url = "https://files.pythonhosted.org/packages/0b/28/dd0967a76aab36731b6ebfe64dec4e981aff7e0608f60c2d46b46982607d/cffi-2.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:5fed36fccc0612a53f1d4d9a816b50a36702c28a2aa880cb8a122b3466638743", size = 217078 },+ { url = "https://files.pythonhosted.org/packages/2b/c0/015b25184413d7ab0a410775fdb4a50fca20f5589b5dab1dbbfa3baad8ce/cffi-2.0.0-cp311-cp311-win32.whl", hash = "sha256:c649e3a33450ec82378822b3dad03cc228b8f5963c0c12fc3b1e0ab940f768a5", size = 172076 },+ { url = "https://files.pythonhosted.org/packages/ae/8f/dc5531155e7070361eb1b7e4c1a9d896d0cb21c49f807a6c03fd63fc877e/cffi-2.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:66f011380d0e49ed280c789fbd08ff0d40968ee7b665575489afa95c98196ab5", size = 182820 },+ { url = "https://files.pythonhosted.org/packages/95/5c/1b493356429f9aecfd56bc171285a4c4ac8697f76e9bbbbb105e537853a1/cffi-2.0.0-cp311-cp311-win_arm64.whl", hash = "sha256:c6638687455baf640e37344fe26d37c404db8b80d037c3d29f58fe8d1c3b194d", size = 177635 },+ { url = "https://files.pythonhosted.org/packages/ea/47/4f61023ea636104d4f16ab488e268b93008c3d0bb76893b1b31db1f96802/cffi-2.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6d02d6655b0e54f54c4ef0b94eb6be0607b70853c45ce98bd278dc7de718be5d", size = 185271 },+ { url = "https://files.pythonhosted.org/packages/df/a2/781b623f57358e360d62cdd7a8c681f074a71d445418a776eef0aadb4ab4/cffi-2.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8eca2a813c1cb7ad4fb74d368c2ffbbb4789d377ee5bb8df98373c2cc0dee76c", size = 181048 },+ { url = "https://files.pythonhosted.org/packages/ff/df/a4f0fbd47331ceeba3d37c2e51e9dfc9722498becbeec2bd8bc856c9538a/cffi-2.0.0-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:21d1152871b019407d8ac3985f6775c079416c282e431a4da6afe7aefd2bccbe", size = 212529 },+ { url = "https://files.pythonhosted.org/packages/d5/72/12b5f8d3865bf0f87cf1404d8c374e7487dcf097a1c91c436e72e6badd83/cffi-2.0.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b21e08af67b8a103c71a250401c78d5e0893beff75e28c53c98f4de42f774062", size = 220097 },+ { url = "https://files.pythonhosted.org/packages/c2/95/7a135d52a50dfa7c882ab0ac17e8dc11cec9d55d2c18dda414c051c5e69e/cffi-2.0.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:1e3a615586f05fc4065a8b22b8152f0c1b00cdbc60596d187c2a74f9e3036e4e", size = 207983 },+ { url = "https://files.pythonhosted.org/packages/3a/c8/15cb9ada8895957ea171c62dc78ff3e99159ee7adb13c0123c001a2546c1/cffi-2.0.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:81afed14892743bbe14dacb9e36d9e0e504cd204e0b165062c488942b9718037", size = 206519 },+ { url = "https://files.pythonhosted.org/packages/78/2d/7fa73dfa841b5ac06c7b8855cfc18622132e365f5b81d02230333ff26e9e/cffi-2.0.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3e17ed538242334bf70832644a32a7aae3d83b57567f9fd60a26257e992b79ba", size = 219572 },+ { url = "https://files.pythonhosted.org/packages/07/e0/267e57e387b4ca276b90f0434ff88b2c2241ad72b16d31836adddfd6031b/cffi-2.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3925dd22fa2b7699ed2617149842d2e6adde22b262fcbfada50e3d195e4b3a94", size = 222963 },+ { url = "https://files.pythonhosted.org/packages/b6/75/1f2747525e06f53efbd878f4d03bac5b859cbc11c633d0fb81432d98a795/cffi-2.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2c8f814d84194c9ea681642fd164267891702542f028a15fc97d4674b6206187", size = 221361 },+ { url = "https://files.pythonhosted.org/packages/7b/2b/2b6435f76bfeb6bbf055596976da087377ede68df465419d192acf00c437/cffi-2.0.0-cp312-cp312-win32.whl", hash = "sha256:da902562c3e9c550df360bfa53c035b2f241fed6d9aef119048073680ace4a18", size = 172932 },+ { url = "https://files.pythonhosted.org/packages/f8/ed/13bd4418627013bec4ed6e54283b1959cf6db888048c7cf4b4c3b5b36002/cffi-2.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:da68248800ad6320861f129cd9c1bf96ca849a2771a59e0344e88681905916f5", size = 183557 },+ { url = "https://files.pythonhosted.org/packages/95/31/9f7f93ad2f8eff1dbc1c3656d7ca5bfd8fb52c9d786b4dcf19b2d02217fa/cffi-2.0.0-cp312-cp312-win_arm64.whl", hash = "sha256:4671d9dd5ec934cb9a73e7ee9676f9362aba54f7f34910956b84d727b0d73fb6", size = 177762 },+ { url = "https://files.pythonhosted.org/packages/4b/8d/a0a47a0c9e413a658623d014e91e74a50cdd2c423f7ccfd44086ef767f90/cffi-2.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:00bdf7acc5f795150faa6957054fbbca2439db2f775ce831222b66f192f03beb", size = 185230 },+ { url = "https://files.pythonhosted.org/packages/4a/d2/a6c0296814556c68ee32009d9c2ad4f85f2707cdecfd7727951ec228005d/cffi-2.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:45d5e886156860dc35862657e1494b9bae8dfa63bf56796f2fb56e1679fc0bca", size = 181043 },+ { url = "https://files.pythonhosted.org/packages/b0/1e/d22cc63332bd59b06481ceaac49d6c507598642e2230f201649058a7e704/cffi-2.0.0-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:07b271772c100085dd28b74fa0cd81c8fb1a3ba18b21e03d7c27f3436a10606b", size = 212446 },+ { url = "https://files.pythonhosted.org/packages/a9/f5/a2c23eb03b61a0b8747f211eb716446c826ad66818ddc7810cc2cc19b3f2/cffi-2.0.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d48a880098c96020b02d5a1f7d9251308510ce8858940e6fa99ece33f610838b", size = 220101 },+ { url = "https://files.pythonhosted.org/packages/f2/7f/e6647792fc5850d634695bc0e6ab4111ae88e89981d35ac269956605feba/cffi-2.0.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:f93fd8e5c8c0a4aa1f424d6173f14a892044054871c771f8566e4008eaa359d2", size = 207948 },+ { url = "https://files.pythonhosted.org/packages/cb/1e/a5a1bd6f1fb30f22573f76533de12a00bf274abcdc55c8edab639078abb6/cffi-2.0.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:dd4f05f54a52fb558f1ba9f528228066954fee3ebe629fc1660d874d040ae5a3", size = 206422 },+ { url = "https://files.pythonhosted.org/packages/98/df/0a1755e750013a2081e863e7cd37e0cdd02664372c754e5560099eb7aa44/cffi-2.0.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c8d3b5532fc71b7a77c09192b4a5a200ea992702734a2e9279a37f2478236f26", size = 219499 },+ { url = "https://files.pythonhosted.org/packages/50/e1/a969e687fcf9ea58e6e2a928ad5e2dd88cc12f6f0ab477e9971f2309b57c/cffi-2.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d9b29c1f0ae438d5ee9acb31cadee00a58c46cc9c0b2f9038c6b0b3470877a8c", size = 222928 },+ { url = "https://files.pythonhosted.org/packages/36/54/0362578dd2c9e557a28ac77698ed67323ed5b9775ca9d3fe73fe191bb5d8/cffi-2.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6d50360be4546678fc1b79ffe7a66265e28667840010348dd69a314145807a1b", size = 221302 },+ { url = "https://files.pythonhosted.org/packages/eb/6d/bf9bda840d5f1dfdbf0feca87fbdb64a918a69bca42cfa0ba7b137c48cb8/cffi-2.0.0-cp313-cp313-win32.whl", hash = "sha256:74a03b9698e198d47562765773b4a8309919089150a0bb17d829ad7b44b60d27", size = 172909 },+ { url = "https://files.pythonhosted.org/packages/37/18/6519e1ee6f5a1e579e04b9ddb6f1676c17368a7aba48299c3759bbc3c8b3/cffi-2.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:19f705ada2530c1167abacb171925dd886168931e0a7b78f5bffcae5c6b5be75", size = 183402 },+ { url = "https://files.pythonhosted.org/packages/cb/0e/02ceeec9a7d6ee63bb596121c2c8e9b3a9e150936f4fbef6ca1943e6137c/cffi-2.0.0-cp313-cp313-win_arm64.whl", hash = "sha256:256f80b80ca3853f90c21b23ee78cd008713787b1b1e93eae9f3d6a7134abd91", size = 177780 },+ { url = "https://files.pythonhosted.org/packages/92/c4/3ce07396253a83250ee98564f8d7e9789fab8e58858f35d07a9a2c78de9f/cffi-2.0.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:fc33c5141b55ed366cfaad382df24fe7dcbc686de5be719b207bb248e3053dc5", size = 185320 },+ { url = "https://files.pythonhosted.org/packages/59/dd/27e9fa567a23931c838c6b02d0764611c62290062a6d4e8ff7863daf9730/cffi-2.0.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c654de545946e0db659b3400168c9ad31b5d29593291482c43e3564effbcee13", size = 181487 },+ { url = "https://files.pythonhosted.org/packages/d6/43/0e822876f87ea8a4ef95442c3d766a06a51fc5298823f884ef87aaad168c/cffi-2.0.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:24b6f81f1983e6df8db3adc38562c83f7d4a0c36162885ec7f7b77c7dcbec97b", size = 220049 },+ { url = "https://files.pythonhosted.org/packages/b4/89/76799151d9c2d2d1ead63c2429da9ea9d7aac304603de0c6e8764e6e8e70/cffi-2.0.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:12873ca6cb9b0f0d3a0da705d6086fe911591737a59f28b7936bdfed27c0d47c", size = 207793 },+ { url = "https://files.pythonhosted.org/packages/bb/dd/3465b14bb9e24ee24cb88c9e3730f6de63111fffe513492bf8c808a3547e/cffi-2.0.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:d9b97165e8aed9272a6bb17c01e3cc5871a594a446ebedc996e2397a1c1ea8ef", size = 206300 },+ { url = "https://files.pythonhosted.org/packages/47/d9/d83e293854571c877a92da46fdec39158f8d7e68da75bf73581225d28e90/cffi-2.0.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:afb8db5439b81cf9c9d0c80404b60c3cc9c3add93e114dcae767f1477cb53775", size = 219244 },+ { url = "https://files.pythonhosted.org/packages/2b/0f/1f177e3683aead2bb00f7679a16451d302c436b5cbf2505f0ea8146ef59e/cffi-2.0.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:737fe7d37e1a1bffe70bd5754ea763a62a066dc5913ca57e957824b72a85e205", size = 222828 },+ { url = "https://files.pythonhosted.org/packages/c6/0f/cafacebd4b040e3119dcb32fed8bdef8dfe94da653155f9d0b9dc660166e/cffi-2.0.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:38100abb9d1b1435bc4cc340bb4489635dc2f0da7456590877030c9b3d40b0c1", size = 220926 },+ { url = "https://files.pythonhosted.org/packages/3e/aa/df335faa45b395396fcbc03de2dfcab242cd61a9900e914fe682a59170b1/cffi-2.0.0-cp314-cp314-win32.whl", hash = "sha256:087067fa8953339c723661eda6b54bc98c5625757ea62e95eb4898ad5e776e9f", size = 175328 },+ { url = "https://files.pythonhosted.org/packages/bb/92/882c2d30831744296ce713f0feb4c1cd30f346ef747b530b5318715cc367/cffi-2.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:203a48d1fb583fc7d78a4c6655692963b860a417c0528492a6bc21f1aaefab25", size = 185650 },+ { url = "https://files.pythonhosted.org/packages/9f/2c/98ece204b9d35a7366b5b2c6539c350313ca13932143e79dc133ba757104/cffi-2.0.0-cp314-cp314-win_arm64.whl", hash = "sha256:dbd5c7a25a7cb98f5ca55d258b103a2054f859a46ae11aaf23134f9cc0d356ad", size = 180687 },+ { url = "https://files.pythonhosted.org/packages/3e/61/c768e4d548bfa607abcda77423448df8c471f25dbe64fb2ef6d555eae006/cffi-2.0.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:9a67fc9e8eb39039280526379fb3a70023d77caec1852002b4da7e8b270c4dd9", size = 188773 },+ { url = "https://files.pythonhosted.org/packages/2c/ea/5f76bce7cf6fcd0ab1a1058b5af899bfbef198bea4d5686da88471ea0336/cffi-2.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7a66c7204d8869299919db4d5069a82f1561581af12b11b3c9f48c584eb8743d", size = 185013 },+ { url = "https://files.pythonhosted.org/packages/be/b4/c56878d0d1755cf9caa54ba71e5d049479c52f9e4afc230f06822162ab2f/cffi-2.0.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:7cc09976e8b56f8cebd752f7113ad07752461f48a58cbba644139015ac24954c", size = 221593 },+ { url = "https://files.pythonhosted.org/packages/e0/0d/eb704606dfe8033e7128df5e90fee946bbcb64a04fcdaa97321309004000/cffi-2.0.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:92b68146a71df78564e4ef48af17551a5ddd142e5190cdf2c5624d0c3ff5b2e8", size = 209354 },+ { url = "https://files.pythonhosted.org/packages/d8/19/3c435d727b368ca475fb8742ab97c9cb13a0de600ce86f62eab7fa3eea60/cffi-2.0.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:b1e74d11748e7e98e2f426ab176d4ed720a64412b6a15054378afdb71e0f37dc", size = 208480 },+ { url = "https://files.pythonhosted.org/packages/d0/44/681604464ed9541673e486521497406fadcc15b5217c3e326b061696899a/cffi-2.0.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:28a3a209b96630bca57cce802da70c266eb08c6e97e5afd61a75611ee6c64592", size = 221584 },+ { url = "https://files.pythonhosted.org/packages/25/8e/342a504ff018a2825d395d44d63a767dd8ebc927ebda557fecdaca3ac33a/cffi-2.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:7553fb2090d71822f02c629afe6042c299edf91ba1bf94951165613553984512", size = 224443 },+ { url = "https://files.pythonhosted.org/packages/e1/5e/b666bacbbc60fbf415ba9988324a132c9a7a0448a9a8f125074671c0f2c3/cffi-2.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:6c6c373cfc5c83a975506110d17457138c8c63016b563cc9ed6e056a82f13ce4", size = 223437 },+ { url = "https://files.pythonhosted.org/packages/a0/1d/ec1a60bd1a10daa292d3cd6bb0b359a81607154fb8165f3ec95fe003b85c/cffi-2.0.0-cp314-cp314t-win32.whl", hash = "sha256:1fc9ea04857caf665289b7a75923f2c6ed559b8298a1b8c49e59f7dd95c8481e", size = 180487 },+ { url = "https://files.pythonhosted.org/packages/bf/41/4c1168c74fac325c0c8156f04b6749c8b6a8f405bbf91413ba088359f60d/cffi-2.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:d68b6cef7827e8641e8ef16f4494edda8b36104d79773a334beaa1e3521430f6", size = 191726 },+ { url = "https://files.pythonhosted.org/packages/ae/3a/dbeec9d1ee0844c679f6bb5d6ad4e9f198b1224f4e7a32825f47f6192b0c/cffi-2.0.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0a1527a803f0a659de1af2e1fd700213caba79377e27e4693648c2923da066f9", size = 184195 },][[package]]name = "charset-normalizer"-version = "3.4.3"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/83/2d/5fd176ceb9b2fc619e63405525573493ca23441330fcdaee6bef9460e924/charset_normalizer-3.4.3.tar.gz", hash = "sha256:6fce4b8500244f6fcb71465d4a4930d132ba9ab8e71a7859e6a5d59851068d14", size = 122371 }-wheels = [- { url = "https://files.pythonhosted.org/packages/7f/b5/991245018615474a60965a7c9cd2b4efbaabd16d582a5547c47ee1c7730b/charset_normalizer-3.4.3-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:b256ee2e749283ef3ddcff51a675ff43798d92d746d1a6e4631bf8c707d22d0b", size = 204483 },- { url = "https://files.pythonhosted.org/packages/c7/2a/ae245c41c06299ec18262825c1569c5d3298fc920e4ddf56ab011b417efd/charset_normalizer-3.4.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:13faeacfe61784e2559e690fc53fa4c5ae97c6fcedb8eb6fb8d0a15b475d2c64", size = 145520 },- { url = "https://files.pythonhosted.org/packages/3a/a4/b3b6c76e7a635748c4421d2b92c7b8f90a432f98bda5082049af37ffc8e3/charset_normalizer-3.4.3-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:00237675befef519d9af72169d8604a067d92755e84fe76492fef5441db05b91", size = 158876 },- { url = "https://files.pythonhosted.org/packages/e2/e6/63bb0e10f90a8243c5def74b5b105b3bbbfb3e7bb753915fe333fb0c11ea/charset_normalizer-3.4.3-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:585f3b2a80fbd26b048a0be90c5aae8f06605d3c92615911c3a2b03a8a3b796f", size = 156083 },- { url = "https://files.pythonhosted.org/packages/87/df/b7737ff046c974b183ea9aa111b74185ac8c3a326c6262d413bd5a1b8c69/charset_normalizer-3.4.3-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0e78314bdc32fa80696f72fa16dc61168fda4d6a0c014e0380f9d02f0e5d8a07", size = 150295 },- { url = "https://files.pythonhosted.org/packages/61/f1/190d9977e0084d3f1dc169acd060d479bbbc71b90bf3e7bf7b9927dec3eb/charset_normalizer-3.4.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:96b2b3d1a83ad55310de8c7b4a2d04d9277d5591f40761274856635acc5fcb30", size = 148379 },- { url = "https://files.pythonhosted.org/packages/4c/92/27dbe365d34c68cfe0ca76f1edd70e8705d82b378cb54ebbaeabc2e3029d/charset_normalizer-3.4.3-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:939578d9d8fd4299220161fdd76e86c6a251987476f5243e8864a7844476ba14", size = 160018 },- { url = "https://files.pythonhosted.org/packages/99/04/baae2a1ea1893a01635d475b9261c889a18fd48393634b6270827869fa34/charset_normalizer-3.4.3-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:fd10de089bcdcd1be95a2f73dbe6254798ec1bda9f450d5828c96f93e2536b9c", size = 157430 },- { url = "https://files.pythonhosted.org/packages/2f/36/77da9c6a328c54d17b960c89eccacfab8271fdaaa228305330915b88afa9/charset_normalizer-3.4.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:1e8ac75d72fa3775e0b7cb7e4629cec13b7514d928d15ef8ea06bca03ef01cae", size = 151600 },- { url = "https://files.pythonhosted.org/packages/64/d4/9eb4ff2c167edbbf08cdd28e19078bf195762e9bd63371689cab5ecd3d0d/charset_normalizer-3.4.3-cp311-cp311-win32.whl", hash = "sha256:6cf8fd4c04756b6b60146d98cd8a77d0cdae0e1ca20329da2ac85eed779b6849", size = 99616 },- { url = "https://files.pythonhosted.org/packages/f4/9c/996a4a028222e7761a96634d1820de8a744ff4327a00ada9c8942033089b/charset_normalizer-3.4.3-cp311-cp311-win_amd64.whl", hash = "sha256:31a9a6f775f9bcd865d88ee350f0ffb0e25936a7f930ca98995c05abf1faf21c", size = 107108 },- { url = "https://files.pythonhosted.org/packages/e9/5e/14c94999e418d9b87682734589404a25854d5f5d0408df68bc15b6ff54bb/charset_normalizer-3.4.3-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:e28e334d3ff134e88989d90ba04b47d84382a828c061d0d1027b1b12a62b39b1", size = 205655 },- { url = "https://files.pythonhosted.org/packages/7d/a8/c6ec5d389672521f644505a257f50544c074cf5fc292d5390331cd6fc9c3/charset_normalizer-3.4.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0cacf8f7297b0c4fcb74227692ca46b4a5852f8f4f24b3c766dd94a1075c4884", size = 146223 },- { url = "https://files.pythonhosted.org/packages/fc/eb/a2ffb08547f4e1e5415fb69eb7db25932c52a52bed371429648db4d84fb1/charset_normalizer-3.4.3-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c6fd51128a41297f5409deab284fecbe5305ebd7e5a1f959bee1c054622b7018", size = 159366 },- { url = "https://files.pythonhosted.org/packages/82/10/0fd19f20c624b278dddaf83b8464dcddc2456cb4b02bb902a6da126b87a1/charset_normalizer-3.4.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:3cfb2aad70f2c6debfbcb717f23b7eb55febc0bb23dcffc0f076009da10c6392", size = 157104 },- { url = "https://files.pythonhosted.org/packages/16/ab/0233c3231af734f5dfcf0844aa9582d5a1466c985bbed6cedab85af9bfe3/charset_normalizer-3.4.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1606f4a55c0fd363d754049cdf400175ee96c992b1f8018b993941f221221c5f", size = 151830 },- { url = "https://files.pythonhosted.org/packages/ae/02/e29e22b4e02839a0e4a06557b1999d0a47db3567e82989b5bb21f3fbbd9f/charset_normalizer-3.4.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:027b776c26d38b7f15b26a5da1044f376455fb3766df8fc38563b4efbc515154", size = 148854 },- { url = "https://files.pythonhosted.org/packages/05/6b/e2539a0a4be302b481e8cafb5af8792da8093b486885a1ae4d15d452bcec/charset_normalizer-3.4.3-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:42e5088973e56e31e4fa58eb6bd709e42fc03799c11c42929592889a2e54c491", size = 160670 },- { url = "https://files.pythonhosted.org/packages/31/e7/883ee5676a2ef217a40ce0bffcc3d0dfbf9e64cbcfbdf822c52981c3304b/charset_normalizer-3.4.3-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:cc34f233c9e71701040d772aa7490318673aa7164a0efe3172b2981218c26d93", size = 158501 },- { url = "https://files.pythonhosted.org/packages/c1/35/6525b21aa0db614cf8b5792d232021dca3df7f90a1944db934efa5d20bb1/charset_normalizer-3.4.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:320e8e66157cc4e247d9ddca8e21f427efc7a04bbd0ac8a9faf56583fa543f9f", size = 153173 },- { url = "https://files.pythonhosted.org/packages/50/ee/f4704bad8201de513fdc8aac1cabc87e38c5818c93857140e06e772b5892/charset_normalizer-3.4.3-cp312-cp312-win32.whl", hash = "sha256:fb6fecfd65564f208cbf0fba07f107fb661bcd1a7c389edbced3f7a493f70e37", size = 99822 },- { url = "https://files.pythonhosted.org/packages/39/f5/3b3836ca6064d0992c58c7561c6b6eee1b3892e9665d650c803bd5614522/charset_normalizer-3.4.3-cp312-cp312-win_amd64.whl", hash = "sha256:86df271bf921c2ee3818f0522e9a5b8092ca2ad8b065ece5d7d9d0e9f4849bcc", size = 107543 },- { url = "https://files.pythonhosted.org/packages/65/ca/2135ac97709b400c7654b4b764daf5c5567c2da45a30cdd20f9eefe2d658/charset_normalizer-3.4.3-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:14c2a87c65b351109f6abfc424cab3927b3bdece6f706e4d12faaf3d52ee5efe", size = 205326 },- { url = "https://files.pythonhosted.org/packages/71/11/98a04c3c97dd34e49c7d247083af03645ca3730809a5509443f3c37f7c99/charset_normalizer-3.4.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:41d1fc408ff5fdfb910200ec0e74abc40387bccb3252f3f27c0676731df2b2c8", size = 146008 },- { url = "https://files.pythonhosted.org/packages/60/f5/4659a4cb3c4ec146bec80c32d8bb16033752574c20b1252ee842a95d1a1e/charset_normalizer-3.4.3-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1bb60174149316da1c35fa5233681f7c0f9f514509b8e399ab70fea5f17e45c9", size = 159196 },- { url = "https://files.pythonhosted.org/packages/86/9e/f552f7a00611f168b9a5865a1414179b2c6de8235a4fa40189f6f79a1753/charset_normalizer-3.4.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:30d006f98569de3459c2fc1f2acde170b7b2bd265dc1943e87e1a4efe1b67c31", size = 156819 },- { url = "https://files.pythonhosted.org/packages/7e/95/42aa2156235cbc8fa61208aded06ef46111c4d3f0de233107b3f38631803/charset_normalizer-3.4.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:416175faf02e4b0810f1f38bcb54682878a4af94059a1cd63b8747244420801f", size = 151350 },- { url = "https://files.pythonhosted.org/packages/c2/a9/3865b02c56f300a6f94fc631ef54f0a8a29da74fb45a773dfd3dcd380af7/charset_normalizer-3.4.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:6aab0f181c486f973bc7262a97f5aca3ee7e1437011ef0c2ec04b5a11d16c927", size = 148644 },- { url = "https://files.pythonhosted.org/packages/77/d9/cbcf1a2a5c7d7856f11e7ac2d782aec12bdfea60d104e60e0aa1c97849dc/charset_normalizer-3.4.3-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:fdabf8315679312cfa71302f9bd509ded4f2f263fb5b765cf1433b39106c3cc9", size = 160468 },- { url = "https://files.pythonhosted.org/packages/f6/42/6f45efee8697b89fda4d50580f292b8f7f9306cb2971d4b53f8914e4d890/charset_normalizer-3.4.3-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:bd28b817ea8c70215401f657edef3a8aa83c29d447fb0b622c35403780ba11d5", size = 158187 },- { url = "https://files.pythonhosted.org/packages/70/99/f1c3bdcfaa9c45b3ce96f70b14f070411366fa19549c1d4832c935d8e2c3/charset_normalizer-3.4.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:18343b2d246dc6761a249ba1fb13f9ee9a2bcd95decc767319506056ea4ad4dc", size = 152699 },- { url = "https://files.pythonhosted.org/packages/a3/ad/b0081f2f99a4b194bcbb1934ef3b12aa4d9702ced80a37026b7607c72e58/charset_normalizer-3.4.3-cp313-cp313-win32.whl", hash = "sha256:6fb70de56f1859a3f71261cbe41005f56a7842cc348d3aeb26237560bfa5e0ce", size = 99580 },- { url = "https://files.pythonhosted.org/packages/9a/8f/ae790790c7b64f925e5c953b924aaa42a243fb778fed9e41f147b2a5715a/charset_normalizer-3.4.3-cp313-cp313-win_amd64.whl", hash = "sha256:cf1ebb7d78e1ad8ec2a8c4732c7be2e736f6e5123a4146c5b89c9d1f585f8cef", size = 107366 },- { url = "https://files.pythonhosted.org/packages/8e/91/b5a06ad970ddc7a0e513112d40113e834638f4ca1120eb727a249fb2715e/charset_normalizer-3.4.3-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:3cd35b7e8aedeb9e34c41385fda4f73ba609e561faedfae0a9e75e44ac558a15", size = 204342 },- { url = "https://files.pythonhosted.org/packages/ce/ec/1edc30a377f0a02689342f214455c3f6c2fbedd896a1d2f856c002fc3062/charset_normalizer-3.4.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b89bc04de1d83006373429975f8ef9e7932534b8cc9ca582e4db7d20d91816db", size = 145995 },- { url = "https://files.pythonhosted.org/packages/17/e5/5e67ab85e6d22b04641acb5399c8684f4d37caf7558a53859f0283a650e9/charset_normalizer-3.4.3-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:2001a39612b241dae17b4687898843f254f8748b796a2e16f1051a17078d991d", size = 158640 },- { url = "https://files.pythonhosted.org/packages/f1/e5/38421987f6c697ee3722981289d554957c4be652f963d71c5e46a262e135/charset_normalizer-3.4.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8dcfc373f888e4fb39a7bc57e93e3b845e7f462dacc008d9749568b1c4ece096", size = 156636 },- { url = "https://files.pythonhosted.org/packages/a0/e4/5a075de8daa3ec0745a9a3b54467e0c2967daaaf2cec04c845f73493e9a1/charset_normalizer-3.4.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:18b97b8404387b96cdbd30ad660f6407799126d26a39ca65729162fd810a99aa", size = 150939 },- { url = "https://files.pythonhosted.org/packages/02/f7/3611b32318b30974131db62b4043f335861d4d9b49adc6d57c1149cc49d4/charset_normalizer-3.4.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:ccf600859c183d70eb47e05a44cd80a4ce77394d1ac0f79dbd2dd90a69a3a049", size = 148580 },- { url = "https://files.pythonhosted.org/packages/7e/61/19b36f4bd67f2793ab6a99b979b4e4f3d8fc754cbdffb805335df4337126/charset_normalizer-3.4.3-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:53cd68b185d98dde4ad8990e56a58dea83a4162161b1ea9272e5c9182ce415e0", size = 159870 },- { url = "https://files.pythonhosted.org/packages/06/57/84722eefdd338c04cf3030ada66889298eaedf3e7a30a624201e0cbe424a/charset_normalizer-3.4.3-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:30a96e1e1f865f78b030d65241c1ee850cdf422d869e9028e2fc1d5e4db73b92", size = 157797 },- { url = "https://files.pythonhosted.org/packages/72/2a/aff5dd112b2f14bcc3462c312dce5445806bfc8ab3a7328555da95330e4b/charset_normalizer-3.4.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:d716a916938e03231e86e43782ca7878fb602a125a91e7acb8b5112e2e96ac16", size = 152224 },- { url = "https://files.pythonhosted.org/packages/b7/8c/9839225320046ed279c6e839d51f028342eb77c91c89b8ef2549f951f3ec/charset_normalizer-3.4.3-cp314-cp314-win32.whl", hash = "sha256:c6dbd0ccdda3a2ba7c2ecd9d77b37f3b5831687d8dc1b6ca5f56a4880cc7b7ce", size = 100086 },- { url = "https://files.pythonhosted.org/packages/ee/7a/36fbcf646e41f710ce0a563c1c9a343c6edf9be80786edeb15b6f62e17db/charset_normalizer-3.4.3-cp314-cp314-win_amd64.whl", hash = "sha256:73dc19b562516fc9bcf6e5d6e596df0b4eb98d87e4f79f3ae71840e6ed21361c", size = 107400 },- { url = "https://files.pythonhosted.org/packages/8a/1f/f041989e93b001bc4e44bb1669ccdcf54d3f00e628229a85b08d330615c5/charset_normalizer-3.4.3-py3-none-any.whl", hash = "sha256:ce571ab16d890d23b5c278547ba694193a45011ff86a9162a71307ed9f86759a", size = 53175 },+version = "3.4.4"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/13/69/33ddede1939fdd074bce5434295f38fae7136463422fe4fd3e0e89b98062/charset_normalizer-3.4.4.tar.gz", hash = "sha256:94537985111c35f28720e43603b8e7b43a6ecfb2ce1d3058bbe955b73404e21a", size = 129418 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/ed/27/c6491ff4954e58a10f69ad90aca8a1b6fe9c5d3c6f380907af3c37435b59/charset_normalizer-3.4.4-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:6e1fcf0720908f200cd21aa4e6750a48ff6ce4afe7ff5a79a90d5ed8a08296f8", size = 206988 },+ { url = "https://files.pythonhosted.org/packages/94/59/2e87300fe67ab820b5428580a53cad894272dbb97f38a7a814a2a1ac1011/charset_normalizer-3.4.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5f819d5fe9234f9f82d75bdfa9aef3a3d72c4d24a6e57aeaebba32a704553aa0", size = 147324 },+ { url = "https://files.pythonhosted.org/packages/07/fb/0cf61dc84b2b088391830f6274cb57c82e4da8bbc2efeac8c025edb88772/charset_normalizer-3.4.4-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:a59cb51917aa591b1c4e6a43c132f0cdc3c76dbad6155df4e28ee626cc77a0a3", size = 142742 },+ { url = "https://files.pythonhosted.org/packages/62/8b/171935adf2312cd745d290ed93cf16cf0dfe320863ab7cbeeae1dcd6535f/charset_normalizer-3.4.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8ef3c867360f88ac904fd3f5e1f902f13307af9052646963ee08ff4f131adafc", size = 160863 },+ { url = "https://files.pythonhosted.org/packages/09/73/ad875b192bda14f2173bfc1bc9a55e009808484a4b256748d931b6948442/charset_normalizer-3.4.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d9e45d7faa48ee908174d8fe84854479ef838fc6a705c9315372eacbc2f02897", size = 157837 },+ { url = "https://files.pythonhosted.org/packages/6d/fc/de9cce525b2c5b94b47c70a4b4fb19f871b24995c728e957ee68ab1671ea/charset_normalizer-3.4.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:840c25fb618a231545cbab0564a799f101b63b9901f2569faecd6b222ac72381", size = 151550 },+ { url = "https://files.pythonhosted.org/packages/55/c2/43edd615fdfba8c6f2dfbd459b25a6b3b551f24ea21981e23fb768503ce1/charset_normalizer-3.4.4-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ca5862d5b3928c4940729dacc329aa9102900382fea192fc5e52eb69d6093815", size = 149162 },+ { url = "https://files.pythonhosted.org/packages/03/86/bde4ad8b4d0e9429a4e82c1e8f5c659993a9a863ad62c7df05cf7b678d75/charset_normalizer-3.4.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:d9c7f57c3d666a53421049053eaacdd14bbd0a528e2186fcb2e672effd053bb0", size = 150019 },+ { url = "https://files.pythonhosted.org/packages/1f/86/a151eb2af293a7e7bac3a739b81072585ce36ccfb4493039f49f1d3cae8c/charset_normalizer-3.4.4-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:277e970e750505ed74c832b4bf75dac7476262ee2a013f5574dd49075879e161", size = 143310 },+ { url = "https://files.pythonhosted.org/packages/b5/fe/43dae6144a7e07b87478fdfc4dbe9efd5defb0e7ec29f5f58a55aeef7bf7/charset_normalizer-3.4.4-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:31fd66405eaf47bb62e8cd575dc621c56c668f27d46a61d975a249930dd5e2a4", size = 162022 },+ { url = "https://files.pythonhosted.org/packages/80/e6/7aab83774f5d2bca81f42ac58d04caf44f0cc2b65fc6db2b3b2e8a05f3b3/charset_normalizer-3.4.4-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:0d3d8f15c07f86e9ff82319b3d9ef6f4bf907608f53fe9d92b28ea9ae3d1fd89", size = 149383 },+ { url = "https://files.pythonhosted.org/packages/4f/e8/b289173b4edae05c0dde07f69f8db476a0b511eac556dfe0d6bda3c43384/charset_normalizer-3.4.4-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:9f7fcd74d410a36883701fafa2482a6af2ff5ba96b9a620e9e0721e28ead5569", size = 159098 },+ { url = "https://files.pythonhosted.org/packages/d8/df/fe699727754cae3f8478493c7f45f777b17c3ef0600e28abfec8619eb49c/charset_normalizer-3.4.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ebf3e58c7ec8a8bed6d66a75d7fb37b55e5015b03ceae72a8e7c74495551e224", size = 152991 },+ { url = "https://files.pythonhosted.org/packages/1a/86/584869fe4ddb6ffa3bd9f491b87a01568797fb9bd8933f557dba9771beaf/charset_normalizer-3.4.4-cp311-cp311-win32.whl", hash = "sha256:eecbc200c7fd5ddb9a7f16c7decb07b566c29fa2161a16cf67b8d068bd21690a", size = 99456 },+ { url = "https://files.pythonhosted.org/packages/65/f6/62fdd5feb60530f50f7e38b4f6a1d5203f4d16ff4f9f0952962c044e919a/charset_normalizer-3.4.4-cp311-cp311-win_amd64.whl", hash = "sha256:5ae497466c7901d54b639cf42d5b8c1b6a4fead55215500d2f486d34db48d016", size = 106978 },+ { url = "https://files.pythonhosted.org/packages/7a/9d/0710916e6c82948b3be62d9d398cb4fcf4e97b56d6a6aeccd66c4b2f2bd5/charset_normalizer-3.4.4-cp311-cp311-win_arm64.whl", hash = "sha256:65e2befcd84bc6f37095f5961e68a6f077bf44946771354a28ad434c2cce0ae1", size = 99969 },+ { url = "https://files.pythonhosted.org/packages/f3/85/1637cd4af66fa687396e757dec650f28025f2a2f5a5531a3208dc0ec43f2/charset_normalizer-3.4.4-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:0a98e6759f854bd25a58a73fa88833fba3b7c491169f86ce1180c948ab3fd394", size = 208425 },+ { url = "https://files.pythonhosted.org/packages/9d/6a/04130023fef2a0d9c62d0bae2649b69f7b7d8d24ea5536feef50551029df/charset_normalizer-3.4.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b5b290ccc2a263e8d185130284f8501e3e36c5e02750fc6b6bdeb2e9e96f1e25", size = 148162 },+ { url = "https://files.pythonhosted.org/packages/78/29/62328d79aa60da22c9e0b9a66539feae06ca0f5a4171ac4f7dc285b83688/charset_normalizer-3.4.4-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:74bb723680f9f7a6234dcf67aea57e708ec1fbdf5699fb91dfd6f511b0a320ef", size = 144558 },+ { url = "https://files.pythonhosted.org/packages/86/bb/b32194a4bf15b88403537c2e120b817c61cd4ecffa9b6876e941c3ee38fe/charset_normalizer-3.4.4-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f1e34719c6ed0b92f418c7c780480b26b5d9c50349e9a9af7d76bf757530350d", size = 161497 },+ { url = "https://files.pythonhosted.org/packages/19/89/a54c82b253d5b9b111dc74aca196ba5ccfcca8242d0fb64146d4d3183ff1/charset_normalizer-3.4.4-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2437418e20515acec67d86e12bf70056a33abdacb5cb1655042f6538d6b085a8", size = 159240 },+ { url = "https://files.pythonhosted.org/packages/c0/10/d20b513afe03acc89ec33948320a5544d31f21b05368436d580dec4e234d/charset_normalizer-3.4.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:11d694519d7f29d6cd09f6ac70028dba10f92f6cdd059096db198c283794ac86", size = 153471 },+ { url = "https://files.pythonhosted.org/packages/61/fa/fbf177b55bdd727010f9c0a3c49eefa1d10f960e5f09d1d887bf93c2e698/charset_normalizer-3.4.4-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ac1c4a689edcc530fc9d9aa11f5774b9e2f33f9a0c6a57864e90908f5208d30a", size = 150864 },+ { url = "https://files.pythonhosted.org/packages/05/12/9fbc6a4d39c0198adeebbde20b619790e9236557ca59fc40e0e3cebe6f40/charset_normalizer-3.4.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:21d142cc6c0ec30d2efee5068ca36c128a30b0f2c53c1c07bd78cb6bc1d3be5f", size = 150647 },+ { url = "https://files.pythonhosted.org/packages/ad/1f/6a9a593d52e3e8c5d2b167daf8c6b968808efb57ef4c210acb907c365bc4/charset_normalizer-3.4.4-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:5dbe56a36425d26d6cfb40ce79c314a2e4dd6211d51d6d2191c00bed34f354cc", size = 145110 },+ { url = "https://files.pythonhosted.org/packages/30/42/9a52c609e72471b0fc54386dc63c3781a387bb4fe61c20231a4ebcd58bdd/charset_normalizer-3.4.4-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:5bfbb1b9acf3334612667b61bd3002196fe2a1eb4dd74d247e0f2a4d50ec9bbf", size = 162839 },+ { url = "https://files.pythonhosted.org/packages/c4/5b/c0682bbf9f11597073052628ddd38344a3d673fda35a36773f7d19344b23/charset_normalizer-3.4.4-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:d055ec1e26e441f6187acf818b73564e6e6282709e9bcb5b63f5b23068356a15", size = 150667 },+ { url = "https://files.pythonhosted.org/packages/e4/24/a41afeab6f990cf2daf6cb8c67419b63b48cf518e4f56022230840c9bfb2/charset_normalizer-3.4.4-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:af2d8c67d8e573d6de5bc30cdb27e9b95e49115cd9baad5ddbd1a6207aaa82a9", size = 160535 },+ { url = "https://files.pythonhosted.org/packages/2a/e5/6a4ce77ed243c4a50a1fecca6aaaab419628c818a49434be428fe24c9957/charset_normalizer-3.4.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:780236ac706e66881f3b7f2f32dfe90507a09e67d1d454c762cf642e6e1586e0", size = 154816 },+ { url = "https://files.pythonhosted.org/packages/a8/ef/89297262b8092b312d29cdb2517cb1237e51db8ecef2e9af5edbe7b683b1/charset_normalizer-3.4.4-cp312-cp312-win32.whl", hash = "sha256:5833d2c39d8896e4e19b689ffc198f08ea58116bee26dea51e362ecc7cd3ed26", size = 99694 },+ { url = "https://files.pythonhosted.org/packages/3d/2d/1e5ed9dd3b3803994c155cd9aacb60c82c331bad84daf75bcb9c91b3295e/charset_normalizer-3.4.4-cp312-cp312-win_amd64.whl", hash = "sha256:a79cfe37875f822425b89a82333404539ae63dbdddf97f84dcbc3d339aae9525", size = 107131 },+ { url = "https://files.pythonhosted.org/packages/d0/d9/0ed4c7098a861482a7b6a95603edce4c0d9db2311af23da1fb2b75ec26fc/charset_normalizer-3.4.4-cp312-cp312-win_arm64.whl", hash = "sha256:376bec83a63b8021bb5c8ea75e21c4ccb86e7e45ca4eb81146091b56599b80c3", size = 100390 },+ { url = "https://files.pythonhosted.org/packages/97/45/4b3a1239bbacd321068ea6e7ac28875b03ab8bc0aa0966452db17cd36714/charset_normalizer-3.4.4-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:e1f185f86a6f3403aa2420e815904c67b2f9ebc443f045edd0de921108345794", size = 208091 },+ { url = "https://files.pythonhosted.org/packages/7d/62/73a6d7450829655a35bb88a88fca7d736f9882a27eacdca2c6d505b57e2e/charset_normalizer-3.4.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6b39f987ae8ccdf0d2642338faf2abb1862340facc796048b604ef14919e55ed", size = 147936 },+ { url = "https://files.pythonhosted.org/packages/89/c5/adb8c8b3d6625bef6d88b251bbb0d95f8205831b987631ab0c8bb5d937c2/charset_normalizer-3.4.4-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3162d5d8ce1bb98dd51af660f2121c55d0fa541b46dff7bb9b9f86ea1d87de72", size = 144180 },+ { url = "https://files.pythonhosted.org/packages/91/ed/9706e4070682d1cc219050b6048bfd293ccf67b3d4f5a4f39207453d4b99/charset_normalizer-3.4.4-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:81d5eb2a312700f4ecaa977a8235b634ce853200e828fbadf3a9c50bab278328", size = 161346 },+ { url = "https://files.pythonhosted.org/packages/d5/0d/031f0d95e4972901a2f6f09ef055751805ff541511dc1252ba3ca1f80cf5/charset_normalizer-3.4.4-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5bd2293095d766545ec1a8f612559f6b40abc0eb18bb2f5d1171872d34036ede", size = 158874 },+ { url = "https://files.pythonhosted.org/packages/f5/83/6ab5883f57c9c801ce5e5677242328aa45592be8a00644310a008d04f922/charset_normalizer-3.4.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a8a8b89589086a25749f471e6a900d3f662d1d3b6e2e59dcecf787b1cc3a1894", size = 153076 },+ { url = "https://files.pythonhosted.org/packages/75/1e/5ff781ddf5260e387d6419959ee89ef13878229732732ee73cdae01800f2/charset_normalizer-3.4.4-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:bc7637e2f80d8530ee4a78e878bce464f70087ce73cf7c1caf142416923b98f1", size = 150601 },+ { url = "https://files.pythonhosted.org/packages/d7/57/71be810965493d3510a6ca79b90c19e48696fb1ff964da319334b12677f0/charset_normalizer-3.4.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f8bf04158c6b607d747e93949aa60618b61312fe647a6369f88ce2ff16043490", size = 150376 },+ { url = "https://files.pythonhosted.org/packages/e5/d5/c3d057a78c181d007014feb7e9f2e65905a6c4ef182c0ddf0de2924edd65/charset_normalizer-3.4.4-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:554af85e960429cf30784dd47447d5125aaa3b99a6f0683589dbd27e2f45da44", size = 144825 },+ { url = "https://files.pythonhosted.org/packages/e6/8c/d0406294828d4976f275ffbe66f00266c4b3136b7506941d87c00cab5272/charset_normalizer-3.4.4-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:74018750915ee7ad843a774364e13a3db91682f26142baddf775342c3f5b1133", size = 162583 },+ { url = "https://files.pythonhosted.org/packages/d7/24/e2aa1f18c8f15c4c0e932d9287b8609dd30ad56dbe41d926bd846e22fb8d/charset_normalizer-3.4.4-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:c0463276121fdee9c49b98908b3a89c39be45d86d1dbaa22957e38f6321d4ce3", size = 150366 },+ { url = "https://files.pythonhosted.org/packages/e4/5b/1e6160c7739aad1e2df054300cc618b06bf784a7a164b0f238360721ab86/charset_normalizer-3.4.4-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:362d61fd13843997c1c446760ef36f240cf81d3ebf74ac62652aebaf7838561e", size = 160300 },+ { url = "https://files.pythonhosted.org/packages/7a/10/f882167cd207fbdd743e55534d5d9620e095089d176d55cb22d5322f2afd/charset_normalizer-3.4.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:9a26f18905b8dd5d685d6d07b0cdf98a79f3c7a918906af7cc143ea2e164c8bc", size = 154465 },+ { url = "https://files.pythonhosted.org/packages/89/66/c7a9e1b7429be72123441bfdbaf2bc13faab3f90b933f664db506dea5915/charset_normalizer-3.4.4-cp313-cp313-win32.whl", hash = "sha256:9b35f4c90079ff2e2edc5b26c0c77925e5d2d255c42c74fdb70fb49b172726ac", size = 99404 },+ { url = "https://files.pythonhosted.org/packages/c4/26/b9924fa27db384bdcd97ab83b4f0a8058d96ad9626ead570674d5e737d90/charset_normalizer-3.4.4-cp313-cp313-win_amd64.whl", hash = "sha256:b435cba5f4f750aa6c0a0d92c541fb79f69a387c91e61f1795227e4ed9cece14", size = 107092 },+ { url = "https://files.pythonhosted.org/packages/af/8f/3ed4bfa0c0c72a7ca17f0380cd9e4dd842b09f664e780c13cff1dcf2ef1b/charset_normalizer-3.4.4-cp313-cp313-win_arm64.whl", hash = "sha256:542d2cee80be6f80247095cc36c418f7bddd14f4a6de45af91dfad36d817bba2", size = 100408 },+ { url = "https://files.pythonhosted.org/packages/2a/35/7051599bd493e62411d6ede36fd5af83a38f37c4767b92884df7301db25d/charset_normalizer-3.4.4-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:da3326d9e65ef63a817ecbcc0df6e94463713b754fe293eaa03da99befb9a5bd", size = 207746 },+ { url = "https://files.pythonhosted.org/packages/10/9a/97c8d48ef10d6cd4fcead2415523221624bf58bcf68a802721a6bc807c8f/charset_normalizer-3.4.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8af65f14dc14a79b924524b1e7fffe304517b2bff5a58bf64f30b98bbc5079eb", size = 147889 },+ { url = "https://files.pythonhosted.org/packages/10/bf/979224a919a1b606c82bd2c5fa49b5c6d5727aa47b4312bb27b1734f53cd/charset_normalizer-3.4.4-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:74664978bb272435107de04e36db5a9735e78232b85b77d45cfb38f758efd33e", size = 143641 },+ { url = "https://files.pythonhosted.org/packages/ba/33/0ad65587441fc730dc7bd90e9716b30b4702dc7b617e6ba4997dc8651495/charset_normalizer-3.4.4-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:752944c7ffbfdd10c074dc58ec2d5a8a4cd9493b314d367c14d24c17684ddd14", size = 160779 },+ { url = "https://files.pythonhosted.org/packages/67/ed/331d6b249259ee71ddea93f6f2f0a56cfebd46938bde6fcc6f7b9a3d0e09/charset_normalizer-3.4.4-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d1f13550535ad8cff21b8d757a3257963e951d96e20ec82ab44bc64aeb62a191", size = 159035 },+ { url = "https://files.pythonhosted.org/packages/67/ff/f6b948ca32e4f2a4576aa129d8bed61f2e0543bf9f5f2b7fc3758ed005c9/charset_normalizer-3.4.4-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ecaae4149d99b1c9e7b88bb03e3221956f68fd6d50be2ef061b2381b61d20838", size = 152542 },+ { url = "https://files.pythonhosted.org/packages/16/85/276033dcbcc369eb176594de22728541a925b2632f9716428c851b149e83/charset_normalizer-3.4.4-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:cb6254dc36b47a990e59e1068afacdcd02958bdcce30bb50cc1700a8b9d624a6", size = 149524 },+ { url = "https://files.pythonhosted.org/packages/9e/f2/6a2a1f722b6aba37050e626530a46a68f74e63683947a8acff92569f979a/charset_normalizer-3.4.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c8ae8a0f02f57a6e61203a31428fa1d677cbe50c93622b4149d5c0f319c1d19e", size = 150395 },+ { url = "https://files.pythonhosted.org/packages/60/bb/2186cb2f2bbaea6338cad15ce23a67f9b0672929744381e28b0592676824/charset_normalizer-3.4.4-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:47cc91b2f4dd2833fddaedd2893006b0106129d4b94fdb6af1f4ce5a9965577c", size = 143680 },+ { url = "https://files.pythonhosted.org/packages/7d/a5/bf6f13b772fbb2a90360eb620d52ed8f796f3c5caee8398c3b2eb7b1c60d/charset_normalizer-3.4.4-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:82004af6c302b5d3ab2cfc4cc5f29db16123b1a8417f2e25f9066f91d4411090", size = 162045 },+ { url = "https://files.pythonhosted.org/packages/df/c5/d1be898bf0dc3ef9030c3825e5d3b83f2c528d207d246cbabe245966808d/charset_normalizer-3.4.4-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:2b7d8f6c26245217bd2ad053761201e9f9680f8ce52f0fcd8d0755aeae5b2152", size = 149687 },+ { url = "https://files.pythonhosted.org/packages/a5/42/90c1f7b9341eef50c8a1cb3f098ac43b0508413f33affd762855f67a410e/charset_normalizer-3.4.4-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:799a7a5e4fb2d5898c60b640fd4981d6a25f1c11790935a44ce38c54e985f828", size = 160014 },+ { url = "https://files.pythonhosted.org/packages/76/be/4d3ee471e8145d12795ab655ece37baed0929462a86e72372fd25859047c/charset_normalizer-3.4.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:99ae2cffebb06e6c22bdc25801d7b30f503cc87dbd283479e7b606f70aff57ec", size = 154044 },+ { url = "https://files.pythonhosted.org/packages/b0/6f/8f7af07237c34a1defe7defc565a9bc1807762f672c0fde711a4b22bf9c0/charset_normalizer-3.4.4-cp314-cp314-win32.whl", hash = "sha256:f9d332f8c2a2fcbffe1378594431458ddbef721c1769d78e2cbc06280d8155f9", size = 99940 },+ { url = "https://files.pythonhosted.org/packages/4b/51/8ade005e5ca5b0d80fb4aff72a3775b325bdc3d27408c8113811a7cbe640/charset_normalizer-3.4.4-cp314-cp314-win_amd64.whl", hash = "sha256:8a6562c3700cce886c5be75ade4a5db4214fda19fede41d9792d100288d8f94c", size = 107104 },+ { url = "https://files.pythonhosted.org/packages/da/5f/6b8f83a55bb8278772c5ae54a577f3099025f9ade59d0136ac24a0df4bde/charset_normalizer-3.4.4-cp314-cp314-win_arm64.whl", hash = "sha256:de00632ca48df9daf77a2c65a484531649261ec9f25489917f09e455cb09ddb2", size = 100743 },+ { url = "https://files.pythonhosted.org/packages/0a/4c/925909008ed5a988ccbb72dcc897407e5d6d3bd72410d69e051fc0c14647/charset_normalizer-3.4.4-py3-none-any.whl", hash = "sha256:7a32c560861a02ff789ad905a2fe94e3f840803362c84fecf1851cb4cf3dc37f", size = 53402 },][[package]]name = "click"-version = "8.2.1"+version = "8.3.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "colorama", marker = "platform_system == 'Windows'" },]-sdist = { url = "https://files.pythonhosted.org/packages/60/6c/8ca2efa64cf75a977a0d7fac081354553ebe483345c734fb6b6515d96bbc/click-8.2.1.tar.gz", hash = "sha256:27c491cc05d968d271d5a1db13e3b5a184636d9d930f148c50b038f0d0646202", size = 286342 }+sdist = { url = "https://files.pythonhosted.org/packages/46/61/de6cd827efad202d7057d93e0fed9294b96952e188f7384832791c7b2254/click-8.3.0.tar.gz", hash = "sha256:e7b8232224eba16f4ebe410c25ced9f7875cb5f3263ffc93cc3e8da705e229c4", size = 276943 }wheels = [- { url = "https://files.pythonhosted.org/packages/85/32/10bb5764d90a8eee674e9dc6f4db6a0ab47c8c4d0d83c27f7c39ac415a4d/click-8.2.1-py3-none-any.whl", hash = "sha256:61a3265b914e850b85317d0b3109c7f8cd35a670f963866005d6ef1d5175a12b", size = 102215 },+ { url = "https://files.pythonhosted.org/packages/db/d3/9dcc0f5797f070ec8edf30fbadfb200e71d9db6b84d211e3b2085a7589a0/click-8.3.0-py3-none-any.whl", hash = "sha256:9b9f285302c6e3064f4330c05f05b81945b2a39544279343e6e7c5f27a9baddc", size = 107295 },][[package]]@@ -316,16 +370,16 @@ wheels = [[[package]]name = "cv2-enumerate-cameras"-version = "1.2.2"+version = "1.3.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "pyobjc-framework-avfoundation", marker = "platform_system == 'Darwin'" },]-sdist = { url = "https://files.pythonhosted.org/packages/67/e9/1ed371073498f6a4be7cf32dd19605e7fa067497328668a1083e85a3ae71/cv2_enumerate_cameras-1.2.2.tar.gz", hash = "sha256:7dce1335605a4d19fc402c2b3b7d45d5bd80143c20b77be3655f96f30ad76510", size = 11942 }+sdist = { url = "https://files.pythonhosted.org/packages/71/cf/a6eb5fa54d7dfc87c93a6161aef57527c6ef4d8239be7cef10d13fb9efd6/cv2_enumerate_cameras-1.3.0.tar.gz", hash = "sha256:795d8005b0e92ca117e1b8c4849c752edb39b7e2a1818b2d7ac4463aa26caac1", size = 12455 }wheels = [- { url = "https://files.pythonhosted.org/packages/a1/37/a198560e077b82092f8d7df438e5c27fc5cc97a721456368f248c6cbf62f/cv2_enumerate_cameras-1.2.2-cp32-abi3-win32.whl", hash = "sha256:5068197f58ec5803da84dd9caa23dd016e09d0c2e6a656d888c5c29abb4ec226", size = 19866 },- { url = "https://files.pythonhosted.org/packages/35/ad/efd8779737ccb88596f9a06f4c46389f4c72aca3696b4b8260d18687d8d6/cv2_enumerate_cameras-1.2.2-cp32-abi3-win_amd64.whl", hash = "sha256:b5c2a765161a4187c5af3dbf2dd4fdf5acd486afde0bda2375eed877852117e5", size = 20751 },- { url = "https://files.pythonhosted.org/packages/f5/d5/be643f4c9542fa07752874820daff2a825c9c67432dfab6853662384385f/cv2_enumerate_cameras-1.2.2-py3-none-any.whl", hash = "sha256:0e54301a65a44a69873f4b4300c37119ae0ed1ea0266d96e1504fcbad678a8d5", size = 11024 },+ { url = "https://files.pythonhosted.org/packages/3c/38/cc570b8579a2be52d0a3f6dba7afad536bc6d41cfc44108727ef7d8b185a/cv2_enumerate_cameras-1.3.0-cp32-abi3-win32.whl", hash = "sha256:bd24be3c2df42b88da59e9f6029b97484fc8468678a2be3900aa717835c40f6a", size = 20406 },+ { url = "https://files.pythonhosted.org/packages/9d/ef/0a6e095462e90d12358ef68653c7ea4d86dd6f5dd8f433279ecb5745e9ca/cv2_enumerate_cameras-1.3.0-cp32-abi3-win_amd64.whl", hash = "sha256:ef892cc7d92dec3ad0f696fa592a9d5461e593698048f84e877353cffcfc486f", size = 21296 },+ { url = "https://files.pythonhosted.org/packages/7e/d5/6a6b74c92b6901d7077eb67284010354d90762702ed3451ea5d6297ef692/cv2_enumerate_cameras-1.3.0-py3-none-any.whl", hash = "sha256:7a67d8cc98fd112c3df51ff699c6953884e96088ced2ee05191bdeaaa2e1e847", size = 11571 },][[package]]@@ -339,74 +393,75 @@ wheels = [[[package]]name = "fastapi"-version = "0.116.1"+version = "0.121.2"source = { registry = "https://pypi.org/simple" }dependencies = [+ { name = "annotated-doc" },{ name = "pydantic" },{ name = "starlette" },{ name = "typing-extensions" },]-sdist = { url = "https://files.pythonhosted.org/packages/78/d7/6c8b3bfe33eeffa208183ec037fee0cce9f7f024089ab1c5d12ef04bd27c/fastapi-0.116.1.tar.gz", hash = "sha256:ed52cbf946abfd70c5a0dccb24673f0670deeb517a88b3544d03c2a6bf283143", size = 296485 }+sdist = { url = "https://files.pythonhosted.org/packages/fb/48/f08f264da34cf160db82c62ffb335e838b1fc16cbcc905f474c7d4c815db/fastapi-0.121.2.tar.gz", hash = "sha256:ca8e932b2b823ec1721c641e3669472c855ad9564a2854c9899d904c2848b8b9", size = 342944 }wheels = [- { url = "https://files.pythonhosted.org/packages/e5/47/d63c60f59a59467fda0f93f46335c9d18526d7071f025cb5b89d5353ea42/fastapi-0.116.1-py3-none-any.whl", hash = "sha256:c46ac7c312df840f0c9e220f7964bada936781bc4e2e6eb71f1c4d7553786565", size = 95631 },+ { url = "https://files.pythonhosted.org/packages/eb/23/dfb161e91db7c92727db505dc72a384ee79681fe0603f706f9f9f52c2901/fastapi-0.121.2-py3-none-any.whl", hash = "sha256:f2d80b49a86a846b70cc3a03eb5ea6ad2939298bf6a7fe377aa9cd3dd079d358", size = 109201 },][[package]]name = "flatbuffers"-version = "25.2.10"+version = "25.9.23"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/e4/30/eb5dce7994fc71a2f685d98ec33cc660c0a5887db5610137e60d8cbc4489/flatbuffers-25.2.10.tar.gz", hash = "sha256:97e451377a41262f8d9bd4295cc836133415cc03d8cb966410a4af92eb00d26e", size = 22170 }+sdist = { url = "https://files.pythonhosted.org/packages/9d/1f/3ee70b0a55137442038f2a33469cc5fddd7e0ad2abf83d7497c18a2b6923/flatbuffers-25.9.23.tar.gz", hash = "sha256:676f9fa62750bb50cf531b42a0a2a118ad8f7f797a511eda12881c016f093b12", size = 22067 }wheels = [- { url = "https://files.pythonhosted.org/packages/b8/25/155f9f080d5e4bc0082edfda032ea2bc2b8fab3f4d25d46c1e9dd22a1a89/flatbuffers-25.2.10-py2.py3-none-any.whl", hash = "sha256:ebba5f4d5ea615af3f7fd70fc310636fbb2bbd1f566ac0a23d98dd412de50051", size = 30953 },+ { url = "https://files.pythonhosted.org/packages/ee/1b/00a78aa2e8fbd63f9af08c9c19e6deb3d5d66b4dda677a0f61654680ee89/flatbuffers-25.9.23-py2.py3-none-any.whl", hash = "sha256:255538574d6cb6d0a79a17ec8bc0d30985913b87513a01cce8bcdb6b4c44d0e2", size = 30869 },][[package]]name = "fonttools"-version = "4.59.1"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/11/7f/29c9c3fe4246f6ad96fee52b88d0dc3a863c7563b0afc959e36d78b965dc/fonttools-4.59.1.tar.gz", hash = "sha256:74995b402ad09822a4c8002438e54940d9f1ecda898d2bb057729d7da983e4cb", size = 3534394 }-wheels = [- { url = "https://files.pythonhosted.org/packages/34/62/9667599561f623d4a523cc9eb4f66f3b94b6155464110fa9aebbf90bbec7/fonttools-4.59.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:4909cce2e35706f3d18c54d3dcce0414ba5e0fb436a454dffec459c61653b513", size = 2778815 },- { url = "https://files.pythonhosted.org/packages/8f/78/cc25bcb2ce86033a9df243418d175e58f1956a35047c685ef553acae67d6/fonttools-4.59.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:efbec204fa9f877641747f2d9612b2b656071390d7a7ef07a9dbf0ecf9c7195c", size = 2341631 },- { url = "https://files.pythonhosted.org/packages/a4/cc/fcbb606dd6871f457ac32f281c20bcd6cc77d9fce77b5a4e2b2afab1f500/fonttools-4.59.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:39dfd42cc2dc647b2c5469bc7a5b234d9a49e72565b96dd14ae6f11c2c59ef15", size = 5022222 },- { url = "https://files.pythonhosted.org/packages/61/96/c0b1cf2b74d08eb616a80dbf5564351fe4686147291a25f7dce8ace51eb3/fonttools-4.59.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b11bc177a0d428b37890825d7d025040d591aa833f85f8d8878ed183354f47df", size = 4966512 },- { url = "https://files.pythonhosted.org/packages/a4/26/51ce2e3e0835ffc2562b1b11d1fb9dafd0aca89c9041b64a9e903790a761/fonttools-4.59.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:5b9b4c35b3be45e5bc774d3fc9608bbf4f9a8d371103b858c80edbeed31dd5aa", size = 5001645 },- { url = "https://files.pythonhosted.org/packages/36/11/ef0b23f4266349b6d5ccbd1a07b7adc998d5bce925792aa5d1ec33f593e3/fonttools-4.59.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:01158376b8a418a0bae9625c476cebfcfcb5e6761e9d243b219cd58341e7afbb", size = 5113777 },- { url = "https://files.pythonhosted.org/packages/d0/da/b398fe61ef433da0a0472cdb5d4399124f7581ffe1a31b6242c91477d802/fonttools-4.59.1-cp311-cp311-win32.whl", hash = "sha256:cf7c5089d37787387123f1cb8f1793a47c5e1e3d1e4e7bfbc1cc96e0f925eabe", size = 2215076 },- { url = "https://files.pythonhosted.org/packages/94/bd/e2624d06ab94e41c7c77727b2941f1baed7edb647e63503953e6888020c9/fonttools-4.59.1-cp311-cp311-win_amd64.whl", hash = "sha256:c866eef7a0ba320486ade6c32bfc12813d1a5db8567e6904fb56d3d40acc5116", size = 2262779 },- { url = "https://files.pythonhosted.org/packages/ac/fe/6e069cc4cb8881d164a9bd956e9df555bc62d3eb36f6282e43440200009c/fonttools-4.59.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:43ab814bbba5f02a93a152ee61a04182bb5809bd2bc3609f7822e12c53ae2c91", size = 2769172 },- { url = "https://files.pythonhosted.org/packages/b9/98/ec4e03f748fefa0dd72d9d95235aff6fef16601267f4a2340f0e16b9330f/fonttools-4.59.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4f04c3ffbfa0baafcbc550657cf83657034eb63304d27b05cff1653b448ccff6", size = 2337281 },- { url = "https://files.pythonhosted.org/packages/8b/b1/890360a7e3d04a30ba50b267aca2783f4c1364363797e892e78a4f036076/fonttools-4.59.1-cp312-cp312-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:d601b153e51a5a6221f0d4ec077b6bfc6ac35bfe6c19aeaa233d8990b2b71726", size = 4909215 },- { url = "https://files.pythonhosted.org/packages/8a/ec/2490599550d6c9c97a44c1e36ef4de52d6acf742359eaa385735e30c05c4/fonttools-4.59.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c735e385e30278c54f43a0d056736942023c9043f84ee1021eff9fd616d17693", size = 4951958 },- { url = "https://files.pythonhosted.org/packages/d1/40/bd053f6f7634234a9b9805ff8ae4f32df4f2168bee23cafd1271ba9915a9/fonttools-4.59.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:1017413cdc8555dce7ee23720da490282ab7ec1cf022af90a241f33f9a49afc4", size = 4894738 },- { url = "https://files.pythonhosted.org/packages/ac/a1/3cd12a010d288325a7cfcf298a84825f0f9c29b01dee1baba64edfe89257/fonttools-4.59.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5c6d8d773470a5107052874341ed3c487c16ecd179976d81afed89dea5cd7406", size = 5045983 },- { url = "https://files.pythonhosted.org/packages/a2/af/8a2c3f6619cc43cf87951405337cc8460d08a4e717bb05eaa94b335d11dc/fonttools-4.59.1-cp312-cp312-win32.whl", hash = "sha256:2a2d0d33307f6ad3a2086a95dd607c202ea8852fa9fb52af9b48811154d1428a", size = 2203407 },- { url = "https://files.pythonhosted.org/packages/8e/f2/a19b874ddbd3ebcf11d7e25188ef9ac3f68b9219c62263acb34aca8cde05/fonttools-4.59.1-cp312-cp312-win_amd64.whl", hash = "sha256:0b9e4fa7eaf046ed6ac470f6033d52c052481ff7a6e0a92373d14f556f298dc0", size = 2251561 },- { url = "https://files.pythonhosted.org/packages/19/5e/94a4d7f36c36e82f6a81e0064d148542e0ad3e6cf51fc5461ca128f3658d/fonttools-4.59.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:89d9957b54246c6251345297dddf77a84d2c19df96af30d2de24093bbdf0528b", size = 2760192 },- { url = "https://files.pythonhosted.org/packages/ee/a5/f50712fc33ef9d06953c660cefaf8c8fe4b8bc74fa21f44ee5e4f9739439/fonttools-4.59.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8156b11c0d5405810d216f53907bd0f8b982aa5f1e7e3127ab3be1a4062154ff", size = 2332694 },- { url = "https://files.pythonhosted.org/packages/e9/a2/5a9fc21c354bf8613215ce233ab0d933bd17d5ff4c29693636551adbc7b3/fonttools-4.59.1-cp313-cp313-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:8387876a8011caec52d327d5e5bca705d9399ec4b17afb8b431ec50d47c17d23", size = 4889254 },- { url = "https://files.pythonhosted.org/packages/2d/e5/54a6dc811eba018d022ca2e8bd6f2969291f9586ccf9a22a05fc55f91250/fonttools-4.59.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fb13823a74b3a9204a8ed76d3d6d5ec12e64cc5bc44914eb9ff1cdac04facd43", size = 4949109 },- { url = "https://files.pythonhosted.org/packages/db/15/b05c72a248a95bea0fd05fbd95acdf0742945942143fcf961343b7a3663a/fonttools-4.59.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:e1ca10da138c300f768bb68e40e5b20b6ecfbd95f91aac4cc15010b6b9d65455", size = 4888428 },- { url = "https://files.pythonhosted.org/packages/63/71/c7d6840f858d695adc0c4371ec45e3fb1c8e060b276ba944e2800495aca4/fonttools-4.59.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:2beb5bfc4887a3130f8625349605a3a45fe345655ce6031d1bac11017454b943", size = 5032668 },- { url = "https://files.pythonhosted.org/packages/90/54/57be4aca6f1312e2bc4d811200dd822325794e05bdb26eeff0976edca651/fonttools-4.59.1-cp313-cp313-win32.whl", hash = "sha256:419f16d750d78e6d704bfe97b48bba2f73b15c9418f817d0cb8a9ca87a5b94bf", size = 2201832 },- { url = "https://files.pythonhosted.org/packages/fc/1f/1899a6175a5f900ed8730a0d64f53ca1b596ed7609bfda033cf659114258/fonttools-4.59.1-cp313-cp313-win_amd64.whl", hash = "sha256:c536f8a852e8d3fa71dde1ec03892aee50be59f7154b533f0bf3c1174cfd5126", size = 2250673 },- { url = "https://files.pythonhosted.org/packages/15/07/f6ba82c22f118d9985c37fea65d8d715ca71300d78b6c6e90874dc59f11d/fonttools-4.59.1-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:d5c3bfdc9663f3d4b565f9cb3b8c1efb3e178186435b45105bde7328cfddd7fe", size = 2758606 },- { url = "https://files.pythonhosted.org/packages/3a/81/84aa3d0ce27b0112c28b67b637ff7a47cf401cf5fbfee6476e4bc9777580/fonttools-4.59.1-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:ea03f1da0d722fe3c2278a05957e6550175571a4894fbf9d178ceef4a3783d2b", size = 2330187 },- { url = "https://files.pythonhosted.org/packages/17/41/b3ba43f78afb321e2e50232c87304c8d0f5ab39b64389b8286cc39cdb824/fonttools-4.59.1-cp314-cp314-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:57a3708ca6bfccb790f585fa6d8f29432ec329618a09ff94c16bcb3c55994643", size = 4832020 },- { url = "https://files.pythonhosted.org/packages/67/b1/3af871c7fb325a68938e7ce544ca48bfd2c6bb7b357f3c8252933b29100a/fonttools-4.59.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:729367c91eb1ee84e61a733acc485065a00590618ca31c438e7dd4d600c01486", size = 4930687 },- { url = "https://files.pythonhosted.org/packages/c5/4f/299fc44646b30d9ef03ffaa78b109c7bd32121f0d8f10009ee73ac4514bc/fonttools-4.59.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:8f8ef66ac6db450193ed150e10b3b45dde7aded10c5d279968bc63368027f62b", size = 4875794 },- { url = "https://files.pythonhosted.org/packages/90/cf/a0a3d763ab58f5f81ceff104ddb662fd9da94248694862b9c6cbd509fdd5/fonttools-4.59.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:075f745d539a998cd92cb84c339a82e53e49114ec62aaea8307c80d3ad3aef3a", size = 4985780 },- { url = "https://files.pythonhosted.org/packages/72/c5/ba76511aaae143d89c29cd32ce30bafb61c477e8759a1590b8483f8065f8/fonttools-4.59.1-cp314-cp314-win32.whl", hash = "sha256:c2b0597522d4c5bb18aa5cf258746a2d4a90f25878cbe865e4d35526abd1b9fc", size = 2205610 },- { url = "https://files.pythonhosted.org/packages/a9/65/b250e69d6caf35bc65cddbf608be0662d741c248f2e7503ab01081fc267e/fonttools-4.59.1-cp314-cp314-win_amd64.whl", hash = "sha256:e9ad4ce044e3236f0814c906ccce8647046cc557539661e35211faadf76f283b", size = 2255376 },- { url = "https://files.pythonhosted.org/packages/11/f3/0bc63a23ac0f8175e23d82f85d6ee693fbd849de7ad739f0a3622182ad29/fonttools-4.59.1-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:652159e8214eb4856e8387ebcd6b6bd336ee258cbeb639c8be52005b122b9609", size = 2826546 },- { url = "https://files.pythonhosted.org/packages/e9/46/a3968205590e068fdf60e926be329a207782576cb584d3b7dcd2d2844957/fonttools-4.59.1-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:43d177cd0e847ea026fedd9f099dc917da136ed8792d142298a252836390c478", size = 2359771 },- { url = "https://files.pythonhosted.org/packages/b8/ff/d14b4c283879e8cb57862d9624a34fe6522b6fcdd46ccbfc58900958794a/fonttools-4.59.1-cp314-cp314t-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:e54437651e1440ee53a95e6ceb6ee440b67a3d348c76f45f4f48de1a5ecab019", size = 4831575 },- { url = "https://files.pythonhosted.org/packages/9c/04/a277d9a584a49d98ca12d3b2c6663bdf333ae97aaa83bd0cdabf7c5a6c84/fonttools-4.59.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6065fdec8ff44c32a483fd44abe5bcdb40dd5e2571a5034b555348f2b3a52cea", size = 5069962 },- { url = "https://files.pythonhosted.org/packages/16/6f/3d2ae69d96c4cdee6dfe7598ca5519a1514487700ca3d7c49c5a1ad65308/fonttools-4.59.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:42052b56d176f8b315fbc09259439c013c0cb2109df72447148aeda677599612", size = 4942926 },- { url = "https://files.pythonhosted.org/packages/0c/d3/c17379e0048d03ce26b38e4ab0e9a98280395b00529e093fe2d663ac0658/fonttools-4.59.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:bcd52eaa5c4c593ae9f447c1d13e7e4a00ca21d755645efa660b6999425b3c88", size = 4958678 },- { url = "https://files.pythonhosted.org/packages/8c/3f/c5543a1540abdfb4d375e3ebeb84de365ab9b153ec14cb7db05f537dd1e7/fonttools-4.59.1-cp314-cp314t-win32.whl", hash = "sha256:02e4fdf27c550dded10fe038a5981c29f81cb9bc649ff2eaa48e80dab8998f97", size = 2266706 },- { url = "https://files.pythonhosted.org/packages/3e/99/85bff6e674226bc8402f983e365f07e76d990e7220ba72bcc738fef52391/fonttools-4.59.1-cp314-cp314t-win_amd64.whl", hash = "sha256:412a5fd6345872a7c249dac5bcce380393f40c1c316ac07f447bc17d51900922", size = 2329994 },- { url = "https://files.pythonhosted.org/packages/0f/64/9d606e66d498917cd7a2ff24f558010d42d6fd4576d9dd57f0bd98333f5a/fonttools-4.59.1-py3-none-any.whl", hash = "sha256:647db657073672a8330608970a984d51573557f328030566521bc03415535042", size = 1130094 },+version = "4.60.1"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/4b/42/97a13e47a1e51a5a7142475bbcf5107fe3a68fc34aef331c897d5fb98ad0/fonttools-4.60.1.tar.gz", hash = "sha256:ef00af0439ebfee806b25f24c8f92109157ff3fac5731dc7867957812e87b8d9", size = 3559823 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/ea/85/639aa9bface1537e0fb0f643690672dde0695a5bbbc90736bc571b0b1941/fonttools-4.60.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:7b4c32e232a71f63a5d00259ca3d88345ce2a43295bb049d21061f338124246f", size = 2831872 },+ { url = "https://files.pythonhosted.org/packages/6b/47/3c63158459c95093be9618794acb1067b3f4d30dcc5c3e8114b70e67a092/fonttools-4.60.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:3630e86c484263eaac71d117085d509cbcf7b18f677906824e4bace598fb70d2", size = 2356990 },+ { url = "https://files.pythonhosted.org/packages/94/dd/1934b537c86fcf99f9761823f1fc37a98fbd54568e8e613f29a90fed95a9/fonttools-4.60.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5c1015318e4fec75dd4943ad5f6a206d9727adf97410d58b7e32ab644a807914", size = 5042189 },+ { url = "https://files.pythonhosted.org/packages/d2/d2/9f4e4c4374dd1daa8367784e1bd910f18ba886db1d6b825b12edf6db3edc/fonttools-4.60.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e6c58beb17380f7c2ea181ea11e7db8c0ceb474c9dd45f48e71e2cb577d146a1", size = 4978683 },+ { url = "https://files.pythonhosted.org/packages/cc/c4/0fb2dfd1ecbe9a07954cc13414713ed1eab17b1c0214ef07fc93df234a47/fonttools-4.60.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:ec3681a0cb34c255d76dd9d865a55f260164adb9fa02628415cdc2d43ee2c05d", size = 5021372 },+ { url = "https://files.pythonhosted.org/packages/0c/d5/495fc7ae2fab20223cc87179a8f50f40f9a6f821f271ba8301ae12bb580f/fonttools-4.60.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f4b5c37a5f40e4d733d3bbaaef082149bee5a5ea3156a785ff64d949bd1353fa", size = 5132562 },+ { url = "https://files.pythonhosted.org/packages/bc/fa/021dab618526323c744e0206b3f5c8596a2e7ae9aa38db5948a131123e83/fonttools-4.60.1-cp311-cp311-win32.whl", hash = "sha256:398447f3d8c0c786cbf1209711e79080a40761eb44b27cdafffb48f52bcec258", size = 2230288 },+ { url = "https://files.pythonhosted.org/packages/bb/78/0e1a6d22b427579ea5c8273e1c07def2f325b977faaf60bb7ddc01456cb1/fonttools-4.60.1-cp311-cp311-win_amd64.whl", hash = "sha256:d066ea419f719ed87bc2c99a4a4bfd77c2e5949cb724588b9dd58f3fd90b92bf", size = 2278184 },+ { url = "https://files.pythonhosted.org/packages/e3/f7/a10b101b7a6f8836a5adb47f2791f2075d044a6ca123f35985c42edc82d8/fonttools-4.60.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:7b0c6d57ab00dae9529f3faf187f2254ea0aa1e04215cf2f1a8ec277c96661bc", size = 2832953 },+ { url = "https://files.pythonhosted.org/packages/ed/fe/7bd094b59c926acf2304d2151354ddbeb74b94812f3dc943c231db09cb41/fonttools-4.60.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:839565cbf14645952d933853e8ade66a463684ed6ed6c9345d0faf1f0e868877", size = 2352706 },+ { url = "https://files.pythonhosted.org/packages/c0/ca/4bb48a26ed95a1e7eba175535fe5805887682140ee0a0d10a88e1de84208/fonttools-4.60.1-cp312-cp312-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:8177ec9676ea6e1793c8a084a90b65a9f778771998eb919d05db6d4b1c0b114c", size = 4923716 },+ { url = "https://files.pythonhosted.org/packages/b8/9f/2cb82999f686c1d1ddf06f6ae1a9117a880adbec113611cc9d22b2fdd465/fonttools-4.60.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:996a4d1834524adbb423385d5a629b868ef9d774670856c63c9a0408a3063401", size = 4968175 },+ { url = "https://files.pythonhosted.org/packages/18/79/be569699e37d166b78e6218f2cde8c550204f2505038cdd83b42edc469b9/fonttools-4.60.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a46b2f450bc79e06ef3b6394f0c68660529ed51692606ad7f953fc2e448bc903", size = 4911031 },+ { url = "https://files.pythonhosted.org/packages/cc/9f/89411cc116effaec5260ad519162f64f9c150e5522a27cbb05eb62d0c05b/fonttools-4.60.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:6ec722ee589e89a89f5b7574f5c45604030aa6ae24cb2c751e2707193b466fed", size = 5062966 },+ { url = "https://files.pythonhosted.org/packages/62/a1/f888221934b5731d46cb9991c7a71f30cb1f97c0ef5fcf37f8da8fce6c8e/fonttools-4.60.1-cp312-cp312-win32.whl", hash = "sha256:b2cf105cee600d2de04ca3cfa1f74f1127f8455b71dbad02b9da6ec266e116d6", size = 2218750 },+ { url = "https://files.pythonhosted.org/packages/88/8f/a55b5550cd33cd1028601df41acd057d4be20efa5c958f417b0c0613924d/fonttools-4.60.1-cp312-cp312-win_amd64.whl", hash = "sha256:992775c9fbe2cf794786fa0ffca7f09f564ba3499b8fe9f2f80bd7197db60383", size = 2267026 },+ { url = "https://files.pythonhosted.org/packages/7c/5b/cdd2c612277b7ac7ec8c0c9bc41812c43dc7b2d5f2b0897e15fdf5a1f915/fonttools-4.60.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:6f68576bb4bbf6060c7ab047b1574a1ebe5c50a17de62830079967b211059ebb", size = 2825777 },+ { url = "https://files.pythonhosted.org/packages/d6/8a/de9cc0540f542963ba5e8f3a1f6ad48fa211badc3177783b9d5cadf79b5d/fonttools-4.60.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:eedacb5c5d22b7097482fa834bda0dafa3d914a4e829ec83cdea2a01f8c813c4", size = 2348080 },+ { url = "https://files.pythonhosted.org/packages/2d/8b/371ab3cec97ee3fe1126b3406b7abd60c8fec8975fd79a3c75cdea0c3d83/fonttools-4.60.1-cp313-cp313-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:b33a7884fabd72bdf5f910d0cf46be50dce86a0362a65cfc746a4168c67eb96c", size = 4903082 },+ { url = "https://files.pythonhosted.org/packages/04/05/06b1455e4bc653fcb2117ac3ef5fa3a8a14919b93c60742d04440605d058/fonttools-4.60.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2409d5fb7b55fd70f715e6d34e7a6e4f7511b8ad29a49d6df225ee76da76dd77", size = 4960125 },+ { url = "https://files.pythonhosted.org/packages/8e/37/f3b840fcb2666f6cb97038793606bdd83488dca2d0b0fc542ccc20afa668/fonttools-4.60.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:c8651e0d4b3bdeda6602b85fdc2abbefc1b41e573ecb37b6779c4ca50753a199", size = 4901454 },+ { url = "https://files.pythonhosted.org/packages/fd/9e/eb76f77e82f8d4a46420aadff12cec6237751b0fb9ef1de373186dcffb5f/fonttools-4.60.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:145daa14bf24824b677b9357c5e44fd8895c2a8f53596e1b9ea3496081dc692c", size = 5044495 },+ { url = "https://files.pythonhosted.org/packages/f8/b3/cede8f8235d42ff7ae891bae8d619d02c8ac9fd0cfc450c5927a6200c70d/fonttools-4.60.1-cp313-cp313-win32.whl", hash = "sha256:2299df884c11162617a66b7c316957d74a18e3758c0274762d2cc87df7bc0272", size = 2217028 },+ { url = "https://files.pythonhosted.org/packages/75/4d/b022c1577807ce8b31ffe055306ec13a866f2337ecee96e75b24b9b753ea/fonttools-4.60.1-cp313-cp313-win_amd64.whl", hash = "sha256:a3db56f153bd4c5c2b619ab02c5db5192e222150ce5a1bc10f16164714bc39ac", size = 2266200 },+ { url = "https://files.pythonhosted.org/packages/9a/83/752ca11c1aa9a899b793a130f2e466b79ea0cf7279c8d79c178fc954a07b/fonttools-4.60.1-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:a884aef09d45ba1206712c7dbda5829562d3fea7726935d3289d343232ecb0d3", size = 2822830 },+ { url = "https://files.pythonhosted.org/packages/57/17/bbeab391100331950a96ce55cfbbff27d781c1b85ebafb4167eae50d9fe3/fonttools-4.60.1-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:8a44788d9d91df72d1a5eac49b31aeb887a5f4aab761b4cffc4196c74907ea85", size = 2345524 },+ { url = "https://files.pythonhosted.org/packages/3d/2e/d4831caa96d85a84dd0da1d9f90d81cec081f551e0ea216df684092c6c97/fonttools-4.60.1-cp314-cp314-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:e852d9dda9f93ad3651ae1e3bb770eac544ec93c3807888798eccddf84596537", size = 4843490 },+ { url = "https://files.pythonhosted.org/packages/49/13/5e2ea7c7a101b6fc3941be65307ef8df92cbbfa6ec4804032baf1893b434/fonttools-4.60.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:154cb6ee417e417bf5f7c42fe25858c9140c26f647c7347c06f0cc2d47eff003", size = 4944184 },+ { url = "https://files.pythonhosted.org/packages/0c/2b/cf9603551c525b73fc47c52ee0b82a891579a93d9651ed694e4e2cd08bb8/fonttools-4.60.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:5664fd1a9ea7f244487ac8f10340c4e37664675e8667d6fee420766e0fb3cf08", size = 4890218 },+ { url = "https://files.pythonhosted.org/packages/fd/2f/933d2352422e25f2376aae74f79eaa882a50fb3bfef3c0d4f50501267101/fonttools-4.60.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:583b7f8e3c49486e4d489ad1deacfb8d5be54a8ef34d6df824f6a171f8511d99", size = 4999324 },+ { url = "https://files.pythonhosted.org/packages/38/99/234594c0391221f66216bc2c886923513b3399a148defaccf81dc3be6560/fonttools-4.60.1-cp314-cp314-win32.whl", hash = "sha256:66929e2ea2810c6533a5184f938502cfdaea4bc3efb7130d8cc02e1c1b4108d6", size = 2220861 },+ { url = "https://files.pythonhosted.org/packages/3e/1d/edb5b23726dde50fc4068e1493e4fc7658eeefcaf75d4c5ffce067d07ae5/fonttools-4.60.1-cp314-cp314-win_amd64.whl", hash = "sha256:f3d5be054c461d6a2268831f04091dc82753176f6ea06dc6047a5e168265a987", size = 2270934 },+ { url = "https://files.pythonhosted.org/packages/fb/da/1392aaa2170adc7071fe7f9cfd181a5684a7afcde605aebddf1fb4d76df5/fonttools-4.60.1-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:b6379e7546ba4ae4b18f8ae2b9bc5960936007a1c0e30b342f662577e8bc3299", size = 2894340 },+ { url = "https://files.pythonhosted.org/packages/bf/a7/3b9f16e010d536ce567058b931a20b590d8f3177b2eda09edd92e392375d/fonttools-4.60.1-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:9d0ced62b59e0430b3690dbc5373df1c2aa7585e9a8ce38eff87f0fd993c5b01", size = 2375073 },+ { url = "https://files.pythonhosted.org/packages/9b/b5/e9bcf51980f98e59bb5bb7c382a63c6f6cac0eec5f67de6d8f2322382065/fonttools-4.60.1-cp314-cp314t-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:875cb7764708b3132637f6c5fb385b16eeba0f7ac9fa45a69d35e09b47045801", size = 4849758 },+ { url = "https://files.pythonhosted.org/packages/e3/dc/1d2cf7d1cba82264b2f8385db3f5960e3d8ce756b4dc65b700d2c496f7e9/fonttools-4.60.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a184b2ea57b13680ab6d5fbde99ccef152c95c06746cb7718c583abd8f945ccc", size = 5085598 },+ { url = "https://files.pythonhosted.org/packages/5d/4d/279e28ba87fb20e0c69baf72b60bbf1c4d873af1476806a7b5f2b7fac1ff/fonttools-4.60.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:026290e4ec76583881763fac284aca67365e0be9f13a7fb137257096114cb3bc", size = 4957603 },+ { url = "https://files.pythonhosted.org/packages/78/d4/ff19976305e0c05aa3340c805475abb00224c954d3c65e82c0a69633d55d/fonttools-4.60.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f0e8817c7d1a0c2eedebf57ef9a9896f3ea23324769a9a2061a80fe8852705ed", size = 4974184 },+ { url = "https://files.pythonhosted.org/packages/63/22/8553ff6166f5cd21cfaa115aaacaa0dc73b91c079a8cfd54a482cbc0f4f5/fonttools-4.60.1-cp314-cp314t-win32.whl", hash = "sha256:1410155d0e764a4615774e5c2c6fc516259fe3eca5882f034eb9bfdbee056259", size = 2282241 },+ { url = "https://files.pythonhosted.org/packages/8a/cb/fa7b4d148e11d5a72761a22e595344133e83a9507a4c231df972e657579b/fonttools-4.60.1-cp314-cp314t-win_amd64.whl", hash = "sha256:022beaea4b73a70295b688f817ddc24ed3e3418b5036ffcd5658141184ef0d0c", size = 2345760 },+ { url = "https://files.pythonhosted.org/packages/c7/93/0dd45cd283c32dea1545151d8c3637b4b8c53cdb3a625aeb2885b184d74d/fonttools-4.60.1-py3-none-any.whl", hash = "sha256:906306ac7afe2156fcf0042173d6ebbb05416af70f6b370967b47f8f00103bbb", size = 1143175 },][[package]]@@ -417,12 +472,13 @@ dependencies = [{ name = "ajc27-freemocap-blender-addon" },{ name = "aniposelib" },{ name = "libsass" },- { name = "mediapipe" },{ name = "numpydantic" },{ name = "opencv-contrib-python" },+ { name = "pyceres" },{ name = "pydantic" },{ name = "pyinstaller" },{ name = "requests" },+ { name = "scikit-learn" },{ name = "skelly-viewer" },{ name = "skellycam" },{ name = "skellyforge" },@@ -439,15 +495,16 @@ requires-dist = [{ name = "ajc27-freemocap-blender-addon", specifier = "==2024.12.1032" },{ name = "aniposelib", specifier = ">=0.7.0" },{ name = "libsass", specifier = ">=0.23.0" },- { name = "mediapipe", specifier = ">=0.10.21" },{ name = "numpydantic", specifier = ">=1.6.7" },- { name = "opencv-contrib-python", specifier = ">=4.8.1.78" },+ { name = "opencv-contrib-python", specifier = "==4.10.*" },+ { name = "pyceres", specifier = ">=2.5" },{ name = "pydantic", specifier = ">=2.10.4" },{ name = "pyinstaller", specifier = ">=6.11.0" },{ name = "requests", specifier = ">=2.32.3" },+ { name = "scikit-learn", specifier = ">=1.7.2" },{ name = "skelly-viewer" },{ name = "skellycam", git = "https://github.com/freemocap/skellycam?branch=jon%2Fdevelopment" },- { name = "skellyforge", git = "https://github.com/freemocap/skellyforge" },+ { name = "skellyforge", git = "https://github.com/freemocap/skellyforge?branch=jon%2Fdevelopment" },{ name = "skellytracker", git = "https://github.com/freemocap/skellytracker?branch=jon%2Fdevelopment" },]@@ -493,20 +550,20 @@ wheels = [[[package]]name = "idna"-version = "3.10"+version = "3.11"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/f1/70/7703c29685631f5a7590aa73f1f1d3fa9a380e654b86af429e0934a32f7d/idna-3.10.tar.gz", hash = "sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9", size = 190490 }+sdist = { url = "https://files.pythonhosted.org/packages/6f/6d/0703ccc57f3a7233505399edb88de3cbd678da106337b9fcde432b65ed60/idna-3.11.tar.gz", hash = "sha256:795dafcc9c04ed0c1fb032c2aa73654d8e8c5023a7df64a53f39190ada629902", size = 194582 }wheels = [- { url = "https://files.pythonhosted.org/packages/76/c6/c88e154df9c4e1a2a66ccf0005a88dfb2650c1dffb6f5ce603dfbd452ce3/idna-3.10-py3-none-any.whl", hash = "sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3", size = 70442 },+ { url = "https://files.pythonhosted.org/packages/0e/61/66938bbb5fc52dbdf84594873d5b51fb1f7c7794e9c0f5bd885f30bc507b/idna-3.11-py3-none-any.whl", hash = "sha256:771a87f49d9defaf64091e6e6fe9c18d4833f140bd19464795bc32d966ca37ea", size = 71008 },][[package]]name = "iniconfig"-version = "2.1.0"+version = "2.3.0"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/f2/97/ebf4da567aa6827c909642694d71c9fcf53e5b504f2d96afea02718862f3/iniconfig-2.1.0.tar.gz", hash = "sha256:3abbd2e30b36733fee78f9c7f7308f2d0050e88f0087fd25c2645f63c773e1c7", size = 4793 }+sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503 }wheels = [- { url = "https://files.pythonhosted.org/packages/2c/e1/e6716421ea10d38022b952c159d5161ca1193197fb744506875fbb87ea7b/iniconfig-2.1.0-py3-none-any.whl", hash = "sha256:9deba5723312380e77435581c6bf4935c94cbfab9b1ed33ef8d238ea168eb760", size = 6050 },+ { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484 },][[package]]@@ -531,7 +588,7 @@ wheels = [[[package]]name = "jax"-version = "0.6.1"+version = "0.7.1"source = { registry = "https://pypi.org/simple" }resolution-markers = ["python_full_version < '3.12' and platform_system == 'Darwin'",@@ -542,26 +599,30 @@ resolution-markers = ["(python_full_version == '3.12.*' and platform_machine != 'aarch64' and platform_system != 'Darwin') or (python_full_version == '3.12.*' and platform_system != 'Darwin' and platform_system != 'Linux')",]dependencies = [- { name = "jaxlib", marker = "python_full_version < '3.13'" },+ { name = "jaxlib", version = "0.7.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.13'" },{ name = "ml-dtypes", version = "0.5.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.13'" },{ name = "numpy", marker = "python_full_version < '3.13'" },{ name = "opt-einsum", marker = "python_full_version < '3.13'" },{ name = "scipy", marker = "python_full_version < '3.13'" },]-sdist = { url = "https://files.pythonhosted.org/packages/a3/b9/6d3d88fbab17696d00824ecac3d67feea1ff0abe12d3ebe64166a311ac04/jax-0.6.1.tar.gz", hash = "sha256:c4dcb93e1d34f80cf7adfa81f3fdab62a5068b69107b7a6117f8742ab37b6779", size = 2062260 }+sdist = { url = "https://files.pythonhosted.org/packages/bc/e8/b393ee314d3b042bd66b986d38e52f4e6046590399d916381265c20467d3/jax-0.7.1.tar.gz", hash = "sha256:118f56338c503361d2791f069d24339d8d44a8db442ed851d2e591222fb7a56d", size = 2428411 }wheels = [- { url = "https://files.pythonhosted.org/packages/dc/89/99805cd801919b4535e023bfe2de651f5a3ec4f5846a867cbc08006db455/jax-0.6.1-py3-none-any.whl", hash = "sha256:69a4e4506caa5466702bdfd0d7a13d1f9b7281d473885721100a3087fcabf8f9", size = 2394773 },+ { url = "https://files.pythonhosted.org/packages/83/81/793d78c91b0546b3b1f08e55fdd97437174171cd7d70e46098f1a4d94b7b/jax-0.7.1-py3-none-any.whl", hash = "sha256:056e576e0e58465506125699f48111ac8891cce4c9ebf034704c42b219dfd4a6", size = 2827341 },][[package]]name = "jaxlib"version = "0.6.1"source = { registry = "https://pypi.org/simple" }+resolution-markers = [+ "python_full_version >= '3.13' and platform_system == 'Darwin'",+ "python_full_version >= '3.13' and platform_machine == 'aarch64' and platform_system == 'Linux'",+ "(python_full_version >= '3.13' and platform_machine != 'aarch64' and platform_system != 'Darwin') or (python_full_version >= '3.13' and platform_system != 'Darwin' and platform_system != 'Linux')",+]dependencies = [{ name = "ml-dtypes", version = "0.4.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.13'" },- { name = "ml-dtypes", version = "0.5.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.13'" },- { name = "numpy" },- { name = "scipy" },+ { name = "numpy", marker = "python_full_version >= '3.13'" },+ { name = "scipy", marker = "python_full_version >= '3.13'" },]wheels = [{ url = "https://files.pythonhosted.org/packages/80/62/a3ceb8f8dedb43b4f672b9f2f766029a9f94a016ee6d6974894ab0420eb0/jaxlib-0.6.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:02bac5153389f01616516a9fd1dcd6038d23ee50681dac14e4ddbc43ccb3133a", size = 53771693 },@@ -580,6 +641,57 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/f2/d7/dccc6354589ebe6a78f591dbdf15f2ef41c81084e5d051a3d2d1674ecb8f/jaxlib-0.6.1-cp313-cp313t-manylinux2014_x86_64.whl", hash = "sha256:5e4f49113a527bcbac70c9e7074e95d8abfa35c3d67c2fed01f77a7abfd317aa", size = 89194164 },]+[[package]]+name = "jaxlib"+version = "0.7.1"+source = { registry = "https://pypi.org/simple" }+resolution-markers = [+ "python_full_version < '3.12' and platform_system == 'Darwin'",+ "python_full_version < '3.12' and platform_machine == 'aarch64' and platform_system == 'Linux'",+ "(python_full_version < '3.12' and platform_machine != 'aarch64' and platform_system != 'Darwin') or (python_full_version < '3.12' and platform_system != 'Darwin' and platform_system != 'Linux')",+ "python_full_version == '3.12.*' and platform_system == 'Darwin'",+ "python_full_version == '3.12.*' and platform_machine == 'aarch64' and platform_system == 'Linux'",+ "(python_full_version == '3.12.*' and platform_machine != 'aarch64' and platform_system != 'Darwin') or (python_full_version == '3.12.*' and platform_system != 'Darwin' and platform_system != 'Linux')",+]+dependencies = [+ { name = "ml-dtypes", version = "0.5.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.13'" },+ { name = "numpy", marker = "python_full_version < '3.13'" },+ { name = "scipy", marker = "python_full_version < '3.13'" },+]+wheels = [+ { url = "https://files.pythonhosted.org/packages/8b/af/5058d545e95f99a54289648f5430cc3c23263dd70a1391e7491f24ed328d/jaxlib-0.7.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:3f32c3e4c167b7327c342e82d3df84079714ea0b43718be871d039999670b3c9", size = 57686934 },+ { url = "https://files.pythonhosted.org/packages/e8/77/ef7f6cd03e699da7d9755f88741c29b3015654473fc9d5f906da19edcb47/jaxlib-0.7.1-cp311-cp311-manylinux2014_aarch64.whl", hash = "sha256:9fb189c3b39470c4394ffcb18b71e47cffc5bf85e8fcb1e33692686b0c3e04dd", size = 85134885 },+ { url = "https://files.pythonhosted.org/packages/4d/72/304018d46703f337787f010735f70d17212f86778fcba8bb5cf678f8e460/jaxlib-0.7.1-cp311-cp311-manylinux_2_27_x86_64.whl", hash = "sha256:eaf5f68f53bf4dcb93b6512538547667625588e4f3ccaeef048788fd18d8c0d5", size = 81147868 },+ { url = "https://files.pythonhosted.org/packages/f7/b7/0f0df407518691099d659ba6e19db01320dfb58e49d80594eaddd57d77c1/jaxlib-0.7.1-cp311-cp311-win_amd64.whl", hash = "sha256:ab4510fbaeafac6c794ab335f23e71200d824c48f6a0ab20553db8deab8805c5", size = 61185342 },+ { url = "https://files.pythonhosted.org/packages/ef/1f/10543d7a3f7e76dd4bbdc77134890ac2f41bc8570c565961464f6320009b/jaxlib-0.7.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:127c07c727703e5d59f84f655169bec849f4422e52f8546349cecc30a8a13e1d", size = 57682851 },+ { url = "https://files.pythonhosted.org/packages/de/4d/76ee71959311fe3da9951aa6f55af8f98eb3572bb322f5a7c89faf7ab933/jaxlib-0.7.1-cp312-cp312-manylinux2014_aarch64.whl", hash = "sha256:f0f1f52956b8c2518ab000a4d3d8c21be777e1d47f926ba03640e391061a41ee", size = 85133707 },+ { url = "https://files.pythonhosted.org/packages/0d/50/e37d02e250f5feb755112ec95b1c012a36d48a99209277267037d100f630/jaxlib-0.7.1-cp312-cp312-manylinux_2_27_x86_64.whl", hash = "sha256:74abd3135797f82440dd3711a35cba16c430d1bba65474b85bb70e41733a52e9", size = 81156916 },+ { url = "https://files.pythonhosted.org/packages/5a/97/c6c28dfe57cccffd85512615416024b52dd327d78270204caba9311e71f1/jaxlib-0.7.1-cp312-cp312-win_amd64.whl", hash = "sha256:c4023863b14f280516f24ecb7539b4300a3236ea81ed69ad82595beceed1ba1f", size = 61212445 },+ { url = "https://files.pythonhosted.org/packages/35/ad/ab61b9bf72bc2903ee54d02e8d1e1486a4860878712c80c4a52025bfe003/jaxlib-0.7.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2a27379e5ed29765980ef32d4d77f57dd0e1dd965803ac674554044ac23cd3ec", size = 57681905 },+ { url = "https://files.pythonhosted.org/packages/12/e8/fbc318afd21ea7b232ec6a3a1b0138da0d65db1d6f1cea8af458a7d6a482/jaxlib-0.7.1-cp313-cp313-manylinux2014_aarch64.whl", hash = "sha256:ce6a1ba6019764870c27507aca18e526998ad3ad4bea2dd61e19d0499c3b8b04", size = 85133036 },+ { url = "https://files.pythonhosted.org/packages/56/69/209e5b81dd89da84f729a684c126cc3c22bb8d6516f8c968444c7d86050f/jaxlib-0.7.1-cp313-cp313-manylinux_2_27_x86_64.whl", hash = "sha256:b350f519a86eff5a4b1ee014c7faa36585f47f3d63787d1f3e9bdffe9cc41a66", size = 81155944 },+ { url = "https://files.pythonhosted.org/packages/95/46/685ecf0fa3c6d844ac33c0dea59601b9cc6b7236d0e4eb52dc3b7f6f52bb/jaxlib-0.7.1-cp313-cp313-win_amd64.whl", hash = "sha256:407347dd5846248ee40db33da26f2b18c7d135249ff06c0271a2e33efd8fb3fe", size = 61213006 },+ { url = "https://files.pythonhosted.org/packages/4f/ca/c70e5439eec1abc1a93bad521452dbddeefa68128f256991e6845e9fc56a/jaxlib-0.7.1-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:66b33cc15040af5b8d16d3006811eb31372e9f4cfe09393d6cea91795366bfa4", size = 57787598 },+ { url = "https://files.pythonhosted.org/packages/1f/54/6d54d6d6a2019cbffa7316de038002b0250568199f2b4138326eb27e3910/jaxlib-0.7.1-cp313-cp313t-manylinux2014_aarch64.whl", hash = "sha256:58558fa29fd7d6342c066f837e58fcba335182837a959affc128660c089702de", size = 85286808 },+ { url = "https://files.pythonhosted.org/packages/79/e2/a0ce0ac2aa9b12a83f3bb27c570361017743c5cf82f1044771daa4c865a6/jaxlib-0.7.1-cp313-cp313t-manylinux_2_27_x86_64.whl", hash = "sha256:944f7555960d69f1d1c435fff0a76e4edd6a878fe47fe1781f7a0d63b61072e5", size = 81252495 },+ { url = "https://files.pythonhosted.org/packages/7d/e1/9a5317a520aa964944761bf1d050a6a20d0792d9af5005e25804a1ce0e84/jaxlib-0.7.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:72dd9c3e95457a5a54f00e47ec14863b5e61540b944c0df13bf10c259b4d5d73", size = 57696029 },+ { url = "https://files.pythonhosted.org/packages/98/ae/52cb0552b6e1b1008bc68b45ad51091086cccdc1a7e3d32ba9856d7fa879/jaxlib-0.7.1-cp314-cp314-manylinux2014_aarch64.whl", hash = "sha256:023df41212ae4fda869338370f9532bfcd98ccfaee909bb95ea540d6053df547", size = 85146969 },+ { url = "https://files.pythonhosted.org/packages/c7/3a/a63b6bd9cac259c22ae324fcb1d5c74e053e8acad23f13ad39ffa6fd11e6/jaxlib-0.7.1-cp314-cp314-manylinux_2_27_x86_64.whl", hash = "sha256:d52817a42c130d0c330f48edcb3a3e455dc984b6ce53f3182c37aa0fe960109b", size = 81167909 },+ { url = "https://files.pythonhosted.org/packages/5d/e3/75cc67d24e14279c634ed4c4d501ee62f68d8260aac7d87fd267488aa90a/jaxlib-0.7.1-cp314-cp314-win_amd64.whl", hash = "sha256:38ac46ec17c0a86b428590d04559629357fc6dc3a3c76569f022b982c36fc1af", size = 63566625 },+ { url = "https://files.pythonhosted.org/packages/a8/94/f2adf6979a89fcba2ff68b6add47e316bd1274d6ac1284c991d19d8dc2e0/jaxlib-0.7.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:6057a602632bd3299d6c7ffbbb3f1ef2c7573ccbed9eb06cc92042b96e2ca5d4", size = 57787077 },+ { url = "https://files.pythonhosted.org/packages/f2/64/e581007dabf29be6d916fb201f1af264edabc3f74097be9f02606eae8836/jaxlib-0.7.1-cp314-cp314t-manylinux2014_aarch64.whl", hash = "sha256:9766817cfa51743a48fac78c087605c30bf1a91caf11371ca8c41261e6f3a0c8", size = 85285337 },+ { url = "https://files.pythonhosted.org/packages/ee/0e/2e9e5c82f0b8a5a2be470c5185811ab2d780f2da448339e09f71af06f36a/jaxlib-0.7.1-cp314-cp314t-manylinux_2_27_x86_64.whl", hash = "sha256:1ea54e6182d85b82496fbc58bbe51042bea3ee3e1e0d444b3cff446c245bebd5", size = 81256695 },+]++[[package]]+name = "joblib"+version = "1.5.2"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/e8/5d/447af5ea094b9e4c4054f82e223ada074c552335b9b4b2d14bd9b35a67c4/joblib-1.5.2.tar.gz", hash = "sha256:3faa5c39054b2f03ca547da9b2f52fde67c06240c31853f306aea97f13647b55", size = 331077 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/1e/e8/685f47e0d754320684db4425a0967f7d3fa70126bffd76110b7009a0090f/joblib-1.5.2-py3-none-any.whl", hash = "sha256:4e1f0bdbb987e6d843c70cf43714cb276623def372df3c22fe5266b2670bc241", size = 308396 },+]+[[package]]name = "kiwisolver"version = "1.4.9"@@ -694,25 +806,25 @@ wheels = [[[package]]name = "llvmlite"-version = "0.44.0"+version = "0.45.1"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/89/6a/95a3d3610d5c75293d5dbbb2a76480d5d4eeba641557b69fe90af6c5b84e/llvmlite-0.44.0.tar.gz", hash = "sha256:07667d66a5d150abed9157ab6c0b9393c9356f229784a4385c02f99e94fc94d4", size = 171880 }+sdist = { url = "https://files.pythonhosted.org/packages/99/8d/5baf1cef7f9c084fb35a8afbde88074f0d6a727bc63ef764fe0e7543ba40/llvmlite-0.45.1.tar.gz", hash = "sha256:09430bb9d0bb58fc45a45a57c7eae912850bedc095cd0810a57de109c69e1c32", size = 185600 }wheels = [- { url = "https://files.pythonhosted.org/packages/b5/e2/86b245397052386595ad726f9742e5223d7aea999b18c518a50e96c3aca4/llvmlite-0.44.0-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:eed7d5f29136bda63b6d7804c279e2b72e08c952b7c5df61f45db408e0ee52f3", size = 28132305 },- { url = "https://files.pythonhosted.org/packages/ff/ec/506902dc6870249fbe2466d9cf66d531265d0f3a1157213c8f986250c033/llvmlite-0.44.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:ace564d9fa44bb91eb6e6d8e7754977783c68e90a471ea7ce913bff30bd62427", size = 26201090 },- { url = "https://files.pythonhosted.org/packages/99/fe/d030f1849ebb1f394bb3f7adad5e729b634fb100515594aca25c354ffc62/llvmlite-0.44.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c5d22c3bfc842668168a786af4205ec8e3ad29fb1bc03fd11fd48460d0df64c1", size = 42361858 },- { url = "https://files.pythonhosted.org/packages/d7/7a/ce6174664b9077fc673d172e4c888cb0b128e707e306bc33fff8c2035f0d/llvmlite-0.44.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f01a394e9c9b7b1d4e63c327b096d10f6f0ed149ef53d38a09b3749dcf8c9610", size = 41184200 },- { url = "https://files.pythonhosted.org/packages/5f/c6/258801143975a6d09a373f2641237992496e15567b907a4d401839d671b8/llvmlite-0.44.0-cp311-cp311-win_amd64.whl", hash = "sha256:d8489634d43c20cd0ad71330dde1d5bc7b9966937a263ff1ec1cebb90dc50955", size = 30331193 },- { url = "https://files.pythonhosted.org/packages/15/86/e3c3195b92e6e492458f16d233e58a1a812aa2bfbef9bdd0fbafcec85c60/llvmlite-0.44.0-cp312-cp312-macosx_10_14_x86_64.whl", hash = "sha256:1d671a56acf725bf1b531d5ef76b86660a5ab8ef19bb6a46064a705c6ca80aad", size = 28132297 },- { url = "https://files.pythonhosted.org/packages/d6/53/373b6b8be67b9221d12b24125fd0ec56b1078b660eeae266ec388a6ac9a0/llvmlite-0.44.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:5f79a728e0435493611c9f405168682bb75ffd1fbe6fc360733b850c80a026db", size = 26201105 },- { url = "https://files.pythonhosted.org/packages/cb/da/8341fd3056419441286c8e26bf436923021005ece0bff5f41906476ae514/llvmlite-0.44.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c0143a5ef336da14deaa8ec26c5449ad5b6a2b564df82fcef4be040b9cacfea9", size = 42361901 },- { url = "https://files.pythonhosted.org/packages/53/ad/d79349dc07b8a395a99153d7ce8b01d6fcdc9f8231355a5df55ded649b61/llvmlite-0.44.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d752f89e31b66db6f8da06df8b39f9b91e78c5feea1bf9e8c1fba1d1c24c065d", size = 41184247 },- { url = "https://files.pythonhosted.org/packages/e2/3b/a9a17366af80127bd09decbe2a54d8974b6d8b274b39bf47fbaedeec6307/llvmlite-0.44.0-cp312-cp312-win_amd64.whl", hash = "sha256:eae7e2d4ca8f88f89d315b48c6b741dcb925d6a1042da694aa16ab3dd4cbd3a1", size = 30332380 },- { url = "https://files.pythonhosted.org/packages/89/24/4c0ca705a717514c2092b18476e7a12c74d34d875e05e4d742618ebbf449/llvmlite-0.44.0-cp313-cp313-macosx_10_14_x86_64.whl", hash = "sha256:319bddd44e5f71ae2689859b7203080716448a3cd1128fb144fe5c055219d516", size = 28132306 },- { url = "https://files.pythonhosted.org/packages/01/cf/1dd5a60ba6aee7122ab9243fd614abcf22f36b0437cbbe1ccf1e3391461c/llvmlite-0.44.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:9c58867118bad04a0bb22a2e0068c693719658105e40009ffe95c7000fcde88e", size = 26201090 },- { url = "https://files.pythonhosted.org/packages/d2/1b/656f5a357de7135a3777bd735cc7c9b8f23b4d37465505bd0eaf4be9befe/llvmlite-0.44.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:46224058b13c96af1365290bdfebe9a6264ae62fb79b2b55693deed11657a8bf", size = 42361904 },- { url = "https://files.pythonhosted.org/packages/d8/e1/12c5f20cb9168fb3464a34310411d5ad86e4163c8ff2d14a2b57e5cc6bac/llvmlite-0.44.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:aa0097052c32bf721a4efc03bd109d335dfa57d9bffb3d4c24cc680711b8b4fc", size = 41184245 },- { url = "https://files.pythonhosted.org/packages/d0/81/e66fc86539293282fd9cb7c9417438e897f369e79ffb62e1ae5e5154d4dd/llvmlite-0.44.0-cp313-cp313-win_amd64.whl", hash = "sha256:2fb7c4f2fb86cbae6dca3db9ab203eeea0e22d73b99bc2341cdf9de93612e930", size = 30331193 },+ { url = "https://files.pythonhosted.org/packages/04/ad/9bdc87b2eb34642c1cfe6bcb4f5db64c21f91f26b010f263e7467e7536a3/llvmlite-0.45.1-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:60f92868d5d3af30b4239b50e1717cb4e4e54f6ac1c361a27903b318d0f07f42", size = 43043526 },+ { url = "https://files.pythonhosted.org/packages/a5/ea/c25c6382f452a943b4082da5e8c1665ce29a62884e2ec80608533e8e82d5/llvmlite-0.45.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:98baab513e19beb210f1ef39066288784839a44cd504e24fff5d17f1b3cf0860", size = 37253118 },+ { url = "https://files.pythonhosted.org/packages/fe/af/85fc237de98b181dbbe8647324331238d6c52a3554327ccdc83ced28efba/llvmlite-0.45.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3adc2355694d6a6fbcc024d59bb756677e7de506037c878022d7b877e7613a36", size = 56288209 },+ { url = "https://files.pythonhosted.org/packages/0a/df/3daf95302ff49beff4230065e3178cd40e71294968e8d55baf4a9e560814/llvmlite-0.45.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2f3377a6db40f563058c9515dedcc8a3e562d8693a106a28f2ddccf2c8fcf6ca", size = 55140958 },+ { url = "https://files.pythonhosted.org/packages/a4/56/4c0d503fe03bac820ecdeb14590cf9a248e120f483bcd5c009f2534f23f0/llvmlite-0.45.1-cp311-cp311-win_amd64.whl", hash = "sha256:f9c272682d91e0d57f2a76c6d9ebdfccc603a01828cdbe3d15273bdca0c3363a", size = 38132232 },+ { url = "https://files.pythonhosted.org/packages/e2/7c/82cbd5c656e8991bcc110c69d05913be2229302a92acb96109e166ae31fb/llvmlite-0.45.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:28e763aba92fe9c72296911e040231d486447c01d4f90027c8e893d89d49b20e", size = 43043524 },+ { url = "https://files.pythonhosted.org/packages/9d/bc/5314005bb2c7ee9f33102c6456c18cc81745d7055155d1218f1624463774/llvmlite-0.45.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1a53f4b74ee9fd30cb3d27d904dadece67a7575198bd80e687ee76474620735f", size = 37253123 },+ { url = "https://files.pythonhosted.org/packages/96/76/0f7154952f037cb320b83e1c952ec4a19d5d689cf7d27cb8a26887d7bbc1/llvmlite-0.45.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5b3796b1b1e1c14dcae34285d2f4ea488402fbd2c400ccf7137603ca3800864f", size = 56288211 },+ { url = "https://files.pythonhosted.org/packages/00/b1/0b581942be2683ceb6862d558979e87387e14ad65a1e4db0e7dd671fa315/llvmlite-0.45.1-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:779e2f2ceefef0f4368548685f0b4adde34e5f4b457e90391f570a10b348d433", size = 55140958 },+ { url = "https://files.pythonhosted.org/packages/33/94/9ba4ebcf4d541a325fd8098ddc073b663af75cc8b065b6059848f7d4dce7/llvmlite-0.45.1-cp312-cp312-win_amd64.whl", hash = "sha256:9e6c9949baf25d9aa9cd7cf0f6d011b9ca660dd17f5ba2b23bdbdb77cc86b116", size = 38132231 },+ { url = "https://files.pythonhosted.org/packages/1d/e2/c185bb7e88514d5025f93c6c4092f6120c6cea8fe938974ec9860fb03bbb/llvmlite-0.45.1-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:d9ea9e6f17569a4253515cc01dade70aba536476e3d750b2e18d81d7e670eb15", size = 43043524 },+ { url = "https://files.pythonhosted.org/packages/09/b8/b5437b9ecb2064e89ccf67dccae0d02cd38911705112dd0dcbfa9cd9a9de/llvmlite-0.45.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:c9f3cadee1630ce4ac18ea38adebf2a4f57a89bd2740ce83746876797f6e0bfb", size = 37253121 },+ { url = "https://files.pythonhosted.org/packages/f7/97/ad1a907c0173a90dd4df7228f24a3ec61058bc1a9ff8a0caec20a0cc622e/llvmlite-0.45.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:57c48bf2e1083eedbc9406fb83c4e6483017879714916fe8be8a72a9672c995a", size = 56288210 },+ { url = "https://files.pythonhosted.org/packages/32/d8/c99c8ac7a326e9735401ead3116f7685a7ec652691aeb2615aa732b1fc4a/llvmlite-0.45.1-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3aa3dfceda4219ae39cf18806c60eeb518c1680ff834b8b311bd784160b9ce40", size = 55140957 },+ { url = "https://files.pythonhosted.org/packages/09/56/ed35668130e32dbfad2eb37356793b0a95f23494ab5be7d9bf5cb75850ee/llvmlite-0.45.1-cp313-cp313-win_amd64.whl", hash = "sha256:080e6f8d0778a8239cd47686d402cb66eb165e421efa9391366a9b7e5810a38b", size = 38132232 },][[package]]@@ -741,7 +853,7 @@ wheels = [[[package]]name = "matplotlib"-version = "3.8.2"+version = "3.10.7"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "contourpy" },@@ -754,20 +866,53 @@ dependencies = [{ name = "pyparsing" },{ name = "python-dateutil" },]-sdist = { url = "https://files.pythonhosted.org/packages/fb/ab/38a0e94cb01dacb50f06957c2bed1c83b8f9dac6618988a37b2487862944/matplotlib-3.8.2.tar.gz", hash = "sha256:01a978b871b881ee76017152f1f1a0cbf6bd5f7b8ff8c96df0df1bd57d8755a1", size = 35866957 }-wheels = [- { url = "https://files.pythonhosted.org/packages/a9/0d/53afb186adafc7326d093b8333e8a79974c495095771659f4304626c4bc7/matplotlib-3.8.2-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:d86593ccf546223eb75a39b44c32788e6f6440d13cfc4750c1c15d0fcb850b63", size = 7593458 },- { url = "https://files.pythonhosted.org/packages/ce/25/a557ee10ac9dce1300850024707ce1850a6958f1673a9194be878b99d631/matplotlib-3.8.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:9a5430836811b7652991939012f43d2808a2db9b64ee240387e8c43e2e5578c8", size = 7486840 },- { url = "https://files.pythonhosted.org/packages/e7/3d/72712b3895ee180f6e342638a8591c31912fbcc09ce9084cc256da16d0a0/matplotlib-3.8.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b9576723858a78751d5aacd2497b8aef29ffea6d1c95981505877f7ac28215c6", size = 11387332 },- { url = "https://files.pythonhosted.org/packages/92/1a/cd3e0c90d1a763ad90073e13b189b4702f11becf4e71dbbad70a7a149811/matplotlib-3.8.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5ba9cbd8ac6cf422f3102622b20f8552d601bf8837e49a3afed188d560152788", size = 11616911 },- { url = "https://files.pythonhosted.org/packages/78/4a/bad239071477305a3758eb4810615e310a113399cddd7682998be9f01e97/matplotlib-3.8.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:03f9d160a29e0b65c0790bb07f4f45d6a181b1ac33eb1bb0dd225986450148f0", size = 9549260 },- { url = "https://files.pythonhosted.org/packages/26/5a/27fd341e4510257789f19a4b4be8bb90d1113b8f176c3dab562b4f21466e/matplotlib-3.8.2-cp311-cp311-win_amd64.whl", hash = "sha256:3773002da767f0a9323ba1a9b9b5d00d6257dbd2a93107233167cfb581f64717", size = 7645742 },- { url = "https://files.pythonhosted.org/packages/e4/1b/864d28d5a72d586ac137f4ca54d5afc8b869720e30d508dbd9adcce4d231/matplotlib-3.8.2-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:4c318c1e95e2f5926fba326f68177dee364aa791d6df022ceb91b8221bd0a627", size = 7590988 },- { url = "https://files.pythonhosted.org/packages/9a/b0/dd2b60f2dd90fbc21d1d3129c36a453c322d7995d5e3589f5b3c59ee528d/matplotlib-3.8.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:091275d18d942cf1ee9609c830a1bc36610607d8223b1b981c37d5c9fc3e46a4", size = 7483594 },- { url = "https://files.pythonhosted.org/packages/33/da/9942533ad9f96753bde0e5a5d48eacd6c21de8ea1ad16570e31bda8a017f/matplotlib-3.8.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1b0f3b8ea0e99e233a4bcc44590f01604840d833c280ebb8fe5554fd3e6cfe8d", size = 11380843 },- { url = "https://files.pythonhosted.org/packages/fc/52/bfd36eb4745a3b21b3946c2c3a15679b620e14574fe2b98e9451b65ef578/matplotlib-3.8.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d7b1704a530395aaf73912be741c04d181f82ca78084fbd80bc737be04848331", size = 11604608 },- { url = "https://files.pythonhosted.org/packages/6d/8c/0cdfbf604d4ea3dfa77435176c51e233cc408ad8f3efbf8d2c9f57cbdafb/matplotlib-3.8.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:533b0e3b0c6768eef8cbe4b583731ce25a91ab54a22f830db2b031e83cca9213", size = 9545252 },- { url = "https://files.pythonhosted.org/packages/2e/51/c77a14869b7eb9d6fb440e811b754fc3950d6868c38ace57d0632b674415/matplotlib-3.8.2-cp312-cp312-win_amd64.whl", hash = "sha256:0f4fc5d72b75e2c18e55eb32292659cf731d9d5b312a6eb036506304f4675630", size = 7645067 },+sdist = { url = "https://files.pythonhosted.org/packages/ae/e2/d2d5295be2f44c678ebaf3544ba32d20c1f9ef08c49fe47f496180e1db15/matplotlib-3.10.7.tar.gz", hash = "sha256:a06ba7e2a2ef9131c79c49e63dad355d2d878413a0376c1727c8b9335ff731c7", size = 34804865 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/fc/bc/0fb489005669127ec13f51be0c6adc074d7cf191075dab1da9fe3b7a3cfc/matplotlib-3.10.7-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:53b492410a6cd66c7a471de6c924f6ede976e963c0f3097a3b7abfadddc67d0a", size = 8257507 },+ { url = "https://files.pythonhosted.org/packages/e2/6a/d42588ad895279ff6708924645b5d2ed54a7fb2dc045c8a804e955aeace1/matplotlib-3.10.7-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d9749313deb729f08207718d29c86246beb2ea3fdba753595b55901dee5d2fd6", size = 8119565 },+ { url = "https://files.pythonhosted.org/packages/10/b7/4aa196155b4d846bd749cf82aa5a4c300cf55a8b5e0dfa5b722a63c0f8a0/matplotlib-3.10.7-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2222c7ba2cbde7fe63032769f6eb7e83ab3227f47d997a8453377709b7fe3a5a", size = 8692668 },+ { url = "https://files.pythonhosted.org/packages/e6/e7/664d2b97016f46683a02d854d730cfcf54ff92c1dafa424beebef50f831d/matplotlib-3.10.7-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e91f61a064c92c307c5a9dc8c05dc9f8a68f0a3be199d9a002a0622e13f874a1", size = 9521051 },+ { url = "https://files.pythonhosted.org/packages/a8/a3/37aef1404efa615f49b5758a5e0261c16dd88f389bc1861e722620e4a754/matplotlib-3.10.7-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:6f1851eab59ca082c95df5a500106bad73672645625e04538b3ad0f69471ffcc", size = 9576878 },+ { url = "https://files.pythonhosted.org/packages/33/cd/b145f9797126f3f809d177ca378de57c45413c5099c5990de2658760594a/matplotlib-3.10.7-cp311-cp311-win_amd64.whl", hash = "sha256:6516ce375109c60ceec579e699524e9d504cd7578506f01150f7a6bc174a775e", size = 8115142 },+ { url = "https://files.pythonhosted.org/packages/2e/39/63bca9d2b78455ed497fcf51a9c71df200a11048f48249038f06447fa947/matplotlib-3.10.7-cp311-cp311-win_arm64.whl", hash = "sha256:b172db79759f5f9bc13ef1c3ef8b9ee7b37b0247f987fbbbdaa15e4f87fd46a9", size = 7992439 },+ { url = "https://files.pythonhosted.org/packages/be/b3/09eb0f7796932826ec20c25b517d568627754f6c6462fca19e12c02f2e12/matplotlib-3.10.7-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7a0edb7209e21840e8361e91ea84ea676658aa93edd5f8762793dec77a4a6748", size = 8272389 },+ { url = "https://files.pythonhosted.org/packages/11/0b/1ae80ddafb8652fd8046cb5c8460ecc8d4afccb89e2c6d6bec61e04e1eaf/matplotlib-3.10.7-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:c380371d3c23e0eadf8ebff114445b9f970aff2010198d498d4ab4c3b41eea4f", size = 8128247 },+ { url = "https://files.pythonhosted.org/packages/7d/18/95ae2e242d4a5c98bd6e90e36e128d71cf1c7e39b0874feaed3ef782e789/matplotlib-3.10.7-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d5f256d49fea31f40f166a5e3131235a5d2f4b7f44520b1cf0baf1ce568ccff0", size = 8696996 },+ { url = "https://files.pythonhosted.org/packages/7e/3d/5b559efc800bd05cb2033aa85f7e13af51958136a48327f7c261801ff90a/matplotlib-3.10.7-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:11ae579ac83cdf3fb72573bb89f70e0534de05266728740d478f0f818983c695", size = 9530153 },+ { url = "https://files.pythonhosted.org/packages/88/57/eab4a719fd110312d3c220595d63a3c85ec2a39723f0f4e7fa7e6e3f74ba/matplotlib-3.10.7-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:4c14b6acd16cddc3569a2d515cfdd81c7a68ac5639b76548cfc1a9e48b20eb65", size = 9593093 },+ { url = "https://files.pythonhosted.org/packages/31/3c/80816f027b3a4a28cd2a0a6ef7f89a2db22310e945cd886ec25bfb399221/matplotlib-3.10.7-cp312-cp312-win_amd64.whl", hash = "sha256:0d8c32b7ea6fb80b1aeff5a2ceb3fb9778e2759e899d9beff75584714afcc5ee", size = 8122771 },+ { url = "https://files.pythonhosted.org/packages/de/77/ef1fc78bfe99999b2675435cc52120887191c566b25017d78beaabef7f2d/matplotlib-3.10.7-cp312-cp312-win_arm64.whl", hash = "sha256:5f3f6d315dcc176ba7ca6e74c7768fb7e4cf566c49cb143f6bc257b62e634ed8", size = 7992812 },+ { url = "https://files.pythonhosted.org/packages/02/9c/207547916a02c78f6bdd83448d9b21afbc42f6379ed887ecf610984f3b4e/matplotlib-3.10.7-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:1d9d3713a237970569156cfb4de7533b7c4eacdd61789726f444f96a0d28f57f", size = 8273212 },+ { url = "https://files.pythonhosted.org/packages/bc/d0/b3d3338d467d3fc937f0bb7f256711395cae6f78e22cef0656159950adf0/matplotlib-3.10.7-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:37a1fea41153dd6ee061d21ab69c9cf2cf543160b1b85d89cd3d2e2a7902ca4c", size = 8128713 },+ { url = "https://files.pythonhosted.org/packages/22/ff/6425bf5c20d79aa5b959d1ce9e65f599632345391381c9a104133fe0b171/matplotlib-3.10.7-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b3c4ea4948d93c9c29dc01c0c23eef66f2101bf75158c291b88de6525c55c3d1", size = 8698527 },+ { url = "https://files.pythonhosted.org/packages/d0/7f/ccdca06f4c2e6c7989270ed7829b8679466682f4cfc0f8c9986241c023b6/matplotlib-3.10.7-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:22df30ffaa89f6643206cf13877191c63a50e8f800b038bc39bee9d2d4957632", size = 9529690 },+ { url = "https://files.pythonhosted.org/packages/b8/95/b80fc2c1f269f21ff3d193ca697358e24408c33ce2b106a7438a45407b63/matplotlib-3.10.7-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:b69676845a0a66f9da30e87f48be36734d6748024b525ec4710be40194282c84", size = 9593732 },+ { url = "https://files.pythonhosted.org/packages/e1/b6/23064a96308b9aeceeffa65e96bcde459a2ea4934d311dee20afde7407a0/matplotlib-3.10.7-cp313-cp313-win_amd64.whl", hash = "sha256:744991e0cc863dd669c8dc9136ca4e6e0082be2070b9d793cbd64bec872a6815", size = 8122727 },+ { url = "https://files.pythonhosted.org/packages/b3/a6/2faaf48133b82cf3607759027f82b5c702aa99cdfcefb7f93d6ccf26a424/matplotlib-3.10.7-cp313-cp313-win_arm64.whl", hash = "sha256:fba2974df0bf8ce3c995fa84b79cde38326e0f7b5409e7a3a481c1141340bcf7", size = 7992958 },+ { url = "https://files.pythonhosted.org/packages/4a/f0/b018fed0b599bd48d84c08794cb242227fe3341952da102ee9d9682db574/matplotlib-3.10.7-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:932c55d1fa7af4423422cb6a492a31cbcbdbe68fd1a9a3f545aa5e7a143b5355", size = 8316849 },+ { url = "https://files.pythonhosted.org/packages/b0/b7/bb4f23856197659f275e11a2a164e36e65e9b48ea3e93c4ec25b4f163198/matplotlib-3.10.7-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:5e38c2d581d62ee729a6e144c47a71b3f42fb4187508dbbf4fe71d5612c3433b", size = 8178225 },+ { url = "https://files.pythonhosted.org/packages/62/56/0600609893ff277e6f3ab3c0cef4eafa6e61006c058e84286c467223d4d5/matplotlib-3.10.7-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:786656bb13c237bbcebcd402f65f44dd61ead60ee3deb045af429d889c8dbc67", size = 8711708 },+ { url = "https://files.pythonhosted.org/packages/d8/1a/6bfecb0cafe94d6658f2f1af22c43b76cf7a1c2f0dc34ef84cbb6809617e/matplotlib-3.10.7-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:09d7945a70ea43bf9248f4b6582734c2fe726723204a76eca233f24cffc7ef67", size = 9541409 },+ { url = "https://files.pythonhosted.org/packages/08/50/95122a407d7f2e446fd865e2388a232a23f2b81934960ea802f3171518e4/matplotlib-3.10.7-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:d0b181e9fa8daf1d9f2d4c547527b167cb8838fc587deabca7b5c01f97199e84", size = 9594054 },+ { url = "https://files.pythonhosted.org/packages/13/76/75b194a43b81583478a81e78a07da8d9ca6ddf50dd0a2ccabf258059481d/matplotlib-3.10.7-cp313-cp313t-win_amd64.whl", hash = "sha256:31963603041634ce1a96053047b40961f7a29eb8f9a62e80cc2c0427aa1d22a2", size = 8200100 },+ { url = "https://files.pythonhosted.org/packages/f5/9e/6aefebdc9f8235c12bdeeda44cc0383d89c1e41da2c400caf3ee2073a3ce/matplotlib-3.10.7-cp313-cp313t-win_arm64.whl", hash = "sha256:aebed7b50aa6ac698c90f60f854b47e48cd2252b30510e7a1feddaf5a3f72cbf", size = 8042131 },+ { url = "https://files.pythonhosted.org/packages/0d/4b/e5bc2c321b6a7e3a75638d937d19ea267c34bd5a90e12bee76c4d7c7a0d9/matplotlib-3.10.7-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:d883460c43e8c6b173fef244a2341f7f7c0e9725c7fe68306e8e44ed9c8fb100", size = 8273787 },+ { url = "https://files.pythonhosted.org/packages/86/ad/6efae459c56c2fbc404da154e13e3a6039129f3c942b0152624f1c621f05/matplotlib-3.10.7-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:07124afcf7a6504eafcb8ce94091c5898bbdd351519a1beb5c45f7a38c67e77f", size = 8131348 },+ { url = "https://files.pythonhosted.org/packages/a6/5a/a4284d2958dee4116359cc05d7e19c057e64ece1b4ac986ab0f2f4d52d5a/matplotlib-3.10.7-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c17398b709a6cce3d9fdb1595c33e356d91c098cd9486cb2cc21ea2ea418e715", size = 9533949 },+ { url = "https://files.pythonhosted.org/packages/de/ff/f3781b5057fa3786623ad8976fc9f7b0d02b2f28534751fd5a44240de4cf/matplotlib-3.10.7-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7146d64f561498764561e9cd0ed64fcf582e570fc519e6f521e2d0cfd43365e1", size = 9804247 },+ { url = "https://files.pythonhosted.org/packages/47/5a/993a59facb8444efb0e197bf55f545ee449902dcee86a4dfc580c3b61314/matplotlib-3.10.7-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:90ad854c0a435da3104c01e2c6f0028d7e719b690998a2333d7218db80950722", size = 9595497 },+ { url = "https://files.pythonhosted.org/packages/0d/a5/77c95aaa9bb32c345cbb49626ad8eb15550cba2e6d4c88081a6c2ac7b08d/matplotlib-3.10.7-cp314-cp314-win_amd64.whl", hash = "sha256:4645fc5d9d20ffa3a39361fcdbcec731382763b623b72627806bf251b6388866", size = 8252732 },+ { url = "https://files.pythonhosted.org/packages/74/04/45d269b4268d222390d7817dae77b159651909669a34ee9fdee336db5883/matplotlib-3.10.7-cp314-cp314-win_arm64.whl", hash = "sha256:9257be2f2a03415f9105c486d304a321168e61ad450f6153d77c69504ad764bb", size = 8124240 },+ { url = "https://files.pythonhosted.org/packages/4b/c7/ca01c607bb827158b439208c153d6f14ddb9fb640768f06f7ca3488ae67b/matplotlib-3.10.7-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:1e4bbad66c177a8fdfa53972e5ef8be72a5f27e6a607cec0d8579abd0f3102b1", size = 8316938 },+ { url = "https://files.pythonhosted.org/packages/84/d2/5539e66e9f56d2fdec94bb8436f5e449683b4e199bcc897c44fbe3c99e28/matplotlib-3.10.7-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:d8eb7194b084b12feb19142262165832fc6ee879b945491d1c3d4660748020c4", size = 8178245 },+ { url = "https://files.pythonhosted.org/packages/77/b5/e6ca22901fd3e4fe433a82e583436dd872f6c966fca7e63cf806b40356f8/matplotlib-3.10.7-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b4d41379b05528091f00e1728004f9a8d7191260f3862178b88e8fd770206318", size = 9541411 },+ { url = "https://files.pythonhosted.org/packages/9e/99/a4524db57cad8fee54b7237239a8f8360bfcfa3170d37c9e71c090c0f409/matplotlib-3.10.7-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4a74f79fafb2e177f240579bc83f0b60f82cc47d2f1d260f422a0627207008ca", size = 9803664 },+ { url = "https://files.pythonhosted.org/packages/e6/a5/85e2edf76ea0ad4288d174926d9454ea85f3ce5390cc4e6fab196cbf250b/matplotlib-3.10.7-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:702590829c30aada1e8cef0568ddbffa77ca747b4d6e36c6d173f66e301f89cc", size = 9594066 },+ { url = "https://files.pythonhosted.org/packages/39/69/9684368a314f6d83fe5c5ad2a4121a3a8e03723d2e5c8ea17b66c1bad0e7/matplotlib-3.10.7-cp314-cp314t-win_amd64.whl", hash = "sha256:f79d5de970fc90cd5591f60053aecfce1fcd736e0303d9f0bf86be649fa68fb8", size = 8342832 },+ { url = "https://files.pythonhosted.org/packages/04/5f/e22e08da14bc1a0894184640d47819d2338b792732e20d292bf86e5ab785/matplotlib-3.10.7-cp314-cp314t-win_arm64.whl", hash = "sha256:cb783436e47fcf82064baca52ce748af71725d0352e1d31564cbe9c95df92b9c", size = 8172585 },+ { url = "https://files.pythonhosted.org/packages/58/8f/76d5dc21ac64a49e5498d7f0472c0781dae442dd266a67458baec38288ec/matplotlib-3.10.7-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:15112bcbaef211bd663fa935ec33313b948e214454d949b723998a43357b17b0", size = 8252283 },+ { url = "https://files.pythonhosted.org/packages/27/0d/9c5d4c2317feb31d819e38c9f947c942f42ebd4eb935fc6fd3518a11eaa7/matplotlib-3.10.7-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:d2a959c640cdeecdd2ec3136e8ea0441da59bcaf58d67e9c590740addba2cb68", size = 8116733 },+ { url = "https://files.pythonhosted.org/packages/9a/cc/3fe688ff1355010937713164caacf9ed443675ac48a997bab6ed23b3f7c0/matplotlib-3.10.7-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3886e47f64611046bc1db523a09dd0a0a6bed6081e6f90e13806dd1d1d1b5e91", size = 8693919 },][[package]]@@ -781,31 +926,33 @@ wheels = [[[package]]name = "mediapipe"-version = "0.10.21"+version = "0.10.14"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "absl-py" },{ name = "attrs" },{ name = "flatbuffers" },{ name = "jax", version = "0.4.29", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.13'" },- { name = "jax", version = "0.6.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.13'" },- { name = "jaxlib" },+ { name = "jax", version = "0.7.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.13'" },+ { name = "jaxlib", version = "0.6.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.13'" },+ { name = "jaxlib", version = "0.7.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.13'" },{ name = "matplotlib" },{ name = "numpy" },{ name = "opencv-contrib-python" },{ name = "protobuf" },- { name = "sentencepiece" },{ name = "sounddevice" },]wheels = [- { url = "https://files.pythonhosted.org/packages/6e/37/bd9a3cc4d9b8af54fe40a4858ddd7397e163e079dd67eccec7a948f598a9/mediapipe-0.10.21-cp311-cp311-macosx_11_0_universal2.whl", hash = "sha256:b4946abad54d62812ce4c543187373a4872985fd66cd43fe7437f4b95d53d9ec", size = 49160845 },- { url = "https://files.pythonhosted.org/packages/c5/78/b1bd10f9941eb5853a669d4a72d96010b43c45a8241a90a3c017c543697b/mediapipe-0.10.21-cp311-cp311-macosx_11_0_x86_64.whl", hash = "sha256:fabb8c4703b982dfbc918e939d340202db5d74603f7948c98eeef56166a6cac4", size = 49069767 },- { url = "https://files.pythonhosted.org/packages/ad/83/56f760fecdc60de84c529d6c05c9dfc7d972617c6632bd254d5e021e5b16/mediapipe-0.10.21-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:05dc4a9e593655a79558d05d6227d31018c2537a4bd3362b51e230cf22aecfe3", size = 35622638 },- { url = "https://files.pythonhosted.org/packages/c5/1f/0b2bc80d76d996801113c800e386f7b33aeaec663e2e8ee83695c0dfbde8/mediapipe-0.10.21-cp311-cp311-win_amd64.whl", hash = "sha256:c9ad3adcf2b606f0ebde89afce29da8852f1c93f4fcb7f8dc93d72313625aa6d", size = 50964784 },- { url = "https://files.pythonhosted.org/packages/f1/df/b1912b0d4e88c70a969258b201737c92ea268a90650c470ee842833a6690/mediapipe-0.10.21-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:a65508f8c0e28a73f519c8a717f95949b9d5b2fb3bf4a632b181cdb71224d62e", size = 49176855 },- { url = "https://files.pythonhosted.org/packages/89/34/f490f2e1614c021679fe757b08fdedd6100fd18f21111532af8864d006fe/mediapipe-0.10.21-cp312-cp312-macosx_11_0_x86_64.whl", hash = "sha256:96bf0dafa9851c74b1f930090193f23c257ccf4bb1bdebbd2ca3a02397011c0e", size = 49080132 },- { url = "https://files.pythonhosted.org/packages/9f/99/5da7ae7f7e25847383bc2fe5a9adc7ce150dd371682f486c0666b407cad7/mediapipe-0.10.21-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:956eb1ebc275c629e61b085b2cab89c3a5b9e93bad1bb107348d98dafb5a4bb5", size = 35627340 },- { url = "https://files.pythonhosted.org/packages/b7/79/b77808f8195f229ef0c15875540dfdd36724748a4b3de53d993f23336839/mediapipe-0.10.21-cp312-cp312-win_amd64.whl", hash = "sha256:d07b5e69308411161286ea4e48be2ea3e9ab62745143fcb0cb4acced0517e341", size = 50967082 },+ { url = "https://files.pythonhosted.org/packages/31/fb/09fde872bd3c92720860adc25ffee605f18d3a5165320ae8cd2d71da7003/mediapipe-0.10.14-cp311-cp311-macosx_11_0_universal2.whl", hash = "sha256:4737fce6107bd21e420a6b2aad2c721fbc4cc318f1258b68f0665f10225bde1d", size = 50187308 },+ { url = "https://files.pythonhosted.org/packages/b0/17/8e0ca5c867fe9b9943945b3a0033158fd89ae031c0a2e7dd3dd9101b2f3f/mediapipe-0.10.14-cp311-cp311-macosx_11_0_x86_64.whl", hash = "sha256:e5f8fdf512da074c225219f4e09723f612cdd3449c4793693fd360dc817c9261", size = 50098859 },+ { url = "https://files.pythonhosted.org/packages/74/25/ee5679b8ddc58e97d417cfbc1c2b56346ea085a457aa61901ad225cc80bf/mediapipe-0.10.14-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1061d499d341e7f11dd7f18d5bee747e862db8ef47665ff777323282225d4315", size = 33017085 },+ { url = "https://files.pythonhosted.org/packages/2f/ee/2e9e730dc4d98c8a9541b57bad173bebddf0e4c78f179acc100248c58066/mediapipe-0.10.14-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a807328339e7356fda0bb14df12fedbf1d33bdf81649c5f8666b0026b1cc30b4", size = 35664771 },+ { url = "https://files.pythonhosted.org/packages/c1/0f/4dc0802131756a9fe4d46d2824352014b85a75baca386cb9e43057f39f15/mediapipe-0.10.14-cp311-cp311-win_amd64.whl", hash = "sha256:1b7687d3b63590bcc601ad195b923b80a1b2d6be5cdf43711edc661cecd3dd47", size = 50834141 },+ { url = "https://files.pythonhosted.org/packages/2d/df/be410905b9757de4b00891dd34236d96e6db150b624f28cc27cd90c74564/mediapipe-0.10.14-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:aa2298c1886716cde6bd7ce96aba1505d67d52edaba856f6c2e1ab905de52b0d", size = 50203567 },+ { url = "https://files.pythonhosted.org/packages/32/40/b6a2a50593e8753bf12e2dbfd130dee588eb2fc50ce74939cf6485af2756/mediapipe-0.10.14-cp312-cp312-macosx_11_0_x86_64.whl", hash = "sha256:5c97e32cbb9e9d72b78a33f011257b3cdb55b60fef70a8a864c5d2a4b6652425", size = 50117879 },+ { url = "https://files.pythonhosted.org/packages/f4/da/dfed8db260b3fbe4e24ac17dda32c55787643a656d8d4e78c55bc847efa8/mediapipe-0.10.14-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3e30ed2f39f925924de58adeec6a8e61ba6beb6959325dc0d8a1aa487a74377b", size = 33015939 },+ { url = "https://files.pythonhosted.org/packages/11/73/07c6dcbb322f86e2b8526e0073456dbdd2813d5351f772f882123c985fda/mediapipe-0.10.14-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9b1e72d754cd9e1b4b88d80ec9ead2f1cbe8424b7f883d3bda53341b982a9f8b", size = 35665742 },+ { url = "https://files.pythonhosted.org/packages/f0/26/d228fe6e9f2060dde7f7db738968bcd603e9340f064351655b5b2652a664/mediapipe-0.10.14-cp312-cp312-win_amd64.whl", hash = "sha256:ebb8350e860c8e00b7c84d71e15090fc3ac4cc9d4249892f85fb35011590e372", size = 50837898 },][[package]]@@ -877,41 +1024,31 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/7f/3c/541c4b30815ab90ebfbb51df15d0b4254f2f9f1e2b4907ab229300d5e6f2/ml_dtypes-0.5.3-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5ab039ffb40f3dc0aeeeba84fd6c3452781b5e15bef72e2d10bcb33e4bbffc39", size = 5285284 },]-[[package]]-name = "nuitka"-version = "2.7.12"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "ordered-set" },- { name = "zstandard" },-]-sdist = { url = "https://files.pythonhosted.org/packages/9b/9c/f51b7c7dae304f2381b5af20a5ac6ccb56f0a773d16470b269146f5909db/Nuitka-2.7.12.tar.gz", hash = "sha256:ee28e5699005904e83250ad1b3192cf2c5b46bebbf4ae12f6fc5efa4a0368c16", size = 3887702 }-[[package]]name = "numba"-version = "0.61.2"+version = "0.62.1"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "llvmlite" },{ name = "numpy" },]-sdist = { url = "https://files.pythonhosted.org/packages/1c/a0/e21f57604304aa03ebb8e098429222722ad99176a4f979d34af1d1ee80da/numba-0.61.2.tar.gz", hash = "sha256:8750ee147940a6637b80ecf7f95062185ad8726c8c28a2295b8ec1160a196f7d", size = 2820615 }+sdist = { url = "https://files.pythonhosted.org/packages/a3/20/33dbdbfe60e5fd8e3dbfde299d106279a33d9f8308346022316781368591/numba-0.62.1.tar.gz", hash = "sha256:7b774242aa890e34c21200a1fc62e5b5757d5286267e71103257f4e2af0d5161", size = 2749817 }wheels = [- { url = "https://files.pythonhosted.org/packages/3f/97/c99d1056aed767503c228f7099dc11c402906b42a4757fec2819329abb98/numba-0.61.2-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:efd3db391df53aaa5cfbee189b6c910a5b471488749fd6606c3f33fc984c2ae2", size = 2775825 },- { url = "https://files.pythonhosted.org/packages/95/9e/63c549f37136e892f006260c3e2613d09d5120672378191f2dc387ba65a2/numba-0.61.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:49c980e4171948ffebf6b9a2520ea81feed113c1f4890747ba7f59e74be84b1b", size = 2778695 },- { url = "https://files.pythonhosted.org/packages/97/c8/8740616c8436c86c1b9a62e72cb891177d2c34c2d24ddcde4c390371bf4c/numba-0.61.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3945615cd73c2c7eba2a85ccc9c1730c21cd3958bfcf5a44302abae0fb07bb60", size = 3829227 },- { url = "https://files.pythonhosted.org/packages/fc/06/66e99ae06507c31d15ff3ecd1f108f2f59e18b6e08662cd5f8a5853fbd18/numba-0.61.2-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:bbfdf4eca202cebade0b7d43896978e146f39398909a42941c9303f82f403a18", size = 3523422 },- { url = "https://files.pythonhosted.org/packages/0f/a4/2b309a6a9f6d4d8cfba583401c7c2f9ff887adb5d54d8e2e130274c0973f/numba-0.61.2-cp311-cp311-win_amd64.whl", hash = "sha256:76bcec9f46259cedf888041b9886e257ae101c6268261b19fda8cfbc52bec9d1", size = 2831505 },- { url = "https://files.pythonhosted.org/packages/b4/a0/c6b7b9c615cfa3b98c4c63f4316e3f6b3bbe2387740277006551784218cd/numba-0.61.2-cp312-cp312-macosx_10_14_x86_64.whl", hash = "sha256:34fba9406078bac7ab052efbf0d13939426c753ad72946baaa5bf9ae0ebb8dd2", size = 2776626 },- { url = "https://files.pythonhosted.org/packages/92/4a/fe4e3c2ecad72d88f5f8cd04e7f7cff49e718398a2fac02d2947480a00ca/numba-0.61.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4ddce10009bc097b080fc96876d14c051cc0c7679e99de3e0af59014dab7dfe8", size = 2779287 },- { url = "https://files.pythonhosted.org/packages/9a/2d/e518df036feab381c23a624dac47f8445ac55686ec7f11083655eb707da3/numba-0.61.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5b1bb509d01f23d70325d3a5a0e237cbc9544dd50e50588bc581ba860c213546", size = 3885928 },- { url = "https://files.pythonhosted.org/packages/10/0f/23cced68ead67b75d77cfcca3df4991d1855c897ee0ff3fe25a56ed82108/numba-0.61.2-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:48a53a3de8f8793526cbe330f2a39fe9a6638efcbf11bd63f3d2f9757ae345cd", size = 3577115 },- { url = "https://files.pythonhosted.org/packages/68/1d/ddb3e704c5a8fb90142bf9dc195c27db02a08a99f037395503bfbc1d14b3/numba-0.61.2-cp312-cp312-win_amd64.whl", hash = "sha256:97cf4f12c728cf77c9c1d7c23707e4d8fb4632b46275f8f3397de33e5877af18", size = 2831929 },- { url = "https://files.pythonhosted.org/packages/0b/f3/0fe4c1b1f2569e8a18ad90c159298d862f96c3964392a20d74fc628aee44/numba-0.61.2-cp313-cp313-macosx_10_14_x86_64.whl", hash = "sha256:3a10a8fc9afac40b1eac55717cece1b8b1ac0b946f5065c89e00bde646b5b154", size = 2771785 },- { url = "https://files.pythonhosted.org/packages/e9/71/91b277d712e46bd5059f8a5866862ed1116091a7cb03bd2704ba8ebe015f/numba-0.61.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:7d3bcada3c9afba3bed413fba45845f2fb9cd0d2b27dd58a1be90257e293d140", size = 2773289 },- { url = "https://files.pythonhosted.org/packages/0d/e0/5ea04e7ad2c39288c0f0f9e8d47638ad70f28e275d092733b5817cf243c9/numba-0.61.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:bdbca73ad81fa196bd53dc12e3aaf1564ae036e0c125f237c7644fe64a4928ab", size = 3893918 },- { url = "https://files.pythonhosted.org/packages/17/58/064f4dcb7d7e9412f16ecf80ed753f92297e39f399c905389688cf950b81/numba-0.61.2-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:5f154aaea625fb32cfbe3b80c5456d514d416fcdf79733dd69c0df3a11348e9e", size = 3584056 },- { url = "https://files.pythonhosted.org/packages/af/a4/6d3a0f2d3989e62a18749e1e9913d5fa4910bbb3e3311a035baea6caf26d/numba-0.61.2-cp313-cp313-win_amd64.whl", hash = "sha256:59321215e2e0ac5fa928a8020ab00b8e57cda8a97384963ac0dfa4d4e6aa54e7", size = 2831846 },+ { url = "https://files.pythonhosted.org/packages/dd/5f/8b3491dd849474f55e33c16ef55678ace1455c490555337899c35826836c/numba-0.62.1-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:f43e24b057714e480fe44bc6031de499e7cf8150c63eb461192caa6cc8530bc8", size = 2684279 },+ { url = "https://files.pythonhosted.org/packages/bf/18/71969149bfeb65a629e652b752b80167fe8a6a6f6e084f1f2060801f7f31/numba-0.62.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:57cbddc53b9ee02830b828a8428757f5c218831ccc96490a314ef569d8342b7b", size = 2687330 },+ { url = "https://files.pythonhosted.org/packages/0e/7d/403be3fecae33088027bc8a95dc80a2fda1e3beff3e0e5fc4374ada3afbe/numba-0.62.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:604059730c637c7885386521bb1b0ddcbc91fd56131a6dcc54163d6f1804c872", size = 3739727 },+ { url = "https://files.pythonhosted.org/packages/e0/c3/3d910d08b659a6d4c62ab3cd8cd93c4d8b7709f55afa0d79a87413027ff6/numba-0.62.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d6c540880170bee817011757dc9049dba5a29db0c09b4d2349295991fe3ee55f", size = 3445490 },+ { url = "https://files.pythonhosted.org/packages/5b/82/9d425c2f20d9f0a37f7cb955945a553a00fa06a2b025856c3550227c5543/numba-0.62.1-cp311-cp311-win_amd64.whl", hash = "sha256:03de6d691d6b6e2b76660ba0f38f37b81ece8b2cc524a62f2a0cfae2bfb6f9da", size = 2745550 },+ { url = "https://files.pythonhosted.org/packages/5e/fa/30fa6873e9f821c0ae755915a3ca444e6ff8d6a7b6860b669a3d33377ac7/numba-0.62.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:1b743b32f8fa5fff22e19c2e906db2f0a340782caf024477b97801b918cf0494", size = 2685346 },+ { url = "https://files.pythonhosted.org/packages/a9/d5/504ce8dc46e0dba2790c77e6b878ee65b60fe3e7d6d0006483ef6fde5a97/numba-0.62.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:90fa21b0142bcf08ad8e32a97d25d0b84b1e921bc9423f8dda07d3652860eef6", size = 2688139 },+ { url = "https://files.pythonhosted.org/packages/50/5f/6a802741176c93f2ebe97ad90751894c7b0c922b52ba99a4395e79492205/numba-0.62.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:6ef84d0ac19f1bf80431347b6f4ce3c39b7ec13f48f233a48c01e2ec06ecbc59", size = 3796453 },+ { url = "https://files.pythonhosted.org/packages/7e/df/efd21527d25150c4544eccc9d0b7260a5dec4b7e98b5a581990e05a133c0/numba-0.62.1-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9315cc5e441300e0ca07c828a627d92a6802bcbf27c5487f31ae73783c58da53", size = 3496451 },+ { url = "https://files.pythonhosted.org/packages/80/44/79bfdab12a02796bf4f1841630355c82b5a69933b1d50eb15c7fa37dabe8/numba-0.62.1-cp312-cp312-win_amd64.whl", hash = "sha256:44e3aa6228039992f058f5ebfcfd372c83798e9464297bdad8cc79febcf7891e", size = 2745552 },+ { url = "https://files.pythonhosted.org/packages/22/76/501ea2c07c089ef1386868f33dff2978f43f51b854e34397b20fc55e0a58/numba-0.62.1-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:b72489ba8411cc9fdcaa2458d8f7677751e94f0109eeb53e5becfdc818c64afb", size = 2685766 },+ { url = "https://files.pythonhosted.org/packages/80/68/444986ed95350c0611d5c7b46828411c222ce41a0c76707c36425d27ce29/numba-0.62.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:44a1412095534a26fb5da2717bc755b57da5f3053965128fe3dc286652cc6a92", size = 2688741 },+ { url = "https://files.pythonhosted.org/packages/78/7e/bf2e3634993d57f95305c7cee4c9c6cb3c9c78404ee7b49569a0dfecfe33/numba-0.62.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8c9460b9e936c5bd2f0570e20a0a5909ee6e8b694fd958b210e3bde3a6dba2d7", size = 3804576 },+ { url = "https://files.pythonhosted.org/packages/e8/b6/8a1723fff71f63bbb1354bdc60a1513a068acc0f5322f58da6f022d20247/numba-0.62.1-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:728f91a874192df22d74e3fd42c12900b7ce7190b1aad3574c6c61b08313e4c5", size = 3503367 },+ { url = "https://files.pythonhosted.org/packages/9c/ec/9d414e7a80d6d1dc4af0e07c6bfe293ce0b04ea4d0ed6c45dad9bd6e72eb/numba-0.62.1-cp313-cp313-win_amd64.whl", hash = "sha256:bbf3f88b461514287df66bc8d0307e949b09f2b6f67da92265094e8fa1282dd8", size = 2745529 },][[package]]@@ -940,15 +1077,15 @@ wheels = [[[package]]name = "numpydantic"-version = "1.6.11"+version = "1.7.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "numpy" },{ name = "pydantic" },]-sdist = { url = "https://files.pythonhosted.org/packages/62/c2/7be9f9b092f62a4d13babb010f145b3fe8e16bbf799ec16dce10de3e192a/numpydantic-1.6.11.tar.gz", hash = "sha256:d8e0d29d4a39f6ac190376eb96de6c8a5e29277db2c3ecc3aab8e85384ebfb47", size = 79529 }+sdist = { url = "https://files.pythonhosted.org/packages/59/ba/6bf5e0a7cc3fbfbb02a7824926cad73c58df374322eb7728b378023a76dc/numpydantic-1.7.0.tar.gz", hash = "sha256:268285bee026d9dfdf23efeee13f60c3b75d47de2ffdf2e58b4f0c17a6824e3b", size = 80412 }wheels = [- { url = "https://files.pythonhosted.org/packages/e9/cc/15fb976ec779cb154c06e402f2abe9bafbef100592c3492c93e467e8c2d9/numpydantic-1.6.11-py3-none-any.whl", hash = "sha256:491b500b8210d5163af8e15bb39142d96caf91717c43c88d29366fa12c05ec46", size = 86052 },+ { url = "https://files.pythonhosted.org/packages/21/e0/42f0ea229a8b5ada24a1eae4f5522b80ab65b4083f5cea4c7372bc894af3/numpydantic-1.7.0-py3-none-any.whl", hash = "sha256:81314ed00423efa954a711a48003dba5382156e899f677f405ce043f5296b090", size = 86734 },][[package]]@@ -977,15 +1114,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/23/cd/066e86230ae37ed0be70aae89aabf03ca8d9f39c8aea0dec8029455b5540/opt_einsum-3.4.0-py3-none-any.whl", hash = "sha256:69bb92469f86a1565195ece4ac0323943e83477171b91d24c35afe028a90d7cd", size = 71932 },]-[[package]]-name = "ordered-set"-version = "4.1.0"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/4c/ca/bfac8bc689799bcca4157e0e0ced07e70ce125193fc2e166d2e685b7e2fe/ordered-set-4.1.0.tar.gz", hash = "sha256:694a8e44c87657c59292ede72891eb91d34131f6531463aab3009191c77364a8", size = 12826 }-wheels = [- { url = "https://files.pythonhosted.org/packages/33/55/af02708f230eb77084a299d7b08175cff006dea4f2721074b92cdb0296c0/ordered_set-4.1.0-py3-none-any.whl", hash = "sha256:046e1132c71fcf3330438a539928932caf51ddbc582496833e23de611de14562", size = 7634 },-]-[[package]]name = "packaging"version = "25.0"@@ -997,7 +1125,7 @@ wheels = [[[package]]name = "pandas"-version = "2.1.4"+version = "2.3.3"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "numpy" },@@ -1005,20 +1133,48 @@ dependencies = [{ name = "pytz" },{ name = "tzdata" },]-sdist = { url = "https://files.pythonhosted.org/packages/6f/41/eb562668eaf93790762f600536b28c97b45803cba9253cd8e436cda96aef/pandas-2.1.4.tar.gz", hash = "sha256:fcb68203c833cc735321512e13861358079a96c174a61f5116a1de89c58c0ef7", size = 4274800 }-wheels = [- { url = "https://files.pythonhosted.org/packages/6e/48/892f8835774dd5a84fff3e890f31d1da3dfba2ee1571ac739589b14af66d/pandas-2.1.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:b7d852d16c270e4331f6f59b3e9aa23f935f5c4b0ed2d0bc77637a8890a5d092", size = 11621200 },- { url = "https://files.pythonhosted.org/packages/3e/89/cbca600319463a91ae6a46e537d548900ddf2114df66c902344c4fe6bb4c/pandas-2.1.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:bd7d5f2f54f78164b3d7a40f33bf79a74cdee72c31affec86bfcabe7e0789821", size = 10780136 },- { url = "https://files.pythonhosted.org/packages/12/3c/f21ca75cc511c606b8b4de2a03927f7c181ac70aa3eb8d563a93a54b1563/pandas-2.1.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0aa6e92e639da0d6e2017d9ccff563222f4eb31e4b2c3cf32a2a392fc3103c0d", size = 14822123 },- { url = "https://files.pythonhosted.org/packages/f8/8c/9ad173c5cd2c7178c84075c02ec37b5d1d53fb1d015f51ea3e623ea9c31c/pandas-2.1.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d797591b6846b9db79e65dc2d0d48e61f7db8d10b2a9480b4e3faaddc421a171", size = 12234407 },- { url = "https://files.pythonhosted.org/packages/ff/e9/4950bc4502c187df621c0a48f7d10bd61ae41663ce97bc489b5d94cc02c6/pandas-2.1.4-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:d2d3e7b00f703aea3945995ee63375c61b2e6aa5aa7871c5d622870e5e137623", size = 13067655 },- { url = "https://files.pythonhosted.org/packages/11/17/fb1a34f3e73debbc2fd15a01ea17eaab3717943d08463ff4979a4f024b3f/pandas-2.1.4-cp311-cp311-win_amd64.whl", hash = "sha256:dc9bf7ade01143cddc0074aa6995edd05323974e6e40d9dbde081021ded8510e", size = 10614628 },- { url = "https://files.pythonhosted.org/packages/f5/16/64109832ed426d5c3e9f6b791e64a2b78d785823657640afb8f416ed1dc9/pandas-2.1.4-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:482d5076e1791777e1571f2e2d789e940dedd927325cc3cb6d0800c6304082f6", size = 11357488 },- { url = "https://files.pythonhosted.org/packages/0b/e0/8d97c7ecd73624f4cd5755578990b3cfbc6bbe350b8e017ede3580173a6f/pandas-2.1.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8a706cfe7955c4ca59af8c7a0517370eafbd98593155b48f10f9811da440248b", size = 10613199 },- { url = "https://files.pythonhosted.org/packages/54/be/98b894bef9acfc310de70fc03524473a9695981e1e87c7afa56ada08f016/pandas-2.1.4-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b0513a132a15977b4a5b89aabd304647919bc2169eac4c8536afb29c07c23540", size = 14288250 },- { url = "https://files.pythonhosted.org/packages/5b/5f/076b1ce74f80df0a9db244d30e30c4d4dee45342cbfa5f3e01f64cadf663/pandas-2.1.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e9f17f2b6fc076b2a0078862547595d66244db0f41bf79fc5f64a5c4d635bead", size = 11673138 },- { url = "https://files.pythonhosted.org/packages/cc/a8/13dced3276ea4514909a80c8dd08b43ab23007b4949701e3d7ae2a8ccd2d/pandas-2.1.4-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:45d63d2a9b1b37fa6c84a68ba2422dc9ed018bdaa668c7f47566a01188ceeec1", size = 12389903 },- { url = "https://files.pythonhosted.org/packages/ae/d9/3741b344f57484b423cd22194025a8489992ad9962196a62721ef9980045/pandas-2.1.4-cp312-cp312-win_amd64.whl", hash = "sha256:f69b0c9bb174a2342818d3e2778584e18c740d56857fc5cdb944ec8bbe4082cf", size = 10498689 },+sdist = { url = "https://files.pythonhosted.org/packages/33/01/d40b85317f86cf08d853a4f495195c73815fdf205eef3993821720274518/pandas-2.3.3.tar.gz", hash = "sha256:e05e1af93b977f7eafa636d043f9f94c7ee3ac81af99c13508215942e64c993b", size = 4495223 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/c1/fa/7ac648108144a095b4fb6aa3de1954689f7af60a14cf25583f4960ecb878/pandas-2.3.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:602b8615ebcc4a0c1751e71840428ddebeb142ec02c786e8ad6b1ce3c8dec523", size = 11578790 },+ { url = "https://files.pythonhosted.org/packages/9b/35/74442388c6cf008882d4d4bdfc4109be87e9b8b7ccd097ad1e7f006e2e95/pandas-2.3.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:8fe25fc7b623b0ef6b5009149627e34d2a4657e880948ec3c840e9402e5c1b45", size = 10833831 },+ { url = "https://files.pythonhosted.org/packages/fe/e4/de154cbfeee13383ad58d23017da99390b91d73f8c11856f2095e813201b/pandas-2.3.3-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b468d3dad6ff947df92dcb32ede5b7bd41a9b3cceef0a30ed925f6d01fb8fa66", size = 12199267 },+ { url = "https://files.pythonhosted.org/packages/bf/c9/63f8d545568d9ab91476b1818b4741f521646cbdd151c6efebf40d6de6f7/pandas-2.3.3-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b98560e98cb334799c0b07ca7967ac361a47326e9b4e5a7dfb5ab2b1c9d35a1b", size = 12789281 },+ { url = "https://files.pythonhosted.org/packages/f2/00/a5ac8c7a0e67fd1a6059e40aa08fa1c52cc00709077d2300e210c3ce0322/pandas-2.3.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1d37b5848ba49824e5c30bedb9c830ab9b7751fd049bc7914533e01c65f79791", size = 13240453 },+ { url = "https://files.pythonhosted.org/packages/27/4d/5c23a5bc7bd209231618dd9e606ce076272c9bc4f12023a70e03a86b4067/pandas-2.3.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:db4301b2d1f926ae677a751eb2bd0e8c5f5319c9cb3f88b0becbbb0b07b34151", size = 13890361 },+ { url = "https://files.pythonhosted.org/packages/8e/59/712db1d7040520de7a4965df15b774348980e6df45c129b8c64d0dbe74ef/pandas-2.3.3-cp311-cp311-win_amd64.whl", hash = "sha256:f086f6fe114e19d92014a1966f43a3e62285109afe874f067f5abbdcbb10e59c", size = 11348702 },+ { url = "https://files.pythonhosted.org/packages/9c/fb/231d89e8637c808b997d172b18e9d4a4bc7bf31296196c260526055d1ea0/pandas-2.3.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6d21f6d74eb1725c2efaa71a2bfc661a0689579b58e9c0ca58a739ff0b002b53", size = 11597846 },+ { url = "https://files.pythonhosted.org/packages/5c/bd/bf8064d9cfa214294356c2d6702b716d3cf3bb24be59287a6a21e24cae6b/pandas-2.3.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3fd2f887589c7aa868e02632612ba39acb0b8948faf5cc58f0850e165bd46f35", size = 10729618 },+ { url = "https://files.pythonhosted.org/packages/57/56/cf2dbe1a3f5271370669475ead12ce77c61726ffd19a35546e31aa8edf4e/pandas-2.3.3-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ecaf1e12bdc03c86ad4a7ea848d66c685cb6851d807a26aa245ca3d2017a1908", size = 11737212 },+ { url = "https://files.pythonhosted.org/packages/e5/63/cd7d615331b328e287d8233ba9fdf191a9c2d11b6af0c7a59cfcec23de68/pandas-2.3.3-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b3d11d2fda7eb164ef27ffc14b4fcab16a80e1ce67e9f57e19ec0afaf715ba89", size = 12362693 },+ { url = "https://files.pythonhosted.org/packages/a6/de/8b1895b107277d52f2b42d3a6806e69cfef0d5cf1d0ba343470b9d8e0a04/pandas-2.3.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a68e15f780eddf2b07d242e17a04aa187a7ee12b40b930bfdd78070556550e98", size = 12771002 },+ { url = "https://files.pythonhosted.org/packages/87/21/84072af3187a677c5893b170ba2c8fbe450a6ff911234916da889b698220/pandas-2.3.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:371a4ab48e950033bcf52b6527eccb564f52dc826c02afd9a1bc0ab731bba084", size = 13450971 },+ { url = "https://files.pythonhosted.org/packages/86/41/585a168330ff063014880a80d744219dbf1dd7a1c706e75ab3425a987384/pandas-2.3.3-cp312-cp312-win_amd64.whl", hash = "sha256:a16dcec078a01eeef8ee61bf64074b4e524a2a3f4b3be9326420cabe59c4778b", size = 10992722 },+ { url = "https://files.pythonhosted.org/packages/cd/4b/18b035ee18f97c1040d94debd8f2e737000ad70ccc8f5513f4eefad75f4b/pandas-2.3.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:56851a737e3470de7fa88e6131f41281ed440d29a9268dcbf0002da5ac366713", size = 11544671 },+ { url = "https://files.pythonhosted.org/packages/31/94/72fac03573102779920099bcac1c3b05975c2cb5f01eac609faf34bed1ca/pandas-2.3.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:bdcd9d1167f4885211e401b3036c0c8d9e274eee67ea8d0758a256d60704cfe8", size = 10680807 },+ { url = "https://files.pythonhosted.org/packages/16/87/9472cf4a487d848476865321de18cc8c920b8cab98453ab79dbbc98db63a/pandas-2.3.3-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e32e7cc9af0f1cc15548288a51a3b681cc2a219faa838e995f7dc53dbab1062d", size = 11709872 },+ { url = "https://files.pythonhosted.org/packages/15/07/284f757f63f8a8d69ed4472bfd85122bd086e637bf4ed09de572d575a693/pandas-2.3.3-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:318d77e0e42a628c04dc56bcef4b40de67918f7041c2b061af1da41dcff670ac", size = 12306371 },+ { url = "https://files.pythonhosted.org/packages/33/81/a3afc88fca4aa925804a27d2676d22dcd2031c2ebe08aabd0ae55b9ff282/pandas-2.3.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4e0a175408804d566144e170d0476b15d78458795bb18f1304fb94160cabf40c", size = 12765333 },+ { url = "https://files.pythonhosted.org/packages/8d/0f/b4d4ae743a83742f1153464cf1a8ecfafc3ac59722a0b5c8602310cb7158/pandas-2.3.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:93c2d9ab0fc11822b5eece72ec9587e172f63cff87c00b062f6e37448ced4493", size = 13418120 },+ { url = "https://files.pythonhosted.org/packages/4f/c7/e54682c96a895d0c808453269e0b5928a07a127a15704fedb643e9b0a4c8/pandas-2.3.3-cp313-cp313-win_amd64.whl", hash = "sha256:f8bfc0e12dc78f777f323f55c58649591b2cd0c43534e8355c51d3fede5f4dee", size = 10993991 },+ { url = "https://files.pythonhosted.org/packages/f9/ca/3f8d4f49740799189e1395812f3bf23b5e8fc7c190827d55a610da72ce55/pandas-2.3.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:75ea25f9529fdec2d2e93a42c523962261e567d250b0013b16210e1d40d7c2e5", size = 12048227 },+ { url = "https://files.pythonhosted.org/packages/0e/5a/f43efec3e8c0cc92c4663ccad372dbdff72b60bdb56b2749f04aa1d07d7e/pandas-2.3.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:74ecdf1d301e812db96a465a525952f4dde225fdb6d8e5a521d47e1f42041e21", size = 11411056 },+ { url = "https://files.pythonhosted.org/packages/46/b1/85331edfc591208c9d1a63a06baa67b21d332e63b7a591a5ba42a10bb507/pandas-2.3.3-cp313-cp313t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6435cb949cb34ec11cc9860246ccb2fdc9ecd742c12d3304989017d53f039a78", size = 11645189 },+ { url = "https://files.pythonhosted.org/packages/44/23/78d645adc35d94d1ac4f2a3c4112ab6f5b8999f4898b8cdf01252f8df4a9/pandas-2.3.3-cp313-cp313t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:900f47d8f20860de523a1ac881c4c36d65efcb2eb850e6948140fa781736e110", size = 12121912 },+ { url = "https://files.pythonhosted.org/packages/53/da/d10013df5e6aaef6b425aa0c32e1fc1f3e431e4bcabd420517dceadce354/pandas-2.3.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:a45c765238e2ed7d7c608fc5bc4a6f88b642f2f01e70c0c23d2224dd21829d86", size = 12712160 },+ { url = "https://files.pythonhosted.org/packages/bd/17/e756653095a083d8a37cbd816cb87148debcfcd920129b25f99dd8d04271/pandas-2.3.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:c4fc4c21971a1a9f4bdb4c73978c7f7256caa3e62b323f70d6cb80db583350bc", size = 13199233 },+ { url = "https://files.pythonhosted.org/packages/04/fd/74903979833db8390b73b3a8a7d30d146d710bd32703724dd9083950386f/pandas-2.3.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:ee15f284898e7b246df8087fc82b87b01686f98ee67d85a17b7ab44143a3a9a0", size = 11540635 },+ { url = "https://files.pythonhosted.org/packages/21/00/266d6b357ad5e6d3ad55093a7e8efc7dd245f5a842b584db9f30b0f0a287/pandas-2.3.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1611aedd912e1ff81ff41c745822980c49ce4a7907537be8692c8dbc31924593", size = 10759079 },+ { url = "https://files.pythonhosted.org/packages/ca/05/d01ef80a7a3a12b2f8bbf16daba1e17c98a2f039cbc8e2f77a2c5a63d382/pandas-2.3.3-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6d2cefc361461662ac48810cb14365a365ce864afe85ef1f447ff5a1e99ea81c", size = 11814049 },+ { url = "https://files.pythonhosted.org/packages/15/b2/0e62f78c0c5ba7e3d2c5945a82456f4fac76c480940f805e0b97fcbc2f65/pandas-2.3.3-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ee67acbbf05014ea6c763beb097e03cd629961c8a632075eeb34247120abcb4b", size = 12332638 },+ { url = "https://files.pythonhosted.org/packages/c5/33/dd70400631b62b9b29c3c93d2feee1d0964dc2bae2e5ad7a6c73a7f25325/pandas-2.3.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c46467899aaa4da076d5abc11084634e2d197e9460643dd455ac3db5856b24d6", size = 12886834 },+ { url = "https://files.pythonhosted.org/packages/d3/18/b5d48f55821228d0d2692b34fd5034bb185e854bdb592e9c640f6290e012/pandas-2.3.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:6253c72c6a1d990a410bc7de641d34053364ef8bcd3126f7e7450125887dffe3", size = 13409925 },+ { url = "https://files.pythonhosted.org/packages/a6/3d/124ac75fcd0ecc09b8fdccb0246ef65e35b012030defb0e0eba2cbbbe948/pandas-2.3.3-cp314-cp314-win_amd64.whl", hash = "sha256:1b07204a219b3b7350abaae088f451860223a52cfb8a6c53358e7948735158e5", size = 11109071 },+ { url = "https://files.pythonhosted.org/packages/89/9c/0e21c895c38a157e0faa1fb64587a9226d6dd46452cac4532d80c3c4a244/pandas-2.3.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:2462b1a365b6109d275250baaae7b760fd25c726aaca0054649286bcfbb3e8ec", size = 12048504 },+ { url = "https://files.pythonhosted.org/packages/d7/82/b69a1c95df796858777b68fbe6a81d37443a33319761d7c652ce77797475/pandas-2.3.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0242fe9a49aa8b4d78a4fa03acb397a58833ef6199e9aa40a95f027bb3a1b6e7", size = 11410702 },+ { url = "https://files.pythonhosted.org/packages/f9/88/702bde3ba0a94b8c73a0181e05144b10f13f29ebfc2150c3a79062a8195d/pandas-2.3.3-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a21d830e78df0a515db2b3d2f5570610f5e6bd2e27749770e8bb7b524b89b450", size = 11634535 },+ { url = "https://files.pythonhosted.org/packages/a4/1e/1bac1a839d12e6a82ec6cb40cda2edde64a2013a66963293696bbf31fbbb/pandas-2.3.3-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2e3ebdb170b5ef78f19bfb71b0dc5dc58775032361fa188e814959b74d726dd5", size = 12121582 },+ { url = "https://files.pythonhosted.org/packages/44/91/483de934193e12a3b1d6ae7c8645d083ff88dec75f46e827562f1e4b4da6/pandas-2.3.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:d051c0e065b94b7a3cea50eb1ec32e912cd96dba41647eb24104b6c6c14c5788", size = 12699963 },+ { url = "https://files.pythonhosted.org/packages/70/44/5191d2e4026f86a2a109053e194d3ba7a31a2d10a9c2348368c63ed4e85a/pandas-2.3.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:3869faf4bd07b3b66a9f462417d0ca3a9df29a9f6abd5d0d0dbab15dac7abe87", size = 13202175 },][[package]]@@ -1032,37 +1188,89 @@ wheels = [[[package]]name = "pillow"-version = "10.0.1"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/64/9e/7e638579cce7dc346632f020914141a164a872be813481f058883ee8d421/Pillow-10.0.1.tar.gz", hash = "sha256:d72967b06be9300fed5cfbc8b5bafceec48bf7cdc7dab66b1d2549035287191d", size = 50528551 }-wheels = [- { url = "https://files.pythonhosted.org/packages/6e/f6/fbae883f0a33b0ba2d6a5008515735371f103077afc551c0005d0bd3264b/Pillow-10.0.1-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:fd2a5403a75b54661182b75ec6132437a181209b901446ee5724b589af8edef1", size = 3730189 },- { url = "https://files.pythonhosted.org/packages/e4/93/9226cc667ed8785333969c03deb2a36af2f3757284d3a2cf2ebd70331c32/Pillow-10.0.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:2d7e91b4379f7a76b31c2dda84ab9e20c6220488e50f7822e59dac36b0cd92b1", size = 3281476 },- { url = "https://files.pythonhosted.org/packages/6a/0c/18f9407e3b1176eb19f177139673c51f3857e4a29e13a21dafdc54519bcc/Pillow-10.0.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:19e9adb3f22d4c416e7cd79b01375b17159d6990003633ff1d8377e21b7f1b21", size = 3411397 },- { url = "https://files.pythonhosted.org/packages/c6/43/f2f31fd9d8282ac9724f5f2b6534ffd556dc7b67b64f239167e175e5b5c5/Pillow-10.0.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:93139acd8109edcdeffd85e3af8ae7d88b258b3a1e13a038f542b79b6d255c54", size = 3486491 },- { url = "https://files.pythonhosted.org/packages/f7/61/15b10190a6738db342efe4d06378ac4032b13d8ba6e9e1d89890119b2b8f/Pillow-10.0.1-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:92a23b0431941a33242b1f0ce6c88a952e09feeea9af4e8be48236a68ffe2205", size = 3462862 },- { url = "https://files.pythonhosted.org/packages/3c/49/f87cecbdec4b00cc1187f01196d48c08828204cd861915fab44972dc705c/Pillow-10.0.1-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:cbe68deb8580462ca0d9eb56a81912f59eb4542e1ef8f987405e35a0179f4ea2", size = 3607900 },- { url = "https://files.pythonhosted.org/packages/5d/d3/5e98b9c48bd35e884455e6e6850e473fdebc387c4779deacb6cf7648b591/Pillow-10.0.1-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:522ff4ac3aaf839242c6f4e5b406634bfea002469656ae8358644fc6c4856a3b", size = 3548941 },- { url = "https://files.pythonhosted.org/packages/be/d3/7d83335c19148d40a271c9e895c9a129dfc3f5f0d7b1aa2fbed2d9aaff05/Pillow-10.0.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:84efb46e8d881bb06b35d1d541aa87f574b58e87f781cbba8d200daa835b42e1", size = 3587102 },- { url = "https://files.pythonhosted.org/packages/54/9b/debe992677af84859ec1e38777b1d5c0671918188324153ecbc1f16f6cb6/Pillow-10.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:898f1d306298ff40dc1b9ca24824f0488f6f039bc0e25cfb549d3195ffa17088", size = 2513753 },- { url = "https://files.pythonhosted.org/packages/a1/aa/16d01cc6c4de2b8a48b3ef14fc3a5a89b43b9b60cd7aef8407c3cbee8dcd/Pillow-10.0.1-cp312-cp312-macosx_10_10_x86_64.whl", hash = "sha256:bcf1207e2f2385a576832af02702de104be71301c2696d0012b1b93fe34aaa5b", size = 3729828 },- { url = "https://files.pythonhosted.org/packages/5c/72/6d0a22c3f499e966f8b6b89842dfb915fb9449d0c9aa2b4e336259a7f00c/Pillow-10.0.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:5d6c9049c6274c1bb565021367431ad04481ebb54872edecfcd6088d27edd6ed", size = 3280585 },- { url = "https://files.pythonhosted.org/packages/54/4f/f38b5ca4a6bf209f32598796ef75b72afac3b9ee934898279d0a1ab39439/Pillow-10.0.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:28444cb6ad49726127d6b340217f0627abc8732f1194fd5352dec5e6a0105635", size = 3411566 },- { url = "https://files.pythonhosted.org/packages/7e/ea/45eb6c6d184183f560b26c5bd42c0601bf4b3c093762fdb3fd1c89769d23/Pillow-10.0.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:de596695a75496deb3b499c8c4f8e60376e0516e1a774e7bc046f0f48cd620ad", size = 3487109 },- { url = "https://files.pythonhosted.org/packages/ed/eb/fa2b371469b6301e1241472a34ede5f98ebdd256e99f88ba05bc1b0db888/Pillow-10.0.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:2872f2d7846cf39b3dbff64bc1104cc48c76145854256451d33c5faa55c04d1a", size = 3462905 },- { url = "https://files.pythonhosted.org/packages/0c/ce/3cceae2fab54118a5fcdfd9a2ddd0167c21169446c05378c5dc10b0d5093/Pillow-10.0.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:4ce90f8a24e1c15465048959f1e94309dfef93af272633e8f37361b824532e91", size = 3608054 },- { url = "https://files.pythonhosted.org/packages/26/d3/7a8e0c9c8dbef3354a45ab9164c26fc47a2884bbcec9bcc8504a7e0c7825/Pillow-10.0.1-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:ee7810cf7c83fa227ba9125de6084e5e8b08c59038a7b2c9045ef4dde61663b4", size = 3549376 },- { url = "https://files.pythonhosted.org/packages/2e/af/22305136707228776a5500d539ff6e0d7d0d2490ce8ef6905bd45e15e54b/Pillow-10.0.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:b1be1c872b9b5fcc229adeadbeb51422a9633abd847c0ff87dc4ef9bb184ae08", size = 3588197 },- { url = "https://files.pythonhosted.org/packages/00/00/d42abea0b4a415ea1e0975c981f95f354de1280d7e7bef3882bf1464b795/Pillow-10.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:98533fd7fa764e5f85eebe56c8e4094db912ccbe6fbf3a58778d543cadd0db08", size = 2514032 },-]--[[package]]-name = "pip"-version = "25.2"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/20/16/650289cd3f43d5a2fadfd98c68bd1e1e7f2550a1a5326768cddfbcedb2c5/pip-25.2.tar.gz", hash = "sha256:578283f006390f85bb6282dffb876454593d637f5d1be494b5202ce4877e71f2", size = 1840021 }-wheels = [- { url = "https://files.pythonhosted.org/packages/b7/3f/945ef7ab14dc4f9d7f40288d2df998d1837ee0888ec3659c813487572faa/pip-25.2-py3-none-any.whl", hash = "sha256:6d67a2b4e7f14d8b31b8b52648866fa717f45a1eb70e83002f4331d07e953717", size = 1752557 },+version = "12.0.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/5a/b0/cace85a1b0c9775a9f8f5d5423c8261c858760e2466c79b2dd184638b056/pillow-12.0.0.tar.gz", hash = "sha256:87d4f8125c9988bfbed67af47dd7a953e2fc7b0cc1e7800ec6d2080d490bb353", size = 47008828 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/0e/5a/a2f6773b64edb921a756eb0729068acad9fc5208a53f4a349396e9436721/pillow-12.0.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:0fd00cac9c03256c8b2ff58f162ebcd2587ad3e1f2e397eab718c47e24d231cc", size = 5289798 },+ { url = "https://files.pythonhosted.org/packages/2e/05/069b1f8a2e4b5a37493da6c5868531c3f77b85e716ad7a590ef87d58730d/pillow-12.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a3475b96f5908b3b16c47533daaa87380c491357d197564e0ba34ae75c0f3257", size = 4650589 },+ { url = "https://files.pythonhosted.org/packages/61/e3/2c820d6e9a36432503ead175ae294f96861b07600a7156154a086ba7111a/pillow-12.0.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:110486b79f2d112cf6add83b28b627e369219388f64ef2f960fef9ebaf54c642", size = 6230472 },+ { url = "https://files.pythonhosted.org/packages/4f/89/63427f51c64209c5e23d4d52071c8d0f21024d3a8a487737caaf614a5795/pillow-12.0.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5269cc1caeedb67e6f7269a42014f381f45e2e7cd42d834ede3c703a1d915fe3", size = 8033887 },+ { url = "https://files.pythonhosted.org/packages/f6/1b/c9711318d4901093c15840f268ad649459cd81984c9ec9887756cca049a5/pillow-12.0.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:aa5129de4e174daccbc59d0a3b6d20eaf24417d59851c07ebb37aeb02947987c", size = 6343964 },+ { url = "https://files.pythonhosted.org/packages/41/1e/db9470f2d030b4995083044cd8738cdd1bf773106819f6d8ba12597d5352/pillow-12.0.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bee2a6db3a7242ea309aa7ee8e2780726fed67ff4e5b40169f2c940e7eb09227", size = 7034756 },+ { url = "https://files.pythonhosted.org/packages/cc/b0/6177a8bdd5ee4ed87cba2de5a3cc1db55ffbbec6176784ce5bb75aa96798/pillow-12.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:90387104ee8400a7b4598253b4c406f8958f59fcf983a6cea2b50d59f7d63d0b", size = 6458075 },+ { url = "https://files.pythonhosted.org/packages/bc/5e/61537aa6fa977922c6a03253a0e727e6e4a72381a80d63ad8eec350684f2/pillow-12.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:bc91a56697869546d1b8f0a3ff35224557ae7f881050e99f615e0119bf934b4e", size = 7125955 },+ { url = "https://files.pythonhosted.org/packages/1f/3d/d5033539344ee3cbd9a4d69e12e63ca3a44a739eb2d4c8da350a3d38edd7/pillow-12.0.0-cp311-cp311-win32.whl", hash = "sha256:27f95b12453d165099c84f8a8bfdfd46b9e4bda9e0e4b65f0635430027f55739", size = 6298440 },+ { url = "https://files.pythonhosted.org/packages/4d/42/aaca386de5cc8bd8a0254516957c1f265e3521c91515b16e286c662854c4/pillow-12.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:b583dc9070312190192631373c6c8ed277254aa6e6084b74bdd0a6d3b221608e", size = 6999256 },+ { url = "https://files.pythonhosted.org/packages/ba/f1/9197c9c2d5708b785f631a6dfbfa8eb3fb9672837cb92ae9af812c13b4ed/pillow-12.0.0-cp311-cp311-win_arm64.whl", hash = "sha256:759de84a33be3b178a64c8ba28ad5c135900359e85fb662bc6e403ad4407791d", size = 2436025 },+ { url = "https://files.pythonhosted.org/packages/2c/90/4fcce2c22caf044e660a198d740e7fbc14395619e3cb1abad12192c0826c/pillow-12.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:53561a4ddc36facb432fae7a9d8afbfaf94795414f5cdc5fc52f28c1dca90371", size = 5249377 },+ { url = "https://files.pythonhosted.org/packages/fd/e0/ed960067543d080691d47d6938ebccbf3976a931c9567ab2fbfab983a5dd/pillow-12.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:71db6b4c1653045dacc1585c1b0d184004f0d7e694c7b34ac165ca70c0838082", size = 4650343 },+ { url = "https://files.pythonhosted.org/packages/e7/a1/f81fdeddcb99c044bf7d6faa47e12850f13cee0849537a7d27eeab5534d4/pillow-12.0.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:2fa5f0b6716fc88f11380b88b31fe591a06c6315e955c096c35715788b339e3f", size = 6232981 },+ { url = "https://files.pythonhosted.org/packages/88/e1/9098d3ce341a8750b55b0e00c03f1630d6178f38ac191c81c97a3b047b44/pillow-12.0.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:82240051c6ca513c616f7f9da06e871f61bfd7805f566275841af15015b8f98d", size = 8041399 },+ { url = "https://files.pythonhosted.org/packages/a7/62/a22e8d3b602ae8cc01446d0c57a54e982737f44b6f2e1e019a925143771d/pillow-12.0.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:55f818bd74fe2f11d4d7cbc65880a843c4075e0ac7226bc1a23261dbea531953", size = 6347740 },+ { url = "https://files.pythonhosted.org/packages/4f/87/424511bdcd02c8d7acf9f65caa09f291a519b16bd83c3fb3374b3d4ae951/pillow-12.0.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b87843e225e74576437fd5b6a4c2205d422754f84a06942cfaf1dc32243e45a8", size = 7040201 },+ { url = "https://files.pythonhosted.org/packages/dc/4d/435c8ac688c54d11755aedfdd9f29c9eeddf68d150fe42d1d3dbd2365149/pillow-12.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c607c90ba67533e1b2355b821fef6764d1dd2cbe26b8c1005ae84f7aea25ff79", size = 6462334 },+ { url = "https://files.pythonhosted.org/packages/2b/f2/ad34167a8059a59b8ad10bc5c72d4d9b35acc6b7c0877af8ac885b5f2044/pillow-12.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:21f241bdd5080a15bc86d3466a9f6074a9c2c2b314100dd896ac81ee6db2f1ba", size = 7134162 },+ { url = "https://files.pythonhosted.org/packages/0c/b1/a7391df6adacf0a5c2cf6ac1cf1fcc1369e7d439d28f637a847f8803beb3/pillow-12.0.0-cp312-cp312-win32.whl", hash = "sha256:dd333073e0cacdc3089525c7df7d39b211bcdf31fc2824e49d01c6b6187b07d0", size = 6298769 },+ { url = "https://files.pythonhosted.org/packages/a2/0b/d87733741526541c909bbf159e338dcace4f982daac6e5a8d6be225ca32d/pillow-12.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:9fe611163f6303d1619bbcb653540a4d60f9e55e622d60a3108be0d5b441017a", size = 7001107 },+ { url = "https://files.pythonhosted.org/packages/bc/96/aaa61ce33cc98421fb6088af2a03be4157b1e7e0e87087c888e2370a7f45/pillow-12.0.0-cp312-cp312-win_arm64.whl", hash = "sha256:7dfb439562f234f7d57b1ac6bc8fe7f838a4bd49c79230e0f6a1da93e82f1fad", size = 2436012 },+ { url = "https://files.pythonhosted.org/packages/62/f2/de993bb2d21b33a98d031ecf6a978e4b61da207bef02f7b43093774c480d/pillow-12.0.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:0869154a2d0546545cde61d1789a6524319fc1897d9ee31218eae7a60ccc5643", size = 4045493 },+ { url = "https://files.pythonhosted.org/packages/0e/b6/bc8d0c4c9f6f111a783d045310945deb769b806d7574764234ffd50bc5ea/pillow-12.0.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:a7921c5a6d31b3d756ec980f2f47c0cfdbce0fc48c22a39347a895f41f4a6ea4", size = 4120461 },+ { url = "https://files.pythonhosted.org/packages/5d/57/d60d343709366a353dc56adb4ee1e7d8a2cc34e3fbc22905f4167cfec119/pillow-12.0.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:1ee80a59f6ce048ae13cda1abf7fbd2a34ab9ee7d401c46be3ca685d1999a399", size = 3576912 },+ { url = "https://files.pythonhosted.org/packages/a4/a4/a0a31467e3f83b94d37568294b01d22b43ae3c5d85f2811769b9c66389dd/pillow-12.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:c50f36a62a22d350c96e49ad02d0da41dbd17ddc2e29750dbdba4323f85eb4a5", size = 5249132 },+ { url = "https://files.pythonhosted.org/packages/83/06/48eab21dd561de2914242711434c0c0eb992ed08ff3f6107a5f44527f5e9/pillow-12.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:5193fde9a5f23c331ea26d0cf171fbf67e3f247585f50c08b3e205c7aeb4589b", size = 4650099 },+ { url = "https://files.pythonhosted.org/packages/fc/bd/69ed99fd46a8dba7c1887156d3572fe4484e3f031405fcc5a92e31c04035/pillow-12.0.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:bde737cff1a975b70652b62d626f7785e0480918dece11e8fef3c0cf057351c3", size = 6230808 },+ { url = "https://files.pythonhosted.org/packages/ea/94/8fad659bcdbf86ed70099cb60ae40be6acca434bbc8c4c0d4ef356d7e0de/pillow-12.0.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a6597ff2b61d121172f5844b53f21467f7082f5fb385a9a29c01414463f93b07", size = 8037804 },+ { url = "https://files.pythonhosted.org/packages/20/39/c685d05c06deecfd4e2d1950e9a908aa2ca8bc4e6c3b12d93b9cafbd7837/pillow-12.0.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0b817e7035ea7f6b942c13aa03bb554fc44fea70838ea21f8eb31c638326584e", size = 6345553 },+ { url = "https://files.pythonhosted.org/packages/38/57/755dbd06530a27a5ed74f8cb0a7a44a21722ebf318edbe67ddbd7fb28f88/pillow-12.0.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f4f1231b7dec408e8670264ce63e9c71409d9583dd21d32c163e25213ee2a344", size = 7037729 },+ { url = "https://files.pythonhosted.org/packages/ca/b6/7e94f4c41d238615674d06ed677c14883103dce1c52e4af16f000338cfd7/pillow-12.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:6e51b71417049ad6ab14c49608b4a24d8fb3fe605e5dfabfe523b58064dc3d27", size = 6459789 },+ { url = "https://files.pythonhosted.org/packages/9c/14/4448bb0b5e0f22dd865290536d20ec8a23b64e2d04280b89139f09a36bb6/pillow-12.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:d120c38a42c234dc9a8c5de7ceaaf899cf33561956acb4941653f8bdc657aa79", size = 7130917 },+ { url = "https://files.pythonhosted.org/packages/dd/ca/16c6926cc1c015845745d5c16c9358e24282f1e588237a4c36d2b30f182f/pillow-12.0.0-cp313-cp313-win32.whl", hash = "sha256:4cc6b3b2efff105c6a1656cfe59da4fdde2cda9af1c5e0b58529b24525d0a098", size = 6302391 },+ { url = "https://files.pythonhosted.org/packages/6d/2a/dd43dcfd6dae9b6a49ee28a8eedb98c7d5ff2de94a5d834565164667b97b/pillow-12.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:4cf7fed4b4580601c4345ceb5d4cbf5a980d030fd5ad07c4d2ec589f95f09905", size = 7007477 },+ { url = "https://files.pythonhosted.org/packages/77/f0/72ea067f4b5ae5ead653053212af05ce3705807906ba3f3e8f58ddf617e6/pillow-12.0.0-cp313-cp313-win_arm64.whl", hash = "sha256:9f0b04c6b8584c2c193babcccc908b38ed29524b29dd464bc8801bf10d746a3a", size = 2435918 },+ { url = "https://files.pythonhosted.org/packages/f5/5e/9046b423735c21f0487ea6cb5b10f89ea8f8dfbe32576fe052b5ba9d4e5b/pillow-12.0.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:7fa22993bac7b77b78cae22bad1e2a987ddf0d9015c63358032f84a53f23cdc3", size = 5251406 },+ { url = "https://files.pythonhosted.org/packages/12/66/982ceebcdb13c97270ef7a56c3969635b4ee7cd45227fa707c94719229c5/pillow-12.0.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:f135c702ac42262573fe9714dfe99c944b4ba307af5eb507abef1667e2cbbced", size = 4653218 },+ { url = "https://files.pythonhosted.org/packages/16/b3/81e625524688c31859450119bf12674619429cab3119eec0e30a7a1029cb/pillow-12.0.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:c85de1136429c524e55cfa4e033b4a7940ac5c8ee4d9401cc2d1bf48154bbc7b", size = 6266564 },+ { url = "https://files.pythonhosted.org/packages/98/59/dfb38f2a41240d2408096e1a76c671d0a105a4a8471b1871c6902719450c/pillow-12.0.0-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:38df9b4bfd3db902c9c2bd369bcacaf9d935b2fff73709429d95cc41554f7b3d", size = 8069260 },+ { url = "https://files.pythonhosted.org/packages/dc/3d/378dbea5cd1874b94c312425ca77b0f47776c78e0df2df751b820c8c1d6c/pillow-12.0.0-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7d87ef5795da03d742bf49439f9ca4d027cde49c82c5371ba52464aee266699a", size = 6379248 },+ { url = "https://files.pythonhosted.org/packages/84/b0/d525ef47d71590f1621510327acec75ae58c721dc071b17d8d652ca494d8/pillow-12.0.0-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:aff9e4d82d082ff9513bdd6acd4f5bd359f5b2c870907d2b0a9c5e10d40c88fe", size = 7066043 },+ { url = "https://files.pythonhosted.org/packages/61/2c/aced60e9cf9d0cde341d54bf7932c9ffc33ddb4a1595798b3a5150c7ec4e/pillow-12.0.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:8d8ca2b210ada074d57fcee40c30446c9562e542fc46aedc19baf758a93532ee", size = 6490915 },+ { url = "https://files.pythonhosted.org/packages/ef/26/69dcb9b91f4e59f8f34b2332a4a0a951b44f547c4ed39d3e4dcfcff48f89/pillow-12.0.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:99a7f72fb6249302aa62245680754862a44179b545ded638cf1fef59befb57ef", size = 7157998 },+ { url = "https://files.pythonhosted.org/packages/61/2b/726235842220ca95fa441ddf55dd2382b52ab5b8d9c0596fe6b3f23dafe8/pillow-12.0.0-cp313-cp313t-win32.whl", hash = "sha256:4078242472387600b2ce8d93ade8899c12bf33fa89e55ec89fe126e9d6d5d9e9", size = 6306201 },+ { url = "https://files.pythonhosted.org/packages/c0/3d/2afaf4e840b2df71344ababf2f8edd75a705ce500e5dc1e7227808312ae1/pillow-12.0.0-cp313-cp313t-win_amd64.whl", hash = "sha256:2c54c1a783d6d60595d3514f0efe9b37c8808746a66920315bfd34a938d7994b", size = 7013165 },+ { url = "https://files.pythonhosted.org/packages/6f/75/3fa09aa5cf6ed04bee3fa575798ddf1ce0bace8edb47249c798077a81f7f/pillow-12.0.0-cp313-cp313t-win_arm64.whl", hash = "sha256:26d9f7d2b604cd23aba3e9faf795787456ac25634d82cd060556998e39c6fa47", size = 2437834 },+ { url = "https://files.pythonhosted.org/packages/54/2a/9a8c6ba2c2c07b71bec92cf63e03370ca5e5f5c5b119b742bcc0cde3f9c5/pillow-12.0.0-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:beeae3f27f62308f1ddbcfb0690bf44b10732f2ef43758f169d5e9303165d3f9", size = 4045531 },+ { url = "https://files.pythonhosted.org/packages/84/54/836fdbf1bfb3d66a59f0189ff0b9f5f666cee09c6188309300df04ad71fa/pillow-12.0.0-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:d4827615da15cd59784ce39d3388275ec093ae3ee8d7f0c089b76fa87af756c2", size = 4120554 },+ { url = "https://files.pythonhosted.org/packages/0d/cd/16aec9f0da4793e98e6b54778a5fbce4f375c6646fe662e80600b8797379/pillow-12.0.0-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:3e42edad50b6909089750e65c91aa09aaf1e0a71310d383f11321b27c224ed8a", size = 3576812 },+ { url = "https://files.pythonhosted.org/packages/f6/b7/13957fda356dc46339298b351cae0d327704986337c3c69bb54628c88155/pillow-12.0.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:e5d8efac84c9afcb40914ab49ba063d94f5dbdf5066db4482c66a992f47a3a3b", size = 5252689 },+ { url = "https://files.pythonhosted.org/packages/fc/f5/eae31a306341d8f331f43edb2e9122c7661b975433de5e447939ae61c5da/pillow-12.0.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:266cd5f2b63ff316d5a1bba46268e603c9caf5606d44f38c2873c380950576ad", size = 4650186 },+ { url = "https://files.pythonhosted.org/packages/86/62/2a88339aa40c4c77e79108facbd307d6091e2c0eb5b8d3cf4977cfca2fe6/pillow-12.0.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:58eea5ebe51504057dd95c5b77d21700b77615ab0243d8152793dc00eb4faf01", size = 6230308 },+ { url = "https://files.pythonhosted.org/packages/c7/33/5425a8992bcb32d1cb9fa3dd39a89e613d09a22f2c8083b7bf43c455f760/pillow-12.0.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f13711b1a5ba512d647a0e4ba79280d3a9a045aaf7e0cc6fbe96b91d4cdf6b0c", size = 8039222 },+ { url = "https://files.pythonhosted.org/packages/d8/61/3f5d3b35c5728f37953d3eec5b5f3e77111949523bd2dd7f31a851e50690/pillow-12.0.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6846bd2d116ff42cba6b646edf5bf61d37e5cbd256425fa089fee4ff5c07a99e", size = 6346657 },+ { url = "https://files.pythonhosted.org/packages/3a/be/ee90a3d79271227e0f0a33c453531efd6ed14b2e708596ba5dd9be948da3/pillow-12.0.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c98fa880d695de164b4135a52fd2e9cd7b7c90a9d8ac5e9e443a24a95ef9248e", size = 7038482 },+ { url = "https://files.pythonhosted.org/packages/44/34/a16b6a4d1ad727de390e9bd9f19f5f669e079e5826ec0f329010ddea492f/pillow-12.0.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fa3ed2a29a9e9d2d488b4da81dcb54720ac3104a20bf0bd273f1e4648aff5af9", size = 6461416 },+ { url = "https://files.pythonhosted.org/packages/b6/39/1aa5850d2ade7d7ba9f54e4e4c17077244ff7a2d9e25998c38a29749eb3f/pillow-12.0.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:d034140032870024e6b9892c692fe2968493790dd57208b2c37e3fb35f6df3ab", size = 7131584 },+ { url = "https://files.pythonhosted.org/packages/bf/db/4fae862f8fad0167073a7733973bfa955f47e2cac3dc3e3e6257d10fab4a/pillow-12.0.0-cp314-cp314-win32.whl", hash = "sha256:1b1b133e6e16105f524a8dec491e0586d072948ce15c9b914e41cdadd209052b", size = 6400621 },+ { url = "https://files.pythonhosted.org/packages/2b/24/b350c31543fb0107ab2599464d7e28e6f856027aadda995022e695313d94/pillow-12.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:8dc232e39d409036af549c86f24aed8273a40ffa459981146829a324e0848b4b", size = 7142916 },+ { url = "https://files.pythonhosted.org/packages/0f/9b/0ba5a6fd9351793996ef7487c4fdbde8d3f5f75dbedc093bb598648fddf0/pillow-12.0.0-cp314-cp314-win_arm64.whl", hash = "sha256:d52610d51e265a51518692045e372a4c363056130d922a7351429ac9f27e70b0", size = 2523836 },+ { url = "https://files.pythonhosted.org/packages/f5/7a/ceee0840aebc579af529b523d530840338ecf63992395842e54edc805987/pillow-12.0.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:1979f4566bb96c1e50a62d9831e2ea2d1211761e5662afc545fa766f996632f6", size = 5255092 },+ { url = "https://files.pythonhosted.org/packages/44/76/20776057b4bfd1aef4eeca992ebde0f53a4dce874f3ae693d0ec90a4f79b/pillow-12.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:b2e4b27a6e15b04832fe9bf292b94b5ca156016bbc1ea9c2c20098a0320d6cf6", size = 4653158 },+ { url = "https://files.pythonhosted.org/packages/82/3f/d9ff92ace07be8836b4e7e87e6a4c7a8318d47c2f1463ffcf121fc57d9cb/pillow-12.0.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:fb3096c30df99fd01c7bf8e544f392103d0795b9f98ba71a8054bcbf56b255f1", size = 6267882 },+ { url = "https://files.pythonhosted.org/packages/9f/7a/4f7ff87f00d3ad33ba21af78bfcd2f032107710baf8280e3722ceec28cda/pillow-12.0.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7438839e9e053ef79f7112c881cef684013855016f928b168b81ed5835f3e75e", size = 8071001 },+ { url = "https://files.pythonhosted.org/packages/75/87/fcea108944a52dad8cca0715ae6247e271eb80459364a98518f1e4f480c1/pillow-12.0.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5d5c411a8eaa2299322b647cd932586b1427367fd3184ffbb8f7a219ea2041ca", size = 6380146 },+ { url = "https://files.pythonhosted.org/packages/91/52/0d31b5e571ef5fd111d2978b84603fce26aba1b6092f28e941cb46570745/pillow-12.0.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d7e091d464ac59d2c7ad8e7e08105eaf9dafbc3883fd7265ffccc2baad6ac925", size = 7067344 },+ { url = "https://files.pythonhosted.org/packages/7b/f4/2dd3d721f875f928d48e83bb30a434dee75a2531bca839bb996bb0aa5a91/pillow-12.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:792a2c0be4dcc18af9d4a2dfd8a11a17d5e25274a1062b0ec1c2d79c76f3e7f8", size = 6491864 },+ { url = "https://files.pythonhosted.org/packages/30/4b/667dfcf3d61fc309ba5a15b141845cece5915e39b99c1ceab0f34bf1d124/pillow-12.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:afbefa430092f71a9593a99ab6a4e7538bc9eabbf7bf94f91510d3503943edc4", size = 7158911 },+ { url = "https://files.pythonhosted.org/packages/a2/2f/16cabcc6426c32218ace36bf0d55955e813f2958afddbf1d391849fee9d1/pillow-12.0.0-cp314-cp314t-win32.whl", hash = "sha256:3830c769decf88f1289680a59d4f4c46c72573446352e2befec9a8512104fa52", size = 6408045 },+ { url = "https://files.pythonhosted.org/packages/35/73/e29aa0c9c666cf787628d3f0dcf379f4791fba79f4936d02f8b37165bdf8/pillow-12.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:905b0365b210c73afb0ebe9101a32572152dfd1c144c7e28968a331b9217b94a", size = 7148282 },+ { url = "https://files.pythonhosted.org/packages/c1/70/6b41bdcddf541b437bbb9f47f94d2db5d9ddef6c37ccab8c9107743748a4/pillow-12.0.0-cp314-cp314t-win_arm64.whl", hash = "sha256:99353a06902c2e43b43e8ff74ee65a7d90307d82370604746738a1e0661ccca7", size = 2525630 },+ { url = "https://files.pythonhosted.org/packages/1d/b3/582327e6c9f86d037b63beebe981425d6811104cb443e8193824ef1a2f27/pillow-12.0.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:b22bd8c974942477156be55a768f7aa37c46904c175be4e158b6a86e3a6b7ca8", size = 5215068 },+ { url = "https://files.pythonhosted.org/packages/fd/d6/67748211d119f3b6540baf90f92fae73ae51d5217b171b0e8b5f7e5d558f/pillow-12.0.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:805ebf596939e48dbb2e4922a1d3852cfc25c38160751ce02da93058b48d252a", size = 4614994 },+ { url = "https://files.pythonhosted.org/packages/2d/e1/f8281e5d844c41872b273b9f2c34a4bf64ca08905668c8ae730eedc7c9fa/pillow-12.0.0-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cae81479f77420d217def5f54b5b9d279804d17e982e0f2fa19b1d1e14ab5197", size = 5246639 },+ { url = "https://files.pythonhosted.org/packages/94/5a/0d8ab8ffe8a102ff5df60d0de5af309015163bf710c7bb3e8311dd3b3ad0/pillow-12.0.0-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aeaefa96c768fc66818730b952a862235d68825c178f1b3ffd4efd7ad2edcb7c", size = 6986839 },+ { url = "https://files.pythonhosted.org/packages/20/2e/3434380e8110b76cd9eb00a363c484b050f949b4bbe84ba770bb8508a02c/pillow-12.0.0-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:09f2d0abef9e4e2f349305a4f8cc784a8a6c2f58a8c4892eea13b10a943bd26e", size = 5313505 },+ { url = "https://files.pythonhosted.org/packages/57/ca/5a9d38900d9d74785141d6580950fe705de68af735ff6e727cb911b64740/pillow-12.0.0-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bdee52571a343d721fb2eb3b090a82d959ff37fc631e3f70422e0c2e029f3e76", size = 5963654 },+ { url = "https://files.pythonhosted.org/packages/95/7e/f896623c3c635a90537ac093c6a618ebe1a90d87206e42309cb5d98a1b9e/pillow-12.0.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:b290fd8aa38422444d4b50d579de197557f182ef1068b75f5aa8558638b8d0a5", size = 6997850 },][[package]]@@ -1103,31 +1311,89 @@ wheels = [][[package]]-name = "pyaudio"-version = "0.2.14"+name = "pyarrow"+version = "22.0.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/30/53/04a7fdc63e6056116c9ddc8b43bc28c12cdd181b85cbeadb79278475f3ae/pyarrow-22.0.0.tar.gz", hash = "sha256:3d600dc583260d845c7d8a6db540339dd883081925da2bd1c5cb808f720b3cd9", size = 1151151 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/2e/b7/18f611a8cdc43417f9394a3ccd3eace2f32183c08b9eddc3d17681819f37/pyarrow-22.0.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:3e294c5eadfb93d78b0763e859a0c16d4051fc1c5231ae8956d61cb0b5666f5a", size = 34272022 },+ { url = "https://files.pythonhosted.org/packages/26/5c/f259e2526c67eb4b9e511741b19870a02363a47a35edbebc55c3178db22d/pyarrow-22.0.0-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:69763ab2445f632d90b504a815a2a033f74332997052b721002298ed6de40f2e", size = 35995834 },+ { url = "https://files.pythonhosted.org/packages/50/8d/281f0f9b9376d4b7f146913b26fac0aa2829cd1ee7e997f53a27411bbb92/pyarrow-22.0.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:b41f37cabfe2463232684de44bad753d6be08a7a072f6a83447eeaf0e4d2a215", size = 45030348 },+ { url = "https://files.pythonhosted.org/packages/f5/e5/53c0a1c428f0976bf22f513d79c73000926cb00b9c138d8e02daf2102e18/pyarrow-22.0.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:35ad0f0378c9359b3f297299c3309778bb03b8612f987399a0333a560b43862d", size = 47699480 },+ { url = "https://files.pythonhosted.org/packages/95/e1/9dbe4c465c3365959d183e6345d0a8d1dc5b02ca3f8db4760b3bc834cf25/pyarrow-22.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:8382ad21458075c2e66a82a29d650f963ce51c7708c7c0ff313a8c206c4fd5e8", size = 48011148 },+ { url = "https://files.pythonhosted.org/packages/c5/b4/7caf5d21930061444c3cf4fa7535c82faf5263e22ce43af7c2759ceb5b8b/pyarrow-22.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:1a812a5b727bc09c3d7ea072c4eebf657c2f7066155506ba31ebf4792f88f016", size = 50276964 },+ { url = "https://files.pythonhosted.org/packages/ae/f3/cec89bd99fa3abf826f14d4e53d3d11340ce6f6af4d14bdcd54cd83b6576/pyarrow-22.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:ec5d40dd494882704fb876c16fa7261a69791e784ae34e6b5992e977bd2e238c", size = 28106517 },+ { url = "https://files.pythonhosted.org/packages/af/63/ba23862d69652f85b615ca14ad14f3bcfc5bf1b99ef3f0cd04ff93fdad5a/pyarrow-22.0.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:bea79263d55c24a32b0d79c00a1c58bb2ee5f0757ed95656b01c0fb310c5af3d", size = 34211578 },+ { url = "https://files.pythonhosted.org/packages/b1/d0/f9ad86fe809efd2bcc8be32032fa72e8b0d112b01ae56a053006376c5930/pyarrow-22.0.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:12fe549c9b10ac98c91cf791d2945e878875d95508e1a5d14091a7aaa66d9cf8", size = 35989906 },+ { url = "https://files.pythonhosted.org/packages/b4/a8/f910afcb14630e64d673f15904ec27dd31f1e009b77033c365c84e8c1e1d/pyarrow-22.0.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:334f900ff08ce0423407af97e6c26ad5d4e3b0763645559ece6fbf3747d6a8f5", size = 45021677 },+ { url = "https://files.pythonhosted.org/packages/13/95/aec81f781c75cd10554dc17a25849c720d54feafb6f7847690478dcf5ef8/pyarrow-22.0.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:c6c791b09c57ed76a18b03f2631753a4960eefbbca80f846da8baefc6491fcfe", size = 47726315 },+ { url = "https://files.pythonhosted.org/packages/bb/d4/74ac9f7a54cfde12ee42734ea25d5a3c9a45db78f9def949307a92720d37/pyarrow-22.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c3200cb41cdbc65156e5f8c908d739b0dfed57e890329413da2748d1a2cd1a4e", size = 47990906 },+ { url = "https://files.pythonhosted.org/packages/2e/71/fedf2499bf7a95062eafc989ace56572f3343432570e1c54e6599d5b88da/pyarrow-22.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ac93252226cf288753d8b46280f4edf3433bf9508b6977f8dd8526b521a1bbb9", size = 50306783 },+ { url = "https://files.pythonhosted.org/packages/68/ed/b202abd5a5b78f519722f3d29063dda03c114711093c1995a33b8e2e0f4b/pyarrow-22.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:44729980b6c50a5f2bfcc2668d36c569ce17f8b17bccaf470c4313dcbbf13c9d", size = 27972883 },+ { url = "https://files.pythonhosted.org/packages/a6/d6/d0fac16a2963002fc22c8fa75180a838737203d558f0ed3b564c4a54eef5/pyarrow-22.0.0-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:e6e95176209257803a8b3d0394f21604e796dadb643d2f7ca21b66c9c0b30c9a", size = 34204629 },+ { url = "https://files.pythonhosted.org/packages/c6/9c/1d6357347fbae062ad3f17082f9ebc29cc733321e892c0d2085f42a2212b/pyarrow-22.0.0-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:001ea83a58024818826a9e3f89bf9310a114f7e26dfe404a4c32686f97bd7901", size = 35985783 },+ { url = "https://files.pythonhosted.org/packages/ff/c0/782344c2ce58afbea010150df07e3a2f5fdad299cd631697ae7bd3bac6e3/pyarrow-22.0.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:ce20fe000754f477c8a9125543f1936ea5b8867c5406757c224d745ed033e691", size = 45020999 },+ { url = "https://files.pythonhosted.org/packages/1b/8b/5362443737a5307a7b67c1017c42cd104213189b4970bf607e05faf9c525/pyarrow-22.0.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:e0a15757fccb38c410947df156f9749ae4a3c89b2393741a50521f39a8cf202a", size = 47724601 },+ { url = "https://files.pythonhosted.org/packages/69/4d/76e567a4fc2e190ee6072967cb4672b7d9249ac59ae65af2d7e3047afa3b/pyarrow-22.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:cedb9dd9358e4ea1d9bce3665ce0797f6adf97ff142c8e25b46ba9cdd508e9b6", size = 48001050 },+ { url = "https://files.pythonhosted.org/packages/01/5e/5653f0535d2a1aef8223cee9d92944cb6bccfee5cf1cd3f462d7cb022790/pyarrow-22.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:252be4a05f9d9185bb8c18e83764ebcfea7185076c07a7a662253af3a8c07941", size = 50307877 },+ { url = "https://files.pythonhosted.org/packages/2d/f8/1d0bd75bf9328a3b826e24a16e5517cd7f9fbf8d34a3184a4566ef5a7f29/pyarrow-22.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:a4893d31e5ef780b6edcaf63122df0f8d321088bb0dee4c8c06eccb1ca28d145", size = 27977099 },+ { url = "https://files.pythonhosted.org/packages/90/81/db56870c997805bf2b0f6eeeb2d68458bf4654652dccdcf1bf7a42d80903/pyarrow-22.0.0-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:f7fe3dbe871294ba70d789be16b6e7e52b418311e166e0e3cba9522f0f437fb1", size = 34336685 },+ { url = "https://files.pythonhosted.org/packages/1c/98/0727947f199aba8a120f47dfc229eeb05df15bcd7a6f1b669e9f882afc58/pyarrow-22.0.0-cp313-cp313t-macosx_12_0_x86_64.whl", hash = "sha256:ba95112d15fd4f1105fb2402c4eab9068f0554435e9b7085924bcfaac2cc306f", size = 36032158 },+ { url = "https://files.pythonhosted.org/packages/96/b4/9babdef9c01720a0785945c7cf550e4acd0ebcd7bdd2e6f0aa7981fa85e2/pyarrow-22.0.0-cp313-cp313t-manylinux_2_28_aarch64.whl", hash = "sha256:c064e28361c05d72eed8e744c9605cbd6d2bb7481a511c74071fd9b24bc65d7d", size = 44892060 },+ { url = "https://files.pythonhosted.org/packages/f8/ca/2f8804edd6279f78a37062d813de3f16f29183874447ef6d1aadbb4efa0f/pyarrow-22.0.0-cp313-cp313t-manylinux_2_28_x86_64.whl", hash = "sha256:6f9762274496c244d951c819348afbcf212714902742225f649cf02823a6a10f", size = 47504395 },+ { url = "https://files.pythonhosted.org/packages/b9/f0/77aa5198fd3943682b2e4faaf179a674f0edea0d55d326d83cb2277d9363/pyarrow-22.0.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:a9d9ffdc2ab696f6b15b4d1f7cec6658e1d788124418cb30030afbae31c64746", size = 48066216 },+ { url = "https://files.pythonhosted.org/packages/79/87/a1937b6e78b2aff18b706d738c9e46ade5bfcf11b294e39c87706a0089ac/pyarrow-22.0.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:ec1a15968a9d80da01e1d30349b2b0d7cc91e96588ee324ce1b5228175043e95", size = 50288552 },+ { url = "https://files.pythonhosted.org/packages/60/ae/b5a5811e11f25788ccfdaa8f26b6791c9807119dffcf80514505527c384c/pyarrow-22.0.0-cp313-cp313t-win_amd64.whl", hash = "sha256:bba208d9c7decf9961998edf5c65e3ea4355d5818dd6cd0f6809bec1afb951cc", size = 28262504 },+ { url = "https://files.pythonhosted.org/packages/bd/b0/0fa4d28a8edb42b0a7144edd20befd04173ac79819547216f8a9f36f9e50/pyarrow-22.0.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:9bddc2cade6561f6820d4cd73f99a0243532ad506bc510a75a5a65a522b2d74d", size = 34224062 },+ { url = "https://files.pythonhosted.org/packages/0f/a8/7a719076b3c1be0acef56a07220c586f25cd24de0e3f3102b438d18ae5df/pyarrow-22.0.0-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:e70ff90c64419709d38c8932ea9fe1cc98415c4f87ea8da81719e43f02534bc9", size = 35990057 },+ { url = "https://files.pythonhosted.org/packages/89/3c/359ed54c93b47fb6fe30ed16cdf50e3f0e8b9ccfb11b86218c3619ae50a8/pyarrow-22.0.0-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:92843c305330aa94a36e706c16209cd4df274693e777ca47112617db7d0ef3d7", size = 45068002 },+ { url = "https://files.pythonhosted.org/packages/55/fc/4945896cc8638536ee787a3bd6ce7cec8ec9acf452d78ec39ab328efa0a1/pyarrow-22.0.0-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:6dda1ddac033d27421c20d7a7943eec60be44e0db4e079f33cc5af3b8280ccde", size = 47737765 },+ { url = "https://files.pythonhosted.org/packages/cd/5e/7cb7edeb2abfaa1f79b5d5eb89432356155c8426f75d3753cbcb9592c0fd/pyarrow-22.0.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:84378110dd9a6c06323b41b56e129c504d157d1a983ce8f5443761eb5256bafc", size = 48048139 },+ { url = "https://files.pythonhosted.org/packages/88/c6/546baa7c48185f5e9d6e59277c4b19f30f48c94d9dd938c2a80d4d6b067c/pyarrow-22.0.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:854794239111d2b88b40b6ef92aa478024d1e5074f364033e73e21e3f76b25e0", size = 50314244 },+ { url = "https://files.pythonhosted.org/packages/3c/79/755ff2d145aafec8d347bf18f95e4e81c00127f06d080135dfc86aea417c/pyarrow-22.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:b883fe6fd85adad7932b3271c38ac289c65b7337c2c132e9569f9d3940620730", size = 28757501 },+ { url = "https://files.pythonhosted.org/packages/0e/d2/237d75ac28ced3147912954e3c1a174df43a95f4f88e467809118a8165e0/pyarrow-22.0.0-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:7a820d8ae11facf32585507c11f04e3f38343c1e784c9b5a8b1da5c930547fe2", size = 34355506 },+ { url = "https://files.pythonhosted.org/packages/1e/2c/733dfffe6d3069740f98e57ff81007809067d68626c5faef293434d11bd6/pyarrow-22.0.0-cp314-cp314t-macosx_12_0_x86_64.whl", hash = "sha256:c6ec3675d98915bf1ec8b3c7986422682f7232ea76cad276f4c8abd5b7319b70", size = 36047312 },+ { url = "https://files.pythonhosted.org/packages/7c/2b/29d6e3782dc1f299727462c1543af357a0f2c1d3c160ce199950d9ca51eb/pyarrow-22.0.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:3e739edd001b04f654b166204fc7a9de896cf6007eaff33409ee9e50ceaff754", size = 45081609 },+ { url = "https://files.pythonhosted.org/packages/8d/42/aa9355ecc05997915af1b7b947a7f66c02dcaa927f3203b87871c114ba10/pyarrow-22.0.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:7388ac685cab5b279a41dfe0a6ccd99e4dbf322edfb63e02fc0443bf24134e91", size = 47703663 },+ { url = "https://files.pythonhosted.org/packages/ee/62/45abedde480168e83a1de005b7b7043fd553321c1e8c5a9a114425f64842/pyarrow-22.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:f633074f36dbc33d5c05b5dc75371e5660f1dbf9c8b1d95669def05e5425989c", size = 48066543 },+ { url = "https://files.pythonhosted.org/packages/84/e9/7878940a5b072e4f3bf998770acafeae13b267f9893af5f6d4ab3904b67e/pyarrow-22.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:4c19236ae2402a8663a2c8f21f1870a03cc57f0bef7e4b6eb3238cc82944de80", size = 50288838 },+ { url = "https://files.pythonhosted.org/packages/7b/03/f335d6c52b4a4761bcc83499789a1e2e16d9d201a58c327a9b5cc9a41bd9/pyarrow-22.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:0c34fe18094686194f204a3b1787a27456897d8a2d62caf84b61e8dfbc0252ae", size = 29185594 },+]++[[package]]+name = "pyceres"+version = "2.6"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/26/1d/8878c7752febb0f6716a7e1a52cb92ac98871c5aa522cba181878091607c/PyAudio-0.2.14.tar.gz", hash = "sha256:78dfff3879b4994d1f4fc6485646a57755c6ee3c19647a491f790a0895bd2f87", size = 47066 }+dependencies = [+ { name = "numpy" },+]wheels = [- { url = "https://files.pythonhosted.org/packages/7b/f0/b0eab89eafa70a86b7b566a4df2f94c7880a2d483aa8de1c77d335335b5b/PyAudio-0.2.14-cp311-cp311-win32.whl", hash = "sha256:506b32a595f8693811682ab4b127602d404df7dfc453b499c91a80d0f7bad289", size = 144624 },- { url = "https://files.pythonhosted.org/packages/82/d8/f043c854aad450a76e476b0cf9cda1956419e1dacf1062eb9df3c0055abe/PyAudio-0.2.14-cp311-cp311-win_amd64.whl", hash = "sha256:bbeb01d36a2f472ae5ee5e1451cacc42112986abe622f735bb870a5db77cf903", size = 164070 },- { url = "https://files.pythonhosted.org/packages/8d/45/8d2b76e8f6db783f9326c1305f3f816d4a12c8eda5edc6a2e1d03c097c3b/PyAudio-0.2.14-cp312-cp312-win32.whl", hash = "sha256:5fce4bcdd2e0e8c063d835dbe2860dac46437506af509353c7f8114d4bacbd5b", size = 144750 },- { url = "https://files.pythonhosted.org/packages/b0/6a/d25812e5f79f06285767ec607b39149d02aa3b31d50c2269768f48768930/PyAudio-0.2.14-cp312-cp312-win_amd64.whl", hash = "sha256:12f2f1ba04e06ff95d80700a78967897a489c05e093e3bffa05a84ed9c0a7fa3", size = 164126 },- { url = "https://files.pythonhosted.org/packages/3a/77/66cd37111a87c1589b63524f3d3c848011d21ca97828422c7fde7665ff0d/PyAudio-0.2.14-cp313-cp313-win32.whl", hash = "sha256:95328285b4dab57ea8c52a4a996cb52be6d629353315be5bfda403d15932a497", size = 150982 },- { url = "https://files.pythonhosted.org/packages/a5/8b/7f9a061c1cc2b230f9ac02a6003fcd14c85ce1828013aecbaf45aa988d20/PyAudio-0.2.14-cp313-cp313-win_amd64.whl", hash = "sha256:692d8c1446f52ed2662120bcd9ddcb5aa2b71f38bda31e58b19fb4672fffba69", size = 173655 },+ { url = "https://files.pythonhosted.org/packages/f9/a3/9519766129c8876f158ec4a8b8d65d1ae9ec03ac97c5cdd621b34d4f0331/pyceres-2.6-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:078ee92e6e9d98a20c030b52396248c41499ed5159342a9163cdfc2ab40e49c0", size = 2414855 },+ { url = "https://files.pythonhosted.org/packages/95/83/53617e96fca87bf01b8d27f9ab51b03c7ff5828cbed1102952c69b4eafbc/pyceres-2.6-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:294b16310be0f3024eb1c592d8df86bbb227b1443008a51cf01c47ac7c9d3eb2", size = 4931387 },+ { url = "https://files.pythonhosted.org/packages/ab/07/f4fb0fb6fa43a986cae009b3dae5ad6e5929786d7528dbdf92429e83c46f/pyceres-2.6-cp311-cp311-win_amd64.whl", hash = "sha256:66e8b8a69c926a01ae59f7aabf3812b1d8496434e22e064b23006335f3913084", size = 8454404 },+ { url = "https://files.pythonhosted.org/packages/b4/a7/bc1aaea0a2e06b35f1b856c95e0a392719d1395488e36ff87066dba09cc4/pyceres-2.6-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:8ef9014f84b31dbf94936f11964411f67e9cc1733aca8ff38fda079b890adfa7", size = 2420210 },+ { url = "https://files.pythonhosted.org/packages/dc/6d/bea6219072d8d86a5f11f6f61c588780be0bbd5aca1221fc8ad646bcba73/pyceres-2.6-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:284204c5303c582dc3918f43288e7b78bfc674a01e5561b252298a2d133ad14d", size = 4933829 },+ { url = "https://files.pythonhosted.org/packages/4c/4c/2291a63a81ddfa306ee18d57156a458758953933212f224ea3a7bb6b036c/pyceres-2.6-cp312-cp312-win_amd64.whl", hash = "sha256:c7e24463365778f423c34cd0e06ce57634a2e26da16935eec094c72263520493", size = 8457845 },+ { url = "https://files.pythonhosted.org/packages/7a/6d/9e55d8f6b1c504b2a5ac8220aa979e4d2c209be680a67cccb8e729cca34e/pyceres-2.6-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:8561fe1e520171499a606ca500baa5d3f90012dd264e9696fdd87126bed9378d", size = 2420311 },+ { url = "https://files.pythonhosted.org/packages/49/9a/17e371fbcbe29f1041a7014630bb7ff03c87215240b14362fe7e57bdef40/pyceres-2.6-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f5a408a205a690431190b21a4448130c67b838b14dfd459cee22361a06060a1f", size = 4933511 },+ { url = "https://files.pythonhosted.org/packages/1f/32/7588f22cc526abdef03414648eb7bedff5bd5353627f5646f988c2129687/pyceres-2.6-cp313-cp313-win_amd64.whl", hash = "sha256:c8da59494f317f38d8f7c3e980052997f4d5b01d456e440d964a38d09a26bdea", size = 8457867 },+ { url = "https://files.pythonhosted.org/packages/63/89/eaf73a99c4999452e1bb8c9369e477567abc58ff8ece636d20522683157b/pyceres-2.6-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:8759bfe308e2f951a7e1f0752b345856dc276300336bddaea9d35dd86f6d8c16", size = 2422877 },+ { url = "https://files.pythonhosted.org/packages/f7/08/25c45688d04b1a474ffba4726f219947afd36e02d925bc3387b4a9073bc1/pyceres-2.6-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0932b7cb21de92823bbc48c7bbb8c8df992c8a43498b99b64ee37293269ef3d0", size = 4934918 },+ { url = "https://files.pythonhosted.org/packages/f4/78/75487ad67101a0c1f2f727fa11020329a43a2ab628f85abbe59937c49c5b/pyceres-2.6-cp314-cp314-win_amd64.whl", hash = "sha256:e89d4d4d6c3507058a751c72b4dd4c59f6742a0a4262845b1ceafff65f943a2c", size = 8634720 },][[package]]name = "pycparser"-version = "2.22"+version = "2.23"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/1d/b2/31537cf4b1ca988837256c910a668b553fceb8f069bedc4b1c826024b52c/pycparser-2.22.tar.gz", hash = "sha256:491c8be9c040f5390f5bf44a5b07752bd07f56edf992381b05c701439eec10f6", size = 172736 }+sdist = { url = "https://files.pythonhosted.org/packages/fe/cf/d2d3b9f5699fb1e4615c8e32ff220203e43b248e1dfcc6736ad9057731ca/pycparser-2.23.tar.gz", hash = "sha256:78816d4f24add8f10a06d6f05b4d424ad9e96cfebf68a4ddc99c65c0720d00c2", size = 173734 }wheels = [- { url = "https://files.pythonhosted.org/packages/13/a3/a812df4e2dd5696d1f351d58b8fe16a405b234ad2886a0dab9183fb78109/pycparser-2.22-py3-none-any.whl", hash = "sha256:c3702b6d3dd8c7abc1afa565d7e63d53a1d0bd86cdc24edd75470f4de499cfcc", size = 117552 },+ { url = "https://files.pythonhosted.org/packages/a0/e3/59cd50310fc9b59512193629e1984c1f95e5c8ae6e5d8c69532ccc65a7fe/pycparser-2.23-py3-none-any.whl", hash = "sha256:e5c6e8d3fbad53479cab09ac03729e0a9faf2bee3db8208a550daf5af81a5934", size = 118140 },][[package]]name = "pydantic"-version = "2.11.7"+version = "2.12.4"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "annotated-types" },@@ -1135,74 +1401,106 @@ dependencies = [{ name = "typing-extensions" },{ name = "typing-inspection" },]-sdist = { url = "https://files.pythonhosted.org/packages/00/dd/4325abf92c39ba8623b5af936ddb36ffcfe0beae70405d456ab1fb2f5b8c/pydantic-2.11.7.tar.gz", hash = "sha256:d989c3c6cb79469287b1569f7447a17848c998458d49ebe294e975b9baf0f0db", size = 788350 }+sdist = { url = "https://files.pythonhosted.org/packages/96/ad/a17bc283d7d81837c061c49e3eaa27a45991759a1b7eae1031921c6bd924/pydantic-2.12.4.tar.gz", hash = "sha256:0f8cb9555000a4b5b617f66bfd2566264c4984b27589d3b845685983e8ea85ac", size = 821038 }wheels = [- { url = "https://files.pythonhosted.org/packages/6a/c0/ec2b1c8712ca690e5d61979dee872603e92b8a32f94cc1b72d53beab008a/pydantic-2.11.7-py3-none-any.whl", hash = "sha256:dde5df002701f6de26248661f6835bbe296a47bf73990135c7d07ce741b9623b", size = 444782 },+ { url = "https://files.pythonhosted.org/packages/82/2f/e68750da9b04856e2a7ec56fc6f034a5a79775e9b9a81882252789873798/pydantic-2.12.4-py3-none-any.whl", hash = "sha256:92d3d202a745d46f9be6df459ac5a064fdaa3c1c4cd8adcfa332ccf3c05f871e", size = 463400 },][[package]]name = "pydantic-core"-version = "2.33.2"+version = "2.41.5"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "typing-extensions" },]-sdist = { url = "https://files.pythonhosted.org/packages/ad/88/5f2260bdfae97aabf98f1778d43f69574390ad787afb646292a638c923d4/pydantic_core-2.33.2.tar.gz", hash = "sha256:7cb8bc3605c29176e1b105350d2e6474142d7c1bd1d9327c4a9bdb46bf827acc", size = 435195 }-wheels = [- { url = "https://files.pythonhosted.org/packages/3f/8d/71db63483d518cbbf290261a1fc2839d17ff89fce7089e08cad07ccfce67/pydantic_core-2.33.2-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:4c5b0a576fb381edd6d27f0a85915c6daf2f8138dc5c267a57c08a62900758c7", size = 2028584 },- { url = "https://files.pythonhosted.org/packages/24/2f/3cfa7244ae292dd850989f328722d2aef313f74ffc471184dc509e1e4e5a/pydantic_core-2.33.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e799c050df38a639db758c617ec771fd8fb7a5f8eaaa4b27b101f266b216a246", size = 1855071 },- { url = "https://files.pythonhosted.org/packages/b3/d3/4ae42d33f5e3f50dd467761304be2fa0a9417fbf09735bc2cce003480f2a/pydantic_core-2.33.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dc46a01bf8d62f227d5ecee74178ffc448ff4e5197c756331f71efcc66dc980f", size = 1897823 },- { url = "https://files.pythonhosted.org/packages/f4/f3/aa5976e8352b7695ff808599794b1fba2a9ae2ee954a3426855935799488/pydantic_core-2.33.2-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a144d4f717285c6d9234a66778059f33a89096dfb9b39117663fd8413d582dcc", size = 1983792 },- { url = "https://files.pythonhosted.org/packages/d5/7a/cda9b5a23c552037717f2b2a5257e9b2bfe45e687386df9591eff7b46d28/pydantic_core-2.33.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:73cf6373c21bc80b2e0dc88444f41ae60b2f070ed02095754eb5a01df12256de", size = 2136338 },- { url = "https://files.pythonhosted.org/packages/2b/9f/b8f9ec8dd1417eb9da784e91e1667d58a2a4a7b7b34cf4af765ef663a7e5/pydantic_core-2.33.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:3dc625f4aa79713512d1976fe9f0bc99f706a9dee21dfd1810b4bbbf228d0e8a", size = 2730998 },- { url = "https://files.pythonhosted.org/packages/47/bc/cd720e078576bdb8255d5032c5d63ee5c0bf4b7173dd955185a1d658c456/pydantic_core-2.33.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:881b21b5549499972441da4758d662aeea93f1923f953e9cbaff14b8b9565aef", size = 2003200 },- { url = "https://files.pythonhosted.org/packages/ca/22/3602b895ee2cd29d11a2b349372446ae9727c32e78a94b3d588a40fdf187/pydantic_core-2.33.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:bdc25f3681f7b78572699569514036afe3c243bc3059d3942624e936ec93450e", size = 2113890 },- { url = "https://files.pythonhosted.org/packages/ff/e6/e3c5908c03cf00d629eb38393a98fccc38ee0ce8ecce32f69fc7d7b558a7/pydantic_core-2.33.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:fe5b32187cbc0c862ee201ad66c30cf218e5ed468ec8dc1cf49dec66e160cc4d", size = 2073359 },- { url = "https://files.pythonhosted.org/packages/12/e7/6a36a07c59ebefc8777d1ffdaf5ae71b06b21952582e4b07eba88a421c79/pydantic_core-2.33.2-cp311-cp311-musllinux_1_1_armv7l.whl", hash = "sha256:bc7aee6f634a6f4a95676fcb5d6559a2c2a390330098dba5e5a5f28a2e4ada30", size = 2245883 },- { url = "https://files.pythonhosted.org/packages/16/3f/59b3187aaa6cc0c1e6616e8045b284de2b6a87b027cce2ffcea073adf1d2/pydantic_core-2.33.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:235f45e5dbcccf6bd99f9f472858849f73d11120d76ea8707115415f8e5ebebf", size = 2241074 },- { url = "https://files.pythonhosted.org/packages/e0/ed/55532bb88f674d5d8f67ab121a2a13c385df382de2a1677f30ad385f7438/pydantic_core-2.33.2-cp311-cp311-win32.whl", hash = "sha256:6368900c2d3ef09b69cb0b913f9f8263b03786e5b2a387706c5afb66800efd51", size = 1910538 },- { url = "https://files.pythonhosted.org/packages/fe/1b/25b7cccd4519c0b23c2dd636ad39d381abf113085ce4f7bec2b0dc755eb1/pydantic_core-2.33.2-cp311-cp311-win_amd64.whl", hash = "sha256:1e063337ef9e9820c77acc768546325ebe04ee38b08703244c1309cccc4f1bab", size = 1952909 },- { url = "https://files.pythonhosted.org/packages/49/a9/d809358e49126438055884c4366a1f6227f0f84f635a9014e2deb9b9de54/pydantic_core-2.33.2-cp311-cp311-win_arm64.whl", hash = "sha256:6b99022f1d19bc32a4c2a0d544fc9a76e3be90f0b3f4af413f87d38749300e65", size = 1897786 },- { url = "https://files.pythonhosted.org/packages/18/8a/2b41c97f554ec8c71f2a8a5f85cb56a8b0956addfe8b0efb5b3d77e8bdc3/pydantic_core-2.33.2-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:a7ec89dc587667f22b6a0b6579c249fca9026ce7c333fc142ba42411fa243cdc", size = 2009000 },- { url = "https://files.pythonhosted.org/packages/a1/02/6224312aacb3c8ecbaa959897af57181fb6cf3a3d7917fd44d0f2917e6f2/pydantic_core-2.33.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3c6db6e52c6d70aa0d00d45cdb9b40f0433b96380071ea80b09277dba021ddf7", size = 1847996 },- { url = "https://files.pythonhosted.org/packages/d6/46/6dcdf084a523dbe0a0be59d054734b86a981726f221f4562aed313dbcb49/pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4e61206137cbc65e6d5256e1166f88331d3b6238e082d9f74613b9b765fb9025", size = 1880957 },- { url = "https://files.pythonhosted.org/packages/ec/6b/1ec2c03837ac00886ba8160ce041ce4e325b41d06a034adbef11339ae422/pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:eb8c529b2819c37140eb51b914153063d27ed88e3bdc31b71198a198e921e011", size = 1964199 },- { url = "https://files.pythonhosted.org/packages/2d/1d/6bf34d6adb9debd9136bd197ca72642203ce9aaaa85cfcbfcf20f9696e83/pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c52b02ad8b4e2cf14ca7b3d918f3eb0ee91e63b3167c32591e57c4317e134f8f", size = 2120296 },- { url = "https://files.pythonhosted.org/packages/e0/94/2bd0aaf5a591e974b32a9f7123f16637776c304471a0ab33cf263cf5591a/pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:96081f1605125ba0855dfda83f6f3df5ec90c61195421ba72223de35ccfb2f88", size = 2676109 },- { url = "https://files.pythonhosted.org/packages/f9/41/4b043778cf9c4285d59742281a769eac371b9e47e35f98ad321349cc5d61/pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8f57a69461af2a5fa6e6bbd7a5f60d3b7e6cebb687f55106933188e79ad155c1", size = 2002028 },- { url = "https://files.pythonhosted.org/packages/cb/d5/7bb781bf2748ce3d03af04d5c969fa1308880e1dca35a9bd94e1a96a922e/pydantic_core-2.33.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:572c7e6c8bb4774d2ac88929e3d1f12bc45714ae5ee6d9a788a9fb35e60bb04b", size = 2100044 },- { url = "https://files.pythonhosted.org/packages/fe/36/def5e53e1eb0ad896785702a5bbfd25eed546cdcf4087ad285021a90ed53/pydantic_core-2.33.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:db4b41f9bd95fbe5acd76d89920336ba96f03e149097365afe1cb092fceb89a1", size = 2058881 },- { url = "https://files.pythonhosted.org/packages/01/6c/57f8d70b2ee57fc3dc8b9610315949837fa8c11d86927b9bb044f8705419/pydantic_core-2.33.2-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:fa854f5cf7e33842a892e5c73f45327760bc7bc516339fda888c75ae60edaeb6", size = 2227034 },- { url = "https://files.pythonhosted.org/packages/27/b9/9c17f0396a82b3d5cbea4c24d742083422639e7bb1d5bf600e12cb176a13/pydantic_core-2.33.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:5f483cfb75ff703095c59e365360cb73e00185e01aaea067cd19acffd2ab20ea", size = 2234187 },- { url = "https://files.pythonhosted.org/packages/b0/6a/adf5734ffd52bf86d865093ad70b2ce543415e0e356f6cacabbc0d9ad910/pydantic_core-2.33.2-cp312-cp312-win32.whl", hash = "sha256:9cb1da0f5a471435a7bc7e439b8a728e8b61e59784b2af70d7c169f8dd8ae290", size = 1892628 },- { url = "https://files.pythonhosted.org/packages/43/e4/5479fecb3606c1368d496a825d8411e126133c41224c1e7238be58b87d7e/pydantic_core-2.33.2-cp312-cp312-win_amd64.whl", hash = "sha256:f941635f2a3d96b2973e867144fde513665c87f13fe0e193c158ac51bfaaa7b2", size = 1955866 },- { url = "https://files.pythonhosted.org/packages/0d/24/8b11e8b3e2be9dd82df4b11408a67c61bb4dc4f8e11b5b0fc888b38118b5/pydantic_core-2.33.2-cp312-cp312-win_arm64.whl", hash = "sha256:cca3868ddfaccfbc4bfb1d608e2ccaaebe0ae628e1416aeb9c4d88c001bb45ab", size = 1888894 },- { url = "https://files.pythonhosted.org/packages/46/8c/99040727b41f56616573a28771b1bfa08a3d3fe74d3d513f01251f79f172/pydantic_core-2.33.2-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:1082dd3e2d7109ad8b7da48e1d4710c8d06c253cbc4a27c1cff4fbcaa97a9e3f", size = 2015688 },- { url = "https://files.pythonhosted.org/packages/3a/cc/5999d1eb705a6cefc31f0b4a90e9f7fc400539b1a1030529700cc1b51838/pydantic_core-2.33.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f517ca031dfc037a9c07e748cefd8d96235088b83b4f4ba8939105d20fa1dcd6", size = 1844808 },- { url = "https://files.pythonhosted.org/packages/6f/5e/a0a7b8885c98889a18b6e376f344da1ef323d270b44edf8174d6bce4d622/pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a9f2c9dd19656823cb8250b0724ee9c60a82f3cdf68a080979d13092a3b0fef", size = 1885580 },- { url = "https://files.pythonhosted.org/packages/3b/2a/953581f343c7d11a304581156618c3f592435523dd9d79865903272c256a/pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:2b0a451c263b01acebe51895bfb0e1cc842a5c666efe06cdf13846c7418caa9a", size = 1973859 },- { url = "https://files.pythonhosted.org/packages/e6/55/f1a813904771c03a3f97f676c62cca0c0a4138654107c1b61f19c644868b/pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1ea40a64d23faa25e62a70ad163571c0b342b8bf66d5fa612ac0dec4f069d916", size = 2120810 },- { url = "https://files.pythonhosted.org/packages/aa/c3/053389835a996e18853ba107a63caae0b9deb4a276c6b472931ea9ae6e48/pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0fb2d542b4d66f9470e8065c5469ec676978d625a8b7a363f07d9a501a9cb36a", size = 2676498 },- { url = "https://files.pythonhosted.org/packages/eb/3c/f4abd740877a35abade05e437245b192f9d0ffb48bbbbd708df33d3cda37/pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9fdac5d6ffa1b5a83bca06ffe7583f5576555e6c8b3a91fbd25ea7780f825f7d", size = 2000611 },- { url = "https://files.pythonhosted.org/packages/59/a7/63ef2fed1837d1121a894d0ce88439fe3e3b3e48c7543b2a4479eb99c2bd/pydantic_core-2.33.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:04a1a413977ab517154eebb2d326da71638271477d6ad87a769102f7c2488c56", size = 2107924 },- { url = "https://files.pythonhosted.org/packages/04/8f/2551964ef045669801675f1cfc3b0d74147f4901c3ffa42be2ddb1f0efc4/pydantic_core-2.33.2-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:c8e7af2f4e0194c22b5b37205bfb293d166a7344a5b0d0eaccebc376546d77d5", size = 2063196 },- { url = "https://files.pythonhosted.org/packages/26/bd/d9602777e77fc6dbb0c7db9ad356e9a985825547dce5ad1d30ee04903918/pydantic_core-2.33.2-cp313-cp313-musllinux_1_1_armv7l.whl", hash = "sha256:5c92edd15cd58b3c2d34873597a1e20f13094f59cf88068adb18947df5455b4e", size = 2236389 },- { url = "https://files.pythonhosted.org/packages/42/db/0e950daa7e2230423ab342ae918a794964b053bec24ba8af013fc7c94846/pydantic_core-2.33.2-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:65132b7b4a1c0beded5e057324b7e16e10910c106d43675d9bd87d4f38dde162", size = 2239223 },- { url = "https://files.pythonhosted.org/packages/58/4d/4f937099c545a8a17eb52cb67fe0447fd9a373b348ccfa9a87f141eeb00f/pydantic_core-2.33.2-cp313-cp313-win32.whl", hash = "sha256:52fb90784e0a242bb96ec53f42196a17278855b0f31ac7c3cc6f5c1ec4811849", size = 1900473 },- { url = "https://files.pythonhosted.org/packages/a0/75/4a0a9bac998d78d889def5e4ef2b065acba8cae8c93696906c3a91f310ca/pydantic_core-2.33.2-cp313-cp313-win_amd64.whl", hash = "sha256:c083a3bdd5a93dfe480f1125926afcdbf2917ae714bdb80b36d34318b2bec5d9", size = 1955269 },- { url = "https://files.pythonhosted.org/packages/f9/86/1beda0576969592f1497b4ce8e7bc8cbdf614c352426271b1b10d5f0aa64/pydantic_core-2.33.2-cp313-cp313-win_arm64.whl", hash = "sha256:e80b087132752f6b3d714f041ccf74403799d3b23a72722ea2e6ba2e892555b9", size = 1893921 },- { url = "https://files.pythonhosted.org/packages/a4/7d/e09391c2eebeab681df2b74bfe6c43422fffede8dc74187b2b0bf6fd7571/pydantic_core-2.33.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:61c18fba8e5e9db3ab908620af374db0ac1baa69f0f32df4f61ae23f15e586ac", size = 1806162 },- { url = "https://files.pythonhosted.org/packages/f1/3d/847b6b1fed9f8ed3bb95a9ad04fbd0b212e832d4f0f50ff4d9ee5a9f15cf/pydantic_core-2.33.2-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:95237e53bb015f67b63c91af7518a62a8660376a6a0db19b89acc77a4d6199f5", size = 1981560 },- { url = "https://files.pythonhosted.org/packages/6f/9a/e73262f6c6656262b5fdd723ad90f518f579b7bc8622e43a942eec53c938/pydantic_core-2.33.2-cp313-cp313t-win_amd64.whl", hash = "sha256:c2fc0a768ef76c15ab9238afa6da7f69895bb5d1ee83aeea2e3509af4472d0b9", size = 1935777 },- { url = "https://files.pythonhosted.org/packages/7b/27/d4ae6487d73948d6f20dddcd94be4ea43e74349b56eba82e9bdee2d7494c/pydantic_core-2.33.2-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:dd14041875d09cc0f9308e37a6f8b65f5585cf2598a53aa0123df8b129d481f8", size = 2025200 },- { url = "https://files.pythonhosted.org/packages/f1/b8/b3cb95375f05d33801024079b9392a5ab45267a63400bf1866e7ce0f0de4/pydantic_core-2.33.2-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:d87c561733f66531dced0da6e864f44ebf89a8fba55f31407b00c2f7f9449593", size = 1859123 },- { url = "https://files.pythonhosted.org/packages/05/bc/0d0b5adeda59a261cd30a1235a445bf55c7e46ae44aea28f7bd6ed46e091/pydantic_core-2.33.2-pp311-pypy311_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2f82865531efd18d6e07a04a17331af02cb7a651583c418df8266f17a63c6612", size = 1892852 },- { url = "https://files.pythonhosted.org/packages/3e/11/d37bdebbda2e449cb3f519f6ce950927b56d62f0b84fd9cb9e372a26a3d5/pydantic_core-2.33.2-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2bfb5112df54209d820d7bf9317c7a6c9025ea52e49f46b6a2060104bba37de7", size = 2067484 },- { url = "https://files.pythonhosted.org/packages/8c/55/1f95f0a05ce72ecb02a8a8a1c3be0579bbc29b1d5ab68f1378b7bebc5057/pydantic_core-2.33.2-pp311-pypy311_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:64632ff9d614e5eecfb495796ad51b0ed98c453e447a76bcbeeb69615079fc7e", size = 2108896 },- { url = "https://files.pythonhosted.org/packages/53/89/2b2de6c81fa131f423246a9109d7b2a375e83968ad0800d6e57d0574629b/pydantic_core-2.33.2-pp311-pypy311_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:f889f7a40498cc077332c7ab6b4608d296d852182211787d4f3ee377aaae66e8", size = 2069475 },- { url = "https://files.pythonhosted.org/packages/b8/e9/1f7efbe20d0b2b10f6718944b5d8ece9152390904f29a78e68d4e7961159/pydantic_core-2.33.2-pp311-pypy311_pp73-musllinux_1_1_armv7l.whl", hash = "sha256:de4b83bb311557e439b9e186f733f6c645b9417c84e2eb8203f3f820a4b988bf", size = 2239013 },- { url = "https://files.pythonhosted.org/packages/3c/b2/5309c905a93811524a49b4e031e9851a6b00ff0fb668794472ea7746b448/pydantic_core-2.33.2-pp311-pypy311_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:82f68293f055f51b51ea42fafc74b6aad03e70e191799430b90c13d643059ebb", size = 2238715 },- { url = "https://files.pythonhosted.org/packages/32/56/8a7ca5d2cd2cda1d245d34b1c9a942920a718082ae8e54e5f3e5a58b7add/pydantic_core-2.33.2-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:329467cecfb529c925cf2bbd4d60d2c509bc2fb52a20c1045bf09bb70971a9c1", size = 2066757 },+sdist = { url = "https://files.pythonhosted.org/packages/71/70/23b021c950c2addd24ec408e9ab05d59b035b39d97cdc1130e1bce647bb6/pydantic_core-2.41.5.tar.gz", hash = "sha256:08daa51ea16ad373ffd5e7606252cc32f07bc72b28284b6bc9c6df804816476e", size = 460952 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/e8/72/74a989dd9f2084b3d9530b0915fdda64ac48831c30dbf7c72a41a5232db8/pydantic_core-2.41.5-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:a3a52f6156e73e7ccb0f8cced536adccb7042be67cb45f9562e12b319c119da6", size = 2105873 },+ { url = "https://files.pythonhosted.org/packages/12/44/37e403fd9455708b3b942949e1d7febc02167662bf1a7da5b78ee1ea2842/pydantic_core-2.41.5-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7f3bf998340c6d4b0c9a2f02d6a400e51f123b59565d74dc60d252ce888c260b", size = 1899826 },+ { url = "https://files.pythonhosted.org/packages/33/7f/1d5cab3ccf44c1935a359d51a8a2a9e1a654b744b5e7f80d41b88d501eec/pydantic_core-2.41.5-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:378bec5c66998815d224c9ca994f1e14c0c21cb95d2f52b6021cc0b2a58f2a5a", size = 1917869 },+ { url = "https://files.pythonhosted.org/packages/6e/6a/30d94a9674a7fe4f4744052ed6c5e083424510be1e93da5bc47569d11810/pydantic_core-2.41.5-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:e7b576130c69225432866fe2f4a469a85a54ade141d96fd396dffcf607b558f8", size = 2063890 },+ { url = "https://files.pythonhosted.org/packages/50/be/76e5d46203fcb2750e542f32e6c371ffa9b8ad17364cf94bb0818dbfb50c/pydantic_core-2.41.5-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6cb58b9c66f7e4179a2d5e0f849c48eff5c1fca560994d6eb6543abf955a149e", size = 2229740 },+ { url = "https://files.pythonhosted.org/packages/d3/ee/fed784df0144793489f87db310a6bbf8118d7b630ed07aa180d6067e653a/pydantic_core-2.41.5-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:88942d3a3dff3afc8288c21e565e476fc278902ae4d6d134f1eeda118cc830b1", size = 2350021 },+ { url = "https://files.pythonhosted.org/packages/c8/be/8fed28dd0a180dca19e72c233cbf58efa36df055e5b9d90d64fd1740b828/pydantic_core-2.41.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f31d95a179f8d64d90f6831d71fa93290893a33148d890ba15de25642c5d075b", size = 2066378 },+ { url = "https://files.pythonhosted.org/packages/b0/3b/698cf8ae1d536a010e05121b4958b1257f0b5522085e335360e53a6b1c8b/pydantic_core-2.41.5-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:c1df3d34aced70add6f867a8cf413e299177e0c22660cc767218373d0779487b", size = 2175761 },+ { url = "https://files.pythonhosted.org/packages/b8/ba/15d537423939553116dea94ce02f9c31be0fa9d0b806d427e0308ec17145/pydantic_core-2.41.5-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:4009935984bd36bd2c774e13f9a09563ce8de4abaa7226f5108262fa3e637284", size = 2146303 },+ { url = "https://files.pythonhosted.org/packages/58/7f/0de669bf37d206723795f9c90c82966726a2ab06c336deba4735b55af431/pydantic_core-2.41.5-cp311-cp311-musllinux_1_1_armv7l.whl", hash = "sha256:34a64bc3441dc1213096a20fe27e8e128bd3ff89921706e83c0b1ac971276594", size = 2340355 },+ { url = "https://files.pythonhosted.org/packages/e5/de/e7482c435b83d7e3c3ee5ee4451f6e8973cff0eb6007d2872ce6383f6398/pydantic_core-2.41.5-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:c9e19dd6e28fdcaa5a1de679aec4141f691023916427ef9bae8584f9c2fb3b0e", size = 2319875 },+ { url = "https://files.pythonhosted.org/packages/fe/e6/8c9e81bb6dd7560e33b9053351c29f30c8194b72f2d6932888581f503482/pydantic_core-2.41.5-cp311-cp311-win32.whl", hash = "sha256:2c010c6ded393148374c0f6f0bf89d206bf3217f201faa0635dcd56bd1520f6b", size = 1987549 },+ { url = "https://files.pythonhosted.org/packages/11/66/f14d1d978ea94d1bc21fc98fcf570f9542fe55bfcc40269d4e1a21c19bf7/pydantic_core-2.41.5-cp311-cp311-win_amd64.whl", hash = "sha256:76ee27c6e9c7f16f47db7a94157112a2f3a00e958bc626e2f4ee8bec5c328fbe", size = 2011305 },+ { url = "https://files.pythonhosted.org/packages/56/d8/0e271434e8efd03186c5386671328154ee349ff0354d83c74f5caaf096ed/pydantic_core-2.41.5-cp311-cp311-win_arm64.whl", hash = "sha256:4bc36bbc0b7584de96561184ad7f012478987882ebf9f9c389b23f432ea3d90f", size = 1972902 },+ { url = "https://files.pythonhosted.org/packages/5f/5d/5f6c63eebb5afee93bcaae4ce9a898f3373ca23df3ccaef086d0233a35a7/pydantic_core-2.41.5-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:f41a7489d32336dbf2199c8c0a215390a751c5b014c2c1c5366e817202e9cdf7", size = 2110990 },+ { url = "https://files.pythonhosted.org/packages/aa/32/9c2e8ccb57c01111e0fd091f236c7b371c1bccea0fa85247ac55b1e2b6b6/pydantic_core-2.41.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:070259a8818988b9a84a449a2a7337c7f430a22acc0859c6b110aa7212a6d9c0", size = 1896003 },+ { url = "https://files.pythonhosted.org/packages/68/b8/a01b53cb0e59139fbc9e4fda3e9724ede8de279097179be4ff31f1abb65a/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e96cea19e34778f8d59fe40775a7a574d95816eb150850a85a7a4c8f4b94ac69", size = 1919200 },+ { url = "https://files.pythonhosted.org/packages/38/de/8c36b5198a29bdaade07b5985e80a233a5ac27137846f3bc2d3b40a47360/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:ed2e99c456e3fadd05c991f8f437ef902e00eedf34320ba2b0842bd1c3ca3a75", size = 2052578 },+ { url = "https://files.pythonhosted.org/packages/00/b5/0e8e4b5b081eac6cb3dbb7e60a65907549a1ce035a724368c330112adfdd/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:65840751b72fbfd82c3c640cff9284545342a4f1eb1586ad0636955b261b0b05", size = 2208504 },+ { url = "https://files.pythonhosted.org/packages/77/56/87a61aad59c7c5b9dc8caad5a41a5545cba3810c3e828708b3d7404f6cef/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e536c98a7626a98feb2d3eaf75944ef6f3dbee447e1f841eae16f2f0a72d8ddc", size = 2335816 },+ { url = "https://files.pythonhosted.org/packages/0d/76/941cc9f73529988688a665a5c0ecff1112b3d95ab48f81db5f7606f522d3/pydantic_core-2.41.5-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eceb81a8d74f9267ef4081e246ffd6d129da5d87e37a77c9bde550cb04870c1c", size = 2075366 },+ { url = "https://files.pythonhosted.org/packages/d3/43/ebef01f69baa07a482844faaa0a591bad1ef129253ffd0cdaa9d8a7f72d3/pydantic_core-2.41.5-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d38548150c39b74aeeb0ce8ee1d8e82696f4a4e16ddc6de7b1d8823f7de4b9b5", size = 2171698 },+ { url = "https://files.pythonhosted.org/packages/b1/87/41f3202e4193e3bacfc2c065fab7706ebe81af46a83d3e27605029c1f5a6/pydantic_core-2.41.5-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:c23e27686783f60290e36827f9c626e63154b82b116d7fe9adba1fda36da706c", size = 2132603 },+ { url = "https://files.pythonhosted.org/packages/49/7d/4c00df99cb12070b6bccdef4a195255e6020a550d572768d92cc54dba91a/pydantic_core-2.41.5-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:482c982f814460eabe1d3bb0adfdc583387bd4691ef00b90575ca0d2b6fe2294", size = 2329591 },+ { url = "https://files.pythonhosted.org/packages/cc/6a/ebf4b1d65d458f3cda6a7335d141305dfa19bdc61140a884d165a8a1bbc7/pydantic_core-2.41.5-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:bfea2a5f0b4d8d43adf9d7b8bf019fb46fdd10a2e5cde477fbcb9d1fa08c68e1", size = 2319068 },+ { url = "https://files.pythonhosted.org/packages/49/3b/774f2b5cd4192d5ab75870ce4381fd89cf218af999515baf07e7206753f0/pydantic_core-2.41.5-cp312-cp312-win32.whl", hash = "sha256:b74557b16e390ec12dca509bce9264c3bbd128f8a2c376eaa68003d7f327276d", size = 1985908 },+ { url = "https://files.pythonhosted.org/packages/86/45/00173a033c801cacf67c190fef088789394feaf88a98a7035b0e40d53dc9/pydantic_core-2.41.5-cp312-cp312-win_amd64.whl", hash = "sha256:1962293292865bca8e54702b08a4f26da73adc83dd1fcf26fbc875b35d81c815", size = 2020145 },+ { url = "https://files.pythonhosted.org/packages/f9/22/91fbc821fa6d261b376a3f73809f907cec5ca6025642c463d3488aad22fb/pydantic_core-2.41.5-cp312-cp312-win_arm64.whl", hash = "sha256:1746d4a3d9a794cacae06a5eaaccb4b8643a131d45fbc9af23e353dc0a5ba5c3", size = 1976179 },+ { url = "https://files.pythonhosted.org/packages/87/06/8806241ff1f70d9939f9af039c6c35f2360cf16e93c2ca76f184e76b1564/pydantic_core-2.41.5-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:941103c9be18ac8daf7b7adca8228f8ed6bb7a1849020f643b3a14d15b1924d9", size = 2120403 },+ { url = "https://files.pythonhosted.org/packages/94/02/abfa0e0bda67faa65fef1c84971c7e45928e108fe24333c81f3bfe35d5f5/pydantic_core-2.41.5-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:112e305c3314f40c93998e567879e887a3160bb8689ef3d2c04b6cc62c33ac34", size = 1896206 },+ { url = "https://files.pythonhosted.org/packages/15/df/a4c740c0943e93e6500f9eb23f4ca7ec9bf71b19e608ae5b579678c8d02f/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0cbaad15cb0c90aa221d43c00e77bb33c93e8d36e0bf74760cd00e732d10a6a0", size = 1919307 },+ { url = "https://files.pythonhosted.org/packages/9a/e3/6324802931ae1d123528988e0e86587c2072ac2e5394b4bc2bc34b61ff6e/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:03ca43e12fab6023fc79d28ca6b39b05f794ad08ec2feccc59a339b02f2b3d33", size = 2063258 },+ { url = "https://files.pythonhosted.org/packages/c9/d4/2230d7151d4957dd79c3044ea26346c148c98fbf0ee6ebd41056f2d62ab5/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:dc799088c08fa04e43144b164feb0c13f9a0bc40503f8df3e9fde58a3c0c101e", size = 2214917 },+ { url = "https://files.pythonhosted.org/packages/e6/9f/eaac5df17a3672fef0081b6c1bb0b82b33ee89aa5cec0d7b05f52fd4a1fa/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:97aeba56665b4c3235a0e52b2c2f5ae9cd071b8a8310ad27bddb3f7fb30e9aa2", size = 2332186 },+ { url = "https://files.pythonhosted.org/packages/cf/4e/35a80cae583a37cf15604b44240e45c05e04e86f9cfd766623149297e971/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:406bf18d345822d6c21366031003612b9c77b3e29ffdb0f612367352aab7d586", size = 2073164 },+ { url = "https://files.pythonhosted.org/packages/bf/e3/f6e262673c6140dd3305d144d032f7bd5f7497d3871c1428521f19f9efa2/pydantic_core-2.41.5-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:b93590ae81f7010dbe380cdeab6f515902ebcbefe0b9327cc4804d74e93ae69d", size = 2179146 },+ { url = "https://files.pythonhosted.org/packages/75/c7/20bd7fc05f0c6ea2056a4565c6f36f8968c0924f19b7d97bbfea55780e73/pydantic_core-2.41.5-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:01a3d0ab748ee531f4ea6c3e48ad9dac84ddba4b0d82291f87248f2f9de8d740", size = 2137788 },+ { url = "https://files.pythonhosted.org/packages/3a/8d/34318ef985c45196e004bc46c6eab2eda437e744c124ef0dbe1ff2c9d06b/pydantic_core-2.41.5-cp313-cp313-musllinux_1_1_armv7l.whl", hash = "sha256:6561e94ba9dacc9c61bce40e2d6bdc3bfaa0259d3ff36ace3b1e6901936d2e3e", size = 2340133 },+ { url = "https://files.pythonhosted.org/packages/9c/59/013626bf8c78a5a5d9350d12e7697d3d4de951a75565496abd40ccd46bee/pydantic_core-2.41.5-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:915c3d10f81bec3a74fbd4faebe8391013ba61e5a1a8d48c4455b923bdda7858", size = 2324852 },+ { url = "https://files.pythonhosted.org/packages/1a/d9/c248c103856f807ef70c18a4f986693a46a8ffe1602e5d361485da502d20/pydantic_core-2.41.5-cp313-cp313-win32.whl", hash = "sha256:650ae77860b45cfa6e2cdafc42618ceafab3a2d9a3811fcfbd3bbf8ac3c40d36", size = 1994679 },+ { url = "https://files.pythonhosted.org/packages/9e/8b/341991b158ddab181cff136acd2552c9f35bd30380422a639c0671e99a91/pydantic_core-2.41.5-cp313-cp313-win_amd64.whl", hash = "sha256:79ec52ec461e99e13791ec6508c722742ad745571f234ea6255bed38c6480f11", size = 2019766 },+ { url = "https://files.pythonhosted.org/packages/73/7d/f2f9db34af103bea3e09735bb40b021788a5e834c81eedb541991badf8f5/pydantic_core-2.41.5-cp313-cp313-win_arm64.whl", hash = "sha256:3f84d5c1b4ab906093bdc1ff10484838aca54ef08de4afa9de0f5f14d69639cd", size = 1981005 },+ { url = "https://files.pythonhosted.org/packages/ea/28/46b7c5c9635ae96ea0fbb779e271a38129df2550f763937659ee6c5dbc65/pydantic_core-2.41.5-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:3f37a19d7ebcdd20b96485056ba9e8b304e27d9904d233d7b1015db320e51f0a", size = 2119622 },+ { url = "https://files.pythonhosted.org/packages/74/1a/145646e5687e8d9a1e8d09acb278c8535ebe9e972e1f162ed338a622f193/pydantic_core-2.41.5-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1d1d9764366c73f996edd17abb6d9d7649a7eb690006ab6adbda117717099b14", size = 1891725 },+ { url = "https://files.pythonhosted.org/packages/23/04/e89c29e267b8060b40dca97bfc64a19b2a3cf99018167ea1677d96368273/pydantic_core-2.41.5-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:25e1c2af0fce638d5f1988b686f3b3ea8cd7de5f244ca147c777769e798a9cd1", size = 1915040 },+ { url = "https://files.pythonhosted.org/packages/84/a3/15a82ac7bd97992a82257f777b3583d3e84bdb06ba6858f745daa2ec8a85/pydantic_core-2.41.5-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:506d766a8727beef16b7adaeb8ee6217c64fc813646b424d0804d67c16eddb66", size = 2063691 },+ { url = "https://files.pythonhosted.org/packages/74/9b/0046701313c6ef08c0c1cf0e028c67c770a4e1275ca73131563c5f2a310a/pydantic_core-2.41.5-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4819fa52133c9aa3c387b3328f25c1facc356491e6135b459f1de698ff64d869", size = 2213897 },+ { url = "https://files.pythonhosted.org/packages/8a/cd/6bac76ecd1b27e75a95ca3a9a559c643b3afcd2dd62086d4b7a32a18b169/pydantic_core-2.41.5-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:2b761d210c9ea91feda40d25b4efe82a1707da2ef62901466a42492c028553a2", size = 2333302 },+ { url = "https://files.pythonhosted.org/packages/4c/d2/ef2074dc020dd6e109611a8be4449b98cd25e1b9b8a303c2f0fca2f2bcf7/pydantic_core-2.41.5-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:22f0fb8c1c583a3b6f24df2470833b40207e907b90c928cc8d3594b76f874375", size = 2064877 },+ { url = "https://files.pythonhosted.org/packages/18/66/e9db17a9a763d72f03de903883c057b2592c09509ccfe468187f2a2eef29/pydantic_core-2.41.5-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:2782c870e99878c634505236d81e5443092fba820f0373997ff75f90f68cd553", size = 2180680 },+ { url = "https://files.pythonhosted.org/packages/d3/9e/3ce66cebb929f3ced22be85d4c2399b8e85b622db77dad36b73c5387f8f8/pydantic_core-2.41.5-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:0177272f88ab8312479336e1d777f6b124537d47f2123f89cb37e0accea97f90", size = 2138960 },+ { url = "https://files.pythonhosted.org/packages/a6/62/205a998f4327d2079326b01abee48e502ea739d174f0a89295c481a2272e/pydantic_core-2.41.5-cp314-cp314-musllinux_1_1_armv7l.whl", hash = "sha256:63510af5e38f8955b8ee5687740d6ebf7c2a0886d15a6d65c32814613681bc07", size = 2339102 },+ { url = "https://files.pythonhosted.org/packages/3c/0d/f05e79471e889d74d3d88f5bd20d0ed189ad94c2423d81ff8d0000aab4ff/pydantic_core-2.41.5-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:e56ba91f47764cc14f1daacd723e3e82d1a89d783f0f5afe9c364b8bb491ccdb", size = 2326039 },+ { url = "https://files.pythonhosted.org/packages/ec/e1/e08a6208bb100da7e0c4b288eed624a703f4d129bde2da475721a80cab32/pydantic_core-2.41.5-cp314-cp314-win32.whl", hash = "sha256:aec5cf2fd867b4ff45b9959f8b20ea3993fc93e63c7363fe6851424c8a7e7c23", size = 1995126 },+ { url = "https://files.pythonhosted.org/packages/48/5d/56ba7b24e9557f99c9237e29f5c09913c81eeb2f3217e40e922353668092/pydantic_core-2.41.5-cp314-cp314-win_amd64.whl", hash = "sha256:8e7c86f27c585ef37c35e56a96363ab8de4e549a95512445b85c96d3e2f7c1bf", size = 2015489 },+ { url = "https://files.pythonhosted.org/packages/4e/bb/f7a190991ec9e3e0ba22e4993d8755bbc4a32925c0b5b42775c03e8148f9/pydantic_core-2.41.5-cp314-cp314-win_arm64.whl", hash = "sha256:e672ba74fbc2dc8eea59fb6d4aed6845e6905fc2a8afe93175d94a83ba2a01a0", size = 1977288 },+ { url = "https://files.pythonhosted.org/packages/92/ed/77542d0c51538e32e15afe7899d79efce4b81eee631d99850edc2f5e9349/pydantic_core-2.41.5-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:8566def80554c3faa0e65ac30ab0932b9e3a5cd7f8323764303d468e5c37595a", size = 2120255 },+ { url = "https://files.pythonhosted.org/packages/bb/3d/6913dde84d5be21e284439676168b28d8bbba5600d838b9dca99de0fad71/pydantic_core-2.41.5-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:b80aa5095cd3109962a298ce14110ae16b8c1aece8b72f9dafe81cf597ad80b3", size = 1863760 },+ { url = "https://files.pythonhosted.org/packages/5a/f0/e5e6b99d4191da102f2b0eb9687aaa7f5bea5d9964071a84effc3e40f997/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3006c3dd9ba34b0c094c544c6006cc79e87d8612999f1a5d43b769b89181f23c", size = 1878092 },+ { url = "https://files.pythonhosted.org/packages/71/48/36fb760642d568925953bcc8116455513d6e34c4beaa37544118c36aba6d/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:72f6c8b11857a856bcfa48c86f5368439f74453563f951e473514579d44aa612", size = 2053385 },+ { url = "https://files.pythonhosted.org/packages/20/25/92dc684dd8eb75a234bc1c764b4210cf2646479d54b47bf46061657292a8/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5cb1b2f9742240e4bb26b652a5aeb840aa4b417c7748b6f8387927bc6e45e40d", size = 2218832 },+ { url = "https://files.pythonhosted.org/packages/e2/09/f53e0b05023d3e30357d82eb35835d0f6340ca344720a4599cd663dca599/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:bd3d54f38609ff308209bd43acea66061494157703364ae40c951f83ba99a1a9", size = 2327585 },+ { url = "https://files.pythonhosted.org/packages/aa/4e/2ae1aa85d6af35a39b236b1b1641de73f5a6ac4d5a7509f77b814885760c/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2ff4321e56e879ee8d2a879501c8e469414d948f4aba74a2d4593184eb326660", size = 2041078 },+ { url = "https://files.pythonhosted.org/packages/cd/13/2e215f17f0ef326fc72afe94776edb77525142c693767fc347ed6288728d/pydantic_core-2.41.5-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d0d2568a8c11bf8225044aa94409e21da0cb09dcdafe9ecd10250b2baad531a9", size = 2173914 },+ { url = "https://files.pythonhosted.org/packages/02/7a/f999a6dcbcd0e5660bc348a3991c8915ce6599f4f2c6ac22f01d7a10816c/pydantic_core-2.41.5-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:a39455728aabd58ceabb03c90e12f71fd30fa69615760a075b9fec596456ccc3", size = 2129560 },+ { url = "https://files.pythonhosted.org/packages/3a/b1/6c990ac65e3b4c079a4fb9f5b05f5b013afa0f4ed6780a3dd236d2cbdc64/pydantic_core-2.41.5-cp314-cp314t-musllinux_1_1_armv7l.whl", hash = "sha256:239edca560d05757817c13dc17c50766136d21f7cd0fac50295499ae24f90fdf", size = 2329244 },+ { url = "https://files.pythonhosted.org/packages/d9/02/3c562f3a51afd4d88fff8dffb1771b30cfdfd79befd9883ee094f5b6c0d8/pydantic_core-2.41.5-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:2a5e06546e19f24c6a96a129142a75cee553cc018ffee48a460059b1185f4470", size = 2331955 },+ { url = "https://files.pythonhosted.org/packages/5c/96/5fb7d8c3c17bc8c62fdb031c47d77a1af698f1d7a406b0f79aaa1338f9ad/pydantic_core-2.41.5-cp314-cp314t-win32.whl", hash = "sha256:b4ececa40ac28afa90871c2cc2b9ffd2ff0bf749380fbdf57d165fd23da353aa", size = 1988906 },+ { url = "https://files.pythonhosted.org/packages/22/ed/182129d83032702912c2e2d8bbe33c036f342cc735737064668585dac28f/pydantic_core-2.41.5-cp314-cp314t-win_amd64.whl", hash = "sha256:80aa89cad80b32a912a65332f64a4450ed00966111b6615ca6816153d3585a8c", size = 1981607 },+ { url = "https://files.pythonhosted.org/packages/9f/ed/068e41660b832bb0b1aa5b58011dea2a3fe0ba7861ff38c4d4904c1c1a99/pydantic_core-2.41.5-cp314-cp314t-win_arm64.whl", hash = "sha256:35b44f37a3199f771c3eaa53051bc8a70cd7b54f333531c59e29fd4db5d15008", size = 1974769 },+ { url = "https://files.pythonhosted.org/packages/11/72/90fda5ee3b97e51c494938a4a44c3a35a9c96c19bba12372fb9c634d6f57/pydantic_core-2.41.5-graalpy311-graalpy242_311_native-macosx_10_12_x86_64.whl", hash = "sha256:b96d5f26b05d03cc60f11a7761a5ded1741da411e7fe0909e27a5e6a0cb7b034", size = 2115441 },+ { url = "https://files.pythonhosted.org/packages/1f/53/8942f884fa33f50794f119012dc6a1a02ac43a56407adaac20463df8e98f/pydantic_core-2.41.5-graalpy311-graalpy242_311_native-macosx_11_0_arm64.whl", hash = "sha256:634e8609e89ceecea15e2d61bc9ac3718caaaa71963717bf3c8f38bfde64242c", size = 1930291 },+ { url = "https://files.pythonhosted.org/packages/79/c8/ecb9ed9cd942bce09fc888ee960b52654fbdbede4ba6c2d6e0d3b1d8b49c/pydantic_core-2.41.5-graalpy311-graalpy242_311_native-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:93e8740d7503eb008aa2df04d3b9735f845d43ae845e6dcd2be0b55a2da43cd2", size = 1948632 },+ { url = "https://files.pythonhosted.org/packages/2e/1b/687711069de7efa6af934e74f601e2a4307365e8fdc404703afc453eab26/pydantic_core-2.41.5-graalpy311-graalpy242_311_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f15489ba13d61f670dcc96772e733aad1a6f9c429cc27574c6cdaed82d0146ad", size = 2138905 },+ { url = "https://files.pythonhosted.org/packages/09/32/59b0c7e63e277fa7911c2fc70ccfb45ce4b98991e7ef37110663437005af/pydantic_core-2.41.5-graalpy312-graalpy250_312_native-macosx_10_12_x86_64.whl", hash = "sha256:7da7087d756b19037bc2c06edc6c170eeef3c3bafcb8f532ff17d64dc427adfd", size = 2110495 },+ { url = "https://files.pythonhosted.org/packages/aa/81/05e400037eaf55ad400bcd318c05bb345b57e708887f07ddb2d20e3f0e98/pydantic_core-2.41.5-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:aabf5777b5c8ca26f7824cb4a120a740c9588ed58df9b2d196ce92fba42ff8dc", size = 1915388 },+ { url = "https://files.pythonhosted.org/packages/6e/0d/e3549b2399f71d56476b77dbf3cf8937cec5cd70536bdc0e374a421d0599/pydantic_core-2.41.5-graalpy312-graalpy250_312_native-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c007fe8a43d43b3969e8469004e9845944f1a80e6acd47c150856bb87f230c56", size = 1942879 },+ { url = "https://files.pythonhosted.org/packages/f7/07/34573da085946b6a313d7c42f82f16e8920bfd730665de2d11c0c37a74b5/pydantic_core-2.41.5-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:76d0819de158cd855d1cbb8fcafdf6f5cf1eb8e470abe056d5d161106e38062b", size = 2139017 },+ { url = "https://files.pythonhosted.org/packages/5f/9b/1b3f0e9f9305839d7e84912f9e8bfbd191ed1b1ef48083609f0dabde978c/pydantic_core-2.41.5-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:b2379fa7ed44ddecb5bfe4e48577d752db9fc10be00a6b7446e9663ba143de26", size = 2101980 },+ { url = "https://files.pythonhosted.org/packages/a4/ed/d71fefcb4263df0da6a85b5d8a7508360f2f2e9b3bf5814be9c8bccdccc1/pydantic_core-2.41.5-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:266fb4cbf5e3cbd0b53669a6d1b039c45e3ce651fd5442eff4d07c2cc8d66808", size = 1923865 },+ { url = "https://files.pythonhosted.org/packages/ce/3a/626b38db460d675f873e4444b4bb030453bbe7b4ba55df821d026a0493c4/pydantic_core-2.41.5-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:58133647260ea01e4d0500089a8c4f07bd7aa6ce109682b1426394988d8aaacc", size = 2134256 },+ { url = "https://files.pythonhosted.org/packages/83/d9/8412d7f06f616bbc053d30cb4e5f76786af3221462ad5eee1f202021eb4e/pydantic_core-2.41.5-pp311-pypy311_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:287dad91cfb551c363dc62899a80e9e14da1f0e2b6ebde82c806612ca2a13ef1", size = 2174762 },+ { url = "https://files.pythonhosted.org/packages/55/4c/162d906b8e3ba3a99354e20faa1b49a85206c47de97a639510a0e673f5da/pydantic_core-2.41.5-pp311-pypy311_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:03b77d184b9eb40240ae9fd676ca364ce1085f203e1b1256f8ab9984dca80a84", size = 2143141 },+ { url = "https://files.pythonhosted.org/packages/1f/f2/f11dd73284122713f5f89fc940f370d035fa8e1e078d446b3313955157fe/pydantic_core-2.41.5-pp311-pypy311_pp73-musllinux_1_1_armv7l.whl", hash = "sha256:a668ce24de96165bb239160b3d854943128f4334822900534f2fe947930e5770", size = 2330317 },+ { url = "https://files.pythonhosted.org/packages/88/9d/b06ca6acfe4abb296110fb1273a4d848a0bfb2ff65f3ee92127b3244e16b/pydantic_core-2.41.5-pp311-pypy311_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:f14f8f046c14563f8eb3f45f499cc658ab8d10072961e07225e507adb700e93f", size = 2316992 },+ { url = "https://files.pythonhosted.org/packages/36/c7/cfc8e811f061c841d7990b0201912c3556bfeb99cdcb7ed24adc8d6f8704/pydantic_core-2.41.5-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:56121965f7a4dc965bff783d70b907ddf3d57f6eba29b6d2e5dabfaf07799c51", size = 2145302 },][[package]]@@ -1216,7 +1514,7 @@ wheels = [[[package]]name = "pyinstaller"-version = "6.15.0"+version = "6.16.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "altgraph" },@@ -1227,51 +1525,51 @@ dependencies = [{ name = "pywin32-ctypes", marker = "sys_platform == 'win32'" },{ name = "setuptools" },]-sdist = { url = "https://files.pythonhosted.org/packages/64/17/b2bb4de22650adbeef401fa82a1b43028976547a8728602e4d29735b455e/pyinstaller-6.15.0.tar.gz", hash = "sha256:a48fc4644ee4aa2aa2a35e7b51f496f8fbd7eecf6a2150646bbf1613ad07bc2d", size = 4331521 }+sdist = { url = "https://files.pythonhosted.org/packages/94/94/1f62e95e4a28b64cfbb5b922ef3046f968b47170d37a1e1a029f56ac9cb4/pyinstaller-6.16.0.tar.gz", hash = "sha256:53559fe1e041a234f2b4dcc3288ea8bdd57f7cad8a6644e422c27bb407f3edef", size = 4008473 }wheels = [- { url = "https://files.pythonhosted.org/packages/24/dd/d5c8a127446adda954f68ea7fac22772f7ab8656ad4b06df396d82574ca9/pyinstaller-6.15.0-py3-none-macosx_10_13_universal2.whl", hash = "sha256:9f00c71c40148cd1e61695b2c6f1e086693d3bcf9bfa22ab513aa4254c3b966f", size = 1016981 },- { url = "https://files.pythonhosted.org/packages/2d/2a/7b50593b419db43e48d9bdeebaac0ff92a5fe035f3c30f87ca3e1650d7e2/pyinstaller-6.15.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:cbcc8eb77320c60722030ac875883b564e00768fe3ff1721c7ba3ad0e0a277e9", size = 726337 },- { url = "https://files.pythonhosted.org/packages/77/83/7f498fba0154c57eb5fc93eb9680a2dbadb9f780a3389fb85b8d79683378/pyinstaller-6.15.0-py3-none-manylinux2014_i686.whl", hash = "sha256:c33e6302bc53db2df1104ed5566bd980b3e0ee7f18416a6e3caa908c12a54542", size = 737539 },- { url = "https://files.pythonhosted.org/packages/09/d6/e4477feab7c8379fb49e7ec95c82d0a69ad88f6ccc247f76bef3cb0e3432/pyinstaller-6.15.0-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:eb902d0fed3bb1f8b7190dc4df5c11f3b59505767e0d56d1ed782b853938bbf3", size = 735426 },- { url = "https://files.pythonhosted.org/packages/32/7e/ff25648276f15e2e77fc563d36d8cfcd917e077bf2a172420df3588601b4/pyinstaller-6.15.0-py3-none-manylinux2014_s390x.whl", hash = "sha256:b4df862adae7cf1f08eff53c43ace283822447f7f528f72e4f94749062712f15", size = 732210 },- { url = "https://files.pythonhosted.org/packages/db/3d/267a7dddd0647de95d260780050ccd8228ab29d2b9edea54ed1f56800967/pyinstaller-6.15.0-py3-none-manylinux2014_x86_64.whl", hash = "sha256:b9ebf16ed0f99016ae8ae5746dee4cb244848a12941539e62ce2eea1df5a3f95", size = 732194 },- { url = "https://files.pythonhosted.org/packages/4d/61/962b2eb79ef225233e2d6e04600e998935328011dfb2fa775b1dd16b943a/pyinstaller-6.15.0-py3-none-musllinux_1_1_aarch64.whl", hash = "sha256:22193489e6a22435417103f61e7950363bba600ef36ec3ab1487303668c81092", size = 731256 },- { url = "https://files.pythonhosted.org/packages/67/5e/4e20e1c0e5791b09b69bef3ac921fd0cd25551b56879324ad999b92fa045/pyinstaller-6.15.0-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:18f743069849dbaee3e10900385f35795a5743eabab55e99dcc42f204e40a0db", size = 731148 },- { url = "https://files.pythonhosted.org/packages/88/31/28956c534991f289e2f981c715730b6241e75dc6295737a8cbd050a0cc8c/pyinstaller-6.15.0-py3-none-win32.whl", hash = "sha256:60da8f1b5071766b45c0f607d8bc3d7e59ba2c3b262d08f2e4066ba65f3544a2", size = 1312297 },- { url = "https://files.pythonhosted.org/packages/09/ab/6a45186c7f8e34c422faecd72580116a67d068158c57faa2d2f6d01faa7f/pyinstaller-6.15.0-py3-none-win_amd64.whl", hash = "sha256:cbea297e16eeda30b41c300d6ec2fd2abea4dbd8d8a32650eeec36431c94fcd9", size = 1373091 },- { url = "https://files.pythonhosted.org/packages/5b/86/72159af032b9db36f2470a3b085f79277ec1c38e7e48f8c5dc1ed16dc4e1/pyinstaller-6.15.0-py3-none-win_arm64.whl", hash = "sha256:f43c035621742cf2d19b84308c60e4e44e72c94786d176b8f6adcde351b5bd98", size = 1314305 },+ { url = "https://files.pythonhosted.org/packages/7b/0a/c42ce6e5d3de287f2e9432a074fb209f1fb72a86a72f3903849fdb5e4829/pyinstaller-6.16.0-py3-none-macosx_10_13_universal2.whl", hash = "sha256:7fd1c785219a87ca747c21fa92f561b0d2926a7edc06d0a0fe37f3736e00bd7a", size = 1027899 },+ { url = "https://files.pythonhosted.org/packages/4e/d0/f18fedde32835d5a758f464c75924e2154065625f09d5456c3c303527654/pyinstaller-6.16.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:b756ddb9007b8141c5476b553351f9d97559b8af5d07f9460869bfae02be26b0", size = 727990 },+ { url = "https://files.pythonhosted.org/packages/7a/db/c8bb47514ce857b24bf9294cf1ff74844b6a489fa0ab4ef6f923288c4e38/pyinstaller-6.16.0-py3-none-manylinux2014_i686.whl", hash = "sha256:0a48f55b85ff60f83169e10050f2759019cf1d06773ad1c4da3a411cd8751058", size = 739238 },+ { url = "https://files.pythonhosted.org/packages/c6/3e/451dc784a8fcca0fe9f9b6b802d58555364a95b60f253613a2c83fc6b023/pyinstaller-6.16.0-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:73ba72e04fcece92e32518bbb1e1fb5ac2892677943dfdff38e01a06e8742851", size = 737142 },+ { url = "https://files.pythonhosted.org/packages/71/37/2f457479ef8fa2821cdb448acee2421dfb19fbe908bf5499d1930c164084/pyinstaller-6.16.0-py3-none-manylinux2014_s390x.whl", hash = "sha256:b1752488248f7899281b17ca3238eefb5410521291371a686a4f5830f29f52b3", size = 734133 },+ { url = "https://files.pythonhosted.org/packages/63/c4/0f7daac4d062a4d1ac2571d8a8b9b5d6812094fcd914d139af591ca5e1ba/pyinstaller-6.16.0-py3-none-manylinux2014_x86_64.whl", hash = "sha256:ba618a61627ee674d6d68e5de084ba17c707b59a4f2a856084b3999bdffbd3f0", size = 733817 },+ { url = "https://files.pythonhosted.org/packages/11/e4/b6127265b42bef883e8873d850becadf748bc5652e5a7029b059328f3c31/pyinstaller-6.16.0-py3-none-musllinux_1_1_aarch64.whl", hash = "sha256:c8b7ef536711617e12fef4673806198872033fa06fa92326ad7fd1d84a9fa454", size = 732912 },+ { url = "https://files.pythonhosted.org/packages/2b/00/c6663107bdf814b2916e71563beabd09f693c47712213bc228994cb2cc65/pyinstaller-6.16.0-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:d1ebf84d02c51fed19b82a8abb4df536923abd55bb684d694e1356e4ae2a0ce5", size = 732773 },+ { url = "https://files.pythonhosted.org/packages/a3/14/cabe9bc5f60b95d2e70e7d045ab94b0015ff8f6c8b16e2142d3597e30749/pyinstaller-6.16.0-py3-none-win32.whl", hash = "sha256:6d5f8617f3650ff9ef893e2ab4ddbf3c0d23d0c602ef74b5df8fbef4607840c8", size = 1313878 },+ { url = "https://files.pythonhosted.org/packages/aa/99/2005efbc297e7813c1d6f18484aa94a1a81ce87b6a5b497c563681f4c4ea/pyinstaller-6.16.0-py3-none-win_amd64.whl", hash = "sha256:bc10eb1a787f99fea613509f55b902fbd2d8b73ff5f51ff245ea29a481d97d41", size = 1374706 },+ { url = "https://files.pythonhosted.org/packages/ca/f4/4dfcf69b86d60fcaae05a42bbff1616d48a91e71726e5ed795d773dae9b3/pyinstaller-6.16.0-py3-none-win_arm64.whl", hash = "sha256:d0af8a401de792c233c32c44b16d065ca9ab8262ee0c906835c12bdebc992a64", size = 1315923 },][[package]]name = "pyinstaller-hooks-contrib"-version = "2025.8"+version = "2025.9"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "packaging" },{ name = "setuptools" },]-sdist = { url = "https://files.pythonhosted.org/packages/71/d6/e5b378b7d4add8c879295c531309b0320e9c07a70458665d091760ffdc87/pyinstaller_hooks_contrib-2025.8.tar.gz", hash = "sha256:3402ad41dfe9b5110af134422e37fc5d421ba342c6cb980bd67cb30b7415641c", size = 164214 }+sdist = { url = "https://files.pythonhosted.org/packages/7d/83/be0f57c0b77b66c33c2283ebd4ea341022b5a743e97c5fb3bebab82b38b9/pyinstaller_hooks_contrib-2025.9.tar.gz", hash = "sha256:56e972bdaad4e9af767ed47d132362d162112260cbe488c9da7fee01f228a5a6", size = 165189 }wheels = [- { url = "https://files.pythonhosted.org/packages/48/34/1d973d0dae849683e53fbcda84443ce016f315e6f4dc7605ede4f56a28c3/pyinstaller_hooks_contrib-2025.8-py3-none-any.whl", hash = "sha256:8d0b8cfa0cb689a619294ae200497374234bd4e3994b3ace2a4442274c899064", size = 442346 },+ { url = "https://files.pythonhosted.org/packages/a2/26/23b4cfc77d7f808c69f59070e1e8293a579ec281a547c61562357160b346/pyinstaller_hooks_contrib-2025.9-py3-none-any.whl", hash = "sha256:ccbfaa49399ef6b18486a165810155e5a8d4c59b41f20dc5da81af7482aaf038", size = 444283 },][[package]]name = "pyobjc-core"-version = "11.1"+version = "12.0"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/e8/e9/0b85c81e2b441267bca707b5d89f56c2f02578ef8f3eafddf0e0c0b8848c/pyobjc_core-11.1.tar.gz", hash = "sha256:b63d4d90c5df7e762f34739b39cc55bc63dbcf9fb2fb3f2671e528488c7a87fe", size = 974602 }+sdist = { url = "https://files.pythonhosted.org/packages/ab/dc/6d63019133e39e2b299dfbab786e64997fff0f145c45a417e1dd51faaf3f/pyobjc_core-12.0.tar.gz", hash = "sha256:7e05c805a776149a937b61b892a0459895d32d9002bedc95ce2be31ef1e37a29", size = 991669 }wheels = [- { url = "https://files.pythonhosted.org/packages/5a/a7/55afc166d89e3fcd87966f48f8bca3305a3a2d7c62100715b9ffa7153a90/pyobjc_core-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:ec36680b5c14e2f73d432b03ba7c1457dc6ca70fa59fd7daea1073f2b4157d33", size = 671075 },- { url = "https://files.pythonhosted.org/packages/c0/09/e83228e878e73bf756749939f906a872da54488f18d75658afa7f1abbab1/pyobjc_core-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:765b97dea6b87ec4612b3212258024d8496ea23517c95a1c5f0735f96b7fd529", size = 677985 },- { url = "https://files.pythonhosted.org/packages/c5/24/12e4e2dae5f85fd0c0b696404ed3374ea6ca398e7db886d4f1322eb30799/pyobjc_core-11.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:18986f83998fbd5d3f56d8a8428b2f3e0754fd15cef3ef786ca0d29619024f2c", size = 676431 },- { url = "https://files.pythonhosted.org/packages/f7/79/031492497624de4c728f1857181b06ce8c56444db4d49418fa459cba217c/pyobjc_core-11.1-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:8849e78cfe6595c4911fbba29683decfb0bf57a350aed8a43316976ba6f659d2", size = 719330 },- { url = "https://files.pythonhosted.org/packages/ed/7d/6169f16a0c7ec15b9381f8bf33872baf912de2ef68d96c798ca4c6ee641f/pyobjc_core-11.1-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:8cb9ed17a8d84a312a6e8b665dd22393d48336ea1d8277e7ad20c19a38edf731", size = 667203 },- { url = "https://files.pythonhosted.org/packages/49/0f/f5ab2b0e57430a3bec9a62b6153c0e79c05a30d77b564efdb9f9446eeac5/pyobjc_core-11.1-cp314-cp314t-macosx_11_0_universal2.whl", hash = "sha256:f2455683e807f8541f0d83fbba0f5d9a46128ab0d5cc83ea208f0bec759b7f96", size = 708807 },+ { url = "https://files.pythonhosted.org/packages/84/c1/c50e312d32644429d8a9bb3a342aeeb772fba85f9573e7681ca458124a8f/pyobjc_core-12.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:dd4962aceb0f9a0ee510e11ced449323db85e42664ac9ade53ad1cc2394dc248", size = 673921 },+ { url = "https://files.pythonhosted.org/packages/38/95/1acf3be6a8ae457a26e8ff6e08aeb71af49bfc79303b331067c058d448a4/pyobjc_core-12.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:1675dbb700b6bb6e3f3c9ce3f5401947e0193e16085eeb70e9160c6c6fc1ace5", size = 681179 },+ { url = "https://files.pythonhosted.org/packages/88/17/6c247bf9d8de2813f6015671f242333534797e81bdac9e85516fb57dfb00/pyobjc_core-12.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:c44b76d8306a130c9eb0cb79d86fd6675c8ba3e5b458e78095d271a10cd38b6a", size = 679700 },+ { url = "https://files.pythonhosted.org/packages/08/a3/1b26c438c78821e5a82b9c02f7b19a86097aeb2c51132d06e159acc22dc2/pyobjc_core-12.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:5c617551e0ab860c49229fcec0135a5cde702485f22254ddc17205eb24b7fc55", size = 721370 },+ { url = "https://files.pythonhosted.org/packages/35/b1/6df7d4b0d9f0088855a59f6af59230d1191f78fa84ca68851723272f1916/pyobjc_core-12.0-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:c2709ff43ac5c2e9e2c574ae515d3aa0e470345847a4d96c5d4a04b1b86e966d", size = 672302 },+ { url = "https://files.pythonhosted.org/packages/f8/10/3a029797c0a22c730ee0d0149ac34ab27afdf51667f96aa23a8ebe7dc3c9/pyobjc_core-12.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:eb6b987e53291e7cafd8f71a80a2dd44d7afec4202a143a3e47b75cb9cdb5716", size = 713255 },][[package]]name = "pyobjc-framework-avfoundation"-version = "11.1"+version = "12.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "pyobjc-core", marker = "platform_system == 'Darwin'" },@@ -1280,124 +1578,125 @@ dependencies = [{ name = "pyobjc-framework-coremedia", marker = "platform_system == 'Darwin'" },{ name = "pyobjc-framework-quartz", marker = "platform_system == 'Darwin'" },]-sdist = { url = "https://files.pythonhosted.org/packages/3c/1f/90cdbce1d3b4861cbb17c12adf57daeec32477eb1df8d3f9ab8551bdadfb/pyobjc_framework_avfoundation-11.1.tar.gz", hash = "sha256:6663056cc6ca49af8de6d36a7fff498f51e1a9a7f1bde7afba718a8ceaaa7377", size = 832178 }+sdist = { url = "https://files.pythonhosted.org/packages/d9/95/29d3dbf7bfa6f2beb865ab4ce22ee1ccd58c2036a6c4caa6fa6568c7a727/pyobjc_framework_avfoundation-12.0.tar.gz", hash = "sha256:e9e9a15edea43341b39de677a58ac98b2a6bd4d6c55176b4804c5f75b3d20ece", size = 310508 }wheels = [- { url = "https://files.pythonhosted.org/packages/0f/48/31286b2b09a619d8047256d7180e0d511be71ab598e5f54f034977b59bbf/pyobjc_framework_avfoundation-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:8a0ccbdba46b69dec1d12eea52eef56fcd63c492f73e41011bb72508b2aa2d0e", size = 70711 },- { url = "https://files.pythonhosted.org/packages/43/30/d5d03dd4a508bdaa2156ff379e9e109020de23cbb6316c5865d341aa6db1/pyobjc_framework_avfoundation-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:94f065db4e87b1baebb5cf9f464cf9d82c5f903fff192001ebc974d9e3132c7e", size = 70746 },- { url = "https://files.pythonhosted.org/packages/3f/8c/b8ced7700b0e931dc37d14b05e2bead28d2598c887832b3d697da55b1845/pyobjc_framework_avfoundation-11.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:e204d155a09c186601490e4402dcffb2845a5831079e389b47bd6a341fe5ee63", size = 70773 },- { url = "https://files.pythonhosted.org/packages/d6/4c/086f4713793aaabdb5134debbf1fdc6c7d4ef5a32a6b35529e2e69580ec8/pyobjc_framework_avfoundation-11.1-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:dd3965aad0b236b8ac12f216d688c1a22b963f63e7e4fdb7107dd6790e80ee12", size = 71352 },- { url = "https://files.pythonhosted.org/packages/a6/5f/d5c4b9812e22c6fdf234421f131efae7c3137e838bb9df9be8bb45cde97b/pyobjc_framework_avfoundation-11.1-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:1ab2108b652496b13b9758c295f0f6de53b6d12125cf574ddae84ce28044bce1", size = 71208 },- { url = "https://files.pythonhosted.org/packages/29/d0/dec23e1745a81f5576cba577fa7218d665f36250a8507eaaa83a84579abf/pyobjc_framework_avfoundation-11.1-cp314-cp314t-macosx_11_0_universal2.whl", hash = "sha256:5dd6ac6a57f86b7ed5ac0a965ce54328f6ce77816b4a1fbf0d85c06fb251867a", size = 71680 },+ { url = "https://files.pythonhosted.org/packages/ed/b6/cd14afee737a14b959ec9f96017134b80bdab55649b82f34f5490c060790/pyobjc_framework_avfoundation-12.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:d47cd250011e6db5e20f1ff6ad72b6d2c40364eb6565009c7d2ff071e0a89647", size = 83319 },+ { url = "https://files.pythonhosted.org/packages/8c/3c/f9c732a33cafeff870e8d99c2378cc90a51f1a3261b5614f414b36902fdc/pyobjc_framework_avfoundation-12.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:803e675fbea532337bbd94becb040a054d58af610e20e86f7fd35fb54fd379f2", size = 83370 },+ { url = "https://files.pythonhosted.org/packages/dd/a3/07b098df03c1d5d8b4762ccba77881c9d41733a94db34815a27853531bf8/pyobjc_framework_avfoundation-12.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:3aef07f73e8e908aeae195846d0d9bddb95bf82bbc10c22b51ec15f822a828fd", size = 83413 },+ { url = "https://files.pythonhosted.org/packages/57/64/bffe9c7980313c84ef66f1c97770c12c505bc91a7e188a401f8655e85f91/pyobjc_framework_avfoundation-12.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:31840a514e703f64094c9f29053a0a22969b4666a207b5061d965fa0ddb96e4d", size = 83866 },+ { url = "https://files.pythonhosted.org/packages/e8/5a/40edf86b2c040070ca18c9eec2e2c52e7d111209279fee919b13ad86d2b2/pyobjc_framework_avfoundation-12.0-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:953bb5d6db3a6e2cddf489eb58bb6a1fb306e441ba6a011d04356b25c60a78e4", size = 83625 },+ { url = "https://files.pythonhosted.org/packages/2d/6d/c6398333f88e2142d18ca9704413c5aa10d86fbc5ed813ded61da70104bc/pyobjc_framework_avfoundation-12.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:a612ae9863abd4e0769ce6ff9960a5bf46128dddb3ef8f027406b8cd136e41f9", size = 83962 },][[package]]name = "pyobjc-framework-cocoa"-version = "11.1"+version = "12.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "pyobjc-core", marker = "platform_system == 'Darwin'" },]-sdist = { url = "https://files.pythonhosted.org/packages/4b/c5/7a866d24bc026f79239b74d05e2cf3088b03263da66d53d1b4cf5207f5ae/pyobjc_framework_cocoa-11.1.tar.gz", hash = "sha256:87df76b9b73e7ca699a828ff112564b59251bb9bbe72e610e670a4dc9940d038", size = 5565335 }+sdist = { url = "https://files.pythonhosted.org/packages/37/6f/89837da349fe7de6476c426f118096b147de923139556d98af1832c64b97/pyobjc_framework_cocoa-12.0.tar.gz", hash = "sha256:02d69305b698015a20fcc8e1296e1528e413d8cf9fdcd590478d359386d76e8a", size = 2771906 }wheels = [- { url = "https://files.pythonhosted.org/packages/90/43/6841046aa4e257b6276cd23e53cacedfb842ecaf3386bb360fa9cc319aa1/pyobjc_framework_cocoa-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:7b9a9b8ba07f5bf84866399e3de2aa311ed1c34d5d2788a995bdbe82cc36cfa0", size = 388177 },- { url = "https://files.pythonhosted.org/packages/68/da/41c0f7edc92ead461cced7e67813e27fa17da3c5da428afdb4086c69d7ba/pyobjc_framework_cocoa-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:806de56f06dfba8f301a244cce289d54877c36b4b19818e3b53150eb7c2424d0", size = 388983 },- { url = "https://files.pythonhosted.org/packages/4e/0b/a01477cde2a040f97e226f3e15e5ffd1268fcb6d1d664885a95ba592eca9/pyobjc_framework_cocoa-11.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:54e93e1d9b0fc41c032582a6f0834befe1d418d73893968f3f450281b11603da", size = 389049 },- { url = "https://files.pythonhosted.org/packages/bc/e6/64cf2661f6ab7c124d0486ec6d1d01a9bb2838a0d2a46006457d8c5e6845/pyobjc_framework_cocoa-11.1-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:fd5245ee1997d93e78b72703be1289d75d88ff6490af94462b564892e9266350", size = 393110 },- { url = "https://files.pythonhosted.org/packages/33/87/01e35c5a3c5bbdc93d5925366421e10835fcd7b23347b6c267df1b16d0b3/pyobjc_framework_cocoa-11.1-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:aede53a1afc5433e1e7d66568cc52acceeb171b0a6005407a42e8e82580b4fc0", size = 392644 },- { url = "https://files.pythonhosted.org/packages/c1/7c/54afe9ffee547c41e1161691e72067a37ed27466ac71c089bfdcd07ca70d/pyobjc_framework_cocoa-11.1-cp314-cp314t-macosx_11_0_universal2.whl", hash = "sha256:1b5de4e1757bb65689d6dc1f8d8717de9ec8587eb0c4831c134f13aba29f9b71", size = 396742 },+ { url = "https://files.pythonhosted.org/packages/8d/7d/1758df5c2cbf9a0a447cab7e9e5690f166c8b2117dc15d8f38a9526af9db/pyobjc_framework_cocoa-12.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:ae041b7c64a8fa93f0e06728681f7ad657ef2c92dcfdf8abc073d89fb6e3910b", size = 383765 },+ { url = "https://files.pythonhosted.org/packages/18/76/ee7a07e64f7afeff36bf2efe66caed93e41fcaa2b23fc89c4746387e4a0d/pyobjc_framework_cocoa-12.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:ed99d53a91f9feb9452ba8942cd09d86727f6dd2d56ecfd9b885ddbd4259ebdd", size = 384540 },+ { url = "https://files.pythonhosted.org/packages/fb/29/cfef5f021576976698c6ae195fa304238b9f6716e1b3eb11258d2572afe9/pyobjc_framework_cocoa-12.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:13e573f5093f4158f305b1bac5e1f783881ce2f5f4a69f3c80cb000f76731259", size = 384659 },+ { url = "https://files.pythonhosted.org/packages/f1/37/d2d9a143ab5387815a00f478916a52425c4792678366ef6cedf20b8cc9cd/pyobjc_framework_cocoa-12.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:3b167793cd1b509eaf693140ace9be1f827a2c8686fceb8c599907661f608bc2", size = 388787 },+ { url = "https://files.pythonhosted.org/packages/0f/15/0a6122e430d0e2ba27ad0e345b89f85346805f39d6f97eea6430a74350d9/pyobjc_framework_cocoa-12.0-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:a2b6fb9ab3e5ab6db04dfa17828a97894e7da85dd8600885c72a0c2c2214d618", size = 384890 },+ { url = "https://files.pythonhosted.org/packages/79/d7/1a3ad814d427c08b99405e571e47a0219598930ad73850ac02d164d88cd0/pyobjc_framework_cocoa-12.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:32ff10250a57f72a0b6eca85b790dcc87548ff71d33d0436ffb69680d5e2f308", size = 388925 },][[package]]name = "pyobjc-framework-coreaudio"-version = "11.1"+version = "12.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "pyobjc-core", marker = "platform_system == 'Darwin'" },{ name = "pyobjc-framework-cocoa", marker = "platform_system == 'Darwin'" },]-sdist = { url = "https://files.pythonhosted.org/packages/39/c0/4ab6005cf97e534725b0c14b110d4864b367c282b1c5b0d8f42aad74a83f/pyobjc_framework_coreaudio-11.1.tar.gz", hash = "sha256:b7b89540ae7efc6c1e3208ac838ef2acfc4d2c506dd629d91f6b3b3120e55c1b", size = 141032 }+sdist = { url = "https://files.pythonhosted.org/packages/4c/a0/604b8e2e53f46536b9045fc0fbfa9468a606910c9c0a238d0f3d31071d87/pyobjc_framework_coreaudio-12.0.tar.gz", hash = "sha256:19741907d2d80a658d3721140eb998061007955323b427afca67eda0e2ad3215", size = 75415 }wheels = [- { url = "https://files.pythonhosted.org/packages/54/1d/81339c1087519a9f125396c717b85a05b49c2c54137bdf4ca01c1ccb6239/pyobjc_framework_coreaudio-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:73a46f0db2fa8ca2e8c47c3ddcc2751e67a0f8600246a6718553b15ee0dbbdb6", size = 35383 },- { url = "https://files.pythonhosted.org/packages/3d/fe/c43521642db98a4ec29fa535781c1316342bb52d5fc709696cbb1e8ca6cd/pyobjc_framework_coreaudio-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:2538d1242dab4e27efb346eafbad50594e7e95597fa7220f0bab2099c825da55", size = 36765 },- { url = "https://files.pythonhosted.org/packages/82/9b/24d03ace273585de2d04385f06b895ce92caf8f5af430b060618ebce9dbe/pyobjc_framework_coreaudio-11.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:f73d996df1e721931d9f78050e1708735a173dbe3a76d9c71fb36e04f7208478", size = 36779 },- { url = "https://files.pythonhosted.org/packages/91/23/aa78365e45d0d04fc37e21cf7d69dc0d11e17b564e83cb5bcd98e89cdf45/pyobjc_framework_coreaudio-11.1-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:67dae111b78d91c26c753dbfbccc3ea5498cfda3dfe83c6f3778628b435e1e7b", size = 38480 },- { url = "https://files.pythonhosted.org/packages/3e/58/fc6d752a68f28567fa6d6d6a229122c829e2251f79ec7304fe0572e0fdcd/pyobjc_framework_coreaudio-11.1-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:9527a16a2b88b37bace578d499f21229f9a33b9afdcdd35d4f44374cb8eb9ab6", size = 36910 },- { url = "https://files.pythonhosted.org/packages/9e/4c/c1c5624418dea005d9965ba690d3649afc33371ade213841ab51922af751/pyobjc_framework_coreaudio-11.1-cp314-cp314t-macosx_11_0_universal2.whl", hash = "sha256:6ba8b67f185c0e3f26b17ae525cee3f411bc8d6e9c9a8bfd899a28f594623d2f", size = 38567 },+ { url = "https://files.pythonhosted.org/packages/e4/42/284cc68a2bd310f4399eb92e5259319a3131b1fba5f1496dfaa477eaaed0/pyobjc_framework_coreaudio-12.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:d6287d67c7b3ca9abf4b7e8a64e1a05e97ebcb52b32e92a78e1e825d1334ec56", size = 35337 },+ { url = "https://files.pythonhosted.org/packages/51/49/97cbda2efdb02e9d8c8507dc980040056b96ca9604dab41cbed3c874fe4a/pyobjc_framework_coreaudio-12.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:c89762834680a26436a8e435dc736b509f1c3aa3927f66db85d3289995d007d2", size = 36920 },+ { url = "https://files.pythonhosted.org/packages/52/c1/8bd4c6a917d7314042a7b26f3433c680c051f64995da682a5f99502202c9/pyobjc_framework_coreaudio-12.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:f7309087b42ce6c399d2971a7173c9216c03a43a998bb2be2eecc90fb362ccb2", size = 36944 },+ { url = "https://files.pythonhosted.org/packages/84/92/23ab5d0f3b953bb944d7bbb99d054c560b9a2d931d173e9165b44172ebb8/pyobjc_framework_coreaudio-12.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:b52a2ef28b557c5f5cbf97264ce0c6f8ce1a4ea0309b4a952122b9bc3a4ad636", size = 38398 },+ { url = "https://files.pythonhosted.org/packages/e2/14/d7f6b39f0234de213889df52091681b9abab9e4b7ca6858eff1cbe5e3c14/pyobjc_framework_coreaudio-12.0-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:30ac30f6be6b35bbe7f21c055269de6643c378c5e15bf5002c4eb1de942904fc", size = 37021 },+ { url = "https://files.pythonhosted.org/packages/34/ee/f1e955191775df1cdac142bfca1dc2787c9dde9f23e821061c7a18ff6e86/pyobjc_framework_coreaudio-12.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:1bb16d186466cf3b9c23e29dbc0470c282c7194dc022b685f075a7585dfc8a43", size = 38498 },][[package]]name = "pyobjc-framework-coremedia"-version = "11.1"+version = "12.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "pyobjc-core", marker = "platform_system == 'Darwin'" },{ name = "pyobjc-framework-cocoa", marker = "platform_system == 'Darwin'" },]-sdist = { url = "https://files.pythonhosted.org/packages/95/5d/81513acd219df77a89176f1574d936b81ad6f6002225cabb64d55efb7e8d/pyobjc_framework_coremedia-11.1.tar.gz", hash = "sha256:82cdc087f61e21b761e677ea618a575d4c0dbe00e98230bf9cea540cff931db3", size = 216389 }+sdist = { url = "https://files.pythonhosted.org/packages/55/6d/ed4f8b525a0520e609cea57fd0677bf7792e168297ad5577df1088eb7cd6/pyobjc_framework_coremedia-12.0.tar.gz", hash = "sha256:d7f76d2eb2890be9f8836b95682e83fa7f158c92043958daa71845fbc4a01ba9", size = 89928 }wheels = [- { url = "https://files.pythonhosted.org/packages/32/48/811ccea77d2c0d8156a489e2900298502eb6648d9c041c7f0c514c8f8a29/pyobjc_framework_coremedia-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:aacf47006e1c6bf6124fb2b5016a8d5fd5cf504b6b488f9eba4e389ab0f0a051", size = 29118 },- { url = "https://files.pythonhosted.org/packages/2c/d1/b3d004d6a2d2188d196779d92fe8cfa2533f5722cd216fbc4f0cffc63b24/pyobjc_framework_coremedia-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:ea5055298af91e463ffa7977d573530f9bada57b8f2968dcc76a75e339b9a598", size = 29015 },- { url = "https://files.pythonhosted.org/packages/1c/23/cafd29011d14eac27fc55770157ebb8e02ffed9f75e01f24e97616417c4c/pyobjc_framework_coremedia-11.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:7ecdb64c743ffe9fd3949c7cc9109891b9f399a0852717fcb969d33c4e7ba527", size = 29031 },- { url = "https://files.pythonhosted.org/packages/de/a6/ca85b7d9d000e8e2748bcacde356278cb90f6ca9aed54dce6a42d1716ba8/pyobjc_framework_coremedia-11.1-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:969ce357c616f6835f47e27d1e73964374cdb671476571dfd358894a8ced06f2", size = 29094 },- { url = "https://files.pythonhosted.org/packages/b8/3d/56d530cf504a6eef84f51c8f6f845af8b947f6108e41db5e0b5189d5a667/pyobjc_framework_coremedia-11.1-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:bf1da05c297776c297ab3489ebf18d954efdff530acbdd6e70c32be811e20ec6", size = 29043 },- { url = "https://files.pythonhosted.org/packages/a4/bc/b237ecd4954a0f07450469236ca45412edb7d8715ff7fc175ac519e7c472/pyobjc_framework_coremedia-11.1-cp314-cp314t-macosx_11_0_universal2.whl", hash = "sha256:aa942d9ad0cf5bc4d3ede8779c3fac2f04cf3857687f2fb8505bae3378d04b95", size = 29111 },+ { url = "https://files.pythonhosted.org/packages/05/1c/5e5fe69b142c98b844803a0579cbd8ea555d1bfeecede95a918e58bdfb67/pyobjc_framework_coremedia-12.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:ed5684c764e1d4eab10cfd8dcaea82b598a85d7757cef35d36e6c78a4bd4b1e5", size = 29508 },+ { url = "https://files.pythonhosted.org/packages/ec/15/9853b2e75db0bf47a80412f9584a84966310e3168dabde8d43f2c6fa9ff1/pyobjc_framework_coremedia-12.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:06e824c97391cacacfe6be4b80acdcb6924a8087d03d9af35ea0edf502f2ada1", size = 29406 },+ { url = "https://files.pythonhosted.org/packages/eb/08/15d500b9325f8c22ed379dba21559dfa9c7430c9b7eb709a55e515648c8d/pyobjc_framework_coremedia-12.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:4d10a8b551626ae99a67436de498fc06a0beaa66db065baed19d7dfc5f1db44f", size = 29425 },+ { url = "https://files.pythonhosted.org/packages/a9/98/ccf63a3a3aff8fce8be57b8ae1a67c9872e278a890c0508e86ed6bf98055/pyobjc_framework_coremedia-12.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:370aece067a0fb85e54eed57c6ca84118a55e7ff697988e5c82358d1bd3b648a", size = 29486 },+ { url = "https://files.pythonhosted.org/packages/8f/fb/43b2a78ffdcb1eed7f04c317f9675d40dcd573f805d7385fec6c54005a2d/pyobjc_framework_coremedia-12.0-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:0c89ca9d7cedd7b37178e358c83332933fcd65d82c362244aa208383724dce6f", size = 29462 },+ { url = "https://files.pythonhosted.org/packages/2f/2b/3cb4ba97483987b6dd9165e2da0f5e85f81044bd8fba26c409271dc2c880/pyobjc_framework_coremedia-12.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:aaa904d82f75f1e38a1ba8ba9a19a5acb3869304626b12fd6b60040a85188211", size = 29512 },][[package]]name = "pyobjc-framework-quartz"-version = "11.1"+version = "12.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "pyobjc-core", marker = "platform_system == 'Darwin'" },{ name = "pyobjc-framework-cocoa", marker = "platform_system == 'Darwin'" },]-sdist = { url = "https://files.pythonhosted.org/packages/c7/ac/6308fec6c9ffeda9942fef72724f4094c6df4933560f512e63eac37ebd30/pyobjc_framework_quartz-11.1.tar.gz", hash = "sha256:a57f35ccfc22ad48c87c5932818e583777ff7276605fef6afad0ac0741169f75", size = 3953275 }+sdist = { url = "https://files.pythonhosted.org/packages/91/0b/3c34fc9de790daff5ca49d1f36cb8dcc353ac10e4e29b4759e397a3831f4/pyobjc_framework_quartz-12.0.tar.gz", hash = "sha256:5bcb9e78d671447e04d89e2e3c39f3135157892243facc5f8468aa333e40d67f", size = 3159509 }wheels = [- { url = "https://files.pythonhosted.org/packages/77/cb/38172fdb350b3f47e18d87c5760e50f4efbb4da6308182b5e1310ff0cde4/pyobjc_framework_quartz-11.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:2d501fe95ef15d8acf587cb7dc4ab4be3c5a84e2252017da8dbb7df1bbe7a72a", size = 215565 },- { url = "https://files.pythonhosted.org/packages/9b/37/ee6e0bdd31b3b277fec00e5ee84d30eb1b5b8b0e025095e24ddc561697d0/pyobjc_framework_quartz-11.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:9ac806067541917d6119b98d90390a6944e7d9bd737f5c0a79884202327c9204", size = 216410 },- { url = "https://files.pythonhosted.org/packages/bd/27/4f4fc0e6a0652318c2844608dd7c41e49ba6006ee5fb60c7ae417c338357/pyobjc_framework_quartz-11.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:43a1138280571bbf44df27a7eef519184b5c4183a588598ebaaeb887b9e73e76", size = 216816 },- { url = "https://files.pythonhosted.org/packages/b8/8a/1d15e42496bef31246f7401aad1ebf0f9e11566ce0de41c18431715aafbc/pyobjc_framework_quartz-11.1-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:b23d81c30c564adf6336e00b357f355b35aad10075dd7e837cfd52a9912863e5", size = 221941 },- { url = "https://files.pythonhosted.org/packages/32/a8/a3f84d06e567efc12c104799c7fd015f9bea272a75f799eda8b79e8163c6/pyobjc_framework_quartz-11.1-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:07cbda78b4a8fcf3a2d96e047a2ff01f44e3e1820f46f0f4b3b6d77ff6ece07c", size = 221312 },- { url = "https://files.pythonhosted.org/packages/76/ef/8c08d4f255bb3efe8806609d1f0b1ddd29684ab0f9ffb5e26d3ad7957b29/pyobjc_framework_quartz-11.1-cp314-cp314t-macosx_11_0_universal2.whl", hash = "sha256:39d02a3df4b5e3eee1e0da0fb150259476910d2a9aa638ab94153c24317a9561", size = 226353 },+ { url = "https://files.pythonhosted.org/packages/b8/ed/13207ed99bd672a681cad3435512ab4e3217dd0cdc991c16a074ef6e7e95/pyobjc_framework_quartz-12.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:6098bdb5db5837ecf6cf57f775efa9e5ce7c31f6452e4c4393de2198f5a3b06b", size = 217787 },+ { url = "https://files.pythonhosted.org/packages/1c/76/2d7e6b0e2eb42b9a17b65c92575693f9d364b832e069024123742b54caa5/pyobjc_framework_quartz-12.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:cb6818cbeea55e8b85c3347bb8acaf6f46ebb2c241ae4eb76ba1358c68f3ec5c", size = 218816 },+ { url = "https://files.pythonhosted.org/packages/60/d8/05f8fb5f27af69c0b5a9802f220a7c00bbe595c790e13edefa042603b957/pyobjc_framework_quartz-12.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:ece7a05aa2bfc3aa215f1a7c8580e873f3867ba40d0006469618cc2ceb796578", size = 219201 },+ { url = "https://files.pythonhosted.org/packages/7e/3f/1228f86de266874e20c04f04736a5f11c5a29a1839efde594ba4097d0255/pyobjc_framework_quartz-12.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:f1b2e34f6f0dd023f80a0e875af4dab0ad27fccac239da9ad3d311a2d2578e27", size = 224330 },+ { url = "https://files.pythonhosted.org/packages/8a/23/ec1804bd10c409fe98ba086329569914fd10b6814208ca6168e81ca0ec1a/pyobjc_framework_quartz-12.0-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:a2cde43ddc5d2a9ace13af38b4a9ee70dbd47d1707ec6b7185a1a3a1d48e54f9", size = 219581 },+ { url = "https://files.pythonhosted.org/packages/86/c2/cf89fda2e477c0c4e2a8aae86202c2891a83bead24e8a7fc733ff490dffc/pyobjc_framework_quartz-12.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:9b928d551ec779141558d986684c19f8f5742251721f440d7087257e4e35b22b", size = 224613 },][[package]]name = "pyparsing"-version = "3.2.3"+version = "3.2.5"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/bb/22/f1129e69d94ffff626bdb5c835506b3a5b4f3d070f17ea295e12c2c6f60f/pyparsing-3.2.3.tar.gz", hash = "sha256:b9c13f1ab8b3b542f72e28f634bad4de758ab3ce4546e4301970ad6fa77c38be", size = 1088608 }+sdist = { url = "https://files.pythonhosted.org/packages/f2/a5/181488fc2b9d093e3972d2a472855aae8a03f000592dbfce716a512b3359/pyparsing-3.2.5.tar.gz", hash = "sha256:2df8d5b7b2802ef88e8d016a2eb9c7aeaa923529cd251ed0fe4608275d4105b6", size = 1099274 }wheels = [- { url = "https://files.pythonhosted.org/packages/05/e7/df2285f3d08fee213f2d041540fa4fc9ca6c2d44cf36d3a035bf2a8d2bcc/pyparsing-3.2.3-py3-none-any.whl", hash = "sha256:a749938e02d6fd0b59b356ca504a24982314bb090c383e3cf201c95ef7e2bfcf", size = 111120 },+ { url = "https://files.pythonhosted.org/packages/10/5e/1aa9a93198c6b64513c9d7752de7422c06402de6600a8767da1524f9570b/pyparsing-3.2.5-py3-none-any.whl", hash = "sha256:e38a4f02064cf41fe6593d328d0512495ad1f3d8a91c4f73fc401b3079a59a5e", size = 113890 },][[package]]name = "pyqt6"-version = "6.9.1"+version = "6.10.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "pyqt6-qt6" },{ name = "pyqt6-sip" },]-sdist = { url = "https://files.pythonhosted.org/packages/32/1b/567f46eb43ca961efd38d7a0b73efb70d7342854f075fd919179fdb2a571/pyqt6-6.9.1.tar.gz", hash = "sha256:50642be03fb40f1c2111a09a1f5a0f79813e039c15e78267e6faaf8a96c1c3a6", size = 1067230 }+sdist = { url = "https://files.pythonhosted.org/packages/f2/57/48985490c01584e00b70040ec0eb02dfe950471097201acb1b65deb633e5/pyqt6-6.10.0.tar.gz", hash = "sha256:710ecfd720d9a03b2c684881ae37f528e11d17e8f1bf96431d00a6a73f308e36", size = 1079921 }wheels = [- { url = "https://files.pythonhosted.org/packages/18/c4/fc2a69cf3df09b213185ef5a677c3940cd20e7855d29e40061a685b9c6ee/pyqt6-6.9.1-cp39-abi3-macosx_10_14_universal2.whl", hash = "sha256:33c23d28f6608747ecc8bfd04c8795f61631af9db4fb1e6c2a7523ec4cc916d9", size = 59770566 },- { url = "https://files.pythonhosted.org/packages/d5/78/92f3c46440a83ebe22ae614bd6792e7b052bcb58ff128f677f5662015184/pyqt6-6.9.1-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:37884df27f774e2e1c0c96fa41e817a222329b80ffc6241725b0dc8c110acb35", size = 37804959 },- { url = "https://files.pythonhosted.org/packages/5a/5e/e77fa2761d809cd08d724f44af01a4b6ceb0ff9648e43173187b0e4fac4e/pyqt6-6.9.1-cp39-abi3-manylinux_2_39_aarch64.whl", hash = "sha256:055870b703c1a49ca621f8a89e2ec4d848e6c739d39367eb9687af3b056d9aa3", size = 40414608 },- { url = "https://files.pythonhosted.org/packages/c4/09/69cf80456b6a985e06dd24ed0c2d3451e43567bf2807a5f3a86ef7a74a2e/pyqt6-6.9.1-cp39-abi3-win_amd64.whl", hash = "sha256:15b95bd273bb6288b070ed7a9503d5ff377aa4882dd6d175f07cad28cdb21da0", size = 25717996 },- { url = "https://files.pythonhosted.org/packages/52/b3/0839d8fd18b86362a4de384740f2f6b6885b5d06fda7720f8a335425e316/pyqt6-6.9.1-cp39-abi3-win_arm64.whl", hash = "sha256:08792c72d130a02e3248a120f0b9bbb4bf4319095f92865bc5b365b00518f53d", size = 25212132 },+ { url = "https://files.pythonhosted.org/packages/f8/99/ca0386e84e39e4f2ef30322f1d39d515f2a3efbc542cccb33e65a1cf7c46/pyqt6-6.10.0-1-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:54b6b022369e4e6ade8cf79c0f988558839df7b2c285f814b4567d15a0fcb756", size = 37745881 },+ { url = "https://files.pythonhosted.org/packages/66/48/be73fb730c6f617f456ab73150db384b17a7a08394d7e2ded55f42de8a7b/pyqt6-6.10.0-cp39-abi3-macosx_10_14_universal2.whl", hash = "sha256:0eb82f152a83a8ae39f7d3ba580829ff7c0e8179d19d70f396853c10c8ddc5ac", size = 59987475 },+ { url = "https://files.pythonhosted.org/packages/00/31/e55f7b718df92423b5af3f0fe11e770e56d7576c03adc6b6866b0e8beb46/pyqt6-6.10.0-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:43e94a0ad4713055b47b4676d23432349845729912e4f3d20ac95935931c5e6f", size = 39028922 },+ { url = "https://files.pythonhosted.org/packages/cf/3d/48465697f530addaeaf41f4d5b3e54108ebabd18ab6da19823de5099e807/pyqt6-6.10.0-cp39-abi3-manylinux_2_39_aarch64.whl", hash = "sha256:357da0f1465557dde249a31bc1f152320b7628a644e1d55d2db09b635394f39f", size = 40619932 },+ { url = "https://files.pythonhosted.org/packages/fb/e4/0c4745cd0b31c17bd85d5da697404679f4faa6424aa7b57112277c1e8027/pyqt6-6.10.0-cp39-abi3-win_amd64.whl", hash = "sha256:8b5e4ea573733017a76bd12ea1b53351fd7f6dc57f8abf4329c4a41fea6dde04", size = 25816996 },+ { url = "https://files.pythonhosted.org/packages/b0/40/0891706e69c60267b6933465fa299138bafa72324d6855c6962ca05a5f9f/pyqt6-6.10.0-cp39-abi3-win_arm64.whl", hash = "sha256:c2b5fc1a028e95b096f3a5966611cc8194e8e9e69984c41477417e18b5ce1362", size = 25663908 },][[package]]name = "pyqt6-qt6"-version = "6.9.1"+version = "6.10.0"source = { registry = "https://pypi.org/simple" }wheels = [- { url = "https://files.pythonhosted.org/packages/51/40/04f652e714f85ba6b0c24f4ead860f2c5769f9e64737f415524d792d5914/pyqt6_qt6-6.9.1-py3-none-macosx_10_14_x86_64.whl", hash = "sha256:3854c7f83ee4e8c2d91e23ab88b77f90e2ca7ace34fe72f634a446959f2b4d4a", size = 66236777 },- { url = "https://files.pythonhosted.org/packages/57/31/e4fa40568a59953ce5cf9a5adfbd1be4a806dafd94e39072d3cc0bed5468/pyqt6_qt6-6.9.1-py3-none-macosx_11_0_arm64.whl", hash = "sha256:123e4aeb037c099bb4696a3ea8edcb1d9d62cedd0b2b950556b26024c97f3293", size = 60551574 },- { url = "https://files.pythonhosted.org/packages/aa/8d/7c8073cbbefe9c103ec8add70f29ffee1db95a3755b429b9f47cd6afa41b/pyqt6_qt6-6.9.1-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:cc5bd193ebd2d1a3ec66e1eee65bf532d762c239459bce1ecebf56177243e89b", size = 82000130 },- { url = "https://files.pythonhosted.org/packages/1e/60/a4ab932028b0c15c0501cb52eb1e7f24f4ce2e4c78d46c7cce58a375a88c/pyqt6_qt6-6.9.1-py3-none-manylinux_2_39_aarch64.whl", hash = "sha256:b065af7243d1d450a49470a8185301196a18b1d41085d3ef476eb55bbb225083", size = 80463127 },- { url = "https://files.pythonhosted.org/packages/e7/85/552710819019a96d39d924071324a474aec54b31c410d7de8ebb398adcc1/pyqt6_qt6-6.9.1-py3-none-win_amd64.whl", hash = "sha256:f9e54c424bc921ecb76792a75d123e4ecfc26b00b0c57dae526f41f1d57951d3", size = 73778423 },- { url = "https://files.pythonhosted.org/packages/16/b4/70f6b18a4913f2326dcf7acb15c12cc0b91cb3932c2ba3b5728811f22acd/pyqt6_qt6-6.9.1-py3-none-win_arm64.whl", hash = "sha256:432caaedf5570bc8a9b7c75bc6af6a26bf88589536472eca73417ac019f59d41", size = 49617924 },+ { url = "https://files.pythonhosted.org/packages/c3/b2/309ba75490d614530f10a5b922555374098706364ec1cc411f98068beb4d/pyqt6_qt6-6.10.0-py3-none-macosx_10_14_x86_64.whl", hash = "sha256:9b48d9eba795a78d21393b1909e7a0406512038ea4667463e4882e284bf95817", size = 68426539 },+ { url = "https://files.pythonhosted.org/packages/25/20/1de54c91f6f34be6042bdb6913c71e253a6bddf002d8aa78cb1acc67f5a8/pyqt6_qt6-6.10.0-py3-none-macosx_11_0_arm64.whl", hash = "sha256:768ced73dbb2c85e6d72ea63fd7409ba934d4b24580ef073a3eb16fd88d3fe70", size = 62509741 },+ { url = "https://files.pythonhosted.org/packages/c1/32/1d84ab75795b0984935e32d2a51200b94328a45954c28360a97d02f1c376/pyqt6_qt6-6.10.0-py3-none-manylinux_2_34_x86_64.whl", hash = "sha256:cd38b281bb7229b8114f13126aacd77f831a97105fdb1d900260a48ead8c9fcd", size = 83787113 },+ { url = "https://files.pythonhosted.org/packages/d9/56/e8daedfb0e4a79e19500b6271958b915389360b39a3e2847961828d2e0b3/pyqt6_qt6-6.10.0-py3-none-manylinux_2_39_aarch64.whl", hash = "sha256:497df665091451ab7fde3355e262b243d2a2d97924b899a5cbb193a0cc573b7e", size = 82848172 },+ { url = "https://files.pythonhosted.org/packages/0b/82/bbbee33205574f57b17c25059c6b8726a129961b55a1fe34f9216b4b0a70/pyqt6_qt6-6.10.0-py3-none-win_amd64.whl", hash = "sha256:d11bc03908cacbd2e3426289ad51dcf6d2896af6ffec595626ce9cf9b93e770d", size = 76322424 },+ { url = "https://files.pythonhosted.org/packages/f2/b7/fb3172c8e85fdcdc942600dbec3d7ebd8d5224159cd4f32ced6cc43949cc/pyqt6_qt6-6.10.0-py3-none-win_arm64.whl", hash = "sha256:7f3ae89337e905dba436c226027ebd8777d4cdeef386131ad9a1b0a53ecc1a81", size = 56552467 },][[package]]@@ -1421,68 +1720,16 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/b0/1e/c6a28a142f14e735088534cc92951c3f48cccd77cdd4f3b10d7996be420f/pyqt6_sip-13.10.2-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:3dde8024d055f496eba7d44061c5a1ba4eb72fc95e5a9d7a0dbc908317e0888b", size = 303833 },{ url = "https://files.pythonhosted.org/packages/89/63/e5adf350c1c3123d4865c013f164c5265512fa79f09ad464fb2fdf9f9e61/pyqt6_sip-13.10.2-cp313-cp313-win_amd64.whl", hash = "sha256:0b097eb58b4df936c4a2a88a2f367c8bb5c20ff049a45a7917ad75d698e3b277", size = 53527 },{ url = "https://files.pythonhosted.org/packages/58/74/2df4195306d050fbf4963fb5636108a66e5afa6dc05fd9e81e51ec96c384/pyqt6_sip-13.10.2-cp313-cp313-win_arm64.whl", hash = "sha256:cc6a1dfdf324efaac6e7b890a608385205e652845c62130de919fd73a6326244", size = 45373 },-]--[[package]]-name = "pyqtgraph"-version = "0.13.3"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "numpy" },-]-sdist = { url = "https://files.pythonhosted.org/packages/6c/b4/3008b3a367251653de280f424b80811a8746a9a6cdf55689d5f619e64b5f/pyqtgraph-0.13.3.tar.gz", hash = "sha256:58108d8411c7054e0841d8b791ee85e101fc296b9b359c0e01dde38a98ff2ace", size = 1398392 }-wheels = [- { url = "https://files.pythonhosted.org/packages/61/57/0a096b8949d0ee5ca32de180f19240ddd5a81015a27c6f2e7342b9044d45/pyqtgraph-0.13.3-py3-none-any.whl", hash = "sha256:fdcc04ac4b32a7bedf1bf3cf74cbb93ab3ba5687791712bbfa8d0712377d2f2b", size = 960972 },-]--[[package]]-name = "pyside6"-version = "6.6.3.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "pyside6-addons" },- { name = "pyside6-essentials" },- { name = "shiboken6" },-]-wheels = [- { url = "https://files.pythonhosted.org/packages/ba/9a/3483d05305701ba810192572cee5977ff884c033a1b8f96ab9582d81ccd4/PySide6-6.6.3.1-cp38-abi3-macosx_11_0_universal2.whl", hash = "sha256:3d2ebb08a7744b59e1270e57f264a9ef5b45fccdc0328a9aeb50d890d6b3f4f2", size = 512759 },- { url = "https://files.pythonhosted.org/packages/14/60/dc79d4ea59ed1ebe6062c5db972b31d489ea84315dcf3bd58a2a741c73b3/PySide6-6.6.3.1-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:35936f06257e5c37ae8993da0cb5a528e5db3ea1fc2bb6b12cdf899a11510966", size = 513325 },- { url = "https://files.pythonhosted.org/packages/51/3e/b77d2b9a1efcb5c90a2df4f51eb10bce45b3787c4fa16b69c599fd6620b9/PySide6-6.6.3.1-cp38-abi3-manylinux_2_31_aarch64.whl", hash = "sha256:f7acd26fe8e1a745ef0be66b49ee49ee8ae50c2a2855d9792db262ebc7916d98", size = 513326 },- { url = "https://files.pythonhosted.org/packages/af/90/3164ace42cb80ed55642e965934133d0c49bfa3ea79e43631dd331cdc866/PySide6-6.6.3.1-cp38-abi3-win_amd64.whl", hash = "sha256:d993989a10725c856f5b07f25e0664c5059daa92c259549c9df0972b5b0c7935", size = 520559 },-]--[[package]]-name = "pyside6-addons"-version = "6.6.3.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "pyside6-essentials" },- { name = "shiboken6" },-]-wheels = [- { url = "https://files.pythonhosted.org/packages/5f/43/b4d9264969552450c2e889450908279302360901b530f3ec3eb1154db5bf/PySide6_Addons-6.6.3.1-cp38-abi3-macosx_11_0_universal2.whl", hash = "sha256:31135adc521ed6e3fdc8203507e7e9d72424d6b9ebd245d1189d991e90669d6a", size = 250159667 },- { url = "https://files.pythonhosted.org/packages/02/fc/e265aa0c338ddd8a4f2c3526aadc58f60980508ac56999ba79cf2ce744a7/PySide6_Addons-6.6.3.1-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:7373479565e5bd963b9662857c40c20768bc0b5853334e2076a62cb039e91f74", size = 125913866 },- { url = "https://files.pythonhosted.org/packages/9e/52/d56c3380f300b14f26be8eaf98af71a128e7e7952a2b3f4c8b24b1547e0a/PySide6_Addons-6.6.3.1-cp38-abi3-manylinux_2_31_aarch64.whl", hash = "sha256:3abdc1e21de0c6763e5392af5ed8b2349291318ce235e7c310d84a2f9d5001a9", size = 111711166 },- { url = "https://files.pythonhosted.org/packages/f3/c6/fc354ab30ca87b34fa62794e75a65a6b8bc7f4e858c5fd217b8706a143bb/PySide6_Addons-6.6.3.1-cp38-abi3-win_amd64.whl", hash = "sha256:d8fbcd726dbf3e713e5d5ccc45ff0e1a9edfe336d7190c96cf7e7c7598681239", size = 111743197 },-]--[[package]]-name = "pyside6-essentials"-version = "6.6.3.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "shiboken6" },-]-wheels = [- { url = "https://files.pythonhosted.org/packages/ec/47/69e1c0dd4305a30e01e54257fe08d7719da0464b1e2bd351d23831c0018c/PySide6_Essentials-6.6.3.1-cp38-abi3-macosx_11_0_universal2.whl", hash = "sha256:6c16530b63079711783796584b640cc80a347e0b2dc12651aa2877265df7a008", size = 147274572 },- { url = "https://files.pythonhosted.org/packages/4a/29/2375cccf188862c3297f40cb06832cd48fd98fd5da73b0b296a59f54c9f4/PySide6_Essentials-6.6.3.1-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:1f41f357ce2384576581e76c9c3df1c4fa5b38e347f0bcd0cae7c5bce42a917c", size = 82521622 },- { url = "https://files.pythonhosted.org/packages/0f/2c/d6c6102a1a803f0619932996fed59c90429a09850a2b8c19f44f92dd4189/PySide6_Essentials-6.6.3.1-cp38-abi3-manylinux_2_31_aarch64.whl", hash = "sha256:27034525fdbdd21ef21f20fcd7aaf5c2ffe26f2bcf5269a69dd9492dec7e92aa", size = 66881609 },- { url = "https://files.pythonhosted.org/packages/03/c2/d4e78dd7661889b97e52fbfed908ce65abf1422dc03cc7e90752b52ff1f5/PySide6_Essentials-6.6.3.1-cp38-abi3-win_amd64.whl", hash = "sha256:31f7e70ada44d3cdbe6686670b3df036c720cfeb1dced0f7704e5f5a4be6a764", size = 77264921 },+ { url = "https://files.pythonhosted.org/packages/23/57/74b4eb7a51b9133958daa8409b55de95e44feb694d4e2e3eba81a070ca20/pyqt6_sip-13.10.2-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:8a76a06a8e5c5b1f17a3f6f3c834ca324877e07b960b18b8b9bbfd9c536ec658", size = 112354 },+ { url = "https://files.pythonhosted.org/packages/f2/cb/fdef02e0d6ee8443a9683a43650d61c6474b634b6ae6e1c6f097da6310bf/pyqt6_sip-13.10.2-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9128d770a611200529468397d710bc972f1dcfe12bfcbb09a3ccddcd4d54fa5b", size = 323488 },+ { url = "https://files.pythonhosted.org/packages/8c/5b/8ede8d6234c3ea884cbd097d7d47ff9910fb114efe041af62b4453acd23b/pyqt6_sip-13.10.2-cp314-cp314-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:d820a0fae7315932c08f27dc0a7e33e0f50fe351001601a8eb9cf6f22b04562e", size = 303881 },+ { url = "https://files.pythonhosted.org/packages/be/44/b5e78b072d1594643b0f1ff348f2bf54d4adb5a3f9b9f0989c54e33238d6/pyqt6_sip-13.10.2-cp314-cp314-win_amd64.whl", hash = "sha256:3213bb6e102d3842a3bb7e59d5f6e55f176c80880ff0b39d0dac0cfe58313fb3", size = 55098 },+ { url = "https://files.pythonhosted.org/packages/e2/91/357e9fcef5d830c3d50503d35e0357818aca3540f78748cc214dfa015d00/pyqt6_sip-13.10.2-cp314-cp314-win_arm64.whl", hash = "sha256:ce33ff1f94960ad4b08035e39fa0c3c9a67070bec39ffe3e435c792721504726", size = 46088 },][[package]]name = "pytest"-version = "8.4.1"+version = "9.0.1"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "colorama", marker = "sys_platform == 'win32'" },@@ -1491,9 +1738,9 @@ dependencies = [{ name = "pluggy" },{ name = "pygments" },]-sdist = { url = "https://files.pythonhosted.org/packages/08/ba/45911d754e8eba3d5a841a5ce61a65a685ff1798421ac054f85aa8747dfb/pytest-8.4.1.tar.gz", hash = "sha256:7c67fd69174877359ed9371ec3af8a3d2b04741818c51e5e99cc1742251fa93c", size = 1517714 }+sdist = { url = "https://files.pythonhosted.org/packages/07/56/f013048ac4bc4c1d9be45afd4ab209ea62822fb1598f40687e6bf45dcea4/pytest-9.0.1.tar.gz", hash = "sha256:3e9c069ea73583e255c3b21cf46b8d3c56f6e3a1a8f6da94ccb0fcf57b9d73c8", size = 1564125 }wheels = [- { url = "https://files.pythonhosted.org/packages/29/16/c8a903f4c4dffe7a12843191437d7cd8e32751d5de349d45d3fe69544e87/pytest-8.4.1-py3-none-any.whl", hash = "sha256:539c70ba6fcead8e78eebbf1115e8b589e7565830d7d006a8723f19ac8a0afb7", size = 365474 },+ { url = "https://files.pythonhosted.org/packages/0b/8b/6300fb80f858cda1c51ffa17075df5d846757081d11ab4aa35cef9e6258b/pytest-9.0.1-py3-none-any.whl", hash = "sha256:67be0030d194df2dfa7b556f2e56fb3c3315bd5c8822c6951162b92b32ce7dad", size = 373668 },][[package]]@@ -1526,6 +1773,61 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/de/3d/8161f7711c017e01ac9f008dfddd9410dff3674334c233bde66e7ba65bbf/pywin32_ctypes-0.2.3-py3-none-any.whl", hash = "sha256:8a1513379d709975552d202d942d9837758905c8d01eb82b8bcc30918929e7b8", size = 30756 },]+[[package]]+name = "pyyaml"+version = "6.0.3"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/6d/16/a95b6757765b7b031c9374925bb718d55e0a9ba8a1b6a12d25962ea44347/pyyaml-6.0.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:44edc647873928551a01e7a563d7452ccdebee747728c1080d881d68af7b997e", size = 185826 },+ { url = "https://files.pythonhosted.org/packages/16/19/13de8e4377ed53079ee996e1ab0a9c33ec2faf808a4647b7b4c0d46dd239/pyyaml-6.0.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:652cb6edd41e718550aad172851962662ff2681490a8a711af6a4d288dd96824", size = 175577 },+ { url = "https://files.pythonhosted.org/packages/0c/62/d2eb46264d4b157dae1275b573017abec435397aa59cbcdab6fc978a8af4/pyyaml-6.0.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:10892704fc220243f5305762e276552a0395f7beb4dbf9b14ec8fd43b57f126c", size = 775556 },+ { url = "https://files.pythonhosted.org/packages/10/cb/16c3f2cf3266edd25aaa00d6c4350381c8b012ed6f5276675b9eba8d9ff4/pyyaml-6.0.3-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:850774a7879607d3a6f50d36d04f00ee69e7fc816450e5f7e58d7f17f1ae5c00", size = 882114 },+ { url = "https://files.pythonhosted.org/packages/71/60/917329f640924b18ff085ab889a11c763e0b573da888e8404ff486657602/pyyaml-6.0.3-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b8bb0864c5a28024fac8a632c443c87c5aa6f215c0b126c449ae1a150412f31d", size = 806638 },+ { url = "https://files.pythonhosted.org/packages/dd/6f/529b0f316a9fd167281a6c3826b5583e6192dba792dd55e3203d3f8e655a/pyyaml-6.0.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1d37d57ad971609cf3c53ba6a7e365e40660e3be0e5175fa9f2365a379d6095a", size = 767463 },+ { url = "https://files.pythonhosted.org/packages/f2/6a/b627b4e0c1dd03718543519ffb2f1deea4a1e6d42fbab8021936a4d22589/pyyaml-6.0.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:37503bfbfc9d2c40b344d06b2199cf0e96e97957ab1c1b546fd4f87e53e5d3e4", size = 794986 },+ { url = "https://files.pythonhosted.org/packages/45/91/47a6e1c42d9ee337c4839208f30d9f09caa9f720ec7582917b264defc875/pyyaml-6.0.3-cp311-cp311-win32.whl", hash = "sha256:8098f252adfa6c80ab48096053f512f2321f0b998f98150cea9bd23d83e1467b", size = 142543 },+ { url = "https://files.pythonhosted.org/packages/da/e3/ea007450a105ae919a72393cb06f122f288ef60bba2dc64b26e2646fa315/pyyaml-6.0.3-cp311-cp311-win_amd64.whl", hash = "sha256:9f3bfb4965eb874431221a3ff3fdcddc7e74e3b07799e0e84ca4a0f867d449bf", size = 158763 },+ { url = "https://files.pythonhosted.org/packages/d1/33/422b98d2195232ca1826284a76852ad5a86fe23e31b009c9886b2d0fb8b2/pyyaml-6.0.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196", size = 182063 },+ { url = "https://files.pythonhosted.org/packages/89/a0/6cf41a19a1f2f3feab0e9c0b74134aa2ce6849093d5517a0c550fe37a648/pyyaml-6.0.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0", size = 173973 },+ { url = "https://files.pythonhosted.org/packages/ed/23/7a778b6bd0b9a8039df8b1b1d80e2e2ad78aa04171592c8a5c43a56a6af4/pyyaml-6.0.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28", size = 775116 },+ { url = "https://files.pythonhosted.org/packages/65/30/d7353c338e12baef4ecc1b09e877c1970bd3382789c159b4f89d6a70dc09/pyyaml-6.0.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c", size = 844011 },+ { url = "https://files.pythonhosted.org/packages/8b/9d/b3589d3877982d4f2329302ef98a8026e7f4443c765c46cfecc8858c6b4b/pyyaml-6.0.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc", size = 807870 },+ { url = "https://files.pythonhosted.org/packages/05/c0/b3be26a015601b822b97d9149ff8cb5ead58c66f981e04fedf4e762f4bd4/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e", size = 761089 },+ { url = "https://files.pythonhosted.org/packages/be/8e/98435a21d1d4b46590d5459a22d88128103f8da4c2d4cb8f14f2a96504e1/pyyaml-6.0.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea", size = 790181 },+ { url = "https://files.pythonhosted.org/packages/74/93/7baea19427dcfbe1e5a372d81473250b379f04b1bd3c4c5ff825e2327202/pyyaml-6.0.3-cp312-cp312-win32.whl", hash = "sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5", size = 137658 },+ { url = "https://files.pythonhosted.org/packages/86/bf/899e81e4cce32febab4fb42bb97dcdf66bc135272882d1987881a4b519e9/pyyaml-6.0.3-cp312-cp312-win_amd64.whl", hash = "sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b", size = 154003 },+ { url = "https://files.pythonhosted.org/packages/1a/08/67bd04656199bbb51dbed1439b7f27601dfb576fb864099c7ef0c3e55531/pyyaml-6.0.3-cp312-cp312-win_arm64.whl", hash = "sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd", size = 140344 },+ { url = "https://files.pythonhosted.org/packages/d1/11/0fd08f8192109f7169db964b5707a2f1e8b745d4e239b784a5a1dd80d1db/pyyaml-6.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8", size = 181669 },+ { url = "https://files.pythonhosted.org/packages/b1/16/95309993f1d3748cd644e02e38b75d50cbc0d9561d21f390a76242ce073f/pyyaml-6.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1", size = 173252 },+ { url = "https://files.pythonhosted.org/packages/50/31/b20f376d3f810b9b2371e72ef5adb33879b25edb7a6d072cb7ca0c486398/pyyaml-6.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c", size = 767081 },+ { url = "https://files.pythonhosted.org/packages/49/1e/a55ca81e949270d5d4432fbbd19dfea5321eda7c41a849d443dc92fd1ff7/pyyaml-6.0.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5", size = 841159 },+ { url = "https://files.pythonhosted.org/packages/74/27/e5b8f34d02d9995b80abcef563ea1f8b56d20134d8f4e5e81733b1feceb2/pyyaml-6.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6", size = 801626 },+ { url = "https://files.pythonhosted.org/packages/f9/11/ba845c23988798f40e52ba45f34849aa8a1f2d4af4b798588010792ebad6/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6", size = 753613 },+ { url = "https://files.pythonhosted.org/packages/3d/e0/7966e1a7bfc0a45bf0a7fb6b98ea03fc9b8d84fa7f2229e9659680b69ee3/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be", size = 794115 },+ { url = "https://files.pythonhosted.org/packages/de/94/980b50a6531b3019e45ddeada0626d45fa85cbe22300844a7983285bed3b/pyyaml-6.0.3-cp313-cp313-win32.whl", hash = "sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26", size = 137427 },+ { url = "https://files.pythonhosted.org/packages/97/c9/39d5b874e8b28845e4ec2202b5da735d0199dbe5b8fb85f91398814a9a46/pyyaml-6.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c", size = 154090 },+ { url = "https://files.pythonhosted.org/packages/73/e8/2bdf3ca2090f68bb3d75b44da7bbc71843b19c9f2b9cb9b0f4ab7a5a4329/pyyaml-6.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb", size = 140246 },+ { url = "https://files.pythonhosted.org/packages/9d/8c/f4bd7f6465179953d3ac9bc44ac1a8a3e6122cf8ada906b4f96c60172d43/pyyaml-6.0.3-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac", size = 181814 },+ { url = "https://files.pythonhosted.org/packages/bd/9c/4d95bb87eb2063d20db7b60faa3840c1b18025517ae857371c4dd55a6b3a/pyyaml-6.0.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310", size = 173809 },+ { url = "https://files.pythonhosted.org/packages/92/b5/47e807c2623074914e29dabd16cbbdd4bf5e9b2db9f8090fa64411fc5382/pyyaml-6.0.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7", size = 766454 },+ { url = "https://files.pythonhosted.org/packages/02/9e/e5e9b168be58564121efb3de6859c452fccde0ab093d8438905899a3a483/pyyaml-6.0.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788", size = 836355 },+ { url = "https://files.pythonhosted.org/packages/88/f9/16491d7ed2a919954993e48aa941b200f38040928474c9e85ea9e64222c3/pyyaml-6.0.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5", size = 794175 },+ { url = "https://files.pythonhosted.org/packages/dd/3f/5989debef34dc6397317802b527dbbafb2b4760878a53d4166579111411e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764", size = 755228 },+ { url = "https://files.pythonhosted.org/packages/d7/ce/af88a49043cd2e265be63d083fc75b27b6ed062f5f9fd6cdc223ad62f03e/pyyaml-6.0.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35", size = 789194 },+ { url = "https://files.pythonhosted.org/packages/23/20/bb6982b26a40bb43951265ba29d4c246ef0ff59c9fdcdf0ed04e0687de4d/pyyaml-6.0.3-cp314-cp314-win_amd64.whl", hash = "sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac", size = 156429 },+ { url = "https://files.pythonhosted.org/packages/f4/f4/a4541072bb9422c8a883ab55255f918fa378ecf083f5b85e87fc2b4eda1b/pyyaml-6.0.3-cp314-cp314-win_arm64.whl", hash = "sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3", size = 143912 },+ { url = "https://files.pythonhosted.org/packages/7c/f9/07dd09ae774e4616edf6cda684ee78f97777bdd15847253637a6f052a62f/pyyaml-6.0.3-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3", size = 189108 },+ { url = "https://files.pythonhosted.org/packages/4e/78/8d08c9fb7ce09ad8c38ad533c1191cf27f7ae1effe5bb9400a46d9437fcf/pyyaml-6.0.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba", size = 183641 },+ { url = "https://files.pythonhosted.org/packages/7b/5b/3babb19104a46945cf816d047db2788bcaf8c94527a805610b0289a01c6b/pyyaml-6.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c", size = 831901 },+ { url = "https://files.pythonhosted.org/packages/8b/cc/dff0684d8dc44da4d22a13f35f073d558c268780ce3c6ba1b87055bb0b87/pyyaml-6.0.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702", size = 861132 },+ { url = "https://files.pythonhosted.org/packages/b1/5e/f77dc6b9036943e285ba76b49e118d9ea929885becb0a29ba8a7c75e29fe/pyyaml-6.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c", size = 839261 },+ { url = "https://files.pythonhosted.org/packages/ce/88/a9db1376aa2a228197c58b37302f284b5617f56a5d959fd1763fb1675ce6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065", size = 805272 },+ { url = "https://files.pythonhosted.org/packages/da/92/1446574745d74df0c92e6aa4a7b0b3130706a4142b2d1a5869f2eaa423c6/pyyaml-6.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65", size = 829923 },+ { url = "https://files.pythonhosted.org/packages/f0/7a/1c7270340330e575b92f397352af856a8c06f230aa3e76f86b39d01b416a/pyyaml-6.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9", size = 174062 },+ { url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341 },+]+[[package]]name = "requests"version = "2.32.5"@@ -1543,94 +1845,125 @@ wheels = [[[package]]name = "rich"-version = "13.7.0"+version = "14.2.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "markdown-it-py" },{ name = "pygments" },]-sdist = { url = "https://files.pythonhosted.org/packages/a7/ec/4a7d80728bd429f7c0d4d51245287158a1516315cadbb146012439403a9d/rich-13.7.0.tar.gz", hash = "sha256:5cb5123b5cf9ee70584244246816e9114227e0b98ad9176eede6ad54bf5403fa", size = 221168 }+sdist = { url = "https://files.pythonhosted.org/packages/fb/d2/8920e102050a0de7bfabeb4c4614a49248cf8d5d7a8d01885fbb24dc767a/rich-14.2.0.tar.gz", hash = "sha256:73ff50c7c0c1c77c8243079283f4edb376f0f6442433aecb8ce7e6d0b92d1fe4", size = 219990 }wheels = [- { url = "https://files.pythonhosted.org/packages/be/be/1520178fa01eabe014b16e72a952b9f900631142ccd03dc36cf93e30c1ce/rich-13.7.0-py3-none-any.whl", hash = "sha256:6da14c108c4866ee9520bbffa71f6fe3962e193b7da68720583850cd4548e235", size = 240632 },+ { url = "https://files.pythonhosted.org/packages/25/7a/b0178788f8dc6cafce37a212c99565fa1fe7872c70c6c9c1e1a372d9d88f/rich-14.2.0-py3-none-any.whl", hash = "sha256:76bc51fe2e57d2b1be1f96c524b890b816e334ab4c1e45888799bfaab0021edd", size = 243393 },+]++[[package]]+name = "scikit-learn"+version = "1.7.2"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "joblib" },+ { name = "numpy" },+ { name = "scipy" },+ { name = "threadpoolctl" },+]+sdist = { url = "https://files.pythonhosted.org/packages/98/c2/a7855e41c9d285dfe86dc50b250978105dce513d6e459ea66a6aeb0e1e0c/scikit_learn-1.7.2.tar.gz", hash = "sha256:20e9e49ecd130598f1ca38a1d85090e1a600147b9c02fa6f15d69cb53d968fda", size = 7193136 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/43/83/564e141eef908a5863a54da8ca342a137f45a0bfb71d1d79704c9894c9d1/scikit_learn-1.7.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c7509693451651cd7361d30ce4e86a1347493554f172b1c72a39300fa2aea79e", size = 9331967 },+ { url = "https://files.pythonhosted.org/packages/18/d6/ba863a4171ac9d7314c4d3fc251f015704a2caeee41ced89f321c049ed83/scikit_learn-1.7.2-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:0486c8f827c2e7b64837c731c8feff72c0bd2b998067a8a9cbc10643c31f0fe1", size = 8648645 },+ { url = "https://files.pythonhosted.org/packages/ef/0e/97dbca66347b8cf0ea8b529e6bb9367e337ba2e8be0ef5c1a545232abfde/scikit_learn-1.7.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:89877e19a80c7b11a2891a27c21c4894fb18e2c2e077815bcade10d34287b20d", size = 9715424 },+ { url = "https://files.pythonhosted.org/packages/f7/32/1f3b22e3207e1d2c883a7e09abb956362e7d1bd2f14458c7de258a26ac15/scikit_learn-1.7.2-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8da8bf89d4d79aaec192d2bda62f9b56ae4e5b4ef93b6a56b5de4977e375c1f1", size = 9509234 },+ { url = "https://files.pythonhosted.org/packages/9f/71/34ddbd21f1da67c7a768146968b4d0220ee6831e4bcbad3e03dd3eae88b6/scikit_learn-1.7.2-cp311-cp311-win_amd64.whl", hash = "sha256:9b7ed8d58725030568523e937c43e56bc01cadb478fc43c042a9aca1dacb3ba1", size = 8894244 },+ { url = "https://files.pythonhosted.org/packages/a7/aa/3996e2196075689afb9fce0410ebdb4a09099d7964d061d7213700204409/scikit_learn-1.7.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:8d91a97fa2b706943822398ab943cde71858a50245e31bc71dba62aab1d60a96", size = 9259818 },+ { url = "https://files.pythonhosted.org/packages/43/5d/779320063e88af9c4a7c2cf463ff11c21ac9c8bd730c4a294b0000b666c9/scikit_learn-1.7.2-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:acbc0f5fd2edd3432a22c69bed78e837c70cf896cd7993d71d51ba6708507476", size = 8636997 },+ { url = "https://files.pythonhosted.org/packages/5c/d0/0c577d9325b05594fdd33aa970bf53fb673f051a45496842caee13cfd7fe/scikit_learn-1.7.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e5bf3d930aee75a65478df91ac1225ff89cd28e9ac7bd1196853a9229b6adb0b", size = 9478381 },+ { url = "https://files.pythonhosted.org/packages/82/70/8bf44b933837ba8494ca0fc9a9ab60f1c13b062ad0197f60a56e2fc4c43e/scikit_learn-1.7.2-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b4d6e9deed1a47aca9fe2f267ab8e8fe82ee20b4526b2c0cd9e135cea10feb44", size = 9300296 },+ { url = "https://files.pythonhosted.org/packages/c6/99/ed35197a158f1fdc2fe7c3680e9c70d0128f662e1fee4ed495f4b5e13db0/scikit_learn-1.7.2-cp312-cp312-win_amd64.whl", hash = "sha256:6088aa475f0785e01bcf8529f55280a3d7d298679f50c0bb70a2364a82d0b290", size = 8731256 },+ { url = "https://files.pythonhosted.org/packages/ae/93/a3038cb0293037fd335f77f31fe053b89c72f17b1c8908c576c29d953e84/scikit_learn-1.7.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0b7dacaa05e5d76759fb071558a8b5130f4845166d88654a0f9bdf3eb57851b7", size = 9212382 },+ { url = "https://files.pythonhosted.org/packages/40/dd/9a88879b0c1104259136146e4742026b52df8540c39fec21a6383f8292c7/scikit_learn-1.7.2-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:abebbd61ad9e1deed54cca45caea8ad5f79e1b93173dece40bb8e0c658dbe6fe", size = 8592042 },+ { url = "https://files.pythonhosted.org/packages/46/af/c5e286471b7d10871b811b72ae794ac5fe2989c0a2df07f0ec723030f5f5/scikit_learn-1.7.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:502c18e39849c0ea1a5d681af1dbcf15f6cce601aebb657aabbfe84133c1907f", size = 9434180 },+ { url = "https://files.pythonhosted.org/packages/f1/fd/df59faa53312d585023b2da27e866524ffb8faf87a68516c23896c718320/scikit_learn-1.7.2-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7a4c328a71785382fe3fe676a9ecf2c86189249beff90bf85e22bdb7efaf9ae0", size = 9283660 },+ { url = "https://files.pythonhosted.org/packages/a7/c7/03000262759d7b6f38c836ff9d512f438a70d8a8ddae68ee80de72dcfb63/scikit_learn-1.7.2-cp313-cp313-win_amd64.whl", hash = "sha256:63a9afd6f7b229aad94618c01c252ce9e6fa97918c5ca19c9a17a087d819440c", size = 8702057 },+ { url = "https://files.pythonhosted.org/packages/55/87/ef5eb1f267084532c8e4aef98a28b6ffe7425acbfd64b5e2f2e066bc29b3/scikit_learn-1.7.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:9acb6c5e867447b4e1390930e3944a005e2cb115922e693c08a323421a6966e8", size = 9558731 },+ { url = "https://files.pythonhosted.org/packages/93/f8/6c1e3fc14b10118068d7938878a9f3f4e6d7b74a8ddb1e5bed65159ccda8/scikit_learn-1.7.2-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:2a41e2a0ef45063e654152ec9d8bcfc39f7afce35b08902bfe290c2498a67a6a", size = 9038852 },+ { url = "https://files.pythonhosted.org/packages/83/87/066cafc896ee540c34becf95d30375fe5cbe93c3b75a0ee9aa852cd60021/scikit_learn-1.7.2-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:98335fb98509b73385b3ab2bd0639b1f610541d3988ee675c670371d6a87aa7c", size = 9527094 },+ { url = "https://files.pythonhosted.org/packages/9c/2b/4903e1ccafa1f6453b1ab78413938c8800633988c838aa0be386cbb33072/scikit_learn-1.7.2-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:191e5550980d45449126e23ed1d5e9e24b2c68329ee1f691a3987476e115e09c", size = 9367436 },+ { url = "https://files.pythonhosted.org/packages/b5/aa/8444be3cfb10451617ff9d177b3c190288f4563e6c50ff02728be67ad094/scikit_learn-1.7.2-cp313-cp313t-win_amd64.whl", hash = "sha256:57dc4deb1d3762c75d685507fbd0bc17160144b2f2ba4ccea5dc285ab0d0e973", size = 9275749 },+ { url = "https://files.pythonhosted.org/packages/d9/82/dee5acf66837852e8e68df6d8d3a6cb22d3df997b733b032f513d95205b7/scikit_learn-1.7.2-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:fa8f63940e29c82d1e67a45d5297bdebbcb585f5a5a50c4914cc2e852ab77f33", size = 9208906 },+ { url = "https://files.pythonhosted.org/packages/3c/30/9029e54e17b87cb7d50d51a5926429c683d5b4c1732f0507a6c3bed9bf65/scikit_learn-1.7.2-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:f95dc55b7902b91331fa4e5845dd5bde0580c9cd9612b1b2791b7e80c3d32615", size = 8627836 },+ { url = "https://files.pythonhosted.org/packages/60/18/4a52c635c71b536879f4b971c2cedf32c35ee78f48367885ed8025d1f7ee/scikit_learn-1.7.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:9656e4a53e54578ad10a434dc1f993330568cfee176dff07112b8785fb413106", size = 9426236 },+ { url = "https://files.pythonhosted.org/packages/99/7e/290362f6ab582128c53445458a5befd471ed1ea37953d5bcf80604619250/scikit_learn-1.7.2-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96dc05a854add0e50d3f47a1ef21a10a595016da5b007c7d9cd9d0bffd1fcc61", size = 9312593 },+ { url = "https://files.pythonhosted.org/packages/8e/87/24f541b6d62b1794939ae6422f8023703bbf6900378b2b34e0b4384dfefd/scikit_learn-1.7.2-cp314-cp314-win_amd64.whl", hash = "sha256:bb24510ed3f9f61476181e4db51ce801e2ba37541def12dc9333b946fc7a9cf8", size = 8820007 },][[package]]name = "scipy"-version = "1.11.4"+version = "1.16.3"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "numpy" },]-sdist = { url = "https://files.pythonhosted.org/packages/6e/1f/91144ba78dccea567a6466262922786ffc97be1e9b06ed9574ef0edc11e1/scipy-1.11.4.tar.gz", hash = "sha256:90a2b78e7f5733b9de748f589f09225013685f9b218275257f8a8168ededaeaa", size = 56336202 }-wheels = [- { url = "https://files.pythonhosted.org/packages/b8/f2/1aefbd5e54ebd8c6163ccf7f73e5d17bc8cb38738d312befc524fce84bb4/scipy-1.11.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f313b39a7e94f296025e3cffc2c567618174c0b1dde173960cf23808f9fae4be", size = 37159197 },- { url = "https://files.pythonhosted.org/packages/4b/48/20e77ddb1f473d4717a7d4d3fc8d15557f406f7708496054c59f635b7734/scipy-1.11.4-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:1b7c3dca977f30a739e0409fb001056484661cb2541a01aba0bb0029f7b68db8", size = 29675057 },- { url = "https://files.pythonhosted.org/packages/75/2e/a781862190d0e7e76afa74752ef363488a9a9d6ea86e46d5e5506cee8df6/scipy-1.11.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:00150c5eae7b610c32589dda259eacc7c4f1665aedf25d921907f4d08a951b1c", size = 32882747 },- { url = "https://files.pythonhosted.org/packages/6b/d4/d62ce38ba00dc67d7ec4ec5cc19d36958d8ed70e63778715ad626bcbc796/scipy-1.11.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:530f9ad26440e85766509dbf78edcfe13ffd0ab7fec2560ee5c36ff74d6269ff", size = 36402732 },- { url = "https://files.pythonhosted.org/packages/88/86/827b56aea1ed04adbb044a675672a73c84d81076a350092bbfcfc1ae723b/scipy-1.11.4-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:5e347b14fe01003d3b78e196e84bd3f48ffe4c8a7b8a1afbcb8f5505cb710993", size = 36622138 },- { url = "https://files.pythonhosted.org/packages/43/d0/f3cd75b62e1b90f48dbf091261b2fc7ceec14a700e308c50f6a69c83d337/scipy-1.11.4-cp311-cp311-win_amd64.whl", hash = "sha256:acf8ed278cc03f5aff035e69cb511741e0418681d25fbbb86ca65429c4f4d9cd", size = 44095631 },- { url = "https://files.pythonhosted.org/packages/df/64/8a690570485b636da614acff35fd725fcbc487f8b1fa9bdb12871b77412f/scipy-1.11.4-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:028eccd22e654b3ea01ee63705681ee79933652b2d8f873e7949898dda6d11b6", size = 37053653 },- { url = "https://files.pythonhosted.org/packages/5e/43/abf331745a7e5f4af51f13d40e2a72f516048db41ecbcf3ac6f86ada54a3/scipy-1.11.4-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:2c6ff6ef9cc27f9b3db93a6f8b38f97387e6e0591600369a297a50a8e96e835d", size = 29641601 },- { url = "https://files.pythonhosted.org/packages/47/9b/62d0ec086dd2871009da8769c504bec6e39b80f4c182c6ead0fcebd8b323/scipy-1.11.4-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b030c6674b9230d37c5c60ab456e2cf12f6784596d15ce8da9365e70896effc4", size = 32272137 },- { url = "https://files.pythonhosted.org/packages/08/77/f90f7306d755ac68bd159c50bb86fffe38400e533e8c609dd8484bd0f172/scipy-1.11.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ad669df80528aeca5f557712102538f4f37e503f0c5b9541655016dd0932ca79", size = 35777534 },- { url = "https://files.pythonhosted.org/packages/00/de/b9f6938090c37b5092969ba1c67118e9114e8e6ef9d197251671444e839c/scipy-1.11.4-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:ce7fff2e23ab2cc81ff452a9444c215c28e6305f396b2ba88343a567feec9660", size = 35963721 },- { url = "https://files.pythonhosted.org/packages/c6/a1/357e4cd43af2748e1e0407ae0e9a5ea8aaaa6b702833c81be11670dcbad8/scipy-1.11.4-cp312-cp312-win_amd64.whl", hash = "sha256:36750b7733d960d7994888f0d148d31ea3017ac15eef664194b4ef68d36a4a97", size = 43730653 },-]--[[package]]-name = "sentencepiece"-version = "0.2.1"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/15/15/2e7a025fc62d764b151ae6d0f2a92f8081755ebe8d4a64099accc6f77ba6/sentencepiece-0.2.1.tar.gz", hash = "sha256:8138cec27c2f2282f4a34d9a016e3374cd40e5c6e9cb335063db66a0a3b71fad", size = 3228515 }-wheels = [- { url = "https://files.pythonhosted.org/packages/d8/15/46afbab00733d81788b64be430ca1b93011bb9388527958e26cc31832de5/sentencepiece-0.2.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:6356d0986b8b8dc351b943150fcd81a1c6e6e4d439772e8584c64230e58ca987", size = 1942560 },- { url = "https://files.pythonhosted.org/packages/fa/79/7c01b8ef98a0567e9d84a4e7a910f8e7074fcbf398a5cd76f93f4b9316f9/sentencepiece-0.2.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:8f8ba89a3acb3dc1ae90f65ec1894b0b9596fdb98ab003ff38e058f898b39bc7", size = 1325385 },- { url = "https://files.pythonhosted.org/packages/bb/88/2b41e07bd24f33dcf2f18ec3b74247aa4af3526bad8907b8727ea3caba03/sentencepiece-0.2.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:02593eca45440ef39247cee8c47322a34bdcc1d8ae83ad28ba5a899a2cf8d79a", size = 1253319 },- { url = "https://files.pythonhosted.org/packages/a0/54/38a1af0c6210a3c6f95aa46d23d6640636d020fba7135cd0d9a84ada05a7/sentencepiece-0.2.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0a0d15781a171d188b661ae4bde1d998c303f6bd8621498c50c671bd45a4798e", size = 1316162 },- { url = "https://files.pythonhosted.org/packages/ef/66/fb191403ade791ad2c3c1e72fe8413e63781b08cfa3aa4c9dfc536d6e795/sentencepiece-0.2.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4f5a3e0d9f445ed9d66c0fec47d4b23d12cfc858b407a03c194c1b26c2ac2a63", size = 1387785 },- { url = "https://files.pythonhosted.org/packages/a9/2d/3bd9b08e70067b2124518b308db6a84a4f8901cc8a4317e2e4288cdd9b4d/sentencepiece-0.2.1-cp311-cp311-win32.whl", hash = "sha256:6d297a1748d429ba8534eebe5535448d78b8acc32d00a29b49acf28102eeb094", size = 999555 },- { url = "https://files.pythonhosted.org/packages/32/b8/f709977f5fda195ae1ea24f24e7c581163b6f142b1005bc3d0bbfe4d7082/sentencepiece-0.2.1-cp311-cp311-win_amd64.whl", hash = "sha256:82d9ead6591015f009cb1be1cb1c015d5e6f04046dbb8c9588b931e869a29728", size = 1054617 },- { url = "https://files.pythonhosted.org/packages/7a/40/a1fc23be23067da0f703709797b464e8a30a1c78cc8a687120cd58d4d509/sentencepiece-0.2.1-cp311-cp311-win_arm64.whl", hash = "sha256:39f8651bd10974eafb9834ce30d9bcf5b73e1fc798a7f7d2528f9820ca86e119", size = 1033877 },- { url = "https://files.pythonhosted.org/packages/4a/be/32ce495aa1d0e0c323dcb1ba87096037358edee539cac5baf8755a6bd396/sentencepiece-0.2.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:57cae326c8727de58c85977b175af132a7138d84c764635d7e71bbee7e774133", size = 1943152 },- { url = "https://files.pythonhosted.org/packages/88/7e/ff23008899a58678e98c6ff592bf4d368eee5a71af96d0df6b38a039dd4f/sentencepiece-0.2.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:56dd39a3c4d6493db3cdca7e8cc68c6b633f0d4195495cbadfcf5af8a22d05a6", size = 1325651 },- { url = "https://files.pythonhosted.org/packages/19/84/42eb3ce4796777a1b5d3699dfd4dca85113e68b637f194a6c8d786f16a04/sentencepiece-0.2.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:d9381351182ff9888cc80e41c632e7e274b106f450de33d67a9e8f6043da6f76", size = 1253645 },- { url = "https://files.pythonhosted.org/packages/89/fa/d3d5ebcba3cb9e6d3775a096251860c41a6bc53a1b9461151df83fe93255/sentencepiece-0.2.1-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:99f955df238021bf11f0fc37cdb54fd5e5b5f7fd30ecc3d93fb48b6815437167", size = 1316273 },- { url = "https://files.pythonhosted.org/packages/04/88/14f2f4a2b922d8b39be45bf63d79e6cd3a9b2f248b2fcb98a69b12af12f5/sentencepiece-0.2.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0cdfecef430d985f1c2bcbfff3defd1d95dae876fbd0173376012d2d7d24044b", size = 1387881 },- { url = "https://files.pythonhosted.org/packages/fd/b8/903e5ccb77b4ef140605d5d71b4f9e0ad95d456d6184688073ed11712809/sentencepiece-0.2.1-cp312-cp312-win32.whl", hash = "sha256:a483fd29a34c3e34c39ac5556b0a90942bec253d260235729e50976f5dba1068", size = 999540 },- { url = "https://files.pythonhosted.org/packages/2d/81/92df5673c067148c2545b1bfe49adfd775bcc3a169a047f5a0e6575ddaca/sentencepiece-0.2.1-cp312-cp312-win_amd64.whl", hash = "sha256:4cdc7c36234fda305e85c32949c5211faaf8dd886096c7cea289ddc12a2d02de", size = 1054671 },- { url = "https://files.pythonhosted.org/packages/fe/02/c5e3bc518655d714622bec87d83db9cdba1cd0619a4a04e2109751c4f47f/sentencepiece-0.2.1-cp312-cp312-win_arm64.whl", hash = "sha256:daeb5e9e9fcad012324807856113708614d534f596d5008638eb9b40112cd9e4", size = 1033923 },- { url = "https://files.pythonhosted.org/packages/ba/4a/85fbe1706d4d04a7e826b53f327c4b80f849cf1c7b7c5e31a20a97d8f28b/sentencepiece-0.2.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:dcd8161eee7b41aae57ded06272905dbd680a0a04b91edd0f64790c796b2f706", size = 1943150 },- { url = "https://files.pythonhosted.org/packages/c2/83/4cfb393e287509fc2155480b9d184706ef8d9fa8cbf5505d02a5792bf220/sentencepiece-0.2.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:c6c8f42949f419ff8c7e9960dbadcfbc982d7b5efc2f6748210d3dd53a7de062", size = 1325651 },- { url = "https://files.pythonhosted.org/packages/8d/de/5a007fb53b1ab0aafc69d11a5a3dd72a289d5a3e78dcf2c3a3d9b14ffe93/sentencepiece-0.2.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:097f3394e99456e9e4efba1737c3749d7e23563dd1588ce71a3d007f25475fff", size = 1253641 },- { url = "https://files.pythonhosted.org/packages/2c/d2/f552be5928105588f4f4d66ee37dd4c61460d8097e62d0e2e0eec41bc61d/sentencepiece-0.2.1-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d7b670879c370d350557edabadbad1f6561a9e6968126e6debca4029e5547820", size = 1316271 },- { url = "https://files.pythonhosted.org/packages/96/df/0cfe748ace5485be740fed9476dee7877f109da32ed0d280312c94ec259f/sentencepiece-0.2.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c7f0fd2f2693309e6628aeeb2e2faf6edd221134dfccac3308ca0de01f8dab47", size = 1387882 },- { url = "https://files.pythonhosted.org/packages/ac/dd/f7774d42a881ced8e1739f393ab1e82ece39fc9abd4779e28050c2e975b5/sentencepiece-0.2.1-cp313-cp313-win32.whl", hash = "sha256:92b3816aa2339355fda2c8c4e021a5de92180b00aaccaf5e2808972e77a4b22f", size = 999541 },- { url = "https://files.pythonhosted.org/packages/dd/e9/932b9eae6fd7019548321eee1ab8d5e3b3d1294df9d9a0c9ac517c7b636d/sentencepiece-0.2.1-cp313-cp313-win_amd64.whl", hash = "sha256:10ed3dab2044c47f7a2e7b4969b0c430420cdd45735d78c8f853191fa0e3148b", size = 1054669 },- { url = "https://files.pythonhosted.org/packages/c9/3a/76488a00ea7d6931689cda28726a1447d66bf1a4837943489314593d5596/sentencepiece-0.2.1-cp313-cp313-win_arm64.whl", hash = "sha256:ac650534e2251083c5f75dde4ff28896ce7c8904133dc8fef42780f4d5588fcd", size = 1033922 },- { url = "https://files.pythonhosted.org/packages/4a/b6/08fe2ce819e02ccb0296f4843e3f195764ce9829cbda61b7513f29b95718/sentencepiece-0.2.1-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:8dd4b477a7b069648d19363aad0cab9bad2f4e83b2d179be668efa672500dc94", size = 1946052 },- { url = "https://files.pythonhosted.org/packages/ab/d9/1ea0e740591ff4c6fc2b6eb1d7510d02f3fb885093f19b2f3abd1363b402/sentencepiece-0.2.1-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0c0f672da370cc490e4c59d89e12289778310a0e71d176c541e4834759e1ae07", size = 1327408 },- { url = "https://files.pythonhosted.org/packages/99/7e/1fb26e8a21613f6200e1ab88824d5d203714162cf2883248b517deb500b7/sentencepiece-0.2.1-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:ad8493bea8432dae8d6830365352350f3b4144415a1d09c4c8cb8d30cf3b6c3c", size = 1254857 },- { url = "https://files.pythonhosted.org/packages/bc/85/c72fd1f3c7a6010544d6ae07f8ddb38b5e2a7e33bd4318f87266c0bbafbf/sentencepiece-0.2.1-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b81a24733726e3678d2db63619acc5a8dccd074f7aa7a54ecd5ca33ca6d2d596", size = 1315722 },- { url = "https://files.pythonhosted.org/packages/4a/e8/661e5bd82a8aa641fd6c1020bd0e890ef73230a2b7215ddf9c8cd8e941c2/sentencepiece-0.2.1-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0a81799d0a68d618e89063fb423c3001a034c893069135ffe51fee439ae474d6", size = 1387452 },- { url = "https://files.pythonhosted.org/packages/99/5e/ae66c361023a470afcbc1fbb8da722c72ea678a2fcd9a18f1a12598c7501/sentencepiece-0.2.1-cp313-cp313t-win32.whl", hash = "sha256:89a3ea015517c42c0341d0d962f3e6aaf2cf10d71b1932d475c44ba48d00aa2b", size = 1002501 },- { url = "https://files.pythonhosted.org/packages/c1/03/d332828c4ff764e16c1b56c2c8f9a33488bbe796b53fb6b9c4205ddbf167/sentencepiece-0.2.1-cp313-cp313t-win_amd64.whl", hash = "sha256:33f068c9382dc2e7c228eedfd8163b52baa86bb92f50d0488bf2b7da7032e484", size = 1057555 },- { url = "https://files.pythonhosted.org/packages/88/14/5aee0bf0864df9bd82bd59e7711362908e4935e3f9cdc1f57246b5d5c9b9/sentencepiece-0.2.1-cp313-cp313t-win_arm64.whl", hash = "sha256:b3616ad246f360e52c85781e47682d31abfb6554c779e42b65333d4b5f44ecc0", size = 1036042 },- { url = "https://files.pythonhosted.org/packages/24/9c/89eb8b2052f720a612478baf11c8227dcf1dc28cd4ea4c0c19506b5af2a2/sentencepiece-0.2.1-cp314-cp314-macosx_10_13_universal2.whl", hash = "sha256:5d0350b686c320068702116276cfb26c066dc7e65cfef173980b11bb4d606719", size = 1943147 },- { url = "https://files.pythonhosted.org/packages/82/0b/a1432bc87f97c2ace36386ca23e8bd3b91fb40581b5e6148d24b24186419/sentencepiece-0.2.1-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:c7f54a31cde6fa5cb030370566f68152a742f433f8d2be458463d06c208aef33", size = 1325624 },- { url = "https://files.pythonhosted.org/packages/ea/99/bbe054ebb5a5039457c590e0a4156ed073fb0fe9ce4f7523404dd5b37463/sentencepiece-0.2.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c83b85ab2d6576607f31df77ff86f28182be4a8de6d175d2c33ca609925f5da1", size = 1253670 },- { url = "https://files.pythonhosted.org/packages/19/ad/d5c7075f701bd97971d7c2ac2904f227566f51ef0838dfbdfdccb58cd212/sentencepiece-0.2.1-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1855f57db07b51fb51ed6c9c452f570624d2b169b36f0f79ef71a6e6c618cd8b", size = 1316247 },- { url = "https://files.pythonhosted.org/packages/fb/03/35fbe5f3d9a7435eebd0b473e09584bd3cc354ce118b960445b060d33781/sentencepiece-0.2.1-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:01e6912125cb45d3792f530a4d38f8e21bf884d6b4d4ade1b2de5cf7a8d2a52b", size = 1387894 },- { url = "https://files.pythonhosted.org/packages/dc/aa/956ef729aafb6c8f9c443104c9636489093bb5c61d6b90fc27aa1a865574/sentencepiece-0.2.1-cp314-cp314-win32.whl", hash = "sha256:c415c9de1447e0a74ae3fdb2e52f967cb544113a3a5ce3a194df185cbc1f962f", size = 1096698 },- { url = "https://files.pythonhosted.org/packages/b8/cb/fe400d8836952cc535c81a0ce47dc6875160e5fedb71d2d9ff0e9894c2a6/sentencepiece-0.2.1-cp314-cp314-win_amd64.whl", hash = "sha256:881b2e44b14fc19feade3cbed314be37de639fc415375cefaa5bc81a4be137fd", size = 1155115 },- { url = "https://files.pythonhosted.org/packages/32/89/047921cf70f36c7b6b6390876b2399b3633ab73b8d0cb857e5a964238941/sentencepiece-0.2.1-cp314-cp314-win_arm64.whl", hash = "sha256:2005242a16d2dc3ac5fe18aa7667549134d37854823df4c4db244752453b78a8", size = 1133890 },- { url = "https://files.pythonhosted.org/packages/a1/11/5b414b9fae6255b5fb1e22e2ed3dc3a72d3a694e5703910e640ac78346bb/sentencepiece-0.2.1-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:a19adcec27c524cb7069a1c741060add95f942d1cbf7ad0d104dffa0a7d28a2b", size = 1946081 },- { url = "https://files.pythonhosted.org/packages/77/eb/7a5682bb25824db8545f8e5662e7f3e32d72a508fdce086029d89695106b/sentencepiece-0.2.1-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:e37e4b4c4a11662b5db521def4e44d4d30ae69a1743241412a93ae40fdcab4bb", size = 1327406 },- { url = "https://files.pythonhosted.org/packages/03/b0/811dae8fb9f2784e138785d481469788f2e0d0c109c5737372454415f55f/sentencepiece-0.2.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:477c81505db072b3ab627e7eab972ea1025331bd3a92bacbf798df2b75ea86ec", size = 1254846 },- { url = "https://files.pythonhosted.org/packages/ef/23/195b2e7ec85ebb6a547969f60b723c7aca5a75800ece6cc3f41da872d14e/sentencepiece-0.2.1-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:010f025a544ef770bb395091d57cb94deb9652d8972e0d09f71d85d5a0816c8c", size = 1315721 },- { url = "https://files.pythonhosted.org/packages/7e/aa/553dbe4178b5f23eb28e59393dddd64186178b56b81d9b8d5c3ff1c28395/sentencepiece-0.2.1-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:733e59ff1794d26db706cd41fc2d7ca5f6c64a820709cb801dc0ea31780d64ab", size = 1387458 },- { url = "https://files.pythonhosted.org/packages/66/7c/08ff0012507297a4dd74a5420fdc0eb9e3e80f4e88cab1538d7f28db303d/sentencepiece-0.2.1-cp314-cp314t-win32.whl", hash = "sha256:d3233770f78e637dc8b1fda2cd7c3b99ec77e7505041934188a4e7fe751de3b0", size = 1099765 },- { url = "https://files.pythonhosted.org/packages/91/d5/2a69e1ce15881beb9ddfc7e3f998322f5cedcd5e4d244cb74dade9441663/sentencepiece-0.2.1-cp314-cp314t-win_amd64.whl", hash = "sha256:5e4366c97b68218fd30ea72d70c525e6e78a6c0a88650f57ac4c43c63b234a9d", size = 1157807 },- { url = "https://files.pythonhosted.org/packages/f3/16/54f611fcfc2d1c46cbe3ec4169780b2cfa7cf63708ef2b71611136db7513/sentencepiece-0.2.1-cp314-cp314t-win_arm64.whl", hash = "sha256:105e36e75cbac1292642045458e8da677b2342dcd33df503e640f0b457cb6751", size = 1136264 },+sdist = { url = "https://files.pythonhosted.org/packages/0a/ca/d8ace4f98322d01abcd52d381134344bf7b431eba7ed8b42bdea5a3c2ac9/scipy-1.16.3.tar.gz", hash = "sha256:01e87659402762f43bd2fee13370553a17ada367d42e7487800bf2916535aecb", size = 30597883 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/9b/5f/6f37d7439de1455ce9c5a556b8d1db0979f03a796c030bafdf08d35b7bf9/scipy-1.16.3-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:40be6cf99e68b6c4321e9f8782e7d5ff8265af28ef2cd56e9c9b2638fa08ad97", size = 36630881 },+ { url = "https://files.pythonhosted.org/packages/7c/89/d70e9f628749b7e4db2aa4cd89735502ff3f08f7b9b27d2e799485987cd9/scipy-1.16.3-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:8be1ca9170fcb6223cc7c27f4305d680ded114a1567c0bd2bfcbf947d1b17511", size = 28941012 },+ { url = "https://files.pythonhosted.org/packages/a8/a8/0e7a9a6872a923505dbdf6bb93451edcac120363131c19013044a1e7cb0c/scipy-1.16.3-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:bea0a62734d20d67608660f69dcda23e7f90fb4ca20974ab80b6ed40df87a005", size = 20931935 },+ { url = "https://files.pythonhosted.org/packages/bd/c7/020fb72bd79ad798e4dbe53938543ecb96b3a9ac3fe274b7189e23e27353/scipy-1.16.3-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:2a207a6ce9c24f1951241f4693ede2d393f59c07abc159b2cb2be980820e01fb", size = 23534466 },+ { url = "https://files.pythonhosted.org/packages/be/a0/668c4609ce6dbf2f948e167836ccaf897f95fb63fa231c87da7558a374cd/scipy-1.16.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:532fb5ad6a87e9e9cd9c959b106b73145a03f04c7d57ea3e6f6bb60b86ab0876", size = 33593618 },+ { url = "https://files.pythonhosted.org/packages/ca/6e/8942461cf2636cdae083e3eb72622a7fbbfa5cf559c7d13ab250a5dbdc01/scipy-1.16.3-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0151a0749efeaaab78711c78422d413c583b8cdd2011a3c1d6c794938ee9fdb2", size = 35899798 },+ { url = "https://files.pythonhosted.org/packages/79/e8/d0f33590364cdbd67f28ce79368b373889faa4ee959588beddf6daef9abe/scipy-1.16.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:b7180967113560cca57418a7bc719e30366b47959dd845a93206fbed693c867e", size = 36226154 },+ { url = "https://files.pythonhosted.org/packages/39/c1/1903de608c0c924a1749c590064e65810f8046e437aba6be365abc4f7557/scipy-1.16.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:deb3841c925eeddb6afc1e4e4a45e418d19ec7b87c5df177695224078e8ec733", size = 38878540 },+ { url = "https://files.pythonhosted.org/packages/f1/d0/22ec7036ba0b0a35bccb7f25ab407382ed34af0b111475eb301c16f8a2e5/scipy-1.16.3-cp311-cp311-win_amd64.whl", hash = "sha256:53c3844d527213631e886621df5695d35e4f6a75f620dca412bcd292f6b87d78", size = 38722107 },+ { url = "https://files.pythonhosted.org/packages/7b/60/8a00e5a524bb3bf8898db1650d350f50e6cffb9d7a491c561dc9826c7515/scipy-1.16.3-cp311-cp311-win_arm64.whl", hash = "sha256:9452781bd879b14b6f055b26643703551320aa8d79ae064a71df55c00286a184", size = 25506272 },+ { url = "https://files.pythonhosted.org/packages/40/41/5bf55c3f386b1643812f3a5674edf74b26184378ef0f3e7c7a09a7e2ca7f/scipy-1.16.3-cp312-cp312-macosx_10_14_x86_64.whl", hash = "sha256:81fc5827606858cf71446a5e98715ba0e11f0dbc83d71c7409d05486592a45d6", size = 36659043 },+ { url = "https://files.pythonhosted.org/packages/1e/0f/65582071948cfc45d43e9870bf7ca5f0e0684e165d7c9ef4e50d783073eb/scipy-1.16.3-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:c97176013d404c7346bf57874eaac5187d969293bf40497140b0a2b2b7482e07", size = 28898986 },+ { url = "https://files.pythonhosted.org/packages/96/5e/36bf3f0ac298187d1ceadde9051177d6a4fe4d507e8f59067dc9dd39e650/scipy-1.16.3-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:2b71d93c8a9936046866acebc915e2af2e292b883ed6e2cbe5c34beb094b82d9", size = 20889814 },+ { url = "https://files.pythonhosted.org/packages/80/35/178d9d0c35394d5d5211bbff7ac4f2986c5488b59506fef9e1de13ea28d3/scipy-1.16.3-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:3d4a07a8e785d80289dfe66b7c27d8634a773020742ec7187b85ccc4b0e7b686", size = 23565795 },+ { url = "https://files.pythonhosted.org/packages/fa/46/d1146ff536d034d02f83c8afc3c4bab2eddb634624d6529a8512f3afc9da/scipy-1.16.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0553371015692a898e1aa858fed67a3576c34edefa6b7ebdb4e9dde49ce5c203", size = 33349476 },+ { url = "https://files.pythonhosted.org/packages/79/2e/415119c9ab3e62249e18c2b082c07aff907a273741b3f8160414b0e9193c/scipy-1.16.3-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:72d1717fd3b5e6ec747327ce9bda32d5463f472c9dce9f54499e81fbd50245a1", size = 35676692 },+ { url = "https://files.pythonhosted.org/packages/27/82/df26e44da78bf8d2aeaf7566082260cfa15955a5a6e96e6a29935b64132f/scipy-1.16.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:1fb2472e72e24d1530debe6ae078db70fb1605350c88a3d14bc401d6306dbffe", size = 36019345 },+ { url = "https://files.pythonhosted.org/packages/82/31/006cbb4b648ba379a95c87262c2855cd0d09453e500937f78b30f02fa1cd/scipy-1.16.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c5192722cffe15f9329a3948c4b1db789fbb1f05c97899187dcf009b283aea70", size = 38678975 },+ { url = "https://files.pythonhosted.org/packages/c2/7f/acbd28c97e990b421af7d6d6cd416358c9c293fc958b8529e0bd5d2a2a19/scipy-1.16.3-cp312-cp312-win_amd64.whl", hash = "sha256:56edc65510d1331dae01ef9b658d428e33ed48b4f77b1d51caf479a0253f96dc", size = 38555926 },+ { url = "https://files.pythonhosted.org/packages/ce/69/c5c7807fd007dad4f48e0a5f2153038dc96e8725d3345b9ee31b2b7bed46/scipy-1.16.3-cp312-cp312-win_arm64.whl", hash = "sha256:a8a26c78ef223d3e30920ef759e25625a0ecdd0d60e5a8818b7513c3e5384cf2", size = 25463014 },+ { url = "https://files.pythonhosted.org/packages/72/f1/57e8327ab1508272029e27eeef34f2302ffc156b69e7e233e906c2a5c379/scipy-1.16.3-cp313-cp313-macosx_10_14_x86_64.whl", hash = "sha256:d2ec56337675e61b312179a1ad124f5f570c00f920cc75e1000025451b88241c", size = 36617856 },+ { url = "https://files.pythonhosted.org/packages/44/13/7e63cfba8a7452eb756306aa2fd9b37a29a323b672b964b4fdeded9a3f21/scipy-1.16.3-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:16b8bc35a4cc24db80a0ec836a9286d0e31b2503cb2fd7ff7fb0e0374a97081d", size = 28874306 },+ { url = "https://files.pythonhosted.org/packages/15/65/3a9400efd0228a176e6ec3454b1fa998fbbb5a8defa1672c3f65706987db/scipy-1.16.3-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:5803c5fadd29de0cf27fa08ccbfe7a9e5d741bf63e4ab1085437266f12460ff9", size = 20865371 },+ { url = "https://files.pythonhosted.org/packages/33/d7/eda09adf009a9fb81827194d4dd02d2e4bc752cef16737cc4ef065234031/scipy-1.16.3-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:b81c27fc41954319a943d43b20e07c40bdcd3ff7cf013f4fb86286faefe546c4", size = 23524877 },+ { url = "https://files.pythonhosted.org/packages/7d/6b/3f911e1ebc364cb81320223a3422aab7d26c9c7973109a9cd0f27c64c6c0/scipy-1.16.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0c3b4dd3d9b08dbce0f3440032c52e9e2ab9f96ade2d3943313dfe51a7056959", size = 33342103 },+ { url = "https://files.pythonhosted.org/packages/21/f6/4bfb5695d8941e5c570a04d9fcd0d36bce7511b7d78e6e75c8f9791f82d0/scipy-1.16.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7dc1360c06535ea6116a2220f760ae572db9f661aba2d88074fe30ec2aa1ff88", size = 35697297 },+ { url = "https://files.pythonhosted.org/packages/04/e1/6496dadbc80d8d896ff72511ecfe2316b50313bfc3ebf07a3f580f08bd8c/scipy-1.16.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:663b8d66a8748051c3ee9c96465fb417509315b99c71550fda2591d7dd634234", size = 36021756 },+ { url = "https://files.pythonhosted.org/packages/fe/bd/a8c7799e0136b987bda3e1b23d155bcb31aec68a4a472554df5f0937eef7/scipy-1.16.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:eab43fae33a0c39006a88096cd7b4f4ef545ea0447d250d5ac18202d40b6611d", size = 38696566 },+ { url = "https://files.pythonhosted.org/packages/cd/01/1204382461fcbfeb05b6161b594f4007e78b6eba9b375382f79153172b4d/scipy-1.16.3-cp313-cp313-win_amd64.whl", hash = "sha256:062246acacbe9f8210de8e751b16fc37458213f124bef161a5a02c7a39284304", size = 38529877 },+ { url = "https://files.pythonhosted.org/packages/7f/14/9d9fbcaa1260a94f4bb5b64ba9213ceb5d03cd88841fe9fd1ffd47a45b73/scipy-1.16.3-cp313-cp313-win_arm64.whl", hash = "sha256:50a3dbf286dbc7d84f176f9a1574c705f277cb6565069f88f60db9eafdbe3ee2", size = 25455366 },+ { url = "https://files.pythonhosted.org/packages/e2/a3/9ec205bd49f42d45d77f1730dbad9ccf146244c1647605cf834b3a8c4f36/scipy-1.16.3-cp313-cp313t-macosx_10_14_x86_64.whl", hash = "sha256:fb4b29f4cf8cc5a8d628bc8d8e26d12d7278cd1f219f22698a378c3d67db5e4b", size = 37027931 },+ { url = "https://files.pythonhosted.org/packages/25/06/ca9fd1f3a4589cbd825b1447e5db3a8ebb969c1eaf22c8579bd286f51b6d/scipy-1.16.3-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:8d09d72dc92742988b0e7750bddb8060b0c7079606c0d24a8cc8e9c9c11f9079", size = 29400081 },+ { url = "https://files.pythonhosted.org/packages/6a/56/933e68210d92657d93fb0e381683bc0e53a965048d7358ff5fbf9e6a1b17/scipy-1.16.3-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:03192a35e661470197556de24e7cb1330d84b35b94ead65c46ad6f16f6b28f2a", size = 21391244 },+ { url = "https://files.pythonhosted.org/packages/a8/7e/779845db03dc1418e215726329674b40576879b91814568757ff0014ad65/scipy-1.16.3-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:57d01cb6f85e34f0946b33caa66e892aae072b64b034183f3d87c4025802a119", size = 23929753 },+ { url = "https://files.pythonhosted.org/packages/4c/4b/f756cf8161d5365dcdef9e5f460ab226c068211030a175d2fc7f3f41ca64/scipy-1.16.3-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:96491a6a54e995f00a28a3c3badfff58fd093bf26cd5fb34a2188c8c756a3a2c", size = 33496912 },+ { url = "https://files.pythonhosted.org/packages/09/b5/222b1e49a58668f23839ca1542a6322bb095ab8d6590d4f71723869a6c2c/scipy-1.16.3-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:cd13e354df9938598af2be05822c323e97132d5e6306b83a3b4ee6724c6e522e", size = 35802371 },+ { url = "https://files.pythonhosted.org/packages/c1/8d/5964ef68bb31829bde27611f8c9deeac13764589fe74a75390242b64ca44/scipy-1.16.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:63d3cdacb8a824a295191a723ee5e4ea7768ca5ca5f2838532d9f2e2b3ce2135", size = 36190477 },+ { url = "https://files.pythonhosted.org/packages/ab/f2/b31d75cb9b5fa4dd39a0a931ee9b33e7f6f36f23be5ef560bf72e0f92f32/scipy-1.16.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:e7efa2681ea410b10dde31a52b18b0154d66f2485328830e45fdf183af5aefc6", size = 38796678 },+ { url = "https://files.pythonhosted.org/packages/b4/1e/b3723d8ff64ab548c38d87055483714fefe6ee20e0189b62352b5e015bb1/scipy-1.16.3-cp313-cp313t-win_amd64.whl", hash = "sha256:2d1ae2cf0c350e7705168ff2429962a89ad90c2d49d1dd300686d8b2a5af22fc", size = 38640178 },+ { url = "https://files.pythonhosted.org/packages/8e/f3/d854ff38789aca9b0cc23008d607ced9de4f7ab14fa1ca4329f86b3758ca/scipy-1.16.3-cp313-cp313t-win_arm64.whl", hash = "sha256:0c623a54f7b79dd88ef56da19bc2873afec9673a48f3b85b18e4d402bdd29a5a", size = 25803246 },+ { url = "https://files.pythonhosted.org/packages/99/f6/99b10fd70f2d864c1e29a28bbcaa0c6340f9d8518396542d9ea3b4aaae15/scipy-1.16.3-cp314-cp314-macosx_10_14_x86_64.whl", hash = "sha256:875555ce62743e1d54f06cdf22c1e0bc47b91130ac40fe5d783b6dfa114beeb6", size = 36606469 },+ { url = "https://files.pythonhosted.org/packages/4d/74/043b54f2319f48ea940dd025779fa28ee360e6b95acb7cd188fad4391c6b/scipy-1.16.3-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:bb61878c18a470021fb515a843dc7a76961a8daceaaaa8bad1332f1bf4b54657", size = 28872043 },+ { url = "https://files.pythonhosted.org/packages/4d/e1/24b7e50cc1c4ee6ffbcb1f27fe9f4c8b40e7911675f6d2d20955f41c6348/scipy-1.16.3-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:f2622206f5559784fa5c4b53a950c3c7c1cf3e84ca1b9c4b6c03f062f289ca26", size = 20862952 },+ { url = "https://files.pythonhosted.org/packages/dd/3a/3e8c01a4d742b730df368e063787c6808597ccb38636ed821d10b39ca51b/scipy-1.16.3-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:7f68154688c515cdb541a31ef8eb66d8cd1050605be9dcd74199cbd22ac739bc", size = 23508512 },+ { url = "https://files.pythonhosted.org/packages/1f/60/c45a12b98ad591536bfe5330cb3cfe1850d7570259303563b1721564d458/scipy-1.16.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:8b3c820ddb80029fe9f43d61b81d8b488d3ef8ca010d15122b152db77dc94c22", size = 33413639 },+ { url = "https://files.pythonhosted.org/packages/71/bc/35957d88645476307e4839712642896689df442f3e53b0fa016ecf8a3357/scipy-1.16.3-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d3837938ae715fc0fe3c39c0202de3a8853aff22ca66781ddc2ade7554b7e2cc", size = 35704729 },+ { url = "https://files.pythonhosted.org/packages/3b/15/89105e659041b1ca11c386e9995aefacd513a78493656e57789f9d9eab61/scipy-1.16.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:aadd23f98f9cb069b3bd64ddc900c4d277778242e961751f77a8cb5c4b946fb0", size = 36086251 },+ { url = "https://files.pythonhosted.org/packages/1a/87/c0ea673ac9c6cc50b3da2196d860273bc7389aa69b64efa8493bdd25b093/scipy-1.16.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:b7c5f1bda1354d6a19bc6af73a649f8285ca63ac6b52e64e658a5a11d4d69800", size = 38716681 },+ { url = "https://files.pythonhosted.org/packages/91/06/837893227b043fb9b0d13e4bd7586982d8136cb249ffb3492930dab905b8/scipy-1.16.3-cp314-cp314-win_amd64.whl", hash = "sha256:e5d42a9472e7579e473879a1990327830493a7047506d58d73fc429b84c1d49d", size = 39358423 },+ { url = "https://files.pythonhosted.org/packages/95/03/28bce0355e4d34a7c034727505a02d19548549e190bedd13a721e35380b7/scipy-1.16.3-cp314-cp314-win_arm64.whl", hash = "sha256:6020470b9d00245926f2d5bb93b119ca0340f0d564eb6fbaad843eaebf9d690f", size = 26135027 },+ { url = "https://files.pythonhosted.org/packages/b2/6f/69f1e2b682efe9de8fe9f91040f0cd32f13cfccba690512ba4c582b0bc29/scipy-1.16.3-cp314-cp314t-macosx_10_14_x86_64.whl", hash = "sha256:e1d27cbcb4602680a49d787d90664fa4974063ac9d4134813332a8c53dbe667c", size = 37028379 },+ { url = "https://files.pythonhosted.org/packages/7c/2d/e826f31624a5ebbab1cd93d30fd74349914753076ed0593e1d56a98c4fb4/scipy-1.16.3-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:9b9c9c07b6d56a35777a1b4cc8966118fb16cfd8daf6743867d17d36cfad2d40", size = 29400052 },+ { url = "https://files.pythonhosted.org/packages/69/27/d24feb80155f41fd1f156bf144e7e049b4e2b9dd06261a242905e3bc7a03/scipy-1.16.3-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:3a4c460301fb2cffb7f88528f30b3127742cff583603aa7dc964a52c463b385d", size = 21391183 },+ { url = "https://files.pythonhosted.org/packages/f8/d3/1b229e433074c5738a24277eca520a2319aac7465eea7310ea6ae0e98ae2/scipy-1.16.3-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:f667a4542cc8917af1db06366d3f78a5c8e83badd56409f94d1eac8d8d9133fa", size = 23930174 },+ { url = "https://files.pythonhosted.org/packages/16/9d/d9e148b0ec680c0f042581a2be79a28a7ab66c0c4946697f9e7553ead337/scipy-1.16.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f379b54b77a597aa7ee5e697df0d66903e41b9c85a6dd7946159e356319158e8", size = 33497852 },+ { url = "https://files.pythonhosted.org/packages/2f/22/4e5f7561e4f98b7bea63cf3fd7934bff1e3182e9f1626b089a679914d5c8/scipy-1.16.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4aff59800a3b7f786b70bfd6ab551001cb553244988d7d6b8299cb1ea653b353", size = 35798595 },+ { url = "https://files.pythonhosted.org/packages/83/42/6644d714c179429fc7196857866f219fef25238319b650bb32dde7bf7a48/scipy-1.16.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:da7763f55885045036fabcebd80144b757d3db06ab0861415d1c3b7c69042146", size = 36186269 },+ { url = "https://files.pythonhosted.org/packages/ac/70/64b4d7ca92f9cf2e6fc6aaa2eecf80bb9b6b985043a9583f32f8177ea122/scipy-1.16.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ffa6eea95283b2b8079b821dc11f50a17d0571c92b43e2b5b12764dc5f9b285d", size = 38802779 },+ { url = "https://files.pythonhosted.org/packages/61/82/8d0e39f62764cce5ffd5284131e109f07cf8955aef9ab8ed4e3aa5e30539/scipy-1.16.3-cp314-cp314t-win_amd64.whl", hash = "sha256:d9f48cafc7ce94cf9b15c6bffdc443a81a27bf7075cf2dcd5c8b40f85d10c4e7", size = 39471128 },+ { url = "https://files.pythonhosted.org/packages/64/47/a494741db7280eae6dc033510c319e34d42dd41b7ac0c7ead39354d1a2b5/scipy-1.16.3-cp314-cp314t-win_arm64.whl", hash = "sha256:21d9d6b197227a12dcbf9633320a4e34c6b0e51c57268df255a0942983bac562", size = 26464127 },][[package]]@@ -1674,17 +2007,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/a3/dc/17031897dae0efacfea57dfd3a82fdd2a2aeb58e0ff71b77b87e44edc772/setuptools-80.9.0-py3-none-any.whl", hash = "sha256:062d34222ad13e0cc312a4c02d73f059e86a4acbfbdea8f8f76b28c99f306922", size = 1201486 },]-[[package]]-name = "shiboken6"-version = "6.6.3.1"-source = { registry = "https://pypi.org/simple" }-wheels = [- { url = "https://files.pythonhosted.org/packages/af/fb/183b7889168f44b19526f58c571b88e23375150abcbd5b603dd3a288ef7a/shiboken6-6.6.3.1-cp38-abi3-macosx_11_0_universal2.whl", hash = "sha256:2a8df586aa9eb629388b368d3157893083c5217ed3eb637bf182d1948c823a0f", size = 345925 },- { url = "https://files.pythonhosted.org/packages/77/f1/feb2a8be699f91fb27fbe8758b405fb38a22e3ae5bd5e05258dbef18d462/shiboken6-6.6.3.1-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:b1aeff0d79d84ddbdc9970144c1bbc3a52fcb45618d1b33d17d57f99f1246d45", size = 171474 },- { url = "https://files.pythonhosted.org/packages/b9/03/e71f0f3fc35fcc90265d1345e3afa509bbd2d6bb305c6e78427a9b27efea/shiboken6-6.6.3.1-cp38-abi3-manylinux_2_31_aarch64.whl", hash = "sha256:902d9e126ac57cc3841cdc50ba38d53948b40cf667538172f253c4ae7b2dcb2c", size = 162427 },- { url = "https://files.pythonhosted.org/packages/b8/f3/b4153287806a63ee064570ed527f16f9eacedab4f4ea99cb84b55e624e21/shiboken6-6.6.3.1-cp38-abi3-win_amd64.whl", hash = "sha256:88494b5e08a1f235efddbe2b0b225a3a66e07d72b6091fcc2fc5448572453649", size = 1068203 },-]-[[package]]name = "six"version = "1.17.0"@@ -1716,22 +2038,18 @@ wheels = [[[package]]name = "skellycam"version = "2023.9.1086"-source = { git = "https://github.com/freemocap/skellycam?branch=jon%2Fdevelopment#85ad0f6b537da46c35d9b4ace699246db75d2055" }+source = { git = "https://github.com/freemocap/skellycam?branch=jon%2Fdevelopment#81294e899bd220f721bb2f7b69a906b665440719" }dependencies = [{ name = "cv2-enumerate-cameras" },{ name = "fastapi" },{ name = "httpx" },- { name = "nuitka" },{ name = "numpy" },{ name = "numpydantic" },{ name = "opencv-contrib-python" },{ name = "pandas" },{ name = "pillow" },- { name = "pip" },{ name = "psutil" },- { name = "pyaudio" },{ name = "pydantic" },- { name = "pyinstaller" },{ name = "scipy" },{ name = "setproctitle" },{ name = "tabulate" },@@ -1743,14 +2061,12 @@ dependencies = [[[package]]name = "skellyforge"version = "2024.12.1009"-source = { git = "https://github.com/freemocap/skellyforge#c9ba6af7fc1750df146d85e06b45e903c77c8a7e" }+source = { git = "https://github.com/freemocap/skellyforge?branch=jon%2Fdevelopment#eedf81f46886cc9edf95c8d8f4df15df3e99f387" }dependencies = [- { name = "matplotlib" },{ name = "numpy" },{ name = "pandas" },- { name = "pyqtgraph" },- { name = "pyside6" },- { name = "rich" },+ { name = "pyarrow" },+ { name = "pyyaml" },{ name = "scipy" },{ name = "toml" },]@@ -1758,8 +2074,9 @@ dependencies = [[[package]]name = "skellytracker"version = "2024.9.1019"-source = { git = "https://github.com/freemocap/skellytracker?branch=jon%2Fdevelopment#ae3bd730c12e8dcd79fa4ea00e9b8f21e4505f3f" }+source = { git = "https://github.com/freemocap/skellytracker?branch=jon%2Fdevelopment#39abbf930cff2c1e8ccd634be6074184dde05db6" }dependencies = [+ { name = "mediapipe" },{ name = "numpy" },{ name = "numpydantic" },{ name = "opencv-contrib-python" },@@ -1779,30 +2096,30 @@ wheels = [[[package]]name = "sounddevice"-version = "0.5.2"+version = "0.5.3"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "cffi" },]-sdist = { url = "https://files.pythonhosted.org/packages/91/a6/91e9f08ed37c7c9f56b5227c6aea7f2ae63ba2d59520eefb24e82cbdd589/sounddevice-0.5.2.tar.gz", hash = "sha256:c634d51bd4e922d6f0fa5e1a975cc897c947f61d31da9f79ba7ea34dff448b49", size = 53150 }+sdist = { url = "https://files.pythonhosted.org/packages/4e/4f/28e734898b870db15b6474453f19813d3c81b91c806d9e6f867bd6e4dd03/sounddevice-0.5.3.tar.gz", hash = "sha256:cbac2b60198fbab84533697e7c4904cc895ec69d5fb3973556c9eb74a4629b2c", size = 53465 }wheels = [- { url = "https://files.pythonhosted.org/packages/75/2d/582738fc01352a5bc20acac9221e58538365cecb3bb264838f66419df219/sounddevice-0.5.2-py3-none-any.whl", hash = "sha256:82375859fac2e73295a4ab3fc60bd4782743157adc339561c1f1142af472f505", size = 32450 },- { url = "https://files.pythonhosted.org/packages/3f/6f/e3dd751face4fcb5be25e8abba22f25d8e6457ebd7e9ed79068b768dc0e5/sounddevice-0.5.2-py3-none-macosx_10_6_x86_64.macosx_10_6_universal2.whl", hash = "sha256:943f27e66037d41435bdd0293454072cdf657b594c9cde63cd01ee3daaac7ab3", size = 108088 },- { url = "https://files.pythonhosted.org/packages/45/0b/bfad79af0b380aa7c0bfe73e4b03e0af45354a48ad62549489bd7696c5b0/sounddevice-0.5.2-py3-none-win32.whl", hash = "sha256:3a113ce614a2c557f14737cb20123ae6298c91fc9301eb014ada0cba6d248c5f", size = 312665 },- { url = "https://files.pythonhosted.org/packages/e1/3e/61d88e6b0a7383127cdc779195cb9d83ebcf11d39bc961de5777e457075e/sounddevice-0.5.2-py3-none-win_amd64.whl", hash = "sha256:e18944b767d2dac3771a7771bdd7ff7d3acd7d334e72c4bedab17d1aed5dbc22", size = 363808 },+ { url = "https://files.pythonhosted.org/packages/73/e7/9020e9f0f3df00432728f4c4044387468a743e3d9a4f91123d77be10010e/sounddevice-0.5.3-py3-none-any.whl", hash = "sha256:ea7738baa0a9f9fef7390f649e41c9f2c8ada776180e56c2ffd217133c92a806", size = 32670 },+ { url = "https://files.pythonhosted.org/packages/2f/39/714118f8413e0e353436914f2b976665161f1be2b6483ac15a8f61484c14/sounddevice-0.5.3-py3-none-macosx_10_6_x86_64.macosx_10_6_universal2.whl", hash = "sha256:278dc4451fff70934a176df048b77d80d7ce1623a6ec9db8b34b806f3112f9c2", size = 108306 },+ { url = "https://files.pythonhosted.org/packages/f5/74/52186e3e5c833d00273f7949a9383adff93692c6e02406bf359cb4d3e921/sounddevice-0.5.3-py3-none-win32.whl", hash = "sha256:845d6927bcf14e84be5292a61ab3359cf8e6b9145819ec6f3ac2619ff089a69c", size = 312882 },+ { url = "https://files.pythonhosted.org/packages/66/c7/16123d054aef6d445176c9122bfbe73c11087589b2413cab22aff5a7839a/sounddevice-0.5.3-py3-none-win_amd64.whl", hash = "sha256:f55ad20082efc2bdec06928e974fbcae07bc6c405409ae1334cefe7d377eb687", size = 364025 },][[package]]name = "starlette"-version = "0.47.3"+version = "0.49.3"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "anyio" },{ name = "typing-extensions", marker = "python_full_version < '3.13'" },]-sdist = { url = "https://files.pythonhosted.org/packages/15/b9/cc3017f9a9c9b6e27c5106cc10cc7904653c3eec0729793aec10479dd669/starlette-0.47.3.tar.gz", hash = "sha256:6bc94f839cc176c4858894f1f8908f0ab79dfec1a6b8402f6da9be26ebea52e9", size = 2584144 }+sdist = { url = "https://files.pythonhosted.org/packages/de/1a/608df0b10b53b0beb96a37854ee05864d182ddd4b1156a22f1ad3860425a/starlette-0.49.3.tar.gz", hash = "sha256:1c14546f299b5901a1ea0e34410575bc33bbd741377a10484a54445588d00284", size = 2655031 }wheels = [- { url = "https://files.pythonhosted.org/packages/ce/fd/901cfa59aaa5b30a99e16876f11abe38b59a1a2c51ffb3d7142bb6089069/starlette-0.47.3-py3-none-any.whl", hash = "sha256:89c0778ca62a76b826101e7c709e70680a1699ca7da6b44d38eb0a7e61fe4b51", size = 72991 },+ { url = "https://files.pythonhosted.org/packages/a3/e0/021c772d6a662f43b63044ab481dc6ac7592447605b5b35a957785363122/starlette-0.49.3-py3-none-any.whl", hash = "sha256:b579b99715fdc2980cf88c8ec96d3bf1ce16f5a8051a7c2b84ef9b1cdecaea2f", size = 74340 },][[package]]@@ -1814,6 +2131,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/40/44/4a5f08c96eb108af5cb50b41f76142f0afa346dfa99d5296fe7202a11854/tabulate-0.9.0-py3-none-any.whl", hash = "sha256:024ca478df22e9340661486f85298cff5f6dcdba14f3813e8830015b9ed1948f", size = 35252 },]+[[package]]+name = "threadpoolctl"+version = "3.6.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/b7/4d/08c89e34946fce2aec4fbb45c9016efd5f4d7f24af8e5d93296e935631d8/threadpoolctl-3.6.0.tar.gz", hash = "sha256:8ab8b4aa3491d812b623328249fab5302a68d2d71745c8a4c719a2fcaba9f44e", size = 21274 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/32/d5/f9a850d79b0851d1d4ef6456097579a9005b31fea68726a4ae5f2d82ddd9/threadpoolctl-3.6.0-py3-none-any.whl", hash = "sha256:43a0b8fd5a2928500110039e43a5eed8480b918967083ea48dc3ab9f13c4a7fb", size = 18638 },+]+[[package]]name = "toml"version = "0.10.2"@@ -1846,14 +2172,14 @@ wheels = [[[package]]name = "typing-inspection"-version = "0.4.1"+version = "0.4.2"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "typing-extensions" },]-sdist = { url = "https://files.pythonhosted.org/packages/f8/b1/0c11f5058406b3af7609f121aaa6b609744687f1d158b3c3a5bf4cc94238/typing_inspection-0.4.1.tar.gz", hash = "sha256:6ae134cc0203c33377d43188d4064e9b357dba58cff3185f22924610e70a9d28", size = 75726 }+sdist = { url = "https://files.pythonhosted.org/packages/55/e3/70399cb7dd41c10ac53367ae42139cf4b1ca5f36bb3dc6c9d33acdb43655/typing_inspection-0.4.2.tar.gz", hash = "sha256:ba561c48a67c5958007083d386c3295464928b01faa735ab8547c5692e87f464", size = 75949 }wheels = [- { url = "https://files.pythonhosted.org/packages/17/69/cd203477f944c353c31bade965f880aa1061fd6bf05ded0726ca845b6ff7/typing_inspection-0.4.1-py3-none-any.whl", hash = "sha256:389055682238f53b04f7badcb49b989835495a96700ced5dab2d8feae4b26f51", size = 14552 },+ { url = "https://files.pythonhosted.org/packages/dc/9b/47798a6c91d8bdb567fe2698fe81e0c6b7cb7ef4d13da4114b41d239f65d/typing_inspection-0.4.2-py3-none-any.whl", hash = "sha256:4ed1cacbdc298c220f1bd249ed5287caa16f34d44ef4e9c3d0cbad5b521545e7", size = 14611 },][[package]]@@ -1888,15 +2214,15 @@ wheels = [[[package]]name = "uvicorn"-version = "0.35.0"+version = "0.38.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "click" },{ name = "h11" },]-sdist = { url = "https://files.pythonhosted.org/packages/5e/42/e0e305207bb88c6b8d3061399c6a961ffe5fbb7e2aa63c9234df7259e9cd/uvicorn-0.35.0.tar.gz", hash = "sha256:bc662f087f7cf2ce11a1d7fd70b90c9f98ef2e2831556dd078d131b96cc94a01", size = 78473 }+sdist = { url = "https://files.pythonhosted.org/packages/cb/ce/f06b84e2697fef4688ca63bdb2fdf113ca0a3be33f94488f2cadb690b0cf/uvicorn-0.38.0.tar.gz", hash = "sha256:fd97093bdd120a2609fc0d3afe931d4d4ad688b6e75f0f929fde1bc36fe0e91d", size = 80605 }wheels = [- { url = "https://files.pythonhosted.org/packages/d2/e2/dc81b1bd1dcfe91735810265e9d26bc8ec5da45b4c0f6237e286819194c3/uvicorn-0.35.0-py3-none-any.whl", hash = "sha256:197535216b25ff9b785e29a0b79199f55222193d47f820816e7da751e9bc8d4a", size = 66406 },+ { url = "https://files.pythonhosted.org/packages/ee/d9/d88e73ca598f4f6ff671fb5fde8a32925c2e08a637303a1d12883c7305fa/uvicorn-0.38.0-py3-none-any.whl", hash = "sha256:48c0afd214ceb59340075b4a052ea1ee91c16fbc2a9b1469cca0e54566977b02", size = 68109 },][[package]]@@ -1940,77 +2266,3 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/1b/6c/c65773d6cab416a64d191d6ee8a8b1c68a09970ea6909d16965d26bfed1e/websockets-15.0.1-cp313-cp313-win_amd64.whl", hash = "sha256:e09473f095a819042ecb2ab9465aee615bd9c2028e4ef7d933600a8401c79561", size = 176837 },{ url = "https://files.pythonhosted.org/packages/fa/a8/5b41e0da817d64113292ab1f8247140aac61cbf6cfd085d6a0fa77f4984f/websockets-15.0.1-py3-none-any.whl", hash = "sha256:f7a866fbc1e97b5c617ee4116daaa09b722101d4a3c170c787450ba409f9736f", size = 169743 },]--[[package]]-name = "zstandard"-version = "0.24.0"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/09/1b/c20b2ef1d987627765dcd5bf1dadb8ef6564f00a87972635099bb76b7a05/zstandard-0.24.0.tar.gz", hash = "sha256:fe3198b81c00032326342d973e526803f183f97aa9e9a98e3f897ebafe21178f", size = 905681 }-wheels = [- { url = "https://files.pythonhosted.org/packages/01/1f/5c72806f76043c0ef9191a2b65281dacdf3b65b0828eb13bb2c987c4fb90/zstandard-0.24.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:addfc23e3bd5f4b6787b9ca95b2d09a1a67ad5a3c318daaa783ff90b2d3a366e", size = 795228 },- { url = "https://files.pythonhosted.org/packages/0b/ba/3059bd5cd834666a789251d14417621b5c61233bd46e7d9023ea8bc1043a/zstandard-0.24.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:6b005bcee4be9c3984b355336283afe77b2defa76ed6b89332eced7b6fa68b68", size = 640520 },- { url = "https://files.pythonhosted.org/packages/57/07/f0e632bf783f915c1fdd0bf68614c4764cae9dd46ba32cbae4dd659592c3/zstandard-0.24.0-cp311-cp311-manylinux2010_i686.manylinux2014_i686.manylinux_2_12_i686.manylinux_2_17_i686.whl", hash = "sha256:3f96a9130171e01dbb6c3d4d9925d604e2131a97f540e223b88ba45daf56d6fb", size = 5347682 },- { url = "https://files.pythonhosted.org/packages/a6/4c/63523169fe84773a7462cd090b0989cb7c7a7f2a8b0a5fbf00009ba7d74d/zstandard-0.24.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cd0d3d16e63873253bad22b413ec679cf6586e51b5772eb10733899832efec42", size = 5057650 },- { url = "https://files.pythonhosted.org/packages/c6/16/49013f7ef80293f5cebf4c4229535a9f4c9416bbfd238560edc579815dbe/zstandard-0.24.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:b7a8c30d9bf4bd5e4dcfe26900bef0fcd9749acde45cdf0b3c89e2052fda9a13", size = 5404893 },- { url = "https://files.pythonhosted.org/packages/4d/38/78e8bcb5fc32a63b055f2b99e0be49b506f2351d0180173674f516cf8a7a/zstandard-0.24.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:52cd7d9fa0a115c9446abb79b06a47171b7d916c35c10e0c3aa6f01d57561382", size = 5452389 },- { url = "https://files.pythonhosted.org/packages/55/8a/81671f05619edbacd49bd84ce6899a09fc8299be20c09ae92f6618ccb92d/zstandard-0.24.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a0f6fc2ea6e07e20df48752e7700e02e1892c61f9a6bfbacaf2c5b24d5ad504b", size = 5558888 },- { url = "https://files.pythonhosted.org/packages/49/cc/e83feb2d7d22d1f88434defbaeb6e5e91f42a4f607b5d4d2d58912b69d67/zstandard-0.24.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:e46eb6702691b24ddb3e31e88b4a499e31506991db3d3724a85bd1c5fc3cfe4e", size = 5048038 },- { url = "https://files.pythonhosted.org/packages/08/c3/7a5c57ff49ef8943877f85c23368c104c2aea510abb339a2dc31ad0a27c3/zstandard-0.24.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:d5e3b9310fd7f0d12edc75532cd9a56da6293840c84da90070d692e0bb15f186", size = 5573833 },- { url = "https://files.pythonhosted.org/packages/f9/00/64519983cd92535ba4bdd4ac26ac52db00040a52d6c4efb8d1764abcc343/zstandard-0.24.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:76cdfe7f920738ea871f035568f82bad3328cbc8d98f1f6988264096b5264efd", size = 4961072 },- { url = "https://files.pythonhosted.org/packages/72/ab/3a08a43067387d22994fc87c3113636aa34ccd2914a4d2d188ce365c5d85/zstandard-0.24.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:3f2fe35ec84908dddf0fbf66b35d7c2878dbe349552dd52e005c755d3493d61c", size = 5268462 },- { url = "https://files.pythonhosted.org/packages/49/cf/2abb3a1ad85aebe18c53e7eca73223f1546ddfa3bf4d2fb83fc5a064c5ca/zstandard-0.24.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:aa705beb74ab116563f4ce784fa94771f230c05d09ab5de9c397793e725bb1db", size = 5443319 },- { url = "https://files.pythonhosted.org/packages/40/42/0dd59fc2f68f1664cda11c3b26abdf987f4e57cb6b6b0f329520cd074552/zstandard-0.24.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:aadf32c389bb7f02b8ec5c243c38302b92c006da565e120dfcb7bf0378f4f848", size = 5822355 },- { url = "https://files.pythonhosted.org/packages/99/c0/ea4e640fd4f7d58d6f87a1e7aca11fb886ac24db277fbbb879336c912f63/zstandard-0.24.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:e40cd0fc734aa1d4bd0e7ad102fd2a1aefa50ce9ef570005ffc2273c5442ddc3", size = 5365257 },- { url = "https://files.pythonhosted.org/packages/27/a9/92da42a5c4e7e4003271f2e1f0efd1f37cfd565d763ad3604e9597980a1c/zstandard-0.24.0-cp311-cp311-win32.whl", hash = "sha256:cda61c46343809ecda43dc620d1333dd7433a25d0a252f2dcc7667f6331c7b61", size = 435559 },- { url = "https://files.pythonhosted.org/packages/e2/8e/2c8e5c681ae4937c007938f954a060fa7c74f36273b289cabdb5ef0e9a7e/zstandard-0.24.0-cp311-cp311-win_amd64.whl", hash = "sha256:3b95fc06489aa9388400d1aab01a83652bc040c9c087bd732eb214909d7fb0dd", size = 505070 },- { url = "https://files.pythonhosted.org/packages/52/10/a2f27a66bec75e236b575c9f7b0d7d37004a03aa2dcde8e2decbe9ed7b4d/zstandard-0.24.0-cp311-cp311-win_arm64.whl", hash = "sha256:ad9fd176ff6800a0cf52bcf59c71e5de4fa25bf3ba62b58800e0f84885344d34", size = 461507 },- { url = "https://files.pythonhosted.org/packages/26/e9/0bd281d9154bba7fc421a291e263911e1d69d6951aa80955b992a48289f6/zstandard-0.24.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:a2bda8f2790add22773ee7a4e43c90ea05598bffc94c21c40ae0a9000b0133c3", size = 795710 },- { url = "https://files.pythonhosted.org/packages/36/26/b250a2eef515caf492e2d86732e75240cdac9d92b04383722b9753590c36/zstandard-0.24.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:cc76de75300f65b8eb574d855c12518dc25a075dadb41dd18f6322bda3fe15d5", size = 640336 },- { url = "https://files.pythonhosted.org/packages/79/bf/3ba6b522306d9bf097aac8547556b98a4f753dc807a170becaf30dcd6f01/zstandard-0.24.0-cp312-cp312-manylinux2010_i686.manylinux2014_i686.manylinux_2_12_i686.manylinux_2_17_i686.whl", hash = "sha256:d2b3b4bda1a025b10fe0269369475f420177f2cb06e0f9d32c95b4873c9f80b8", size = 5342533 },- { url = "https://files.pythonhosted.org/packages/ea/ec/22bc75bf054e25accdf8e928bc68ab36b4466809729c554ff3a1c1c8bce6/zstandard-0.24.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:9b84c6c210684286e504022d11ec294d2b7922d66c823e87575d8b23eba7c81f", size = 5062837 },- { url = "https://files.pythonhosted.org/packages/48/cc/33edfc9d286e517fb5b51d9c3210e5bcfce578d02a675f994308ca587ae1/zstandard-0.24.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:c59740682a686bf835a1a4d8d0ed1eefe31ac07f1c5a7ed5f2e72cf577692b00", size = 5393855 },- { url = "https://files.pythonhosted.org/packages/73/36/59254e9b29da6215fb3a717812bf87192d89f190f23817d88cb8868c47ac/zstandard-0.24.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:6324fde5cf5120fbf6541d5ff3c86011ec056e8d0f915d8e7822926a5377193a", size = 5451058 },- { url = "https://files.pythonhosted.org/packages/9a/c7/31674cb2168b741bbbe71ce37dd397c9c671e73349d88ad3bca9e9fae25b/zstandard-0.24.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:51a86bd963de3f36688553926a84e550d45d7f9745bd1947d79472eca27fcc75", size = 5546619 },- { url = "https://files.pythonhosted.org/packages/e6/01/1a9f22239f08c00c156f2266db857545ece66a6fc0303d45c298564bc20b/zstandard-0.24.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:d82ac87017b734f2fb70ff93818c66f0ad2c3810f61040f077ed38d924e19980", size = 5046676 },- { url = "https://files.pythonhosted.org/packages/a7/91/6c0cf8fa143a4988a0361380ac2ef0d7cb98a374704b389fbc38b5891712/zstandard-0.24.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:92ea7855d5bcfb386c34557516c73753435fb2d4a014e2c9343b5f5ba148b5d8", size = 5576381 },- { url = "https://files.pythonhosted.org/packages/e2/77/1526080e22e78871e786ccf3c84bf5cec9ed25110a9585507d3c551da3d6/zstandard-0.24.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3adb4b5414febf074800d264ddf69ecade8c658837a83a19e8ab820e924c9933", size = 4953403 },- { url = "https://files.pythonhosted.org/packages/6e/d0/a3a833930bff01eab697eb8abeafb0ab068438771fa066558d96d7dafbf9/zstandard-0.24.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:6374feaf347e6b83ec13cc5dcfa70076f06d8f7ecd46cc71d58fac798ff08b76", size = 5267396 },- { url = "https://files.pythonhosted.org/packages/f3/5e/90a0db9a61cd4769c06374297ecfcbbf66654f74cec89392519deba64d76/zstandard-0.24.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:13fc548e214df08d896ee5f29e1f91ee35db14f733fef8eabea8dca6e451d1e2", size = 5433269 },- { url = "https://files.pythonhosted.org/packages/ce/58/fc6a71060dd67c26a9c5566e0d7c99248cbe5abfda6b3b65b8f1a28d59f7/zstandard-0.24.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:0a416814608610abf5488889c74e43ffa0343ca6cf43957c6b6ec526212422da", size = 5814203 },- { url = "https://files.pythonhosted.org/packages/5c/6a/89573d4393e3ecbfa425d9a4e391027f58d7810dec5cdb13a26e4cdeef5c/zstandard-0.24.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0d66da2649bb0af4471699aeb7a83d6f59ae30236fb9f6b5d20fb618ef6c6777", size = 5359622 },- { url = "https://files.pythonhosted.org/packages/60/ff/2cbab815d6f02a53a9d8d8703bc727d8408a2e508143ca9af6c3cca2054b/zstandard-0.24.0-cp312-cp312-win32.whl", hash = "sha256:ff19efaa33e7f136fe95f9bbcc90ab7fb60648453b03f95d1de3ab6997de0f32", size = 435968 },- { url = "https://files.pythonhosted.org/packages/ce/a3/8f96b8ddb7ad12344218fbd0fd2805702dafd126ae9f8a1fb91eef7b33da/zstandard-0.24.0-cp312-cp312-win_amd64.whl", hash = "sha256:bc05f8a875eb651d1cc62e12a4a0e6afa5cd0cc231381adb830d2e9c196ea895", size = 505195 },- { url = "https://files.pythonhosted.org/packages/a3/4a/bfca20679da63bfc236634ef2e4b1b4254203098b0170e3511fee781351f/zstandard-0.24.0-cp312-cp312-win_arm64.whl", hash = "sha256:b04c94718f7a8ed7cdd01b162b6caa1954b3c9d486f00ecbbd300f149d2b2606", size = 461605 },- { url = "https://files.pythonhosted.org/packages/ec/ef/db949de3bf81ed122b8ee4db6a8d147a136fe070e1015f5a60d8a3966748/zstandard-0.24.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e4ebb000c0fe24a6d0f3534b6256844d9dbf042fdf003efe5cf40690cf4e0f3e", size = 795700 },- { url = "https://files.pythonhosted.org/packages/99/56/fc04395d6f5eabd2fe6d86c0800d198969f3038385cb918bfbe94f2b0c62/zstandard-0.24.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:498f88f5109666c19531f0243a90d2fdd2252839cd6c8cc6e9213a3446670fa8", size = 640343 },- { url = "https://files.pythonhosted.org/packages/9b/0f/0b0e0d55f2f051d5117a0d62f4f9a8741b3647440c0ee1806b7bd47ed5ae/zstandard-0.24.0-cp313-cp313-manylinux2010_i686.manylinux2014_i686.manylinux_2_12_i686.manylinux_2_17_i686.whl", hash = "sha256:0a9e95ceb180ccd12a8b3437bac7e8a8a089c9094e39522900a8917745542184", size = 5342571 },- { url = "https://files.pythonhosted.org/packages/5d/43/d74e49f04fbd62d4b5d89aeb7a29d693fc637c60238f820cd5afe6ca8180/zstandard-0.24.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:bcf69e0bcddbf2adcfafc1a7e864edcc204dd8171756d3a8f3340f6f6cc87b7b", size = 5062723 },- { url = "https://files.pythonhosted.org/packages/8e/97/df14384d4d6a004388e6ed07ded02933b5c7e0833a9150c57d0abc9545b7/zstandard-0.24.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:10e284748a7e7fbe2815ca62a9d6e84497d34cfdd0143fa9e8e208efa808d7c4", size = 5393282 },- { url = "https://files.pythonhosted.org/packages/7e/09/8f5c520e59a4d41591b30b7568595eda6fd71c08701bb316d15b7ed0613a/zstandard-0.24.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:1bda8a85e5b9d5e73af2e61b23609a8cc1598c1b3b2473969912979205a1ff25", size = 5450895 },- { url = "https://files.pythonhosted.org/packages/d9/3d/02aba892327a67ead8cba160ee835cfa1fc292a9dcb763639e30c07da58b/zstandard-0.24.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1b14bc92af065d0534856bf1b30fc48753163ea673da98857ea4932be62079b1", size = 5546353 },- { url = "https://files.pythonhosted.org/packages/6a/6e/96c52afcde44da6a5313a1f6c356349792079808f12d8b69a7d1d98ef353/zstandard-0.24.0-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:b4f20417a4f511c656762b001ec827500cbee54d1810253c6ca2df2c0a307a5f", size = 5046404 },- { url = "https://files.pythonhosted.org/packages/da/b6/eefee6b92d341a7db7cd1b3885d42d30476a093720fb5c181e35b236d695/zstandard-0.24.0-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:337572a7340e1d92fd7fb5248c8300d0e91071002d92e0b8cabe8d9ae7b58159", size = 5576095 },- { url = "https://files.pythonhosted.org/packages/a3/29/743de3131f6239ba6611e17199581e6b5e0f03f268924d42468e29468ca0/zstandard-0.24.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:df4be1cf6e8f0f2bbe2a3eabfff163ef592c84a40e1a20a8d7db7f27cfe08fc2", size = 4953448 },- { url = "https://files.pythonhosted.org/packages/c9/11/bd36ef49fba82e307d69d93b5abbdcdc47d6a0bcbc7ffbbfe0ef74c2fec5/zstandard-0.24.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:6885ae4b33aee8835dbdb4249d3dfec09af55e705d74d9b660bfb9da51baaa8b", size = 5267388 },- { url = "https://files.pythonhosted.org/packages/c0/23/a4cfe1b871d3f1ce1f88f5c68d7e922e94be0043f3ae5ed58c11578d1e21/zstandard-0.24.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:663848a8bac4fdbba27feea2926049fdf7b55ec545d5b9aea096ef21e7f0b079", size = 5433383 },- { url = "https://files.pythonhosted.org/packages/77/26/f3fb85f00e732cca617d4b9cd1ffa6484f613ea07fad872a8bdc3a0ce753/zstandard-0.24.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:05d27c953f2e0a3ecc8edbe91d6827736acc4c04d0479672e0400ccdb23d818c", size = 5813988 },- { url = "https://files.pythonhosted.org/packages/3d/8c/d7e3b424b73f3ce66e754595cbcb6d94ff49790c9ac37d50e40e8145cd44/zstandard-0.24.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:77b8b7b98893eaf47da03d262816f01f251c2aa059c063ed8a45c50eada123a5", size = 5359756 },- { url = "https://files.pythonhosted.org/packages/90/6c/f1f0e11f1b295138f9da7e7ae22dcd9a1bb96a9544fa3b31507e431288f5/zstandard-0.24.0-cp313-cp313-win32.whl", hash = "sha256:cf7fbb4e54136e9a03c7ed7691843c4df6d2ecc854a2541f840665f4f2bb2edd", size = 435957 },- { url = "https://files.pythonhosted.org/packages/9f/03/ab8b82ae5eb49eca4d3662705399c44442666cc1ce45f44f2d263bb1ae31/zstandard-0.24.0-cp313-cp313-win_amd64.whl", hash = "sha256:d64899cc0f33a8f446f1e60bffc21fa88b99f0e8208750d9144ea717610a80ce", size = 505171 },- { url = "https://files.pythonhosted.org/packages/db/12/89a2ecdea4bc73a934a30b66a7cfac5af352beac94d46cf289e103b65c34/zstandard-0.24.0-cp313-cp313-win_arm64.whl", hash = "sha256:57be3abb4313e0dd625596376bbb607f40059d801d51c1a1da94d7477e63b255", size = 461596 },- { url = "https://files.pythonhosted.org/packages/c9/56/f3d2c4d64aacee4aab89e788783636884786b6f8334c819f09bff1aa207b/zstandard-0.24.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:b7fa260dd2731afd0dfa47881c30239f422d00faee4b8b341d3e597cface1483", size = 795747 },- { url = "https://files.pythonhosted.org/packages/32/2d/9d3e5f6627e4cb5e511803788be1feee2f0c3b94594591e92b81db324253/zstandard-0.24.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:e05d66239d14a04b4717998b736a25494372b1b2409339b04bf42aa4663bf251", size = 640475 },- { url = "https://files.pythonhosted.org/packages/be/5d/48e66abf8c146d95330e5385633a8cfdd556fa8bd14856fe721590cbab2b/zstandard-0.24.0-cp314-cp314-manylinux2010_i686.manylinux2014_i686.manylinux_2_12_i686.manylinux_2_17_i686.whl", hash = "sha256:622e1e04bd8a085994e02313ba06fbcf4f9ed9a488c6a77a8dbc0692abab6a38", size = 5343866 },- { url = "https://files.pythonhosted.org/packages/95/6c/65fe7ba71220a551e082e4a52790487f1d6bb8dfc2156883e088f975ad6d/zstandard-0.24.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:55872e818598319f065e8192ebefecd6ac05f62a43f055ed71884b0a26218f41", size = 5062719 },- { url = "https://files.pythonhosted.org/packages/cb/68/15ed0a813ff91be80cc2a610ac42e0fc8d29daa737de247bbf4bab9429a1/zstandard-0.24.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:bb2446a55b3a0fd8aa02aa7194bd64740015464a2daaf160d2025204e1d7c282", size = 5393090 },- { url = "https://files.pythonhosted.org/packages/d4/89/e560427b74fa2da6a12b8f3af8ee29104fe2bb069a25e7d314c35eec7732/zstandard-0.24.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:2825a3951f945fb2613ded0f517d402b1e5a68e87e0ee65f5bd224a8333a9a46", size = 5450383 },- { url = "https://files.pythonhosted.org/packages/a3/95/0498328cbb1693885509f2fc145402b108b750a87a3af65b7250b10bd896/zstandard-0.24.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:09887301001e7a81a3618156bc1759e48588de24bddfdd5b7a4364da9a8fbc20", size = 5546142 },- { url = "https://files.pythonhosted.org/packages/8a/8a/64aa15a726594df3bf5d8decfec14fe20cd788c60890f44fcfc74d98c2cc/zstandard-0.24.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:98ca91dc9602cf351497d5600aa66e6d011a38c085a8237b370433fcb53e3409", size = 4953456 },- { url = "https://files.pythonhosted.org/packages/b0/b6/e94879c5cd6017af57bcba08519ed1228b1ebb15681efd949f4a00199449/zstandard-0.24.0-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:e69f8e534b4e254f523e2f9d4732cf9c169c327ca1ce0922682aac9a5ee01155", size = 5268287 },- { url = "https://files.pythonhosted.org/packages/fd/e5/1a3b3a93f953dbe9e77e2a19be146e9cd2af31b67b1419d6cc8e8898d409/zstandard-0.24.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:444633b487a711e34f4bccc46a0c5dfbe1aee82c1a511e58cdc16f6bd66f187c", size = 5433197 },- { url = "https://files.pythonhosted.org/packages/39/83/b6eb1e1181de994b29804e1e0d2dc677bece4177f588c71653093cb4f6d5/zstandard-0.24.0-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:f7d3fe9e1483171e9183ffdb1fab07c5fef80a9c3840374a38ec2ab869ebae20", size = 5813161 },- { url = "https://files.pythonhosted.org/packages/f6/d3/2fb4166561591e9d75e8e35c79182aa9456644e2f4536f29e51216d1c513/zstandard-0.24.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:27b6fa72b57824a3f7901fc9cc4ce1c1c834b28f3a43d1d4254c64c8f11149d4", size = 5359831 },- { url = "https://files.pythonhosted.org/packages/11/94/6a9227315b774f64a67445f62152c69b4e5e49a52a3c7c4dad8520a55e20/zstandard-0.24.0-cp314-cp314-win32.whl", hash = "sha256:fdc7a52a4cdaf7293e10813fd6a3abc0c7753660db12a3b864ab1fb5a0c60c16", size = 444448 },- { url = "https://files.pythonhosted.org/packages/fc/de/67acaba311013e0798cb96d1a2685cb6edcdfc1cae378b297ea7b02c319f/zstandard-0.24.0-cp314-cp314-win_amd64.whl", hash = "sha256:656ed895b28c7e42dd5b40dfcea3217cfc166b6b7eef88c3da2f5fc62484035b", size = 516075 },- { url = "https://files.pythonhosted.org/packages/10/ae/45fd8921263cea0228b20aa31bce47cc66016b2aba1afae1c6adcc3dbb1f/zstandard-0.24.0-cp314-cp314-win_arm64.whl", hash = "sha256:0101f835da7de08375f380192ff75135527e46e3f79bef224e3c49cb640fef6a", size = 476847 },-]