Download app.py from questfeed/dam-intelligence-dashboard: direct link, hf CLI and curl.
- Browser
- Download file 30.8 kB
-
https://huggingface.co/spaces/questfeed/dam-intelligence-dashboard/resolve/main/app.py
- Command line
-
hf download hf://spaces/questfeed/dam-intelligence-dashboard/app.py
-
curl -L -o app.py https://huggingface.co/spaces/questfeed/dam-intelligence-dashboard/resolve/main/app.py
30.8 kB
| """ | |
| 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 | |
| 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 ==================== | |
| 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 | |
| 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 | |
| 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" | |
| 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 | |
| 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" | |
| ) |