Danial7 commited on
Commit
41fd171
·
verified ·
1 Parent(s): 696b731

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -48
app.py CHANGED
@@ -1,54 +1,61 @@
1
  import streamlit as st
2
  import requests
3
  from geopy.geocoders import Nominatim
4
- import os
5
  from dotenv import load_dotenv
 
 
6
 
7
  load_dotenv()
8
 
9
- # API keys
10
- GOOGLE_MAPS_API_KEY = os.getenv("GOOGLE_MAPS_API_KEY")
11
  OPENWEATHER_API_KEY = os.getenv("OPENWEATHER_API_KEY")
12
- NEWS_API_KEY = os.getenv("NEWS_API_KEY")
13
 
14
  geolocator = Nominatim(user_agent="commute_planner")
15
 
16
- st.title("🚗 Commute Planner with Live Weather, AQI & Traffic Updates")
 
17
 
18
  source = st.text_input("Enter your current location:")
19
  destination = st.text_input("Enter your destination:")
20
 
21
  if st.button("Plan My Commute") and source and destination:
22
- with st.spinner("Getting route info..."):
23
- def get_coordinates(location):
 
24
  try:
25
  loc = geolocator.geocode(location)
26
  return (loc.latitude, loc.longitude)
27
  except:
28
  return None
29
 
30
- src_coords = get_coordinates(source)
31
- dest_coords = get_coordinates(destination)
32
 
33
  if not src_coords or not dest_coords:
34
- st.error("Could not get coordinates. Please check the location.")
35
  else:
36
- # 1. Estimated travel time using Google Maps Directions API
37
- directions_url = "https://maps.googleapis.com/maps/api/directions/json"
38
- directions_params = {
39
- "origin": source,
40
- "destination": destination,
41
- "key": GOOGLE_MAPS_API_KEY,
42
  }
43
- route = requests.get(directions_url, params=directions_params).json()
44
-
45
- try:
46
- duration = route["routes"][0]["legs"][0]["duration"]["text"]
47
- st.success(f"Estimated Commute Time: {duration}")
48
- except:
49
- st.warning("Could not retrieve travel time.")
 
 
 
 
 
 
 
50
 
51
- # 2. Weather and AQI using OpenWeatherMap
52
  weather_url = "https://api.openweathermap.org/data/2.5/weather"
53
  weather_params = {
54
  "lat": src_coords[0],
@@ -56,12 +63,12 @@ if st.button("Plan My Commute") and source and destination:
56
  "appid": OPENWEATHER_API_KEY,
57
  "units": "metric"
58
  }
59
- weather_data = requests.get(weather_url, params=weather_params).json()
60
- temp = weather_data.get("main", {}).get("temp", "N/A")
61
  st.info(f"🌡️ Current Temperature: {temp}°C")
62
 
63
- # AQI
64
- aqi_url = "http://api.openweathermap.org/data/2.5/air_pollution"
65
  aqi_params = {
66
  "lat": src_coords[0],
67
  "lon": src_coords[1],
@@ -69,30 +76,23 @@ if st.button("Plan My Commute") and source and destination:
69
  }
70
  aqi_data = requests.get(aqi_url, params=aqi_params).json()
71
  aqi = aqi_data.get("list", [{}])[0].get("main", {}).get("aqi", "N/A")
72
- aqi_status = {
73
  1: "Good",
74
  2: "Fair",
75
  3: "Moderate",
76
  4: "Poor",
77
  5: "Very Poor"
78
  }
79
- st.info(f"🌀 Air Quality Index: {aqi} - {aqi_status.get(aqi, 'Unknown')}")
80
 
81
- # 3. News or traffic updates (using NewsAPI)
82
- st.subheader("��� Related Traffic News")
83
- news_url = "https://newsapi.org/v2/everything"
84
- query = f"{source} {destination} traffic OR accident OR construction"
85
- news_params = {
86
- "q": query,
87
- "apiKey": NEWS_API_KEY,
88
- "sortBy": "publishedAt",
89
- "language": "en",
90
- "pageSize": 5,
91
- }
92
- news_data = requests.get(news_url, params=news_params).json()
93
- articles = news_data.get("articles", [])
94
- if articles:
95
- for article in articles:
96
- st.markdown(f"[{article['title']}]({article['url']})")
97
- else:
98
- st.write("No recent traffic-related news found for your route.")
 
