MogulojuSai commited on
Commit
23b96bf
·
verified ·
1 Parent(s): 8196298

initial commit

Browse files
Files changed (2) hide show
  1. requirements.txt +5 -0
  2. weather_app.py +216 -0
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ python-dotenv
2
+ pandas
3
+ requests
4
+ streamlit
5
+ Pillow
weather_app.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ from datetime import datetime, timedelta
4
+ import pandas as pd
5
+ from dotenv import load_dotenv
6
+ import os
7
+ from PIL import Image
8
+ from io import BytesIO
9
+
10
+ # Load environment variables
11
+ load_dotenv()
12
+ API_KEY = os.getenv('WEATHER_API_KEY')
13
+ BASE_URL = "http://api.weatherapi.com/v1"
14
+
15
+ # Configure the app
16
+ st.set_page_config(
17
+ page_title="Weather Dashboard",
18
+ page_icon="🌤️",
19
+ layout="wide"
20
+ )
21
+
22
+ # Custom CSS
23
+ st.markdown("""
24
+ <style>
25
+ .weather-icon {
26
+ width: 64px;
27
+ height: 64px;
28
+ margin: 10px auto;
29
+ }
30
+ .stMetric {
31
+ background-color: rgba(255, 255, 255, 0.1);
32
+ padding: 10px;
33
+ border-radius: 5px;
34
+ }
35
+ .main-header {
36
+ text-align: center;
37
+ color: #1E88E5;
38
+ padding: 20px;
39
+ }
40
+ </style>
41
+ """, unsafe_allow_html=True)
42
+
43
+ def load_weather_icon(icon_url):
44
+ """Load and display weather icon from URL"""
45
+ try:
46
+ response = requests.get(icon_url)
47
+ img = Image.open(BytesIO(response.content))
48
+ return img
49
+ except Exception as e:
50
+ st.warning(f"Could not load weather icon: {e}")
51
+ return None
52
+
53
+ def get_weather_data(location, is_historical=False, date=None):
54
+ """Fetch weather data from the API"""
55
+ try:
56
+ if is_historical:
57
+ endpoint = f"{BASE_URL}/history.json"
58
+ params = {
59
+ 'key': API_KEY,
60
+ 'q': location,
61
+ 'dt': date.strftime('%Y-%m-%d')
62
+ }
63
+ else:
64
+ endpoint = f"{BASE_URL}/forecast.json"
65
+ params = {
66
+ 'key': API_KEY,
67
+ 'q': location,
68
+ 'days': 1,
69
+ 'aqi': 'no'
70
+ }
71
+
72
+ response = requests.get(endpoint, params=params)
73
+ response.raise_for_status()
74
+ return response.json()
75
+
76
+ except requests.exceptions.RequestException as e:
77
+ st.error(f"Error fetching weather data: {e}")
78
+ return None
79
+
80
+ def display_weather_data(weather_data, selected_datetime, container):
81
+ """Display weather data in the specified container"""
82
+ if not weather_data:
83
+ container.error("No weather data available")
84
+ return
85
+
86
+ container.subheader(f"Date: {selected_datetime.strftime('%Y-%m-%d %H:%M')}")
87
+
88
+ # Handle both historical and forecast data structure
89
+ if 'current' in weather_data:
90
+ current_data = weather_data['current']
91
+ else:
92
+ historical_hour = min(
93
+ weather_data['forecast']['forecastday'][0]['hour'],
94
+ key=lambda x: abs(datetime.strptime(x['time'], '%Y-%m-%d %H:%M').time().hour -
95
+ selected_datetime.time().hour)
96
+ )
97
+ current_data = historical_hour
98
+
99
+ # Display current weather icon and condition
100
+ icon_url = f"https:{current_data['condition']['icon']}"
101
+ weather_icon = load_weather_icon(icon_url)
102
+ if weather_icon:
103
+ col1, col2, col3 = container.columns([1, 2, 1])
104
+ with col2:
105
+ st.image(weather_icon, caption=current_data['condition']['text'], use_container_width=True)
106
+
107
+ # Create metrics in a grid
108
+ metric_col1, metric_col2 = container.columns(2)
109
+
110
+ with metric_col1:
111
+ st.metric("Temperature", f"{current_data['temp_c']}°C",
112
+ f"Feels like {current_data['feelslike_c']}°C")
113
+ st.metric("Wind", f"{current_data['wind_kph']} km/h",
114
+ f"Direction: {current_data['wind_dir']}")
115
+
116
+ with metric_col2:
117
+ st.metric("Humidity", f"{current_data['humidity']}%")
118
+ st.metric("Pressure", f"{current_data['pressure_mb']} mb")
119
+
120
+ # Display hourly forecast
121
+ container.subheader("Hourly Forecast")
122
+ hourly_data = weather_data['forecast']['forecastday'][0]['hour']
123
+
124
+ # Create a more visual hourly forecast
125
+ hours_to_show = 6
126
+ current_hour = selected_datetime.hour
127
+ relevant_hours = [h for h in hourly_data if datetime.strptime(h['time'], '%Y-%m-%d %H:%M').hour >= current_hour][:hours_to_show]
128
+
129
+ hour_cols = container.columns(min(hours_to_show, len(relevant_hours)))
130
+
131
+ for hour, col in zip(relevant_hours, hour_cols):
132
+ with col:
133
+ hour_time = datetime.strptime(hour['time'], '%Y-%m-%d %H:%M').strftime('%I %p')
134
+ st.markdown(f"**{hour_time}**")
135
+
136
+ hour_icon_url = f"https:{hour['condition']['icon']}"
137
+ hour_icon = load_weather_icon(hour_icon_url)
138
+ if hour_icon:
139
+ st.image(hour_icon, use_container_width=True)
140
+
141
+ st.markdown(f"🌡️ {hour['temp_c']}°C")
142
+ st.markdown(f"💧 {hour['chance_of_rain']}%")
143
+ st.markdown(f"💨 {hour['wind_kph']} km/h")
144
+
145
+ # Display detailed hourly data
146
+ with container.expander("Detailed Hourly Forecast"):
147
+ hourly_df = pd.DataFrame([
148
+ {
149
+ 'Time': datetime.strptime(hour['time'], '%Y-%m-%d %H:%M').strftime('%I:%M %p'),
150
+ 'Temperature': f"{hour['temp_c']}°C",
151
+ 'Condition': hour['condition']['text'],
152
+ 'Chance of Rain': f"{hour['chance_of_rain']}%",
153
+ 'Wind Speed': f"{hour['wind_kph']} km/h",
154
+ 'Humidity': f"{hour['humidity']}%"
155
+ }
156
+ for hour in hourly_data
157
+ ])
158
+
159
+ st.dataframe(
160
+ hourly_df,
161
+ hide_index=True,
162
+ use_container_width=True
163
+ )
164
+
165
+ def main():
166
+ """Main function to run the Streamlit app"""
167
+ st.markdown("<h1 class='main-header'>🌤️ Weather Forecast Dashboard</h1>", unsafe_allow_html=True)
168
+
169
+ # Sidebar inputs
170
+ with st.sidebar:
171
+ st.header("Settings")
172
+ location = st.text_input("Enter Location", "London")
173
+
174
+ # Date selection
175
+ view_type = st.radio("Select View", ["Current & Forecast", "Historical"])
176
+
177
+ if view_type == "Historical":
178
+ max_date = datetime.now() - timedelta(days=1)
179
+ min_date = max_date - timedelta(days=7)
180
+ selected_date = st.date_input(
181
+ "Select Date",
182
+ value=max_date,
183
+ min_value=min_date,
184
+ max_value=max_date
185
+ )
186
+ selected_time = st.time_input("Select Time", datetime.now().time())
187
+ selected_datetime = datetime.combine(selected_date, selected_time)
188
+ is_historical = True
189
+ else:
190
+ selected_datetime = datetime.now()
191
+ is_historical = False
192
+
193
+ if st.button("Get Weather Data"):
194
+ with st.spinner("Fetching weather data..."):
195
+ weather_data = get_weather_data(
196
+ location,
197
+ is_historical=is_historical,
198
+ date=selected_datetime if is_historical else None
199
+ )
200
+
201
+ if weather_data:
202
+ st.session_state.weather_data = weather_data
203
+ st.session_state.selected_datetime = selected_datetime
204
+
205
+ # Main content area
206
+ if 'weather_data' in st.session_state:
207
+ display_weather_data(
208
+ st.session_state.weather_data,
209
+ st.session_state.selected_datetime,
210
+ st
211
+ )
212
+ else:
213
+ st.info("Enter a location and click 'Get Weather Data' to start")
214
+
215
+ if __name__ == "__main__":
216
+ main()