Update app.py
Browse files
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
|
| 37 |
st.error(f"Error fetching earthquake data: {e}")
|
| 38 |
return None
|
| 39 |
|
| 40 |
@staticmethod
|
| 41 |
-
def
|
| 42 |
-
"""Fetch
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
| 47 |
}
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
-
|
| 66 |
-
def
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
def show_climate_analysis():
|
| 84 |
st.header("Climate Analysis")
|
| 85 |
-
|
| 86 |
data_collector = DataCollector()
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
if
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
col1, col2 = st.columns(2)
|
| 96 |
-
|
| 97 |
with col1:
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
st.plotly_chart(fig)
|
| 100 |
-
|
| 101 |
with col2:
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
st.plotly_chart(fig)
|
| 104 |
-
|
| 105 |
-
|
|
|
|
|
|
|
| 106 |
cols = st.columns(3)
|
| 107 |
-
|
| 108 |
with cols[0]:
|
| 109 |
-
|
| 110 |
-
st.metric("Average Temperature", f"{avg_temp:.1f}°C")
|
| 111 |
-
|
| 112 |
with cols[1]:
|
| 113 |
-
|
| 114 |
-
|
|
|
|
| 115 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
with cols[2]:
|
| 117 |
-
|
| 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 |
-
#
|
| 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()
|