Redfire-1234 commited on
Commit
f06644b
·
verified ·
1 Parent(s): 77bf120

Update backend/app.py

Browse files
Files changed (1) hide show
  1. backend/app.py +104 -103
backend/app.py CHANGED
@@ -1,104 +1,105 @@
1
- from fastapi import FastAPI, File, UploadFile, HTTPException
2
- from fastapi.middleware.cors import CORSMiddleware
3
- from fastapi.responses import JSONResponse, FileResponse
4
- from fastapi.staticfiles import StaticFiles
5
- import os
6
- import shutil
7
- from pathlib import Path
8
- import json
9
- from tracker import VideoTracker
10
- from utils import save_trajectory_json, create_output_dirs
11
-
12
- app = FastAPI(title="3D Trajectory Tracker")
13
-
14
- # CORS middleware
15
- app.add_middleware(
16
- CORSMiddleware,
17
- allow_origins=["*"],
18
- allow_credentials=True,
19
- allow_methods=["*"],
20
- allow_headers=["*"],
21
- )
22
-
23
- # Create necessary directories
24
- UPLOAD_DIR = Path("uploads")
25
- OUTPUT_DIR = Path("outputs")
26
- FRONTEND_DIR = Path("frontend")
27
-
28
- create_output_dirs([UPLOAD_DIR, OUTPUT_DIR])
29
-
30
- # Mount static files
31
- if FRONTEND_DIR.exists():
32
- app.mount("/static", StaticFiles(directory=FRONTEND_DIR), name="static")
33
-
34
- @app.get("/")
35
- async def read_root():
36
- """Serve the main HTML page"""
37
- index_path = FRONTEND_DIR / "index.html"
38
- if index_path.exists():
39
- return FileResponse(index_path)
40
- return {"message": "3D Trajectory Tracker API"}
41
-
42
- @app.post("/api/upload")
43
- async def upload_video(file: UploadFile = File(...)):
44
- """Upload and process video file"""
45
- try:
46
- # Validate file type
47
- if not file.filename.lower().endswith(('.mp4', '.avi', '.mov', '.mkv')):
48
- raise HTTPException(400, "Invalid file type. Please upload a video file.")
49
-
50
- # Save uploaded file
51
- file_path = UPLOAD_DIR / file.filename
52
- with open(file_path, "wb") as buffer:
53
- shutil.copyfileobj(file.file, buffer)
54
-
55
- # Process video
56
- tracker = VideoTracker(str(file_path))
57
- trajectories = tracker.process_video()
58
-
59
- # Save results
60
- output_path = OUTPUT_DIR / f"{Path(file.filename).stem}_trajectories.json"
61
- save_trajectory_json(trajectories, output_path)
62
-
63
- # Clean up uploaded file
64
- os.remove(file_path)
65
-
66
- return JSONResponse({
67
- "success": True,
68
- "trajectories": trajectories,
69
- "output_file": str(output_path)
70
- })
71
-
72
- except Exception as e:
73
- raise HTTPException(500, f"Processing error: {str(e)}")
74
-
75
- @app.get("/api/trajectories/{filename}")
76
- async def get_trajectory(filename: str):
77
- """Retrieve saved trajectory data"""
78
- file_path = OUTPUT_DIR / filename
79
- if not file_path.exists():
80
- raise HTTPException(404, "Trajectory file not found")
81
-
82
- with open(file_path, "r") as f:
83
- data = json.load(f)
84
-
85
- return JSONResponse(data)
86
-
87
- @app.get("/api/list")
88
- async def list_trajectories():
89
- """List all processed trajectories"""
90
- files = [f.name for f in OUTPUT_DIR.glob("*.json")]
91
- return JSONResponse({"files": files})
92
-
93
- @app.delete("/api/clear")
94
- async def clear_data():
95
- """Clear all uploaded and processed files"""
96
- for folder in [UPLOAD_DIR, OUTPUT_DIR]:
97
- for file in folder.glob("*"):
98
- if file.is_file():
99
- os.remove(file)
100
- return JSONResponse({"success": True, "message": "All data cleared"})
101
-
102
- if __name__ == "__main__":
103
- import uvicorn
 
