File size: 2,221 Bytes
08bdf44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
from fastapi import FastAPI, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
import shutil
import os
from app.utils import predict_image, get_ip_location, fetch_hospitals, ALERT_CLASSES

app = FastAPI(
    title="AccidentAI API",
    description="YOLOv8-powered accident & fire detection with emergency hospital alerts",
    version="1.0.0",
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

UPLOAD_FOLDER = "temp"
os.makedirs(UPLOAD_FOLDER, exist_ok=True)


@app.get("/")
def home():
    return {"message": "AccidentAI โ€” YOLO Accident Detection API ๐Ÿš€", "status": "running"}


@app.post("/predict")
async def predict(file: UploadFile = File(...), lat: float = None, lon: float = None):
    """
    Upload an image for accident/fire detection.
    Optionally pass lat/lon for hospital lookup; otherwise IP geolocation is used.
    """
    file_path = os.path.join(UPLOAD_FOLDER, file.filename)

    with open(file_path, "wb") as buffer:
        shutil.copyfileobj(file.file, buffer)

    detections = predict_image(file_path)

    # Clean up uploaded file
    try:
        os.remove(file_path)
    except OSError:
        pass

    # Check for alerts
    alert_labels = [d["label"] for d in detections if d["label"] in ALERT_CLASSES]
    has_alert = len(alert_labels) > 0

    response = {
        "filename": file.filename,
        "detections": detections,
        "alert": has_alert,
        "alert_labels": list(set(alert_labels)),
    }

    # If accident/fire detected โ†’ find nearby hospitals
    if has_alert:
        if lat is not None and lon is not None:
            location = {"lat": lat, "lon": lon}
        else:
            location = get_ip_location()

        if location:
            hospitals = fetch_hospitals(location["lat"], location["lon"])
            response["location"] = location
            response["hospitals_nearby"] = hospitals
            response["hospitals_notified"] = len(hospitals[:3])
            response["nearest_hospital"] = hospitals[0] if hospitals else None
        else:
            response["location"] = None
            response["hospitals_nearby"] = []

    return response