Update download_api.py
Browse files- download_api.py +49 -20
download_api.py
CHANGED
|
@@ -1,20 +1,49 @@
|
|
| 1 |
-
from fastapi import FastAPI, HTTPException
|
| 2 |
-
from fastapi.responses import FileResponse
|
| 3 |
-
from pathlib import Path
|
| 4 |
-
import os
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
def
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
from fastapi.responses import FileResponse
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import os
|
| 5 |
+
import threading
|
| 6 |
+
import time
|
| 7 |
+
import sys
|
| 8 |
+
sys.path.append(str(Path(__file__).parent / "scripts"))
|
| 9 |
+
from cursor_tracker import track_cursor
|
| 10 |
+
|
| 11 |
+
app = FastAPI()
|
| 12 |
+
|
| 13 |
+
ANNOTATIONS_DIR = Path("annotations").resolve()
|
| 14 |
+
|
| 15 |
+
# Only run once per server start
|
| 16 |
+
cursor_tracking_started = False
|
| 17 |
+
|
| 18 |
+
def run_cursor_tracker_once():
|
| 19 |
+
global cursor_tracking_started
|
| 20 |
+
if cursor_tracking_started:
|
| 21 |
+
return
|
| 22 |
+
cursor_tracking_started = True
|
| 23 |
+
try:
|
| 24 |
+
# These should match your preset values
|
| 25 |
+
FRAMES_DIR = 'frames/sample_task'
|
| 26 |
+
CURSOR_TEMPLATES_DIR = 'cursors'
|
| 27 |
+
OUTPUT_JSON = 'annotations/test.json'
|
| 28 |
+
THRESHOLD = 0.8
|
| 29 |
+
print("[INFO] Running cursor tracking on server startup...")
|
| 30 |
+
track_cursor(FRAMES_DIR, CURSOR_TEMPLATES_DIR, OUTPUT_JSON, THRESHOLD, start_frame=0, email_results=False)
|
| 31 |
+
except Exception as e:
|
| 32 |
+
print(f"[ERROR] Cursor tracking failed: {e}")
|
| 33 |
+
|
| 34 |
+
@app.on_event("startup")
|
| 35 |
+
def startup_event():
|
| 36 |
+
# Run in a thread so server starts immediately
|
| 37 |
+
threading.Thread(target=run_cursor_tracker_once, daemon=True).start()
|
| 38 |
+
|
| 39 |
+
@app.get("/download/{filename}")
|
| 40 |
+
def download_file(filename: str):
|
| 41 |
+
file_path = ANNOTATIONS_DIR / filename
|
| 42 |
+
if not file_path.exists() or not file_path.is_file():
|
| 43 |
+
raise HTTPException(status_code=404, detail="File not found")
|
| 44 |
+
return FileResponse(str(file_path), filename=filename)
|
| 45 |
+
|
| 46 |
+
@app.get("/")
|
| 47 |
+
def root():
|
| 48 |
+
files = [f.name for f in ANNOTATIONS_DIR.glob("*.json")]
|
| 49 |
+
return {"message": "Use /download/{filename} to download a file.", "available_files": files}
|