Update api.py
Browse files
api.py
CHANGED
|
@@ -8,18 +8,16 @@ import os
|
|
| 8 |
load_dotenv()
|
| 9 |
|
| 10 |
TOMTOM_API_KEY = os.getenv("TOMTOM_API_KEY")
|
|
|
|
| 11 |
|
| 12 |
-
def get_realtime_traffic(origin_coords: Tuple[float, float],dest_coords: Tuple[float, float]) -> Optional[Dict]:
|
| 13 |
-
"""
|
| 14 |
-
Get real-time traffic using tomtom api
|
| 15 |
-
"""
|
| 16 |
base_url = "https://api.tomtom.com/routing/1/calculateRoute"
|
| 17 |
origin = f"{origin_coords[0]},{origin_coords[1]}"
|
| 18 |
destination = f"{dest_coords[0]},{dest_coords[1]}"
|
| 19 |
url = f"{base_url}/{origin}:{destination}/json"
|
| 20 |
|
| 21 |
headers = {"Accept": "application/json"}
|
| 22 |
-
|
| 23 |
params = {
|
| 24 |
"key": TOMTOM_API_KEY,
|
| 25 |
"traffic": "true",
|
|
@@ -36,25 +34,102 @@ def get_realtime_traffic(origin_coords: Tuple[float, float],dest_coords: Tuple[f
|
|
| 36 |
print(f"Error fetching traffic data: {e}")
|
| 37 |
return None
|
| 38 |
|
| 39 |
-
|
|
|
|
| 40 |
"""
|
| 41 |
-
|
|
|
|
| 42 |
"""
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
params = {
|
| 46 |
"q": address,
|
| 47 |
"format": "json",
|
| 48 |
"limit": 1
|
| 49 |
}
|
| 50 |
-
|
| 51 |
headers = {
|
| 52 |
"User-Agent": "DeliveryOptimizationSystem/1.0"
|
| 53 |
}
|
| 54 |
|
| 55 |
try:
|
| 56 |
time.sleep(1)
|
| 57 |
-
response = requests.get(url, params=params, headers=headers, timeout=
|
| 58 |
response.raise_for_status()
|
| 59 |
data = response.json()
|
| 60 |
|
|
@@ -68,14 +143,11 @@ def geocode_address_nominatim(address: str) -> Optional[Tuple[float, float]]:
|
|
| 68 |
|
| 69 |
def get_route_osrm(origin_coords: Tuple[float, float],
|
| 70 |
dest_coords: Tuple[float, float]) -> Optional[Dict]:
|
| 71 |
-
"""
|
| 72 |
-
Routing using OSRM (OpenStreetMap Routing Machine
|
| 73 |
-
"""
|
| 74 |
lat1, lon1 = origin_coords
|
| 75 |
lat2, lon2 = dest_coords
|
| 76 |
|
| 77 |
url = f"http://router.project-osrm.org/route/v1/driving/{lon1},{lat1};{lon2},{lat2}"
|
| 78 |
-
|
| 79 |
params = {
|
| 80 |
"overview": "full",
|
| 81 |
"geometries": "geojson",
|
|
@@ -104,14 +176,11 @@ def get_route_osrm(origin_coords: Tuple[float, float],
|
|
| 104 |
|
| 105 |
def get_alternative_routes_osrm(origin_coords: Tuple[float, float],
|
| 106 |
dest_coords: Tuple[float, float]) -> list:
|
| 107 |
-
"""
|
| 108 |
-
Get multiple route options
|
| 109 |
-
"""
|
| 110 |
lat1, lon1 = origin_coords
|
| 111 |
lat2, lon2 = dest_coords
|
| 112 |
|
| 113 |
url = f"http://router.project-osrm.org/route/v1/driving/{lon1},{lat1};{lon2},{lat2}"
|
| 114 |
-
|
| 115 |
params = {
|
| 116 |
"alternatives": "true",
|
| 117 |
"steps": "true",
|
|
@@ -134,16 +203,14 @@ def get_alternative_routes_osrm(origin_coords: Tuple[float, float],
|
|
| 134 |
except:
|
| 135 |
return []
|
| 136 |
|
|
|
|
| 137 |
def get_detailed_route_with_instructions(origin_coords: Tuple[float, float],
|
| 138 |
dest_coords: Tuple[float, float]) -> Optional[Dict]:
|
| 139 |
-
"""
|
| 140 |
-
Get detailed route with turn-by-turn instructions and road names
|
| 141 |
-
"""
|
| 142 |
lat1, lon1 = origin_coords
|
| 143 |
lat2, lon2 = dest_coords
|
| 144 |
|
| 145 |
url = f"http://router.project-osrm.org/route/v1/driving/{lon1},{lat1};{lon2},{lat2}"
|
| 146 |
-
|
| 147 |
params = {
|
| 148 |
"alternatives": "true",
|
| 149 |
"steps": "true",
|
|
|
|
| 8 |
load_dotenv()
|
| 9 |
|
| 10 |
TOMTOM_API_KEY = os.getenv("TOMTOM_API_KEY")
|
| 11 |
+
OPENWEATHER_API_KEY = os.getenv("OPENWEATHER_API_KEY")
|
| 12 |
|
| 13 |
+
def get_realtime_traffic(origin_coords: Tuple[float, float], dest_coords: Tuple[float, float]) -> Optional[Dict]:
|
| 14 |
+
"""Get real-time traffic using TomTom API"""
|
|
|
|
|
|
|
| 15 |
base_url = "https://api.tomtom.com/routing/1/calculateRoute"
|
| 16 |
origin = f"{origin_coords[0]},{origin_coords[1]}"
|
| 17 |
destination = f"{dest_coords[0]},{dest_coords[1]}"
|
| 18 |
url = f"{base_url}/{origin}:{destination}/json"
|
| 19 |
|
| 20 |
headers = {"Accept": "application/json"}
|
|
|
|
| 21 |
params = {
|
| 22 |
"key": TOMTOM_API_KEY,
|
| 23 |
"traffic": "true",
|
|
|
|
| 34 |
print(f"Error fetching traffic data: {e}")
|
| 35 |
return None
|
| 36 |
|
| 37 |
+
|
| 38 |
+
def get_weather_data(lat: float, lon: float) -> Optional[Dict]:
|
| 39 |
"""
|
| 40 |
+
Get weather data using OpenWeatherMap API
|
| 41 |
+
Returns: temperature, condition, precipitation, wind speed
|
| 42 |
"""
|
| 43 |
+
if not OPENWEATHER_API_KEY:
|
| 44 |
+
return None
|
| 45 |
+
|
| 46 |
+
url = "https://api.openweathermap.org/data/2.5/weather"
|
| 47 |
+
params = {
|
| 48 |
+
"lat": lat,
|
| 49 |
+
"lon": lon,
|
| 50 |
+
"appid": OPENWEATHER_API_KEY,
|
| 51 |
+
"units": "metric"
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
try:
|
| 55 |
+
response = requests.get(url, params=params, timeout=10)
|
| 56 |
+
response.raise_for_status()
|
| 57 |
+
data = response.json()
|
| 58 |
+
|
| 59 |
+
return {
|
| 60 |
+
"temperature": data["main"]["temp"],
|
| 61 |
+
"feels_like": data["main"]["feels_like"],
|
| 62 |
+
"condition": data["weather"][0]["main"],
|
| 63 |
+
"description": data["weather"][0]["description"],
|
| 64 |
+
"humidity": data["main"]["humidity"],
|
| 65 |
+
"wind_speed": data["wind"]["speed"],
|
| 66 |
+
"rain": data.get("rain", {}).get("1h", 0),
|
| 67 |
+
"visibility": data.get("visibility", 10000) / 1000 # km
|
| 68 |
+
}
|
| 69 |
+
except Exception as e:
|
| 70 |
+
print(f"Weather API error: {e}")
|
| 71 |
+
return None
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def get_weather_along_route(origin_coords: Tuple[float, float],
|
| 75 |
+
dest_coords: Tuple[float, float]) -> Dict:
|
| 76 |
+
"""
|
| 77 |
+
Get weather for origin and destination, calculate weather impact
|
| 78 |
+
"""
|
| 79 |
+
origin_weather = get_weather_data(origin_coords[0], origin_coords[1])
|
| 80 |
+
dest_weather = get_weather_data(dest_coords[0], dest_coords[1])
|
| 81 |
|
| 82 |
+
weather_factor = 1.0
|
| 83 |
+
warnings = []
|
| 84 |
+
|
| 85 |
+
if origin_weather:
|
| 86 |
+
if origin_weather["rain"] > 2.5:
|
| 87 |
+
weather_factor += 0.3
|
| 88 |
+
warnings.append(f"Heavy rain at origin ({origin_weather['rain']:.1f}mm/h)")
|
| 89 |
+
elif origin_weather["rain"] > 0.5:
|
| 90 |
+
weather_factor += 0.15
|
| 91 |
+
warnings.append(f"Light rain at origin ({origin_weather['rain']:.1f}mm/h)")
|
| 92 |
+
|
| 93 |
+
# Visibility impact
|
| 94 |
+
if origin_weather["visibility"] < 1:
|
| 95 |
+
weather_factor += 0.2
|
| 96 |
+
warnings.append(f"Low visibility at origin ({origin_weather['visibility']:.1f}km)")
|
| 97 |
+
|
| 98 |
+
# Wind impact
|
| 99 |
+
if origin_weather["wind_speed"] > 15:
|
| 100 |
+
weather_factor += 0.1
|
| 101 |
+
warnings.append(f"Strong winds at origin ({origin_weather['wind_speed']:.1f}m/s)")
|
| 102 |
+
|
| 103 |
+
if dest_weather:
|
| 104 |
+
if dest_weather["rain"] > 2.5:
|
| 105 |
+
weather_factor += 0.2
|
| 106 |
+
warnings.append(f"Heavy rain at destination ({dest_weather['rain']:.1f}mm/h)")
|
| 107 |
+
elif dest_weather["rain"] > 0.5:
|
| 108 |
+
weather_factor += 0.1
|
| 109 |
+
|
| 110 |
+
return {
|
| 111 |
+
"origin": origin_weather,
|
| 112 |
+
"destination": dest_weather,
|
| 113 |
+
"weather_factor": min(weather_factor, 1.8),
|
| 114 |
+
"warnings": warnings
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def geocode_address_nominatim(address: str) -> Optional[Tuple[float, float]]:
|
| 119 |
+
"""Geocoding using Nominatim (OpenStreetMap)"""
|
| 120 |
+
url = "https://nominatim.openstreetmap.org/search"
|
| 121 |
params = {
|
| 122 |
"q": address,
|
| 123 |
"format": "json",
|
| 124 |
"limit": 1
|
| 125 |
}
|
|
|
|
| 126 |
headers = {
|
| 127 |
"User-Agent": "DeliveryOptimizationSystem/1.0"
|
| 128 |
}
|
| 129 |
|
| 130 |
try:
|
| 131 |
time.sleep(1)
|
| 132 |
+
response = requests.get(url, params=params, headers=headers, timeout=30)
|
| 133 |
response.raise_for_status()
|
| 134 |
data = response.json()
|
| 135 |
|
|
|
|
| 143 |
|
| 144 |
def get_route_osrm(origin_coords: Tuple[float, float],
|
| 145 |
dest_coords: Tuple[float, float]) -> Optional[Dict]:
|
| 146 |
+
"""Routing using OSRM (OpenStreetMap Routing Machine)"""
|
|
|
|
|
|
|
| 147 |
lat1, lon1 = origin_coords
|
| 148 |
lat2, lon2 = dest_coords
|
| 149 |
|
| 150 |
url = f"http://router.project-osrm.org/route/v1/driving/{lon1},{lat1};{lon2},{lat2}"
|
|
|
|
| 151 |
params = {
|
| 152 |
"overview": "full",
|
| 153 |
"geometries": "geojson",
|
|
|
|
| 176 |
|
| 177 |
def get_alternative_routes_osrm(origin_coords: Tuple[float, float],
|
| 178 |
dest_coords: Tuple[float, float]) -> list:
|
| 179 |
+
"""Get multiple route options"""
|
|
|
|
|
|
|
| 180 |
lat1, lon1 = origin_coords
|
| 181 |
lat2, lon2 = dest_coords
|
| 182 |
|
| 183 |
url = f"http://router.project-osrm.org/route/v1/driving/{lon1},{lat1};{lon2},{lat2}"
|
|
|
|
| 184 |
params = {
|
| 185 |
"alternatives": "true",
|
| 186 |
"steps": "true",
|
|
|
|
| 203 |
except:
|
| 204 |
return []
|
| 205 |
|
| 206 |
+
|
| 207 |
def get_detailed_route_with_instructions(origin_coords: Tuple[float, float],
|
| 208 |
dest_coords: Tuple[float, float]) -> Optional[Dict]:
|
| 209 |
+
"""Get detailed route with turn-by-turn instructions and road names"""
|
|
|
|
|
|
|
| 210 |
lat1, lon1 = origin_coords
|
| 211 |
lat2, lon2 = dest_coords
|
| 212 |
|
| 213 |
url = f"http://router.project-osrm.org/route/v1/driving/{lon1},{lat1};{lon2},{lat2}"
|
|
|
|
| 214 |
params = {
|
| 215 |
"alternatives": "true",
|
| 216 |
"steps": "true",
|