RushiMane2003 commited on
Commit
640d7ff
ยท
verified ยท
1 Parent(s): d00c58e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +854 -0
app.py CHANGED
@@ -0,0 +1,854 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import google.generativeai as genai
3
+ from geopy.geocoders import Nominatim
4
+ # from geopy.exc import GeocoderTimedOut, GeocoderUnavailable # Not explicitly caught, requests.timeout handles
5
+ import folium
6
+ from streamlit_folium import st_folium
7
+ import pandas as pd
8
+ import requests
9
+ import re
10
+ import os
11
+ from datetime import datetime, timedelta
12
+
13
+ # --- Page Configuration ---
14
+ st.set_page_config(
15
+ layout="wide",
16
+ page_title="Landslide Factor Explorer | India", # More professional title
17
+ page_icon="๐Ÿ”๏ธ", # Favicon
18
+ initial_sidebar_state="collapsed"
19
+ )
20
+ # Custom CSS for enhanced UI
21
+ st.markdown("""
22
+ <style>
23
+ /* Main styling */
24
+ .main .block-container {
25
+ padding-top: 1rem; /* Reduced top padding */
26
+ padding-bottom: 2rem;
27
+ padding-left: 2rem; /* Added horizontal padding */
28
+ padding-right: 2rem; /* Added horizontal padding */
29
+ }
30
+
31
+ /* Header styling */
32
+ h1, h2, h3, h4, h5 {
33
+ font-family: 'Roboto', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
34
+ color: #2c3e50; /* Dark blue-gray for headers */
35
+ }
36
+ h1 {
37
+ color: #1f618d; /* Slightly different color for main title if needed */
38
+ }
39
+
40
+ /* Card-like containers */
41
+ .card {
42
+ background-color: #FFFFFF;
43
+ border-radius: 12px; /* Softer radius */
44
+ padding: 20px;
45
+ box-shadow: 0 6px 12px rgba(0, 0, 0, 0.08); /* Softer shadow */
46
+ margin-bottom: 20px;
47
+ border: 1px solid #e0e0e0; /* Light border */
48
+ }
49
+ .data-card { /* Specific card for data sections */
50
+ background-color: #f9f9f9; /* Slightly off-white */
51
+ border-radius: 10px;
52
+ padding: 15px;
53
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
54
+ margin-bottom: 15px;
55
+ border-left: 5px solid #3498db; /* Accent color */
56
+ }
57
+
58
+
59
+ /* For metric containers */
60
+ .metric-container {
61
+ background-color: #f8f9fa; /* Lighter background */
62
+ border-radius: 8px;
63
+ padding: 15px;
64
+ border-left: 4px solid #1abc9c; /* Green accent */
65
+ margin-bottom: 10px;
66
+ text-align: center;
67
+ }
68
+ .stMetric { /* Target Streamlit's metric component */
69
+ background-color: #ffffff;
70
+ border-radius: 8px;
71
+ padding: 15px 20px;
72
+ box-shadow: 0 2px 4px rgba(0,0,0,0.05);
73
+ border: 1px solid #eee;
74
+ }
75
+ .stMetric > label { /* Metric label */
76
+ font-weight: 500 !important;
77
+ color: #555 !important;
78
+ }
79
+ .stMetric > div:nth-child(2) > div { /* Metric value */
80
+ font-size: 1.6em !important;
81
+ font-weight: 600 !important;
82
+ color: #2c3e50 !important;
83
+ }
84
+
85
+
86
+ /* For maps */
87
+ .map-container {
88
+ border-radius: 12px;
89
+ overflow: hidden;
90
+ border: 1px solid #ddd;
91
+ box-shadow: 0 4px 8px rgba(0,0,0,0.05);
92
+ }
93
+
94
+ /* KPI badges (using Streamlit's delta color logic more directly) */
95
+ /* .stMetric [data-testid="stMetricDelta"] { ... } if specific styling is needed */
96
+
97
+
98
+ /* Data visualization enhancements */
99
+ .data-viz { /* For charts */
100
+ border-radius: 8px;
101
+ overflow: hidden;
102
+ border: 1px solid #eaeaea;
103
+ padding: 10px;
104
+ background-color: #fff;
105
+ }
106
+
107
+ /* Dividers */
108
+ hr {
109
+ margin: 30px 0;
110
+ border: 0;
111
+ height: 1px;
112
+ background-image: linear-gradient(to right, rgba(0, 0, 0, 0), rgba(44, 62, 80, 0.2), rgba(0, 0, 0, 0));
113
+ }
114
+
115
+ /* Button enhancements */
116
+ .stButton>button {
117
+ border-radius: 25px;
118
+ font-weight: 600;
119
+ padding: 10px 20px;
120
+ transition: all 0.2s ease-in-out;
121
+ border: 1px solid #3498db; /* Primary color border */
122
+ background-color: #3498db; /* Primary color */
123
+ color: white;
124
+ }
125
+ .stButton>button:hover {
126
+ transform: translateY(-2px);
127
+ box-shadow: 0 5px 10px rgba(52, 152, 219, 0.3);
128
+ background-color: #2980b9; /* Darker shade on hover */
129
+ border-color: #2980b9;
130
+ }
131
+ .stButton>button[kind="secondary"] { /* For reset button */
132
+ background-color: #e74c3c;
133
+ border-color: #e74c3c;
134
+ }
135
+ .stButton>button[kind="secondary"]:hover {
136
+ background-color: #c0392b;
137
+ border-color: #c0392b;
138
+ box-shadow: 0 5px 10px rgba(231, 76, 60, 0.3);
139
+ }
140
+
141
+
142
+ /* Tab styling */
143
+ .stTabs [data-baseweb="tab-list"] {
144
+ gap: 10px; /* Increased gap */
145
+ border-bottom: 2px solid #ddd; /* Underline for tab list */
146
+ }
147
+ .stTabs [data-baseweb="tab"] {
148
+ border-radius: 6px 6px 0px 0px;
149
+ padding: 12px 18px; /* More padding */
150
+ font-weight: 600; /* Bolder */
151
+ background-color: #f0f2f6; /* Light background for inactive tabs */
152
+ color: #555;
153
+ transition: background-color 0.2s, color 0.2s;
154
+ }
155
+ .stTabs [data-baseweb="tab--selected"] {
156
+ background-color: #3498db; /* Primary color for selected tab */
157
+ color: white;
158
+ border-bottom: 2px solid #3498db; /* Ensure it aligns with tab list border */
159
+ }
160
+
161
+ /* Primary header styling */
162
+ .main-header {
163
+ background: white;
164
+ color: #000080; /* Navy Blue - from original, kept for consistency */
165
+ padding: 15px 25px;
166
+ border-radius: 12px;
167
+ margin-bottom: 25px;
168
+ text-align: center;
169
+ box-shadow: 0 4px 10px rgba(0,0,0,0.1);
170
+ }
171
+ .main-header h1 {
172
+ margin: 0;
173
+ font-size: 2.2em;
174
+ font-weight: 700;
175
+ color: #2c3e50; /* Overriding the general h1 for this specific header */
176
+ text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
177
+ }
178
+
179
+ /* Warning box styling */
180
+ .warning-box {
181
+ background-color: #fff9e6; /* Lighter yellow */
182
+ border-left: 6px solid #ffc107;
183
+ color: #856404;
184
+ padding: 20px;
185
+ border-radius: 8px;
186
+ margin: 20px 0;
187
+ box-shadow: 0 2px 4px rgba(0,0,0,0.05);
188
+ }
189
+ .warning-box h3 {
190
+ margin-top: 0;
191
+ color: #856404; /* Match text color */
192
+ font-weight: 600;
193
+ }
194
+ .warning-box ul {
195
+ padding-left: 20px;
196
+ margin-bottom: 0;
197
+ }
198
+
199
+ /* KPI metrics overall container styling */
200
+ .kpi-grid {
201
+ display: grid;
202
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
203
+ gap: 15px;
204
+ margin-bottom: 20px;
205
+ }
206
+
207
+ /* Footer styling */
208
+ .footer {
209
+ margin-top: 40px;
210
+ text-align: center;
211
+ padding: 25px;
212
+ background-color: #34495e; /* Dark footer */
213
+ color: #ecf0f1; /* Light text for dark footer */
214
+ border-radius: 10px 10px 0 0; /* Rounded top corners */
215
+ font-size: 0.9em;
216
+ }
217
+ .footer a {
218
+ color: #3498db; /* Link color */
219
+ text-decoration: none;
220
+ }
221
+ .footer a:hover {
222
+ text-decoration: underline;
223
+ }
224
+
225
+ /* Search box enhancement */
226
+ .search-container .stTextInput input {
227
+ border-radius: 25px !important;
228
+ padding: 12px 20px !important;
229
+ border: 1px solid #bdc3c7 !important; /* Light gray border */
230
+ box-shadow: none !important; /* Remove default Streamlit shadow */
231
+ transition: border-color 0.2s, box-shadow 0.2s;
232
+ }
233
+ .search-container .stTextInput input:focus {
234
+ border-color: #3498db !important; /* Primary color on focus */
235
+ box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2) !important;
236
+ }
237
+
238
+ /* Styling for info/success messages */
239
+ .stAlert > div[data-baseweb="alert"] {
240
+ border-radius: 8px !important;
241
+ }
242
+
243
+ /* Section headers */
244
+ .section-header {
245
+ margin-top: 25px;
246
+ margin-bottom: 15px;
247
+ padding-bottom: 5px;
248
+ border-bottom: 2px solid #3498db; /* Primary color underline */
249
+ display: inline-block; /* To make border only as wide as text */
250
+ }
251
+ .section-header h4 {
252
+ margin-bottom: 0;
253
+ color: #3498db; /* Primary color for section titles */
254
+ }
255
+
256
+ /* Expander styling */
257
+ .stExpander {
258
+ border: 1px solid #e0e0e0 !important;
259
+ border-radius: 8px !important;
260
+ box-shadow: 0 2px 4px rgba(0,0,0,0.03) !important;
261
+ }
262
+ .stExpander header {
263
+ background-color: #f8f9fa !important;
264
+ border-radius: 8px 8px 0 0 !important; /* Match expander radius */
265
+ padding: 10px 15px !important;
266
+ }
267
+
268
+ </style>
269
+ """, unsafe_allow_html=True)
270
+
271
+ # --- Gemini API Key Handling ---
272
+ API_KEY = os.getenv("GOOGLE_API_KEY", "AIzaSyDkiYr-eSkqIXpZ1fHlik_YFsFtfQoFi0w") # Use yours, or allow env var
273
+ if not API_KEY or API_KEY == "YOUR_API_KEY_HERE": # Default check
274
+ st.sidebar.error("๐Ÿ”ด GOOGLE_API_KEY not set. Please set it as an environment variable or enter below.")
275
+ API_KEY = st.sidebar.text_input("Enter your Gemini API Key:", type="password", key="api_key_input_explorer_v4")
276
+
277
+ if API_KEY and API_KEY != "YOUR_API_KEY_HERE":
278
+ try:
279
+ genai.configure(api_key=API_KEY)
280
+ except Exception as e:
281
+ st.error(f"Error configuring Gemini API: {e}")
282
+ st.stop()
283
+ else:
284
+ st.error("๐Ÿ”ด Gemini API Key is required to run this application.")
285
+ st.stop()
286
+
287
+ # --- Services & Constants ---
288
+ geolocator = Nominatim(user_agent="india_landslide_explorer_v4")
289
+ FORECAST_DAYS = 14
290
+ SEISMIC_RADIUS_KM = 150
291
+ SEISMIC_MIN_MAGNITUDE = 4.0
292
+ SEISMIC_DAYS_AGO = 30
293
+
294
+ # --- Session State Initialization ---
295
+ if 'map_center_india' not in st.session_state: st.session_state.map_center_india = [20.5937, 78.9629]
296
+ if 'map_zoom_india' not in st.session_state: st.session_state.map_zoom_india = 4
297
+ if 'selected_lat_lon' not in st.session_state: st.session_state.selected_lat_lon = None
298
+ if 'location_name' not in st.session_state: st.session_state.location_name = ""
299
+ if 'exploration_output' not in st.session_state: st.session_state.exploration_output = {"kpi_data": {}, "detailed_text": {}}
300
+ if 'api_data_fetched' not in st.session_state: st.session_state.api_data_fetched = {}
301
+ if 'is_fetching_data' not in st.session_state: st.session_state.is_fetching_data = False
302
+
303
+
304
+ # --- Helper Functions (get_elevation, fetch_rainfall_data, fetch_seismic_data, reverse_geocode) ---
305
+ def get_elevation(lat, lon):
306
+ try:
307
+ url = f"https://api.open-meteo.com/v1/elevation?latitude={lat}&longitude={lon}"
308
+ response = requests.get(url, timeout=10)
309
+ response.raise_for_status()
310
+ data = response.json()
311
+ return data['elevation'][0]
312
+ except Exception: return "N/A"
313
+
314
+ def fetch_rainfall_data(lat, lon, forecast_days_count=FORECAST_DAYS):
315
+ url = "https://api.open-meteo.com/v1/forecast"
316
+ params = {
317
+ "latitude": lat, "longitude": lon,
318
+ "daily": "precipitation_sum,precipitation_hours",
319
+ "current": "precipitation,rain,showers,snowfall",
320
+ "forecast_days": forecast_days_count, "timezone": "auto"
321
+ }
322
+ try:
323
+ response = requests.get(url, params=params, timeout=15)
324
+ response.raise_for_status()
325
+ data = response.json()
326
+ current_data = data.get("current", {})
327
+ daily_data = data.get("daily", {})
328
+ df_daily_forecast = pd.DataFrame()
329
+ if daily_data.get("time") and daily_data.get("precipitation_sum"):
330
+ df_daily_forecast = pd.DataFrame({
331
+ "Date": pd.to_datetime(daily_data["time"]),
332
+ "Rainfall_Sum (mm)": daily_data["precipitation_sum"],
333
+ "Precipitation_Hours (hrs)": daily_data.get("precipitation_hours", [0]*len(daily_data["time"]))
334
+ }).set_index("Date")
335
+ return {
336
+ "current_precipitation_mm": current_data.get("precipitation", "N/A"),
337
+ "current_rain_mm": current_data.get("rain", "N/A"),
338
+ "current_showers_mm": current_data.get("showers", "N/A"),
339
+ "current_snowfall_cm": current_data.get("snowfall", "N/A"),
340
+ "daily_forecast_df": df_daily_forecast
341
+ }
342
+ except Exception as e:
343
+ st.toast(f"Weather fetch error: {e}", icon="๐ŸŒฆ๏ธ")
344
+ return {"current_precipitation_mm": "Error", "daily_forecast_df": pd.DataFrame()}
345
+
346
+ def fetch_seismic_data(lat, lon, radius_km=SEISMIC_RADIUS_KM, min_mag=SEISMIC_MIN_MAGNITUDE, days_ago=SEISMIC_DAYS_AGO):
347
+ try:
348
+ end_time = datetime.utcnow()
349
+ start_time = end_time - timedelta(days=days_ago)
350
+ url = "https://earthquake.usgs.gov/fdsnws/event/1/query"
351
+ params = {
352
+ "format": "geojson", "latitude": lat, "longitude": lon,
353
+ "maxradiuskm": radius_km, "minmagnitude": min_mag,
354
+ "starttime": start_time.strftime("%Y-%m-%dT%H:%M:%S"),
355
+ "endtime": end_time.strftime("%Y-%m-%dT%H:%M:%S"), "orderby": "time"
356
+ }
357
+ response = requests.get(url, params=params, timeout=15)
358
+ response.raise_for_status()
359
+ data = response.json()
360
+ earthquakes = []
361
+ for feature in data.get("features", []):
362
+ props = feature.get("properties", {}); geom = feature.get("geometry", {})
363
+ if props and geom and props.get("mag") is not None and geom.get("coordinates"):
364
+ earthquakes.append({
365
+ "place": props.get("place", "Unknown"), "magnitude": props.get("mag"),
366
+ "time": datetime.utcfromtimestamp(props.get("time") / 1000).strftime('%Y-%m-%d %H:%M UTC'),
367
+ "depth_km": geom.get("coordinates")[2] if len(geom.get("coordinates", [])) > 2 else "N/A",
368
+ "url": props.get("url")})
369
+ return earthquakes
370
+ except Exception as e:
371
+ st.toast(f"Seismic fetch error: {e}", icon="๐ŸŒ‹"); return []
372
+
373
+ def reverse_geocode(lat, lon):
374
+ try:
375
+ location = geolocator.reverse((lat, lon), exactly_one=True, timeout=10)
376
+ return location.address if location else "Unknown location"
377
+ except Exception: return "Could not determine address"
378
+
379
+ # --- Gemini Prompt and Parsing V4 ---
380
+ def get_gemini_exploration_v4(location_name, lat_lon, api_data):
381
+ model = genai.GenerativeModel('gemini-1.5-flash-latest')
382
+
383
+ elevation_str = f"{api_data.get('elevation_m', 'N/A')}"
384
+ weather_data = api_data.get('weather', {})
385
+ current_precip_str = f"{weather_data.get('current_precipitation_mm', 'N/A')}"
386
+ forecast_df = weather_data.get('daily_forecast_df')
387
+ forecast_summary_str = "N/A"
388
+ if forecast_df is not None and not forecast_df.empty:
389
+ summary_days = min(7, len(forecast_df))
390
+ forecast_days_summary = [f"Day {i+1} ({forecast_df.index[i].strftime('%Y-%m-%d')}): {forecast_df['Rainfall_Sum (mm)'].iloc[i] if pd.notna(forecast_df['Rainfall_Sum (mm)'].iloc[i]) else 'N/A'} mm" for i in range(summary_days)]
391
+ forecast_summary_str = "; ".join(forecast_days_summary) if forecast_days_summary else "No forecast data."
392
+ elif isinstance(forecast_df, pd.DataFrame) and forecast_df.empty:
393
+ forecast_summary_str = "Forecast data empty/unavailable."
394
+
395
+ seismic_events = api_data.get('seismic', [])
396
+ seismic_summary_str = "No significant recent seismic activity reported by USGS in the vicinity."
397
+ if seismic_events:
398
+ event_strs = [f"Mag {event['magnitude']} event near {event['place'].split('of')[-1].strip() if 'of' in event['place'] else event['place']}, on {event['time'].split(' ')[0]}" for event in seismic_events[:2]]
399
+ seismic_summary_str = "Recent Seismic Activity: " + "; ".join(event_strs)
400
+ if len(seismic_events) > 2: seismic_summary_str += f"; and {len(seismic_events)-2} more similar events."
401
+
402
+ prompt = f"""
403
+ You are an AI assistant for an advanced educational landslide factor exploration tool focused on INDIA (Version 4 - Visual Focus).
404
+ This tool DOES NOT use specific user observations of local conditions.
405
+ Your discussion will be based on the provided general location, fetched API data (elevation, weather, recent seismic activity), and your broad knowledge of Indian geography, geology, land cover, and climate.
406
+ This is strictly for educational purposes to explore POTENTIAL factors for a TYPE of area, NOT a real-time prediction or specific site assessment.
407
+
408
+ Location & Fetched Data:
409
+ - Approximate Location Name: "{location_name}" (Lat/Lon: {lat_lon[0]:.4f}, {lat_lon[1]:.4f})
410
+ - Elevation: {elevation_str} meters
411
+ - Current Precipitation Summary: {current_precip_str} mm
412
+ - Rainfall Forecast Summary (e.g., next 7 days): {forecast_summary_str}
413
+ - Recent Seismic Activity Summary (within ~{SEISMIC_RADIUS_KM}km, M{SEISMIC_MIN_MAGNITUDE}+, last {SEISMIC_DAYS_AGO} days): {seismic_summary_str}
414
+
415
+ Task:
416
+ Based on the above information and your general knowledge, please provide the following structured exploration.
417
+ First, provide specific KPI data, then provide the detailed textual explanations.
418
+
419
+ KPI_DATA_START
420
+ GENERAL_SUSCEPTIBILITY_LEVEL: [Provide one single category: Low / Moderate / High / Very High - based on typical regional characteristics for this type of area]
421
+ RAINFALL_IMPACT_ASSESSMENT: [Provide one single category: Low Concern / Moderate Concern / Significant Concern / High Concern - regarding its potential to trigger landslides in this type of area given the forecast and typical seasonal patterns]
422
+ SEISMIC_IMPACT_ASSESSMENT: [Provide one single category: Negligible / Low Potential / Moderate Potential / Significant Potential - as a landslide trigger in this type of area, considering reported activity and general regional seismicity]
423
+ TOP_HYPOTHETICAL_LANDSLIDE_TYPES: [List up to 3 most common/likely landslide types for similar regions in India, separated by commas, e.g., Debris Flow, Rockfall, Rotational Slump]
424
+ KEY_CONTRIBUTING_FACTORS_POINTS:
425
+ - [Brief point (max 10 words) on a key natural factor, e.g., Steep topography typical of the region]
426
+ - [Brief point (max 10 words) on a key human-induced factor, e.g., Unplanned construction if prevalent in similar areas]
427
+ - [Brief point (max 10 words) on another critical factor, e.g., Intense monsoon rainfall patterns]
428
+ TYPICAL_LAND_COVER_INFERRED: [Describe in 1-3 words the most typical general land cover you infer for this type of region, e.g., Forested Slopes, Agricultural Terraces, Urbanizing Hillsides, Barren Rocky Terrain]
429
+ KPI_DATA_END
430
+
431
+ Now, provide the detailed textual explanations, structured with the following headers:
432
+
433
+ HEADER_KEY_INSIGHTS_SUMMARY
434
+ Provide 2-3 bullet points elaborating on the most critical potential landslide-related insights or considerations for this TYPE of area in India, building upon the KPI data.
435
+
436
+ HEADER_SUSCEPTIBILITY_DISCUSSION
437
+ A. General Discussion of Landslide Susceptibility for this TYPE of Area:
438
+ (Elaborate on the GENERAL_SUSCEPTIBILITY_LEVEL. Discuss typical geological features, soil types, or topographical characteristics for this type of area. Ensure the output for GENERAL_SUSCEPTIBILITY_LEVEL provided in KPI_DATA_START is consistent with this discussion and includes "General Susceptibility for this type of area: " before the level, e.g., "General Susceptibility for this type of area: Moderate").
439
+
440
+ HEADER_DATA_ANALYSIS
441
+ B. Analysis of Fetched Data in Context of Potential Landslides:
442
+ (Elaborate on RAINFALL_IMPACT_ASSESSMENT and SEISMIC_IMPACT_ASSESSMENT. Discuss how fetched rainfall, elevation, and seismic data influence landslide potential, considering seasonal patterns and regional context).
443
+
444
+ HEADER_HYPOTHETICAL_FACTORS
445
+ C. Hypothetical Contributing Factors (Beyond Fetched Data):
446
+ (Elaborate on KEY_CONTRIBUTING_FACTORS_POINTS and TYPICAL_LAND_COVER_INFERRED. Discuss typical land cover and other natural/human-induced factors common to such regions in India).
447
+
448
+ HEADER_COMMON_LANDSLIDE_TYPES
449
+ D. Common Landslide Types in Similar Indian Regions:
450
+ (Elaborate on TOP_HYPOTHETICAL_LANDSLIDE_TYPES. Describe their characteristics and triggers relevant to the scenario).
451
+
452
+ HEADER_CRITICAL_LOCAL_DATA_NEED
453
+ E. Critical Importance of Local Site-Specific Data (Emphasize very strongly!):
454
+ (Explain why absence of local observations makes specific risk assessment impossible. Detail necessary local data).
455
+
456
+ HEADER_AWARENESS_PREPAREDNESS
457
+ F. General Awareness & Preparedness Ideas (India Context):
458
+ (Suggest general, non-site-specific educational points on landslide awareness/preparedness).
459
+
460
+ HEADER_OFFICIAL_RESOURCES
461
+ G. Official Indian Resources & Further Learning:
462
+ (List key Indian government agencies and information sources).
463
+
464
+ Structure your response exactly with the specified KPI_DATA_START/END and HEADER_ SECTION NAMES.
465
+ Maintain an educational tone. Explicitly and repeatedly state the limitations.
466
+ """
467
+ try:
468
+ response = model.generate_content(prompt)
469
+ return response.text
470
+ except Exception as e:
471
+ st.error(f"Error communicating with Gemini API: {e}")
472
+ return None
473
+
474
+ def parse_gemini_output_v4(text):
475
+ if not text: return {"kpi_data": {}, "detailed_text": {}}
476
+
477
+ kpi_data = {}
478
+ default_kpi_values = {
479
+ "GENERAL_SUSCEPTIBILITY_LEVEL": "N/A",
480
+ "RAINFALL_IMPACT_ASSESSMENT": "N/A",
481
+ "SEISMIC_IMPACT_ASSESSMENT": "N/A",
482
+ "TOP_HYPOTHETICAL_LANDSLIDE_TYPES": "Not specified",
483
+ "KEY_CONTRIBUTING_FACTORS_POINTS": [],
484
+ "TYPICAL_LAND_COVER_INFERRED": "N/A"
485
+ }
486
+ kpi_data.update(default_kpi_values)
487
+
488
+ detailed_text_sections_map = {
489
+ "HEADER_KEY_INSIGHTS_SUMMARY": "๐Ÿ”‘ Key Insights Summary",
490
+ "HEADER_SUSCEPTIBILITY_DISCUSSION": "๐Ÿง General Susceptibility Discussion",
491
+ "HEADER_DATA_ANALYSIS": "๐Ÿ“Š Analysis of Fetched Data",
492
+ "HEADER_HYPOTHETICAL_FACTORS": "๐Ÿค” Contributing Factors",
493
+ "HEADER_COMMON_LANDSLIDE_TYPES": "๐Ÿž๏ธ Common Landslide Types",
494
+ "HEADER_CRITICAL_LOCAL_DATA_NEED": "โ—CRUCIAL: Need for Local Site-Specific Dataโ—",
495
+ "HEADER_AWARENESS_PREPAREDNESS": "๐Ÿ’ก General Awareness & Preparedness",
496
+ "HEADER_OFFICIAL_RESOURCES": "๐Ÿ‡ฎ๐Ÿ‡ณ Official Resources & Further Learning"
497
+ }
498
+ parsed_detailed_text = {display_name: [] for _, display_name in detailed_text_sections_map.items()}
499
+
500
+ in_kpi_section = False
501
+ current_detailed_section_key = None
502
+ key_factors_collecting = False
503
+
504
+ kpi_regex_map = {
505
+ "GENERAL_SUSCEPTIBILITY_LEVEL": re.compile(r"GENERAL_SUSCEPTIBILITY_LEVEL:\s*(.+)", re.IGNORECASE),
506
+ "RAINFALL_IMPACT_ASSESSMENT": re.compile(r"RAINFALL_IMPACT_ASSESSMENT:\s*(.+)", re.IGNORECASE),
507
+ "SEISMIC_IMPACT_ASSESSMENT": re.compile(r"SEISMIC_IMPACT_ASSESSMENT:\s*(.+)", re.IGNORECASE),
508
+ "TOP_HYPOTHETICAL_LANDSLIDE_TYPES": re.compile(r"TOP_HYPOTHETICAL_LANDSLIDE_TYPES:\s*(.+)", re.IGNORECASE),
509
+ "TYPICAL_LAND_COVER_INFERRED": re.compile(r"TYPICAL_LAND_COVER_INFERRED:\s*(.+)", re.IGNORECASE),
510
+ }
511
+
512
+ for line in text.splitlines():
513
+ line_strip = line.strip()
514
+ if not line_strip: continue
515
+
516
+ if line_strip == "KPI_DATA_START":
517
+ in_kpi_section = True; continue
518
+ if line_strip == "KPI_DATA_END":
519
+ in_kpi_section = False; key_factors_collecting = False; continue
520
+
521
+ if in_kpi_section:
522
+ matched_specific_kpi = False
523
+ for key, pattern in kpi_regex_map.items():
524
+ match = pattern.match(line_strip)
525
+ if match:
526
+ kpi_data[key] = match.group(1).strip()
527
+ matched_specific_kpi = True; break
528
+ if matched_specific_kpi: continue
529
+
530
+ if line_strip.startswith("KEY_CONTRIBUTING_FACTORS_POINTS:"):
531
+ key_factors_collecting = True; kpi_data["KEY_CONTRIBUTING_FACTORS_POINTS"] = [] # Reset for new parse
532
+ continue
533
+
534
+ if key_factors_collecting and line_strip.startswith("-"):
535
+ kpi_data["KEY_CONTRIBUTING_FACTORS_POINTS"].append(line_strip.lstrip("- ").strip())
536
+ continue
537
+
538
+ found_new_header = False
539
+ for header_key_from_prompt, display_name in detailed_text_sections_map.items():
540
+ if line_strip == header_key_from_prompt:
541
+ current_detailed_section_key = display_name
542
+ found_new_header = True; break
543
+ if not found_new_header and current_detailed_section_key:
544
+ parsed_detailed_text[current_detailed_section_key].append(line)
545
+
546
+ final_detailed_text = {k: "\n".join(v).strip() for k, v in parsed_detailed_text.items()}
547
+ return {"kpi_data": kpi_data, "detailed_text": final_detailed_text}
548
+
549
+ # --- UI Rendering with Enhanced Styling ---
550
+ st.markdown('<div class="main-header"><h1>๐Ÿ‡ฎ๐Ÿ‡ณ India Landslide Factor Explorer V4</h1></div>', unsafe_allow_html=True)
551
+ st.caption("Educational Tool by Google Gemini & Streamlit - Exploring Potential Landslide Factors")
552
+
553
+
554
+
555
+
556
+ st.markdown("""
557
+ <div class="card">
558
+ <h3>๐Ÿ—บ๏ธ How to Use This Tool</h3>
559
+ <p>Welcome! Begin by <strong>selecting a location on the map</strong> or using the <strong>search bar</strong> to find a specific place in India.
560
+ The tool will then fetch publicly available data (elevation, weather forecast, recent seismic activity) for the chosen area.
561
+ After data retrieval, you can initiate an AI-powered exploration. The AI will provide a <em>generalized discussion</em> on potential landslide susceptibility and contributing factors relevant to that <strong>type of area in India</strong>, based on the fetched data and its broad geographical knowledge.</p>
562
+ </div>
563
+ """, unsafe_allow_html=True)
564
+
565
+ st.markdown("""
566
+ <div class="warning-box">
567
+ <h3>โš ๏ธ CRITICAL DISCLAIMER & LIMITATIONS</h3>
568
+ <ul>
569
+ <li>This tool <strong>DOES NOT use any specific local observations or detailed site-specific geotechnical data</strong>.</li>
570
+ <li>The AI-generated discussion is <strong>HIGHLY GENERALIZED, HYPOTHETICAL, and intended for BROAD EDUCATIONAL PURPOSES ONLY</strong>.</li>
571
+ <li><strong>IT IS NOT A PREDICTION, nor a real-time warning system, nor a site-specific risk assessment.</strong> It cannot replace professional engineering or geological surveys.</li>
572
+ <li>For actual safety information, risk assessment, or emergency guidance, <strong>ALWAYS consult official Indian government authorities</strong> (like NDMA, GSI) and qualified local geotechnical experts.</li>
573
+ </ul>
574
+ </div>
575
+ """, unsafe_allow_html=True)
576
+
577
+ col_map_input, col_ai_output = st.columns([0.45, 0.55]) # Adjusted column ratio
578
+
579
+ with col_map_input:
580
+ st.markdown('<div class="card">', unsafe_allow_html=True) # Wrap entire input column in a card
581
+ st.markdown('<div class="section-header"><h4>๐Ÿ“ Select Location & View Data</h4></div>', unsafe_allow_html=True)
582
+
583
+ st.markdown('<div class="search-container">', unsafe_allow_html=True)
584
+ search_location_input = st.text_input(
585
+ "Search for a location in India:",
586
+ key="search_loc_v4",
587
+ placeholder="e.g., Shimla, Munnar, Darjeeling..."
588
+ )
589
+ st.markdown('</div>', unsafe_allow_html=True)
590
+
591
+ search_btn_col, reset_btn_col = st.columns([3,1])
592
+ with search_btn_col:
593
+ if st.button("๐Ÿ” Search Location", key="search_btn_v4", use_container_width=True):
594
+ if search_location_input:
595
+ with st.spinner(f"Searching for '{search_location_input}'..."):
596
+ try:
597
+ loc = geolocator.geocode(search_location_input + ", India", timeout=10)
598
+ if loc:
599
+ st.session_state.selected_lat_lon = [loc.latitude, loc.longitude]
600
+ st.session_state.map_center_india = [loc.latitude, loc.longitude]
601
+ st.session_state.map_zoom_india = 11
602
+ st.session_state.location_name = loc.address
603
+ st.session_state.api_data_fetched = {}
604
+ st.session_state.exploration_output = {"kpi_data": {}, "detailed_text": {}}
605
+ st.session_state.is_fetching_data = True # Trigger data fetching
606
+ st.toast(f"๐Ÿ—บ๏ธ Location found: {loc.address.split(',')[0]}. Fetching data...", icon="โœ…")
607
+ st.rerun()
608
+ else:
609
+ st.warning(f"โŒ Could not find '{search_location_input}'. Please try a different or more specific name.")
610
+ except Exception as e:
611
+ st.error(f"Geocoding error: {e}")
612
+ else:
613
+ st.info("Please enter a location name to search.")
614
+ with reset_btn_col:
615
+ if st.button("๐Ÿ”„ Reset", key="reset_btn_v4", use_container_width=True, type="secondary"):
616
+ st.session_state.selected_lat_lon = None
617
+ st.session_state.map_center_india = [20.5937, 78.9629]
618
+ st.session_state.map_zoom_india = 4
619
+ st.session_state.location_name = ""
620
+ st.session_state.api_data_fetched = {}
621
+ st.session_state.exploration_output = {"kpi_data": {}, "detailed_text": {}}
622
+ st.session_state.is_fetching_data = False
623
+ st.toast("๐Ÿ”„ Map & selection reset.", icon="๐Ÿ—บ๏ธ")
624
+ st.rerun()
625
+
626
+
627
+ st.markdown('<div class="map-container">', unsafe_allow_html=True)
628
+ st.markdown("<small><i>Click on the map to select a point, or use search above.</i></small>", unsafe_allow_html=True)
629
+ folium_map_display = folium.Map(
630
+ location=st.session_state.map_center_india,
631
+ zoom_start=st.session_state.map_zoom_india,
632
+ tiles="CartoDB positron",
633
+ key="folium_map_v4_instance" # Ensure unique key if map is complex
634
+ )
635
+ if st.session_state.selected_lat_lon:
636
+ folium.Marker(
637
+ st.session_state.selected_lat_lon,
638
+ popup=f"Selected: {st.session_state.location_name.split(',')[0]}" if st.session_state.location_name else "Selected Point",
639
+ tooltip="Current Selection",
640
+ icon=folium.Icon(color="red", icon="info-sign")
641
+ ).add_to(folium_map_display)
642
+
643
+ map_interaction_data = st_folium(
644
+ folium_map_display,
645
+ width="100%",
646
+ height=330,
647
+ key="map_v4_interaction",
648
+ returned_objects=["last_clicked"]
649
+ )
650
+ st.markdown('</div>', unsafe_allow_html=True)
651
+
652
+ if map_interaction_data and map_interaction_data.get("last_clicked"):
653
+ clicked_lat = map_interaction_data["last_clicked"]["lat"]
654
+ clicked_lon = map_interaction_data["last_clicked"]["lng"]
655
+ if st.session_state.selected_lat_lon is None or \
656
+ abs(st.session_state.selected_lat_lon[0] - clicked_lat) > 0.00001 or \
657
+ abs(st.session_state.selected_lat_lon[1] - clicked_lon) > 0.00001:
658
+ st.session_state.selected_lat_lon = [clicked_lat, clicked_lon]
659
+ st.session_state.location_name = reverse_geocode(clicked_lat, clicked_lon)
660
+ st.session_state.map_center_india = [clicked_lat, clicked_lon] # Recenter map
661
+ st.session_state.map_zoom_india = max(st.session_state.map_zoom_india, 11) # Zoom in
662
+ st.session_state.api_data_fetched = {}
663
+ st.session_state.exploration_output = {"kpi_data": {}, "detailed_text": {}}
664
+ st.session_state.is_fetching_data = True # Trigger data fetching
665
+ st.toast(f"๐Ÿ“ Pinned: {st.session_state.location_name.split(',')[0]}. Fetching data...", icon="๐Ÿ—บ๏ธ")
666
+ st.rerun()
667
+
668
+ explore_button_active = False
669
+ if st.session_state.selected_lat_lon:
670
+ st.success(f"**Selected Location:** {st.session_state.location_name}\n(Lat: {st.session_state.selected_lat_lon[0]:.4f}, Lon: {st.session_state.selected_lat_lon[1]:.4f})")
671
+
672
+ if st.session_state.is_fetching_data and not st.session_state.api_data_fetched: # Fetch data only if flag is true and not fetched
673
+ with st.spinner(f"โณ Fetching environmental data for {st.session_state.location_name.split(',')[0]}... This might take a few seconds."):
674
+ lat, lon = st.session_state.selected_lat_lon
675
+ api_data_temp = {}
676
+ api_data_temp['elevation_m'] = get_elevation(lat, lon)
677
+ api_data_temp['weather'] = fetch_rainfall_data(lat, lon)
678
+ api_data_temp['seismic'] = fetch_seismic_data(lat, lon)
679
+ st.session_state.api_data_fetched = api_data_temp
680
+ st.session_state.is_fetching_data = False # Reset flag
681
+ st.rerun() # Rerun to display fetched data
682
+
683
+ if st.session_state.api_data_fetched: # Display fetched data
684
+ st.markdown('<div class="data-card">', unsafe_allow_html=True)
685
+ st.markdown("##### ๐Ÿ›ฐ๏ธ Fetched Environmental Data:")
686
+ api_data = st.session_state.api_data_fetched
687
+ elev = api_data.get('elevation_m', 'N/A')
688
+ weather = api_data.get('weather', {})
689
+ curr_precip = weather.get('current_precipitation_mm', 'N/A')
690
+ seismic_events = api_data.get('seismic', [])
691
+
692
+ data_cols = st.columns(2)
693
+ with data_cols[0]:
694
+ st.metric(label="๐Ÿ”๏ธ Elevation", value=f"{elev} m" if elev != "N/A" else "N/A")
695
+ with data_cols[1]:
696
+ st.metric(label="๐Ÿ’ง Current Precip.", value=f"{curr_precip} mm" if curr_precip not in ["N/A", "Error"] else curr_precip)
697
+
698
+ with st.expander(f"๐ŸŒ‹ Seismic Activity (Last {SEISMIC_DAYS_AGO} days, M{SEISMIC_MIN_MAGNITUDE}+, ~{SEISMIC_RADIUS_KM}km radius)", expanded=len(seismic_events) > 0):
699
+ if seismic_events:
700
+ st.caption(f"Found {len(seismic_events)} significant earthquake(s) reported by USGS:")
701
+ for event in seismic_events[:5]:
702
+ st.markdown(f"- **M {event['magnitude']}** - {event['place']} ({event['time']}). Depth: {event['depth_km']} km. [More Info]({event.get('url', '#')})", unsafe_allow_html=True)
703
+ if len(seismic_events) > 5: st.caption(f"...and {len(seismic_events)-5} more.")
704
+ else:
705
+ st.caption("No significant recent seismic activity reported by USGS matching criteria.")
706
+
707
+ st.markdown("##### ๐ŸŒฆ๏ธ Rainfall Forecast (mm/day):")
708
+ forecast_df = weather.get('daily_forecast_df')
709
+ if forecast_df is not None and not forecast_df.empty:
710
+ st.markdown('<div class="data-viz">', unsafe_allow_html=True)
711
+ st.line_chart(forecast_df['Rainfall_Sum (mm)'], height=180)
712
+ st.markdown('</div>', unsafe_allow_html=True)
713
+ cum_rain = forecast_df['Rainfall_Sum (mm)'].cumsum()
714
+ periods = [3, 7, min(FORECAST_DAYS, len(cum_rain))]
715
+ st.markdown("**Cumulative Rainfall Forecast:**")
716
+ cum_cols_display = st.columns(len(periods))
717
+ for i, p_days in enumerate(periods):
718
+ if 0 < p_days <= len(cum_rain):
719
+ val = cum_rain.iloc[p_days-1]
720
+ with cum_cols_display[i]:
721
+ st.metric(label=f"{p_days}-Day Total", value=f"{val:.1f}mm" if pd.notna(val) else "N/A")
722
+ else:
723
+ st.caption("Rainfall forecast data unavailable or encountered an error.")
724
+ st.markdown('</div>', unsafe_allow_html=True) # End data-card
725
+
726
+ if elev != "N/A" and curr_precip not in ["N/A", "Error"]: # Enable button if core data is present
727
+ explore_button_active = True
728
+ else: # No location selected
729
+ st.info("๐Ÿ‘ˆ Please select a location on the map or use the search bar to begin.")
730
+
731
+ if explore_button_active:
732
+ if st.button("๐Ÿค– Explore Potential Factors with AI", type="primary", use_container_width=True, key="explore_btn_v4"):
733
+ if st.session_state.selected_lat_lon and st.session_state.api_data_fetched:
734
+ with st.spinner("๐Ÿ’ก Gemini AI is analyzing... This may take a moment for a comprehensive exploration."):
735
+ raw_gemini_output = get_gemini_exploration_v4(
736
+ st.session_state.location_name,
737
+ st.session_state.selected_lat_lon,
738
+ st.session_state.api_data_fetched
739
+ )
740
+ if raw_gemini_output:
741
+ st.session_state.exploration_output = parse_gemini_output_v4(raw_gemini_output)
742
+ st.toast("โœ… AI Exploration complete!", icon="๐Ÿ’ก")
743
+ else:
744
+ st.error("AI exploration failed. Please check API key or try again later.")
745
+ else:
746
+ st.warning("Please select a location and ensure data is fetched before exploring.")
747
+ elif st.session_state.selected_lat_lon and not st.session_state.api_data_fetched and not st.session_state.is_fetching_data:
748
+ st.warning("Data for the selected location is still fetching or incomplete. AI exploration is disabled until data is ready.")
749
+
750
+ st.markdown('</div>', unsafe_allow_html=True) # End of card for col_map_input
751
+
752
+ with col_ai_output:
753
+ st.markdown('<div class="card">', unsafe_allow_html=True) # Wrap entire AI output column in a card
754
+ st.markdown('<div class="section-header"><h4>๐ŸŒ AI-Powered Exploration (Generalized)</h4></div>', unsafe_allow_html=True)
755
+
756
+ output_data = st.session_state.exploration_output
757
+ kpi_results = output_data.get("kpi_data", {})
758
+ detailed_results = output_data.get("detailed_text", {})
759
+
760
+ if kpi_results and any(val != "N/A" and val != "Not specified" and val for val in kpi_results.values()):
761
+ st.markdown("##### ๐Ÿ“Š Key Indicators (AI Inferred for this Type of Area):")
762
+ st.markdown('<div class="kpi-grid">', unsafe_allow_html=True)
763
+
764
+ sus_level = kpi_results.get("GENERAL_SUSCEPTIBILITY_LEVEL", "N/A")
765
+ sus_delta_color = "normal"
766
+ if "low" in sus_level.lower(): sus_delta_color = "normal"
767
+ elif "moderate" in sus_level.lower(): sus_delta_color = "off"
768
+ elif "high" in sus_level.lower() or "very high" in sus_level.lower(): sus_delta_color = "inverse"
769
+ st.metric(label="๐Ÿ”๏ธ General Susceptibility", value=sus_level, delta_color=sus_delta_color, help="AI's assessment of general landslide susceptibility for this type of area in India, based on broad knowledge.")
770
+
771
+ rain_impact = kpi_results.get("RAINFALL_IMPACT_ASSESSMENT", "N/A")
772
+ rain_delta_color = "normal"
773
+ if "low" in rain_impact.lower(): rain_delta_color = "normal"
774
+ elif "moderate" in rain_impact.lower(): rain_delta_color = "off"
775
+ elif "significant" in rain_impact.lower() or "high" in rain_impact.lower(): rain_delta_color = "inverse"
776
+ st.metric(label="๐Ÿ’ง Rainfall Impact", value=rain_impact, delta_color=rain_delta_color, help="AI's assessment of rainfall's potential role, considering forecast and typical seasonal patterns for the area type.")
777
+
778
+ seismic_impact = kpi_results.get("SEISMIC_IMPACT_ASSESSMENT", "N/A")
779
+ seis_delta_color = "normal"
780
+ if "negligible" in seismic_impact.lower() or "low" in seismic_impact.lower(): seis_delta_color = "normal"
781
+ elif "moderate" in seismic_impact.lower(): seis_delta_color = "off"
782
+ elif "significant" in seismic_impact.lower(): seis_delta_color = "inverse"
783
+ st.metric(label="๐ŸŒ‹ Seismic Impact", value=seismic_impact, delta_color=seis_delta_color, help="AI's assessment of seismic activity's potential role as a trigger for this type of area.")
784
+ st.markdown('</div>', unsafe_allow_html=True) # End kpi-grid
785
+ st.markdown("---")
786
+
787
+ col_kpi_list1, col_kpi_list2 = st.columns(2)
788
+ with col_kpi_list1:
789
+ st.markdown("##### ๐Ÿž๏ธ Top Landslide Types:")
790
+ top_types_str = kpi_results.get("TOP_HYPOTHETICAL_LANDSLIDE_TYPES", "Not specified by AI.")
791
+ top_types_list = [s.strip() for s in top_types_str.split(',') if s.strip()]
792
+ if top_types_list and top_types_list[0].lower() != "not specified":
793
+ for l_type in top_types_list: st.markdown(f"- {l_type}")
794
+ else: st.caption(top_types_str)
795
+
796
+ with col_kpi_list2:
797
+ st.markdown("##### ๐ŸŒณ Typical Land Cover (Inferred):")
798
+ land_cover = kpi_results.get("TYPICAL_LAND_COVER_INFERRED", "Not specified by AI.")
799
+ st.info(f"{land_cover}")
800
+
801
+
802
+ st.markdown("##### ๐Ÿ”‘ Key Contributing Factors:")
803
+ key_factors = kpi_results.get("KEY_CONTRIBUTING_FACTORS_POINTS", [])
804
+ if key_factors and isinstance(key_factors, list) and any(key_factors):
805
+ for factor in key_factors: st.markdown(f"- _{factor}_")
806
+ else: st.caption("Not specified or N/A by AI.")
807
+
808
+ st.markdown("---")
809
+ st.markdown("##### ๐Ÿ’ฌ Detailed AI Exploration Text:")
810
+ tab_titles = [key for key in detailed_results.keys() if detailed_results[key]]
811
+ if tab_titles:
812
+ tabs = st.tabs(tab_titles)
813
+ for i, title in enumerate(tab_titles):
814
+ with tabs[i]:
815
+ st.markdown(detailed_results[title], unsafe_allow_html=True) # Allow HTML for Gemini's formatting
816
+ else:
817
+ st.warning("AI exploration did not yield detailed textual content. The API might have had an issue or the prompt needs adjustment.")
818
+ if 'gemini_raw_output_debug' in st.session_state and st.session_state['gemini_raw_output_debug']:
819
+ with st.expander("Show Raw Gemini Output (for debugging)"):
820
+ st.text_area("Raw Output:", st.session_state['gemini_raw_output_debug'], height=200)
821
+
822
+ elif st.session_state.selected_lat_lon and explore_button_active:
823
+ st.info("๐Ÿค– Click the 'Explore Potential Factors with AI' button on the left panel after data for the selected location has been fetched. The AI's insights will appear here.")
824
+ elif not st.session_state.selected_lat_lon:
825
+ st.info("๐Ÿ‘ˆ Please select a location in the left panel first. AI exploration results will then be generated and displayed here.")
826
+ else:
827
+ st.info("AI exploration results will appear here once a location is selected, data is fetched, and the AI analysis is run.")
828
+
829
+ st.markdown("---")
830
+ st.markdown('<div class="section-header"><h4>๐Ÿ‡ฎ๐Ÿ‡ณ Official Indian Resources</h4></div>', unsafe_allow_html=True)
831
+ st.markdown("""
832
+ For accurate, official, and site-specific landslide information and warnings in India, please consult these primary resources:
833
+ - **National Disaster Management Authority (NDMA):** [ndma.gov.in](https://ndma.gov.in) - For national guidelines and disaster management.
834
+ - **Geological Survey of India (GSI):** [gsi.gov.in](https://www.gsi.gov.in/) - For geological data, landslide hazard zonation maps.
835
+ - **National Remote Sensing Centre (NRSC) Bhuvan Portal (ISRO):** [bhuvan.nrsc.gov.in](https://bhuvan.nrsc.gov.in/bhuvan_links.php) - For satellite imagery, thematic maps & disaster related services.
836
+ - **India Meteorological Department (IMD):** [mausam.imd.gov.in](https://mausam.imd.gov.in/) - For weather forecasts and warnings.
837
+ - **Your local State Disaster Management Authority (SDMA)** website (search for your state's SDMA).
838
+ """, unsafe_allow_html=True)
839
+ st.markdown('</div>', unsafe_allow_html=True) # End of card for col_ai_output
840
+
841
+
842
+ st.markdown("---")
843
+ st.markdown(
844
+ """
845
+ <div class="footer">
846
+ <p><strong>Tool Version:</strong> Explorer 4.0 Enhanced UI</p>
847
+ <p>This is an <strong>educational tool</strong> for exploring POTENTIAL landslide factors based on generalized knowledge and limited public data.
848
+ It <strong>DOES NOT</strong> provide official warnings, site-specific risk assessments, or professional geotechnical advice.
849
+ Real-world landslide analysis requires extensive, detailed local data and expert assessment by qualified professionals.
850
+ Always refer to official government sources for safety and risk information.</p>
851
+ <p>Powered by <a href="https://streamlit.io" target="_blank">Streamlit</a> and <a href="https://ai.google.dev/" target="_blank">Google Gemini</a>.</p>
852
+ </div>
853
+ """, unsafe_allow_html=True
854
+ )