""" FastAPI application for the CommunityOne Open Navigator system. Provides REST API endpoints for: - Initiating policy analysis workflows - Querying advocacy opportunities - Retrieving generated materials - Accessing visualizations - System status and monitoring """ from typing import List, Dict, Any, Optional from datetime import datetime, date import sys import time from pathlib import Path from fastapi import FastAPI, HTTPException, Query, BackgroundTasks, Request, Response from fastapi.responses import HTMLResponse, JSONResponse from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.gzip import GZipMiddleware from fastapi.staticfiles import StaticFiles from fastapi.openapi.docs import get_swagger_ui_html from api.static_cache import CachedStaticFiles from pydantic import BaseModel, Field from loguru import logger import os from agents.orchestrator import OrchestratorAgent from agents.scraper import ScraperAgent from agents.parser import ParserAgent from agents.classifier import ClassifierAgent from agents.sentiment import SentimentAnalyzerAgent from agents.advocacy import AdvocacyWriterAgent from ingestion.delta_lake import DeltaLakePipeline from scripts.visualization.heatmap import AdvocacyHeatmap from config import settings # Configure logging with rotation and retention # Output to both file (with rotation) and stderr (for HuggingFace container logs) logger.remove() # Remove default handler # Add console output (shows in HuggingFace container logs) logger.add( sys.stderr, format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function} - {message}", level=settings.log_level ) # Add file output with rotation and retention logger.add( settings.log_file, rotation="500 MB", # Create new file when size exceeds 500MB retention="10 days", # Delete logs older than 10 days level=settings.log_level, format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function} - {message}" ) # Initialize FastAPI app app = FastAPI( title="Open Navigator API", description="Multi-agent system for analyzing local government oral health policy discussions", version="1.0.0", docs_url=None, # Disable default docs to use custom redoc_url="/redoc", # Keep ReDoc at /redoc openapi_tags=[ { "name": "auth", "description": "Authentication and user management" }, { "name": "social", "description": "Social features - follow users, leaders, organizations, and causes" }, { "name": "workflows", "description": "Policy analysis workflows" }, { "name": "opportunities", "description": "Advocacy opportunities" } ] ) # Custom OpenAPI schema with logo def custom_openapi(): if app.openapi_schema: return app.openapi_schema from fastapi.openapi.utils import get_openapi openapi_schema = get_openapi( title=app.title, version=app.version, description=app.description, routes=app.routes, ) # Add custom logo openapi_schema["info"]["x-logo"] = { "url": "/static/communityone_logo.svg", "altText": "CommunityOne Logo" } app.openapi_schema = openapi_schema return app.openapi_schema app.openapi = custom_openapi # Bootstrap OpenTelemetry: instrument the app at startup and configure the # exporter (OTLP collector if OTEL_EXPORTER_OTLP_ENDPOINT is set, else a console # exporter for dev). Idempotent. Spans for the search DB path are opened in # api/routes/search*.py via the shared `tracer`. from api.telemetry import setup_telemetry setup_telemetry(app) # Add CORS middleware. Origins come from an explicit env-driven allowlist # (api/origins.py), never "*": with allow_credentials=True, Starlette reflects # the caller's Origin, so "*" would trust every site on the internet. from api.origins import allowed_origins app.add_middleware( CORSMiddleware, allow_origins=list(allowed_origins()), allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Compress responses (notably the large /data JSON marts — county_metrics is # ~2.6MB, jurisdiction_mapping_quality ~6.6MB; both compress ~5-10x). app.add_middleware(GZipMiddleware, minimum_size=1000) # Request logging middleware @app.middleware("http") async def log_requests(request: Request, call_next): """Log all API requests with timing and response info""" start_time = time.time() # Get client info client_host = request.client.host if request.client else "unknown" # Log incoming request logger.info(f"➡️ {request.method} {request.url.path} - Client: {client_host}") # Process request try: response = await call_next(request) # Calculate duration duration_ms = (time.time() - start_time) * 1000 # Get response size if available response_size = response.headers.get("content-length", "unknown") # Log response with appropriate emoji based on status if response.status_code < 400: logger.info( f"✅ {request.method} {request.url.path} - " f"Status: {response.status_code} - " f"Duration: {duration_ms:.2f}ms - " f"Size: {response_size} bytes" ) elif response.status_code < 500: logger.warning( f"⚠️ {request.method} {request.url.path} - " f"Status: {response.status_code} - " f"Duration: {duration_ms:.2f}ms" ) else: logger.error( f"❌ {request.method} {request.url.path} - " f"Status: {response.status_code} - " f"Duration: {duration_ms:.2f}ms" ) return response except Exception as e: duration_ms = (time.time() - start_time) * 1000 # A client that disconnects mid-flight (e.g. the frontend's # AbortController timing out a slow request) cancels the downstream # task, so Starlette's BaseHTTPMiddleware reports # "No response returned." That's a normal client abort, not a server # fault — log it quietly and return 499 (Client Closed Request) instead # of re-raising a 500 with a noisy traceback. if ( isinstance(e, RuntimeError) and str(e) == "No response returned." and await request.is_disconnected() ): logger.info( f"🚫 {request.method} {request.url.path} - " f"Client disconnected - Duration: {duration_ms:.2f}ms" ) return Response(status_code=499) logger.error( f"💥 {request.method} {request.url.path} - " f"Error: {str(e)} - " f"Duration: {duration_ms:.2f}ms" ) raise # Mount static files for logo static_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "web_app", "public") if os.path.exists(static_dir): app.mount("/static", StaticFiles(directory=static_dir), name="static") # Serve the whole public /data tree the way Vite does in dev. Besides the # census-map marts this covers the per-state ZCTA (ZIP) tiles under # /data/zctas (the lowest drilldown tier) and the jurisdiction-quality # snapshot — mounting only /data/census-map left those paths 404ing. data_dir = Path(static_dir) / "data" if data_dir.is_dir(): app.mount("/data", CachedStaticFiles(directory=data_dir), name="public_data") else: logger.warning(f"Public data bundle missing (expected {data_dir})") else: logger.warning(f"Static directory not found: {static_dir}") # Serve favicon at root @app.get("/favicon.ico", include_in_schema=False) async def favicon(): """Serve favicon — HF deploy strips binary assets, so fall back to PNG/SVG.""" from fastapi.responses import FileResponse candidates = [ (Path(__file__).parent / "static" / "favicon.ico", "image/x-icon"), (Path(static_dir) / "favicon.ico", "image/x-icon"), (Path(__file__).parent / "static" / "communityone_logo_64.png", "image/png"), (Path(static_dir) / "communityone_logo_64.png", "image/png"), (Path(__file__).parent / "static" / "communityone_logo.svg", "image/svg+xml"), (Path(static_dir) / "communityone_logo.svg", "image/svg+xml"), ] for path, media_type in candidates: if path.exists(): return FileResponse(path, media_type=media_type) raise HTTPException(status_code=404, detail="Favicon not found") # Custom Exception Handlers for better error messages from fastapi.exceptions import RequestValidationError from starlette.exceptions import HTTPException as StarletteHTTPException from api.error_pages import error_response @app.exception_handler(StarletteHTTPException) async def http_exception_handler(request: Request, exc: StarletteHTTPException): """Handle HTTP exceptions with user-friendly, content-negotiated messages.""" if exc.status_code == 404: return error_response( request, status_code=404, title="Page not found", message=f"We couldn't find '{request.url.path}'.", suggestion="Check the link and try again, or head back to the homepage.", extra={"documentation": "/api/docs"}, ) elif exc.status_code == 401: return error_response( request, status_code=401, title="Sign-in required", message=exc.detail or "You need to be signed in to access this.", suggestion="Please sign in and try again.", extra={"login": "/api/auth/login/google"}, ) elif exc.status_code == 403: return error_response( request, status_code=403, title="Access denied", message=exc.detail or "You don't have permission to access this.", suggestion="Contact support if you believe this is a mistake.", ) elif exc.status_code == 503: return error_response( request, status_code=503, title="Temporarily unavailable", message=exc.detail or "This service is temporarily unavailable.", suggestion="Please try again in a few minutes.", ) else: return error_response( request, status_code=exc.status_code, title=str(exc.detail) if exc.detail else "Something went wrong", message=str(exc.detail) if exc.detail else "An error occurred while processing your request.", ) @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): """Handle validation errors with detailed, user-friendly messages""" errors = [] for error in exc.errors(): field = " -> ".join(str(loc) for loc in error["loc"]) errors.append({ "field": field, "message": error["msg"], "type": error["type"] }) return error_response( request, status_code=422, title="Validation Error", message="The request data is invalid. Please check the fields and try again.", suggestion="Review the error details and correct the invalid fields.", extra={"errors": errors, "documentation": "/api/docs"}, ) @app.exception_handler(500) async def internal_server_error_handler(request: Request, exc: Exception): """Handle internal server errors with a generic message (hide details from users).""" logger.error(f"Internal server error on {request.url.path}: {exc}") return error_response( request, status_code=500, title="Something went wrong", message="Something went wrong on our end. We've been notified and are working to fix it.", suggestion="Please try again in a little while. If it keeps happening, email support and we'll help.", ) # Include authentication routes from api.routes import auth as auth_routes from api.routes import social as social_routes from api.routes import search as search_routes from api.routes import people as people_routes from api.routes import decisions as decisions_routes from api.routes import policy_questions as policy_questions_routes from api.routes import documents as documents_routes from api.routes import jurisdiction_documents as jurisdiction_documents_routes from api.routes import jurisdiction_meeting_documents as jurisdiction_meeting_documents_routes from api.routes import governing_bodies as governing_bodies_routes from api.routes import event_bills as event_bills_routes from api.routes import meetings as meetings_routes from api.routes import meeting_comparison as meeting_comparison_routes # Use Neon database for fast stats queries (500x faster than parquet) from api.routes import stats_neon as stats_routes # Was: stats from api.routes import contact as contact_routes from api.routes import chat_meetings as chat_meetings_routes from api.routes import stance as stance_routes # Use hybrid approach for bills: Neon for map, parquet for drill-down (saves space) from api.routes import bills_neon as bills_routes # Was: bills from api.routes import data_deletion as data_deletion_routes from api.routes import trending as trending_routes from api.routes import lighthouse_reports as lighthouse_reports_routes from api.routes import jurisdiction_mapping as jurisdiction_mapping_routes from api.routes import batch_jobs as batch_jobs_routes from api.routes import deployments as deployments_routes from api.routes import locations as locations_routes from api.routes import addresses as addresses_routes from api.routes import geocode as geocode_routes from api.routes import cpi as cpi_routes from api.routes import grants as grants_routes from api.routes import efile990 as efile990_routes from api.routes import lenses as lenses_routes from api.routes import money_flow as money_flow_routes from api.routes import topics as topics_routes from api.routes import seo as seo_routes from api.routes import short_term_rentals as short_term_rentals_routes from api.routes import topic_companies as topic_companies_routes from api.routes import topic_timeline as topic_timeline_routes from api.routes import topic_yoy as topic_yoy_routes from api.routes import rankings as rankings_routes from api.routes import topic_policy as topic_policy_routes from api.routes import topic_upcoming as topic_upcoming_routes from api.routes import topic_organizations as topic_organizations_routes from api.routes import topic_outcomes as topic_outcomes_routes from api.routes import topic_caption_facts as topic_caption_facts_routes from api.routes import organizations as organizations_routes from api.routes import money_and_talk as money_and_talk_routes from api.routes import grandkid_outlook as grandkid_outlook_routes from api.routes import local_finance as local_finance_routes from api.routes import benchmark as benchmark_routes from api.routes import browse as browse_routes from api.routes import decision_browse as decision_browse_routes from api.routes import meeting_browse as meeting_browse_routes from api.routes import feed as feed_routes from api.routes import alerts as alerts_routes from api.routes import data_centers as data_centers_routes from api.routes import data_center_comments as data_center_comments_routes from api.routes import data_center_drill as data_center_drill_routes from api.database import init_db app.include_router(auth_routes.router, prefix="/api") app.include_router(social_routes.router, prefix="/api") app.include_router(search_routes.router, prefix="/api") app.include_router(people_routes.router, prefix="/api") app.include_router(decisions_routes.router, prefix="/api") app.include_router(policy_questions_routes.router, prefix="/api") app.include_router(jurisdiction_documents_routes.router, prefix="/api") app.include_router(jurisdiction_meeting_documents_routes.router, prefix="/api") app.include_router(governing_bodies_routes.router, prefix="/api") app.include_router(documents_routes.router, prefix="/api") app.include_router(event_bills_routes.router, prefix="/api") app.include_router(meetings_routes.router, prefix="/api") app.include_router(meeting_comparison_routes.router, prefix="/api") app.include_router(stats_routes.router, prefix="/api", tags=["stats"]) app.include_router(contact_routes.router, prefix="/api") app.include_router(chat_meetings_routes.router, prefix="/api") app.include_router(stance_routes.router, prefix="/api") app.include_router(bills_routes.router, prefix="/api") app.include_router(data_deletion_routes.router, prefix="/api", tags=["privacy"]) app.include_router(trending_routes.router) app.include_router(lighthouse_reports_routes.router, prefix="/api") app.include_router(jurisdiction_mapping_routes.router, prefix="/api") app.include_router(batch_jobs_routes.router, prefix="/api") app.include_router(deployments_routes.router, prefix="/api") app.include_router(locations_routes.router, prefix="/api") app.include_router(addresses_routes.router, prefix="/api") app.include_router(geocode_routes.router, prefix="/api") app.include_router(cpi_routes.router, prefix="/api", tags=["cpi"]) app.include_router(grants_routes.router, prefix="/api") app.include_router(efile990_routes.router, prefix="/api") # Prefix ("/api/lenses") is baked into the router — include with NO extra prefix # (mirrors how trending_routes is registered). app.include_router(lenses_routes.router) # Prefix ("/api/money-flow") baked into the router — include with NO extra prefix. app.include_router(money_flow_routes.router) # Prefix ("/api/topics") baked into the router — include with NO extra prefix. app.include_router(topics_routes.router) # Sitemaps + the server-rendered SPA shell with per-route meta (#1430); registered before the catch-all. app.include_router(seo_routes.router) # Prefix ("/api/short-term-rentals") baked into the router (#1015). app.include_router(short_term_rentals_routes.router) app.include_router(topic_companies_routes.router) # Topic timeline + period dumbbell (#1140); prefix /api/topics baked in. app.include_router(topic_timeline_routes.router) # Every main topic, last year vs this year (#1343); prefix /api/topics baked in. app.include_router(topic_yoy_routes.router) # Where places stand on a topic (#1437); prefix /api/rankings baked in. app.include_router(rankings_routes.router) # State bills, local actions and public positions on a topic (#1274); prefix /api/topics baked in. app.include_router(topic_policy_routes.router) app.include_router(topic_upcoming_routes.router) # The nonprofits tied to a topic, ranked by evidence (#1345). app.include_router(topic_organizations_routes.router) app.include_router(topic_outcomes_routes.router) # Prefix ("/api/topics") baked into the router (#1125): the facts behind a topic caption. app.include_router(topic_caption_facts_routes.router) # Prefix ("/api/organizations") baked into the router (#1015): the organization page. app.include_router(organizations_routes.router) # Prefix ("/api/money-and-talk") baked into the router — include with NO extra prefix. app.include_router(money_and_talk_routes.router) # Prefix ("/api/grandkid-outlook") baked into the router — include with NO extra prefix. app.include_router(grandkid_outlook_routes.router) # Prefix ("/api/local-finance") baked into the router — include with NO extra prefix. app.include_router(local_finance_routes.router) app.include_router(benchmark_routes.router) # Prefix ("/api/browse") baked into the router — include with NO extra prefix. app.include_router(browse_routes.router) # Flat decision-browse list. Router prefix is "/decisions"; add the shared "/api" # prefix the other routers use (distinct from decisions_routes' "/decision" detail). app.include_router(decision_browse_routes.router, prefix="/api") # Flat meeting-browse list. Router prefix is "/meetings"; add the shared "/api" # prefix (meeting-grain analogue of decision_browse_routes). app.include_router(meeting_browse_routes.router, prefix="/api") app.include_router(alerts_routes.router, prefix="/api") app.include_router(feed_routes.router, prefix="/api") # Data-center job claims by phase (#246). Router prefix is "/data-centers". app.include_router(data_centers_routes.router, prefix="/api") app.include_router(data_center_comments_routes.router, prefix="/api") app.include_router(data_center_drill_routes.router, prefix="/api") # Data center sites over time and recording coverage (#1348). from api.routes import data_center_sites_timeline as data_center_sites_timeline_routes from api.routes import recorded_coverage as recorded_coverage_routes app.include_router(data_center_sites_timeline_routes.router, prefix="/api") app.include_router(recorded_coverage_routes.router, prefix="/api") # Data-center job-application links (#248): public list + admin screen. from api.routes import application_links as application_links_routes app.include_router(application_links_routes.public_router, prefix="/api") app.include_router(application_links_routes.admin_router, prefix="/api") # Jev meeting-kind review / override (#668). from api.routes import meeting_kind_reviews as meeting_kind_reviews_routes app.include_router(meeting_kind_reviews_routes.admin_router, prefix="/api") # Official profile claims + pending edits (#1062). Router prefix is "/people". from api.routes import person_claims as person_claims_routes app.include_router(person_claims_routes.router, prefix="/api") # Custom Swagger UI with logo. # Served at /api/docs (not /docs) so the /docs/ path is free for the Docusaurus # documentation bundle in single-process deployments (Databricks Apps) and to # match the HuggingFace layout where nginx owns /docs/. ReDoc stays at /redoc. @app.get("/api/docs", include_in_schema=False) async def custom_swagger_ui_html(): """Custom Swagger UI with CommunityOne logo""" return get_swagger_ui_html( openapi_url=app.openapi_url, title=f"{app.title} - API Documentation", swagger_favicon_url="/static/communityone_logo_64.png", swagger_ui_parameters={ "defaultModelsExpandDepth": -1, "docExpansion": "list", "filter": True, "syntaxHighlight.theme": "monokai" } ) # Initialize database on startup @app.on_event("startup") async def init_database(): """Initialize authentication database""" try: init_db() logger.info("✅ Authentication database initialized") except Exception as e: logger.warning(f"⚠️ Database initialization skipped: {e}") # Initialize components orchestrator = OrchestratorAgent() pipeline = DeltaLakePipeline() heatmap_generator = AdvocacyHeatmap() # Pydantic models for API class ScrapeTarget(BaseModel): """Configuration for a scraping target.""" url: str municipality: str state: str platform: str = "generic" class WorkflowRequest(BaseModel): """Request to start a new analysis workflow.""" scrape_targets: List[ScrapeTarget] date_range: Optional[Dict[str, str]] = None description: Optional[str] = None class WorkflowResponse(BaseModel): """Response for workflow operations.""" workflow_id: str status: str message: str class OpportunityFilter(BaseModel): """Filters for querying opportunities.""" state: Optional[str] = None municipality: Optional[str] = None topic: Optional[str] = None urgency: Optional[str] = None min_date: Optional[date] = None max_date: Optional[date] = None class OpportunityResponse(BaseModel): """Response containing advocacy opportunities.""" opportunities: List[Dict[str, Any]] total_count: int filters_applied: Dict[str, Any] class SystemStatus(BaseModel): """System status information.""" status: str active_workflows: int agent_status: Dict[str, Any] last_update: datetime class StatesResponse(BaseModel): """Response containing US state codes with active opportunities.""" states: List[str] = Field(..., description="List of 2-letter US state codes") count: int = Field(..., description="Total count of states") # API Endpoints @app.get("/", response_class=HTMLResponse) async def root(request: Request): """Root endpoint. Single-process deployments (Databricks Apps) have no nginx in front to serve the built React SPA, so when the Vite build is present (``api/static/index.html``) we serve it here. Without a build (e.g. an API-only container) we fall back to the informational API landing page below. """ spa_index = Path(__file__).parent / "static" / "index.html" if spa_index.is_file(): # The home page's own meta (#1430), the same shell every SPA path gets. return await seo_routes.spa_response(spa_index, str(request.url.path) + (f"?{request.url.query}" if request.url.query else "")) html_content = """ Open Navigator API

