Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,144 +1,144 @@
|
|
| 1 |
-
# app.py
|
| 2 |
-
from fastapi import FastAPI, UploadFile, Form, BackgroundTasks
|
| 3 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
-
from fastapi.responses import JSONResponse
|
| 5 |
-
from pathlib import Path
|
| 6 |
-
import subprocess
|
| 7 |
-
import shutil
|
| 8 |
-
import time
|
| 9 |
-
import traceback
|
| 10 |
-
import cloudinary
|
| 11 |
-
import cloudinary.uploader
|
| 12 |
-
from io import BytesIO
|
| 13 |
-
from huggingface_hub import hf_hub_download
|
| 14 |
-
|
| 15 |
-
app = FastAPI(
|
| 16 |
-
title="🚦 VRU Detection & Forecasting API",
|
| 17 |
-
description="Backend API for VRU Detection, Tracking & Forecasting pipeline (Hugging Face Spaces Edition)",
|
| 18 |
-
version="1.0.0"
|
| 19 |
-
)
|
| 20 |
-
|
| 21 |
-
# ==============================
|
| 22 |
-
# CONFIG
|
| 23 |
-
# ==============================
|
| 24 |
-
# Configure Cloudinary (you can put these in .env instead)
|
| 25 |
-
cloudinary.config(
|
| 26 |
-
cloud_name="YOUR_CLOUD_NAME",
|
| 27 |
-
api_key="YOUR_API_KEY",
|
| 28 |
-
api_secret="YOUR_API_SECRET"
|
| 29 |
-
)
|
| 30 |
-
|
| 31 |
-
SCRIPTS = [
|
| 32 |
-
("Video Creation", "video_creation.py"),
|
| 33 |
-
("YOLO + DeepSORT Tracking", "yolo_deepsort_tracker.py"),
|
| 34 |
-
("Excel Generation", "excel_generation.py"),
|
| 35 |
-
("Feature Engineering", "feature_engineering_forecasting.py"),
|
| 36 |
-
("Trajectory Forecasting (Transformer)", "vru_forecasting_transformer.py"),
|
| 37 |
-
("Trajectory Visualization", "animated_visualization.py")
|
| 38 |
-
]
|
| 39 |
-
|
| 40 |
-
OUTPUT_GIF = Path("trajectory_comparison.gif")
|
| 41 |
-
|
| 42 |
-
# ==============================
|
| 43 |
-
# CORS
|
| 44 |
-
# ==============================
|
| 45 |
-
app.add_middleware(
|
| 46 |
-
CORSMiddleware,
|
| 47 |
-
allow_origins=["
|
| 48 |
-
allow_credentials=True,
|
| 49 |
-
allow_methods=["*"],
|
| 50 |
-
allow_headers=["*"],
|
| 51 |
-
)
|
| 52 |
-
|
| 53 |
-
# ==============================
|
| 54 |
-
# UTILS
|
| 55 |
-
# ==============================
|
| 56 |
-
def run_pipeline(input_path: str):
|
| 57 |
-
"""Sequentially run all VRU pipeline scripts."""
|
| 58 |
-
total = len(SCRIPTS)
|
| 59 |
-
progress = []
|
| 60 |
-
for i, (label, script) in enumerate(SCRIPTS):
|
| 61 |
-
stage_info = {
|
| 62 |
-
"stage": i + 1,
|
| 63 |
-
"label": label,
|
| 64 |
-
"status": "running",
|
| 65 |
-
"progress": round((i + 1) / total, 2)
|
| 66 |
-
}
|
| 67 |
-
progress.append(stage_info)
|
| 68 |
-
try:
|
| 69 |
-
result = subprocess.run(
|
| 70 |
-
["python", script, input_path],
|
| 71 |
-
capture_output=True, text=True
|
| 72 |
-
)
|
| 73 |
-
if result.returncode == 0:
|
| 74 |
-
stage_info["status"] = "completed"
|
| 75 |
-
stage_info["output"] = result.stdout
|
| 76 |
-
else:
|
| 77 |
-
stage_info["status"] = "failed"
|
| 78 |
-
stage_info["error"] = result.stderr
|
| 79 |
-
return {"status": "failed", "progress": progress}
|
| 80 |
-
except Exception as e:
|
| 81 |
-
stage_info["status"] = "error"
|
| 82 |
-
stage_info["error"] = str(e)
|
| 83 |
-
return {"status": "failed", "progress": progress}
|
| 84 |
-
time.sleep(0.5)
|
| 85 |
-
return {"status": "completed", "progress": progress}
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
# ==============================
|
| 89 |
-
# ROUTES
|
| 90 |
-
# ==============================
|
| 91 |
-
@app.get("/")
|
| 92 |
-
def home():
|
| 93 |
-
return {"message": "🚦 VRU Detection Backend Running on Hugging Face Spaces!"}
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
@app.post("/run_pipeline/")
|
| 97 |
-
async def run_vru_pipeline(
|
| 98 |
-
background_tasks: BackgroundTasks,
|
| 99 |
-
dataset_name: str = Form(None),
|
| 100 |
-
file: UploadFile = None
|
| 101 |
-
):
|
| 102 |
-
"""
|
| 103 |
-
Run full VRU pipeline.
|
| 104 |
-
Accepts either uploaded file or Hugging Face dataset name.
|
| 105 |
-
"""
|
| 106 |
-
|
| 107 |
-
try:
|
| 108 |
-
# Handle file upload
|
| 109 |
-
if file:
|
| 110 |
-
temp_path = Path("uploaded_" + file.filename)
|
| 111 |
-
with open(temp_path, "wb") as buffer:
|
| 112 |
-
shutil.copyfileobj(file.file, buffer)
|
| 113 |
-
input_path = str(temp_path)
|
| 114 |
-
|
| 115 |
-
# Handle Hugging Face dataset file
|
| 116 |
-
elif dataset_name:
|
| 117 |
-
input_path = hf_hub_download(
|
| 118 |
-
repo_id=dataset_name,
|
| 119 |
-
filename="ring_side_left/video.mp4" # Adjust if structure differs
|
| 120 |
-
)
|
| 121 |
-
|
| 122 |
-
else:
|
| 123 |
-
return JSONResponse({"error": "Please provide a dataset_name or upload a file."}, status_code=400)
|
| 124 |
-
|
| 125 |
-
# Run pipeline
|
| 126 |
-
result = run_pipeline(input_path)
|
| 127 |
-
response = {"input_path": input_path, "result": result}
|
| 128 |
-
|
| 129 |
-
# Upload visualization if available
|
| 130 |
-
if OUTPUT_GIF.exists():
|
| 131 |
-
upload_result = cloudinary.uploader.upload(
|
| 132 |
-
str(OUTPUT_GIF),
|
| 133 |
-
resource_type="image",
|
| 134 |
-
folder="vru_results/"
|
| 135 |
-
)
|
| 136 |
-
response["visualization_url"] = upload_result["secure_url"]
|
| 137 |
-
|
| 138 |
-
return JSONResponse(response)
|
| 139 |
-
|
| 140 |
-
except Exception as e:
|
| 141 |
-
return JSONResponse(
|
| 142 |
-
{"error": str(e), "trace": traceback.format_exc()},
|
| 143 |
-
status_code=500
|
| 144 |
-
)
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
from fastapi import FastAPI, UploadFile, Form, BackgroundTasks
|
| 3 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
+
from fastapi.responses import JSONResponse
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import subprocess
|
| 7 |
+
import shutil
|
| 8 |
+
import time
|
| 9 |
+
import traceback
|
| 10 |
+
import cloudinary
|
| 11 |
+
import cloudinary.uploader
|
| 12 |
+
from io import BytesIO
|
| 13 |
+
from huggingface_hub import hf_hub_download
|
| 14 |
+
|
| 15 |
+
app = FastAPI(
|
| 16 |
+
title="🚦 VRU Detection & Forecasting API",
|
| 17 |
+
description="Backend API for VRU Detection, Tracking & Forecasting pipeline (Hugging Face Spaces Edition)",
|
| 18 |
+
version="1.0.0"
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
# ==============================
|
| 22 |
+
# CONFIG
|
| 23 |
+
# ==============================
|
| 24 |
+
# Configure Cloudinary (you can put these in .env instead)
|
| 25 |
+
cloudinary.config(
|
| 26 |
+
cloud_name="YOUR_CLOUD_NAME",
|
| 27 |
+
api_key="YOUR_API_KEY",
|
| 28 |
+
api_secret="YOUR_API_SECRET"
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
SCRIPTS = [
|
| 32 |
+
("Video Creation", "video_creation.py"),
|
| 33 |
+
("YOLO + DeepSORT Tracking", "yolo_deepsort_tracker.py"),
|
| 34 |
+
("Excel Generation", "excel_generation.py"),
|
| 35 |
+
("Feature Engineering", "feature_engineering_forecasting.py"),
|
| 36 |
+
("Trajectory Forecasting (Transformer)", "vru_forecasting_transformer.py"),
|
| 37 |
+
("Trajectory Visualization", "animated_visualization.py")
|
| 38 |
+
]
|
| 39 |
+
|
| 40 |
+
OUTPUT_GIF = Path("trajectory_comparison.gif")
|
| 41 |
+
|
| 42 |
+
# ==============================
|
| 43 |
+
# CORS
|
| 44 |
+
# ==============================
|
| 45 |
+
app.add_middleware(
|
| 46 |
+
CORSMiddleware,
|
| 47 |
+
allow_origins=["https://vru-detection.vercel.app/"], # later replace with your frontend URL
|
| 48 |
+
allow_credentials=True,
|
| 49 |
+
allow_methods=["*"],
|
| 50 |
+
allow_headers=["*"],
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
# ==============================
|
| 54 |
+
# UTILS
|
| 55 |
+
# ==============================
|
| 56 |
+
def run_pipeline(input_path: str):
|
| 57 |
+
"""Sequentially run all VRU pipeline scripts."""
|
| 58 |
+
total = len(SCRIPTS)
|
| 59 |
+
progress = []
|
| 60 |
+
for i, (label, script) in enumerate(SCRIPTS):
|
| 61 |
+
stage_info = {
|
| 62 |
+
"stage": i + 1,
|
| 63 |
+
"label": label,
|
| 64 |
+
"status": "running",
|
| 65 |
+
"progress": round((i + 1) / total, 2)
|
| 66 |
+
}
|
| 67 |
+
progress.append(stage_info)
|
| 68 |
+
try:
|
| 69 |
+
result = subprocess.run(
|
| 70 |
+
["python", script, input_path],
|
| 71 |
+
capture_output=True, text=True
|
| 72 |
+
)
|
| 73 |
+
if result.returncode == 0:
|
| 74 |
+
stage_info["status"] = "completed"
|
| 75 |
+
stage_info["output"] = result.stdout
|
| 76 |
+
else:
|
| 77 |
+
stage_info["status"] = "failed"
|
| 78 |
+
stage_info["error"] = result.stderr
|
| 79 |
+
return {"status": "failed", "progress": progress}
|
| 80 |
+
except Exception as e:
|
| 81 |
+
stage_info["status"] = "error"
|
| 82 |
+
stage_info["error"] = str(e)
|
| 83 |
+
return {"status": "failed", "progress": progress}
|
| 84 |
+
time.sleep(0.5)
|
| 85 |
+
return {"status": "completed", "progress": progress}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ==============================
|
| 89 |
+
# ROUTES
|
| 90 |
+
# ==============================
|
| 91 |
+
@app.get("/")
|
| 92 |
+
def home():
|
| 93 |
+
return {"message": "🚦 VRU Detection Backend Running on Hugging Face Spaces!"}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@app.post("/run_pipeline/")
|
| 97 |
+
async def run_vru_pipeline(
|
| 98 |
+
background_tasks: BackgroundTasks,
|
| 99 |
+
dataset_name: str = Form(None),
|
| 100 |
+
file: UploadFile = None
|
| 101 |
+
):
|
| 102 |
+
"""
|
| 103 |
+
Run full VRU pipeline.
|
| 104 |
+
Accepts either uploaded file or Hugging Face dataset name.
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
try:
|
| 108 |
+
# Handle file upload
|
| 109 |
+
if file:
|
| 110 |
+
temp_path = Path("uploaded_" + file.filename)
|
| 111 |
+
with open(temp_path, "wb") as buffer:
|
| 112 |
+
shutil.copyfileobj(file.file, buffer)
|
| 113 |
+
input_path = str(temp_path)
|
| 114 |
+
|
| 115 |
+
# Handle Hugging Face dataset file
|
| 116 |
+
elif dataset_name:
|
| 117 |
+
input_path = hf_hub_download(
|
| 118 |
+
repo_id=dataset_name,
|
| 119 |
+
filename="ring_side_left/video.mp4" # Adjust if structure differs
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
else:
|
| 123 |
+
return JSONResponse({"error": "Please provide a dataset_name or upload a file."}, status_code=400)
|
| 124 |
+
|
| 125 |
+
# Run pipeline
|
| 126 |
+
result = run_pipeline(input_path)
|
| 127 |
+
response = {"input_path": input_path, "result": result}
|
| 128 |
+
|
| 129 |
+
# Upload visualization if available
|
| 130 |
+
if OUTPUT_GIF.exists():
|
| 131 |
+
upload_result = cloudinary.uploader.upload(
|
| 132 |
+
str(OUTPUT_GIF),
|
| 133 |
+
resource_type="image",
|
| 134 |
+
folder="vru_results/"
|
| 135 |
+
)
|
| 136 |
+
response["visualization_url"] = upload_result["secure_url"]
|
| 137 |
+
|
| 138 |
+
return JSONResponse(response)
|
| 139 |
+
|
| 140 |
+
except Exception as e:
|
| 141 |
+
return JSONResponse(
|
| 142 |
+
{"error": str(e), "trace": traceback.format_exc()},
|
| 143 |
+
status_code=500
|
| 144 |
+
)
|