Spaces:
Paused
Paused
File size: 25,151 Bytes
22eeb7e | 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 | # app/main.py
"""
π€ PENNY - People's Engagement Network Navigator for You
FastAPI Entry Point with Azure-Ready Configuration
This is Penny's front door. She loads her environment, registers all her endpoints,
and makes sure she's ready to help residents find what they need.
MISSION: Connect residents to civic resources through a warm, multilingual interface
that removes barriers and empowers communities.
"""
from fastapi import FastAPI, Request, status
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import logging
import sys
import os
from dotenv import load_dotenv
import pathlib
from typing import Dict, Any, Optional, List
from datetime import datetime, timedelta
# --- LOGGING CONFIGURATION (Must be set up before other imports) ---
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout)
]
)
logger = logging.getLogger(__name__)
# --- CRITICAL: FORCE .ENV LOADING BEFORE ANY OTHER IMPORTS ---
# Determine the absolute path to the project root
PROJECT_ROOT = pathlib.Path(__file__).parent.parent
# Load environment variables into the active Python session IMMEDIATELY
# This ensures Azure Maps keys, API tokens, and model paths are available
try:
load_dotenv(PROJECT_ROOT / ".env")
# Verify critical environment variables are loaded
REQUIRED_ENV_VARS = ["AZURE_MAPS_KEY"]
missing_vars = [var for var in REQUIRED_ENV_VARS if not os.getenv(var)]
if missing_vars:
logger.warning(f"β οΈ WARNING: Missing required environment variables: {missing_vars}")
logger.warning(f"π Looking for .env file at: {PROJECT_ROOT / '.env'}")
else:
logger.info("β
Environment variables loaded successfully")
except Exception as e:
logger.error(f"β Error loading environment variables: {e}")
logger.error(f"π Expected .env location: {PROJECT_ROOT / '.env'}")
# --- NOW SAFE TO IMPORT MODULES THAT DEPEND ON ENV VARS ---
try:
from app.weather_agent import get_weather_for_location
from app.router import router as api_router
from app.location_utils import (
initialize_location_system,
get_all_supported_cities,
validate_city_data_files,
SupportedCities,
get_city_coordinates
)
except ImportError as e:
logger.error(f"β Critical import error: {e}")
logger.error("β οΈ Penny cannot start without core modules")
sys.exit(1)
# --- FASTAPI APP INITIALIZATION ---
app = FastAPI(
title="PENNY - Civic Engagement Assistant",
description=(
"π Multilingual civic chatbot connecting residents with local services, "
"government programs, and community resources.\n\n"
"**Powered by:**\n"
"- Transformer models for natural language understanding\n"
"- Azure ML infrastructure for scalable deployment\n"
"- 27-language translation support\n"
"- Real-time weather integration\n"
"- Multi-city civic resource databases\n\n"
"**Supported Cities:** Atlanta, Birmingham, Chesterfield, El Paso, Providence, Seattle"
),
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc",
contact={
"name": "Penny Support",
"email": "support@pennyai.example"
},
license_info={
"name": "Proprietary",
}
)
# --- CORS MIDDLEWARE (Configure for your deployment) ---
# Production: Update allowed_origins to restrict to specific domains
allowed_origins = os.getenv("ALLOWED_ORIGINS", "*").split(",")
app.add_middleware(
CORSMiddleware,
allow_origins=allowed_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# --- APPLICATION STATE (For health checks and monitoring) ---
app.state.location_system_healthy = False
app.state.startup_time = None
app.state.startup_errors: List[str] = []
# --- GLOBAL EXCEPTION HANDLER ---
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception) -> JSONResponse:
"""
π‘οΈ Catches any unhandled exceptions and returns a user-friendly response.
Logs full error details for debugging while keeping responses safe for users.
Penny stays helpful even when things go wrong!
Args:
request: FastAPI request object
exc: The unhandled exception
Returns:
JSONResponse with error details (sanitized for production)
"""
logger.error(
f"Unhandled exception on {request.url.path} | "
f"method={request.method} | "
f"error={exc}",
exc_info=True
)
# Check if debug mode is enabled
debug_mode = os.getenv("DEBUG_MODE", "false").lower() == "true"
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={
"error": "An unexpected error occurred. Penny's on it!",
"message": "Our team has been notified and we're working to fix this.",
"detail": str(exc) if debug_mode else None,
"request_path": str(request.url.path),
"timestamp": datetime.utcnow().isoformat()
}
)
# --- STARTUP EVENT ---
@app.on_event("startup")
async def startup_event() -> None:
"""
π Runs when Penny wakes up.
Responsibilities:
1. Validate environment configuration
2. Initialize location/city systems
3. Verify data files exist
4. Log system status
"""
try:
app.state.startup_time = datetime.utcnow()
app.state.startup_errors = []
logger.info("=" * 60)
logger.info("π€ PENNY STARTUP INITIALIZED")
logger.info("=" * 60)
# --- Environment Info ---
logger.info(f"π Project Root: {PROJECT_ROOT}")
logger.info(f"π Environment: {os.getenv('ENVIRONMENT', 'development')}")
logger.info(f"π Python Version: {sys.version.split()[0]}")
# --- Azure Configuration Check ---
azure_maps_key = os.getenv("AZURE_MAPS_KEY")
if azure_maps_key:
logger.info("πΊοΈ Azure Maps: β
Configured")
else:
error_msg = "Azure Maps key missing - weather features will be limited"
logger.warning(f"πΊοΈ Azure Maps: β οΈ {error_msg}")
app.state.startup_errors.append(error_msg)
# --- Initialize Location System ---
logger.info("πΊοΈ Initializing location system...")
try:
location_system_ready = initialize_location_system()
app.state.location_system_healthy = location_system_ready
if location_system_ready:
logger.info("β
Location system initialized successfully")
# Log supported cities
cities = SupportedCities.get_all_cities()
logger.info(f"π Supported cities: {len(cities)}")
for city in cities:
logger.info(f" - {city.full_name} ({city.tenant_id})")
# Validate data files
validation = validate_city_data_files()
missing_data = [
tid for tid, status in validation.items()
if not status["events"] or not status["resources"]
]
if missing_data:
error_msg = f"Incomplete data for cities: {missing_data}"
logger.warning(f"β οΈ {error_msg}")
app.state.startup_errors.append(error_msg)
else:
error_msg = "Location system initialization failed"
logger.error(f"β {error_msg}")
app.state.startup_errors.append(error_msg)
except Exception as e:
error_msg = f"Error initializing location system: {e}"
logger.error(f"β {error_msg}", exc_info=True)
app.state.location_system_healthy = False
app.state.startup_errors.append(error_msg)
# --- Startup Summary ---
logger.info("=" * 60)
if app.state.startup_errors:
logger.warning(f"β οΈ PENNY STARTED WITH {len(app.state.startup_errors)} WARNING(S)")
for error in app.state.startup_errors:
logger.warning(f" - {error}")
else:
logger.info("π PENNY IS READY TO HELP RESIDENTS!")
logger.info("π API Documentation: http://localhost:8000/docs")
logger.info("=" * 60)
except Exception as e:
logger.error(f"β Critical startup error: {e}", exc_info=True)
app.state.startup_errors.append(f"Critical startup failure: {e}")
# --- SHUTDOWN EVENT ---
@app.on_event("shutdown")
async def shutdown_event() -> None:
"""
π Cleanup tasks when Penny shuts down.
"""
try:
logger.info("=" * 60)
logger.info("π PENNY SHUTTING DOWN")
logger.info("=" * 60)
# Calculate uptime
if app.state.startup_time:
uptime = datetime.utcnow() - app.state.startup_time
logger.info(f"β±οΈ Total uptime: {uptime}")
# TODO: Add cleanup tasks here
# - Close database connections
# - Save state if needed
# - Release model resources
logger.info("β
Shutdown complete. Goodbye for now!")
except Exception as e:
logger.error(f"Error during shutdown: {e}", exc_info=True)
# --- ROUTER INCLUSION ---
# All API endpoints defined in router.py are registered here
try:
app.include_router(api_router)
logger.info("β
API router registered successfully")
except Exception as e:
logger.error(f"β Failed to register API router: {e}", exc_info=True)
# ============================================================
# CORE HEALTH & STATUS ENDPOINTS
# ============================================================
@app.get("/", tags=["Health"])
async def root() -> Dict[str, Any]:
"""
π Root endpoint - confirms Penny is alive and running.
This is the first thing users/load balancers will hit.
Penny always responds with warmth, even to bots! π
Returns:
Basic status and feature information
"""
try:
return {
"message": "π Hi! I'm Penny, your civic engagement assistant.",
"status": "operational",
"tagline": "Connecting residents to community resources since 2024",
"docs": "/docs",
"api_version": "1.0.0",
"supported_cities": len(SupportedCities.get_all_cities()),
"features": [
"27-language translation",
"Real-time weather",
"Community events",
"Local resource finder",
"Document processing"
],
"timestamp": datetime.utcnow().isoformat()
}
except Exception as e:
logger.error(f"Error in root endpoint: {e}", exc_info=True)
return {
"message": "π Hi! I'm Penny, your civic engagement assistant.",
"status": "degraded",
"error": "Some features may be unavailable"
}
@app.get("/health", tags=["Health"])
async def health_check() -> JSONResponse:
"""
π₯ Comprehensive health check for Azure load balancers and monitoring.
Returns detailed status of all critical components:
- Environment configuration
- Location system
- Data availability
- API components
Returns:
JSONResponse with health status (200 = healthy, 503 = degraded)
"""
try:
# Calculate uptime
uptime = None
if app.state.startup_time:
uptime_delta = datetime.utcnow() - app.state.startup_time
uptime = str(uptime_delta).split('.')[0] # Remove microseconds
# Validate data files
validation = validate_city_data_files()
cities_with_full_data = sum(
1 for v in validation.values()
if v.get("events", False) and v.get("resources", False)
)
total_cities = len(SupportedCities.get_all_cities())
health_status = {
"status": "healthy",
"timestamp": datetime.utcnow().isoformat(),
"uptime": uptime,
"environment": {
"azure_maps_configured": bool(os.getenv("AZURE_MAPS_KEY")),
"debug_mode": os.getenv("DEBUG_MODE", "false").lower() == "true",
"environment_type": os.getenv("ENVIRONMENT", "development")
},
"location_system": {
"status": "operational" if app.state.location_system_healthy else "degraded",
"supported_cities": total_cities,
"cities_with_full_data": cities_with_full_data
},
"api_components": {
"router": "operational",
"weather_agent": "operational" if os.getenv("AZURE_MAPS_KEY") else "degraded",
"translation": "operational",
"document_processing": "operational"
},
"startup_errors": app.state.startup_errors if app.state.startup_errors else None,
"api_version": "1.0.0"
}
# Determine overall health status
critical_checks = [
app.state.location_system_healthy,
bool(os.getenv("AZURE_MAPS_KEY"))
]
all_healthy = all(critical_checks)
if not all_healthy:
health_status["status"] = "degraded"
logger.warning(f"Health check: System degraded - {health_status}")
return JSONResponse(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
content=health_status
)
return JSONResponse(
status_code=status.HTTP_200_OK,
content=health_status
)
except Exception as e:
logger.error(f"Health check failed: {e}", exc_info=True)
return JSONResponse(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
content={
"status": "error",
"timestamp": datetime.utcnow().isoformat(),
"error": "Health check failed",
"detail": str(e) if os.getenv("DEBUG_MODE", "false").lower() == "true" else None
}
)
@app.get("/cities", tags=["Location"])
async def list_supported_cities() -> JSONResponse:
"""
π Lists all cities Penny currently supports.
Returns:
List of city information including tenant_id and display name.
Useful for frontend dropdowns and API clients.
Example Response:
{
"total": 6,
"cities": [
{
"tenant_id": "atlanta_ga",
"name": "Atlanta, GA",
"state": "GA",
"data_status": {"events": true, "resources": true}
}
]
}
"""
try:
cities = get_all_supported_cities()
# Add validation status for each city
validation = validate_city_data_files()
for city in cities:
tenant_id = city["tenant_id"]
city["data_status"] = validation.get(tenant_id, {
"events": False,
"resources": False
})
return JSONResponse(
status_code=status.HTTP_200_OK,
content={
"total": len(cities),
"cities": cities,
"message": "These are the cities where Penny can help you find resources!",
"timestamp": datetime.utcnow().isoformat()
}
)
except Exception as e:
logger.error(f"Error listing cities: {e}", exc_info=True)
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={
"error": "Unable to retrieve city list",
"message": "I'm having trouble loading the city list right now. Please try again in a moment!",
"detail": str(e) if os.getenv("DEBUG_MODE", "false").lower() == "true" else None,
"timestamp": datetime.utcnow().isoformat()
}
)
# ============================================================
# WEATHER ENDPOINTS
# ============================================================
@app.get("/weather_direct", tags=["Weather"])
async def weather_direct_endpoint(lat: float, lon: float) -> JSONResponse:
"""
π€οΈ Direct weather lookup by coordinates.
Args:
lat: Latitude (-90 to 90)
lon: Longitude (-180 to 180)
Returns:
Current weather conditions for the specified location
Example:
GET /weather_direct?lat=36.8508&lon=-76.2859 (Norfolk, VA)
"""
# Validate coordinates
if not (-90 <= lat <= 90):
return JSONResponse(
status_code=status.HTTP_400_BAD_REQUEST,
content={
"error": "Invalid latitude",
"message": "Latitude must be between -90 and 90",
"provided_value": lat
}
)
if not (-180 <= lon <= 180):
return JSONResponse(
status_code=status.HTTP_400_BAD_REQUEST,
content={
"error": "Invalid longitude",
"message": "Longitude must be between -180 and 180",
"provided_value": lon
}
)
try:
weather = await get_weather_for_location(lat=lat, lon=lon)
return JSONResponse(
status_code=status.HTTP_200_OK,
content={
"latitude": lat,
"longitude": lon,
"weather": weather,
"source": "Azure Maps Weather API",
"message": "Current weather conditions at your location",
"timestamp": datetime.utcnow().isoformat()
}
)
except Exception as e:
logger.error(f"Weather lookup failed for ({lat}, {lon}): {e}", exc_info=True)
return JSONResponse(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
content={
"error": "Weather service temporarily unavailable",
"message": "We're having trouble reaching the weather service. Please try again in a moment.",
"latitude": lat,
"longitude": lon,
"timestamp": datetime.utcnow().isoformat()
}
)
@app.get("/weather/{tenant_id}", tags=["Weather"])
async def weather_by_city(tenant_id: str) -> JSONResponse:
"""
π€οΈ Get weather for a supported city by tenant ID.
Args:
tenant_id: City identifier (e.g., 'atlanta_ga', 'seattle_wa')
Returns:
Current weather conditions for the specified city
Example:
GET /weather/atlanta_ga
"""
try:
# Get city info
city_info = SupportedCities.get_city_by_tenant_id(tenant_id)
if not city_info:
supported = [c["tenant_id"] for c in get_all_supported_cities()]
return JSONResponse(
status_code=status.HTTP_404_NOT_FOUND,
content={
"error": f"City not found: {tenant_id}",
"message": f"I don't have data for '{tenant_id}' yet. Try one of the supported cities!",
"supported_cities": supported,
"timestamp": datetime.utcnow().isoformat()
}
)
# Get coordinates
coords = get_city_coordinates(tenant_id)
if not coords:
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={
"error": "City coordinates not available",
"city": city_info.full_name,
"tenant_id": tenant_id,
"timestamp": datetime.utcnow().isoformat()
}
)
lat, lon = coords["lat"], coords["lon"]
weather = await get_weather_for_location(lat=lat, lon=lon)
return JSONResponse(
status_code=status.HTTP_200_OK,
content={
"city": city_info.full_name,
"tenant_id": tenant_id,
"coordinates": {"latitude": lat, "longitude": lon},
"weather": weather,
"source": "Azure Maps Weather API",
"timestamp": datetime.utcnow().isoformat()
}
)
except Exception as e:
logger.error(f"Weather lookup failed for {tenant_id}: {e}", exc_info=True)
return JSONResponse(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
content={
"error": "Weather service temporarily unavailable",
"message": "We're having trouble getting the weather right now. Please try again in a moment!",
"tenant_id": tenant_id,
"timestamp": datetime.utcnow().isoformat()
}
)
# ============================================================
# DEBUG ENDPOINTS (Only available in debug mode)
# ============================================================
@app.get("/debug/validation", tags=["Debug"], include_in_schema=False)
async def debug_validation() -> JSONResponse:
"""
π§ͺ Debug endpoint: Shows data file validation status.
Only available when DEBUG_MODE=true
"""
if os.getenv("DEBUG_MODE", "false").lower() != "true":
return JSONResponse(
status_code=status.HTTP_403_FORBIDDEN,
content={"error": "Debug endpoints are disabled in production"}
)
try:
validation = validate_city_data_files()
return JSONResponse(
status_code=status.HTTP_200_OK,
content={
"validation": validation,
"summary": {
"total_cities": len(validation),
"cities_with_events": sum(1 for v in validation.values() if v.get("events", False)),
"cities_with_resources": sum(1 for v in validation.values() if v.get("resources", False))
},
"timestamp": datetime.utcnow().isoformat()
}
)
except Exception as e:
logger.error(f"Debug validation failed: {e}", exc_info=True)
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={"error": str(e)}
)
@app.get("/debug/env", tags=["Debug"], include_in_schema=False)
async def debug_environment() -> JSONResponse:
"""
π§ͺ Debug endpoint: Shows environment configuration.
Sensitive values are masked. Only available when DEBUG_MODE=true
"""
if os.getenv("DEBUG_MODE", "false").lower() != "true":
return JSONResponse(
status_code=status.HTTP_403_FORBIDDEN,
content={"error": "Debug endpoints are disabled in production"}
)
def mask_sensitive(key: str, value: str) -> str:
"""Masks sensitive environment variables."""
sensitive_keys = ["key", "secret", "password", "token"]
if any(s in key.lower() for s in sensitive_keys):
return f"{value[:4]}...{value[-4:]}" if len(value) > 8 else "***"
return value
try:
env_vars = {
key: mask_sensitive(key, value)
for key, value in os.environ.items()
if key.startswith(("AZURE_", "PENNY_", "DEBUG_", "ENVIRONMENT"))
}
return JSONResponse(
status_code=status.HTTP_200_OK,
content={
"environment_variables": env_vars,
"project_root": str(PROJECT_ROOT),
"location_system_healthy": app.state.location_system_healthy,
"startup_errors": app.state.startup_errors,
"timestamp": datetime.utcnow().isoformat()
}
)
except Exception as e:
logger.error(f"Debug environment check failed: {e}", exc_info=True)
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={"error": str(e)}
) |