SharmilNK commited on
Commit
70519cd
Β·
1 Parent(s): 95b07de

Add source files

Browse files
src/images/RAIN.jpg ADDED
src/images/chill.jpg ADDED
src/images/cloudy.jpg ADDED
src/images/shower.jpg ADDED
src/images/sun.jpg ADDED
src/images/weather.jpg ADDED
src/streamlit_app.py CHANGED
@@ -1,40 +1,119 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
 
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
1
+ import os
2
+ import requests
3
+ from dotenv import load_dotenv
4
+ import re
5
  import streamlit as st
6
+ import pandas as pd
7
+ from st_aggrid import AgGrid, GridOptionsBuilder
8
+ from streamlit_echarts import st_echarts
9
+ from streamlit_chat import message
10
+
11
+ #absolute path to the folder
12
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
13
+
14
+ # Load API key from .env file
15
+ load_dotenv(dotenv_path=r"C:/Users/som/Desktop/Sharm/Study/Colleges/Duke/STudy/PYTHON/Assignments/my-local-repo/Week5/D2/Assignment/.gitignore/.env")
16
+ API_KEY = os.getenv("OPENWEATHER_API_KEY")
17
+ if not API_KEY:
18
+ st.error("❌ API Key not found! Make sure it's set in your .env file.")
19
+ st.stop()
20
+
21
+ def get_weather(city):
22
+ # 1. Create the API endpoint URL
23
+ base_url = "https://api.openweathermap.org/data/2.5/weather"
24
+
25
+ # 2. Set query parameters
26
+ params = {
27
+ "q": city,
28
+ "appid": API_KEY,
29
+ "units": "metric" # temperature in Celsius
30
+ }
31
+
32
+ # 3. Make the request
33
+ response = requests.get(base_url, params=params)
34
+
35
+ if response.status_code == 200: #checks whether API call was successful(200 is the standard code for "OK").
36
+ # 4. Parse JSON
37
+ data = response.json()
38
+
39
+ # 5. Extract key info
40
+ temp = data['main']['temp']
41
+ humidity = data['main']['humidity']
42
+ description = data['weather'][0]['description']
43
+ desc_lower = description.lower()
44
+ # Advice suggestion logic
45
+ if temp <= 10:
46
+ img_file = os.path.join(BASE_DIR, "images", "chill.jpg")
47
+ advice = "πŸ§₯ It's chilly β€” wear a jacket."
48
+ elif 10 < temp <= 20:
49
+ if "rain" in desc_lower:
50
+ img_file = os.path.join(BASE_DIR, "images", "shower.jpg")
51
+ advice = "🌧️ Showers expected β€” carry an umbrella."
52
+ else:
53
+ img_file = os.path.join(BASE_DIR, "images", "sun.jpg")
54
+ advice = "🧒 Mild day β€” a hat might be nice."
55
+ else: # temp > 20
56
+ if "rain" in desc_lower:
57
+ img_file = os.path.join(BASE_DIR, "images", "RAIN.jpg")
58
+ advice = "β˜” Warm but rainy β€” take an umbrella."
59
+ else:
60
+ img_file = os.path.join(BASE_DIR, "images", "cloudy.jpg")
61
+ advice = "😎 Warm and clear β€” enjoy the day!"
62
+
63
+ # display image in col1, weather info in col2
64
+ col1, col2 = st.columns([1, 2])
65
+ with col1:
66
+ st.image(img_file, use_container_width=True)
67
+
68
+ with col2:
69
+
70
+ #Highlight keywords using regex and ANSI bold
71
+ st.markdown(f"""
72
+ ### πŸ“ Weather in **{city.capitalize()}**
73
+ - 🌑️ **Temperature:** {temp} °C
74
+ - πŸ’§ **Humidity:** {humidity}%
75
+ - πŸ“ **Description:** {description.capitalize()}
76
+ - πŸ”” **Suggestion:** {advice}
77
+ """)
78
+ else:
79
+ st.error("❌ Could not retrieve weather data. Please check the city name.")
80
+
81
+
82
+ def main():
83
+ # 1. Title and description
84
+ st.title(" 🌍 Weather Information App")
85
+ st.markdown("---")
86
+ st.write("Fetch and Display the current weather for any city in the world. ")
87
+
88
+ with st.expander("ℹ️ About this app"):
89
+ 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).")
90
+ st.markdown("---")
91
+ st.image("images/weather.jpg", use_container_width=True)
92
+ st.markdown("---")
93
+ with st.container():
94
+ st.subheader("UserName")
95
+ # Text input tied to session state key "username"
96
+ name = st.text_input("Enter your name", key="username")
97
+
98
+ # Use the stored value elsewhere
99
+ if name:
100
+
101
+ st.success(f"πŸ‘‹ Hello, {st.session_state.username}!")
102
+ st.markdown("---")
103
+ st.title(" Stay informed about the weather 🌦️ ")
104
+ st.write("*" *80)
105
+
106
+ city = st.text_input("Enter the name of the city:")
107
+ city = re.sub(r"[^a-zA-Z\s]", "", city).strip()
108
+
109
+ if st.button("Get Weather"):
110
+ if city:
111
+ get_weather(city)
112
+ #with st.spinner("Fetching weather..."):
113
+
114
+ else:
115
+ st.error("❌ Please enter a city name before fetching weather.")
116
+
117
 
118
+ if __name__ == "__main__":
119
+ main()