File size: 30,829 Bytes
97d418a | 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 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 | """
Dam Intelligence Dashboard - Complete Application
Interactive AI-Driven Digital Twin Dashboard for Dam Watershed Intelligence
ICGSTD Workshop - October 29, 2025
"""
import dash
from dash import dcc, html, Input, Output, State, callback_context
import dash_bootstrap_components as dbc
import dash_daq as daq
import dash_leaflet as dl
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import json
import os
# Try to import GEE (optional for deployment)
try:
import ee
import geemap
# Initialize Earth Engine with service account
SERVICE_ACCOUNT = os.environ.get('GEE_SERVICE_ACCOUNT', '')
KEY_DATA = os.environ.get('GEE_KEY_DATA', '')
if SERVICE_ACCOUNT and KEY_DATA:
credentials = ee.ServiceAccountCredentials(
email=SERVICE_ACCOUNT,
key_data=KEY_DATA
)
ee.Initialize(credentials=credentials)
GEE_INITIALIZED = True
else:
ee.Initialize()
GEE_INITIALIZED = True
except:
GEE_INITIALIZED = False
print("Warning: Running without Google Earth Engine connection")
# ==================== CONFIGURATION ====================
# Dam database
DAM_DATABASE = {
'Aswan High Dam': {
'coords': [32.877, 23.970],
'country': 'Egypt',
'climate': 'Arid',
'capacity_km3': 169,
'watershed_km2': 2800000
},
'Three Gorges Dam': {
'coords': [111.003, 30.823],
'country': 'China',
'climate': 'Subtropical',
'capacity_km3': 39.3,
'watershed_km2': 1000000
},
'Hoover Dam': {
'coords': [-114.738, 36.016],
'country': 'USA',
'climate': 'Desert',
'capacity_km3': 35.2,
'watershed_km2': 435000
},
'Kariba Dam': {
'coords': [28.760, -16.520],
'country': 'Zimbabwe/Zambia',
'climate': 'Tropical',
'capacity_km3': 180,
'watershed_km2': 663000
},
'Beni Haroun Dam': {
'coords': [6.269, 36.551],
'country': 'Algeria',
'climate': 'Mediterranean',
'capacity_km3': 0.96,
'watershed_km2': 7725
}
}
# Color scheme
COLORS = {
'primary': '#1e88e5',
'success': '#43a047',
'warning': '#fb8c00',
'danger': '#e53935',
'info': '#00acc1',
'dark': '#37474f',
'light': '#eceff1'
}
# ==================== DATA FUNCTIONS ====================
def generate_sample_data(dam_name, start_date, end_date):
"""Generate sample time series data for demonstration"""
dates = pd.date_range(start=start_date, end=end_date, freq='MS')
n = len(dates)
# Base patterns with seasonal variation
water_area = 500 + 100*np.sin(np.arange(n)*2*np.pi/12) + np.random.normal(0, 20, n)
precipitation = 60 + 40*np.sin(np.arange(n)*2*np.pi/12 + np.pi) + np.random.normal(0, 10, n)
temperature = 25 + 10*np.sin(np.arange(n)*2*np.pi/12) + np.random.normal(0, 2, n)
ndvi = 0.4 + 0.2*np.sin(np.arange(n)*2*np.pi/12) + np.random.normal(0, 0.05, n)
# Create DataFrame
df = pd.DataFrame({
'date': dates,
'water_area_km2': water_area,
'precipitation_mm': precipitation,
'temperature_c': temperature,
'ndvi': ndvi,
'water_level_m': 150 + water_area/10 + np.random.normal(0, 2, n)
})
# Calculate derived metrics
df['flood_risk'] = np.clip(((df['water_area_km2'] - 450) / 100 * 30 +
(df['precipitation_mm'] - 50) / 50 * 20), 0, 100)
df['drought_risk'] = np.clip((100 - df['flood_risk'] -
(df['precipitation_mm'] / 100 * 50)), 0, 100)
df['environmental_score'] = np.clip(70 + df['ndvi'] * 50 -
abs(df['water_area_km2'] - 500) / 10, 0, 100)
return df
def fetch_gee_data(dam_coords, start_date, end_date):
"""Fetch real data from Google Earth Engine (if available)"""
if not GEE_INITIALIZED:
return None
try:
point = ee.Geometry.Point(dam_coords)
region = point.buffer(20000) # 20km buffer
# Fetch Sentinel-2 data
collection = ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED') \
.filterBounds(region) \
.filterDate(start_date, end_date) \
.filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20))
# Calculate monthly NDWI
def calculate_ndwi(image):
ndwi = image.normalizedDifference(['B3', 'B8'])
return image.addBands(ndwi.rename('ndwi'))
with_ndwi = collection.map(calculate_ndwi)
# Get time series
def extract_data(image):
stats = image.select('ndwi').reduceRegion(
reducer=ee.Reducer.mean(),
geometry=region,
scale=30,
maxPixels=1e9
)
return ee.Feature(None, {
'date': image.date().format('YYYY-MM-dd'),
'ndwi': stats.get('ndwi')
})
features = with_ndwi.map(extract_data)
data = features.getInfo()
# Convert to DataFrame
df = pd.DataFrame([f['properties'] for f in data['features']])
df['date'] = pd.to_datetime(df['date'])
return df
except Exception as e:
print(f"Error fetching GEE data: {e}")
return None
# ==================== LAYOUT COMPONENTS ====================
def create_header():
"""Create dashboard header"""
return dbc.Navbar(
dbc.Container([
dbc.Row([
dbc.Col([
html.Img(src="https://cdn-icons-png.flaticon.com/512/2454/2454348.png",
height="40px", className="me-3"),
html.Div([
html.H3("Dam Intelligence System", className="text-white mb-0"),
html.P("AI-Driven Digital Twin Dashboard", className="text-white-50 mb-0 small")
], className="d-inline-block align-middle")
], width="auto"),
dbc.Col([
html.Div([
dbc.Badge("LIVE", color="success", className="me-2"),
html.Span(datetime.now().strftime("%Y-%m-%d %H:%M"),
id="current-time", className="text-white")
], className="text-end")
], className="ms-auto")
], align="center", className="g-0 w-100")
], fluid=True, className="py-2"),
color="primary",
dark=True,
className="mb-3"
)
def create_control_panel():
"""Create control panel for dam selection and parameters"""
return dbc.Card([
dbc.CardHeader([
html.I(className="fas fa-sliders-h me-2"),
html.Span("Control Panel")
], className="fw-bold"),
dbc.CardBody([
# Dam selector
html.Label("Select Dam:", className="fw-bold mb-2"),
dcc.Dropdown(
id="dam-selector",
options=[{"label": f"{dam} ({info['country']})", "value": dam}
for dam, info in DAM_DATABASE.items()],
value="Aswan High Dam",
className="mb-3"
),
# Dam info display
html.Div(id="dam-info", className="mb-3 p-2 bg-light rounded"),
html.Hr(),
# Date range selector
html.Label("Analysis Period:", className="fw-bold mb-2"),
dcc.DatePickerRange(
id="date-range",
start_date=datetime.now() - timedelta(days=730),
end_date=datetime.now(),
display_format="MMM Y",
className="mb-3 w-100"
),
html.Hr(),
# Analysis layers
html.Label("Active Layers:", className="fw-bold mb-2"),
dbc.Checklist(
id="layer-selector",
options=[
{"label": " Water Extent", "value": "water"},
{"label": " Precipitation", "value": "precip"},
{"label": " Vegetation (NDVI)", "value": "vegetation"},
{"label": " Temperature", "value": "temp"},
{"label": " Risk Assessment", "value": "risk"}
],
value=["water", "precip", "risk"],
switch=True,
className="mb-3"
),
html.Hr(),
# Action buttons
dbc.Row([
dbc.Col([
dbc.Button(
[html.I(className="fas fa-sync-alt me-2"), "Refresh"],
id="refresh-btn",
color="primary",
className="w-100",
size="sm"
)
], width=6),
dbc.Col([
dbc.Button(
[html.I(className="fas fa-download me-2"), "Export"],
id="export-btn",
color="success",
className="w-100",
size="sm"
)
], width=6)
])
])
], className="h-100")
def create_metric_card(title, value, unit="", change=None, icon="fas fa-chart-line", color="primary"):
"""Create a metric display card"""
change_element = html.Div()
if change is not None:
change_color = "success" if change >= 0 else "danger"
arrow = "fa-arrow-up" if change >= 0 else "fa-arrow-down"
change_element = html.Div([
html.I(className=f"fas {arrow} me-1"),
html.Span(f"{abs(change):.1f}%")
], className=f"small text-{change_color}")
return dbc.Card([
dbc.CardBody([
html.Div([
html.I(className=f"{icon} fa-2x mb-2", style={"color": COLORS[color]}),
html.H6(title, className="text-muted mb-1"),
html.H4([
html.Span(f"{value:,.1f}" if isinstance(value, (int, float)) else value),
html.Small(f" {unit}", className="text-muted ms-1")
], className="mb-1"),
change_element
], className="text-center")
])
], className="h-100")
def create_gauges_panel():
"""Create panel with gauge visualizations"""
return dbc.Card([
dbc.CardHeader([
html.I(className="fas fa-tachometer-alt me-2"),
html.Span("Risk Assessment")
], className="fw-bold"),
dbc.CardBody([
dbc.Row([
dbc.Col([
daq.Gauge(
id="flood-risk-gauge",
label="Flood Risk",
value=30,
max=100,
min=0,
showCurrentValue=True,
color={"gradient": True,
"ranges": {
"green": [0, 30],
"yellow": [30, 70],
"red": [70, 100]
}},
size=120
)
], md=6),
dbc.Col([
daq.Gauge(
id="drought-risk-gauge",
label="Drought Risk",
value=20,
max=100,
min=0,
showCurrentValue=True,
color={"gradient": True,
"ranges": {
"green": [0, 30],
"yellow": [30, 70],
"red": [70, 100]
}},
size=120
)
], md=6)
], className="mb-3"),
html.Hr(),
dbc.Row([
dbc.Col([
daq.Tank(
id="water-level-tank",
label="Water Level",
value=75,
max=100,
min=0,
showCurrentValue=True,
units="%",
height=150,
width=60,
color="#1e88e5"
)
], className="text-center")
])
])
])
# ==================== MAIN APPLICATION ====================
# Initialize Dash app
app = dash.Dash(
__name__,
external_stylesheets=[
dbc.themes.BOOTSTRAP,
"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
],
suppress_callback_exceptions=True,
meta_tags=[
{"name": "viewport", "content": "width=device-width, initial-scale=1"}
]
)
# Server for deployment
server = app.server
# Add health check endpoint for Docker/monitoring
@server.route('/health')
def health_check():
return {'status': 'healthy', 'service': 'dam-dashboard'}, 200
# App title
app.title = "Dam Intelligence System"
# ==================== LAYOUT ====================
app.layout = dbc.Container([
# Header
create_header(),
# Alert for notifications
dbc.Alert(
id="notification-alert",
is_open=False,
dismissable=True,
duration=4000,
className="mb-3"
),
# Main content
dbc.Row([
# Left sidebar - Control Panel
dbc.Col([
create_control_panel()
], xs=12, md=3, className="mb-3"),
# Center - Main visualizations
dbc.Col([
# Metrics row
dbc.Row([
dbc.Col([
create_metric_card(
"Water Area",
485.3,
"km²",
-3.2,
"fas fa-water",
"primary"
)
], xs=6, md=3),
dbc.Col([
create_metric_card(
"Precipitation",
45.6,
"mm",
12.5,
"fas fa-cloud-rain",
"info"
)
], xs=6, md=3),
dbc.Col([
create_metric_card(
"Temperature",
28.5,
"°C",
2.1,
"fas fa-thermometer-half",
"warning"
)
], xs=6, md=3),
dbc.Col([
create_metric_card(
"NDVI",
0.42,
"",
-5.3,
"fas fa-leaf",
"success"
)
], xs=6, md=3),
], className="mb-3 g-2"),
# Map
dbc.Card([
dbc.CardHeader([
html.I(className="fas fa-map me-2"),
html.Span("Satellite View"),
dbc.ButtonGroup([
dbc.Button("Satellite", id="btn-satellite", size="sm", color="primary"),
dbc.Button("Terrain", id="btn-terrain", size="sm", outline=True, color="primary"),
dbc.Button("Water", id="btn-water", size="sm", outline=True, color="primary")
], className="float-end", size="sm")
], className="d-flex justify-content-between align-items-center"),
dbc.CardBody([
html.Div(
id="map-container",
style={"height": "400px", "backgroundColor": "#f0f0f0"},
className="rounded"
)
])
], className="mb-3"),
# Time series charts
dbc.Card([
dbc.CardHeader([
html.I(className="fas fa-chart-line me-2"),
html.Span("Time Series Analysis"),
dbc.ButtonGroup([
dbc.Button("1M", id="btn-1m", size="sm", outline=True, color="primary"),
dbc.Button("3M", id="btn-3m", size="sm", outline=True, color="primary"),
dbc.Button("1Y", id="btn-1y", size="sm", color="primary"),
dbc.Button("All", id="btn-all", size="sm", outline=True, color="primary")
], className="float-end", size="sm")
]),
dbc.CardBody([
dcc.Graph(
id="time-series-chart",
config={"displayModeBar": False},
style={"height": "400px"}
)
])
])
], xs=12, md=6, className="mb-3"),
# Right sidebar - Risk and alerts
dbc.Col([
# Risk gauges
create_gauges_panel(),
html.Br(),
# Environmental score
dbc.Card([
dbc.CardHeader([
html.I(className="fas fa-seedling me-2"),
html.Span("Environmental Health")
], className="fw-bold"),
dbc.CardBody([
daq.LEDDisplay(
id="env-score-display",
label="Score",
value="72",
color="#43a047",
size=40
),
html.Hr(),
dbc.Progress(
value=72,
max=100,
striped=True,
animated=True,
color="success",
className="mb-2"
),
html.Small("Good condition", className="text-success")
])
]),
html.Br(),
# Alerts panel
dbc.Card([
dbc.CardHeader([
html.I(className="fas fa-exclamation-triangle me-2"),
html.Span("Active Alerts"),
dbc.Badge("2", color="danger", className="ms-2")
], className="fw-bold"),
dbc.CardBody([
dbc.Alert(
[
html.I(className="fas fa-water me-2"),
"Water level declining"
],
color="warning",
className="mb-2 py-2"
),
dbc.Alert(
[
html.I(className="fas fa-thermometer-full me-2"),
"High temperature detected"
],
color="danger",
className="mb-0 py-2"
)
])
])
], xs=12, md=3, className="mb-3")
]),
# Footer
html.Hr(),
dbc.Row([
dbc.Col([
html.P([
"© 2025 Dam Intelligence System | ",
html.A("ICGSTD Workshop", href="#", className="text-decoration-none"),
" | Powered by ",
html.A("Google Earth Engine", href="https://earthengine.google.com",
target="_blank", className="text-decoration-none")
], className="text-center text-muted small mb-3")
])
]),
# Hidden stores for data
dcc.Store(id="current-data-store"),
dcc.Store(id="time-series-store"),
# Interval for updates (5 minutes)
dcc.Interval(
id="interval-component",
interval=300000, # milliseconds
n_intervals=0
),
# Download component
dcc.Download(id="download-data")
], fluid=True)
# ==================== CALLBACKS ====================
@app.callback(
Output("dam-info", "children"),
Output("notification-alert", "children"),
Output("notification-alert", "color"),
Output("notification-alert", "is_open"),
Input("dam-selector", "value")
)
def update_dam_info(selected_dam):
"""Update dam information display"""
if selected_dam and selected_dam in DAM_DATABASE:
info = DAM_DATABASE[selected_dam]
info_display = [
html.Strong("Location: "), f"{info['country']}", html.Br(),
html.Strong("Climate: "), info['climate'], html.Br(),
html.Strong("Capacity: "), f"{info['capacity_km3']:.1f} km³", html.Br(),
html.Strong("Watershed: "), f"{info['watershed_km2']:,} km²"
]
alert_msg = f"Switched to {selected_dam}"
return info_display, alert_msg, "success", True
return [], "", "primary", False
@app.callback(
Output("time-series-chart", "figure"),
Output("time-series-store", "data"),
Input("dam-selector", "value"),
Input("date-range", "start_date"),
Input("date-range", "end_date"),
Input("layer-selector", "value"),
Input("refresh-btn", "n_clicks")
)
def update_time_series(dam_name, start_date, end_date, layers, n_clicks):
"""Update time series visualization"""
# Generate or fetch data
df = generate_sample_data(dam_name, start_date, end_date)
# Create subplots based on selected layers
n_plots = len(layers) if layers else 1
fig = make_subplots(
rows=n_plots,
cols=1,
subplot_titles=[l.title() for l in layers] if layers else ["No data selected"],
vertical_spacing=0.05,
shared_xaxes=True
)
if layers:
for i, layer in enumerate(layers, 1):
if layer == "water":
fig.add_trace(
go.Scatter(
x=df['date'],
y=df['water_area_km2'],
mode='lines+markers',
name='Water Area',
line=dict(color=COLORS['primary'], width=2),
marker=dict(size=4)
),
row=i, col=1
)
fig.update_yaxes(title_text="Area (km²)", row=i, col=1)
elif layer == "precip":
fig.add_trace(
go.Bar(
x=df['date'],
y=df['precipitation_mm'],
name='Precipitation',
marker_color=COLORS['info'],
opacity=0.7
),
row=i, col=1
)
fig.update_yaxes(title_text="Precip (mm)", row=i, col=1)
elif layer == "vegetation":
fig.add_trace(
go.Scatter(
x=df['date'],
y=df['ndvi'],
mode='lines',
name='NDVI',
line=dict(color=COLORS['success'], width=2),
fill='tozeroy',
fillcolor='rgba(67, 160, 71, 0.1)'
),
row=i, col=1
)
fig.update_yaxes(title_text="NDVI", row=i, col=1)
elif layer == "temp":
fig.add_trace(
go.Scatter(
x=df['date'],
y=df['temperature_c'],
mode='lines+markers',
name='Temperature',
line=dict(color=COLORS['warning'], width=2),
marker=dict(size=4)
),
row=i, col=1
)
fig.update_yaxes(title_text="Temp (°C)", row=i, col=1)
elif layer == "risk":
fig.add_trace(
go.Scatter(
x=df['date'],
y=df['flood_risk'],
mode='lines',
name='Flood Risk',
line=dict(color=COLORS['danger'], width=2)
),
row=i, col=1
)
fig.add_trace(
go.Scatter(
x=df['date'],
y=df['drought_risk'],
mode='lines',
name='Drought Risk',
line=dict(color=COLORS['warning'], width=2, dash='dash')
),
row=i, col=1
)
fig.update_yaxes(title_text="Risk (%)", row=i, col=1)
# Update layout
fig.update_xaxes(title_text="Date", row=n_plots, col=1)
fig.update_layout(
height=100 + 100 * n_plots,
showlegend=False,
hovermode='x unified',
template='plotly_white',
margin=dict(l=60, r=20, t=30, b=40)
)
# Store data for export
data_json = df.to_json(date_format='iso', orient='records')
return fig, data_json
@app.callback(
Output("flood-risk-gauge", "value"),
Output("drought-risk-gauge", "value"),
Output("water-level-tank", "value"),
Output("env-score-display", "value"),
Input("interval-component", "n_intervals"),
Input("refresh-btn", "n_clicks"),
State("time-series-store", "data")
)
def update_gauges(n_intervals, n_clicks, stored_data):
"""Update gauge displays with latest values"""
if stored_data:
df = pd.read_json(stored_data)
if not df.empty:
latest = df.iloc[-1]
flood_risk = min(100, max(0, latest['flood_risk'] + np.random.normal(0, 5)))
drought_risk = min(100, max(0, latest['drought_risk'] + np.random.normal(0, 5)))
water_level = min(100, max(0, (latest['water_level_m'] - 100) / 100 * 100))
env_score = min(100, max(0, latest['environmental_score']))
return (
round(flood_risk),
round(drought_risk),
round(water_level),
str(round(env_score))
)
# Default values
return 30, 20, 75, "72"
@app.callback(
Output("download-data", "data"),
Input("export-btn", "n_clicks"),
State("time-series-store", "data"),
State("dam-selector", "value"),
prevent_initial_call=True
)
def export_data(n_clicks, stored_data, dam_name):
"""Export data as CSV"""
if n_clicks and stored_data:
df = pd.read_json(stored_data)
filename = f"{dam_name.replace(' ', '_')}_analysis_{datetime.now().strftime('%Y%m%d')}.csv"
return dcc.send_data_frame(df.to_csv, filename, index=False)
return None
@app.callback(
Output("map-container", "children"),
Input("dam-selector", "value"),
Input("btn-satellite", "n_clicks"),
Input("btn-terrain", "n_clicks"),
Input("btn-water", "n_clicks")
)
def update_map(dam_name, btn_sat, btn_terrain, btn_water):
"""Update map display with real Leaflet tiles"""
if dam_name and dam_name in DAM_DATABASE:
coords = DAM_DATABASE[dam_name]['coords']
lon, lat = coords[0], coords[1]
# Determine which button was clicked
ctx = callback_context
map_type = "satellite"
if ctx.triggered:
button_id = ctx.triggered[0]['prop_id'].split('.')[0]
if button_id == "btn-terrain":
map_type = "terrain"
elif button_id == "btn-water":
map_type = "water"
# Free tile layer URLs (no API key required!)
tile_layers = {
"satellite": {
"url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
"attribution": "ESRI World Imagery",
"name": "ESRI Satellite"
},
"terrain": {
"url": "https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png",
"attribution": "OpenTopoMap",
"name": "Terrain"
},
"water": {
"url": "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
"attribution": "OpenStreetMap",
"name": "Water/Streets"
}
}
selected_layer = tile_layers.get(map_type, tile_layers["satellite"])
# Create Leaflet map
leaflet_map = dl.Map(
children=[
# Tile layer
dl.TileLayer(
url=selected_layer["url"],
attribution=selected_layer["attribution"]
),
# Dam marker
dl.Marker(
position=[lat, lon],
children=[
dl.Tooltip(dam_name),
dl.Popup([
html.H6(dam_name, className="mb-2"),
html.P([
html.Strong("Country: "), f"{DAM_DATABASE[dam_name]['country']}", html.Br(),
html.Strong("Climate: "), f"{DAM_DATABASE[dam_name]['climate']}", html.Br(),
html.Strong("Capacity: "), f"{DAM_DATABASE[dam_name]['capacity_km3']:.1f} km³", html.Br(),
html.Strong("Coordinates: "), f"{lat:.3f}°, {lon:.3f}°"
], className="mb-0 small")
])
]
),
# Circle showing approximate watershed area
dl.Circle(
center=[lat, lon],
radius=20000, # 20km radius
color="#1e88e5",
fillColor="#1e88e5",
fillOpacity=0.1,
weight=2
)
],
center=[lat, lon],
zoom=10,
style={"width": "100%", "height": "400px"}
)
return leaflet_map
return html.Div("Select a dam to view map", className="text-center text-muted py-5")
# ==================== RUN APPLICATION ====================
if __name__ == "__main__":
# Get port from environment variable (for deployment)
# HF Spaces uses port 7860 by default
port = int(os.environ.get("PORT", os.environ.get("GRADIO_SERVER_PORT", 7860)))
# Run server
app.run_server(
host="0.0.0.0",
port=port,
debug=os.environ.get("DEBUG", "False") == "True"
) |