shaheerawan3 commited on
Commit
7dc4cfb
·
verified ·
1 Parent(s): 201e353

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +128 -69
app.py CHANGED
@@ -9,7 +9,6 @@ import plotly.express as px
9
  import plotly.graph_objects as go
10
  from datetime import datetime, timedelta
11
  import json
12
- import csv
13
  from io import StringIO
14
 
15
  # Page configuration
@@ -18,12 +17,12 @@ st.set_page_config(layout="wide", page_title="Pakistan Climate & Disaster Monito
18
  class DataCollector:
19
  @staticmethod
20
  def fetch_usgs_earthquake_data():
21
- """Fetch earthquake data from USGS website."""
22
  url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_month.geojson"
23
  try:
24
  response = requests.get(url)
25
- response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
26
  data = response.json()
 
27
  pakistan_data = {
28
  "type": "FeatureCollection",
29
  "features": [
@@ -33,93 +32,153 @@ class DataCollector:
33
  ]
34
  }
35
  return pakistan_data
36
- except requests.exceptions.RequestException as e:
37
  st.error(f"Error fetching earthquake data: {e}")
38
  return None
39
 
40
  @staticmethod
41
- def fetch_world_bank_climate_data():
42
- """Fetch climate data from World Bank Climate Change Knowledge Portal."""
43
- url = "https://climateknowledgeportal.worldbank.org/api/data/get-download-data"
44
- params = {
45
- "region": "South Asia",
46
- "country": "Pakistan"
 
 
 
47
  }
48
- try:
49
- response = requests.post(url, data=params)
50
- response.raise_for_status()
51
- # Use StringIO and specify encoding to handle potential issues
52
- df = pd.read_csv(StringIO(response.text), encoding='utf-8')
53
- return df
54
- except requests.exceptions.RequestException as e:
55
- st.error(f"Error fetching climate data: {e}")
56
- return None
57
- except pd.errors.ParserError as e:
58
- st.error(f"Error parsing climate data (CSV): {e}. Check the data format.")
59
- st.error(f"Response Text: {response.text}") # Print response for debugging
60
- return None
61
- except Exception as e:
62
- st.error(f"An unexpected error occurred: {e}")
63
- return None
 
 
 
 
 
 
64
 
65
-
66
- def create_dashboard():
67
- st.title("Pakistan Climate & Disaster Monitoring System")
68
-
69
- page = st.sidebar.selectbox(
70
- "Select Module",
71
- ["Climate Analysis", "Disaster Monitor", "Risk Assessment", "Environmental Data"]
72
- )
73
-
74
- if page == "Climate Analysis":
75
- show_climate_analysis()
76
- elif page == "Disaster Monitor":
77
- show_disaster_monitor()
78
- elif page == "Risk Assessment":
79
- show_risk_assessment()
80
- elif page == "Environmental Data":
81
- show_environmental_data()
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
  def show_climate_analysis():
84
  st.header("Climate Analysis")
85
-
86
  data_collector = DataCollector()
87
- climate_data = data_collector.fetch_world_bank_climate_data()
88
-
89
- if climate_data is not None:
90
- if 'Temperature - (Celsius)' in climate_data.columns:
91
- climate_data = climate_data.rename(columns={'Temperature - (Celsius)': 'Temperature'})
92
- if 'Annual average precipitation in mm' in climate_data.columns:
93
- climate_data = climate_data.rename(columns={'Annual average precipitation in mm': 'Precipitation'})
94
-
95
  col1, col2 = st.columns(2)
96
-
97
  with col1:
98
- fig = px.line(climate_data, x='Year', y='Temperature', title='Historical Temperature Trends')
 
 
 
 
99
  st.plotly_chart(fig)
100
-
101
  with col2:
102
- fig = px.bar(climate_data, x='Year', y='Precipitation', title='Annual Precipitation')
 
 
 
 
103
  st.plotly_chart(fig)
104
-
105
- st.subheader("Climate Indicators")
 
 
106
  cols = st.columns(3)
107
-
108
  with cols[0]:
109
- avg_temp = climate_data['Temperature'].mean()
110
- st.metric("Average Temperature", f"{avg_temp:.1f}°C")
111
-
112
  with cols[1]:
113
- avg_precip = climate_data['Precipitation'].mean()
114
- st.metric("Average Precipitation", f"{avg_precip:.1f}mm")
 
115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  with cols[2]:
117
- temp_trend = climate_data['Temperature'].diff().mean()
118
- st.metric("Temperature Trend", f"{temp_trend:+.2f}°C/year")
119
- else:
120
- st.warning("Could not retrieve climate data. Please check the data source.")
121
 
122
- # ... (rest of the functions: show_disaster_monitor, show_risk_assessment, show_environmental_data) - No changes needed here
123
 
124
  if __name__ == "__main__":
125
  create_dashboard()
 
9
  import plotly.graph_objects as go
10
  from datetime import datetime, timedelta
11
  import json
 
12
  from io import StringIO
13
 
14
  # Page configuration
 
17
  class DataCollector:
18
  @staticmethod
19
  def fetch_usgs_earthquake_data():
20
+ """Fetch earthquake data from USGS website (free, no API key needed)"""
21
  url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_month.geojson"
22
  try:
23
  response = requests.get(url)
 
24
  data = response.json()
25
+ # Filter for Pakistan region
26
  pakistan_data = {
27
  "type": "FeatureCollection",
28
  "features": [
 
32
  ]
33
  }
34
  return pakistan_data
35
+ except Exception as e:
36
  st.error(f"Error fetching earthquake data: {e}")
37
  return None
38
 
39
  @staticmethod
40
+ def fetch_weather_data():
41
+ """Fetch weather data from OpenMeteo (free, no API required)"""
42
+ # Multiple cities in Pakistan
43
+ cities = {
44
+ 'Islamabad': {'lat': 33.7294, 'lon': 73.0931},
45
+ 'Karachi': {'lat': 24.8607, 'lon': 67.0011},
46
+ 'Lahore': {'lat': 31.5204, 'lon': 74.3587},
47
+ 'Peshawar': {'lat': 34.0151, 'lon': 71.5249},
48
+ 'Quetta': {'lat': 30.1798, 'lon': 66.9750}
49
  }
50
+
51
+ weather_data = []
52
+ for city, coords in cities.items():
53
+ url = f"https://api.open-meteo.com/v1/forecast?latitude={coords['lat']}&longitude={coords['lon']}&daily=temperature_2m_max,temperature_2m_min,precipitation_sum&timezone=auto"
54
+ try:
55
+ response = requests.get(url)
56
+ data = response.json()
57
+ df = pd.DataFrame({
58
+ 'Date': pd.to_datetime(data['daily']['time']),
59
+ 'Temperature_Max': data['daily']['temperature_2m_max'],
60
+ 'Temperature_Min': data['daily']['temperature_2m_min'],
61
+ 'Precipitation': data['daily']['precipitation_sum'],
62
+ 'City': city
63
+ })
64
+ weather_data.append(df)
65
+ except Exception as e:
66
+ st.error(f"Error fetching data for {city}: {e}")
67
+ continue
68
+
69
+ if weather_data:
70
+ return pd.concat(weather_data, ignore_index=True)
71
+ return None
72
 
73
+ @staticmethod
74
+ def fetch_air_quality_data():
75
+ """Fetch air quality data from OpenMeteo Air Quality API (free)"""
76
+ cities = {
77
+ 'Islamabad': {'lat': 33.7294, 'lon': 73.0931},
78
+ 'Karachi': {'lat': 24.8607, 'lon': 67.0011},
79
+ 'Lahore': {'lat': 31.5204, 'lon': 74.3587}
80
+ }
81
+
82
+ aqi_data = []
83
+ for city, coords in cities.items():
84
+ url = f"https://air-quality-api.open-meteo.com/v1/air-quality?latitude={coords['lat']}&longitude={coords['lon']}&hourly=pm10,pm2_5,carbon_monoxide&timezone=auto"
85
+ try:
86
+ response = requests.get(url)
87
+ data = response.json()
88
+ df = pd.DataFrame({
89
+ 'Time': pd.to_datetime(data['hourly']['time']),
90
+ 'PM10': data['hourly']['pm10'],
91
+ 'PM2.5': data['hourly']['pm2_5'],
92
+ 'CO': data['hourly']['carbon_monoxide'],
93
+ 'City': city
94
+ })
95
+ aqi_data.append(df)
96
+ except Exception as e:
97
+ st.error(f"Error fetching AQI data for {city}: {e}")
98
+ continue
99
+
100
+ if aqi_data:
101
+ return pd.concat(aqi_data, ignore_index=True)
102
+ return None
103
 
104
  def show_climate_analysis():
105
  st.header("Climate Analysis")
106
+
107
  data_collector = DataCollector()
108
+ weather_data = data_collector.fetch_weather_data()
109
+
110
+ if weather_data is not None:
111
+ # City selector
112
+ selected_city = st.selectbox("Select City", weather_data['City'].unique())
113
+ city_data = weather_data[weather_data['City'] == selected_city]
114
+
 
115
  col1, col2 = st.columns(2)
116
+
117
  with col1:
118
+ # Temperature trends
119
+ fig = px.line(city_data,
120
+ x='Date',
121
+ y=['Temperature_Max', 'Temperature_Min'],
122
+ title=f'Temperature Trends - {selected_city}')
123
  st.plotly_chart(fig)
124
+
125
  with col2:
126
+ # Precipitation patterns
127
+ fig = px.bar(city_data,
128
+ x='Date',
129
+ y='Precipitation',
130
+ title=f'Daily Precipitation - {selected_city}')
131
  st.plotly_chart(fig)
132
+
133
+ # Climate indicators
134
+ st.subheader("Current Climate Indicators")
135
+ latest_data = city_data.iloc[-1]
136
  cols = st.columns(3)
137
+
138
  with cols[0]:
139
+ st.metric("Max Temperature", f"{latest_data['Temperature_Max']:.1f}°C")
 
 
140
  with cols[1]:
141
+ st.metric("Min Temperature", f"{latest_data['Temperature_Min']:.1f}°C")
142
+ with cols[2]:
143
+ st.metric("Precipitation", f"{latest_data['Precipitation']:.1f}mm")
144
 
145
+ def show_environmental_data():
146
+ st.header("Environmental Data")
147
+
148
+ data_collector = DataCollector()
149
+ aqi_data = data_collector.fetch_air_quality_data()
150
+
151
+ if aqi_data is not None:
152
+ # City selector
153
+ selected_city = st.selectbox("Select City", aqi_data['City'].unique())
154
+ city_data = aqi_data[aqi_data['City'] == selected_city]
155
+
156
+ # Latest 24 hours of data
157
+ recent_data = city_data.tail(24)
158
+
159
+ # AQI time series
160
+ st.subheader("Air Quality Indicators")
161
+ metric = st.selectbox("Select Pollutant", ['PM10', 'PM2.5', 'CO'])
162
+
163
+ fig = px.line(recent_data,
164
+ x='Time',
165
+ y=metric,
166
+ title=f'{metric} Levels - {selected_city} (Last 24 Hours)')
167
+ st.plotly_chart(fig)
168
+
169
+ # Current conditions
170
+ st.subheader("Current Air Quality")
171
+ latest_data = city_data.iloc[-1]
172
+ cols = st.columns(3)
173
+
174
+ with cols[0]:
175
+ st.metric("PM10", f"{latest_data['PM10']:.1f} µg/m³")
176
+ with cols[1]:
177
+ st.metric("PM2.5", f"{latest_data['PM2.5']:.1f} µg/m³")
178
  with cols[2]:
179
+ st.metric("Carbon Monoxide", f"{latest_data['CO']:.1f} µg/m³")
 
 
 
180
 
181
+ # [Previous show_disaster_monitor and show_risk_assessment functions remain the same]
182
 
183
  if __name__ == "__main__":
184
  create_dashboard()