feat: Initial CBPOA commit — 武汉儿童呼吸疾病风险评估系统

Context: Build a spatial risk assessment system correlating air quality
data with children's respiratory disease incidence across Wuhan.

Approach: FastAPI backend serving PostGIS spatial queries, React
frontend with Deck.gl maps, and a PyTorch SpatialTemporalGCN pipeline
for multi-day (1d/3d/7d) risk prediction.

Changes:
- backend/ — FastAPI API with auth (JWT), alerts, risk analysis,
  geocoded case data, grid statistics, and report endpoints
- frontend/ — React dashboard with interactive risk maps, alert
  monitoring, district comparison charts, and timeline player
- models/ — SpatialTemporalGCN model with trained weights and ONNX
  export for inference
- scripts/ — ETL pipeline for weather + medical data, grid generation,
  feature engineering, training, and daily inference
- deploy/ — Docker Compose configs for backend, frontend, and MLflow
- docs/ — API docs, deployment guide, user guide, and code review

Impact: Enables spatial risk visualization, alert monitoring, and
ML-driven health risk forecasting for environmental health teams.
This commit is contained in:
2026-06-05 02:13:49 +08:00
commit fc468464b2
117 changed files with 18282 additions and 0 deletions

0
backend/auth/__init__.py Normal file
View File

View File

@@ -0,0 +1,27 @@
"""FastAPI dependencies for authentication."""
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from .service import decode_access_token
security = HTTPBearer()
async def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(security),
) -> str:
"""Extract and validate the current user from the Authorization header."""
payload = decode_access_token(credentials.credentials)
if payload is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired token",
headers={"WWW-Authenticate": "Bearer"},
)
username: str | None = payload.get("sub")
if not username:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token missing subject",
)
return username

View File

@@ -0,0 +1,3 @@
"""Auth middleware — currently a no-op placeholder for future rate-limiting / audit logging."""
# Middleware for auth events can be added here (e.g., failed-login rate limiter).
# Kept as a placeholder so the module structure is complete.

21
backend/auth/models.py Normal file
View File

@@ -0,0 +1,21 @@
"""Pydantic models for authentication."""
from pydantic import BaseModel, Field
class UserCreate(BaseModel):
username: str = Field(..., min_length=3, max_length=50)
password: str = Field(..., min_length=6, max_length=128)
class UserLogin(BaseModel):
username: str
password: str
class Token(BaseModel):
access_token: str
token_type: str = "bearer"
class UserOut(BaseModel):
username: str

34
backend/auth/router.py Normal file
View File

@@ -0,0 +1,34 @@
"""Authentication endpoints: login, register, whoami."""
from fastapi import APIRouter, Depends, HTTPException, status
from .models import UserCreate, UserLogin, Token, UserOut
from .service import authenticate_user, create_access_token, create_user
from .dependencies import get_current_user
router = APIRouter(prefix="/api/auth", tags=["auth"])
@router.post("/login", response_model=Token)
async def login(body: UserLogin):
if not authenticate_user(body.username, body.password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
)
token = create_access_token({"sub": body.username})
return Token(access_token=token)
@router.post("/register", response_model=UserOut, status_code=status.HTTP_201_CREATED)
async def register(body: UserCreate):
if not create_user(body.username, body.password):
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Username already exists",
)
return UserOut(username=body.username)
@router.get("/me", response_model=UserOut)
async def me(username: str = Depends(get_current_user)):
return UserOut(username=username)

66
backend/auth/service.py Normal file
View File

@@ -0,0 +1,66 @@
"""JWT token creation and password hashing utilities."""
import os
import logging
from datetime import datetime, timedelta, timezone
from jose import JWTError, jwt
from passlib.context import CryptContext
logger = logging.getLogger("cbpoa.auth")
SECRET_KEY = os.getenv("AUTH_SECRET_KEY", "cbpoa-dev-secret-change-in-production")
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("AUTH_TOKEN_EXPIRE_MINUTES", "480"))
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# In-memory user store (replace with DB table when auth matures)
_users: dict[str, str] = {}
def seed_default_admin() -> None:
"""Create default admin user if no users exist."""
if not _users:
default_user = os.getenv("AUTH_DEFAULT_USER", "admin")
default_pass = os.getenv("AUTH_DEFAULT_PASSWORD", "admin123")
_users[default_user] = pwd_context.hash(default_pass)
logger.info("Seeded default user '%s'", default_user)
def verify_password(plain: str, hashed: str) -> bool:
return pwd_context.verify(plain, hashed)
def hash_password(password: str) -> str:
return pwd_context.hash(password)
def authenticate_user(username: str, password: str) -> bool:
hashed = _users.get(username)
if not hashed:
return False
return verify_password(password, hashed)
def create_user(username: str, password: str) -> bool:
"""Register a new user. Returns False if username already exists."""
if username in _users:
return False
_users[username] = hash_password(password)
logger.info("Registered new user '%s'", username)
return True
def create_access_token(data: dict) -> str:
to_encode = data.copy()
expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
def decode_access_token(token: str) -> dict | None:
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
return payload
except JWTError:
return None