Skip to content

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

TypeScript

web app

Endurance Idehen2b9e7f6137a9
diff --git a/Dockerfile b/Dockerfile
index 5d8e9666..71de937b 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -17,6 +17,7 @@ RUN rm -rf /etc/apt/apt.conf.d/docker-clean
COPY ./bin/builds/ .
+# Apt-get install packages here since we're using Debian as a root OS for this particular Dockerfile.
RUN --mount=type=cache,target=/var/cache/apt ./install_packages \
dumb-init \
tk \
@@ -24,6 +25,7 @@ RUN --mount=type=cache,target=/var/cache/apt ./install_packages \
libglib2.0-0 \
imagemagick
+
# Install pip packages
ENV PATH=/root/.local/bin:$PATH
COPY requirements.txt .
diff --git a/freemocap-ui/package.json b/freemocap-ui/package.json
index 9aa05ee4..d0ac7f43 100644
--- a/freemocap-ui/package.json
+++ b/freemocap-ui/package.json
@@ -13,22 +13,33 @@
"@mui/styled-engine": "^5.2.6",
"@mui/system": "^5.2.8",
"@reduxjs/toolkit": "^1.7.1",
- "@testing-library/jest-dom": "^4.2.4",
- "@testing-library/react": "^9.5.0",
- "@testing-library/user-event": "^7.2.1",
- "@types/jest": "^24.9.1",
- "@types/node": "^12.20.41",
- "@types/react": "^16.14.21",
- "@types/react-dom": "^16.9.14",
- "@types/react-redux": "^7.1.22",
+ "@types/dom-mediacapture-record": "^1.0.11",
+ "axios": "^0.25.0",
+ "class-transformer": "0.5.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.6",
"react-router": "^6.2.1",
"react-router-dom": "^6.2.1",
"react-scripts": "5.0.0",
+ "react-use": "^17.3.2",
"react-webcam": "^6.0.0",
- "typescript": "~4.1.5"
+ "reflect-metadata": "^0.1.13",
+ "typescript": "4.1.5"
+ },
+ "devDependencies": {
+ "@testing-library/jest-dom": "^5.16.1",
+ "@testing-library/react": "^12.1.2",
+ "@testing-library/user-event": "^13.5.0",
+ "@types/axios": "^0.14.0",
+ "@types/debounce": "^1.2.1",
+ "@types/jest": "^27.4.0",
+ "@types/lodash": "^4.14.165",
+ "@types/node": "^16.11.21",
+ "@types/react": "^17.0.38",
+ "@types/react-dom": "^17.0.11",
+ "@types/react-redux": "^7.1.11",
+ "@types/react-router-dom": "^5.1.6"
},
"scripts": {
"start": "react-scripts start",
diff --git a/freemocap-ui/src/components/start-stop-process.tsx b/freemocap-ui/src/components/start-stop-process.tsx
new file mode 100644
index 00000000..445c358f
--- /dev/null
+++ b/freemocap-ui/src/components/start-stop-process.tsx
@@ -0,0 +1,36 @@
+import {Box, Button} from "@mui/material"
+import React, {useEffect, useState} from "react"
+import {RecorderManager, StreamByDeviceId} from "../services/recorder";
+
+interface Props {
+ streams?: StreamByDeviceId;
+}
+
+export const StartStopProcess = (props: Props) => {
+ const [manager, setManager] = useState<RecorderManager>();
+ useEffect(() => {
+ if (!props.streams) { return; }
+ const manager = new RecorderManager(props.streams);
+ manager.registerDataHandler();
+ setManager(manager);
+ }, [props.streams]);
+
+
+ return (
+ <Box display={'flex'}>
+
+ <Box mr={2}>
+ <Button variant={'contained'} onClick={manager?.start}>Start Capture</Button>
+ </Box>
+
+ <Box mr={2}>
+ <Button variant={'contained'} onClick={manager?.stop}>Stop Capture</Button>
+ </Box>
+
+ <Box mr={2}>
+ <Button variant={'contained'} onClick={manager?.process}>Process Recording</Button>
+ </Box>
+ </Box>
+
+ )
+}
\ No newline at end of file
diff --git a/freemocap-ui/src/components/webcam/webcam-capture.tsx b/freemocap-ui/src/components/webcam/webcam-capture.tsx
index a1d2725f..bd466b5a 100644
--- a/freemocap-ui/src/components/webcam/webcam-capture.tsx
+++ b/freemocap-ui/src/components/webcam/webcam-capture.tsx
@@ -23,7 +23,7 @@ export const WebcamCapture = () => {
{devices.map((device, key) => (
<div>
<Webcam audio={false} videoConstraints={{ deviceId: device.deviceId }} />
- {device.label || `Device ${key + 1}`}
+ {device.label || `Device ${device.deviceId}`}
</div>
))}
diff --git a/freemocap-ui/src/features/camera/cameraSlice.tsx b/freemocap-ui/src/features/camera/cameraSlice.tsx
new file mode 100644
index 00000000..1bf6cf75
--- /dev/null
+++ b/freemocap-ui/src/features/camera/cameraSlice.tsx
@@ -0,0 +1,27 @@
+import { createSlice, PayloadAction } from '@reduxjs/toolkit'
+
+export class AppCameraState {
+
+}
+
+// const initialState: CounterState = {
+// value: 0,
+// }
+
+export const cameraSlice = createSlice({
+ name: 'counter',
+ initialState: new AppCameraState(),
+ reducers: {
+ increment: (state) => {
+ },
+ decrement: (state) => {
+ },
+ incrementByAmount: (state, action: PayloadAction<number>) => {
+ },
+ },
+})
+
+// Action creators are generated for each case reducer function
+// export const { increment, decrement, incrementByAmount } = counterSlice.actions
+//
+// export default counterSlice.reducer
diff --git a/freemocap-ui/src/layout/routing/router.tsx b/freemocap-ui/src/layout/routing/router.tsx
index 9f7a150e..5f1c1786 100644
--- a/freemocap-ui/src/layout/routing/router.tsx
+++ b/freemocap-ui/src/layout/routing/router.tsx
@@ -1,12 +1,15 @@
import React from 'react';
import {Route, Routes} from "react-router-dom";
import {ShowCameras} from "../../views/ShowCameras";
+import {WebcamStreamCapture} from "../../views/Capture";
+import {ConfigView} from "../../views/Config";
export const Router = () => {
return (
<Routes>
<Route path={'/'} element={<React.Fragment />} />
- <Route path={'/show_cameras'} element={<ShowCameras />} />
+ <Route path={'/show_cameras'} element={<WebcamStreamCapture />} />
+ <Route path={'/config'} element={<ConfigView />} />
</Routes>
)
}
\ No newline at end of file
diff --git a/freemocap-ui/src/services/cam.ts b/freemocap-ui/src/services/cam.ts
new file mode 100644
index 00000000..7cbd652e
--- /dev/null
+++ b/freemocap-ui/src/services/cam.ts
@@ -0,0 +1,6 @@
+export class BrowserCam {
+ public async findAllCameras() {
+ const devices = await navigator.mediaDevices.enumerateDevices();
+ return devices.filter(({ kind }) => kind === "videoinput");
+ }
+}
\ No newline at end of file
diff --git a/freemocap-ui/src/services/download.ts b/freemocap-ui/src/services/download.ts
new file mode 100644
index 00000000..b0a335ea
--- /dev/null
+++ b/freemocap-ui/src/services/download.ts
@@ -0,0 +1,13 @@
+
+
+export const download = (inputBlob: Blob, outputFileName) => {
+ const url = URL.createObjectURL(inputBlob);
+ const a = document.createElement("a");
+ document.body.appendChild(a);
+ // @ts-ignore
+ a.style = "display: none";
+ a.href = url;
+ a.download = outputFileName;
+ a.click();
+ window.URL.revokeObjectURL(url);
+}
\ No newline at end of file
diff --git a/freemocap-ui/src/services/recorder.ts b/freemocap-ui/src/services/recorder.ts
new file mode 100644
index 00000000..4bcb00df
--- /dev/null
+++ b/freemocap-ui/src/services/recorder.ts
@@ -0,0 +1,68 @@
+import axios from "axios";
+
+export type DeviceId = string;
+export type StreamByDeviceId = Record<DeviceId, MediaStream>;
+export type RecorderByDeviceId = Record<DeviceId, MediaRecorder>;
+export type StreamDataByDeviceId = Record<DeviceId, Blob[]>;
+
+export class RecorderManager {
+ private _recordedData: StreamDataByDeviceId = {};
+ private readonly _recorders: RecorderByDeviceId;
+ private readonly _deviceIds: Array<DeviceId>;
+ private readonly _timesliceInMs: number;
+
+ constructor(streams: StreamByDeviceId, timesliceInMS: number = 500) {
+ this._timesliceInMs = timesliceInMS;
+ this._deviceIds = (Object.keys(streams) as Array<DeviceId>);
+ this._recorders = this._deviceIds.reduce((prev, curDeviceId) => {
+ return {
+ ...prev,
+ [curDeviceId]: new MediaRecorder(streams[curDeviceId])
+ }
+ }, {});
+ this._init_recorded_data();
+ }
+
+ private _init_recorded_data() {
+ const deviceIds = this._deviceIds;
+ deviceIds.forEach(deviceId => {
+ this._recordedData[deviceId] = [];
+ });
+ }
+
+ public registerDataHandler = () => {
+ const deviceIds = this._deviceIds;
+ deviceIds.forEach(deviceId => {
+ const recorder = this._recorders[deviceId];
+ recorder.ondataavailable = (event) => {
+ this._recordedData[deviceId].push(event.data)
+ }
+ })
+ }
+
+ public start = () => {
+ const deviceIds = this._deviceIds;
+ deviceIds.forEach(deviceId => {
+ const recorder = this._recorders[deviceId];
+ recorder.start(10)
+ })
+ }
+
+ public stop = () => {
+ const deviceIds = this._deviceIds;
+ deviceIds.forEach(deviceId => {
+ const recorder = this._recorders[deviceId];
+ recorder.stop()
+ });
+ }
+
+ public process = async () => {
+ const deviceIds = this._deviceIds;
+ for (const deviceId of deviceIds) {
+ const blobChunks = this._recordedData[deviceId];
+ const combinedBlob = new Blob(blobChunks, {type: "video/webm"});
+ await axios.post('http://localhost:8080/camera/upload', combinedBlob);
+ }
+ }
+}
+
diff --git a/freemocap-ui/src/views/Capture.tsx b/freemocap-ui/src/views/Capture.tsx
new file mode 100644
index 00000000..5a98ec09
--- /dev/null
+++ b/freemocap-ui/src/views/Capture.tsx
@@ -0,0 +1,51 @@
+import {Box} from "@mui/material";
+import React, {useState} from "react";
+import Webcam from "react-webcam";
+import {useAsync} from "react-use";
+import {StartStopProcess} from "../components/start-stop-process";
+import {BrowserCam} from "../services/cam";
+import {StreamByDeviceId} from "../services/recorder";
+
+class ViewState {
+ public deviceInfos: MediaDeviceInfo[] = [];
+ public streams!: StreamByDeviceId;
+}
+
+export const WebcamStreamCapture = () => {
+ const [devices, setDevices] = useState<ViewState>(() => new ViewState());
+ // grab all devices
+ useAsync(async () => {
+ const cam = new BrowserCam();
+ const devices = await cam.findAllCameras();
+ setDevices(prev => {
+ return {
+ ...prev,
+ deviceInfos: devices
+ };
+ });
+ }, []);
+
+ return (
+ <Box>
+ <Box>
+ {devices.deviceInfos.map(dev => {
+ return (
+ <Webcam audio={false} videoConstraints={{deviceId: dev.deviceId}} onUserMedia={stream => {
+ setDevices(prev => {
+ return {
+ ...prev,
+ streams: {
+ ...prev.streams,
+ [dev.deviceId]: stream
+ }
+ };
+ });
+ }} />
+ )
+ })}
+ </Box>
+ {devices.streams ? <StartStopProcess streams={devices.streams} /> : <></>}
+
+ </Box>
+ );
+};
diff --git a/freemocap-ui/src/views/Config.tsx b/freemocap-ui/src/views/Config.tsx
new file mode 100644
index 00000000..503071ec
--- /dev/null
+++ b/freemocap-ui/src/views/Config.tsx
@@ -0,0 +1,26 @@
+import {Box, Typography} from "@mui/material";
+import React from "react";
+import {useAsync} from "react-use";
+import {BrowserCam} from "../services/cam";
+
+export const ConfigView = () => {
+ const [Container] = [Box, Box];
+ const [devices, setDevices] = React.useState<MediaDeviceInfo[]>([]);
+ useAsync(async () => {
+ const cam = new BrowserCam();
+ const deviceInfos = await cam.findAllCameras();
+ setDevices(deviceInfos)
+ });
+ const devicesWithNames = devices.filter(x => x.label);
+ return (
+ <Container>
+ <Typography>Configuration</Typography>
+ {devicesWithNames
+ .map(device => {
+ return (
+ <Typography>Webcam {device.label}</Typography>
+ )
+ })}
+ </Container>
+ )
+}
\ No newline at end of file
diff --git a/freemocap-ui/src/views/ShowCameras.tsx b/freemocap-ui/src/views/ShowCameras.tsx
index 04333de9..96cf1841 100644
--- a/freemocap-ui/src/views/ShowCameras.tsx
+++ b/freemocap-ui/src/views/ShowCameras.tsx
@@ -1,7 +1,9 @@
-import {WebcamCapture} from "../components/webcam/webcam-capture";
+import {Box} from "@mui/material";
export const ShowCameras = () => {
return (
- <WebcamCapture/>
+ <Box>
+
+ </Box>
)
}
\ No newline at end of file
diff --git a/freemocap-ui/tsconfig.json b/freemocap-ui/tsconfig.json
index 41929ff7..a02c4268 100644
--- a/freemocap-ui/tsconfig.json
+++ b/freemocap-ui/tsconfig.json
@@ -19,7 +19,8 @@
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
- "noImplicitAny": false
+ "noImplicitAny": false,
+ "experimentalDecorators": true
},
"include": [
"src"
diff --git a/freemocap/dev_scratchpad/dev_alpha_old/FMC_MultiCamera.py b/freemocap/dev_scratchpad/dev_alpha_old/FMC_MultiCamera.py
index 6dd4fd9c..a5bddc89 100644
--- a/freemocap/dev_scratchpad/dev_alpha_old/FMC_MultiCamera.py
+++ b/freemocap/dev_scratchpad/dev_alpha_old/FMC_MultiCamera.py
@@ -303,7 +303,7 @@ class FMC_MultiCamera:
for cam_num in range(self.num_cams):
this_cam_image_timestamp_tuple = self.cam_frame_queue.get()
this_cam_num = this_cam_image_timestamp_tuple[0]
- this_cam_index = self.cams_to_use_list.index(this_cam_num)
+ this_cam_index = self.cams_to_use_list.port_number(this_cam_num)
these_images_list[this_cam_index] = this_cam_image_timestamp_tuple[1]
these_timestamps[this_cam_index] = this_cam_image_timestamp_tuple[2]
this_multi_cam_tuple_as_a_list[this_cam_index] = this_cam_image_timestamp_tuple
diff --git a/freemocap/package-lock.json b/freemocap/package-lock.json
new file mode 100644
index 00000000..1f051745
--- /dev/null
+++ b/freemocap/package-lock.json
@@ -0,0 +1,6 @@
+{
+ "name": "freemocap",
+ "lockfileVersion": 2,
+ "requires": true,
+ "packages": {}
+}
diff --git a/freemocap/prod/README.md b/freemocap/prod/README.md
new file mode 100644
index 00000000..4a40fe2d
--- /dev/null
+++ b/freemocap/prod/README.md
@@ -0,0 +1,5 @@
+
+
+Installation instructions for Mac
+
+- brew install python-tk
\ No newline at end of file
diff --git a/freemocap/prod/cam/cam_detection.py b/freemocap/prod/cam/cam_detection.py
index 9994a54e..1deacc8e 100644
--- a/freemocap/prod/cam/cam_detection.py
+++ b/freemocap/prod/cam/cam_detection.py
@@ -1,4 +1,5 @@
import logging
+import platform
from typing import List
import cv2
@@ -10,27 +11,29 @@ logger = logging.getLogger(__name__)
class RawCamera(BaseModel):
- index: int
+ port_number: int
class FindAvailableResponse(BaseModel):
camera_found_count: int
cams_to_use: List[RawCamera]
+ cv2_backend: int
class DetectPossibleCameras:
def find_available_cameras(self) -> FindAvailableResponse:
- capBackend = cv2.CAP_ANY
+ cv2_backend = self._determine_backend()
cams_to_use_list = []
for camNum in range(CAM_CHECK_NUM):
- cap = cv2.VideoCapture(camNum, capBackend)
+ cap = cv2.VideoCapture(camNum, cv2_backend)
success, image = cap.read()
if success:
+ logger.info(f"We found one: {camNum}")
try:
cams_to_use_list.append(RawCamera(
- index=camNum,
+ port_number=camNum,
))
logger.info(cap.get(cv2.CAP_PROP_SETTINGS))
finally:
@@ -38,5 +41,12 @@ class DetectPossibleCameras:
return FindAvailableResponse(
camera_found_count=len(cams_to_use_list),
- cams_to_use=cams_to_use_list
- )
\ No newline at end of file
+ cams_to_use=cams_to_use_list,
+ cv2_backend=cv2_backend
+ )
+
+ def _determine_backend(self):
+ if platform.system() == 'Windows':
+ return cv2.CAP_DSHOW
+ else:
+ return cv2.CAP_ANY
diff --git a/freemocap/prod/cam/main.py b/freemocap/prod/cam/main.py
new file mode 100644
index 00000000..5970bfab
--- /dev/null
+++ b/freemocap/prod/cam/main.py
@@ -0,0 +1,15 @@
+from freemocap.prod.cam.cam_detection import DetectPossibleCameras
+
+if __name__ == "__main__":
+ c = DetectPossibleCameras()
+ available_cameras = c.find_available_cameras()
+ open_cv_cameras = []
+ #
+ # for cam in available_cameras.cams_to_use:
+ # port_number = cam.port_number
+ # options = OpenCVCameraOptions(
+ # port_number=cam.port_number
+ # )
+ # cv_cam = OpenCVCamera()
+
+
diff --git a/freemocap/prod/cam/opencv_camera.py b/freemocap/prod/cam/opencv_camera.py
index c0cd7807..b7572895 100644
--- a/freemocap/prod/cam/opencv_camera.py
+++ b/freemocap/prod/cam/opencv_camera.py
@@ -1,7 +1,12 @@
+import logging
+
import cv2
from pydantic import BaseModel
-from freemocap.prod.cam.cam_detection import DetectPossibleCameras
+from freemocap.prod.cam.cam_detection import DetectPossibleCameras, FindAvailableResponse
+from jon_scratch.opencv_camera import NoCameraAvailableException
+
+logger = logging.getLogger(__name__)
class OpenCVCameraOptions(BaseModel):
@@ -9,16 +14,32 @@ class OpenCVCameraOptions(BaseModel):
exposure: int = -5
resolution_width: int = 1280
resolution_height: int = 720
+ cv2_backend: int
# # OpenCV Implementation of interacting with a camera
class OpenCVCamera:
def __init__(self, options: OpenCVCameraOptions):
+ self._cam_object = None
self._options = options
def connect(self):
- c = DetectPossibleCameras()
- available_cameras = c.find_available_cameras()
-
-
+ self._cam_object = self._create_cv_cam_object()
+
+ @property
+ def cv2_object(self):
+ return self._cam_object
+
+ # other methods in this class for manipulating the camera
+
+ def _create_cv_cam_object(self):
+ cam_object = cv2.VideoCapture(self._options.port_number, camera_response.cv2_backend)
+ success, image = cam_object.read()
+ if success:
+ logger.info(f'Camera found at port number {individual_camera.port_number}')
+ return cam_object
+ else:
+ error_text = f'Could not connect to a camera at port# {individual_camera.port_number}'
+ logger.error(error_text)
+ raise SystemError(error_text)
diff --git a/freemocap_blender_addon/load_freemocap_data_into_blender.py b/freemocap_blender_addon/load_freemocap_data_into_blender.py
index f52a836e..ab8f0af5 100644
--- a/freemocap_blender_addon/load_freemocap_data_into_blender.py
+++ b/freemocap_blender_addon/load_freemocap_data_into_blender.py
@@ -62,9 +62,9 @@ for frame_number in track(range(number_of_frames), description="[cyan]Loading tr
bpy.context.scene.frame_set(frame_number)
for this_empty_name in tracked_point_names:
this_empty = bpy.data.objects[this_empty_name]
- this_empty.location = (mediapipe_skel_fr_mar_dim[frame_number,tracked_point_names.index(this_empty_name),0],
- mediapipe_skel_fr_mar_dim[frame_number,tracked_point_names.index(this_empty_name),1],
- mediapipe_skel_fr_mar_dim[frame_number,tracked_point_names.index(this_empty_name),2])
+ this_empty.location = (mediapipe_skel_fr_mar_dim[frame_number,tracked_point_names.port_number(this_empty_name),0],
+ mediapipe_skel_fr_mar_dim[frame_number,tracked_point_names.port_number(this_empty_name),1],
+ mediapipe_skel_fr_mar_dim[frame_number,tracked_point_names.port_number(this_empty_name),2])
this_empty.keyframe_insert(data_path='location', frame=frame_number)
diff --git a/jon_scratch/multi_camera_handler.py b/jon_scratch/multi_camera_handler.py
index 15d7784e..7bac589a 100644
--- a/jon_scratch/multi_camera_handler.py
+++ b/jon_scratch/multi_camera_handler.py
@@ -161,7 +161,7 @@ while not thread_exit_event.is_set():
time_elapsed = time.time() - approx_start_time
this_qsize = incoming_frames_queue.qsize()
qsize.append(this_qsize)
- print('Time remaining: {:3.2f} - Queueue size: {:3.0f} '.format(end_after_seconds - time_elapsed, this_qsize))
+ print('Time remaining: {:3.2f} - Queue size: {:3.0f} '.format(end_after_seconds - time_elapsed, this_qsize))
if time_elapsed > end_after_seconds:
thread_exit_event.set()
cv2.destroyAllWindows()
diff --git a/jon_scratch/opencv_camera.py b/jon_scratch/opencv_camera.py
index b583f03d..dc2c284f 100644
--- a/jon_scratch/opencv_camera.py
+++ b/jon_scratch/opencv_camera.py
@@ -20,7 +20,8 @@ class FailedFrameGrabException(Exception):
class TweakedModel(BaseModel):
class Config:
arbitrary_types_allowed = True
-
+
+
# OpenCV Implementation of interacting with a camera
class OpenCVCamera(TweakedModel):
port_number: int=0
@@ -59,7 +60,8 @@ class OpenCVCamera(TweakedModel):
def get_next_frame(self)->dict:
timestamp_ns_pre_grab = time.time_ns()
- grab_success = self.opencv_video_capture_object.grab() #Why grab not read? see -> https://stackoverflow.com/questions/57716962/difference-between-video-capture-read-and-grab
+ # Why grab not read? see -> https://stackoverflow.com/questions/57716962/difference-between-video-capture-read-and-grab
+ grab_success = self.opencv_video_capture_object.grab()
timestamp_ns_post_grab = time.time_ns()
timestamp_ns = (timestamp_ns_pre_grab + timestamp_ns_post_grab)/2
diff --git a/jon_scratch/run_window.py b/jon_scratch/run_window.py
new file mode 100644
index 00000000..f32c0d27
--- /dev/null
+++ b/jon_scratch/run_window.py
@@ -0,0 +1,8 @@
+import time
+import cv2
+
+while True:
+ cv2.namedWindow("test")
+ key = cv2.waitKey(0)
+ if key == 27:
+ break
diff --git a/requirements.txt b/requirements.txt
index eeca4432..e25fd8cf 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -3,7 +3,7 @@ h5py>=3.1.0
imutils~=0.5.4
matplotlib~=3.1.3
mediapipe==0.8.8
-opencv-contrib-python~=3.4.14.51
+opencv-contrib-python==4.5.5.62
pandas~=1.2.5
rich~=10.4.0
tqdm~=4.61.1
@@ -18,5 +18,4 @@ fastapi==0.71.0
gunicorn==20.1.0
requests==2.27.1
pyudev==0.22.0
-# opencv-python-headless==4.5.5.62
-# opencv-python
\ No newline at end of file
+python-multipart==0.0.5
\ No newline at end of file
diff --git a/src/api/app_factory.py b/src/api/app_factory.py
index 1b1a1e35..6b90261e 100644
--- a/src/api/app_factory.py
+++ b/src/api/app_factory.py
@@ -1,18 +1,21 @@
import uvicorn
from fastapi import FastAPI
+from src.api.middleware.cors import cors
from src.api.routes import enabled_routers
def create_app():
- app = FastAPI()
+ _app = FastAPI()
+
+ cors(_app)
for router in enabled_routers:
- app.include_router(router)
+ _app.include_router(router)
- return app
+ return _app
if __name__ == "__main__":
- app = create_app()
- uvicorn.run(app, host="127.0.0.1", port=8080, log_level="info")
+ script_app = create_app()
+ uvicorn.run(script_app, host="127.0.0.1", port=8080, log_level="info")
diff --git a/src/api/middleware/cors.py b/src/api/middleware/cors.py
new file mode 100644
index 00000000..adb00b8a
--- /dev/null
+++ b/src/api/middleware/cors.py
@@ -0,0 +1,11 @@
+from fastapi.middleware.cors import CORSMiddleware
+
+
+def cors(app):
+ app.add_middleware(
+ CORSMiddleware,
+ allow_origins=["*"],
+ allow_credentials=True,
+ allow_methods=["*"],
+ allow_headers=["*"],
+ )
\ No newline at end of file
diff --git a/src/api/routes/camera/camera_route.py b/src/api/routes/camera/camera_route.py
index d732d11f..b3fe04b7 100644
--- a/src/api/routes/camera/camera_route.py
+++ b/src/api/routes/camera/camera_route.py
@@ -1,12 +1,28 @@
+import random
+import uuid
+
+import numpy as np
from fastapi import APIRouter
-from freemocap.prod.cam.cam_detection import DetectPossibleCameras
+from starlette.requests import Request
-# Make a router
camera_router = APIRouter()
# create an endpoint
-@camera_router.get("/camera/detect")
-def camera_detect():
- dpc = DetectPossibleCameras()
- return dpc.getSerialNumber()
+# @camera_router.post("/camera")
+# def begin_detection():
+# pass
+
+
+@camera_router.post('/camera/upload')
+async def stream_camera_bytes(request: Request):
+ body = b''
+ # uuid_str = str(uuid.uuid4())
+ with open(f"{random.randint(0,10000)}.webm", "wb") as fd:
+ async for chunk in request.stream():
+ body += chunk
+ fd.write(chunk)
+
+ # convert into numpy array
+ camera_data = np.frombuffer(body, dtype=np.uint8)
+ print(camera_data)