Danial7 commited on
Commit
f9e9c2e
·
verified ·
1 Parent(s): 5fc964b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -37
app.py CHANGED
@@ -1,59 +1,102 @@
1
  import streamlit as st
2
  import openrouteservice
3
  from openrouteservice import convert
 
 
4
  import folium
5
  from streamlit_folium import st_folium
 
6
 
7
- # Load API key from Streamlit secrets
8
- ORS_API_KEY = st.secrets["ORS_API_KEY"]
 
 
 
 
 
 
9
 
10
- # Initialize ORS client
11
  client = openrouteservice.Client(key=ORS_API_KEY)
 
12
 
13
- # Supported transport modes
14
- MODES = {
15
  "Driving": "driving-car",
16
  "Walking": "foot-walking",
17
- "Cycling": "cycling-regular"
 
18
  }
19
 
20
- # App title
21
- st.set_page_config(page_title="Commute Planner", layout="centered")
22
- st.title("🚗 Commute Planner")
 
 
23
 
24
- # Input fields
25
- start_location = st.text_input("Start location (address or place name):")
26
- end_location = st.text_input("Destination (address or place name):")
27
- mode = st.selectbox("Transportation mode", list(MODES.keys()))
 
 
 
28
 
29
- # Process user input
30
- if st.button("Get Route") and start_location and end_location:
31
- try:
32
- # Geocode start and end addresses
33
- geocode_start = client.pelias_search(start_location)
34
- start_coords = geocode_start["features"][0]["geometry"]["coordinates"]
 
 
 
 
 
 
 
 
 
35
 
36
- geocode_end = client.pelias_search(end_location)
37
- end_coords = geocode_end["features"][0]["geometry"]["coordinates"]
 
 
 
 
 
38
 
39
- coords = (start_coords, end_coords)
 
40
 
41
- # Get route info
42
- route = client.directions(coords, profile=MODES[mode], format="geojson")
43
- properties = route["features"][0]["properties"]["summary"]
44
- distance_km = properties["distance"] / 1000
45
- duration_min = properties["duration"] / 60
46
 
47
- st.success(f"🛣️ Distance: {distance_km:.2f} km | ⏱️ Duration: {duration_min:.1f} minutes")
 
 
 
 
 
 
48
 
49
- # Map
50
- m = folium.Map(location=[start_coords[1], start_coords[0]], zoom_start=13)
51
- folium.Marker([start_coords[1], start_coords[0]], popup="Start", icon=folium.Icon(color='green')).add_to(m)
52
- folium.Marker([end_coords[1], end_coords[0]], popup="End", icon=folium.Icon(color='red')).add_to(m)
53
- folium.GeoJson(route, name="Route").add_to(m)
 
 
 
54
 
55
- st.subheader("📍 Route Map")
56
- st_folium(m, width=700, height=500)
 
57
 
58
- except Exception as e:
59
- st.error(f"Error fetching route: {e}")
 
 
 
 
1
  import streamlit as st
2
  import openrouteservice
3
  from openrouteservice import convert
4
+ import requests
5
+ from geopy.geocoders import Nominatim
6
  import folium
7
  from streamlit_folium import st_folium
8
+ import os
9
 
10
+ # Title
11
+ st.set_page_config(page_title="Commute Planner", layout="centered")
12
+ st.title("🚗 Commute Planner")
13
+ st.markdown("Estimate your travel time, view the route map, current weather, and air quality index.")
14
+
15
+ # API keys (use st.secrets if deploying)
16
+ ORS_API_KEY = os.getenv("ORS_API_KEY", st.secrets.get("ORS_API_KEY", ""))
17
+ OWM_API_KEY = os.getenv("OWM_API_KEY", st.secrets.get("OWM_API_KEY", ""))
18
 
19
+ # Initialize OpenRouteService client
20
  client = openrouteservice.Client(key=ORS_API_KEY)