Open Navigator API

CommunityOne: The open path to everything local

🔑 Key Endpoints:

POST /workflow/start - Start a new analysis workflow
GET /opportunities - Query advocacy opportunities
GET /heatmap - Get advocacy heatmap visualization
GET /status - System status and health
POST /auth/login/{provider} - OAuth login (HuggingFace, Google, Facebook, GitHub)
📚 View Full API Documentation """ return HTMLResponse(content=html_content) @app.post("/workflow/start", response_model=WorkflowResponse) async def start_workflow( request: WorkflowRequest, background_tasks: BackgroundTasks ): """ Start a new policy analysis workflow. This initiates the full multi-agent pipeline: 1. Scrape meeting minutes from specified sources 2. Parse and structure the data 3. Classify by oral health topics 4. Analyze sentiment and policy stance 5. Generate advocacy materials """ try: # Register agents with orchestrator orchestrator.register_agent(ScraperAgent()) orchestrator.register_agent(ParserAgent()) orchestrator.register_agent(ClassifierAgent()) orchestrator.register_agent(SentimentAnalyzerAgent()) orchestrator.register_agent(AdvocacyWriterAgent()) # Convert targets to dict format targets = [target.dict() for target in request.scrape_targets] # Start workflow in background background_tasks.add_task( orchestrator.execute_pipeline, targets, request.date_range ) return WorkflowResponse( workflow_id="wf-" + datetime.utcnow().strftime("%Y%m%d-%H%M%S"), status="started", message=f"Workflow started with {len(targets)} targets" ) except Exception as e: logger.error(f"Error starting workflow: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.get("/workflow/{workflow_id}/status") async def get_workflow_status(workflow_id: str): """Get the status of a specific workflow.""" # Query workflow status from orchestrator # This is a placeholder - would query actual workflow state return { "workflow_id": workflow_id, "status": "running", "stage": "classification", "progress": 0.6 } @app.get("/opportunities", response_model=OpportunityResponse) async def get_opportunities( state: Optional[str] = Query(None, description="Filter by state code"), municipality: Optional[str] = Query(None, description="Filter by municipality"), topic: Optional[str] = Query(None, description="Filter by policy topic"), urgency: Optional[str] = Query(None, description="Filter by urgency level"), limit: int = Query(100, ge=1, le=1000, description="Maximum results to return") ): """ Query advocacy opportunities. Returns a list of identified opportunities for advocacy action based on the specified filters. """ try: # Query from Delta Lake opportunities = pipeline.query_opportunities_by_state(state, urgency) # Apply additional filters if municipality: opportunities = [ opp for opp in opportunities if opp.get("municipality", "").lower() == municipality.lower() ] if topic: opportunities = [ opp for opp in opportunities if opp.get("topic") == topic ] # Limit results opportunities = opportunities[:limit] return OpportunityResponse( opportunities=opportunities, total_count=len(opportunities), filters_applied={ "state": state, "municipality": municipality, "topic": topic, "urgency": urgency } ) except Exception as e: logger.error(f"Error querying opportunities: {e}") raise HTTPException(status_code=500, detail=str(e)) # Deterministic state center coordinates (WGS84) used as a fallback when a bill's # linked jurisdiction row does not provide explicit latitude/longitude coordinates. STATE_COORDS: Dict[str, tuple[float, float]] = { "AL": (32.806671, -86.791130), "AK": (61.370716, -152.404419), "AZ": (33.729759, -111.431221), "AR": (34.969704, -92.373123), "CA": (36.116203, -119.681564), "CO": (39.059811, -105.311104), "CT": (41.597782, -72.755371), "DE": (39.318523, -75.507141), "DC": (38.897438, -77.026817), "FL": (27.766279, -81.686783), "GA": (33.040619, -83.643074), "HI": (21.094318, -157.498337), "ID": (44.240459, -114.478828), "IL": (40.349457, -88.986137), "IN": (39.849426, -86.258278), "IA": (42.011539, -93.210526), "KS": (38.526600, -96.726486), "KY": (37.668140, -84.670067), "LA": (31.169546, -91.867805), "ME": (44.693947, -69.381927), "MD": (39.063946, -76.802101), "MA": (42.230171, -71.530106), "MI": (43.326618, -84.536095), "MN": (45.694454, -93.900192), "MS": (32.741646, -89.678696), "MO": (38.456085, -92.288368), "MT": (46.921925, -110.454353), "NE": (41.125370, -98.268082), "NV": (38.313515, -117.055374), "NH": (43.452492, -71.563896), "NJ": (40.298904, -74.521011), "NM": (34.840515, -106.248482), "NY": (42.165726, -74.948051), "NC": (35.630066, -79.806419), "ND": (47.528912, -99.784012), "OH": (40.388783, -82.764915), "OK": (35.565342, -96.928917), "OR": (44.572021, -122.070938), "PA": (40.590752, -77.209755), "RI": (41.680893, -71.511780), "SC": (33.856892, -80.945007), "SD": (44.299782, -99.438828), "TN": (35.747845, -86.692345), "TX": (31.054487, -97.563461), "UT": (40.150032, -111.862434), "VT": (44.045876, -72.710686), "VA": (37.769337, -78.169968), "WA": (47.400902, -121.490494), "WV": (38.491226, -80.954453), "WI": (44.268543, -89.616508), "WY": (42.755966, -107.302490), } DEFAULT_OPPORTUNITY_STATES: tuple[str, ...] = ("AL", "GA", "IN", "MA", "WA", "WI") _OPPORTUNITY_TOPIC_ALIASES: Dict[str, str] = { "fluoride": "water_fluoridation", "water_fluoridation": "water_fluoridation", "dental": "school_dental_screening", "school_dental_screening": "school_dental_screening", "medicaid": "medicaid_dental_expansion", "medicaid_dental_expansion": "medicaid_dental_expansion", } # React frontend endpoints with /api/ prefix @app.get("/api/opportunities") async def get_api_opportunities( state: Optional[str] = Query(None), topic: Optional[str] = Query(None), urgency: Optional[str] = Query(None), limit: int = Query(100, ge=1, le=1000) ): """API endpoint for React frontend opportunities page - returns fluoridation bills as advocacy opportunities.""" try: from api.routes.bills_neon import get_pool if state is not None: state_norm = state.strip().upper() if state_norm not in STATE_COORDS: return {"opportunities": [], "total": 0} states = [state_norm] else: states = list(DEFAULT_OPPORTUNITY_STATES) topic_norm: Optional[str] = None if topic is not None and topic.strip(): raw_topic = topic.strip().lower() topic_norm = _OPPORTUNITY_TOPIC_ALIASES.get(raw_topic, raw_topic) urgency_norm: Optional[str] = ( urgency.strip().lower() if urgency is not None and urgency.strip() else None ) pool = await get_pool() if pool is None: return {"opportunities": [], "total": 0} sql_limit = min(max(limit * 5, limit), 1000) if (topic_norm or urgency_norm) else limit # Query the Postgres `bills` mart joined to `jurisdictions` so real # jurisdiction coordinates are used when available, with deterministic # fallback to STATE_COORDS. query_with_jurisdictions = """ SELECT b.state_code, b.title, b.identifier, b.session_identifier, b.latest_action_description, b.latest_action_date, j.latitude::float8 AS jurisdiction_latitude, j.longitude::float8 AS jurisdiction_longitude FROM bills b LEFT JOIN jurisdictions j ON j.jurisdiction_id = b.jurisdiction_id WHERE b.state_code = ANY($1::text[]) AND (LOWER(b.title) LIKE '%fluorid%' OR LOWER(b.title) LIKE '%dental%' OR LOWER(b.title) LIKE '%oral health%' OR LOWER(b.title) LIKE '%water treat%') ORDER BY b.latest_action_date DESC NULLS LAST, b.identifier ASC LIMIT $2 """ fallback_query = """ SELECT state_code, title, identifier, session_identifier, latest_action_description, latest_action_date FROM bills WHERE state_code = ANY($1::text[]) AND (LOWER(title) LIKE '%fluorid%' OR LOWER(title) LIKE '%dental%' OR LOWER(title) LIKE '%oral health%' OR LOWER(title) LIKE '%water treat%') ORDER BY latest_action_date DESC NULLS LAST, identifier ASC LIMIT $2 """ async with pool.acquire() as conn: try: result = await conn.fetch(query_with_jurisdictions, states, sql_limit) except Exception: result = await conn.fetch(fallback_query, states, sql_limit) opportunities = [] for row in result: row_dict = dict(row) state_code = (row_dict.get("state_code") or "").strip().upper() title = row_dict.get("title") identifier = row_dict.get("identifier") session = row_dict.get("session_identifier") latest_action = row_dict.get("latest_action_description") latest_action_date = row_dict.get("latest_action_date") title_lower = title.lower() if title else "" if "fluoride" in title_lower or "fluorin" in title_lower or "water" in title_lower: urgency_level = "critical" confidence = 0.9 topic_type = "water_fluoridation" elif "dental" in title_lower: urgency_level = "high" confidence = 0.75 topic_type = "school_dental_screening" else: urgency_level = "medium" confidence = 0.6 topic_type = "medicaid_dental_expansion" if topic_norm and topic_type != topic_norm: continue if urgency_norm and urgency_level != urgency_norm: continue juris_lat = row_dict.get("jurisdiction_latitude") juris_lon = row_dict.get("jurisdiction_longitude") if juris_lat is not None and juris_lon is not None: latitude = float(juris_lat) longitude = float(juris_lon) elif state_code in STATE_COORDS: latitude, longitude = STATE_COORDS[state_code] else: continue opportunities.append({ "state": state_code, "municipality": f"{state_code} Legislature", "latitude": latitude, "longitude": longitude, "topic": topic_type, "urgency": urgency_level, "confidence": confidence, "meeting_date": latest_action_date.isoformat() if hasattr(latest_action_date, "isoformat") else (str(latest_action_date) if latest_action_date else None), "title": title, "bill_id": identifier, "session": session, "latest_action": latest_action, }) if len(opportunities) >= limit: break return {"opportunities": opportunities, "total": len(opportunities)} except Exception as e: logger.error(f"Error: {e}") return {"opportunities": [], "total": 0} @app.get("/api/documents") async def get_api_documents( search: Optional[str] = Query(None), page: int = Query(1), limit: int = Query(20) ): """API endpoint for React frontend documents page.""" try: # Get all opportunities (documents) documents = pipeline.query_opportunities_by_state(None, None) # Apply search filter if search: search_lower = search.lower() documents = [ d for d in documents if search_lower in d.get("title", "").lower() or search_lower in d.get("municipality", "").lower() or search_lower in d.get("content", "").lower() ] # Paginate start = (page - 1) * limit end = start + limit return { "documents": documents[start:end], "total": len(documents), "page": page, "limit": limit } except Exception as e: logger.error(f"Error: {e}") return {"documents": [], "total": 0} @app.get("/opportunities/{opportunity_id}") async def get_opportunity_detail(opportunity_id: str): """Get detailed information about a specific opportunity.""" # Query specific opportunity document = pipeline.get_document_by_id(opportunity_id) if not document: raise HTTPException(status_code=404, detail="Opportunity not found") return document @app.get("/opportunities/{opportunity_id}/materials") async def get_advocacy_materials(opportunity_id: str): """Get generated advocacy materials for an opportunity.""" # Query materials from Delta Lake # This is a placeholder return { "opportunity_id": opportunity_id, "materials": { "email": { "subject": "Support Oral Health Policy", "body": "..." }, "talking_points": [], "social_media": {} } } @app.get("/heatmap", response_class=HTMLResponse) async def get_heatmap( urgency: Optional[str] = Query(None, description="Filter by urgency level") ): """ Get interactive heatmap visualization. Returns an HTML page with an interactive map showing advocacy opportunities across the country. """ try: # Query opportunities opportunities = pipeline.query_opportunities_by_state(None, urgency) # Generate map m = heatmap_generator.create_folium_map( opportunities, title="Open Navigator - Advocacy Heatmap" ) # Return HTML return HTMLResponse(content=m._repr_html_()) except Exception as e: logger.error(f"Error generating heatmap: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.get("/dashboard") async def get_dashboard(): """ Get complete dashboard data including statistics and visualizations. """ try: # Query all opportunities opportunities = pipeline.query_opportunities_by_state(None, None) # Generate dashboard dashboard = heatmap_generator.create_dashboard(opportunities) # Convert visualizations to JSON-serializable format return { "statistics": dashboard["statistics"], "topic_distribution": dashboard["topic_distribution"].to_json(), "timeline": dashboard["timeline"].to_json() } except Exception as e: logger.error(f"Error generating dashboard: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.get("/api/dashboard") async def get_api_dashboard(): """ Get dashboard statistics for React frontend. Returns data in format expected by frontend Dashboard component. """ try: # Query all opportunities opportunities = pipeline.query_opportunities_by_state(None, None) # Count topics topics_count = {} for opp in opportunities: topic = opp.get("topic", "unknown") topics_count[topic] = topics_count.get(topic, 0) + 1 # Get unique states states = set(opp.get("state") for opp in opportunities if opp.get("state")) # Get recent opportunities (last 10) recent = sorted( opportunities, key=lambda x: x.get("meeting_date", ""), reverse=True )[:10] return { "total_documents": len(opportunities), "total_opportunities": len(opportunities), "states_monitored": len(states), "topics": topics_count, "recent_opportunities": recent } except Exception as e: logger.error(f"Error generating API dashboard: {e}") # Return mock data if there's an error return { "total_documents": 0, "total_opportunities": 0, "states_monitored": 0, "topics": {}, "recent_opportunities": [] } @app.get("/topics") async def get_topics(): """Get list of all policy topics being tracked.""" return { "topics": settings.policy_topics, "count": len(settings.policy_topics) } @app.get("/states", response_model=StatesResponse, tags=["opportunities"]) @app.get("/api/states", response_model=StatesResponse, tags=["opportunities"]) async def get_states() -> StatesResponse: """Get list of all states with active opportunities. Queries distinct state codes from active bills in the database if available. When the query fails or returns nothing, uses the configured `settings.target_states` (real configuration). If that is not set either, returns an empty list rather than inventing states. """ try: from api.routes.bills_neon import get_pool pool = await get_pool() if pool is not None: query = """ SELECT DISTINCT UPPER(state_code) AS state_code FROM bills WHERE state_code IS NOT NULL AND state_code != '' AND ( LOWER(title) LIKE '%fluorid%' OR LOWER(title) LIKE '%dental%' OR LOWER(title) LIKE '%oral health%' OR LOWER(title) LIKE '%water treat%' ) ORDER BY UPPER(state_code) """ async with pool.acquire() as conn: rows = await conn.fetch(query) db_states = sorted(set(str(row["state_code"]).strip().upper() for row in rows if row.get("state_code"))) if db_states: return StatesResponse(states=db_states, count=len(db_states)) except Exception as e: logger.warning(f"Failed to query active opportunity states from bills database: {e}") # No database result: use configured target states (real configuration), never an invented list. configured_states = settings.target_states if configured_states: resolved = sorted(set(st.strip().upper() for st in configured_states if st and st.strip())) else: resolved = [] logger.warning("No active opportunity states from the database and settings.target_states is not set; returning an empty list") return StatesResponse(states=resolved, count=len(resolved)) @app.get("/status", response_model=SystemStatus) async def get_system_status(): """Get current system status and health.""" try: agent_status = orchestrator.get_all_agent_states() return SystemStatus( status="operational", active_workflows=len(orchestrator.active_workflows), agent_status=agent_status, last_update=datetime.utcnow() ) except Exception as e: logger.error(f"Error getting system status: {e}") return SystemStatus( status="error", active_workflows=0, agent_status={}, last_update=datetime.utcnow() ) @app.get("/nonprofits") async def search_nonprofits( location: str = Query("Tuscaloosa, AL", description="City, State format"), keyword: Optional[str] = Query(None, description="Service keyword (e.g., 'dental', 'health')"), state: Optional[str] = Query(None, description="2-letter state code (e.g., 'AL')"), ntee_code: Optional[str] = Query(None, description="NTEE code (e.g., 'E' for health)"), source: Optional[str] = Query(None, description="Data source: 'propublica', 'everyorg', 'all'") ): """ Search for nonprofits using free open data APIs. Integrates data from: - ProPublica Nonprofit Explorer (financial data, NTEE codes) - Every.org (mission statements, logos) - IRS TEOS (official tax-exempt status) Example: /nonprofits?location=Tuscaloosa,AL&keyword=dental&ntee_code=E """ try: from scrapers.irs.nonprofit_discovery import NonprofitDiscovery discovery = NonprofitDiscovery() results = [] # Parse location for state/city location_parts = location.split(',') city = location_parts[0].strip() if len(location_parts) > 0 else None state_from_location = location_parts[1].strip() if len(location_parts) > 1 else None state_code = state or state_from_location or "AL" # Determine which sources to query sources_to_query = ['propublica', 'everyorg'] if source == 'all' or not source else [source] # Query ProPublica if 'propublica' in sources_to_query: try: propublica_results = discovery.search_propublica( state=state_code, city=city, ntee_code=ntee_code ) results.extend(propublica_results) logger.info(f"ProPublica: Found {len(propublica_results)} organizations") except Exception as e: logger.warning(f"ProPublica search failed: {e}") # Query Every.org if 'everyorg' in sources_to_query: try: causes = [] if keyword: # Map keywords to causes keyword_lower = keyword.lower() if 'health' in keyword_lower or 'dental' in keyword_lower or 'medical' in keyword_lower: causes.append('health') if 'education' in keyword_lower or 'school' in keyword_lower: causes.append('education') everyorg_results = discovery.search_everyorg( location=location, causes=causes if causes else None ) results.extend(everyorg_results) logger.info(f"Every.org: Found {len(everyorg_results)} organizations") except Exception as e: logger.warning(f"Every.org search failed: {e}") # Filter by keyword if provided if keyword and results: keyword_lower = keyword.lower() filtered_results = [] for org in results: # Search in name, description, mission, ntee_description searchable_text = ' '.join([ str(org.get('name', '')), str(org.get('description', '')), str(org.get('mission', '')), str(org.get('ntee_description', '')) ]).lower() if keyword_lower in searchable_text: filtered_results.append(org) results = filtered_results return { "location": location, "keyword": keyword, "state": state_code, "ntee_code": ntee_code, "count": len(results), "nonprofits": results, "data_sources": { "propublica": "https://projects.propublica.org/nonprofits/api", "everyorg": "https://www.every.org/nonprofit-api", "irs_teos": "https://www.irs.gov/charities-non-profits/tax-exempt-organization-search-bulk-data-downloads" } } except Exception as e: logger.error(f"Nonprofit search error: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.get("/api/nonprofits") async def search_nonprofits_api( location: str = Query("Tuscaloosa, AL", description="City, State format"), keyword: Optional[str] = Query(None, description="Service keyword (e.g., 'dental', 'health')"), state: Optional[str] = Query(None, description="2-letter state code (e.g., 'AL')"), ntee_code: Optional[str] = Query(None, description="NTEE code (e.g., 'E' for health)"), source: Optional[str] = Query(None, description="Data source: 'propublica', 'everyorg', 'all'") ): """ Search for nonprofits using free open data APIs (API-prefixed endpoint for frontend). This is a duplicate of /nonprofits with /api prefix for frontend routing. """ return await search_nonprofits(location, keyword, state, ntee_code, source) @app.get("/data/status") async def get_data_ingestion_status(): """ Get status of reference data ingestions. Shows Census jurisdictions, NCES school districts, and nonprofit cache status. Every count is a real warehouse value (see ``stats_neon.fetch_national_reference_counts``) or ``null`` when it can't be computed — never a hard-coded estimate (CLAUDE.md, "No Fabricated Data"). """ try: from pathlib import Path from api.routes.stats_neon import fetch_national_reference_counts counts = await fetch_national_reference_counts() status = { "census": { "jurisdictions": counts["jurisdictions"], "counties": counts["counties"], "municipalities": counts["municipalities"], "status": "public.jurisdiction_state_aggregate (national) + public.civic_jurisdiction", }, "nces": { "school_districts": counts["school_districts"], "status": "public.jurisdiction_state_aggregate (national)", }, "nonprofits": { "total_available": counts["nonprofits"], "cached_searches": 0, "cache_path": "data/cache/nonprofits" }, # Per-source meeting counts (MeetingBank, City Scrapers, Open States) # are not modeled in `public`; unavailable rather than guessed. "meetings": { "meetingbank": None, "city_scrapers": None, "open_states": None, } } # Check cache directories cache_dir = Path("data/cache/nonprofits") if cache_dir.exists(): cached_files = list(cache_dir.glob("*.json")) status["nonprofits"]["cached_searches"] = len(cached_files) return status except Exception as e: logger.error(f"Data status error: {e}") return {"error": str(e)} @app.post("/data/ingest/nonprofits") async def bulk_ingest_nonprofits( state: str = Query(..., description="State code (e.g., AL)"), ntee_code: Optional[str] = Query("E", description="NTEE code (default: E for Health)") ): """ Bulk ingest nonprofit data for a state. Caches ProPublica API results for offline use. """ try: from scrapers.irs.nonprofit_discovery import NonprofitDiscovery discovery = NonprofitDiscovery() orgs = discovery.search_propublica(state=state, ntee_code=ntee_code) return { "message": f"Ingested {len(orgs)} nonprofits for {state}", "state": state, "ntee_code": ntee_code, "count": len(orgs), "cache_location": "data/cache/nonprofits" } except Exception as e: logger.error(f"Nonprofit ingestion error: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.get("/health") async def health_check(): """Health check endpoint for monitoring.""" return { "status": "healthy", "timestamp": datetime.utcnow().isoformat(), "version": "1.0.0" } @app.get("/api/health") async def api_health_check(): """Health check endpoint for monitoring (API path).""" return { "status": "healthy", "timestamp": datetime.utcnow().isoformat(), "version": "1.0.0" } @app.post("/admin/initialize") async def initialize_system(): """Initialize Delta Lake tables and system components.""" try: pipeline.initialize_tables() return { "status": "success", "message": "System initialized successfully" } except Exception as e: logger.error(f"Error initializing system: {e}") raise HTTPException(status_code=500, detail=str(e)) # Startup event @app.post("/api/debate-grade") async def grade_decision_with_debate_framework( document_id: Optional[str] = Query(None, description="Document ID to grade"), text: Optional[str] = Query(None, description="Text to grade directly"), title: Optional[str] = Query("", description="Document title") ): """ Grade a government decision using debate framework (Harms/Solvency/Topicality). Translates debate concepts for laypeople: - Harms → "The Problem": Why is this a crisis? - Solvency → "The Fix": How does this solution work? - Topicality → "The Scope": Does the government have authority? Example: /api/debate-grade?text=The city council approved funding for dental screening... """ try: from agents.debate_grader import DebateGraderAgent grader = DebateGraderAgent() # Get document content if document_id: document = pipeline.get_document_by_id(document_id) if not document: raise HTTPException(status_code=404, detail="Document not found") elif text: document = { "content": text, "title": title, "id": "custom_text" } else: raise HTTPException(status_code=400, detail="Provide either document_id or text") # Grade the document grade = await grader._grade_document(document) return { "document_id": document.get("id"), "title": document.get("title", ""), "debate_grade": grade, "explanation": { "harms": "This measures how well the decision identifies and documents the problem using data and evidence", "solvency": "This measures how clearly the solution is defined and whether it will actually fix the problem", "topicality": "This measures whether the government body has the legal authority to take this action" } } except HTTPException: raise except Exception as e: logger.error(f"Debate grading error: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.post("/api/debate-grade/batch") async def grade_decisions_batch( state: Optional[str] = Query(None, description="Filter by state"), topic: Optional[str] = Query(None, description="Filter by topic"), limit: int = Query(50, description="Number of documents to grade") ): """ Grade multiple government decisions using debate framework. Returns aggregate insights about decision quality across dimensions. """ try: from agents.debate_grader import DebateGraderAgent from agents.base import AgentMessage, MessageType, AgentRole grader = DebateGraderAgent() # Get documents to grade documents = pipeline.query_opportunities_by_state(state, None) if topic: documents = [d for d in documents if d.get("topic") == topic] documents = documents[:limit] # Create message and process message = AgentMessage( message_id=f"batch_grade_{datetime.utcnow().timestamp()}", sender=AgentRole.ORCHESTRATOR, recipient=AgentRole.DEBATE_GRADER, message_type=MessageType.COMMAND, payload={"documents": documents} ) result = await grader.process(message) graded_documents = result[0].payload.get("documents", []) insights = result[0].payload.get("insights", {}) return { "graded_count": len(graded_documents), "documents": graded_documents, "insights": insights, "explanation": { "average_scores": "Average scores across all three debate dimensions (out of 5)", "strongest_dimension": "Which dimension governments perform best on", "weakest_dimension": "Which dimension needs the most improvement" } } except Exception as e: logger.error(f"Batch debate grading error: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.on_event("startup") async def startup_event(): """Initialize system on startup with data validation.""" logger.info("="*80) logger.info("🚀 STARTING Open Navigator API") logger.info("="*80) logger.info(f"Configuration: {settings.catalog_name}.{settings.schema_name}") logger.info(f"Log Level: {settings.log_level}") logger.info(f"Log File: {settings.log_file}") # Check if running on HuggingFace Spaces IS_HF_SPACES = os.getenv("HF_SPACES") == "1" if IS_HF_SPACES: logger.info(f"🤗 Running on HuggingFace Spaces") else: logger.info(f"💻 Running in local/standard environment") # Validate critical data files logger.info("") logger.info("📊 VALIDATING DATA AVAILABILITY...") logger.info("-" * 80) data_dir = Path("data/gold") critical_files = [] optional_files = [] # Check reference data (critical). These now come from the Postgres `public` # schema rather than local parquet (CLAUDE.md: API must read `public`). # Each probe reports its live row count via SELECT count(*). import psycopg2 _ref_dsn = os.getenv( "NEON_DATABASE_URL_DEV", "postgresql://postgres:password@localhost:5433/open_navigator", ) # label -> SQL count query against public schema reference_db_checks = [ ("jurisdictions (city/town/county)", "SELECT count(*) FROM public.jurisdictions " "WHERE jurisdiction_type IN ('city','town','county')"), ("jurisdictions (counties)", "SELECT count(*) FROM public.jurisdictions " "WHERE jurisdiction_type = 'county'"), ("causes (public.tag)", "SELECT count(*) FROM public.tag"), ] try: _ref_conn = psycopg2.connect(_ref_dsn) _ref_cur = _ref_conn.cursor() for label, query in reference_db_checks: try: _ref_cur.execute(query) _count = _ref_cur.fetchone()[0] logger.info(f" ✅ {label}: {_count:,} records (public schema)") critical_files.append(label) except Exception as e: logger.error(f" ❌ {label}: ERROR - {e}") _ref_cur.close() _ref_conn.close() except Exception as e: logger.error(f" ❌ reference counts: could not connect to public schema - {e}") # State data availability — served from the Postgres `public` schema. # events -> public.event grouped by state_code (NOT per-state parquet dirs). # NOTE: nonprofits (public.mdm_organization_nonprofit) has no state_code and # no usable org->location join, so a per-state nonprofit count is not # available here; only the national count is logged below. logger.info("") logger.info("📍 STATE DATA AVAILABILITY:") try: _state_conn = psycopg2.connect(_ref_dsn) _state_cur = _state_conn.cursor() _state_cur.execute( "SELECT state_code, count(*) FROM public.event " "WHERE state_code IS NOT NULL GROUP BY state_code ORDER BY state_code" ) _state_rows = _state_cur.fetchall() _state_cur.execute("SELECT count(*) FROM public.mdm_organization_nonprofit") _np_national = _state_cur.fetchone()[0] _state_cur.close() _state_conn.close() for sc, cnt in _state_rows[:10]: # Show first 10 states logger.info(f" ✅ {sc}: {cnt:,} events") total_states = len(_state_rows) if total_states > 10: logger.info(f" ... and {total_states - 10} more states") logger.info(f"") logger.info(f" 📊 Total states with events: {total_states}") logger.info(f" 🏢 public.mdm_organization_nonprofit: {_np_national:,} nonprofits (national)") except Exception as e: logger.warning(f" ⚠️ Could not read per-state event counts from public schema: {e}") # Officials are served from contact_official (not parquet). Log the # live row count once so the startup banner still reports officials volume. try: import psycopg2 _officials_dsn = os.getenv( "NEON_DATABASE_URL_DEV", "postgresql://postgres:password@localhost:5433/open_navigator", ) _conn = psycopg2.connect(_officials_dsn) _cur = _conn.cursor() _cur.execute("SELECT count(*) FROM contact_official") _officials_count = _cur.fetchone()[0] _cur.close() _conn.close() logger.info(f" 🏛️ contact_official: {_officials_count:,} officials") except Exception as e: logger.warning(f" ⚠️ Could not count contact_official: {e}") # Validate HuggingFace datasets if running on HF Spaces if IS_HF_SPACES: logger.info("") logger.info("🤗 VALIDATING HUGGINGFACE DATASETS...") logger.info("-" * 80) # Check a sample of critical datasets (using new consolidated datasets) import requests test_datasets = [ ("https://huggingface.co/datasets/CommunityOne/one-bills/resolve/main/data/train-00000-of-00001.parquet", "Bills (Consolidated)"), ("https://huggingface.co/datasets/CommunityOne/one-local-officials/resolve/main/data/train-00000-of-00001.parquet", "Local Officials (Consolidated)"), ("https://huggingface.co/datasets/CommunityOne/one-nonprofits-organizations/resolve/main/data/train-00000-of-00001.parquet", "Nonprofits (Consolidated)"), ] hf_datasets_ok = 0 for url, display_name in test_datasets: try: response = requests.head(url, timeout=10, allow_redirects=True) if response.status_code == 200: logger.info(f" ✅ {display_name}: Accessible") hf_datasets_ok += 1 else: logger.error(f" ❌ {display_name}: HTTP {response.status_code}") logger.error(f" URL: {url}") except Exception as e: logger.error(f" ❌ {display_name}: {type(e).__name__} - {e}") logger.error(f" URL: {url}") logger.info("") logger.info(f" 📊 HuggingFace datasets validated: {hf_datasets_ok}/{len(test_datasets)}") if hf_datasets_ok < len(test_datasets): logger.warning(" ⚠️ Some datasets are not accessible - API may have limited functionality") logger.info("") logger.info("="*80) logger.info(f"✅ API READY - {len(critical_files)}/{len(reference_db_checks)} critical files available") if IS_HF_SPACES: logger.info(f"✅ HuggingFace datasets validated") logger.info("="*80) logger.info("") # Shutdown event @app.on_event("shutdown") async def shutdown_event(): """Cleanup on shutdown.""" logger.info("Shutting down CommunityOne Open Navigator API") # --------------------------------------------------------------------------- # Built frontend (React/Vite) + docs (Docusaurus) — single-process serving # --------------------------------------------------------------------------- # In the HuggingFace deployment nginx serves these static bundles and proxies # only /api to uvicorn. Databricks Apps run ONE process with no fronting proxy, # so FastAPI itself must serve the SPA and the docs. These routes are registered # LAST (after every API router) so the greedy ``/{full_path:path}`` catch-all # cannot shadow a real API route. The whole block is a no-op when no build is # present (api/static/index.html missing), e.g. an API-only container. _spa_static_dir = Path(__file__).parent / "static" if (_spa_static_dir / "index.html").is_file(): from fastapi.responses import FileResponse # Hashed JS/CSS produced by Vite (build outDir = api/static, so /assets here). _assets_dir = _spa_static_dir / "assets" if _assets_dir.is_dir(): app.mount("/assets", StaticFiles(directory=_assets_dir), name="spa_assets") logger.info(f"Serving built SPA + docs from {_spa_static_dir}") @app.get("/{full_path:path}", include_in_schema=False) async def serve_spa_and_docs(full_path: str, request: Request): """Serve the built docs / SPA for any non-API path. Resolution order: 1. /api/* that fell through the routers -> 404 (never serve the SPA for a missing API endpoint, which would mask bugs with a 200 HTML body). 2. A concrete static file inside api/static (assets handled by the mount above; this covers /docs/*, /robots.txt, /pdf/*, favicon, etc.). 3. A directory request that has an index.html (e.g. /docs/ -> docs/index.html). 4. Otherwise the React index.html (client-side routing). Path traversal is guarded via ``relative_to``. """ if full_path == "api" or full_path.startswith("api/"): raise HTTPException(status_code=404, detail="API endpoint not found") if full_path: candidate = (_spa_static_dir / full_path).resolve() try: candidate.relative_to(_spa_static_dir.resolve()) except ValueError: candidate = None if candidate is not None: if candidate.is_file(): return FileResponse(candidate) # Directory (e.g. /docs/) -> its index.html if present. index_in_dir = candidate / "index.html" if candidate.is_dir() and index_in_dir.is_file(): return FileResponse(index_in_dir) # The React shell, with this path's own title, description, canonical and OpenGraph tags (#1430). query = f"?{request.url.query}" if request.url.query else "" return await seo_routes.spa_response(_spa_static_dir / "index.html", f"/{full_path}{query}") if __name__ == "__main__": import uvicorn # Honor DATABRICKS_APP_PORT when running this module directly so a local # `python api/main.py` mirrors the platform launch. The app.yaml command is # the authoritative entry point in production. _port = int(os.getenv("DATABRICKS_APP_PORT", str(settings.api_port))) uvicorn.run( app, host="0.0.0.0", port=_port, workers=settings.api_workers, )