Skip to content

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

TypeScript

lots of stuff, prob. ctrl-c/v over skellycam updates etc

jonmatthis8b66423925e2
diff --git a/freemocap-ui/electron/main/helpers/app-paths.ts b/freemocap-ui/electron/main/helpers/app-paths.ts
index 080be397..3fecf0d8 100644
--- a/freemocap-ui/electron/main/helpers/app-paths.ts
+++ b/freemocap-ui/electron/main/helpers/app-paths.ts
@@ -7,6 +7,8 @@ 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.ts
index 6f07f4c5..1d7963f1 100644
--- a/freemocap-ui/electron/main/helpers/ipc-manager.ts
+++ b/freemocap-ui/electron/main/helpers/ipc-manager.ts
@@ -18,6 +18,7 @@ export class IpcManager {
child.loadURL(`${process.env.VITE_DEV_SERVER_URL}#${route}`);
});
}
+
private static handleFileSystemControls() {
ipcMain.handle('select-directory', async () => {
const result = await dialog.showOpenDialog({
@@ -43,11 +44,24 @@ export class IpcManager {
});
+ 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 };
+ return {error: 'Folder does not exist', path: folderPath};
}
// Get all files and directories in the folder
@@ -96,7 +110,7 @@ export class IpcManager {
ipcMain.handle('restart-python-server', () => {
console.log('Restarting Python Server');
PythonServer.shutdown();
- PythonServer.start();
+ PythonServer.start(null);
});
}
}
diff --git a/freemocap-ui/electron/main/helpers/python-server.ts b/freemocap-ui/electron/main/helpers/python-server.ts
index b4abf2f1..3603da29 100644
--- a/freemocap-ui/electron/main/helpers/python-server.ts
+++ b/freemocap-ui/electron/main/helpers/python-server.ts
@@ -4,30 +4,42 @@ 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() {
+ static async start(exePath: string | null) {
console.log('Starting python server subprocess');
- this.validateExecutable();
+ let executablePath = APP_PATHS.PYTHON_SERVER_EXECUTABLE_PATH;
+ try {
+ await this.shutdown();
- pythonProcess = exec(`"${APP_PATHS.PYTHON_SERVER_EXECUTABLE_PATH}"`, {
+ 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,
- PYTHONIOENCODING: 'utf-8',
- PYTHONUTF8: '1'
},
- maxBuffer: 1024 * 1024
+ maxBuffer: 1024 * 1024 * 100 // 100MB buffer
});
- pythonProcess.stdout?.on('data', (data) =>
- console.log(`[Python] ${data}`));
-
- pythonProcess.stderr?.on('data', (data) =>
- console.error(`[Python Error] ${data}`));
-
pythonProcess.on('exit', (code) => {
console.log(`Python exited (code: ${code})`);
});
@@ -57,7 +69,7 @@ export class PythonServer {
pythonProcess = null;
}
- private static validateExecutable() {
+ 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}`);
@@ -70,12 +82,8 @@ export class PythonServer {
}
};
- try {
- checkPath(APP_PATHS.PYTHON_SERVER_EXECUTABLE_PATH);
- } catch {
- checkPath(APP_PATHS.PYTHON_SERVER_EXECUTABLE_DEV);
- APP_PATHS.PYTHON_SERVER_EXECUTABLE_PATH = APP_PATHS.PYTHON_SERVER_EXECUTABLE_DEV;
- }
+ checkPath(exePath);
+
console.log(`Using python server executable at ${APP_PATHS.PYTHON_SERVER_EXECUTABLE_PATH}`);
}
diff --git a/freemocap-ui/electron/main/index.ts b/freemocap-ui/electron/main/index.ts
index 496f6ab6..110f63c5 100644
--- a/freemocap-ui/electron/main/index.ts
+++ b/freemocap-ui/electron/main/index.ts
@@ -5,8 +5,7 @@ import {WindowManager} from "./helpers/window-manager";
import {PythonServer} from "./helpers/python-server";
import {LifecycleLogger} from "./helpers/logger";
import os from "node:os";
-import {APP_ENVIRONMENT} from "./helpers/app-environment";
-import {installExtension, REDUX_DEVTOOLS} from 'electron-devtools-installer';
+
// Environment variables that `python` server will use for its lifecycle management
@@ -25,25 +24,12 @@ function startApplication() {
app.whenReady()
.then(() => {
console.log('App is ready')
- const options = {
- loadExtensionOptions: { allowFileAccess: true },
- };
- installExtension(REDUX_DEVTOOLS, options)
- .then((ext) => console.log(`Added Extension: ${ext.name}`))
- .catch((err) => console.log('An error occurred: ', err));
- console.log('SHOULD_LAUNCH_PYTHON:', APP_ENVIRONMENT.SHOULD_LAUNCH_PYTHON);
- if (APP_ENVIRONMENT.SHOULD_LAUNCH_PYTHON) {
- console.log('Launching Python Server');
- PythonServer.start();
- }
+
+
const mainWindow = WindowManager.createMainWindow();
- // TODO: Add Redux and React DevTools Extensions to Electron App BrowserWindow - the code below didn't work
- // installExtension([REDUX_DEVTOOLS, REACT_DEVELOPER_TOOLS])
- // .then(([redux, react]) => console.log(`Added Extensions: ${redux.name}, ${react.name}`))
- // .catch((err) => console.log('An error occurred: ', err));
update(mainWindow);
});
}
diff --git a/freemocap-ui/electron/preload/index.ts b/freemocap-ui/electron/preload/index.ts
index 5d8b61f2..a5199c90 100644
--- a/freemocap-ui/electron/preload/index.ts
+++ b/freemocap-ui/electron/preload/index.ts
@@ -7,6 +7,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
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 ---------
diff --git a/freemocap-ui/src/App.tsx b/freemocap-ui/src/App.tsx
index f59b959c..31e70ed4 100644
--- a/freemocap-ui/src/App.tsx
+++ b/freemocap-ui/src/App.tsx
@@ -4,14 +4,16 @@ 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";
function App() {
- const wsUrl = urlService.getWebSocketUrl();
return (
<Provider store={AppStateStore}>
- <WebSocketContextProvider url={wsUrl}>
+ <PythonServerContextProvider>
+ <WebSocketContextProvider>
<PaperbaseContent/>
</WebSocketContextProvider>
+ </PythonServerContextProvider>
</Provider>
);
}
diff --git a/freemocap-ui/src/components/server-settings-panel/ServerConnectionStatus.tsx b/freemocap-ui/src/components/server-settings-panel/ServerConnectionStatus.tsx
new file mode 100644
index 00000000..b5b3b4e0
--- /dev/null
+++ b/freemocap-ui/src/components/server-settings-panel/ServerConnectionStatus.tsx
@@ -0,0 +1,70 @@
+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.tsx
new file mode 100644
index 00000000..17941813
--- /dev/null
+++ b/freemocap-ui/src/components/server-settings-panel/ServerSettingsPanel.tsx
@@ -0,0 +1,172 @@
+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
+ defaultExpandedItems={['server-status']}
+ 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"
+ />
+
+ <Box sx={{display: 'flex', alignItems: 'center', gap: 1}}>
+ <TextField
+ label="Host"
+ value={host}
+ onChange={(e) => setHost(e.target.value)}
+ size="small"
+ sx={{flex: 1}}
+ />
+ <TextField
+ label="HTTP Port"
+ type="number"
+ value={httpPort}
+ onChange={(e) => setHttpPort(Number(e.target.value))}
+ size="small"
+ sx={{width: 100}}
+ />
+ </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)}
+ />
+ }
+ 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"
+ />
+ </Box>
+ )}
+
+ <FormControlLabel
+ control={
+ <Checkbox
+ checked={preShrink}
+ onChange={(e) => setPreShrink(e.target.checked)}
+ />
+ }
+ 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"
+ />
+ </Box>
+ )}
+ </Box>
+ </TreeItem>
+ </Box>
+ </TreeItem>
+ </SimpleTreeView>
+ </Box>
+ );
+};
diff --git a/freemocap-ui/src/components/WebsocketConnectionStatus.tsx b/freemocap-ui/src/components/server-settings-panel/WebsocketConnectionStatus.tsx
similarity index 82%
rename from freemocap-ui/src/components/WebsocketConnectionStatus.tsx
rename to freemocap-ui/src/components/server-settings-panel/WebsocketConnectionStatus.tsx
index 335b1ea0..cf93133a 100644
--- a/freemocap-ui/src/components/WebsocketConnectionStatus.tsx
+++ b/freemocap-ui/src/components/server-settings-panel/WebsocketConnectionStatus.tsx
@@ -10,14 +10,16 @@ const WebsocketConnectionStatus = () => {
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>
+ // <Tooltip title={`WebSocket URL: ${wsUrl}`} placement="bottom-start" arrow>
<Box
sx={{
display: 'flex',
@@ -27,6 +29,12 @@ const WebsocketConnectionStatus = () => {
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}
>
@@ -41,14 +49,14 @@ const WebsocketConnectionStatus = () => {
>
<Box sx={{
border: '1px solid rgba(255, 255, 255, 0.3)',
- backgroundColor: isConnected ? 'rgba(0, 255, 0, 0.1)' : 'rgba(255, 0, 0, 0.1)',
width: '24px',
height: '24px',
marginRight: '8px',
cursor: 'pointer',
borderRadius: '4px',
transition: 'background-color 0.3s, border-color 0.3s',
- borderColor: isConnected ? 'rgba(0, 255, 0, 0.5)' : 'rgba(255, 0, 0, 0.5)',
+ 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',
@@ -68,7 +76,7 @@ const WebsocketConnectionStatus = () => {
Websocket: {isConnected ? 'connected' : 'disconnected'}
</Typography>
</Box>
- </Tooltip>
+ // </Tooltip>
)
;
};
diff --git a/freemocap-ui/src/components/ui-components/LeftSidePanelContent.tsx b/freemocap-ui/src/components/ui-components/LeftSidePanelContent.tsx
index 85c518d8..956de991 100644
--- a/freemocap-ui/src/components/ui-components/LeftSidePanelContent.tsx
+++ b/freemocap-ui/src/components/ui-components/LeftSidePanelContent.tsx
@@ -2,7 +2,6 @@
import * as React from 'react';
import Box from "@mui/material/Box";
import {IconButton, List, ListItem, useTheme} from "@mui/material";
-import WebsocketConnectionStatus from "@/components/WebsocketConnectionStatus";
import {AvailableCamerasPanel} from "@/components/available-cameras-panel/AvailableCamerasPanel";
import {RecordingInfoPanel} from "@/components/recording-info-panel/RecordingInfoPanel";
import ThemeToggle from "@/components/ui-components/ThemeToggle";
@@ -13,6 +12,7 @@ import VideoLibraryIcon from '@mui/icons-material/VideoLibrary';
import DirectionsRunIcon from '@mui/icons-material/DirectionsRun';
import {VideoFolderPanel} from "@/components/video-folder-panel/VideoFolderPanel";
import {ProcessingPipelinePanel} from "@/components/processing-pipeline-panel/ProcessingPipelinePanel";
+import {ServerSettingsPanel} from "@/components/server-settings-panel/ServerSettingsPanel";
// Extract reusable scrollbar styles
const scrollbarStyles = {
'&::-webkit-scrollbar': {
@@ -120,19 +120,19 @@ export const LeftSidePanelContent = () => {
</ListItem>
</List>
- <WebsocketConnectionStatus/>
+ <ServerSettingsPanel/>
- <Box sx={{
- flex: 1,
- overflowY: 'auto',
- overflowX: 'hidden',
- ...scrollbarStyles
- }}>
- <AvailableCamerasPanel/>
- <RecordingInfoPanel/>
- <ProcessingPipelinePanel/>
+ <Box sx={{
+ flex: 1,
+ overflowY: 'auto',
+ overflowX: 'hidden',
+ ...scrollbarStyles
+ }}>
+ <AvailableCamerasPanel/>
+ <RecordingInfoPanel/>
+ <ProcessingPipelinePanel/>
- </Box>
+ </Box>
{location.pathname === '/videos' && (
<Box sx={{
diff --git a/freemocap-ui/src/context/python-server-context/PythonServerContext.tsx b/freemocap-ui/src/context/python-server-context/PythonServerContext.tsx
new file mode 100644
index 00000000..a9c1d5e1
--- /dev/null
+++ b/freemocap-ui/src/context/python-server-context/PythonServerContext.tsx
@@ -0,0 +1,32 @@
+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.ts
new file mode 100644
index 00000000..1d622884
--- /dev/null
+++ b/freemocap-ui/src/context/python-server-context/usePythonServer.ts
@@ -0,0 +1,31 @@
+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.tsx
index d59b8ce4..67815ee7 100644
--- a/freemocap-ui/src/context/websocket-context/WebSocketContext.tsx
+++ b/freemocap-ui/src/context/websocket-context/WebSocketContext.tsx
@@ -14,14 +14,13 @@ interface WebSocketContextProps {
interface WebSocketProviderProps {
- url: string;
children: ReactNode;
}
const WebSocketContext = createContext<WebSocketContextProps | undefined>(undefined);
-export const WebSocketContextProvider: React.FC<WebSocketProviderProps> = ({url, children}) => {
- const { isConnected, connect, disconnect, latestImageData,acknowledgeFrameRendered } = useWebSocket(url);
+export const WebSocketContextProvider: React.FC<WebSocketProviderProps> = ({ children}) => {
+ const { isConnected, connect, disconnect, latestImageData,acknowledgeFrameRendered } = useWebSocket();
return (
<WebSocketContext.Provider value={{isConnected, connect, disconnect,latestImageData,acknowledgeFrameRendered}}>
diff --git a/freemocap-ui/src/context/websocket-context/useWebSocket.ts b/freemocap-ui/src/context/websocket-context/useWebSocket.ts
index 9544d899..cbf59fce 100644
--- a/freemocap-ui/src/context/websocket-context/useWebSocket.ts
+++ b/freemocap-ui/src/context/websocket-context/useWebSocket.ts
@@ -7,9 +7,10 @@ import {
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 "@/services/urlService";
-export const useWebSocket = (wsUrl: string) => {
+export const useWebSocket = () => {
const [isConnected, setIsConnected] = useState(false);
const [shouldReconnect, setShouldReconnect] = useState(true);
const [websocket, setWebSocket] = useState<WebSocket | null>(null);
@@ -114,7 +115,7 @@ export const useWebSocket = (wsUrl: string) => {
return;
}
- const ws = new WebSocket(wsUrl);
+ const ws = new WebSocket(urlService.getWebSocketUrl());
ws.binaryType = "arraybuffer";
ws.onopen = () => {
@@ -122,7 +123,7 @@ export const useWebSocket = (wsUrl: string) => {
setConnectAttempt(0);
setShouldReconnect(true);
ws.send("Hello from the Skellycam FrontendπŸ’€πŸ“ΈπŸ‘‹");
- console.log(`Websocket is connected to url: ${wsUrl}`);
+ console.log(`Websocket is connected to url: ${urlService.getWebSocketUrl()}`);
};
ws.onclose = () => {
@@ -144,7 +145,7 @@ export const useWebSocket = (wsUrl: string) => {
console.error("Websocket error:", error);
};
setWebSocket(ws);
- }, [wsUrl, websocket, connectAttempt]);
+ }, [websocket, connectAttempt]);
const disconnect = useCallback((shouldReconnect:boolean=true) => {
if (websocket) {
@@ -160,7 +161,7 @@ export const useWebSocket = (wsUrl: string) => {
}
const timeout = setTimeout(() => {
console.log(
- `Connecting to websocket at url: ${wsUrl} (attempt #${connectAttempt + 1})`
+ `Connecting to websocket at url: ${urlService.getWebSocketUrl()} (attempt #${connectAttempt + 1})`
);
connect();
}, Math.min(1000 * Math.pow(2, connectAttempt), 10000)); // exponential backoff
@@ -168,7 +169,7 @@ export const useWebSocket = (wsUrl: string) => {
return () => {
clearTimeout(timeout);
};
- }, [connect, connectAttempt, wsUrl]);
+ }, [connect, connectAttempt]);
return {
isConnected,
diff --git a/freemocap-ui/src/services/urlService.ts b/freemocap-ui/src/services/urlService.ts
index 710b4b60..f5152e55 100644
--- a/freemocap-ui/src/services/urlService.ts
+++ b/freemocap-ui/src/services/urlService.ts
@@ -11,7 +11,7 @@ class UrlService {
/**
* Builds the base URL for HTTP requests
*/
- private getBaseUrl(): string {
+ getBaseHttpUrl(): string {
const { protocol, host, port } = config.server;
return `${protocol}://${host}:${port}${config.server.basePath}`;
}
@@ -19,7 +19,7 @@ class UrlService {
/**
* Builds the base WebSocket URL
*/
- private getBaseWsUrl(): string {
+ getBaseWsUrl(): string {
const { wsProtocol, host, port } = config.server;
return `${wsProtocol}://${host}:${port}${config.server.basePath}`;
}
@@ -28,7 +28,7 @@ class UrlService {
* Generates a complete API URL from a path
*/
getApiUrl(path: string): string {
- return `${this.getBaseUrl()}${path}`;
+ return `${this.getBaseHttpUrl()}${path}`;
}
/**
diff --git a/freemocap/core/__init__.py b/freemocap/core/__init__.py
new file mode 100644
index 00000000..04fcf0dc
--- /dev/null
+++ b/freemocap/core/__init__.py
@@ -0,0 +1,17 @@
+"""A free and open source markerless motion capture system for everyone πŸ’€βœ¨"""
+
+__author__ = """Skelly FreeMoCap"""
+__email__ = "[email protected]"
+__version__ = "v1.4.7"
+__description__ = "A free and open source markerless motion capture system for everyone πŸ’€βœ¨"
+
+__package_name__ = "freemocap"
+__repo_url__ = f"https://github.com/freemocap/{__package_name__}/"
+__repo_issues_url__ = f"{__repo_url__}issues"
+
+from freemocap.system.logging_configuration.configure_logging import configure_logging
+from freemocap.system.logging_configuration.log_levels import LogLevels
+
+LOG_LEVEL = LogLevels.TRACE
+configure_logging(LOG_LEVEL)
+
diff --git a/freemocap/pipelines/__init__.py b/freemocap/core/pipelines/__init__.py
similarity index 100%
rename from freemocap/pipelines/__init__.py
rename to freemocap/core/pipelines/__init__.py
diff --git a/freemocap/pipelines/calibration_pipeline/__calibration_pipeline.py b/freemocap/core/pipelines/calibration_pipeline/__calibration_pipeline.py
similarity index 100%
rename from freemocap/pipelines/calibration_pipeline/__calibration_pipeline.py
rename to freemocap/core/pipelines/calibration_pipeline/__calibration_pipeline.py
diff --git a/freemocap/pipelines/calibration_pipeline/__init__.py b/freemocap/core/pipelines/calibration_pipeline/__init__.py
similarity index 100%
rename from freemocap/pipelines/calibration_pipeline/__init__.py
rename to freemocap/core/pipelines/calibration_pipeline/__init__.py
diff --git a/freemocap/pipelines/calibration_pipeline/calculate_sparse_jacobian.py b/freemocap/core/pipelines/calibration_pipeline/calculate_sparse_jacobian.py
similarity index 100%
rename from freemocap/pipelines/calibration_pipeline/calculate_sparse_jacobian.py
rename to freemocap/core/pipelines/calibration_pipeline/calculate_sparse_jacobian.py
diff --git a/freemocap/pipelines/calibration_pipeline/calibration_aggregation_node.py b/freemocap/core/pipelines/calibration_pipeline/calibration_aggregation_node.py
similarity index 100%
rename from freemocap/pipelines/calibration_pipeline/calibration_aggregation_node.py
rename to freemocap/core/pipelines/calibration_pipeline/calibration_aggregation_node.py
diff --git a/freemocap/pipelines/calibration_pipeline/calibration_camera_node.py b/freemocap/core/pipelines/calibration_pipeline/calibration_camera_node.py
similarity index 100%
rename from freemocap/pipelines/calibration_pipeline/calibration_camera_node.py
rename to freemocap/core/pipelines/calibration_pipeline/calibration_camera_node.py
diff --git a/freemocap/pipelines/calibration_pipeline/calibration_camera_node_output_data.py b/freemocap/core/pipelines/calibration_pipeline/calibration_camera_node_output_data.py
similarity index 100%
rename from freemocap/pipelines/calibration_pipeline/calibration_camera_node_output_data.py
rename to freemocap/core/pipelines/calibration_pipeline/calibration_camera_node_output_data.py
diff --git a/freemocap/pipelines/calibration_pipeline/calibration_numpy_types.py b/freemocap/core/pipelines/calibration_pipeline/calibration_numpy_types.py
similarity index 100%
rename from freemocap/pipelines/calibration_pipeline/calibration_numpy_types.py
rename to freemocap/core/pipelines/calibration_pipeline/calibration_numpy_types.py
diff --git a/freemocap/pipelines/calibration_pipeline/camera_math_models.py b/freemocap/core/pipelines/calibration_pipeline/camera_math_models.py
similarity index 100%
rename from freemocap/pipelines/calibration_pipeline/camera_math_models.py
rename to freemocap/core/pipelines/calibration_pipeline/camera_math_models.py
diff --git a/freemocap/pipelines/calibration_pipeline/least_squares_optimizer.py b/freemocap/core/pipelines/calibration_pipeline/least_squares_optimizer.py
similarity index 100%
rename from freemocap/pipelines/calibration_pipeline/least_squares_optimizer.py
rename to freemocap/core/pipelines/calibration_pipeline/least_squares_optimizer.py
diff --git a/freemocap/pipelines/calibration_pipeline/multi_camera_calibration/__init__.py b/freemocap/core/pipelines/calibration_pipeline/multi_camera_calibration/__init__.py
similarity index 100%
rename from freemocap/pipelines/calibration_pipeline/multi_camera_calibration/__init__.py
rename to freemocap/core/pipelines/calibration_pipeline/multi_camera_calibration/__init__.py
diff --git a/freemocap/pipelines/calibration_pipeline/multi_camera_calibration/anipose_calibration_optimizer.py b/freemocap/core/pipelines/calibration_pipeline/multi_camera_calibration/anipose_calibration_optimizer.py
similarity index 100%
rename from freemocap/pipelines/calibration_pipeline/multi_camera_calibration/anipose_calibration_optimizer.py
rename to freemocap/core/pipelines/calibration_pipeline/multi_camera_calibration/anipose_calibration_optimizer.py
diff --git a/freemocap/pipelines/calibration_pipeline/multi_camera_calibration/calibration_utilities.py b/freemocap/core/pipelines/calibration_pipeline/multi_camera_calibration/calibration_utilities.py
similarity index 100%
rename from freemocap/pipelines/calibration_pipeline/multi_camera_calibration/calibration_utilities.py
rename to freemocap/core/pipelines/calibration_pipeline/multi_camera_calibration/calibration_utilities.py
diff --git a/freemocap/pipelines/calibration_pipeline/multi_camera_calibration/triangulation_method.py b/freemocap/core/pipelines/calibration_pipeline/multi_camera_calibration/triangulation_method.py
similarity index 100%
rename from freemocap/pipelines/calibration_pipeline/multi_camera_calibration/triangulation_method.py
rename to freemocap/core/pipelines/calibration_pipeline/multi_camera_calibration/triangulation_method.py
diff --git a/freemocap/pipelines/calibration_pipeline/multi_camera_calibrator.py b/freemocap/core/pipelines/calibration_pipeline/multi_camera_calibrator.py
similarity index 89%
rename from freemocap/pipelines/calibration_pipeline/multi_camera_calibrator.py
rename to freemocap/core/pipelines/calibration_pipeline/multi_camera_calibrator.py
index c9641eda..8635d2a3 100644
--- a/freemocap/pipelines/calibration_pipeline/multi_camera_calibrator.py
+++ b/freemocap/core/pipelines/calibration_pipeline/multi_camera_calibrator.py
@@ -2,31 +2,31 @@ import logging
import numpy as np
from pydantic import BaseModel
-from skellycam import CameraId
+from skellycam.core.types.type_overloads import CameraIdString
-from freemocap.pipelines.calibration_pipeline.calibration_camera_node_output_data import CalibrationCameraNodeOutputData
-from freemocap.pipelines.calibration_pipeline.least_squares_optimizer import SparseBundleOptimizer
-from freemocap.pipelines.calibration_pipeline.shared_view_accumulator import SharedViewAccumulator
+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__)
-from freemocap.pipelines.calibration_pipeline.single_camera_calibrator import SingleCameraCalibrator, \
- CameraIntrinsicsEstimate
-from freemocap.pipelines.calibration_pipeline.camera_math_models import TransformationMatrix
-
class MultiCameraCalibrationEstimate(BaseModel):
- principal_camera_id: CameraId
- camera_transforms_by_camera_id: dict[CameraId, TransformationMatrix]
+ principal_camera_id: CameraIdString
+ camera_transforms_by_camera_id: dict[CameraIdString, TransformationMatrix]
class MultiCameraCalibrator(BaseModel):
- principal_camera_id: CameraId
- camera_id_to_index: dict[CameraId, int]
+ principal_camera_id: CameraIdString
+ camera_id_to_index: dict[CameraIdString, int]
shared_view_accumulator: SharedViewAccumulator
- single_camera_calibrators: dict[CameraId, SingleCameraCalibrator] | None = None
+ 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
@@ -39,20 +39,20 @@ class MultiCameraCalibrator(BaseModel):
self.single_camera_calibrators.values()) and self.multi_camera_calibration_estimate is not None
@property
- def camera_intrinsics(self) -> dict[CameraId, CameraIntrinsicsEstimate]:
+ 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[CameraId], principal_camera_id: CameraId|None = None):
+ 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[CameraId, CalibrationCameraNodeOutputData]):
+ 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)
@@ -62,9 +62,9 @@ class MultiCameraCalibrator(BaseModel):
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[
- CameraId, CalibrationCameraNodeOutputData]):
+ CameraIdString, CalibrationCameraNodeOutputData]):
- self.single_camera_calibrators: dict[CameraId, SingleCameraCalibrator] = {}
+ 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,
@@ -138,7 +138,7 @@ class MultiCameraCalibrator(BaseModel):
)
def _calculate_camera_to_principal_camera_transforms(self, camera_pair_secondary_camera_transform_estimates) -> \
- dict[CameraId, TransformationMatrix]:
+ 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(
diff --git a/freemocap/pipelines/calibration_pipeline/positional_6dof.py b/freemocap/core/pipelines/calibration_pipeline/positional_6dof.py
similarity index 100%
rename from freemocap/pipelines/calibration_pipeline/positional_6dof.py
rename to freemocap/core/pipelines/calibration_pipeline/positional_6dof.py
diff --git a/freemocap/pipelines/calibration_pipeline/shared_view_accumulator.py b/freemocap/core/pipelines/calibration_pipeline/shared_view_accumulator.py
similarity index 100%
rename from freemocap/pipelines/calibration_pipeline/shared_view_accumulator.py
rename to freemocap/core/pipelines/calibration_pipeline/shared_view_accumulator.py
diff --git a/freemocap/pipelines/calibration_pipeline/single_camera_calibration_estimate.py b/freemocap/core/pipelines/calibration_pipeline/single_camera_calibration_estimate.py
similarity index 100%
rename from freemocap/pipelines/calibration_pipeline/single_camera_calibration_estimate.py
rename to freemocap/core/pipelines/calibration_pipeline/single_camera_calibration_estimate.py
diff --git a/freemocap/pipelines/calibration_pipeline/single_camera_calibrator.py b/freemocap/core/pipelines/calibration_pipeline/single_camera_calibrator.py
similarity index 100%
rename from freemocap/pipelines/calibration_pipeline/single_camera_calibrator.py
rename to freemocap/core/pipelines/calibration_pipeline/single_camera_calibrator.py
diff --git a/freemocap/pipelines/calibration_pipeline/triangulate_points.py b/freemocap/core/pipelines/calibration_pipeline/triangulate_points.py
similarity index 100%
rename from freemocap/pipelines/calibration_pipeline/triangulate_points.py
rename to freemocap/core/pipelines/calibration_pipeline/triangulate_points.py
diff --git a/freemocap/pipelines/dummy_pipeline.py b/freemocap/core/pipelines/dummy_pipeline.py
similarity index 100%
rename from freemocap/pipelines/dummy_pipeline.py
rename to freemocap/core/pipelines/dummy_pipeline.py
diff --git a/freemocap/pipelines/freemocap_frontend_payload.py b/freemocap/core/pipelines/freemocap_frontend_payload.py
similarity index 100%
rename from freemocap/pipelines/freemocap_frontend_payload.py
rename to freemocap/core/pipelines/freemocap_frontend_payload.py
diff --git a/freemocap/pipelines/mocap_pipeline/__init__.py b/freemocap/core/pipelines/mocap_pipeline/__init__.py
similarity index 100%
rename from freemocap/pipelines/mocap_pipeline/__init__.py
rename to freemocap/core/pipelines/mocap_pipeline/__init__.py
diff --git a/freemocap/pipelines/mocap_pipeline/__mocap_pipeline.py b/freemocap/core/pipelines/mocap_pipeline/__mocap_pipeline.py
similarity index 100%
rename from freemocap/pipelines/mocap_pipeline/__mocap_pipeline.py
rename to freemocap/core/pipelines/mocap_pipeline/__mocap_pipeline.py
diff --git a/freemocap/pipelines/mocap_pipeline/mocap_aggregation_node.py b/freemocap/core/pipelines/mocap_pipeline/mocap_aggregation_node.py
similarity index 100%
rename from freemocap/pipelines/mocap_pipeline/mocap_aggregation_node.py
rename to freemocap/core/pipelines/mocap_pipeline/mocap_aggregation_node.py
diff --git a/freemocap/pipelines/mocap_pipeline/mocap_camera_node.py b/freemocap/core/pipelines/mocap_pipeline/mocap_camera_node.py
similarity index 100%
rename from freemocap/pipelines/mocap_pipeline/mocap_camera_node.py
rename to freemocap/core/pipelines/mocap_pipeline/mocap_camera_node.py
diff --git a/freemocap/pipelines/mocap_pipeline/point_trangulator.py b/freemocap/core/pipelines/mocap_pipeline/point_trangulator.py
similarity index 100%
rename from freemocap/pipelines/mocap_pipeline/point_trangulator.py
rename to freemocap/core/pipelines/mocap_pipeline/point_trangulator.py
diff --git a/freemocap/pipelines/pipeline_ipc.py b/freemocap/core/pipelines/pipeline_ipc.py
similarity index 100%
rename from freemocap/pipelines/pipeline_ipc.py
rename to freemocap/core/pipelines/pipeline_ipc.py
diff --git a/freemocap/pipelines/processing_pipeline.py b/freemocap/core/pipelines/processing_pipeline.py
similarity index 100%
rename from freemocap/pipelines/processing_pipeline.py
rename to freemocap/core/pipelines/processing_pipeline.py
diff --git a/freemocap/core/types/__init__.py b/freemocap/core/types/__init__.py
new file mode 100644
index 00000000..04fcf0dc
--- /dev/null
+++ b/freemocap/core/types/__init__.py
@@ -0,0 +1,17 @@
+"""A free and open source markerless motion capture system for everyone πŸ’€βœ¨"""
+
+__author__ = """Skelly FreeMoCap"""
+__email__ = "[email protected]"
+__version__ = "v1.4.7"
+__description__ = "A free and open source markerless motion capture system for everyone πŸ’€βœ¨"
+
+__package_name__ = "freemocap"
+__repo_url__ = f"https://github.com/freemocap/{__package_name__}/"
+__repo_issues_url__ = f"{__repo_url__}issues"
+
+from freemocap.system.logging_configuration.configure_logging import configure_logging
+from freemocap.system.logging_configuration.log_levels import LogLevels
+
+LOG_LEVEL = LogLevels.TRACE
+configure_logging(LOG_LEVEL)
+