diff --git a/src/climatevision/api/main.py b/src/climatevision/api/main.py index c702e40..81972a2 100644 --- a/src/climatevision/api/main.py +++ b/src/climatevision/api/main.py @@ -7,552 +7,39 @@ - Flood detection - Organization (NGO) management - Alert and subscription systems + +The endpoints live in ``climatevision.api.routes``, one module per resource; +this module builds the application and wires in middleware and routers. """ from __future__ import annotations -import json import logging import os import time -from datetime import datetime, timezone -from pathlib import Path -from typing import Any, Optional, Literal +from typing import Any from contextlib import asynccontextmanager -from pydantic import field_validator - -from fastapi import ( - FastAPI, - File, - Form, - HTTPException, - UploadFile, - Header, - Query, - Depends, - Request, - WebSocket, - WebSocketDisconnect, -) +from fastapi import FastAPI, Request from fastapi.responses import FileResponse, RedirectResponse from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles from starlette.middleware.base import BaseHTTPMiddleware from starlette.responses import Response -from pydantic import BaseModel, Field, EmailStr, model_validator -from climatevision.db import ( - get_connection, - init_db, - create_organization, - get_organization, - get_organization_by_api_key, - list_organizations, - create_subscription, - get_subscriptions_for_organization, - create_organization_alert, - get_alerts_for_organization, - get_pending_alerts, - acknowledge_alert, - mark_alert_delivered, -) -from climatevision.inference import run_inference_from_file, run_inference_from_gee -from climatevision.inference.flood_pipeline import run_flood_inference_from_gee -from climatevision.api.auth import require_api_key -from climatevision.governance import explain_prediction, SHAPExplainer +from climatevision.db import init_db +from climatevision.api.routes import include_routers +from climatevision.api.shared import PROJECT_ROOT from climatevision.security.api_security import SecurityMiddleware from climatevision.workers.alert_delivery import AlertDeliveryWorker -from climatevision.api.run_events import build_status_event, run_event_hub logger = logging.getLogger(__name__) -# ===== Type Definitions ===== - -AnalysisType = Literal["deforestation", "ice_melting", "flooding", "flooding_sar", "drought", "wildfire"] -OrganizationType = Literal["ngo", "government", "research", "corporate"] -NotificationChannel = Literal["email", "webhook", "api", "sms"] -AlertSeverity = Literal["low", "medium", "high", "critical"] - -SUPPORTED_ANALYSIS_TYPES: list[dict[str, Any]] = [ - { - "name": "deforestation", - "display_name": "Deforestation Detection", - "description": "Monitor forest coverage and detect deforestation events", - "enabled": True, - "bands": ["B04", "B03", "B02", "B08"], - "classes": ["non_forest", "forest"], - }, - { - "name": "ice_melting", - "display_name": "Arctic Ice Melting", - "description": "Monitor sea ice extent and melting patterns in polar regions", - "enabled": True, - "bands": ["B02", "B03", "B04", "B11"], - "classes": ["sea_ice", "open_water", "land"], - }, - { - "name": "flooding", - "display_name": "Flood Detection", - "description": "Detect and monitor flooding events and affected areas", - "enabled": True, - "bands": ["B03", "B08", "B11"], - "classes": ["water", "flooded", "dry_land"], - }, - { - "name": "flooding_sar", - "display_name": "Flood Detection (SAR)", - "description": "All-weather flood detection from Sentinel-1 VV/VH using a physics-based ensemble", - "enabled": True, - "bands": ["VV", "VH"], - "classes": ["dry_land", "permanent_water", "flooded"], - }, - { - "name": "drought", - "display_name": "Drought Monitoring", - "description": "Monitor vegetation stress and drought conditions", - "enabled": False, - "bands": ["B04", "B08", "B11", "B12"], - "classes": ["normal", "stressed", "severe_drought"], - }, - { - "name": "wildfire", - "display_name": "Wildfire Detection", - "description": "Detect active fires and burned areas", - "enabled": False, - "bands": ["B04", "B08", "B11", "B12"], - "classes": ["unburned", "burned", "active_fire"], - }, -] - - -def _utc_now_iso() -> str: - return datetime.now(timezone.utc).isoformat() - - -# ===== Run Status Streaming ===== - -# Statuses after which no further updates are expected, so the socket closes. -TERMINAL_RUN_STATUSES = frozenset({"completed", "failed"}) - -# Application-defined close code for "the requested run does not exist". -# The 4000-4999 range is reserved for application use by RFC 6455. -WS_RUN_NOT_FOUND = 4404 - - -def _read_run_status( - run_id: int, -) -> Optional[tuple[str, Optional[dict[str, Any]]]]: - """Read a run's current status and latest result payload. - - Args: - run_id: The run to read. - - Returns: - A ``(status, result_payload)`` pair, or ``None`` if no such run exists. - The payload is ``None`` when the run has not produced a result yet. - """ - with get_connection() as conn: - run = conn.execute( - "SELECT status FROM runs WHERE id = ?", (run_id,) - ).fetchone() - if run is None: - return None - result = conn.execute( - "SELECT payload_json FROM results WHERE run_id = ? ORDER BY id DESC LIMIT 1", - (run_id,), - ).fetchone() - - payload: Optional[dict[str, Any]] = None - if result is not None: - payload = json.loads(result["payload_json"]) - return run["status"], payload - - -def _status_event_for( - run_id: int, status: str, result_payload: Optional[dict[str, Any]] -) -> dict[str, Any]: - """Build a status event, routing the payload to ``result`` or ``error``. - - A failed run stores its message under ``error`` inside the result payload, - so surface that as the event's ``error`` field rather than as a result. - - Args: - run_id: The run the event describes. - status: The run's current status. - result_payload: The stored result payload, if any. - - Returns: - The event dictionary to send over the WebSocket. - """ - if status == "failed": - error = None - if result_payload is not None: - error = result_payload.get("error") - return build_status_event(run_id, status, error=error or "Inference failed") - if status == "completed": - return build_status_event(run_id, status, result=result_payload) - return build_status_event(run_id, status) - - -# ===== Request/Response Models ===== - -class PredictRequest(BaseModel): - kind: str = Field(default="demo") - analysis_type: AnalysisType = Field(default="deforestation") - bbox: Optional[list[float]] = None - start_date: Optional[str] = Field( - default=None, - description="Start date in YYYY-MM-DD format. Must be earlier than end_date.", - ) - end_date: Optional[str] = Field( - default=None, - description="End date in YYYY-MM-DD format. Must be later than start_date.", - ) - enable_carbon: bool = Field( - default=False, - description="If true, include carbon loss estimates for deforestation runs.", - ) - forest_type: Optional[str] = Field( - default=None, - description="Forest type for carbon estimation (e.g. tropical_moist, mangrove).", - ) - region: Optional[str] = Field( - default=None, - description="Region for carbon estimation adjustment (e.g. amazon, congo).", - ) - - @field_validator("bbox") - @classmethod - def validate_bbox(cls, v: Optional[list[float]]) -> Optional[list[float]]: - if v is None: - return v - if len(v) != 4: - raise ValueError("bbox must have exactly 4 values: [west, south, east, north]") - west, south, east, north = v - if not (-180 <= west <= 180 and -180 <= east <= 180): - raise ValueError("bbox longitude values must be between -180 and 180") - if not (-90 <= south <= 90 and -90 <= north <= 90): - raise ValueError("bbox latitude values must be between -90 and 90") - if west >= east: - raise ValueError("bbox west longitude must be less than east longitude") - if south >= north: - raise ValueError("bbox south latitude must be less than north latitude") - return v - - @model_validator(mode="after") - def validate_date_range(self) -> "PredictRequest": - if self.start_date and self.end_date: - try: - start = datetime.strptime(self.start_date, "%Y-%m-%d") - end = datetime.strptime(self.end_date, "%Y-%m-%d") - except ValueError: - raise ValueError("start_date and end_date must be in YYYY-MM-DD format") - if start >= end: - raise ValueError("start_date must be earlier than end_date") - return self - - -class RunRow(BaseModel): - id: int - kind: str - status: str - analysis_type: str = "deforestation" - bbox: Optional[str] = None - start_date: Optional[str] = None - end_date: Optional[str] = None - created_at: str - updated_at: str - - -class ResultRow(BaseModel): - id: int - run_id: int - payload: dict[str, Any] - mask_path: Optional[str] = None - created_at: str - - -# ===== Carbon analytics helpers ===== - - -def _extract_deforested_pixels(payload: dict[str, Any]) -> Optional[int]: - """Pull the deforested-pixel count from a deforestation result payload. - - Returns None when the payload does not carry an inference pixel count. - """ - inference = payload.get("inference") - if not isinstance(inference, dict): - return None - pixels = inference.get("non_forest_pixels") - if pixels is None: - return None - try: - return int(pixels) - except (TypeError, ValueError): - return None - - -def _compute_carbon_estimation( - payload: dict[str, Any], - forest_type: Optional[str] = None, - region: Optional[str] = None, -) -> Optional[dict[str, float]]: - """Deterministic carbon loss estimate for embedding in a predict response. - - Returns None if the carbon module is unavailable or the payload lacks a - pixel count, so the caller can degrade gracefully. - """ - pixels = _extract_deforested_pixels(payload) - if pixels is None: - return None - try: - from climatevision.analytics.carbon import estimate_carbon_loss - - estimate = estimate_carbon_loss( - deforested_pixels=pixels, - forest_type=forest_type or "tropical_moist", - region=region or "default", - ) - except Exception: - logger.exception("Carbon estimation failed") - return None - - return { - "carbon_tonnes": estimate["carbon_tonnes"], - "hectares_lost": estimate["hectares"], - "co2_equivalent": estimate["co2_equivalent"], - "forest_type": forest_type or "tropical_moist", - "region": region or "default", - } - - -def _validate_forest_type(forest_type: Optional[str]) -> None: - """Reject an unknown forest_type instead of silently defaulting. - - A typo such as ``tropical-moist`` (hyphen) would otherwise fall through - to a generic biomass density and return plausible-looking but wrong - numbers with a 200 OK. - """ - if forest_type is None: - return - from climatevision.analytics.carbon import AGB_DENSITY - - if forest_type not in AGB_DENSITY: - raise HTTPException( - status_code=422, - detail=( - f"Unknown forest_type '{forest_type}'. " - f"Valid values: {sorted(AGB_DENSITY)}" - ), - ) - - -def _validate_region(region: Optional[str]) -> None: - """Reject an unknown region instead of silently applying no adjustment. - - An unmatched region (e.g. ``Amazon`` capitalised, or ``amazon `` with a - trailing space) would otherwise fall back to a 1.0 factor and return a - confident-looking number that is wrong by the real regional adjustment. - Since these figures are meant to be cited, fail loudly instead. - """ - if region is None: - return - from climatevision.analytics.carbon import REGIONAL_FACTORS - - if region not in REGIONAL_FACTORS: - raise HTTPException( - status_code=422, - detail=( - f"Unknown region '{region}'. " - f"Valid values: {sorted(REGIONAL_FACTORS)}" - ), - ) - - -# Organization models -class CreateOrganizationRequest(BaseModel): - name: str = Field(..., min_length=2, max_length=200) - type: OrganizationType = Field(default="ngo") - description: Optional[str] = None - contact_email: Optional[EmailStr] = None - website_url: Optional[str] = None - regions_of_interest: Optional[list[str]] = None - - -class OrganizationResponse(BaseModel): - id: int - name: str - type: str - description: Optional[str] = None - logo_url: Optional[str] = None - website_url: Optional[str] = None - contact_email: Optional[str] = None - active: bool - created_at: str - - -class OrganizationWithKeyResponse(OrganizationResponse): - api_key: str - - -class CreateSubscriptionRequest(BaseModel): - name: Optional[str] = None - description: Optional[str] = None - bbox: list[float] = Field(..., min_length=4, max_length=4) - analysis_types: list[AnalysisType] = Field(default=["deforestation"]) - alert_threshold: float = Field(default=5.0, ge=0, le=100) - notification_channel: NotificationChannel = Field(default="email") - webhook_url: Optional[str] = None - - -class SubscriptionResponse(BaseModel): - id: int - organization_id: int - name: Optional[str] = None - bbox: list[float] - analysis_types: list[str] - alert_threshold: float - notification_channel: str - active: bool - created_at: str - - -class AlertResponse(BaseModel): - id: int - organization_id: int - alert_type: str - severity: str - title: str - message: str - delivered: bool - acknowledged: bool - created_at: str - - -class CreateAlertRequest(BaseModel): - alert_type: str - severity: AlertSeverity = Field(default="medium") - title: str - message: str - subscription_id: Optional[int] = None - run_id: Optional[int] = None - details: Optional[str] = None - - -# Explainability models -class ExplainRequest(BaseModel): - run_id: Optional[int] = None - analysis_type: AnalysisType = Field(default="deforestation") - target_class: Optional[int] = None - - -class BandContribution(BaseModel): - band: str - importance: float - - -class ExplainResponse(BaseModel): - run_id: Optional[int] = None - analysis_type: str - target_class: int - prediction: int - confidence: float - top_bands: list[BandContribution] - heatmap_path: Optional[str] = None - explainer_type: str - - -# ===== Helper Functions ===== - -def _load_template_result( - *, - bbox: Optional[list[float]], - start_date: Optional[str], - end_date: Optional[str], - analysis_type: str = "deforestation", -) -> dict[str, Any]: - """Load or create a template result for failed inference.""" - outputs_dir = Path(__file__).resolve().parents[3] / "outputs" - template_path = outputs_dir / "inference_results.json" - - if template_path.exists(): - template: dict[str, Any] = json.loads(template_path.read_text(encoding="utf-8")) - else: - # Create analysis-specific template - if analysis_type == "ice_melting": - template = { - "region": {"bbox": bbox or None}, - "inference": { - "image_size": [256, 256], - "ice_pixels": 0, - "water_pixels": 0, - "land_pixels": 0, - "ice_percentage": 0.0, - "mean_confidence": 0.0, - }, - } - elif analysis_type == "flooding": - template = { - "region": {"bbox": bbox or None}, - "inference": { - "image_size": [256, 256], - "flooded_pixels": 0, - "dry_pixels": 0, - "water_pixels": 0, - "flooded_percentage": 0.0, - "mean_confidence": 0.0, - }, - } - else: # deforestation (default) - template = { - "region": {"bbox": bbox or None}, - "ndvi_stats": {"NDVI_min": 0.0, "NDVI_mean": 0.0, "NDVI_max": 0.0}, - "inference": { - "image_size": [256, 256], - "forest_pixels": 0, - "non_forest_pixels": 0, - "forest_percentage": 0.0, - "mean_confidence": 0.0, - }, - } - - if bbox is not None: - template.setdefault("region", {})["bbox"] = bbox - if start_date and end_date: - template.setdefault("region", {})["date_range"] = f"{start_date} to {end_date}" - - template["analysis_type"] = analysis_type - - return template - - -async def _persist_upload(*, run_id: int, file: UploadFile) -> str: - """Save uploaded file to disk.""" - outputs_dir = Path(__file__).resolve().parents[3] / "outputs" - uploads_dir = outputs_dir / "uploads" - uploads_dir.mkdir(parents=True, exist_ok=True) - dest = uploads_dir / f"run_{run_id}_{file.filename}" - dest.write_bytes(await file.read()) - return str(dest) - - -async def get_current_organization( - x_api_key: Optional[str] = Header(None, alias="X-API-Key"), -) -> Optional[dict]: - """Dependency to get current organization from API key.""" - if not x_api_key: - return None - org = get_organization_by_api_key(x_api_key) - if org: - return dict(org) - return None - - # ===== Audit Logging Middleware ===== + class AuditLogMiddleware(BaseHTTPMiddleware): """Log every API request with method, path, status code, and duration.""" @@ -575,6 +62,7 @@ async def dispatch(self, request: Request, call_next: Any) -> Response: # ===== Application Factory ===== + def create_app() -> FastAPI: init_db() @@ -636,903 +124,28 @@ async def lifespan(_app: FastAPI): # wraps middleware in reverse add_middleware order, so the last call # is the outermost wrapper. from climatevision.api.middleware import RequestIDMiddleware + app.add_middleware(RequestIDMiddleware) # Wire OWASP-aligned security controls (rate limiting, payload limits, etc.) app.add_middleware(SecurityMiddleware) from climatevision.api import admin as _admin + app.include_router(_admin.router) # ===== Core Endpoints ===== - _frontend_dist = Path(__file__).resolve().parents[3] / "frontend" / "dist" + _frontend_dist = PROJECT_ROOT / "frontend" / "dist" if not (_frontend_dist / "index.html").exists(): + @app.get("/") def root() -> RedirectResponse: """Redirect to API docs when no frontend is built.""" return RedirectResponse(url="/docs", status_code=302) - @app.get("/api/health") - def health() -> dict[str, Any]: - """Health check endpoint with API information and config validation.""" - from climatevision.data.band_mapping import get_model_config - - enabled_types = [t for t in SUPPORTED_ANALYSIS_TYPES if t["enabled"]] - config_issues: list[dict[str, Any]] = [] - - for atype in enabled_types: - name = atype["name"] - try: - cfg = get_model_config(name) - expected_channels = len(atype["bands"]) - expected_classes = len(atype["classes"]) - if cfg.get("in_channels") != expected_channels: - config_issues.append( - { - "analysis_type": name, - "issue": "in_channels mismatch", - "expected": expected_channels, - "got": cfg.get("in_channels"), - } - ) - if cfg.get("num_classes") != expected_classes: - config_issues.append( - { - "analysis_type": name, - "issue": "num_classes mismatch", - "expected": expected_classes, - "got": cfg.get("num_classes"), - } - ) - except Exception as exc: - config_issues.append( - {"analysis_type": name, "issue": "config missing", "error": str(exc)} - ) - - health_status = "ok" if not config_issues else "degraded" - - return { - "status": health_status, - "version": "0.2.0", - "analysis_types": [t["name"] for t in enabled_types], - "config_valid": len(config_issues) == 0, - "config_issues": config_issues, - } - - @app.get("/api/health/models") - def health_models() -> dict[str, Any]: - """Report which analysis types have trained weights available on disk.""" - from climatevision.data.band_mapping import get_model_config - - models_status = [] - for atype in SUPPORTED_ANALYSIS_TYPES: - name = atype["name"] - cfg = get_model_config(name) - weights_path = cfg.get("weights") - has_weights = False - if weights_path: - has_weights = (Path(__file__).resolve().parents[3] / weights_path).exists() - models_status.append( - { - "analysis_type": name, - "enabled": atype["enabled"], - "has_trained_weights": has_weights, - "weights_path": weights_path, - "note": "production inference" if has_weights else "synthetic/demo fallback", - } - ) - - ready_count = sum(1 for m in models_status if m["has_trained_weights"]) - return { - "status": "ready" if ready_count else "demo_mode", - "models": models_status, - "ready_count": ready_count, - "total_count": len(models_status), - } - - @app.get("/api/analysis-types") - def list_analysis_types(enabled_only: bool = True) -> list[dict[str, Any]]: - """List available analysis types.""" - if enabled_only: - return [t for t in SUPPORTED_ANALYSIS_TYPES if t["enabled"]] - return SUPPORTED_ANALYSIS_TYPES - - @app.get("/api/analysis-types/{analysis_type}") - def get_analysis_type(analysis_type: str) -> dict[str, Any]: - """Get details for a specific analysis type.""" - for t in SUPPORTED_ANALYSIS_TYPES: - if t["name"] == analysis_type: - return t - raise HTTPException(status_code=404, detail=f"Analysis type '{analysis_type}' not found") - - # ===== Run Endpoints ===== - - @app.get("/api/runs") - def list_runs( - limit: int = Query(default=50, le=200), - offset: int = Query(default=0, ge=0), - status: Optional[str] = None, - analysis_type: Optional[str] = None, - ) -> dict[str, Any]: - """List analysis runs with optional filtering and pagination metadata.""" - where_clauses = ["1=1"] - params: list = [] - - if status: - where_clauses.append("status = ?") - params.append(status) - if analysis_type: - where_clauses.append("analysis_type = ?") - params.append(analysis_type) - - where = " AND ".join(where_clauses) - - with get_connection() as conn: - total: int = conn.execute( - f"SELECT COUNT(*) FROM runs WHERE {where}", params - ).fetchone()[0] - rows = conn.execute( - f"SELECT * FROM runs WHERE {where} ORDER BY id DESC LIMIT ? OFFSET ?", - params + [int(limit), int(offset)], - ).fetchall() - - return { - "total": total, - "limit": limit, - "offset": offset, - "runs": [RunRow(**dict(r)) for r in rows], - } - - @app.get("/api/runs/stats") - def get_run_stats() -> dict[str, Any]: - """Return aggregated run statistics for dashboard KPI cards.""" - with get_connection() as conn: - total = conn.execute("SELECT COUNT(*) FROM runs").fetchone()[0] - - by_status = { - row["status"]: row["count"] - for row in conn.execute( - "SELECT status, COUNT(*) as count FROM runs GROUP BY status" - ).fetchall() - } - - by_analysis_type = { - row["analysis_type"]: row["count"] - for row in conn.execute( - "SELECT analysis_type, COUNT(*) as count FROM runs GROUP BY analysis_type" - ).fetchall() - } - - recent_completed = conn.execute( - "SELECT COUNT(*) FROM runs WHERE status = 'completed' " - "AND created_at >= datetime('now', '-7 days')" - ).fetchone()[0] - - # Alerts are created and acknowledged in organization_alerts; the - # legacy alerts table has no acknowledged column. - alerts_total = conn.execute( - "SELECT COUNT(*) FROM organization_alerts" - ).fetchone()[0] - alerts_unacknowledged = conn.execute( - "SELECT COUNT(*) FROM organization_alerts WHERE acknowledged = 0" - ).fetchone()[0] - - return { - "total_runs": total, - "completed_last_7_days": recent_completed, - "by_status": by_status, - "by_analysis_type": by_analysis_type, - "alerts": { - "total": alerts_total, - "unacknowledged": alerts_unacknowledged, - }, - } - - @app.get("/api/runs/{run_id}") - def get_run(run_id: int) -> dict[str, Any]: - """Get details for a specific run including results.""" - with get_connection() as conn: - run = conn.execute("SELECT * FROM runs WHERE id = ?", (run_id,)).fetchone() - if run is None: - raise HTTPException(status_code=404, detail="Run not found") - result = conn.execute( - "SELECT * FROM results WHERE run_id = ? ORDER BY id DESC LIMIT 1", (run_id,) - ).fetchone() - - payload: Optional[dict[str, Any]] = None - mask_path: Optional[str] = None - if result is not None: - payload = json.loads(result["payload_json"]) - mask_path = result["mask_path"] - - return { - "run": dict(run), - "result": None - if result is None - else { - "id": result["id"], - "run_id": result["run_id"], - "payload": payload, - "mask_path": mask_path, - "created_at": result["created_at"], - }, - } - - @app.websocket("/ws/runs/{run_id}") - async def watch_run(websocket: WebSocket, run_id: int) -> None: - """Stream status updates for a single run. - - On connect the current status is read from the database and sent - immediately, so a client attaching to an already-finished run still - receives a terminal event. If the run is still in progress the socket - then streams transitions until it reaches ``completed``/``failed``, - and closes once a terminal status has been delivered. - """ - await websocket.accept() - - # Subscribe before the initial read, otherwise a transition happening - # between the read and the subscribe would be missed entirely. - async with run_event_hub.subscribe(run_id) as queue: - snapshot = _read_run_status(run_id) - if snapshot is None: - await websocket.send_json( - {"type": "error", "run_id": run_id, "error": "Run not found"} - ) - await websocket.close(code=WS_RUN_NOT_FOUND) - return - - status, result_payload = snapshot - await websocket.send_json( - _status_event_for(run_id, status, result_payload) - ) - if status in TERMINAL_RUN_STATUSES: - await websocket.close() - return - - try: - while True: - event = await queue.get() - await websocket.send_json(event) - if event.get("status") in TERMINAL_RUN_STATUSES: - break - except WebSocketDisconnect: - # Client went away mid-run; the subscription is released by - # the context manager, nothing else to clean up. - logger.debug("WebSocket client disconnected from run %s", run_id) - return - - await websocket.close() - - @app.get("/api/reports/{run_id}") - def get_report(run_id: int) -> dict[str, Any]: - """Structured carbon impact report for a completed deforestation run. - - Recomputes the estimate (with uncertainty bounds) from the stored - pixel count, so it works whether or not carbon was requested at - prediction time. - """ - with get_connection() as conn: - run = conn.execute("SELECT * FROM runs WHERE id = ?", (run_id,)).fetchone() - if run is None: - raise HTTPException(status_code=404, detail="Run not found") - result = conn.execute( - "SELECT * FROM results WHERE run_id = ? ORDER BY id DESC LIMIT 1", (run_id,) - ).fetchone() - - if result is None: - raise HTTPException(status_code=404, detail="No result available for run") - - payload = json.loads(result["payload_json"]) - if payload.get("analysis_type") != "deforestation": - raise HTTPException( - status_code=400, - detail="Impact reports are only available for deforestation runs", - ) - - pixels = _extract_deforested_pixels(payload) - if pixels is None: - raise HTTPException( - status_code=422, detail="Result payload has no pixel count to report on" - ) - - # Reuse the forest_type/region chosen at prediction time so the report - # and the /api/predict response describe the same run. Falling back to - # the estimator defaults keeps reports working for runs saved before - # carbon was requested. - carbon_meta = payload.get("carbon_estimation") or {} - forest_type = carbon_meta.get("forest_type", "tropical_moist") - region = carbon_meta.get("region", "default") - _validate_forest_type(forest_type) - _validate_region(region) - - try: - from climatevision.analytics.carbon import CarbonEstimator - - estimator = CarbonEstimator(forest_type=forest_type, region=region) - estimate = estimator.estimate_from_pixel_count(pixels) - except Exception as exc: - logger.exception("Impact report generation failed for run %s", run_id) - raise HTTPException( - status_code=503, detail="Carbon analytics unavailable" - ) from exc - - region_bbox = json.loads(run["bbox"]) if run["bbox"] else None - - return { - "run_id": run_id, - "hectares_lost": estimate.hectares, - "biomass_tonnes": estimate.biomass_tonnes, - "carbon_tonnes": estimate.carbon_tonnes, - "co2_equivalent": estimate.co2_equivalent, - "confidence_interval": { - "lower": estimate.ci_lower, - "upper": estimate.ci_upper, - "uncertainty_pct": estimate.uncertainty_pct, - "unit": "tCO2e", - }, - "region_bbox": region_bbox, - "forest_type": estimate.forest_type, - "region": estimate.region, - } - - # ===== Prediction Endpoints ===== - - @app.post("/api/predict") - async def predict_json( - body: PredictRequest, - org: dict[str, Any] = Depends(require_api_key), - ) -> dict[str, Any]: - """Run prediction using bounding box and date range.""" - if body.enable_carbon: - _validate_forest_type(body.forest_type) - _validate_region(body.region) - - created_at = _utc_now_iso() - bbox_json = json.dumps(body.bbox) if body.bbox else None - - with get_connection() as conn: - cur = conn.execute( - """ - INSERT INTO runs (kind, status, analysis_type, bbox, start_date, end_date, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?) - """, - ( - body.kind, - "running", - body.analysis_type, - bbox_json, - body.start_date, - body.end_date, - created_at, - created_at, - ), - ) - run_id = int(cur.lastrowid) - - # Run inference. SAR flood detection has its own Sentinel-1 + JRC pipeline; - # all other analysis types use the shared Sentinel-2 inference path. - try: - if body.analysis_type == "flooding_sar": - result_payload = run_flood_inference_from_gee( - bbox=body.bbox, - start_date=body.start_date, - end_date=body.end_date, - ) - else: - result_payload = run_inference_from_gee( - bbox=body.bbox, - start_date=body.start_date, - end_date=body.end_date, - analysis_type=body.analysis_type, - ) - result_payload["analysis_type"] = body.analysis_type - status = "completed" - except Exception as exc: - logger.exception("Inference failed for run %s", run_id) - result_payload = _load_template_result( - bbox=body.bbox, - start_date=body.start_date, - end_date=body.end_date, - analysis_type=body.analysis_type, - ) - result_payload["error"] = str(exc) - status = "failed" - - # Carbon estimation (feature-flagged). Degrades gracefully if the - # analytics module is unavailable or the payload lacks pixel counts. - if ( - body.enable_carbon - and status == "completed" - and body.analysis_type == "deforestation" - ): - carbon = _compute_carbon_estimation( - result_payload, - forest_type=body.forest_type, - region=body.region, - ) - if carbon is not None: - result_payload["carbon_estimation"] = carbon - - # Persist result - result_created_at = _utc_now_iso() - with get_connection() as conn: - conn.execute( - "UPDATE runs SET status = ?, updated_at = ? WHERE id = ?", - (status, result_created_at, run_id), - ) - conn.execute( - """ - INSERT INTO results (run_id, payload_json, mask_path, created_at) - VALUES (?, ?, ?, ?) - """, - (run_id, json.dumps(result_payload), None, result_created_at), - ) - - await run_event_hub.publish( - run_id, _status_event_for(run_id, status, result_payload) - ) - - return {"run_id": run_id, "result": result_payload} - - @app.post("/api/predict/upload") - async def predict_upload( - kind: str = Form(default="upload"), - org: dict[str, Any] = Depends(require_api_key), - analysis_type: str = Form(default="deforestation"), - bbox: str | None = Form(default=None), - start_date: str | None = Form(default=None), - end_date: str | None = Form(default=None), - file: UploadFile = File(...), - ) -> dict[str, Any]: - """Run prediction on uploaded satellite imagery file.""" - if start_date and end_date and start_date > end_date: - raise HTTPException(status_code=400, detail="start_date must be before end_date") - - created_at = _utc_now_iso() - - parsed_bbox: Optional[list[float]] = None - if bbox: - try: - parsed_bbox = json.loads(bbox) - except json.JSONDecodeError as e: - raise HTTPException(status_code=400, detail="Invalid bbox JSON") from e - - with get_connection() as conn: - cur = conn.execute( - """ - INSERT INTO runs (kind, status, analysis_type, bbox, start_date, end_date, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?) - """, - ( - kind, - "running", - analysis_type, - json.dumps(parsed_bbox) if parsed_bbox else None, - start_date, - end_date, - created_at, - created_at, - ), - ) - run_id = int(cur.lastrowid) - - dest = await _persist_upload(run_id=run_id, file=file) - - # Run inference - try: - result_payload = run_inference_from_file( - dest, - bbox=parsed_bbox, - start_date=start_date, - end_date=end_date, - analysis_type=analysis_type, - ) - result_payload["analysis_type"] = analysis_type - status = "completed" - except Exception as exc: - logger.exception("Inference failed for upload run %s", run_id) - result_payload = _load_template_result( - bbox=parsed_bbox, - start_date=start_date, - end_date=end_date, - analysis_type=analysis_type, - ) - result_payload.setdefault("input", {})["file"] = dest - result_payload["error"] = str(exc) - status = "failed" - - # Persist result - result_created_at = _utc_now_iso() - with get_connection() as conn: - conn.execute( - "UPDATE runs SET status = ?, updated_at = ? WHERE id = ?", - (status, result_created_at, run_id), - ) - conn.execute( - """ - INSERT INTO results (run_id, payload_json, mask_path, created_at) - VALUES (?, ?, ?, ?) - """, - (run_id, json.dumps(result_payload), None, result_created_at), - ) - - await run_event_hub.publish( - run_id, _status_event_for(run_id, status, result_payload) - ) - - return {"run_id": run_id, "result": result_payload} - - # ===== Explainability Endpoints ===== - - @app.post("/api/explain", response_model=ExplainResponse) - async def explain_run(body: ExplainRequest) -> dict[str, Any]: - """ - Generate SHAP-based explanation for a prediction. - - Returns band-level contributions showing which spectral bands - drove the model's classification decision. - """ - from climatevision.inference.pipeline import _load_model, _load_image_file - import numpy as np - import torch - - # If run_id provided, get the image from that run - image_path = None - if body.run_id: - with get_connection() as conn: - run = conn.execute( - "SELECT * FROM runs WHERE id = ?", (body.run_id,) - ).fetchone() - if run is None: - raise HTTPException(status_code=404, detail="Run not found") - - result = conn.execute( - "SELECT * FROM results WHERE run_id = ? ORDER BY id DESC LIMIT 1", - (body.run_id,), - ).fetchone() - - if result: - payload = json.loads(result["payload_json"]) - input_info = payload.get("input", {}) - image_path = input_info.get("file") - - # Load model and create explainer - model, device = _load_model(body.analysis_type) - - # If we have an image, use it; otherwise create synthetic - if image_path: - try: - image = _load_image_file(image_path) - except Exception: - image = np.random.randn(model.n_channels, 256, 256).astype(np.float32) - else: - image = np.random.randn(model.n_channels, 256, 256).astype(np.float32) - - # Ensure correct shape - if image.ndim == 3 and image.shape[2] < image.shape[0]: - image = np.transpose(image, (2, 0, 1)) - - n_channels = model.n_channels - c, h, w = image.shape - if c < n_channels: - pad = np.zeros((n_channels - c, h, w), dtype=image.dtype) - image = np.concatenate([image, pad], axis=0) - elif c > n_channels: - image = image[:n_channels] - - tensor = torch.FloatTensor(image.astype(np.float32)).unsqueeze(0) - - # Generate explanation - explainer = SHAPExplainer(model, device=device) - result = explainer.explain(tensor, target_class=body.target_class) - - # Format band contributions - band_names = { - "deforestation": ["Red", "Green", "Blue", "NIR"], - "ice_melting": ["Red", "Green", "Blue", "NIR"], - "flooding": ["Green", "NIR", "SWIR1"], - } - names = band_names.get(body.analysis_type, [f"Band_{i}" for i in range(n_channels)]) - - top_bands = [] - for i, (band_key, importance) in enumerate( - sorted(result["band_contributions"].items(), key=lambda x: x[1], reverse=True) - ): - band_idx = int(band_key.split("_")[1]) - band_name = names[band_idx] if band_idx < len(names) else band_key - top_bands.append(BandContribution(band=band_name, importance=round(importance, 4))) - - return { - "run_id": body.run_id, - "analysis_type": body.analysis_type, - "target_class": result["target_class"], - "prediction": result["prediction"], - "confidence": round(result["confidence"], 4), - "top_bands": top_bands, - "heatmap_path": None, - "explainer_type": result["explainer_type"], - } - - @app.get("/api/explain/{run_id}") - async def get_explanation( - run_id: int, - target_class: Optional[int] = None, - ) -> dict[str, Any]: - """Get SHAP explanation for a specific run.""" - with get_connection() as conn: - run = conn.execute( - "SELECT * FROM runs WHERE id = ?", (run_id,) - ).fetchone() - if run is None: - raise HTTPException(status_code=404, detail="Run not found") - - analysis_type = run["analysis_type"] or "deforestation" - - body = ExplainRequest( - run_id=run_id, - analysis_type=analysis_type, - target_class=target_class, - ) - return await explain_run(body) - - # ===== Organization (NGO) Endpoints ===== - - @app.post("/api/organizations", response_model=OrganizationWithKeyResponse) - def create_org( - body: CreateOrganizationRequest, - org: dict[str, Any] = Depends(require_api_key), - ) -> dict[str, Any]: - """Register a new organization. Returns API key (save it securely).""" - result = create_organization( - name=body.name, - org_type=body.type, - description=body.description, - contact_email=body.contact_email, - website_url=body.website_url, - regions_of_interest=body.regions_of_interest, - ) - - # Fetch full organization data - org = get_organization(result["id"]) - if not org: - raise HTTPException(status_code=500, detail="Failed to create organization") - - return { - **dict(org), - "active": bool(org["active"]), - "api_key": result["api_key"], - } - - @app.get("/api/organizations") - def list_orgs( - type: Optional[str] = None, - limit: int = Query(default=50, le=200), - ) -> list[OrganizationResponse]: - """List all registered organizations.""" - orgs = list_organizations(org_type=type, limit=limit) - return [ - OrganizationResponse( - id=org["id"], - name=org["name"], - type=org["type"], - description=org["description"], - logo_url=org["logo_url"], - website_url=org["website_url"], - contact_email=org["contact_email"], - active=bool(org["active"]), - created_at=org["created_at"], - ) - for org in orgs - ] - - @app.get("/api/organizations/{org_id}") - def get_org(org_id: int) -> OrganizationResponse: - """Get organization details by ID.""" - org = get_organization(org_id) - if not org: - raise HTTPException(status_code=404, detail="Organization not found") - - return OrganizationResponse( - id=org["id"], - name=org["name"], - type=org["type"], - description=org["description"], - logo_url=org["logo_url"], - website_url=org["website_url"], - contact_email=org["contact_email"], - active=bool(org["active"]), - created_at=org["created_at"], - ) - - # ===== Subscription Endpoints ===== - - @app.post("/api/organizations/{org_id}/subscriptions") - def create_org_subscription( - org_id: int, - body: CreateSubscriptionRequest, - org: dict[str, Any] = Depends(require_api_key), - ) -> SubscriptionResponse: - """Create a new region subscription for an organization.""" - org = get_organization(org_id) - if not org: - raise HTTPException(status_code=404, detail="Organization not found") - - result = create_subscription( - organization_id=org_id, - bbox=body.bbox, - name=body.name, - analysis_types=body.analysis_types, - alert_threshold=body.alert_threshold, - notification_channel=body.notification_channel, - webhook_url=body.webhook_url, - ) - - return SubscriptionResponse( - id=result["id"], - organization_id=org_id, - name=body.name, - bbox=body.bbox, - analysis_types=body.analysis_types, - alert_threshold=body.alert_threshold, - notification_channel=body.notification_channel, - active=True, - created_at=result["created_at"], - ) - - @app.get("/api/organizations/{org_id}/subscriptions") - def list_org_subscriptions(org_id: int) -> list[SubscriptionResponse]: - """List all subscriptions for an organization.""" - org = get_organization(org_id) - if not org: - raise HTTPException(status_code=404, detail="Organization not found") - - subs = get_subscriptions_for_organization(org_id) - results = [] - for sub in subs: - bbox = json.loads(sub["bbox"]) if sub["bbox"] else [] - analysis_types = json.loads(sub["analysis_types"]) if sub["analysis_types"] else [] - results.append( - SubscriptionResponse( - id=sub["id"], - organization_id=sub["organization_id"], - name=sub["name"], - bbox=bbox, - analysis_types=analysis_types, - alert_threshold=sub["alert_threshold"], - notification_channel=sub["notification_channel"], - active=bool(sub["active"]), - created_at=sub["created_at"], - ) - ) - return results - - # ===== Alert Endpoints ===== - - @app.get("/api/organizations/{org_id}/alerts") - def list_org_alerts( - org_id: int, - undelivered_only: bool = False, - unacknowledged_only: bool = False, - limit: int = Query(default=50, le=200), - ) -> list[AlertResponse]: - """List alerts for an organization.""" - org = get_organization(org_id) - if not org: - raise HTTPException(status_code=404, detail="Organization not found") - - alerts = get_alerts_for_organization( - org_id, - undelivered_only=undelivered_only, - unacknowledged_only=unacknowledged_only, - limit=limit, - ) - - return [ - AlertResponse( - id=alert["id"], - organization_id=alert["organization_id"], - alert_type=alert["alert_type"], - severity=alert["severity"], - title=alert["title"], - message=alert["message"], - delivered=bool(alert["delivered"]), - acknowledged=bool(alert["acknowledged"]), - created_at=alert["created_at"], - ) - for alert in alerts - ] - - @app.post("/api/organizations/{org_id}/alerts") - def create_org_alert( - org_id: int, - body: CreateAlertRequest, - org: dict[str, Any] = Depends(require_api_key), - ) -> AlertResponse: - """Create a new alert for an organization.""" - org = get_organization(org_id) - if not org: - raise HTTPException(status_code=404, detail="Organization not found") - - alert_id = create_organization_alert( - organization_id=org_id, - alert_type=body.alert_type, - title=body.title, - message=body.message, - severity=body.severity, - subscription_id=body.subscription_id, - run_id=body.run_id, - details=body.details, - ) - - return AlertResponse( - id=alert_id, - organization_id=org_id, - alert_type=body.alert_type, - severity=body.severity, - title=body.title, - message=body.message, - delivered=False, - acknowledged=False, - created_at=_utc_now_iso(), - ) - - @app.post("/api/alerts/{alert_id}/acknowledge") - def acknowledge_org_alert( - alert_id: int, - acknowledged_by: Optional[str] = None, - org: dict[str, Any] = Depends(require_api_key), - ) -> dict[str, Any]: - """Acknowledge an alert.""" - success = acknowledge_alert(alert_id, acknowledged_by) - if not success: - raise HTTPException(status_code=404, detail="Alert not found") - return {"success": True, "alert_id": alert_id} - - @app.post("/api/alerts/{alert_id}/deliver") - def mark_alert_as_delivered( - alert_id: int, - org: dict[str, Any] = Depends(require_api_key), - ) -> dict[str, Any]: - """Mark an alert as delivered.""" - success = mark_alert_delivered(alert_id) - if not success: - raise HTTPException(status_code=404, detail="Alert not found") - return {"success": True, "alert_id": alert_id} - - @app.get("/api/organizations/{org_id}/alerts/pending") - def list_pending_alerts( - org_id: int, - limit: int = Query(default=50, le=200), - ) -> list[AlertResponse]: - """List pending (undelivered) alerts for an organization. - - This endpoint is designed for monitoring and dashboard use, - showing alerts that the delivery worker has not yet processed. - """ - org = get_organization(org_id) - if not org: - raise HTTPException(status_code=404, detail="Organization not found") - - alerts = get_pending_alerts(max_attempts=3, limit=limit) - # Filter to this specific organization's alerts - org_alerts = [a for a in alerts if a["organization_id"] == org_id] - - return [ - AlertResponse( - id=alert["id"], - organization_id=alert["organization_id"], - alert_type=alert["alert_type"], - severity=alert["severity"], - title=alert["title"], - message=alert["message"], - delivered=bool(alert["delivered"]), - acknowledged=bool(alert["acknowledged"]), - created_at=alert["created_at"], - ) - for alert in org_alerts[:limit] - ] + include_routers(app) # ===== Static Files ===== @@ -1542,7 +155,9 @@ def list_pending_alerts( # work on direct navigation and refresh. dist_dir = _frontend_dist if (dist_dir / "index.html").exists(): - app.mount("/assets", StaticFiles(directory=str(dist_dir / "assets")), name="assets") + app.mount( + "/assets", StaticFiles(directory=str(dist_dir / "assets")), name="assets" + ) @app.get("/{full_path:path}", include_in_schema=False) def frontend(full_path: str) -> FileResponse: diff --git a/src/climatevision/api/routes/__init__.py b/src/climatevision/api/routes/__init__.py new file mode 100644 index 0000000..f23589f --- /dev/null +++ b/src/climatevision/api/routes/__init__.py @@ -0,0 +1,36 @@ +""" +Route modules of the ClimateVision API, one ``APIRouter`` per resource. +""" + +from __future__ import annotations + +from fastapi import FastAPI + +from climatevision.api.routes import ( + alerts, + analysis, + explain, + health, + organizations, + predict, + runs, + subscriptions, +) + +# Included in this order, which is the order the routes are matched in. +ROUTERS = ( + health.router, + analysis.router, + runs.router, + predict.router, + explain.router, + organizations.router, + subscriptions.router, + alerts.router, +) + + +def include_routers(app: FastAPI) -> None: + """Include every API router in ``app``.""" + for router in ROUTERS: + app.include_router(router) diff --git a/src/climatevision/api/routes/alerts.py b/src/climatevision/api/routes/alerts.py new file mode 100644 index 0000000..b476ab4 --- /dev/null +++ b/src/climatevision/api/routes/alerts.py @@ -0,0 +1,177 @@ +""" +Alert endpoints: listing, creation, acknowledgement and delivery of alerts. +""" + +from __future__ import annotations + +from typing import Any, Optional + +from fastapi import APIRouter, Depends, HTTPException, Query +from pydantic import BaseModel, Field + +from climatevision.api.auth import require_api_key +from climatevision.api.shared import AlertSeverity, _utc_now_iso +from climatevision.db import ( + acknowledge_alert, + create_organization_alert, + get_alerts_for_organization, + get_organization, + get_pending_alerts, + mark_alert_delivered, +) + +router = APIRouter() + + +class AlertResponse(BaseModel): + id: int + organization_id: int + alert_type: str + severity: str + title: str + message: str + delivered: bool + acknowledged: bool + created_at: str + + +class CreateAlertRequest(BaseModel): + alert_type: str + severity: AlertSeverity = Field(default="medium") + title: str + message: str + subscription_id: Optional[int] = None + run_id: Optional[int] = None + details: Optional[str] = None + + +# ===== Alert Endpoints ===== + + +@router.get("/api/organizations/{org_id}/alerts") +def list_org_alerts( + org_id: int, + undelivered_only: bool = False, + unacknowledged_only: bool = False, + limit: int = Query(default=50, le=200), +) -> list[AlertResponse]: + """List alerts for an organization.""" + org = get_organization(org_id) + if not org: + raise HTTPException(status_code=404, detail="Organization not found") + + alerts = get_alerts_for_organization( + org_id, + undelivered_only=undelivered_only, + unacknowledged_only=unacknowledged_only, + limit=limit, + ) + + return [ + AlertResponse( + id=alert["id"], + organization_id=alert["organization_id"], + alert_type=alert["alert_type"], + severity=alert["severity"], + title=alert["title"], + message=alert["message"], + delivered=bool(alert["delivered"]), + acknowledged=bool(alert["acknowledged"]), + created_at=alert["created_at"], + ) + for alert in alerts + ] + + +@router.post("/api/organizations/{org_id}/alerts") +def create_org_alert( + org_id: int, + body: CreateAlertRequest, + org: dict[str, Any] = Depends(require_api_key), +) -> AlertResponse: + """Create a new alert for an organization.""" + org = get_organization(org_id) + if not org: + raise HTTPException(status_code=404, detail="Organization not found") + + alert_id = create_organization_alert( + organization_id=org_id, + alert_type=body.alert_type, + title=body.title, + message=body.message, + severity=body.severity, + subscription_id=body.subscription_id, + run_id=body.run_id, + details=body.details, + ) + + return AlertResponse( + id=alert_id, + organization_id=org_id, + alert_type=body.alert_type, + severity=body.severity, + title=body.title, + message=body.message, + delivered=False, + acknowledged=False, + created_at=_utc_now_iso(), + ) + + +@router.post("/api/alerts/{alert_id}/acknowledge") +def acknowledge_org_alert( + alert_id: int, + acknowledged_by: Optional[str] = None, + org: dict[str, Any] = Depends(require_api_key), +) -> dict[str, Any]: + """Acknowledge an alert.""" + success = acknowledge_alert(alert_id, acknowledged_by) + if not success: + raise HTTPException(status_code=404, detail="Alert not found") + return {"success": True, "alert_id": alert_id} + + +@router.post("/api/alerts/{alert_id}/deliver") +def mark_alert_as_delivered( + alert_id: int, + org: dict[str, Any] = Depends(require_api_key), +) -> dict[str, Any]: + """Mark an alert as delivered.""" + success = mark_alert_delivered(alert_id) + if not success: + raise HTTPException(status_code=404, detail="Alert not found") + return {"success": True, "alert_id": alert_id} + + +@router.get("/api/organizations/{org_id}/alerts/pending") +def list_pending_alerts( + org_id: int, + limit: int = Query(default=50, le=200), +) -> list[AlertResponse]: + """List pending (undelivered) alerts for an organization. + + This endpoint is designed for monitoring and dashboard use, + showing alerts that the delivery worker has not yet processed. + """ + org = get_organization(org_id) + if not org: + raise HTTPException(status_code=404, detail="Organization not found") + + alerts = get_pending_alerts(max_attempts=3, limit=limit) + # Filter to this specific organization's alerts + org_alerts = [a for a in alerts if a["organization_id"] == org_id] + + return [ + AlertResponse( + id=alert["id"], + organization_id=alert["organization_id"], + alert_type=alert["alert_type"], + severity=alert["severity"], + title=alert["title"], + message=alert["message"], + delivered=bool(alert["delivered"]), + acknowledged=bool(alert["acknowledged"]), + created_at=alert["created_at"], + ) + for alert in org_alerts[:limit] + ] diff --git a/src/climatevision/api/routes/analysis.py b/src/climatevision/api/routes/analysis.py new file mode 100644 index 0000000..4524622 --- /dev/null +++ b/src/climatevision/api/routes/analysis.py @@ -0,0 +1,82 @@ +""" +Analysis type endpoints: the catalogue of supported climate analyses. +""" + +from __future__ import annotations + +from typing import Any + +from fastapi import APIRouter, HTTPException + +router = APIRouter() + + +SUPPORTED_ANALYSIS_TYPES: list[dict[str, Any]] = [ + { + "name": "deforestation", + "display_name": "Deforestation Detection", + "description": "Monitor forest coverage and detect deforestation events", + "enabled": True, + "bands": ["B04", "B03", "B02", "B08"], + "classes": ["non_forest", "forest"], + }, + { + "name": "ice_melting", + "display_name": "Arctic Ice Melting", + "description": "Monitor sea ice extent and melting patterns in polar regions", + "enabled": True, + "bands": ["B02", "B03", "B04", "B11"], + "classes": ["sea_ice", "open_water", "land"], + }, + { + "name": "flooding", + "display_name": "Flood Detection", + "description": "Detect and monitor flooding events and affected areas", + "enabled": True, + "bands": ["B03", "B08", "B11"], + "classes": ["water", "flooded", "dry_land"], + }, + { + "name": "flooding_sar", + "display_name": "Flood Detection (SAR)", + "description": "All-weather flood detection from Sentinel-1 VV/VH using a physics-based ensemble", + "enabled": True, + "bands": ["VV", "VH"], + "classes": ["dry_land", "permanent_water", "flooded"], + }, + { + "name": "drought", + "display_name": "Drought Monitoring", + "description": "Monitor vegetation stress and drought conditions", + "enabled": False, + "bands": ["B04", "B08", "B11", "B12"], + "classes": ["normal", "stressed", "severe_drought"], + }, + { + "name": "wildfire", + "display_name": "Wildfire Detection", + "description": "Detect active fires and burned areas", + "enabled": False, + "bands": ["B04", "B08", "B11", "B12"], + "classes": ["unburned", "burned", "active_fire"], + }, +] + + +@router.get("/api/analysis-types") +def list_analysis_types(enabled_only: bool = True) -> list[dict[str, Any]]: + """List available analysis types.""" + if enabled_only: + return [t for t in SUPPORTED_ANALYSIS_TYPES if t["enabled"]] + return SUPPORTED_ANALYSIS_TYPES + + +@router.get("/api/analysis-types/{analysis_type}") +def get_analysis_type(analysis_type: str) -> dict[str, Any]: + """Get details for a specific analysis type.""" + for t in SUPPORTED_ANALYSIS_TYPES: + if t["name"] == analysis_type: + return t + raise HTTPException( + status_code=404, detail=f"Analysis type '{analysis_type}' not found" + ) diff --git a/src/climatevision/api/routes/explain.py b/src/climatevision/api/routes/explain.py new file mode 100644 index 0000000..391020d --- /dev/null +++ b/src/climatevision/api/routes/explain.py @@ -0,0 +1,156 @@ +""" +Explainability endpoints: SHAP band contributions for a prediction. +""" + +from __future__ import annotations + +import json +from typing import Any, Optional + +from fastapi import APIRouter, HTTPException +from pydantic import BaseModel, Field + +from climatevision.api.shared import AnalysisType +from climatevision.db import get_connection +from climatevision.governance import SHAPExplainer + +router = APIRouter() + + +# Explainability models +class ExplainRequest(BaseModel): + run_id: Optional[int] = None + analysis_type: AnalysisType = Field(default="deforestation") + target_class: Optional[int] = None + + +class BandContribution(BaseModel): + band: str + importance: float + + +class ExplainResponse(BaseModel): + run_id: Optional[int] = None + analysis_type: str + target_class: int + prediction: int + confidence: float + top_bands: list[BandContribution] + heatmap_path: Optional[str] = None + explainer_type: str + + +# ===== Explainability Endpoints ===== + + +@router.post("/api/explain", response_model=ExplainResponse) +async def explain_run(body: ExplainRequest) -> dict[str, Any]: + """ + Generate SHAP-based explanation for a prediction. + + Returns band-level contributions showing which spectral bands + drove the model's classification decision. + """ + from climatevision.inference.pipeline import _load_model, _load_image_file + import numpy as np + import torch + + # If run_id provided, get the image from that run + image_path = None + if body.run_id: + with get_connection() as conn: + run = conn.execute( + "SELECT * FROM runs WHERE id = ?", (body.run_id,) + ).fetchone() + if run is None: + raise HTTPException(status_code=404, detail="Run not found") + + result = conn.execute( + "SELECT * FROM results WHERE run_id = ? ORDER BY id DESC LIMIT 1", + (body.run_id,), + ).fetchone() + + if result: + payload = json.loads(result["payload_json"]) + input_info = payload.get("input", {}) + image_path = input_info.get("file") + + # Load model and create explainer + model, device = _load_model(body.analysis_type) + + # If we have an image, use it; otherwise create synthetic + if image_path: + try: + image = _load_image_file(image_path) + except Exception: + image = np.random.randn(model.n_channels, 256, 256).astype(np.float32) + else: + image = np.random.randn(model.n_channels, 256, 256).astype(np.float32) + + # Ensure correct shape + if image.ndim == 3 and image.shape[2] < image.shape[0]: + image = np.transpose(image, (2, 0, 1)) + + n_channels = model.n_channels + c, h, w = image.shape + if c < n_channels: + pad = np.zeros((n_channels - c, h, w), dtype=image.dtype) + image = np.concatenate([image, pad], axis=0) + elif c > n_channels: + image = image[:n_channels] + + tensor = torch.FloatTensor(image.astype(np.float32)).unsqueeze(0) + + # Generate explanation + explainer = SHAPExplainer(model, device=device) + result = explainer.explain(tensor, target_class=body.target_class) + + # Format band contributions + band_names = { + "deforestation": ["Red", "Green", "Blue", "NIR"], + "ice_melting": ["Red", "Green", "Blue", "NIR"], + "flooding": ["Green", "NIR", "SWIR1"], + } + names = band_names.get(body.analysis_type, [f"Band_{i}" for i in range(n_channels)]) + + top_bands = [] + for i, (band_key, importance) in enumerate( + sorted(result["band_contributions"].items(), key=lambda x: x[1], reverse=True) + ): + band_idx = int(band_key.split("_")[1]) + band_name = names[band_idx] if band_idx < len(names) else band_key + top_bands.append( + BandContribution(band=band_name, importance=round(importance, 4)) + ) + + return { + "run_id": body.run_id, + "analysis_type": body.analysis_type, + "target_class": result["target_class"], + "prediction": result["prediction"], + "confidence": round(result["confidence"], 4), + "top_bands": top_bands, + "heatmap_path": None, + "explainer_type": result["explainer_type"], + } + + +@router.get("/api/explain/{run_id}") +async def get_explanation( + run_id: int, + target_class: Optional[int] = None, +) -> dict[str, Any]: + """Get SHAP explanation for a specific run.""" + with get_connection() as conn: + run = conn.execute("SELECT * FROM runs WHERE id = ?", (run_id,)).fetchone() + if run is None: + raise HTTPException(status_code=404, detail="Run not found") + + analysis_type = run["analysis_type"] or "deforestation" + + body = ExplainRequest( + run_id=run_id, + analysis_type=analysis_type, + target_class=target_class, + ) + return await explain_run(body) diff --git a/src/climatevision/api/routes/health.py b/src/climatevision/api/routes/health.py new file mode 100644 index 0000000..1443435 --- /dev/null +++ b/src/climatevision/api/routes/health.py @@ -0,0 +1,96 @@ +""" +Health endpoints: API status, config validation and model availability. +""" + +from __future__ import annotations + +from typing import Any + +from fastapi import APIRouter + +from climatevision.api.routes.analysis import SUPPORTED_ANALYSIS_TYPES +from climatevision.api.shared import PROJECT_ROOT + +router = APIRouter() + + +@router.get("/api/health") +def health() -> dict[str, Any]: + """Health check endpoint with API information and config validation.""" + from climatevision.data.band_mapping import get_model_config + + enabled_types = [t for t in SUPPORTED_ANALYSIS_TYPES if t["enabled"]] + config_issues: list[dict[str, Any]] = [] + + for atype in enabled_types: + name = atype["name"] + try: + cfg = get_model_config(name) + expected_channels = len(atype["bands"]) + expected_classes = len(atype["classes"]) + if cfg.get("in_channels") != expected_channels: + config_issues.append( + { + "analysis_type": name, + "issue": "in_channels mismatch", + "expected": expected_channels, + "got": cfg.get("in_channels"), + } + ) + if cfg.get("num_classes") != expected_classes: + config_issues.append( + { + "analysis_type": name, + "issue": "num_classes mismatch", + "expected": expected_classes, + "got": cfg.get("num_classes"), + } + ) + except Exception as exc: + config_issues.append( + {"analysis_type": name, "issue": "config missing", "error": str(exc)} + ) + + health_status = "ok" if not config_issues else "degraded" + + return { + "status": health_status, + "version": "0.2.0", + "analysis_types": [t["name"] for t in enabled_types], + "config_valid": len(config_issues) == 0, + "config_issues": config_issues, + } + + +@router.get("/api/health/models") +def health_models() -> dict[str, Any]: + """Report which analysis types have trained weights available on disk.""" + from climatevision.data.band_mapping import get_model_config + + models_status = [] + for atype in SUPPORTED_ANALYSIS_TYPES: + name = atype["name"] + cfg = get_model_config(name) + weights_path = cfg.get("weights") + has_weights = False + if weights_path: + has_weights = (PROJECT_ROOT / weights_path).exists() + models_status.append( + { + "analysis_type": name, + "enabled": atype["enabled"], + "has_trained_weights": has_weights, + "weights_path": weights_path, + "note": ( + "production inference" if has_weights else "synthetic/demo fallback" + ), + } + ) + + ready_count = sum(1 for m in models_status if m["has_trained_weights"]) + return { + "status": "ready" if ready_count else "demo_mode", + "models": models_status, + "ready_count": ready_count, + "total_count": len(models_status), + } diff --git a/src/climatevision/api/routes/organizations.py b/src/climatevision/api/routes/organizations.py new file mode 100644 index 0000000..922e393 --- /dev/null +++ b/src/climatevision/api/routes/organizations.py @@ -0,0 +1,115 @@ +""" +Organization (NGO) endpoints: registration and lookup. +""" + +from __future__ import annotations + +from typing import Any, Optional + +from fastapi import APIRouter, Depends, HTTPException, Query +from pydantic import BaseModel, EmailStr, Field + +from climatevision.api.auth import require_api_key +from climatevision.api.shared import OrganizationType +from climatevision.db import create_organization, get_organization, list_organizations + +router = APIRouter() + + +# Organization models +class CreateOrganizationRequest(BaseModel): + name: str = Field(..., min_length=2, max_length=200) + type: OrganizationType = Field(default="ngo") + description: Optional[str] = None + contact_email: Optional[EmailStr] = None + website_url: Optional[str] = None + regions_of_interest: Optional[list[str]] = None + + +class OrganizationResponse(BaseModel): + id: int + name: str + type: str + description: Optional[str] = None + logo_url: Optional[str] = None + website_url: Optional[str] = None + contact_email: Optional[str] = None + active: bool + created_at: str + + +class OrganizationWithKeyResponse(OrganizationResponse): + api_key: str + + +# ===== Organization (NGO) Endpoints ===== + + +@router.post("/api/organizations", response_model=OrganizationWithKeyResponse) +def create_org( + body: CreateOrganizationRequest, + org: dict[str, Any] = Depends(require_api_key), +) -> dict[str, Any]: + """Register a new organization. Returns API key (save it securely).""" + result = create_organization( + name=body.name, + org_type=body.type, + description=body.description, + contact_email=body.contact_email, + website_url=body.website_url, + regions_of_interest=body.regions_of_interest, + ) + + # Fetch full organization data + org = get_organization(result["id"]) + if not org: + raise HTTPException(status_code=500, detail="Failed to create organization") + + return { + **dict(org), + "active": bool(org["active"]), + "api_key": result["api_key"], + } + + +@router.get("/api/organizations") +def list_orgs( + type: Optional[str] = None, + limit: int = Query(default=50, le=200), +) -> list[OrganizationResponse]: + """List all registered organizations.""" + orgs = list_organizations(org_type=type, limit=limit) + return [ + OrganizationResponse( + id=org["id"], + name=org["name"], + type=org["type"], + description=org["description"], + logo_url=org["logo_url"], + website_url=org["website_url"], + contact_email=org["contact_email"], + active=bool(org["active"]), + created_at=org["created_at"], + ) + for org in orgs + ] + + +@router.get("/api/organizations/{org_id}") +def get_org(org_id: int) -> OrganizationResponse: + """Get organization details by ID.""" + org = get_organization(org_id) + if not org: + raise HTTPException(status_code=404, detail="Organization not found") + + return OrganizationResponse( + id=org["id"], + name=org["name"], + type=org["type"], + description=org["description"], + logo_url=org["logo_url"], + website_url=org["website_url"], + contact_email=org["contact_email"], + active=bool(org["active"]), + created_at=org["created_at"], + ) diff --git a/src/climatevision/api/routes/predict.py b/src/climatevision/api/routes/predict.py new file mode 100644 index 0000000..c155829 --- /dev/null +++ b/src/climatevision/api/routes/predict.py @@ -0,0 +1,357 @@ +""" +Prediction endpoints: run inference from a bounding box or an uploaded image. +""" + +from __future__ import annotations + +import json +import logging +from datetime import datetime +from typing import Any, Optional + +from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile +from pydantic import BaseModel, Field, field_validator, model_validator + +from climatevision.api.auth import require_api_key +from climatevision.api.run_events import run_event_hub +from climatevision.api.shared import ( + PROJECT_ROOT, + AnalysisType, + _compute_carbon_estimation, + _status_event_for, + _utc_now_iso, + _validate_forest_type, + _validate_region, +) +from climatevision.db import get_connection +from climatevision.inference import run_inference_from_file, run_inference_from_gee +from climatevision.inference.flood_pipeline import run_flood_inference_from_gee + +logger = logging.getLogger(__name__) + +router = APIRouter() + + +class PredictRequest(BaseModel): + kind: str = Field(default="demo") + analysis_type: AnalysisType = Field(default="deforestation") + bbox: Optional[list[float]] = None + start_date: Optional[str] = Field( + default=None, + description="Start date in YYYY-MM-DD format. Must be earlier than end_date.", + ) + end_date: Optional[str] = Field( + default=None, + description="End date in YYYY-MM-DD format. Must be later than start_date.", + ) + enable_carbon: bool = Field( + default=False, + description="If true, include carbon loss estimates for deforestation runs.", + ) + forest_type: Optional[str] = Field( + default=None, + description="Forest type for carbon estimation (e.g. tropical_moist, mangrove).", + ) + region: Optional[str] = Field( + default=None, + description="Region for carbon estimation adjustment (e.g. amazon, congo).", + ) + + @field_validator("bbox") + @classmethod + def validate_bbox(cls, v: Optional[list[float]]) -> Optional[list[float]]: + if v is None: + return v + if len(v) != 4: + raise ValueError( + "bbox must have exactly 4 values: [west, south, east, north]" + ) + west, south, east, north = v + if not (-180 <= west <= 180 and -180 <= east <= 180): + raise ValueError("bbox longitude values must be between -180 and 180") + if not (-90 <= south <= 90 and -90 <= north <= 90): + raise ValueError("bbox latitude values must be between -90 and 90") + if west >= east: + raise ValueError("bbox west longitude must be less than east longitude") + if south >= north: + raise ValueError("bbox south latitude must be less than north latitude") + return v + + @model_validator(mode="after") + def validate_date_range(self) -> "PredictRequest": + if self.start_date and self.end_date: + try: + start = datetime.strptime(self.start_date, "%Y-%m-%d") + end = datetime.strptime(self.end_date, "%Y-%m-%d") + except ValueError: + raise ValueError("start_date and end_date must be in YYYY-MM-DD format") + if start >= end: + raise ValueError("start_date must be earlier than end_date") + return self + + +# ===== Helper Functions ===== + + +def _load_template_result( + *, + bbox: Optional[list[float]], + start_date: Optional[str], + end_date: Optional[str], + analysis_type: str = "deforestation", +) -> dict[str, Any]: + """Load or create a template result for failed inference.""" + outputs_dir = PROJECT_ROOT / "outputs" + template_path = outputs_dir / "inference_results.json" + + if template_path.exists(): + template: dict[str, Any] = json.loads(template_path.read_text(encoding="utf-8")) + else: + # Create analysis-specific template + if analysis_type == "ice_melting": + template = { + "region": {"bbox": bbox or None}, + "inference": { + "image_size": [256, 256], + "ice_pixels": 0, + "water_pixels": 0, + "land_pixels": 0, + "ice_percentage": 0.0, + "mean_confidence": 0.0, + }, + } + elif analysis_type == "flooding": + template = { + "region": {"bbox": bbox or None}, + "inference": { + "image_size": [256, 256], + "flooded_pixels": 0, + "dry_pixels": 0, + "water_pixels": 0, + "flooded_percentage": 0.0, + "mean_confidence": 0.0, + }, + } + else: # deforestation (default) + template = { + "region": {"bbox": bbox or None}, + "ndvi_stats": {"NDVI_min": 0.0, "NDVI_mean": 0.0, "NDVI_max": 0.0}, + "inference": { + "image_size": [256, 256], + "forest_pixels": 0, + "non_forest_pixels": 0, + "forest_percentage": 0.0, + "mean_confidence": 0.0, + }, + } + + if bbox is not None: + template.setdefault("region", {})["bbox"] = bbox + if start_date and end_date: + template.setdefault("region", {})["date_range"] = f"{start_date} to {end_date}" + + template["analysis_type"] = analysis_type + + return template + + +async def _persist_upload(*, run_id: int, file: UploadFile) -> str: + """Save uploaded file to disk.""" + outputs_dir = PROJECT_ROOT / "outputs" + uploads_dir = outputs_dir / "uploads" + uploads_dir.mkdir(parents=True, exist_ok=True) + dest = uploads_dir / f"run_{run_id}_{file.filename}" + dest.write_bytes(await file.read()) + return str(dest) + + +# ===== Prediction Endpoints ===== + + +@router.post("/api/predict") +async def predict_json( + body: PredictRequest, + org: dict[str, Any] = Depends(require_api_key), +) -> dict[str, Any]: + """Run prediction using bounding box and date range.""" + if body.enable_carbon: + _validate_forest_type(body.forest_type) + _validate_region(body.region) + + created_at = _utc_now_iso() + bbox_json = json.dumps(body.bbox) if body.bbox else None + + with get_connection() as conn: + cur = conn.execute( + """ + INSERT INTO runs (kind, status, analysis_type, bbox, start_date, end_date, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + body.kind, + "running", + body.analysis_type, + bbox_json, + body.start_date, + body.end_date, + created_at, + created_at, + ), + ) + run_id = int(cur.lastrowid) + + # Run inference. SAR flood detection has its own Sentinel-1 + JRC pipeline; + # all other analysis types use the shared Sentinel-2 inference path. + try: + if body.analysis_type == "flooding_sar": + result_payload = run_flood_inference_from_gee( + bbox=body.bbox, + start_date=body.start_date, + end_date=body.end_date, + ) + else: + result_payload = run_inference_from_gee( + bbox=body.bbox, + start_date=body.start_date, + end_date=body.end_date, + analysis_type=body.analysis_type, + ) + result_payload["analysis_type"] = body.analysis_type + status = "completed" + except Exception as exc: + logger.exception("Inference failed for run %s", run_id) + result_payload = _load_template_result( + bbox=body.bbox, + start_date=body.start_date, + end_date=body.end_date, + analysis_type=body.analysis_type, + ) + result_payload["error"] = str(exc) + status = "failed" + + # Carbon estimation (feature-flagged). Degrades gracefully if the + # analytics module is unavailable or the payload lacks pixel counts. + if ( + body.enable_carbon + and status == "completed" + and body.analysis_type == "deforestation" + ): + carbon = _compute_carbon_estimation( + result_payload, + forest_type=body.forest_type, + region=body.region, + ) + if carbon is not None: + result_payload["carbon_estimation"] = carbon + + # Persist result + result_created_at = _utc_now_iso() + with get_connection() as conn: + conn.execute( + "UPDATE runs SET status = ?, updated_at = ? WHERE id = ?", + (status, result_created_at, run_id), + ) + conn.execute( + """ + INSERT INTO results (run_id, payload_json, mask_path, created_at) + VALUES (?, ?, ?, ?) + """, + (run_id, json.dumps(result_payload), None, result_created_at), + ) + + await run_event_hub.publish( + run_id, _status_event_for(run_id, status, result_payload) + ) + + return {"run_id": run_id, "result": result_payload} + + +@router.post("/api/predict/upload") +async def predict_upload( + kind: str = Form(default="upload"), + org: dict[str, Any] = Depends(require_api_key), + analysis_type: str = Form(default="deforestation"), + bbox: str | None = Form(default=None), + start_date: str | None = Form(default=None), + end_date: str | None = Form(default=None), + file: UploadFile = File(...), +) -> dict[str, Any]: + """Run prediction on uploaded satellite imagery file.""" + if start_date and end_date and start_date > end_date: + raise HTTPException( + status_code=400, detail="start_date must be before end_date" + ) + + created_at = _utc_now_iso() + + parsed_bbox: Optional[list[float]] = None + if bbox: + try: + parsed_bbox = json.loads(bbox) + except json.JSONDecodeError as e: + raise HTTPException(status_code=400, detail="Invalid bbox JSON") from e + + with get_connection() as conn: + cur = conn.execute( + """ + INSERT INTO runs (kind, status, analysis_type, bbox, start_date, end_date, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + kind, + "running", + analysis_type, + json.dumps(parsed_bbox) if parsed_bbox else None, + start_date, + end_date, + created_at, + created_at, + ), + ) + run_id = int(cur.lastrowid) + + dest = await _persist_upload(run_id=run_id, file=file) + + # Run inference + try: + result_payload = run_inference_from_file( + dest, + bbox=parsed_bbox, + start_date=start_date, + end_date=end_date, + analysis_type=analysis_type, + ) + result_payload["analysis_type"] = analysis_type + status = "completed" + except Exception as exc: + logger.exception("Inference failed for upload run %s", run_id) + result_payload = _load_template_result( + bbox=parsed_bbox, + start_date=start_date, + end_date=end_date, + analysis_type=analysis_type, + ) + result_payload.setdefault("input", {})["file"] = dest + result_payload["error"] = str(exc) + status = "failed" + + # Persist result + result_created_at = _utc_now_iso() + with get_connection() as conn: + conn.execute( + "UPDATE runs SET status = ?, updated_at = ? WHERE id = ?", + (status, result_created_at, run_id), + ) + conn.execute( + """ + INSERT INTO results (run_id, payload_json, mask_path, created_at) + VALUES (?, ?, ?, ?) + """, + (run_id, json.dumps(result_payload), None, result_created_at), + ) + + await run_event_hub.publish( + run_id, _status_event_for(run_id, status, result_payload) + ) + + return {"run_id": run_id, "result": result_payload} diff --git a/src/climatevision/api/routes/runs.py b/src/climatevision/api/routes/runs.py new file mode 100644 index 0000000..f143b12 --- /dev/null +++ b/src/climatevision/api/routes/runs.py @@ -0,0 +1,318 @@ +""" +Run endpoints: listing, statistics, details, live status and impact reports. +""" + +from __future__ import annotations + +import json +import logging +from typing import Any, Optional + +from fastapi import APIRouter, HTTPException, Query, WebSocket, WebSocketDisconnect +from pydantic import BaseModel + +from climatevision.api.run_events import run_event_hub +from climatevision.api.shared import ( + _extract_deforested_pixels, + _status_event_for, + _validate_forest_type, + _validate_region, +) +from climatevision.db import get_connection + +logger = logging.getLogger(__name__) + +router = APIRouter() + + +# ===== Run Status Streaming ===== + +# Statuses after which no further updates are expected, so the socket closes. +TERMINAL_RUN_STATUSES = frozenset({"completed", "failed"}) + +# Application-defined close code for "the requested run does not exist". +# The 4000-4999 range is reserved for application use by RFC 6455. +WS_RUN_NOT_FOUND = 4404 + + +def _read_run_status( + run_id: int, +) -> Optional[tuple[str, Optional[dict[str, Any]]]]: + """Read a run's current status and latest result payload. + + Args: + run_id: The run to read. + + Returns: + A ``(status, result_payload)`` pair, or ``None`` if no such run exists. + The payload is ``None`` when the run has not produced a result yet. + """ + with get_connection() as conn: + run = conn.execute("SELECT status FROM runs WHERE id = ?", (run_id,)).fetchone() + if run is None: + return None + result = conn.execute( + "SELECT payload_json FROM results WHERE run_id = ? ORDER BY id DESC LIMIT 1", + (run_id,), + ).fetchone() + + payload: Optional[dict[str, Any]] = None + if result is not None: + payload = json.loads(result["payload_json"]) + return run["status"], payload + + +class RunRow(BaseModel): + id: int + kind: str + status: str + analysis_type: str = "deforestation" + bbox: Optional[str] = None + start_date: Optional[str] = None + end_date: Optional[str] = None + created_at: str + updated_at: str + + +class ResultRow(BaseModel): + id: int + run_id: int + payload: dict[str, Any] + mask_path: Optional[str] = None + created_at: str + + +# ===== Run Endpoints ===== + + +@router.get("/api/runs") +def list_runs( + limit: int = Query(default=50, le=200), + offset: int = Query(default=0, ge=0), + status: Optional[str] = None, + analysis_type: Optional[str] = None, +) -> dict[str, Any]: + """List analysis runs with optional filtering and pagination metadata.""" + where_clauses = ["1=1"] + params: list = [] + + if status: + where_clauses.append("status = ?") + params.append(status) + if analysis_type: + where_clauses.append("analysis_type = ?") + params.append(analysis_type) + + where = " AND ".join(where_clauses) + + with get_connection() as conn: + total: int = conn.execute( + f"SELECT COUNT(*) FROM runs WHERE {where}", params + ).fetchone()[0] + rows = conn.execute( + f"SELECT * FROM runs WHERE {where} ORDER BY id DESC LIMIT ? OFFSET ?", + params + [int(limit), int(offset)], + ).fetchall() + + return { + "total": total, + "limit": limit, + "offset": offset, + "runs": [RunRow(**dict(r)) for r in rows], + } + + +@router.get("/api/runs/stats") +def get_run_stats() -> dict[str, Any]: + """Return aggregated run statistics for dashboard KPI cards.""" + with get_connection() as conn: + total = conn.execute("SELECT COUNT(*) FROM runs").fetchone()[0] + + by_status = { + row["status"]: row["count"] + for row in conn.execute( + "SELECT status, COUNT(*) as count FROM runs GROUP BY status" + ).fetchall() + } + + by_analysis_type = { + row["analysis_type"]: row["count"] + for row in conn.execute( + "SELECT analysis_type, COUNT(*) as count FROM runs GROUP BY analysis_type" + ).fetchall() + } + + recent_completed = conn.execute( + "SELECT COUNT(*) FROM runs WHERE status = 'completed' " + "AND created_at >= datetime('now', '-7 days')" + ).fetchone()[0] + + # Alerts are created and acknowledged in organization_alerts; the + # legacy alerts table has no acknowledged column. + alerts_total = conn.execute( + "SELECT COUNT(*) FROM organization_alerts" + ).fetchone()[0] + alerts_unacknowledged = conn.execute( + "SELECT COUNT(*) FROM organization_alerts WHERE acknowledged = 0" + ).fetchone()[0] + + return { + "total_runs": total, + "completed_last_7_days": recent_completed, + "by_status": by_status, + "by_analysis_type": by_analysis_type, + "alerts": { + "total": alerts_total, + "unacknowledged": alerts_unacknowledged, + }, + } + + +@router.get("/api/runs/{run_id}") +def get_run(run_id: int) -> dict[str, Any]: + """Get details for a specific run including results.""" + with get_connection() as conn: + run = conn.execute("SELECT * FROM runs WHERE id = ?", (run_id,)).fetchone() + if run is None: + raise HTTPException(status_code=404, detail="Run not found") + result = conn.execute( + "SELECT * FROM results WHERE run_id = ? ORDER BY id DESC LIMIT 1", (run_id,) + ).fetchone() + + payload: Optional[dict[str, Any]] = None + mask_path: Optional[str] = None + if result is not None: + payload = json.loads(result["payload_json"]) + mask_path = result["mask_path"] + + return { + "run": dict(run), + "result": ( + None + if result is None + else { + "id": result["id"], + "run_id": result["run_id"], + "payload": payload, + "mask_path": mask_path, + "created_at": result["created_at"], + } + ), + } + + +@router.websocket("/ws/runs/{run_id}") +async def watch_run(websocket: WebSocket, run_id: int) -> None: + """Stream status updates for a single run. + + On connect the current status is read from the database and sent + immediately, so a client attaching to an already-finished run still + receives a terminal event. If the run is still in progress the socket + then streams transitions until it reaches ``completed``/``failed``, + and closes once a terminal status has been delivered. + """ + await websocket.accept() + + # Subscribe before the initial read, otherwise a transition happening + # between the read and the subscribe would be missed entirely. + async with run_event_hub.subscribe(run_id) as queue: + snapshot = _read_run_status(run_id) + if snapshot is None: + await websocket.send_json( + {"type": "error", "run_id": run_id, "error": "Run not found"} + ) + await websocket.close(code=WS_RUN_NOT_FOUND) + return + + status, result_payload = snapshot + await websocket.send_json(_status_event_for(run_id, status, result_payload)) + if status in TERMINAL_RUN_STATUSES: + await websocket.close() + return + + try: + while True: + event = await queue.get() + await websocket.send_json(event) + if event.get("status") in TERMINAL_RUN_STATUSES: + break + except WebSocketDisconnect: + # Client went away mid-run; the subscription is released by + # the context manager, nothing else to clean up. + logger.debug("WebSocket client disconnected from run %s", run_id) + return + + await websocket.close() + + +@router.get("/api/reports/{run_id}") +def get_report(run_id: int) -> dict[str, Any]: + """Structured carbon impact report for a completed deforestation run. + + Recomputes the estimate (with uncertainty bounds) from the stored + pixel count, so it works whether or not carbon was requested at + prediction time. + """ + with get_connection() as conn: + run = conn.execute("SELECT * FROM runs WHERE id = ?", (run_id,)).fetchone() + if run is None: + raise HTTPException(status_code=404, detail="Run not found") + result = conn.execute( + "SELECT * FROM results WHERE run_id = ? ORDER BY id DESC LIMIT 1", (run_id,) + ).fetchone() + + if result is None: + raise HTTPException(status_code=404, detail="No result available for run") + + payload = json.loads(result["payload_json"]) + if payload.get("analysis_type") != "deforestation": + raise HTTPException( + status_code=400, + detail="Impact reports are only available for deforestation runs", + ) + + pixels = _extract_deforested_pixels(payload) + if pixels is None: + raise HTTPException( + status_code=422, detail="Result payload has no pixel count to report on" + ) + + # Reuse the forest_type/region chosen at prediction time so the report + # and the /api/predict response describe the same run. Falling back to + # the estimator defaults keeps reports working for runs saved before + # carbon was requested. + carbon_meta = payload.get("carbon_estimation") or {} + forest_type = carbon_meta.get("forest_type", "tropical_moist") + region = carbon_meta.get("region", "default") + _validate_forest_type(forest_type) + _validate_region(region) + + try: + from climatevision.analytics.carbon import CarbonEstimator + + estimator = CarbonEstimator(forest_type=forest_type, region=region) + estimate = estimator.estimate_from_pixel_count(pixels) + except Exception as exc: + logger.exception("Impact report generation failed for run %s", run_id) + raise HTTPException( + status_code=503, detail="Carbon analytics unavailable" + ) from exc + + region_bbox = json.loads(run["bbox"]) if run["bbox"] else None + + return { + "run_id": run_id, + "hectares_lost": estimate.hectares, + "biomass_tonnes": estimate.biomass_tonnes, + "carbon_tonnes": estimate.carbon_tonnes, + "co2_equivalent": estimate.co2_equivalent, + "confidence_interval": { + "lower": estimate.ci_lower, + "upper": estimate.ci_upper, + "uncertainty_pct": estimate.uncertainty_pct, + "unit": "tCO2e", + }, + "region_bbox": region_bbox, + "forest_type": estimate.forest_type, + "region": estimate.region, + } diff --git a/src/climatevision/api/routes/subscriptions.py b/src/climatevision/api/routes/subscriptions.py new file mode 100644 index 0000000..9ffa40e --- /dev/null +++ b/src/climatevision/api/routes/subscriptions.py @@ -0,0 +1,110 @@ +""" +Subscription endpoints: regions an organization monitors. +""" + +from __future__ import annotations + +import json +from typing import Any, Optional + +from fastapi import APIRouter, Depends, HTTPException +from pydantic import BaseModel, Field + +from climatevision.api.auth import require_api_key +from climatevision.api.shared import AnalysisType, NotificationChannel +from climatevision.db import ( + create_subscription, + get_organization, + get_subscriptions_for_organization, +) + +router = APIRouter() + + +class CreateSubscriptionRequest(BaseModel): + name: Optional[str] = None + description: Optional[str] = None + bbox: list[float] = Field(..., min_length=4, max_length=4) + analysis_types: list[AnalysisType] = Field(default=["deforestation"]) + alert_threshold: float = Field(default=5.0, ge=0, le=100) + notification_channel: NotificationChannel = Field(default="email") + webhook_url: Optional[str] = None + + +class SubscriptionResponse(BaseModel): + id: int + organization_id: int + name: Optional[str] = None + bbox: list[float] + analysis_types: list[str] + alert_threshold: float + notification_channel: str + active: bool + created_at: str + + +# ===== Subscription Endpoints ===== + + +@router.post("/api/organizations/{org_id}/subscriptions") +def create_org_subscription( + org_id: int, + body: CreateSubscriptionRequest, + org: dict[str, Any] = Depends(require_api_key), +) -> SubscriptionResponse: + """Create a new region subscription for an organization.""" + org = get_organization(org_id) + if not org: + raise HTTPException(status_code=404, detail="Organization not found") + + result = create_subscription( + organization_id=org_id, + bbox=body.bbox, + name=body.name, + analysis_types=body.analysis_types, + alert_threshold=body.alert_threshold, + notification_channel=body.notification_channel, + webhook_url=body.webhook_url, + ) + + return SubscriptionResponse( + id=result["id"], + organization_id=org_id, + name=body.name, + bbox=body.bbox, + analysis_types=body.analysis_types, + alert_threshold=body.alert_threshold, + notification_channel=body.notification_channel, + active=True, + created_at=result["created_at"], + ) + + +@router.get("/api/organizations/{org_id}/subscriptions") +def list_org_subscriptions(org_id: int) -> list[SubscriptionResponse]: + """List all subscriptions for an organization.""" + org = get_organization(org_id) + if not org: + raise HTTPException(status_code=404, detail="Organization not found") + + subs = get_subscriptions_for_organization(org_id) + results = [] + for sub in subs: + bbox = json.loads(sub["bbox"]) if sub["bbox"] else [] + analysis_types = ( + json.loads(sub["analysis_types"]) if sub["analysis_types"] else [] + ) + results.append( + SubscriptionResponse( + id=sub["id"], + organization_id=sub["organization_id"], + name=sub["name"], + bbox=bbox, + analysis_types=analysis_types, + alert_threshold=sub["alert_threshold"], + notification_channel=sub["notification_channel"], + active=bool(sub["active"]), + created_at=sub["created_at"], + ) + ) + return results diff --git a/src/climatevision/api/shared.py b/src/climatevision/api/shared.py new file mode 100644 index 0000000..d98de77 --- /dev/null +++ b/src/climatevision/api/shared.py @@ -0,0 +1,169 @@ +""" +Types and helpers shared by the ClimateVision API route modules. +""" + +from __future__ import annotations + +import logging +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Literal, Optional + +from fastapi import Header, HTTPException + +from climatevision.api.run_events import build_status_event +from climatevision.db import get_organization_by_api_key + +logger = logging.getLogger(__name__) + +# Repository root, which holds outputs/, models/ and frontend/. +PROJECT_ROOT = Path(__file__).resolve().parents[3] + + +# ===== Type Definitions ===== + +AnalysisType = Literal[ + "deforestation", "ice_melting", "flooding", "flooding_sar", "drought", "wildfire" +] +OrganizationType = Literal["ngo", "government", "research", "corporate"] +NotificationChannel = Literal["email", "webhook", "api", "sms"] +AlertSeverity = Literal["low", "medium", "high", "critical"] + + +def _utc_now_iso() -> str: + return datetime.now(timezone.utc).isoformat() + + +def _status_event_for( + run_id: int, status: str, result_payload: Optional[dict[str, Any]] +) -> dict[str, Any]: + """Build a status event, routing the payload to ``result`` or ``error``. + + A failed run stores its message under ``error`` inside the result payload, + so surface that as the event's ``error`` field rather than as a result. + + Args: + run_id: The run the event describes. + status: The run's current status. + result_payload: The stored result payload, if any. + + Returns: + The event dictionary to send over the WebSocket. + """ + if status == "failed": + error = None + if result_payload is not None: + error = result_payload.get("error") + return build_status_event(run_id, status, error=error or "Inference failed") + if status == "completed": + return build_status_event(run_id, status, result=result_payload) + return build_status_event(run_id, status) + + +# ===== Carbon analytics helpers ===== + + +def _extract_deforested_pixels(payload: dict[str, Any]) -> Optional[int]: + """Pull the deforested-pixel count from a deforestation result payload. + + Returns None when the payload does not carry an inference pixel count. + """ + inference = payload.get("inference") + if not isinstance(inference, dict): + return None + pixels = inference.get("non_forest_pixels") + if pixels is None: + return None + try: + return int(pixels) + except (TypeError, ValueError): + return None + + +def _compute_carbon_estimation( + payload: dict[str, Any], + forest_type: Optional[str] = None, + region: Optional[str] = None, +) -> Optional[dict[str, float]]: + """Deterministic carbon loss estimate for embedding in a predict response. + + Returns None if the carbon module is unavailable or the payload lacks a + pixel count, so the caller can degrade gracefully. + """ + pixels = _extract_deforested_pixels(payload) + if pixels is None: + return None + try: + from climatevision.analytics.carbon import estimate_carbon_loss + + estimate = estimate_carbon_loss( + deforested_pixels=pixels, + forest_type=forest_type or "tropical_moist", + region=region or "default", + ) + except Exception: + logger.exception("Carbon estimation failed") + return None + + return { + "carbon_tonnes": estimate["carbon_tonnes"], + "hectares_lost": estimate["hectares"], + "co2_equivalent": estimate["co2_equivalent"], + "forest_type": forest_type or "tropical_moist", + "region": region or "default", + } + + +def _validate_forest_type(forest_type: Optional[str]) -> None: + """Reject an unknown forest_type instead of silently defaulting. + + A typo such as ``tropical-moist`` (hyphen) would otherwise fall through + to a generic biomass density and return plausible-looking but wrong + numbers with a 200 OK. + """ + if forest_type is None: + return + from climatevision.analytics.carbon import AGB_DENSITY + + if forest_type not in AGB_DENSITY: + raise HTTPException( + status_code=422, + detail=( + f"Unknown forest_type '{forest_type}'. " + f"Valid values: {sorted(AGB_DENSITY)}" + ), + ) + + +def _validate_region(region: Optional[str]) -> None: + """Reject an unknown region instead of silently applying no adjustment. + + An unmatched region (e.g. ``Amazon`` capitalised, or ``amazon `` with a + trailing space) would otherwise fall back to a 1.0 factor and return a + confident-looking number that is wrong by the real regional adjustment. + Since these figures are meant to be cited, fail loudly instead. + """ + if region is None: + return + from climatevision.analytics.carbon import REGIONAL_FACTORS + + if region not in REGIONAL_FACTORS: + raise HTTPException( + status_code=422, + detail=( + f"Unknown region '{region}'. " + f"Valid values: {sorted(REGIONAL_FACTORS)}" + ), + ) + + +async def get_current_organization( + x_api_key: Optional[str] = Header(None, alias="X-API-Key"), +) -> Optional[dict]: + """Dependency to get current organization from API key.""" + if not x_api_key: + return None + org = get_organization_by_api_key(x_api_key) + if org: + return dict(org) + return None diff --git a/tests/test_api.py b/tests/test_api.py index 4d27d7e..5b77c16 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -68,7 +68,7 @@ def test_predict_valid_date_range_reaches_inference( "analysis_type": "deforestation", } with patch( - "climatevision.api.main.run_inference_from_gee", return_value=fake_result + "climatevision.api.routes.predict.run_inference_from_gee", return_value=fake_result ) as mock_infer: response = client.post( "/api/predict", diff --git a/tests/test_api_routers.py b/tests/test_api_routers.py new file mode 100644 index 0000000..8ed8348 --- /dev/null +++ b/tests/test_api_routers.py @@ -0,0 +1,67 @@ +"""Tests for how the API routers are assembled into the application.""" + +from __future__ import annotations + +from pathlib import Path + +import pytest +from fastapi.routing import APIRoute +from fastapi.testclient import TestClient + +import climatevision.api.main as api_main +from climatevision.api.main import create_app +from climatevision.api.routes import ROUTERS +from climatevision.api.shared import PROJECT_ROOT + + +def _http_routes(router) -> set[tuple[str, str]]: + return { + (route.path, method.lower()) + for route in router.routes + if isinstance(route, APIRoute) + for method in route.methods + } + + +def test_every_router_route_is_served_by_the_app() -> None: + """A router left out of include_routers would silently drop its endpoints.""" + paths = create_app().openapi()["paths"] + served = {(path, method) for path, item in paths.items() for method in item} + + for router in ROUTERS: + assert router.routes, "a router without routes is probably wired wrongly" + assert _http_routes(router) <= served + + +def test_no_route_is_defined_by_two_routers() -> None: + """The same path and method in two routers would make one of them unreachable.""" + seen: set[tuple[str, str]] = set() + for router in ROUTERS: + for route in _http_routes(router): + assert route not in seen, f"{route} is defined twice" + seen.add(route) + + +def test_api_routes_are_matched_before_the_frontend_fallback( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """With a built frontend, API paths must still reach the API, not index.html.""" + dist = tmp_path / "frontend" / "dist" + (dist / "assets").mkdir(parents=True) + (dist / "index.html").write_text("frontend", encoding="utf-8") + monkeypatch.setattr(api_main, "PROJECT_ROOT", tmp_path) + + client = TestClient(create_app()) + + analysis_types = client.get("/api/analysis-types") + assert analysis_types.status_code == 200 + assert isinstance(analysis_types.json(), list) + + deep_link = client.get("/runs") + assert deep_link.status_code == 200 + assert deep_link.text == "frontend" + + +def test_project_root_is_the_repository_root() -> None: + """Paths to outputs/, models/ and frontend/ are resolved from PROJECT_ROOT.""" + assert (PROJECT_ROOT / "src" / "climatevision" / "api" / "shared.py").is_file() diff --git a/tests/test_carbon_api.py b/tests/test_carbon_api.py index d20aa1d..d1265c2 100644 --- a/tests/test_carbon_api.py +++ b/tests/test_carbon_api.py @@ -60,7 +60,7 @@ def test_predict_without_flag_omits_carbon( """Carbon block is absent unless enable_carbon is set.""" monkeypatch.setenv("CLIMATEVISION_ALLOW_DEV_KEY", "1") with patch( - "climatevision.api.main.run_inference_from_gee", + "climatevision.api.routes.predict.run_inference_from_gee", return_value=_deforestation_payload(), ): response = client.post( @@ -81,7 +81,7 @@ def test_predict_with_flag_includes_carbon( """enable_carbon adds a carbon_estimation block with correct figures.""" monkeypatch.setenv("CLIMATEVISION_ALLOW_DEV_KEY", "1") with patch( - "climatevision.api.main.run_inference_from_gee", + "climatevision.api.routes.predict.run_inference_from_gee", return_value=_deforestation_payload(), ): response = client.post( @@ -106,7 +106,7 @@ def test_report_endpoint_returns_impact_report( """GET /api/reports/{run_id} returns a complete impact report.""" monkeypatch.setenv("CLIMATEVISION_ALLOW_DEV_KEY", "1") with patch( - "climatevision.api.main.run_inference_from_gee", + "climatevision.api.routes.predict.run_inference_from_gee", return_value=_deforestation_payload(), ): predict = client.post( @@ -153,7 +153,7 @@ def test_report_respects_predict_forest_type( """ monkeypatch.setenv("CLIMATEVISION_ALLOW_DEV_KEY", "1") with patch( - "climatevision.api.main.run_inference_from_gee", + "climatevision.api.routes.predict.run_inference_from_gee", return_value=_deforestation_payload(), ): predict = client.post( @@ -187,7 +187,7 @@ def test_report_confidence_interval_is_labelled_co2e( """The confidence interval must declare its unit (tCO2e), not sit unlabelled.""" monkeypatch.setenv("CLIMATEVISION_ALLOW_DEV_KEY", "1") with patch( - "climatevision.api.main.run_inference_from_gee", + "climatevision.api.routes.predict.run_inference_from_gee", return_value=_deforestation_payload(), ): predict = client.post( @@ -210,7 +210,7 @@ def test_predict_rejects_unknown_forest_type( """A typo'd forest_type must 422, not silently fall back to a default.""" monkeypatch.setenv("CLIMATEVISION_ALLOW_DEV_KEY", "1") with patch( - "climatevision.api.main.run_inference_from_gee", + "climatevision.api.routes.predict.run_inference_from_gee", return_value=_deforestation_payload(), ): response = client.post( @@ -232,7 +232,7 @@ def test_predict_rejects_unknown_region( """An unmatched region must 422 rather than silently applying a 1.0 factor.""" monkeypatch.setenv("CLIMATEVISION_ALLOW_DEV_KEY", "1") with patch( - "climatevision.api.main.run_inference_from_gee", + "climatevision.api.routes.predict.run_inference_from_gee", return_value=_deforestation_payload(), ): response = client.post( diff --git a/tests/test_ws_run_status.py b/tests/test_ws_run_status.py index 7bb48f2..66cc03d 100644 --- a/tests/test_ws_run_status.py +++ b/tests/test_ws_run_status.py @@ -7,7 +7,7 @@ import pytest from fastapi.testclient import TestClient -from climatevision.api.main import WS_RUN_NOT_FOUND +from climatevision.api.routes.runs import WS_RUN_NOT_FOUND from climatevision.api.run_events import ( RunEventHub, build_status_event, @@ -199,7 +199,7 @@ async def record(run_id: int, event: dict) -> None: fake_result = {"inference": {"forest_percentage": 72.3}} with patch( - "climatevision.api.main.run_inference_from_gee", return_value=fake_result + "climatevision.api.routes.predict.run_inference_from_gee", return_value=fake_result ): response = client.post( "/api/predict", @@ -234,7 +234,7 @@ async def record(run_id: int, event: dict) -> None: monkeypatch.setattr(run_event_hub, "publish", record) with patch( - "climatevision.api.main.run_inference_from_gee", + "climatevision.api.routes.predict.run_inference_from_gee", side_effect=RuntimeError("GEE unavailable"), ): response = client.post(