21
+ geolocator = Nominatim(user_agent="commute_planner")
22
 
23
+ # Transport mode options
24
+ transport_modes = {
25
  "Driving": "driving-car",
26
  "Walking": "foot-walking",
27
+ "Cycling": "cycling-regular",
28
+ "Transit (experimental)": "driving-hgv"
29
  }
30
 
31
+ # Sidebar Inputs
32
+ start_location = st.text_input("Enter Start Location", key="start")
33
+ end_location = st.text_input("Enter Destination", key="end")
34
+ mode = st.selectbox("Select Transportation Mode", list(transport_modes.keys()), key="mode")
35
+ submit = st.button("Get Route")
36
 
37
+ # Only run route logic if submit was clicked
38
+ if submit or st.session_state.get("show_results"):
39
+ if submit:
40
+ try:
41
+ # Geocode locations
42
+ start_coords = geolocator.geocode(start_location)
43
+ end_coords = geolocator.geocode(end_location)
44
 
45
+ if not start_coords or not end_coords:
46
+ st.error("Could not geocode one of the locations.")
47
+ else:
48
+ start_point = [start_coords.longitude, start_coords.latitude]
49
+ end_point = [end_coords.longitude, end_coords.latitude]
50
+
51
+ # Fetch route
52
+ route = client.directions(
53
+ coordinates=[start_point, end_point],
54
+ profile=transport_modes[mode],
55
+ format="geojson"
56
+ )
57
+
58
+ distance_km = route['features'][0]['properties']['segments'][0]['distance'] / 1000
59
+ duration_min = route['features'][0]['properties']['segments'][0]['duration'] / 60
60
 
61
+ # Save to session state
62
+ st.session_state["show_results"] = True
63
+ st.session_state["distance_km"] = distance_km
64
+ st.session_state["duration_min"] = duration_min
65
+ st.session_state["start_coords"] = [start_coords.latitude, start_coords.longitude]
66
+ st.session_state["end_coords"] = [end_coords.latitude, end_coords.longitude]
67
+ st.session_state["route"] = route
68
 
69
+ except Exception as e:
70
+ st.error(f"Error: {e}")
71
 
72
+ # Display results if they exist
73
+ if st.session_state.get("show_results"):
74
+ st.success(f"**Distance:** {st.session_state['distance_km']:.2f} km")
75
+ st.success(f"**Estimated Duration:** {st.session_state['duration_min']:.1f} minutes")
 
76
 
77
+ # Draw map
78
+ route = st.session_state["route"]
79
+ m = folium.Map(location=st.session_state["start_coords"], zoom_start=13)
80
+ folium.Marker(st.session_state["start_coords"], tooltip="Start", icon=folium.Icon(color='green')).add_to(m)
81
+ folium.Marker(st.session_state["end_coords"], tooltip="End", icon=folium.Icon(color='red')).add_to(m)
82
+ folium.GeoJson(route, name="Route").add_to(m)
83
+ st_folium(m, width=700, height=500)
84
 
85
+ # Get weather and AQI
86
+ lat, lon = st.session_state["start_coords"]
87
+ weather_url = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={OWM_API_KEY}&units=metric"
88
+ air_url = f"http://api.openweathermap.org/data/2.5/air_pollution?lat={lat}&lon={lon}&appid={OWM_API_KEY}"
89
+
90
+ try:
91
+ weather = requests.get(weather_url).json()
92
+ air = requests.get(air_url).json()
93
 
94
+ temp = weather['main']['temp']
95
+ condition = weather['weather'][0]['description'].capitalize()
96
+ aqi = air['list'][0]['main']['aqi']
97
 
98
+ st.info(f"**Current Temperature:** {temp}°C")
99
+ st.info(f"**Weather Condition:** {condition}")
100
+ st.info(f"**Air Quality Index (AQI):** {aqi} (1=Good, 5=Very Poor)")
101
+ except:
102
+ st.warning("Could not fetch weather or air quality data.")