Update src/streamlit_app.py
Browse files- src/streamlit_app.py +12 -48
src/streamlit_app.py
CHANGED
@@ -13,7 +13,7 @@ st.set_page_config(
|
|
13 |
)
|
14 |
|
15 |
# --- API Data Fetching Function ---
|
16 |
-
@st.cache_data(ttl=600)
|
17 |
def fetch_earthquakes(start_date, end_date, min_magnitude):
|
18 |
"""
|
19 |
Fetches earthquake data from the specified API endpoint.
|
@@ -27,76 +27,45 @@ def fetch_earthquakes(start_date, end_date, min_magnitude):
|
|
27 |
}
|
28 |
try:
|
29 |
response = requests.get(API_URL, params=params, timeout=20)
|
30 |
-
response.raise_for_status()
|
31 |
data = response.json()
|
32 |
if not data:
|
33 |
-
return pd.DataFrame()
|
34 |
return pd.DataFrame(data)
|
35 |
except requests.exceptions.RequestException as e:
|
36 |
st.error(f"API Request Failed: {e}")
|
37 |
return None
|
38 |
-
except ValueError:
|
39 |
st.error("Failed to decode API response. The API might be temporarily down.")
|
40 |
return None
|
41 |
|
42 |
# --- UI Design ---
|
43 |
-
|
44 |
-
# 1. Title
|
45 |
st.title("πΊοΈ Global Earthquake Activity Explorer")
|
46 |
st.markdown("Analyze and visualize recent earthquake events around the world.")
|
47 |
|
48 |
-
# 2. Sidebar for User Inputs
|
49 |
with st.sidebar:
|
50 |
st.header("π Search Parameters")
|
51 |
-
|
52 |
-
# Use a date range of the last 90 days as a default
|
53 |
today = date.today()
|
54 |
default_start_date = today - timedelta(days=90)
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
value=default_start_date,
|
59 |
-
min_value=date(1900, 1, 1),
|
60 |
-
max_value=today,
|
61 |
-
help="Select the beginning of the date range."
|
62 |
-
)
|
63 |
-
|
64 |
-
end_date = st.date_input(
|
65 |
-
"End Date",
|
66 |
-
value=today,
|
67 |
-
min_value=start_date,
|
68 |
-
max_value=today,
|
69 |
-
help="Select the end of the date range."
|
70 |
-
)
|
71 |
-
|
72 |
-
min_magnitude = st.slider(
|
73 |
-
"Minimum Magnitude",
|
74 |
-
min_value=0.0,
|
75 |
-
max_value=10.0,
|
76 |
-
value=5.5, # A sensible default to avoid clutter
|
77 |
-
step=0.1,
|
78 |
-
help="Drag the slider to set the minimum magnitude for queried earthquakes."
|
79 |
-
)
|
80 |
-
|
81 |
-
# Action button to trigger the search
|
82 |
search_button = st.button("Search Earthquakes", type="primary", use_container_width=True)
|
83 |
|
84 |
-
|
85 |
# --- Main Content Area ---
|
86 |
if search_button:
|
87 |
with st.spinner('Fetching earthquake data from the server... Please wait.'):
|
88 |
-
# 3. Fetch data using the function
|
89 |
df = fetch_earthquakes(start_date, end_date, min_magnitude)
|
90 |
|
91 |
if df is not None and not df.empty:
|
92 |
st.success(f"Found {len(df)} earthquakes matching your criteria.")
|
93 |
|
94 |
-
#
|
95 |
-
df['time'] = pd.to_datetime(df['
|
|
|
96 |
df['magnitude'] = df['mag'].astype(float)
|
97 |
df['depth'] = df['depth'].astype(float)
|
98 |
|
99 |
-
# --- Display Summary Metrics ---
|
100 |
st.subheader("π Summary Statistics")
|
101 |
col1, col2, col3 = st.columns(3)
|
102 |
col1.metric("Total Earthquakes", f"{len(df):,}")
|
@@ -104,8 +73,6 @@ if search_button:
|
|
104 |
col3.metric("Deepest Event (km)", f"{df['depth'].max():.2f}")
|
105 |
|
106 |
st.markdown("---")
|
107 |
-
|
108 |
-
# --- 4. Draw Earthquake Distribution Map ---
|
109 |
st.subheader("π Interactive Earthquake Map")
|
110 |
st.markdown("Hover over points for details. Circle size represents magnitude.")
|
111 |
|
@@ -119,13 +86,13 @@ if search_button:
|
|
119 |
hover_data={
|
120 |
'latitude': ':.2f',
|
121 |
'longitude': ':.2f',
|
122 |
-
'time': True,
|
123 |
'magnitude': ':.2f',
|
124 |
'depth': ':.2f km'
|
125 |
},
|
126 |
projection="natural earth",
|
127 |
title=f"Earthquakes from {start_date} to {end_date} (Magnitude > {min_magnitude})",
|
128 |
-
color_continuous_scale=px.colors.sequential.Plasma_r
|
129 |
)
|
130 |
|
131 |
fig.update_layout(
|
@@ -135,11 +102,8 @@ if search_button:
|
|
135 |
st.plotly_chart(fig, use_container_width=True)
|
136 |
|
137 |
st.markdown("---")
|
138 |
-
|
139 |
-
# --- 5. Show Earthquakes in a Table ---
|
140 |
st.subheader("π Detailed Earthquake Data")
|
141 |
|
142 |
-
# Select and rename columns for a cleaner table display
|
143 |
display_df = df[['time', 'place', 'magnitude', 'depth', 'url']].copy()
|
144 |
display_df.rename(columns={
|
145 |
'time': 'Time (UTC)',
|
|
|
13 |
)
|
14 |
|
15 |
# --- API Data Fetching Function ---
|
16 |
+
@st.cache_data(ttl=600)
|
17 |
def fetch_earthquakes(start_date, end_date, min_magnitude):
|
18 |
"""
|
19 |
Fetches earthquake data from the specified API endpoint.
|
|
|
27 |
}
|
28 |
try:
|
29 |
response = requests.get(API_URL, params=params, timeout=20)
|
30 |
+
response.raise_for_status()
|
31 |
data = response.json()
|
32 |
if not data:
|
33 |
+
return pd.DataFrame()
|
34 |
return pd.DataFrame(data)
|
35 |
except requests.exceptions.RequestException as e:
|
36 |
st.error(f"API Request Failed: {e}")
|
37 |
return None
|
38 |
+
except ValueError:
|
39 |
st.error("Failed to decode API response. The API might be temporarily down.")
|
40 |
return None
|
41 |
|
42 |
# --- UI Design ---
|
|
|
|
|
43 |
st.title("πΊοΈ Global Earthquake Activity Explorer")
|
44 |
st.markdown("Analyze and visualize recent earthquake events around the world.")
|
45 |
|
|
|
46 |
with st.sidebar:
|
47 |
st.header("π Search Parameters")
|
|
|
|
|
48 |
today = date.today()
|
49 |
default_start_date = today - timedelta(days=90)
|
50 |
+
start_date = st.date_input("Start Date", value=default_start_date, min_value=date(1900, 1, 1), max_value=today, help="Select the beginning of the date range.")
|
51 |
+
end_date = st.date_input("End Date", value=today, min_value=start_date, max_value=today, help="Select the end of the date range.")
|
52 |
+
min_magnitude = st.slider("Minimum Magnitude", min_value=0.0, max_value=10.0, value=5.5, step=0.1, help="Drag the slider to set the minimum magnitude for queried earthquakes.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
search_button = st.button("Search Earthquakes", type="primary", use_container_width=True)
|
54 |
|
|
|
55 |
# --- Main Content Area ---
|
56 |
if search_button:
|
57 |
with st.spinner('Fetching earthquake data from the server... Please wait.'):
|
|
|
58 |
df = fetch_earthquakes(start_date, end_date, min_magnitude)
|
59 |
|
60 |
if df is not None and not df.empty:
|
61 |
st.success(f"Found {len(df)} earthquakes matching your criteria.")
|
62 |
|
63 |
+
# CORRECTED LINE: Use 'event_time' from the API and assign it to a new 'time' column.
|
64 |
+
df['time'] = pd.to_datetime(df['event_time'])
|
65 |
+
|
66 |
df['magnitude'] = df['mag'].astype(float)
|
67 |
df['depth'] = df['depth'].astype(float)
|
68 |
|
|
|
69 |
st.subheader("π Summary Statistics")
|
70 |
col1, col2, col3 = st.columns(3)
|
71 |
col1.metric("Total Earthquakes", f"{len(df):,}")
|
|
|
73 |
col3.metric("Deepest Event (km)", f"{df['depth'].max():.2f}")
|
74 |
|
75 |
st.markdown("---")
|
|
|
|
|
76 |
st.subheader("π Interactive Earthquake Map")
|
77 |
st.markdown("Hover over points for details. Circle size represents magnitude.")
|
78 |
|
|
|
86 |
hover_data={
|
87 |
'latitude': ':.2f',
|
88 |
'longitude': ':.2f',
|
89 |
+
'time': True, # This now works because we created the 'time' column
|
90 |
'magnitude': ':.2f',
|
91 |
'depth': ':.2f km'
|
92 |
},
|
93 |
projection="natural earth",
|
94 |
title=f"Earthquakes from {start_date} to {end_date} (Magnitude > {min_magnitude})",
|
95 |
+
color_continuous_scale=px.colors.sequential.Plasma_r
|
96 |
)
|
97 |
|
98 |
fig.update_layout(
|
|
|
102 |
st.plotly_chart(fig, use_container_width=True)
|
103 |
|
104 |
st.markdown("---")
|
|
|
|
|
105 |
st.subheader("π Detailed Earthquake Data")
|
106 |
|
|
|
107 |
display_df = df[['time', 'place', 'magnitude', 'depth', 'url']].copy()
|
108 |
display_df.rename(columns={
|
109 |
'time': 'Time (UTC)',
|