File size: 4,424 Bytes
70519cd
 
 
 
b2f77ec
70519cd
17d4587
 
 
70519cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
851ec11
70519cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2f77ec
70519cd
 
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
import os
import requests
from dotenv import load_dotenv
import re
import streamlit as st
import pandas as pd
#from st_aggrid import AgGrid, GridOptionsBuilder
#from streamlit_echarts import st_echarts
#from streamlit_chat import message

#absolute path to the folder
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

# Load API key from .env file
load_dotenv(dotenv_path=r"C:/Users/som/Desktop/Sharm/Study/Colleges/Duke/STudy/PYTHON/Assignments/my-local-repo/Week5/D2/Assignment/.gitignore/.env")
API_KEY = os.getenv("OPENWEATHER_API_KEY")
if not API_KEY:
    st.error("❌ API Key not found! Make sure it's set in your .env file.")
    st.stop()

def get_weather(city):
    # 1. Create the API endpoint URL
    base_url = "https://api.openweathermap.org/data/2.5/weather"

    # 2. Set query parameters
    params = {
        "q": city,
        "appid": API_KEY,
        "units": "metric"           # temperature in Celsius
    }

    # 3. Make the request
    response = requests.get(base_url, params=params)
    
    if response.status_code == 200:     #checks whether API call was successful(200 is the standard code for "OK").
        # 4. Parse JSON
        data = response.json()

        # 5. Extract key info
        temp = data['main']['temp']
        humidity = data['main']['humidity']
        description = data['weather'][0]['description']
        desc_lower = description.lower()
        # Advice suggestion logic
        if temp <= 10:
            img_file = os.path.join(BASE_DIR, "images", "chill.jpg")
            advice = "πŸ§₯ It's chilly β€” wear a jacket."
        elif 10 < temp <= 20:
            if "rain" in desc_lower:
                img_file = os.path.join(BASE_DIR, "images", "shower.jpg")
                advice = "🌧️ Showers expected β€” carry an umbrella."
            else:
                img_file = os.path.join(BASE_DIR, "images", "sun.jpg")
                advice = "🧒 Mild day β€” a hat might be nice."
        else:  # temp > 20
            if "rain" in desc_lower:
                img_file = os.path.join(BASE_DIR, "images", "RAIN.jpg")
                advice = "β˜” Warm but rainy β€” take an umbrella."
            else:
                img_file = os.path.join(BASE_DIR, "images", "cloudy.jpg")
                advice = "😎 Warm and clear β€” enjoy the day!"
        
        # display image in col1, weather info in col2
        col1, col2 = st.columns([1, 2])
        with col1:
            st.image(img_file, use_container_width=True)

        with col2:

        #Highlight keywords using regex and ANSI bold
            st.markdown(f"""
            ### πŸ“ Weather in **{city.capitalize()}**
            - 🌑️ **Temperature:** {temp} °C  
            - πŸ’§ **Humidity:** {humidity}%  
            - πŸ“ **Description:** {description.capitalize()}  
            - πŸ”” **Suggestion:** {advice}
            """)
    else:
        st.error("❌ Could not retrieve weather data. Please check the city name.")


def main():
# 1. Title and description
    st.title(" 🌍 Weather Information App")
    st.markdown("---")
    st.write("Fetch and Display the current weather for any city in the world. ")

    with st.expander("ℹ️ About this app"):
        st.write("The app uses the [OpenWeatherMap API](https://openweathermap.org/api) and gives practical suggestions based on the weather and temperature (e.g., bring a jacket or umbrella).")
    st.markdown("---")
    #st.image("images/weather.jpg", use_container_width=True)
    st.markdown("---")
    with st.container():
        st.subheader("UserName")
        # Text input tied to session state key "username"
        name = st.text_input("Enter your name", key="username")

# Use the stored value elsewhere
    if name:
        
            st.success(f"πŸ‘‹ Hello, {st.session_state.username}!")
            st.markdown("---")
            st.title(" Stay informed about the weather 🌦️ ")
            st.write("*" *80)
            
            city = st.text_input("Enter the name of the city:")
            city = re.sub(r"[^a-zA-Z\s]", "", city).strip()

            if st.button("Get Weather"):
                if city:
                    get_weather(city)
                            #with st.spinner("Fetching weather..."):
            
                else:
                    st.error("❌ Please enter a city name before fetching weather.")


if __name__ == "__main__":
    main()