1
  import streamlit as st
2
  import requests
3
  from geopy.geocoders import Nominatim
 
4
  from dotenv import load_dotenv
5
+ import os
6
+ import feedparser
7
 
8
  load_dotenv()
9
 
10
+ ORS_API_KEY = os.getenv("ORS_API_KEY")
 
11
  OPENWEATHER_API_KEY = os.getenv("OPENWEATHER_API_KEY")
 
12
 
13
  geolocator = Nominatim(user_agent="commute_planner")
14
 
15
+ st.title("🚗 Free Commute Planner")
16
+ st.markdown("Estimate travel time, check weather, AQI, and traffic-related news — no credit card needed!")
17
 
18
  source = st.text_input("Enter your current location:")
19
  destination = st.text_input("Enter your destination:")
20
 
21
  if st.button("Plan My Commute") and source and destination:
22
+ with st.spinner("Fetching route and environment info..."):
23
+
24
+ def get_coords(location):
25
  try:
26
  loc = geolocator.geocode(location)
27
  return (loc.latitude, loc.longitude)
28
  except:
29
  return None
30
 
31
+ src_coords = get_coords(source)
32
+ dest_coords = get_coords(destination)
33
 
34
  if not src_coords or not dest_coords:
35
+ st.error("Could not find coordinates. Please enter valid locations.")
36
  else:
37
+ # OpenRouteService: Travel Time
38
+ ors_url = "https://api.openrouteservice.org/v2/directions/driving-car"
39
+ headers = {
40
+ "Authorization": ORS_API_KEY,
41
+ "Content-Type": "application/json"
 
42
  }
43
+ data = {
44
+ "coordinates": [
45
+ [src_coords[1], src_coords[0]], # (lon, lat)
46
+ [dest_coords[1], dest_coords[0]]
47
+ ]
48
+ }
49
+ response = requests.post(ors_url, json=data, headers=headers)
50
+ if response.status_code == 200:
51
+ result = response.json()
52
+ duration_sec = result['features'][0]['properties']['segments'][0]['duration']
53
+ duration_min = round(duration_sec / 60, 2)
54
+ st.success(f"🕒 Estimated Travel Time: {duration_min} minutes")
55
+ else:
56
+ st.warning("Could not retrieve travel time. Please check your API key and inputs.")
57
 
58
+ # OpenWeatherMap: Temperature
59
  weather_url = "https://api.openweathermap.org/data/2.5/weather"
60
  weather_params = {
61
  "lat": src_coords[0],
 
63
  "appid": OPENWEATHER_API_KEY,
64
  "units": "metric"
65
  }
66
+ weather = requests.get(weather_url, params=weather_params).json()
67
+ temp = weather.get("main", {}).get("temp", "N/A")
68
  st.info(f"🌡️ Current Temperature: {temp}°C")
69
 
70
+ # OpenWeatherMap: AQI
71
+ aqi_url = "https://api.openweathermap.org/data/2.5/air_pollution"
72
  aqi_params = {
73
  "lat": src_coords[0],
74
  "lon": src_coords[1],
 
76
  }
77
  aqi_data = requests.get(aqi_url, params=aqi_params).json()
78
  aqi = aqi_data.get("list", [{}])[0].get("main", {}).get("aqi", "N/A")
79
+ aqi_levels = {
80
  1: "Good",
81
  2: "Fair",
82
  3: "Moderate",
83
  4: "Poor",
84
  5: "Very Poor"
85
  }
86
+ st.info(f"🌀 Air Quality Index: {aqi} - {aqi_levels.get(aqi, 'Unknown')}")
87
 
88
+ # Traffic News using RSS
89
+ st.subheader("📰 Traffic-Related News")
90
+ feed_url = "https://www.rssmix.com/u/17853882/rss.xml" # Replace with a real local traffic feed or use another from your city
91
+ feed = feedparser.parse(feed_url)
92
+ count = 0
93
+ for entry in feed.entries:
94
+ if "traffic" in entry.title.lower() or "accident" in entry.title.lower() or "road" in entry.title.lower():
95
+ st.markdown(f"[{entry.title}]({entry.link})")
96
+ count += 1
97
+ if count == 0:
98
+ st.write("No recent traffic-related updates found.")