Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,602 +1,442 @@
|
|
| 1 |
-
# main.py - FastAPI application for Flood Vulnerability Assessment
|
| 2 |
-
from fastapi import FastAPI, File, UploadFile, HTTPException, Request
|
| 3 |
-
from fastapi.responses import StreamingResponse, HTMLResponse
|
| 4 |
-
from fastapi.templating import Jinja2Templates
|
| 5 |
-
from pydantic import BaseModel, field_validator
|
| 6 |
-
from typing import Optional, Dict
|
| 7 |
-
import pandas as pd
|
| 8 |
-
import io
|
| 9 |
-
import asyncio
|
| 10 |
-
from concurrent.futures import ThreadPoolExecutor
|
| 11 |
-
|
| 12 |
-
from
|
| 13 |
-
|
| 14 |
-
from
|
| 15 |
-
from
|
| 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 |
-
@app.post("/
|
| 295 |
-
async def
|
| 296 |
-
"""Assess
|
| 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 |
-
result
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
except Exception as e:
|
| 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 |
-
except Exception as e:
|
| 444 |
-
raise HTTPException(status_code=500, detail=f"Assessment failed: {e}")
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
async def process_single_row_multihazard_async(row):
|
| 448 |
-
"""Process a single row with multi-hazard assessment."""
|
| 449 |
-
try:
|
| 450 |
-
from vulnerability import calculate_multi_hazard_vulnerability
|
| 451 |
-
|
| 452 |
-
lat = row['latitude']
|
| 453 |
-
lon = row['longitude']
|
| 454 |
-
height = row.get('height', 0.0)
|
| 455 |
-
basement = row.get('basement', 0.0)
|
| 456 |
-
|
| 457 |
-
loop = asyncio.get_event_loop()
|
| 458 |
-
terrain = await loop.run_in_executor(None, get_terrain_metrics, lat, lon)
|
| 459 |
-
water_dist = await throttled_distance_to_water(lat, lon)
|
| 460 |
-
|
| 461 |
-
result = calculate_multi_hazard_vulnerability(
|
| 462 |
-
lat=lat,
|
| 463 |
-
lon=lon,
|
| 464 |
-
height=height,
|
| 465 |
-
basement=basement,
|
| 466 |
-
terrain_metrics=terrain,
|
| 467 |
-
water_distance=water_dist
|
| 468 |
-
)
|
| 469 |
-
|
| 470 |
-
return {
|
| 471 |
-
'latitude': lat,
|
| 472 |
-
'longitude': lon,
|
| 473 |
-
'height': height,
|
| 474 |
-
'basement': basement,
|
| 475 |
-
'vulnerability_index': result['vulnerability_index'],
|
| 476 |
-
'ci_lower_95': result['confidence_interval']['lower_bound_95'],
|
| 477 |
-
'ci_upper_95': result['confidence_interval']['upper_bound_95'],
|
| 478 |
-
'risk_level': result['risk_level'],
|
| 479 |
-
'confidence': result['uncertainty_analysis']['confidence'],
|
| 480 |
-
'confidence_interpretation': result['uncertainty_analysis']['interpretation'],
|
| 481 |
-
'elevation_m': result['elevation_m'],
|
| 482 |
-
'tpi_m': result['relative_elevation_m'],
|
| 483 |
-
'slope_degrees': result['slope_degrees'],
|
| 484 |
-
'distance_to_water_m': result['distance_to_water_m'],
|
| 485 |
-
'dominant_hazard': result['dominant_hazard'],
|
| 486 |
-
'fluvial_risk': result['hazard_breakdown']['fluvial_riverine'],
|
| 487 |
-
'coastal_risk': result['hazard_breakdown']['coastal_surge'],
|
| 488 |
-
'pluvial_risk': result['hazard_breakdown']['pluvial_drainage'],
|
| 489 |
-
'combined_risk': result['hazard_breakdown']['combined_index'],
|
| 490 |
-
'quality_flags': ','.join(result['uncertainty_analysis']['data_quality_flags'])
|
| 491 |
-
if result['uncertainty_analysis']['data_quality_flags'] else ''
|
| 492 |
-
}
|
| 493 |
-
|
| 494 |
-
except Exception as e:
|
| 495 |
-
return {
|
| 496 |
-
'latitude': row.get('latitude'),
|
| 497 |
-
'longitude': row.get('longitude'),
|
| 498 |
-
'error': str(e),
|
| 499 |
-
'vulnerability_index': None
|
| 500 |
-
}
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
@app.post("/assess_multihazard")
|
| 504 |
-
async def assess_multihazard(data: SingleAssessment) -> Dict:
|
| 505 |
-
"""Multi-hazard assessment (fluvial + coastal + pluvial)"""
|
| 506 |
-
if not gee_ready:
|
| 507 |
-
raise HTTPException(
|
| 508 |
-
status_code=503,
|
| 509 |
-
detail="GEE still initializing, try again in 10 seconds"
|
| 510 |
-
)
|
| 511 |
-
|
| 512 |
-
loop = asyncio.get_event_loop()
|
| 513 |
-
|
| 514 |
-
try:
|
| 515 |
-
from vulnerability import calculate_multi_hazard_vulnerability
|
| 516 |
-
|
| 517 |
-
# Run terrain in background thread
|
| 518 |
-
terrain = await loop.run_in_executor(
|
| 519 |
-
None,
|
| 520 |
-
get_terrain_metrics,
|
| 521 |
-
data.latitude,
|
| 522 |
-
data.longitude
|
| 523 |
-
)
|
| 524 |
-
|
| 525 |
-
# Throttled water distance
|
| 526 |
-
water_dist = await throttled_distance_to_water(data.latitude, data.longitude)
|
| 527 |
-
|
| 528 |
-
result = calculate_multi_hazard_vulnerability(
|
| 529 |
-
lat=data.latitude,
|
| 530 |
-
lon=data.longitude,
|
| 531 |
-
height=data.height,
|
| 532 |
-
basement=data.basement,
|
| 533 |
-
terrain_metrics=terrain,
|
| 534 |
-
water_distance=water_dist
|
| 535 |
-
)
|
| 536 |
-
|
| 537 |
-
return {
|
| 538 |
-
"status": "success",
|
| 539 |
-
"input": data.dict(),
|
| 540 |
-
"assessment": result
|
| 541 |
-
}
|
| 542 |
-
|
| 543 |
-
except Exception as e:
|
| 544 |
-
raise HTTPException(status_code=500, detail=f"Assessment failed: {e}")
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
class HeightRequest(BaseModel):
|
| 548 |
-
latitude: float
|
| 549 |
-
longitude: float
|
| 550 |
-
|
| 551 |
-
@field_validator("latitude")
|
| 552 |
-
@classmethod
|
| 553 |
-
def check_lat(cls, v: float) -> float:
|
| 554 |
-
if not -90 <= v <= 90:
|
| 555 |
-
raise ValueError("Latitude must be between -90 and 90")
|
| 556 |
-
return v
|
| 557 |
-
|
| 558 |
-
@field_validator("longitude")
|
| 559 |
-
@classmethod
|
| 560 |
-
def check_lon(cls, v: float) -> float:
|
| 561 |
-
if not -180 <= v <= 180:
|
| 562 |
-
raise ValueError("Longitude must be between -180 and 180")
|
| 563 |
-
return v
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
@app.post("/predict_height")
|
| 567 |
-
async def predict_height(data: HeightRequest) -> Dict:
|
| 568 |
-
if DISABLE_HEIGHT_PREDICTOR:
|
| 569 |
-
raise HTTPException(status_code=503,
|
| 570 |
-
detail="Height predictor disabled on this deployment.")
|
| 571 |
-
if not model_ready:
|
| 572 |
-
raise HTTPException(
|
| 573 |
-
status_code=503,
|
| 574 |
-
detail="Height predictor still loading, try again later."
|
| 575 |
-
)
|
| 576 |
-
try:
|
| 577 |
-
from height_predictor.inference import get_predictor
|
| 578 |
-
predictor = get_predictor()
|
| 579 |
-
|
| 580 |
-
loop = asyncio.get_event_loop()
|
| 581 |
-
result = await loop.run_in_executor(
|
| 582 |
-
None,
|
| 583 |
-
predictor.predict_from_coordinates,
|
| 584 |
-
data.latitude,
|
| 585 |
-
data.longitude,
|
| 586 |
-
)
|
| 587 |
-
|
| 588 |
-
return result
|
| 589 |
-
|
| 590 |
-
except Exception as e:
|
| 591 |
-
raise HTTPException(
|
| 592 |
-
status_code=500,
|
| 593 |
-
detail=f"Height prediction failed: {str(e)}",
|
| 594 |
-
)
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
# For local development
|
| 598 |
-
if __name__ == "__main__":
|
| 599 |
-
import uvicorn
|
| 600 |
-
import os
|
| 601 |
-
port = int(os.environ.get("PORT", 8000))
|
| 602 |
-
uvicorn.run(app, host="0.0.0.0", port=port)
|
|
|
|
| 1 |
+
# main.py - FastAPI application for Flood Vulnerability Assessment
|
| 2 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException, Request
|
| 3 |
+
from fastapi.responses import StreamingResponse, HTMLResponse
|
| 4 |
+
from fastapi.templating import Jinja2Templates
|
| 5 |
+
from pydantic import BaseModel, field_validator
|
| 6 |
+
from typing import Optional, Dict
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import io
|
| 9 |
+
import asyncio
|
| 10 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 11 |
+
|
| 12 |
+
from spatial_queries import get_terrain_metrics, distance_to_water
|
| 13 |
+
from vulnerability import calculate_vulnerability_index
|
| 14 |
+
from gee_auth import initialize_gee
|
| 15 |
+
from height_predictor.inference import get_predictor
|
| 16 |
+
|
| 17 |
+
# SHAP Explainer Initialization
|
| 18 |
+
try:
|
| 19 |
+
from explainability import VulnerabilityExplainer
|
| 20 |
+
explainer = VulnerabilityExplainer() # Automatically loads rf_explainer.pkl if present
|
| 21 |
+
print("β
SHAP model initialized successfully.")
|
| 22 |
+
except Exception as e:
|
| 23 |
+
print(f"β οΈ SHAP explainer not available: {e}")
|
| 24 |
+
explainer = None
|
| 25 |
+
|
| 26 |
+
# Initialize GEE once at startup
|
| 27 |
+
try:
|
| 28 |
+
initialize_gee()
|
| 29 |
+
print("β
GEE initialized once at startup.")
|
| 30 |
+
except Exception as e:
|
| 31 |
+
print(f"β οΈ GEE initialization failed at startup: {e}")
|
| 32 |
+
|
| 33 |
+
# APP INITIALIZATION
|
| 34 |
+
app = FastAPI(title="Flood Vulnerability Assessment API", version="1.0")
|
| 35 |
+
|
| 36 |
+
# Frontend templates setup
|
| 37 |
+
templates = Jinja2Templates(directory="templates")
|
| 38 |
+
|
| 39 |
+
# Thread pool for batch processing
|
| 40 |
+
executor = ThreadPoolExecutor(max_workers=10)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# DATA MODEL
|
| 44 |
+
class SingleAssessment(BaseModel):
|
| 45 |
+
latitude: float
|
| 46 |
+
longitude: float
|
| 47 |
+
height: Optional[float] = 0.0
|
| 48 |
+
basement: Optional[float] = 0.0
|
| 49 |
+
|
| 50 |
+
@field_validator('latitude')
|
| 51 |
+
@classmethod
|
| 52 |
+
def check_lat(cls, v: float) -> float:
|
| 53 |
+
if not -90 <= v <= 90:
|
| 54 |
+
raise ValueError('Latitude must be between -90 and 90')
|
| 55 |
+
return v
|
| 56 |
+
|
| 57 |
+
@field_validator('longitude')
|
| 58 |
+
@classmethod
|
| 59 |
+
def check_lon(cls, v: float) -> float:
|
| 60 |
+
if not -180 <= v <= 180:
|
| 61 |
+
raise ValueError('Longitude must be between -180 and 180')
|
| 62 |
+
return v
|
| 63 |
+
|
| 64 |
+
@field_validator('basement')
|
| 65 |
+
@classmethod
|
| 66 |
+
def check_basement(cls, v: float) -> float:
|
| 67 |
+
if v > 0:
|
| 68 |
+
raise ValueError('Basement height must be 0 or negative (e.g., -1, -2, -3)')
|
| 69 |
+
return v
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# FRONTEND ROUTE
|
| 73 |
+
@app.get("/", response_class=HTMLResponse)
|
| 74 |
+
async def home(request: Request):
|
| 75 |
+
"""Serve the main web interface"""
|
| 76 |
+
return templates.TemplateResponse("index.html", {"request": request})
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# API ROUTES
|
| 80 |
+
@app.get("/api")
|
| 81 |
+
async def root() -> Dict:
|
| 82 |
+
"""API info endpoint"""
|
| 83 |
+
return {
|
| 84 |
+
"service": "Flood Vulnerability Assessment API",
|
| 85 |
+
"version": "1.0",
|
| 86 |
+
"endpoints": {
|
| 87 |
+
"POST /assess": "Assess single location",
|
| 88 |
+
"POST /assess_batch": "Assess batch from CSV file",
|
| 89 |
+
"GET /health": "Health check"
|
| 90 |
+
}
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
@app.post("/assess")
|
| 95 |
+
async def assess_single(data: SingleAssessment) -> Dict:
|
| 96 |
+
"""Assess flood vulnerability for a single location (non-blocking)."""
|
| 97 |
+
loop = asyncio.get_event_loop()
|
| 98 |
+
|
| 99 |
+
try:
|
| 100 |
+
# Run slow terrain + water queries in a background thread
|
| 101 |
+
terrain, water_dist = await loop.run_in_executor(
|
| 102 |
+
None,
|
| 103 |
+
lambda: (
|
| 104 |
+
get_terrain_metrics(data.latitude, data.longitude),
|
| 105 |
+
distance_to_water(data.latitude, data.longitude)
|
| 106 |
+
)
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
# Calculate vulnerability after terrain + water distance retrieved
|
| 110 |
+
result = calculate_vulnerability_index(
|
| 111 |
+
lat=data.latitude,
|
| 112 |
+
lon=data.longitude,
|
| 113 |
+
height=data.height,
|
| 114 |
+
basement=data.basement,
|
| 115 |
+
terrain_metrics=terrain,
|
| 116 |
+
water_distance=water_dist
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
return {
|
| 120 |
+
"status": "success",
|
| 121 |
+
"input": data.dict(),
|
| 122 |
+
"assessment": result
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
except Exception as e:
|
| 126 |
+
raise HTTPException(status_code=500, detail=f"Assessment failed: {e}")
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
@app.post("/predict_height")
|
| 130 |
+
async def predict_height(data: SingleAssessment) -> Dict:
|
| 131 |
+
try:
|
| 132 |
+
predictor = get_predictor()
|
| 133 |
+
result = predictor.predict_from_coordinates(data.latitude, data.longitude)
|
| 134 |
+
|
| 135 |
+
if result['status'] == 'error':
|
| 136 |
+
raise HTTPException(status_code=500, detail=result['error'])
|
| 137 |
+
|
| 138 |
+
return result
|
| 139 |
+
except Exception as e:
|
| 140 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def process_single_row(row, use_predicted_height=False):
|
| 144 |
+
"""Process a single row from CSV - used for parallel processing."""
|
| 145 |
+
try:
|
| 146 |
+
lat = row['latitude']
|
| 147 |
+
lon = row['longitude']
|
| 148 |
+
height = row.get('height', 0.0)
|
| 149 |
+
basement = row.get('basement', 0.0)
|
| 150 |
+
|
| 151 |
+
if use_predicted_height:
|
| 152 |
+
try:
|
| 153 |
+
predictor = get_predictor()
|
| 154 |
+
pred = predictor.predict_from_coordinates(lat, lon)
|
| 155 |
+
if pred['status'] == 'success' and pred['predicted_height'] is not None:
|
| 156 |
+
height = pred['predicted_height']
|
| 157 |
+
except Exception as e:
|
| 158 |
+
print(f"Height prediction failed for {lat},{lon}: {e}")
|
| 159 |
+
|
| 160 |
+
terrain = get_terrain_metrics(lat, lon)
|
| 161 |
+
water_dist = distance_to_water(lat, lon)
|
| 162 |
+
|
| 163 |
+
result = calculate_vulnerability_index(
|
| 164 |
+
lat=lat,
|
| 165 |
+
lon=lon,
|
| 166 |
+
height=height,
|
| 167 |
+
basement=basement,
|
| 168 |
+
terrain_metrics=terrain,
|
| 169 |
+
water_distance=water_dist
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
# CSV output - essential columns
|
| 173 |
+
return {
|
| 174 |
+
'latitude': lat,
|
| 175 |
+
'longitude': lon,
|
| 176 |
+
'height': height,
|
| 177 |
+
'basement': basement,
|
| 178 |
+
'vulnerability_index': result['vulnerability_index'],
|
| 179 |
+
'ci_lower_95': result['confidence_interval']['lower_bound_95'],
|
| 180 |
+
'ci_upper_95': result['confidence_interval']['upper_bound_95'],
|
| 181 |
+
'vulnerability_level': result['risk_level'],
|
| 182 |
+
'confidence': result['uncertainty_analysis']['confidence'],
|
| 183 |
+
'confidence_interpretation': result['uncertainty_analysis']['interpretation'],
|
| 184 |
+
'elevation_m': result['elevation_m'],
|
| 185 |
+
'tpi_m': result['relative_elevation_m'],
|
| 186 |
+
'slope_degrees': result['slope_degrees'],
|
| 187 |
+
'distance_to_water_m': result['distance_to_water_m'],
|
| 188 |
+
'quality_flags': ','.join(result['uncertainty_analysis']['data_quality_flags']) if result['uncertainty_analysis']['data_quality_flags'] else ''
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
except Exception as e:
|
| 192 |
+
return {
|
| 193 |
+
'latitude': row.get('latitude'),
|
| 194 |
+
'longitude': row.get('longitude'),
|
| 195 |
+
'height': row.get('height', 0.0),
|
| 196 |
+
'basement': row.get('basement', 0.0),
|
| 197 |
+
'error': str(e),
|
| 198 |
+
'vulnerability_index': None,
|
| 199 |
+
'ci_lower_95': None,
|
| 200 |
+
'ci_upper_95': None,
|
| 201 |
+
'risk_level': None,
|
| 202 |
+
'confidence': None,
|
| 203 |
+
'confidence_interpretation': None,
|
| 204 |
+
'elevation_m': None,
|
| 205 |
+
'tpi_m': None,
|
| 206 |
+
'slope_degrees': None,
|
| 207 |
+
'distance_to_water_m': None,
|
| 208 |
+
'quality_flags': ''
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
@app.post("/assess_batch")
|
| 213 |
+
async def assess_batch(file: UploadFile = File(...), use_predicted_height: bool = False) -> StreamingResponse:
|
| 214 |
+
"""Assess flood vulnerability for multiple locations from a CSV file."""
|
| 215 |
+
try:
|
| 216 |
+
contents = await file.read()
|
| 217 |
+
df = pd.read_csv(io.StringIO(contents.decode('utf-8')))
|
| 218 |
+
|
| 219 |
+
if 'latitude' not in df.columns or 'longitude' not in df.columns:
|
| 220 |
+
raise HTTPException(
|
| 221 |
+
status_code=400,
|
| 222 |
+
detail="CSV must contain 'latitude' and 'longitude' columns"
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
import numpy as np
|
| 226 |
+
df = df[(np.abs(df['latitude']) <= 90) & (np.abs(df['longitude']) <= 180)]
|
| 227 |
+
if len(df) == 0:
|
| 228 |
+
raise HTTPException(status_code=400, detail="No valid coordinates in CSV (lat -90..90, lon -180..180)")
|
| 229 |
+
|
| 230 |
+
# Set defaults for optional columns
|
| 231 |
+
if 'height' not in df.columns:
|
| 232 |
+
df['height'] = 0.0
|
| 233 |
+
if 'basement' not in df.columns:
|
| 234 |
+
df['basement'] = 0.0
|
| 235 |
+
|
| 236 |
+
loop = asyncio.get_event_loop()
|
| 237 |
+
results = await loop.run_in_executor(
|
| 238 |
+
executor,
|
| 239 |
+
lambda: [process_single_row(row, use_predicted_height) for _, row in df.iterrows()]
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
results_df = pd.DataFrame(results)
|
| 243 |
+
output = io.StringIO()
|
| 244 |
+
results_df.to_csv(output, index=False)
|
| 245 |
+
output.seek(0)
|
| 246 |
+
return StreamingResponse(
|
| 247 |
+
io.BytesIO(output.getvalue().encode('utf-8')),
|
| 248 |
+
media_type="text/csv",
|
| 249 |
+
headers={
|
| 250 |
+
"Content-Disposition": (
|
| 251 |
+
"attachment; filename=vulnerability_results.csv; "
|
| 252 |
+
"filename*=UTF-8''vulnerability_results.csv"
|
| 253 |
+
)
|
| 254 |
+
}
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
except Exception as e:
|
| 258 |
+
raise HTTPException(status_code=500, detail=f"Batch processing failed: {str(e)}")
|
| 259 |
+
@app.post("/assess_batch_multihazard")
|
| 260 |
+
async def assess_batch_multihazard(file: UploadFile = File(...), use_predicted_height: bool = False) -> StreamingResponse:
|
| 261 |
+
try:
|
| 262 |
+
contents = await file.read()
|
| 263 |
+
df = pd.read_csv(io.StringIO(contents.decode('utf-8')))
|
| 264 |
+
|
| 265 |
+
if 'latitude' not in df.columns or 'longitude' not in df.columns:
|
| 266 |
+
raise HTTPException(
|
| 267 |
+
status_code=400,
|
| 268 |
+
detail="CSV must contain 'latitude' and 'longitude' columns"
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
loop = asyncio.get_event_loop()
|
| 272 |
+
from vulnerability import calculate_multi_hazard_vulnerability
|
| 273 |
+
results = await loop.run_in_executor(
|
| 274 |
+
executor,
|
| 275 |
+
lambda: [process_single_row_multihazard(row, use_predicted_height) for _, row in df.iterrows()]
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
results_df = pd.DataFrame(results)
|
| 279 |
+
output = io.StringIO()
|
| 280 |
+
results_df.to_csv(output, index=False)
|
| 281 |
+
output.seek(0)
|
| 282 |
+
return StreamingResponse(
|
| 283 |
+
io.BytesIO(output.getvalue().encode('utf-8')),
|
| 284 |
+
media_type="text/csv",
|
| 285 |
+
headers={
|
| 286 |
+
"Content-Disposition": (
|
| 287 |
+
"attachment; filename=multihazard_results.csv; "
|
| 288 |
+
"filename*=UTF-8''multihazard_results.csv"
|
| 289 |
+
)
|
| 290 |
+
}
|
| 291 |
+
)
|
| 292 |
+
except Exception as e:
|
| 293 |
+
raise HTTPException(status_code=500, detail=f"Batch multihazard failed: {str(e)}")
|
| 294 |
+
@app.post("/explain")
|
| 295 |
+
async def explain_assessment(data: SingleAssessment) -> Dict:
|
| 296 |
+
"""Assess vulnerability with SHAP explanation"""
|
| 297 |
+
loop = asyncio.get_event_loop()
|
| 298 |
+
|
| 299 |
+
try:
|
| 300 |
+
# Run slow terrain + water queries in a background thread
|
| 301 |
+
terrain, water_dist = await loop.run_in_executor(
|
| 302 |
+
None,
|
| 303 |
+
lambda: (
|
| 304 |
+
get_terrain_metrics(data.latitude, data.longitude),
|
| 305 |
+
distance_to_water(data.latitude, data.longitude)
|
| 306 |
+
)
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
result = calculate_vulnerability_index(
|
| 310 |
+
lat=data.latitude,
|
| 311 |
+
lon=data.longitude,
|
| 312 |
+
height=data.height,
|
| 313 |
+
basement=data.basement,
|
| 314 |
+
terrain_metrics=terrain,
|
| 315 |
+
water_distance=water_dist
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
# Generate explanation if explainer available
|
| 319 |
+
explanation = None
|
| 320 |
+
if explainer:
|
| 321 |
+
try:
|
| 322 |
+
explanation = explainer.explain(result['components'])
|
| 323 |
+
except Exception as e:
|
| 324 |
+
print(f"SHAP explanation failed: {e}")
|
| 325 |
+
|
| 326 |
+
return {
|
| 327 |
+
"status": "success",
|
| 328 |
+
"input": data.dict(),
|
| 329 |
+
"assessment": result,
|
| 330 |
+
"explanation": explanation
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
except Exception as e:
|
| 334 |
+
raise HTTPException(status_code=500, detail=f"Assessment failed: {e}")
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def process_single_row_multihazard(row, use_predicted_height=False):
|
| 338 |
+
"""Process a single row with multi-hazard assessment."""
|
| 339 |
+
try:
|
| 340 |
+
from vulnerability import calculate_multi_hazard_vulnerability
|
| 341 |
+
|
| 342 |
+
lat = row['latitude']
|
| 343 |
+
lon = row['longitude']
|
| 344 |
+
height = row.get('height', 0.0)
|
| 345 |
+
basement = row.get('basement', 0.0)
|
| 346 |
+
|
| 347 |
+
if use_predicted_height:
|
| 348 |
+
try:
|
| 349 |
+
predictor = get_predictor()
|
| 350 |
+
pred = predictor.predict_from_coordinates(lat, lon)
|
| 351 |
+
if pred['status'] == 'success' and pred['predicted_height'] is not None:
|
| 352 |
+
height = pred['predicted_height']
|
| 353 |
+
except Exception as e:
|
| 354 |
+
print(f"Height prediction failed for {lat},{lon}: {e}")
|
| 355 |
+
|
| 356 |
+
terrain = get_terrain_metrics(lat, lon)
|
| 357 |
+
water_dist = distance_to_water(lat, lon)
|
| 358 |
+
|
| 359 |
+
result = calculate_multi_hazard_vulnerability(
|
| 360 |
+
lat=lat,
|
| 361 |
+
lon=lon,
|
| 362 |
+
height=height,
|
| 363 |
+
basement=basement,
|
| 364 |
+
terrain_metrics=terrain,
|
| 365 |
+
water_distance=water_dist
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
return {
|
| 369 |
+
'latitude': lat,
|
| 370 |
+
'longitude': lon,
|
| 371 |
+
'height': height,
|
| 372 |
+
'basement': basement,
|
| 373 |
+
'vulnerability_index': result['vulnerability_index'],
|
| 374 |
+
'ci_lower_95': result['confidence_interval']['lower_bound_95'],
|
| 375 |
+
'ci_upper_95': result['confidence_interval']['upper_bound_95'],
|
| 376 |
+
'vulnerability_level': result['risk_level'],
|
| 377 |
+
'confidence': result['uncertainty_analysis']['confidence'],
|
| 378 |
+
'confidence_interpretation': result['uncertainty_analysis']['interpretation'],
|
| 379 |
+
'elevation_m': result['elevation_m'],
|
| 380 |
+
'tpi_m': result['relative_elevation_m'],
|
| 381 |
+
'slope_degrees': result['slope_degrees'],
|
| 382 |
+
'distance_to_water_m': result['distance_to_water_m'],
|
| 383 |
+
'dominant_hazard': result['dominant_hazard'],
|
| 384 |
+
'fluvial_risk': result['hazard_breakdown']['fluvial_riverine'],
|
| 385 |
+
'coastal_risk': result['hazard_breakdown']['coastal_surge'],
|
| 386 |
+
'pluvial_risk': result['hazard_breakdown']['pluvial_drainage'],
|
| 387 |
+
'combined_risk': result['hazard_breakdown']['combined_index'],
|
| 388 |
+
'quality_flags': ','.join(result['uncertainty_analysis']['data_quality_flags'])
|
| 389 |
+
if result['uncertainty_analysis']['data_quality_flags'] else ''
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
except Exception as e:
|
| 393 |
+
return {
|
| 394 |
+
'latitude': row.get('latitude'),
|
| 395 |
+
'longitude': row.get('longitude'),
|
| 396 |
+
'height': row.get('height', 0.0),
|
| 397 |
+
'basement': row.get('basement', 0.0),
|
| 398 |
+
'error': str(e),
|
| 399 |
+
'vulnerability_index': None
|
| 400 |
+
}
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
@app.post("/assess_multihazard")
|
| 404 |
+
async def assess_multihazard(data: SingleAssessment) -> Dict:
|
| 405 |
+
"""Multi-hazard assessment (fluvial + coastal + pluvial)"""
|
| 406 |
+
loop = asyncio.get_event_loop()
|
| 407 |
+
|
| 408 |
+
try:
|
| 409 |
+
from vulnerability import calculate_multi_hazard_vulnerability
|
| 410 |
+
|
| 411 |
+
# Run slow terrain + water queries in a background thread
|
| 412 |
+
terrain, water_dist = await loop.run_in_executor(
|
| 413 |
+
None,
|
| 414 |
+
lambda: (
|
| 415 |
+
get_terrain_metrics(data.latitude, data.longitude),
|
| 416 |
+
distance_to_water(data.latitude, data.longitude)
|
| 417 |
+
)
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
result = calculate_multi_hazard_vulnerability(
|
| 421 |
+
lat=data.latitude,
|
| 422 |
+
lon=data.longitude,
|
| 423 |
+
height=data.height,
|
| 424 |
+
basement=data.basement,
|
| 425 |
+
terrain_metrics=terrain,
|
| 426 |
+
water_distance=water_dist
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
return {
|
| 430 |
+
"status": "success",
|
| 431 |
+
"input": data.dict(),
|
| 432 |
+
"assessment": result
|
| 433 |
+
}
|
| 434 |
+
|
| 435 |
+
except Exception as e:
|
| 436 |
+
raise HTTPException(status_code=500, detail=f"Assessment failed: {e}")
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
@app.get("/health")
|
| 440 |
+
async def health_check() -> Dict:
|
| 441 |
+
"""Health check endpoint."""
|
| 442 |
+
return {"status": "healthy", "gee_initialized": True}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|