File size: 7,538 Bytes
cb41d0d |
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 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
import streamlit as st
import pandas as pd
import numpy as np
import requests
from bs4 import BeautifulSoup
import folium
from streamlit_folium import folium_static
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta
import json
import csv
from io import StringIO
# Page configuration
st.set_page_config(layout="wide", page_title="Pakistan Climate & Disaster Monitor")
class DataCollector:
@staticmethod
def fetch_usgs_earthquake_data():
"""Fetch earthquake data from USGS website (free, no API key needed)"""
url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_month.geojson"
try:
response = requests.get(url)
data = response.json()
# Filter for Pakistan region
pakistan_data = {
"type": "FeatureCollection",
"features": [
feature for feature in data["features"]
if 60.878 <= feature["geometry"]["coordinates"][0] <= 77.840
and 23.692 <= feature["geometry"]["coordinates"][1] <= 37.097
]
}
return pakistan_data
except Exception as e:
st.error(f"Error fetching earthquake data: {e}")
return None
@staticmethod
def fetch_weather_data():
"""Fetch weather data from WorldBank Climate Data (free dataset)"""
url = "https://climateknowledgeportal.worldbank.org/api/data/get-download-data"
params = {
"region": "South Asia",
"country": "Pakistan"
}
try:
response = requests.post(url, data=params)
df = pd.read_csv(StringIO(response.text))
return df
except Exception as e:
st.error(f"Error fetching weather data: {e}")
return None
def create_dashboard():
st.title("Pakistan Climate & Disaster Monitoring System")
# Sidebar for navigation
page = st.sidebar.selectbox(
"Select Module",
["Climate Analysis", "Disaster Monitor", "Risk Assessment", "Environmental Data"]
)
if page == "Climate Analysis":
show_climate_analysis()
elif page == "Disaster Monitor":
show_disaster_monitor()
elif page == "Risk Assessment":
show_risk_assessment()
elif page == "Environmental Data":
show_environmental_data()
def show_climate_analysis():
st.header("Climate Analysis")
# Historical temperature data from World Bank dataset
data_collector = DataCollector()
climate_data = data_collector.fetch_weather_data()
if climate_data is not None:
col1, col2 = st.columns(2)
with col1:
# Temperature trends
fig = px.line(climate_data,
x='Year',
y='Temperature',
title='Historical Temperature Trends')
st.plotly_chart(fig)
with col2:
# Precipitation patterns
fig = px.bar(climate_data,
x='Year',
y='Precipitation',
title='Annual Precipitation')
st.plotly_chart(fig)
# Climate indicators
st.subheader("Climate Indicators")
cols = st.columns(3)
with cols[0]:
avg_temp = climate_data['Temperature'].mean()
st.metric("Average Temperature", f"{avg_temp:.1f}°C")
with cols[1]:
avg_precip = climate_data['Precipitation'].mean()
st.metric("Average Precipitation", f"{avg_precip:.1f}mm")
with cols[2]:
temp_trend = climate_data['Temperature'].diff().mean()
st.metric("Temperature Trend", f"{temp_trend:+.2f}°C/year")
def show_disaster_monitor():
st.header("Disaster Monitoring")
# Fetch earthquake data
data_collector = DataCollector()
earthquake_data = data_collector.fetch_usgs_earthquake_data()
if earthquake_data:
# Create map
m = folium.Map(location=[30.3753, 69.3451], zoom_start=5)
for eq in earthquake_data['features']:
coords = eq['geometry']['coordinates']
mag = eq['properties']['mag']
folium.CircleMarker(
location=[coords[1], coords[0]],
radius=mag * 3,
color='red',
fill=True,
popup=f"Magnitude: {mag}",
).add_to(m)
st.subheader("Recent Earthquakes Map")
folium_static(m)
# Recent earthquakes list
st.subheader("Recent Earthquakes")
eq_df = pd.DataFrame([
{
'Time': datetime.fromtimestamp(eq['properties']['time']/1000),
'Magnitude': eq['properties']['mag'],
'Location': eq['properties']['place']
}
for eq in earthquake_data['features']
])
st.dataframe(eq_df)
def show_risk_assessment():
st.header("Risk Assessment")
# Sample risk data (could be enhanced with real historical data)
risk_data = pd.DataFrame({
'Region': ['Punjab', 'Sindh', 'KPK', 'Balochistan', 'Gilgit-Baltistan'],
'Flood_Risk': np.random.uniform(0, 1, 5),
'Drought_Risk': np.random.uniform(0, 1, 5),
'Earthquake_Risk': np.random.uniform(0, 1, 5)
})
# Risk heatmap
fig = go.Figure(data=go.Heatmap(
z=[risk_data[col] for col in ['Flood_Risk', 'Drought_Risk', 'Earthquake_Risk']],
x=risk_data['Region'],
y=['Flood', 'Drought', 'Earthquake'],
colorscale='RdYlBu_r'
))
fig.update_layout(title='Regional Risk Assessment Heatmap')
st.plotly_chart(fig)
# Risk analysis
st.subheader("Risk Analysis by Region")
selected_region = st.selectbox("Select Region", risk_data['Region'])
region_data = risk_data[risk_data['Region'] == selected_region].iloc[0]
cols = st.columns(3)
with cols[0]:
st.metric("Flood Risk", f"{region_data['Flood_Risk']:.2%}")
with cols[1]:
st.metric("Drought Risk", f"{region_data['Drought_Risk']:.2%}")
with cols[2]:
st.metric("Earthquake Risk", f"{region_data['Earthquake_Risk']:.2%}")
def show_environmental_data():
st.header("Environmental Data")
# Sample environmental data (could be enhanced with real data sources)
dates = pd.date_range(start='2023-01-01', periods=365, freq='D')
env_data = pd.DataFrame({
'Date': dates,
'Temperature': np.random.normal(25, 5, 365),
'Humidity': np.random.normal(60, 10, 365),
'Air_Quality': np.random.normal(50, 20, 365)
})
# Environmental indicators
st.subheader("Environmental Indicators")
metric = st.selectbox("Select Indicator", ['Temperature', 'Humidity', 'Air_Quality'])
fig = px.line(env_data, x='Date', y=metric,
title=f'{metric} Over Time')
st.plotly_chart(fig)
# Current conditions
st.subheader("Current Conditions")
cols = st.columns(3)
with cols[0]:
st.metric("Temperature", f"{env_data['Temperature'].iloc[-1]:.1f}°C")
with cols[1]:
st.metric("Humidity", f"{env_data['Humidity'].iloc[-1]:.1f}%")
with cols[2]:
st.metric("Air Quality Index", f"{env_data['Air_Quality'].iloc[-1]:.0f}")
if __name__ == "__main__":
create_dashboard() |