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