104
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
+ from fastapi import FastAPI, File, UploadFile, HTTPException
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from fastapi.responses import JSONResponse, FileResponse
4
+ from fastapi.staticfiles import StaticFiles
5
+ import os
6
+ import shutil
7
+ from pathlib import Path
8
+ import json
9
+ from tracker import VideoTracker
10
+ from utils import save_trajectory_json, create_output_dirs
11
+
12
+ app = FastAPI(title="3D Trajectory Tracker")
13
+
14
+ # CORS middleware
15
+ app.add_middleware(
16
+ CORSMiddleware,
17
+ allow_origins=["*"],
18
+ allow_credentials=True,
19
+ allow_methods=["*"],
20
+ allow_headers=["*"],
21
+ )
22
+
23
+ # Create necessary directories
24
+ BASE_DIR = Path(__file__).parent.parent
25
+ UPLOAD_DIR = BASE_DIR / "uploads"
26
+ OUTPUT_DIR = BASE_DIR / "outputs"
27
+ FRONTEND_DIR = BASE_DIR / "frontend"
28
+
29
+ create_output_dirs([UPLOAD_DIR, OUTPUT_DIR])
30
+
31
+ # Mount static files
32
+ if FRONTEND_DIR.exists():
33
+ app.mount("/static", StaticFiles(directory=FRONTEND_DIR), name="static")
34
+
35
+ @app.get("/")
36
+ async def read_root():
37
+ """Serve the main HTML page"""
38
+ index_path = FRONTEND_DIR / "index.html"
39
+ if index_path.exists():
40
+ return FileResponse(index_path)
41
+ return {"message": "3D Trajectory Tracker API"}
42
+
43
+ @app.post("/api/upload")
44
+ async def upload_video(file: UploadFile = File(...)):
45
+ """Upload and process video file"""
46
+ try:
47
+ # Validate file type
48
+ if not file.filename.lower().endswith(('.mp4', '.avi', '.mov', '.mkv')):
49
+ raise HTTPException(400, "Invalid file type. Please upload a video file.")
50
+
51
+ # Save uploaded file
52
+ file_path = UPLOAD_DIR / file.filename
53
+ with open(file_path, "wb") as buffer:
54
+ shutil.copyfileobj(file.file, buffer)
55
+
56
+ # Process video
57
+ tracker = VideoTracker(str(file_path))
58
+ trajectories = tracker.process_video()
59
+
60
+ # Save results
61
+ output_path = OUTPUT_DIR / f"{Path(file.filename).stem}_trajectories.json"
62
+ save_trajectory_json(trajectories, output_path)
63
+
64
+ # Clean up uploaded file
65
+ os.remove(file_path)
66
+
67
+ return JSONResponse({
68
+ "success": True,
69
+ "trajectories": trajectories,
70
+ "output_file": str(output_path)
71
+ })
72
+
73
+ except Exception as e:
74
+ raise HTTPException(500, f"Processing error: {str(e)}")
75
+
76
+ @app.get("/api/trajectories/{filename}")
77
+ async def get_trajectory(filename: str):
78
+ """Retrieve saved trajectory data"""
79
+ file_path = OUTPUT_DIR / filename
80
+ if not file_path.exists():
81
+ raise HTTPException(404, "Trajectory file not found")
82
+
83
+ with open(file_path, "r") as f:
84
+ data = json.load(f)
85
+
86
+ return JSONResponse(data)
87
+
88
+ @app.get("/api/list")
89
+ async def list_trajectories():
90
+ """List all processed trajectories"""
91
+ files = [f.name for f in OUTPUT_DIR.glob("*.json")]
92
+ return JSONResponse({"files": files})
93
+
94
+ @app.delete("/api/clear")
95
+ async def clear_data():
96
+ """Clear all uploaded and processed files"""
97
+ for folder in [UPLOAD_DIR, OUTPUT_DIR]:
98
+ for file in folder.glob("*"):
99
+ if file.is_file():
100
+ os.remove(file)
101
+ return JSONResponse({"success": True, "message": "All data cleared"})
102
+
103
+ if __name__ == "__main__":
104
+ import uvicorn
105
  uvicorn.run(app, host="0.0.0.0", port=7860)