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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import requests
|
| 5 |
+
from bs4 import BeautifulSoup
|
| 6 |
+
import folium
|
| 7 |
+
from streamlit_folium import folium_static
|
| 8 |
+
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
|
| 16 |
+
st.set_page_config(layout="wide", page_title="Pakistan Climate & Disaster Monitor")
|
| 17 |
+
|
| 18 |
+
class DataCollector:
|
| 19 |
+
@staticmethod
|
| 20 |
+
def fetch_usgs_earthquake_data():
|
| 21 |
+
"""Fetch earthquake data from USGS website (free, no API key needed)"""
|
| 22 |
+
url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_month.geojson"
|
| 23 |
+
try:
|
| 24 |
+
response = requests.get(url)
|
| 25 |
+
data = response.json()
|
| 26 |
+
# Filter for Pakistan region
|
| 27 |
+
pakistan_data = {
|
| 28 |
+
"type": "FeatureCollection",
|
| 29 |
+
"features": [
|
| 30 |
+
feature for feature in data["features"]
|
| 31 |
+
if 60.878 <= feature["geometry"]["coordinates"][0] <= 77.840
|
| 32 |
+
and 23.692 <= feature["geometry"]["coordinates"][1] <= 37.097
|
| 33 |
+
]
|
| 34 |
+
}
|
| 35 |
+
return pakistan_data
|
| 36 |
+
except Exception as e:
|
| 37 |
+
st.error(f"Error fetching earthquake data: {e}")
|
| 38 |
+
return None
|
| 39 |
+
|
| 40 |
+
@staticmethod
|
| 41 |
+
def fetch_weather_data():
|
| 42 |
+
"""Fetch weather data from WorldBank Climate Data (free dataset)"""
|
| 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 |
+
df = pd.read_csv(StringIO(response.text))
|
| 51 |
+
return df
|
| 52 |
+
except Exception as e:
|
| 53 |
+
st.error(f"Error fetching weather data: {e}")
|
| 54 |
+
return None
|
| 55 |
+
|
| 56 |
+
def create_dashboard():
|
| 57 |
+
st.title("Pakistan Climate & Disaster Monitoring System")
|
| 58 |
+
|
| 59 |
+
# Sidebar for navigation
|
| 60 |
+
page = st.sidebar.selectbox(
|
| 61 |
+
"Select Module",
|
| 62 |
+
["Climate Analysis", "Disaster Monitor", "Risk Assessment", "Environmental Data"]
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
if page == "Climate Analysis":
|
| 66 |
+
show_climate_analysis()
|
| 67 |
+
elif page == "Disaster Monitor":
|
| 68 |
+
show_disaster_monitor()
|
| 69 |
+
elif page == "Risk Assessment":
|
| 70 |
+
show_risk_assessment()
|
| 71 |
+
elif page == "Environmental Data":
|
| 72 |
+
show_environmental_data()
|
| 73 |
+
|
| 74 |
+
def show_climate_analysis():
|
| 75 |
+
st.header("Climate Analysis")
|
| 76 |
+
|
| 77 |
+
# Historical temperature data from World Bank dataset
|
| 78 |
+
data_collector = DataCollector()
|
| 79 |
+
climate_data = data_collector.fetch_weather_data()
|
| 80 |
+
|
| 81 |
+
if climate_data is not None:
|
| 82 |
+
col1, col2 = st.columns(2)
|
| 83 |
+
|
| 84 |
+
with col1:
|
| 85 |
+
# Temperature trends
|
| 86 |
+
fig = px.line(climate_data,
|
| 87 |
+
x='Year',
|
| 88 |
+
y='Temperature',
|
| 89 |
+
title='Historical Temperature Trends')
|
| 90 |
+
st.plotly_chart(fig)
|
| 91 |
+
|
| 92 |
+
with col2:
|
| 93 |
+
# Precipitation patterns
|
| 94 |
+
fig = px.bar(climate_data,
|
| 95 |
+
x='Year',
|
| 96 |
+
y='Precipitation',
|
| 97 |
+
title='Annual Precipitation')
|
| 98 |
+
st.plotly_chart(fig)
|
| 99 |
+
|
| 100 |
+
# Climate indicators
|
| 101 |
+
st.subheader("Climate Indicators")
|
| 102 |
+
cols = st.columns(3)
|
| 103 |
+
|
| 104 |
+
with cols[0]:
|
| 105 |
+
avg_temp = climate_data['Temperature'].mean()
|
| 106 |
+
st.metric("Average Temperature", f"{avg_temp:.1f}°C")
|
| 107 |
+
|
| 108 |
+
with cols[1]:
|
| 109 |
+
avg_precip = climate_data['Precipitation'].mean()
|
| 110 |
+
st.metric("Average Precipitation", f"{avg_precip:.1f}mm")
|
| 111 |
+
|
| 112 |
+
with cols[2]:
|
| 113 |
+
temp_trend = climate_data['Temperature'].diff().mean()
|
| 114 |
+
st.metric("Temperature Trend", f"{temp_trend:+.2f}°C/year")
|
| 115 |
+
|
| 116 |
+
def show_disaster_monitor():
|
| 117 |
+
st.header("Disaster Monitoring")
|
| 118 |
+
|
| 119 |
+
# Fetch earthquake data
|
| 120 |
+
data_collector = DataCollector()
|
| 121 |
+
earthquake_data = data_collector.fetch_usgs_earthquake_data()
|
| 122 |
+
|
| 123 |
+
if earthquake_data:
|
| 124 |
+
# Create map
|
| 125 |
+
m = folium.Map(location=[30.3753, 69.3451], zoom_start=5)
|
| 126 |
+
|
| 127 |
+
for eq in earthquake_data['features']:
|
| 128 |
+
coords = eq['geometry']['coordinates']
|
| 129 |
+
mag = eq['properties']['mag']
|
| 130 |
+
|
| 131 |
+
folium.CircleMarker(
|
| 132 |
+
location=[coords[1], coords[0]],
|
| 133 |
+
radius=mag * 3,
|
| 134 |
+
color='red',
|
| 135 |
+
fill=True,
|
| 136 |
+
popup=f"Magnitude: {mag}",
|
| 137 |
+
).add_to(m)
|
| 138 |
+
|
| 139 |
+
st.subheader("Recent Earthquakes Map")
|
| 140 |
+
folium_static(m)
|
| 141 |
+
|
| 142 |
+
# Recent earthquakes list
|
| 143 |
+
st.subheader("Recent Earthquakes")
|
| 144 |
+
eq_df = pd.DataFrame([
|
| 145 |
+
{
|
| 146 |
+
'Time': datetime.fromtimestamp(eq['properties']['time']/1000),
|
| 147 |
+
'Magnitude': eq['properties']['mag'],
|
| 148 |
+
'Location': eq['properties']['place']
|
| 149 |
+
}
|
| 150 |
+
for eq in earthquake_data['features']
|
| 151 |
+
])
|
| 152 |
+
st.dataframe(eq_df)
|
| 153 |
+
|
| 154 |
+
def show_risk_assessment():
|
| 155 |
+
st.header("Risk Assessment")
|
| 156 |
+
|
| 157 |
+
# Sample risk data (could be enhanced with real historical data)
|
| 158 |
+
risk_data = pd.DataFrame({
|
| 159 |
+
'Region': ['Punjab', 'Sindh', 'KPK', 'Balochistan', 'Gilgit-Baltistan'],
|
| 160 |
+
'Flood_Risk': np.random.uniform(0, 1, 5),
|
| 161 |
+
'Drought_Risk': np.random.uniform(0, 1, 5),
|
| 162 |
+
'Earthquake_Risk': np.random.uniform(0, 1, 5)
|
| 163 |
+
})
|
| 164 |
+
|
| 165 |
+
# Risk heatmap
|
| 166 |
+
fig = go.Figure(data=go.Heatmap(
|
| 167 |
+
z=[risk_data[col] for col in ['Flood_Risk', 'Drought_Risk', 'Earthquake_Risk']],
|
| 168 |
+
x=risk_data['Region'],
|
| 169 |
+
y=['Flood', 'Drought', 'Earthquake'],
|
| 170 |
+
colorscale='RdYlBu_r'
|
| 171 |
+
))
|
| 172 |
+
fig.update_layout(title='Regional Risk Assessment Heatmap')
|
| 173 |
+
st.plotly_chart(fig)
|
| 174 |
+
|
| 175 |
+
# Risk analysis
|
| 176 |
+
st.subheader("Risk Analysis by Region")
|
| 177 |
+
selected_region = st.selectbox("Select Region", risk_data['Region'])
|
| 178 |
+
region_data = risk_data[risk_data['Region'] == selected_region].iloc[0]
|
| 179 |
+
|
| 180 |
+
cols = st.columns(3)
|
| 181 |
+
with cols[0]:
|
| 182 |
+
st.metric("Flood Risk", f"{region_data['Flood_Risk']:.2%}")
|
| 183 |
+
with cols[1]:
|
| 184 |
+
st.metric("Drought Risk", f"{region_data['Drought_Risk']:.2%}")
|
| 185 |
+
with cols[2]:
|
| 186 |
+
st.metric("Earthquake Risk", f"{region_data['Earthquake_Risk']:.2%}")
|
| 187 |
+
|
| 188 |
+
def show_environmental_data():
|
| 189 |
+
st.header("Environmental Data")
|
| 190 |
+
|
| 191 |
+
# Sample environmental data (could be enhanced with real data sources)
|
| 192 |
+
dates = pd.date_range(start='2023-01-01', periods=365, freq='D')
|
| 193 |
+
env_data = pd.DataFrame({
|
| 194 |
+
'Date': dates,
|
| 195 |
+
'Temperature': np.random.normal(25, 5, 365),
|
| 196 |
+
'Humidity': np.random.normal(60, 10, 365),
|
| 197 |
+
'Air_Quality': np.random.normal(50, 20, 365)
|
| 198 |
+
})
|
| 199 |
+
|
| 200 |
+
# Environmental indicators
|
| 201 |
+
st.subheader("Environmental Indicators")
|
| 202 |
+
metric = st.selectbox("Select Indicator", ['Temperature', 'Humidity', 'Air_Quality'])
|
| 203 |
+
|
| 204 |
+
fig = px.line(env_data, x='Date', y=metric,
|
| 205 |
+
title=f'{metric} Over Time')
|
| 206 |
+
st.plotly_chart(fig)
|
| 207 |
+
|
| 208 |
+
# Current conditions
|
| 209 |
+
st.subheader("Current Conditions")
|
| 210 |
+
cols = st.columns(3)
|
| 211 |
+
with cols[0]:
|
| 212 |
+
st.metric("Temperature", f"{env_data['Temperature'].iloc[-1]:.1f}°C")
|
| 213 |
+
with cols[1]:
|
| 214 |
+
st.metric("Humidity", f"{env_data['Humidity'].iloc[-1]:.1f}%")
|
| 215 |
+
with cols[2]:
|
| 216 |
+
st.metric("Air Quality Index", f"{env_data['Air_Quality'].iloc[-1]:.0f}")
|
| 217 |
+
|
| 218 |
+
if __name__ == "__main__":
|
| 219 |
+
create_dashboard()
|