-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
311 lines (258 loc) Β· 10.2 KB
/
app.py
File metadata and controls
311 lines (258 loc) Β· 10.2 KB
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta
import data_service
import os
st.set_page_config(
page_title="COVID-19 Data Dashboard",
page_icon="π¦ ",
layout="wide",
initial_sidebar_state="expanded"
)
st.title("π¦ COVID-19 Data Analysis Dashboard")
st.markdown("Real-time COVID-19 data from disease.sh API (Johns Hopkins CSSE)")
@st.cache_data(ttl=3600)
def load_and_process_data(countries, days):
"""Load and process data with caching."""
df, errors = data_service.load_data(countries, days)
if not df.empty:
df = data_service.clean_data(df)
df, regional_summary = data_service.analyze_data(df)
return df, regional_summary, errors
return pd.DataFrame(), pd.DataFrame(), errors
with st.sidebar:
st.header("βοΈ Settings")
all_countries = ['USA', 'India', 'Brazil', 'UK', 'France', 'Germany',
'Italy', 'Spain', 'Canada', 'Australia', 'Mexico',
'Russia', 'Japan', 'South Korea', 'Indonesia']
selected_countries = st.multiselect(
"Select Countries",
all_countries,
default=['USA', 'India', 'Brazil', 'UK', 'France', 'Germany', 'Italy', 'Spain', 'Canada', 'Australia']
)
days = st.slider("Days of Historical Data", 30, 365, 90)
if st.button("π Refresh Data", type="primary"):
st.cache_data.clear()
st.rerun()
st.markdown("---")
st.markdown("### π Data Source")
st.markdown("**API:** disease.sh")
st.markdown("**Source:** Johns Hopkins CSSE")
st.markdown("**Update:** Hourly")
if not selected_countries:
st.warning("β οΈ Please select at least one country from the sidebar.")
st.stop()
with st.spinner("Loading COVID-19 data..."):
df, regional_summary, errors = load_and_process_data(tuple(selected_countries), days)
if errors:
with st.expander("β οΈ Data Loading Warnings", expanded=False):
for error in errors:
st.warning(error)
if df.empty:
st.error("β No data available. Please check your selections and try again.")
st.stop()
global_stats = data_service.calculate_global_stats(regional_summary)
min_date, max_date = data_service.get_date_range(df)
st.markdown("### π Global Statistics")
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric(
label="Total Cases",
value=f"{global_stats['total_cases']:,}",
delta=None
)
with col2:
st.metric(
label="Total Deaths",
value=f"{global_stats['total_deaths']:,}",
delta=None
)
with col3:
st.metric(
label="Death Rate",
value=f"{global_stats['death_rate']:.2f}%",
delta=None
)
with col4:
st.metric(
label="Countries",
value=len(selected_countries),
delta=None
)
st.markdown(f"**Data Range:** {min_date.strftime('%Y-%m-%d') if min_date else 'N/A'} to {max_date.strftime('%Y-%m-%d') if max_date else 'N/A'}")
st.markdown("---")
tab1, tab2, tab3 = st.tabs(["π Visualizations", "π Data Tables", "π₯ Export"])
with tab1:
st.markdown("### π Cases Trend Over Time")
fig = go.Figure()
for country in selected_countries:
country_data = data_service.get_country_data(df, country)
if not country_data.empty:
fig.add_trace(go.Scatter(
x=country_data['date'],
y=country_data['cases'],
mode='lines',
name=country,
line=dict(width=2)
))
fig.update_layout(
xaxis_title="Date",
yaxis_title="Total Cases",
hovermode='x unified',
height=500,
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
)
)
st.plotly_chart(fig, width='stretch')
st.markdown("### π Total Cases by Country")
fig2 = px.bar(
regional_summary.head(10),
x='region',
y='cases',
title='Top 10 Countries by Total Cases',
labels={'region': 'Country', 'cases': 'Total Cases'},
color='cases',
color_continuous_scale='Reds'
)
fig2.update_layout(height=500)
st.plotly_chart(fig2, width='stretch')
col1, col2 = st.columns(2)
with col1:
st.markdown("### π Deaths by Country")
fig3 = px.pie(
regional_summary.head(10),
values='deaths',
names='region',
title='Death Distribution (Top 10 Countries)'
)
fig3.update_traces(textposition='inside', textinfo='percent+label')
st.plotly_chart(fig3, width='stretch')
with col2:
st.markdown("### π Death Rate by Country")
regional_summary_copy = regional_summary.copy()
regional_summary_copy['death_rate_pct'] = (
regional_summary_copy['deaths'] / regional_summary_copy['cases'] * 100
)
fig4 = px.bar(
regional_summary_copy.head(10),
x='region',
y='death_rate_pct',
title='Death Rate by Country (%)',
labels={'region': 'Country', 'death_rate_pct': 'Death Rate (%)'},
color='death_rate_pct',
color_continuous_scale='OrRd'
)
st.plotly_chart(fig4, width='stretch')
with tab2:
st.markdown("### π Regional Summary")
display_df = regional_summary.copy()
display_df['Death Rate (%)'] = (display_df['deaths'] / display_df['cases'] * 100).round(2)
display_df['Recovery Rate (%)'] = (display_df['recoveries'] / display_df['cases'] * 100).round(2)
display_df = display_df.rename(columns={
'region': 'Country',
'cases': 'Total Cases',
'deaths': 'Total Deaths',
'recoveries': 'Total Recoveries'
})
st.dataframe(
display_df,
width='stretch',
hide_index=True,
column_config={
"Total Cases": st.column_config.NumberColumn(format="%d"),
"Total Deaths": st.column_config.NumberColumn(format="%d"),
"Total Recoveries": st.column_config.NumberColumn(format="%d"),
"Death Rate (%)": st.column_config.NumberColumn(format="%.2f%%"),
"Recovery Rate (%)": st.column_config.NumberColumn(format="%.2f%%"),
}
)
st.markdown("### π Detailed Timeline Data")
search_country = st.selectbox("Select country to view detailed timeline:", selected_countries)
if search_country:
country_detail = data_service.get_country_data(df, search_country)
if not country_detail.empty:
detail_display = country_detail[['date', 'cases', 'deaths', 'recoveries', 'death_rate']].copy()
detail_display['death_rate'] = (detail_display['death_rate'] * 100).round(2)
detail_display = detail_display.rename(columns={
'date': 'Date',
'cases': 'Cases',
'deaths': 'Deaths',
'recoveries': 'Recoveries',
'death_rate': 'Death Rate (%)'
})
st.dataframe(
detail_display,
width='stretch',
hide_index=True,
height=400
)
with tab3:
st.markdown("### π₯ Export Data")
col1, col2 = st.columns(2)
with col1:
st.markdown("#### Regional Summary")
csv_regional = regional_summary.to_csv(index=False)
st.download_button(
label="π₯ Download Regional Summary (CSV)",
data=csv_regional,
file_name=f"covid_regional_summary_{datetime.now().strftime('%Y%m%d')}.csv",
mime="text/csv"
)
with col2:
st.markdown("#### Full Dataset")
csv_full = df.to_csv(index=False)
st.download_button(
label="π₯ Download Full Dataset (CSV)",
data=csv_full,
file_name=f"covid_full_data_{datetime.now().strftime('%Y%m%d')}.csv",
mime="text/csv"
)
st.markdown("#### Excel Export")
if st.button("π Generate Excel Report"):
with st.spinner("Generating Excel report..."):
try:
output_file = f"outputs/covid_summary_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
os.makedirs("outputs", exist_ok=True)
with pd.ExcelWriter(output_file, engine='openpyxl') as writer:
regional_summary.to_excel(writer, sheet_name='Regional Summary', index=False)
df.to_excel(writer, sheet_name='Full Data', index=False)
for worksheet in writer.sheets.values():
for column in worksheet.columns:
max_length = 0
column_letter = column[0].column_letter
for cell in column:
try:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
adjusted_width = min(max_length + 2, 50)
worksheet.column_dimensions[column_letter].width = adjusted_width
st.success(f"β
Excel report generated: {output_file}")
with open(output_file, 'rb') as f:
st.download_button(
label="π₯ Download Excel Report",
data=f,
file_name=f"covid_report_{datetime.now().strftime('%Y%m%d')}.xlsx",
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
except Exception as e:
st.error(f"β Error generating Excel: {str(e)}")
st.markdown("---")
st.markdown(
"""
<div style='text-align: center; color: gray;'>
<p>Data provided by disease.sh API | Updated hourly</p>
<p>Note: Recovery data may not be available for all regions</p>
</div>
""",
unsafe_allow_html=True
)