File size: 4,467 Bytes
c9fbdc9
 
 
 
41fd171
 
c9fbdc9
 
 
740031c
41fd171
c9fbdc9
 
740031c
c9fbdc9
 
740031c
41fd171
 
c9fbdc9
740031c
c9fbdc9
 
 
 
41fd171
 
 
c9fbdc9
 
 
 
 
 
41fd171
 
c9fbdc9
 
41fd171
c9fbdc9
740031c
41fd171
 
 
 
c9fbdc9
41fd171
 
 
 
 
 
 
740031c
41fd171
 
740031c
 
 
 
 
 
 
 
41fd171
740031c
 
 
 
 
c9fbdc9
740031c
c9fbdc9
 
 
 
 
 
 
41fd171
 
c9fbdc9
 
740031c
41fd171
c9fbdc9
 
 
 
 
 
 
41fd171
c9fbdc9
 
 
 
 
 
41fd171
c9fbdc9
740031c
41fd171
740031c
 
 
41fd171
 
740031c
41fd171
 
740031c
41fd171
 
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
import streamlit as st
import requests
from geopy.geocoders import Nominatim
from dotenv import load_dotenv
import os
import feedparser

load_dotenv()

# Load API keys from environment variables
ORS_API_KEY = os.getenv("ORS_API_KEY")
OPENWEATHER_API_KEY = os.getenv("OPENWEATHER_API_KEY")

# Initialize geolocator
geolocator = Nominatim(user_agent="commute_planner")

# Streamlit UI
st.title("πŸš— Free Commute Planner")
st.markdown("Estimate travel time, check weather, AQI, and traffic-related news β€” no credit card needed!")

# Inputs
source = st.text_input("Enter your current location:")
destination = st.text_input("Enter your destination:")

if st.button("Plan My Commute") and source and destination:
    with st.spinner("Fetching route and environment info..."):

        def get_coords(location):
            try:
                loc = geolocator.geocode(location)
                return (loc.latitude, loc.longitude)
            except:
                return None

        src_coords = get_coords(source)
        dest_coords = get_coords(destination)

        if not src_coords or not dest_coords:
            st.error("Could not find coordinates. Please enter valid locations.")
        else:
            # βœ… Travel Time via OpenRouteService
            ors_url = "https://api.openrouteservice.org/v2/directions/driving-car"
            headers = {
                "Authorization": ORS_API_KEY,
                "Content-Type": "application/json"
            }
            data = {
                "coordinates": [
                    [src_coords[1], src_coords[0]],  # (lon, lat)
                    [dest_coords[1], dest_coords[0]]
                ]
            }
            response = requests.post(ors_url, json=data, headers=headers)

            if response.status_code == 200:
                result = response.json()
                try:
                    duration_sec = result['features'][0]['properties']['segments'][0]['duration']
                    duration_min = round(duration_sec / 60, 2)
                    st.success(f"πŸ•’ Estimated Travel Time: {duration_min} minutes")
                except (KeyError, IndexError):
                    st.error("Received a response but couldn't parse travel time.")
                    st.markdown("**Response from OpenRouteService:**")
                    st.json(result)
            else:
                st.error(f"OpenRouteService API error: {response.status_code}")
                try:
                    st.json(response.json())
                except:
                    st.write(response.text)

            # βœ… Weather from OpenWeatherMap
            weather_url = "https://api.openweathermap.org/data/2.5/weather"
            weather_params = {
                "lat": src_coords[0],
                "lon": src_coords[1],
                "appid": OPENWEATHER_API_KEY,
                "units": "metric"
            }
            weather = requests.get(weather_url, params=weather_params).json()
            temp = weather.get("main", {}).get("temp", "N/A")
            st.info(f"🌑️ Current Temperature: {temp}°C")

            # βœ… Air Quality Index from OpenWeatherMap
            aqi_url = "https://api.openweathermap.org/data/2.5/air_pollution"
            aqi_params = {
                "lat": src_coords[0],
                "lon": src_coords[1],
                "appid": OPENWEATHER_API_KEY
            }
            aqi_data = requests.get(aqi_url, params=aqi_params).json()
            aqi = aqi_data.get("list", [{}])[0].get("main", {}).get("aqi", "N/A")
            aqi_levels = {
                1: "Good",
                2: "Fair",
                3: "Moderate",
                4: "Poor",
                5: "Very Poor"
            }
            st.info(f"πŸŒ€ Air Quality Index: {aqi} - {aqi_levels.get(aqi, 'Unknown')}")

            # βœ… Traffic News via RSS Feed
            st.subheader("πŸ“° Traffic-Related News")
            rss_url = "https://www.rssmix.com/u/17853882/rss.xml"  # Replace with your preferred traffic-related feed
            feed = feedparser.parse(rss_url)

            count = 0
            for entry in feed.entries:
                if any(keyword in entry.title.lower() for keyword in ["traffic", "accident", "road", "construction"]):
                    st.markdown(f"[{entry.title}]({entry.link})")
                    count += 1

            if count == 0:
                st.write("No recent traffic-related updates found.")