File size: 9,870 Bytes
be1ef0b
8e0e1d8
ac8b7e4
be1ef0b
 
 
8e0e1d8
 
 
 
 
c66c8d9
8e0e1d8
ac8b7e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c66c8d9
 
8e0e1d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c66c8d9
 
be1ef0b
c66c8d9
 
be1ef0b
c66c8d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be1ef0b
c66c8d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be1ef0b
 
 
 
 
 
 
 
 
 
 
c66c8d9
be1ef0b
 
 
 
 
 
 
 
 
 
 
 
 
c66c8d9
be1ef0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c66c8d9
be1ef0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c66c8d9
be1ef0b
 
c66c8d9
be1ef0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac8b7e4
 
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
from typing import Dict, Tuple, Optional
from dotenv import load_dotenv
import pandas as pd
import requests
import json
import time
import os

load_dotenv()

TOMTOM_API_KEY = os.getenv("TOMTOM_API_KEY")
OPENWEATHER_API_KEY = os.getenv("OPENWEATHER_API_KEY")



def get_historical_weather(lat: float, lon: float, start_date: str, end_date: str):
    """Fetch hourly historical weather directly from Open-Meteo API (no SDK)."""
    url = "https://archive-api.open-meteo.com/v1/archive"
    params = {
        "latitude": lat,
        "longitude": lon,
        "start_date": start_date,
        "end_date": end_date,
        "hourly": "temperature_2m,relative_humidity_2m,rain,snowfall,wind_speed_10m",
        "timezone": "auto"
    }
    try:
        response = requests.get(url, params=params, timeout=10)
        response.raise_for_status()
        data = response.json()

        hourly = data.get("hourly", {})
        df = pd.DataFrame({
            "time": hourly.get("time", []),
            "temperature": hourly.get("temperature_2m", []),
            "humidity": hourly.get("relative_humidity_2m", []),
            "rain": hourly.get("rain", []),
            "snow": hourly.get("snowfall", []),
            "wind_speed": hourly.get("wind_speed_10m", []),
        })

        df["time"] = pd.to_datetime(df["time"])
        return df

    except Exception as e:
        print(f"Historical weather error: {e}")
        return None


def get_realtime_traffic(origin_coords: Tuple[float, float], dest_coords: Tuple[float, float]) -> Optional[Dict]:
    """Get real-time traffic using TomTom API"""
    base_url = "https://api.tomtom.com/routing/1/calculateRoute"
    origin = f"{origin_coords[0]},{origin_coords[1]}"
    destination = f"{dest_coords[0]},{dest_coords[1]}"
    url = f"{base_url}/{origin}:{destination}/json"
    
    headers = {"Accept": "application/json"}
    params = {
        "key": TOMTOM_API_KEY,
        "traffic": "true",
        "computeTravelTimeFor": "all",
        "routeType": "fastest",
    }

    try:
        response = requests.get(url, headers=headers, params=params, timeout=10)
        response.raise_for_status()
        data = response.json()
        return data["routes"][0]["summary"]
    except Exception as e:
        print(f"Error fetching traffic data: {e}")
        return None


def get_weather_data(lat: float, lon: float) -> Optional[Dict]:
    """
    Get weather data using OpenWeatherMap API
    Returns: temperature, condition, precipitation, wind speed
    """
    if not OPENWEATHER_API_KEY:
        return None
    
    url = "https://api.openweathermap.org/data/2.5/weather"
    params = {
        "lat": lat,
        "lon": lon,
        "appid": OPENWEATHER_API_KEY,
        "units": "metric"
    }
    
    try:
        response = requests.get(url, params=params, timeout=10)
        response.raise_for_status()
        data = response.json()
        
        return {
            "temperature": data["main"]["temp"],
            "feels_like": data["main"]["feels_like"],
            "condition": data["weather"][0]["main"],
            "description": data["weather"][0]["description"],
            "humidity": data["main"]["humidity"],
            "wind_speed": data["wind"]["speed"],
            "rain": data.get("rain", {}).get("1h", 0),
            "visibility": data.get("visibility", 10000) / 1000  # km
        }
    except Exception as e:
        print(f"Weather API error: {e}")
        return None


def get_weather_along_route(origin_coords: Tuple[float, float], 
                            dest_coords: Tuple[float, float]) -> Dict:
    """
    Get weather for origin and destination, calculate weather impact
    """
    origin_weather = get_weather_data(origin_coords[0], origin_coords[1])
    dest_weather = get_weather_data(dest_coords[0], dest_coords[1])
    
    weather_factor = 1.0
    warnings = []
    
    if origin_weather:
        if origin_weather["rain"] > 2.5:
            weather_factor += 0.3
            warnings.append(f"Heavy rain at origin ({origin_weather['rain']:.1f}mm/h)")
        elif origin_weather["rain"] > 0.5:
            weather_factor += 0.15
            warnings.append(f"Light rain at origin ({origin_weather['rain']:.1f}mm/h)")
        
        # Visibility impact
        if origin_weather["visibility"] < 1:
            weather_factor += 0.2
            warnings.append(f"Low visibility at origin ({origin_weather['visibility']:.1f}km)")
        
        # Wind impact
        if origin_weather["wind_speed"] > 15:
            weather_factor += 0.1
            warnings.append(f"Strong winds at origin ({origin_weather['wind_speed']:.1f}m/s)")
    
    if dest_weather:
        if dest_weather["rain"] > 2.5:
            weather_factor += 0.2
            warnings.append(f"Heavy rain at destination ({dest_weather['rain']:.1f}mm/h)")
        elif dest_weather["rain"] > 0.5:
            weather_factor += 0.1
    
    return {
        "origin": origin_weather,
        "destination": dest_weather,
        "weather_factor": min(weather_factor, 1.8),
        "warnings": warnings
    }


