File size: 3,093 Bytes
8b483f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import math
import requests
from app.model import model

# Must match data.yaml: ['Accident', 'Non-accident', 'Fire']
CLASS_NAMES = {0: "Accident", 1: "Non-accident", 2: "Fire"}
ALERT_CLASSES = {"Accident", "Fire"}


def predict_image(file_path, conf_threshold=0.3):
    """Run YOLO inference on an image and return detections list."""
    results = model(file_path, conf=conf_threshold, verbose=False)
    result = results[0]

    detections = []
    for box in result.boxes:
        cls_id = int(box.cls[0])
        conf = float(box.conf[0])
        label = CLASS_NAMES.get(cls_id, "unknown")
        detections.append({"label": label, "confidence": round(conf, 3)})

    return detections


def haversine_km(lat1, lon1, lat2, lon2):
    """Calculate great-circle distance in km between two lat/lon points."""
    R = 6371
    dlat = math.radians(lat2 - lat1)
    dlon = math.radians(lon2 - lon1)
    a = (
        math.sin(dlat / 2) ** 2
        + math.cos(math.radians(lat1))
        * math.cos(math.radians(lat2))
        * math.sin(dlon / 2) ** 2
    )
    return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))


def get_ip_location():
    """Get approximate location via free IP geolocation (no API key)."""
    try:
        r = requests.get("http://ip-api.com/json/", timeout=5)
        d = r.json()
        if d.get("status") == "success":
            return {
                "lat": d["lat"],
                "lon": d["lon"],
                "city": d.get("city", ""),
                "region": d.get("regionName", ""),
                "country": d.get("country", ""),
            }
    except Exception:
        pass
    return None


def fetch_hospitals(lat, lon, radius_m=5000):
    """Query OpenStreetMap Overpass API for hospitals within radius_m metres."""
    query = f"""
    [out:json][timeout:10];
    (
      node["amenity"="hospital"](around:{radius_m},{lat},{lon});
      way["amenity"="hospital"](around:{radius_m},{lat},{lon});
      relation["amenity"="hospital"](around:{radius_m},{lat},{lon});
    );
    out center body;
    """
    try:
        r = requests.post(
            "https://overpass-api.de/api/interpreter",
            data={"data": query},
            timeout=15,
        )
        elements = r.json().get("elements", [])
    except Exception:
        return []

    hospitals = []
    for el in elements:
        tags = el.get("tags", {})
        if el["type"] == "node":
            h_lat, h_lon = el["lat"], el["lon"]
        else:
            c = el.get("center", {})
            h_lat = c.get("lat", lat)
            h_lon = c.get("lon", lon)

        dist = haversine_km(lat, lon, h_lat, h_lon)
        hospitals.append(
            {
                "name": tags.get("name", "Unnamed Hospital"),
                "lat": h_lat,
                "lon": h_lon,
                "distance_km": round(dist, 2),
                "phone": tags.get("phone", tags.get("contact:phone", None)),
                "emergency": tags.get("emergency", "unknown"),
            }
        )

    hospitals.sort(key=lambda h: h["distance_km"])
    return hospitals