def geocode_address_nominatim(address: str) -> Optional[Tuple[float, float]]:
    """Geocoding using Nominatim (OpenStreetMap)"""
    url = "https://nominatim.openstreetmap.org/search"
    params = {
        "q": address,
        "format": "json",
        "limit": 1
    }
    headers = {
        "User-Agent": "DeliveryOptimizationSystem/1.0" 
    }
    
    try:
        time.sleep(1)  
        response = requests.get(url, params=params, headers=headers, timeout=30)
        response.raise_for_status()
        data = response.json()
        
        if data:
            return (float(data[0]["lat"]), float(data[0]["lon"]))
        return None
    except Exception as e:
        print(f"Geocoding error: {e}")
        return None


def get_route_osrm(origin_coords: Tuple[float, float], 
                   dest_coords: Tuple[float, float]) -> Optional[Dict]:
    """Routing using OSRM (OpenStreetMap Routing Machine)"""
    lat1, lon1 = origin_coords
    lat2, lon2 = dest_coords
    
    url = f"http://router.project-osrm.org/route/v1/driving/{lon1},{lat1};{lon2},{lat2}"
    params = {
        "overview": "full",
        "geometries": "geojson",
        "steps": "true",
        "annotations": "true"
    }
    
    try:
        response = requests.get(url, params=params, timeout=15)
        response.raise_for_status()
        data = response.json()
        
        if data.get("code") == "Ok" and data.get("routes"):
            route = data["routes"][0]
            return {
                "distance_km": route["distance"] / 1000,
                "duration_min": route["duration"] / 60,
                "geometry": route["geometry"],
                "steps": route["legs"][0].get("steps", [])
            }
        return None
    except Exception as e:
        print(f"Routing error: {e}")
        return None


def get_alternative_routes_osrm(origin_coords: Tuple[float, float], 
                                dest_coords: Tuple[float, float]) -> list:
    """Get multiple route options"""
    lat1, lon1 = origin_coords
    lat2, lon2 = dest_coords
    
    url = f"http://router.project-osrm.org/route/v1/driving/{lon1},{lat1};{lon2},{lat2}"
    params = {
        "alternatives": "true", 
        "steps": "true",
        "overview": "full"
    }
    
    try:
        response = requests.get(url, params=params, timeout=15)
        data = response.json()
        
        if data.get("code") == "Ok":
            routes = []
            for route in data.get("routes", []):
                routes.append({
                    "distance_km": route["distance"] / 1000,
                    "duration_min": route["duration"] / 60
                })
            return routes
        return []
    except:
        return []


def get_detailed_route_with_instructions(origin_coords: Tuple[float, float], 
                                         dest_coords: Tuple[float, float]) -> Optional[Dict]:
    """Get detailed route with turn-by-turn instructions and road names"""
    lat1, lon1 = origin_coords
    lat2, lon2 = dest_coords
    
    url = f"http://router.project-osrm.org/route/v1/driving/{lon1},{lat1};{lon2},{lat2}"
    params = {
        "alternatives": "true",
        "steps": "true",
        "overview": "full",
        "geometries": "geojson",
        "annotations": "true"
    }
    
    try:
        response = requests.get(url, params=params, timeout=15)
        response.raise_for_status()
        data = response.json()
        
        if data.get("code") == "Ok" and data.get("routes"):
            all_routes = []
            
            for route_idx, route in enumerate(data.get("routes", [])):
                route_info = {
                    "route_number": route_idx + 1,
                    "distance_km": route["distance"] / 1000,
                    "duration_min": route["duration"] / 60,
                    "instructions": []
                }
                
                for leg in route.get("legs", []):
                    for step in leg.get("steps", []):
                        instruction = {
                            "distance_km": step["distance"] / 1000,
                            "duration_min": step["duration"] / 60,
                            "instruction": step.get("maneuver", {}).get("type", "continue"),
                            "road_name": step.get("name", "Unnamed road"),
                            "direction": step.get("maneuver", {}).get("modifier", "")
                        }
                        route_info["instructions"].append(instruction)
                
                all_routes.append(route_info)
            
            return all_routes
        return None
    except Exception as e:
        print(f"Detailed routing error: {e}")
        return None