Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /pfun-health_pfun-cma-model /pfun_cma_model /api.py
| """PFun CMA Model API.""" | |
| # import necessary modules and packages | |
| from pfun_cma_model.admin.models import init_models | |
| from pfun_cma_model.misc.middleware import track_client_request_middleware | |
| from pfun_cma_model.security import ( | |
| setup_security_config, | |
| ) | |
| from guard import SecurityMiddleware | |
| from contextlib import asynccontextmanager | |
| from datetime import datetime | |
| import functools | |
| import importlib | |
| import json | |
| import logging | |
| from pathlib import Path | |
| from typing import Annotated, Mapping, Optional | |
| from fastapi import Body, Depends, FastAPI, Request, Response, Header | |
| from fastapi.responses import RedirectResponse, StreamingResponse | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.middleware.trustedhost import TrustedHostMiddleware | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.templating import Jinja2Templates | |
| from redis.asyncio import Redis | |
| from starlette.middleware.base import BaseHTTPMiddleware | |
| from starlette.middleware.sessions import SessionMiddleware | |
| from pfun_cma_model import __version__ as pfun_cma_model_pkg_version | |
| from pfun_cma_model.engine.cma import CMASleepWakeModel | |
| from pfun_cma_model.engine.cma_model_params import ( | |
| CMAModelParams, | |
| ) | |
| from pfun_common.settings import get_settings | |
| from pfun_cma_model.misc.templating import get_templates | |
| from pfun_cma_model.routes import ( | |
| auth as auth_routes, | |
| dexcom as dexcom_routes, | |
| data as data_routes, | |
| llm as llm_routes, | |
| demo as demo_routes, | |
| params as params_routes, | |
| sso as sso_routes, | |
| ) | |
| # Global variables and constants | |
| debug_mode: bool = get_settings().debug | |
| # --- Setup FastAPI app lifespan-scope events --- | |
| #: globally accessible logger (with appropriate logging level) | |
| from pfun_common.logs import setup_logging | |
| logger = setup_logging(debug=debug_mode) | |
| redis_client: Redis | None = None | |
| #: Global Redis client instance | |
| templates: Jinja2Templates | None = None # type: ignore | |
| #: Global Jinja2 templates instance | |
| async def lifespan(app: FastAPI): | |
| """Lifespan context manager for FastAPI app.""" | |
| # --- Startup task: configure debug mode based on environment variable --- | |
| logger.info("DEBUG flag: %s", str(debug_mode)) | |
| if debug_mode: | |
| app.debug = True | |
| logging.info("Running app in DEBUG mode.") | |
| logging.debug("Debug mode is enabled.") | |
| else: | |
| app.debug = False | |
| logging.info("Running app in PRODUCTION mode.") | |
| logging.debug("Debug mode is disabled.") | |
| # --- Startup task: initialize templates --- | |
| global templates | |
| templates = get_templates() | |
| # --- Startup task: connect to Redis --- | |
| global redis_client | |
| try: | |
| redis_client = Redis( | |
| host=get_settings().redis_host, | |
| port=int(get_settings().redis_port), | |
| db=int(get_settings().redis_db), | |
| password=get_settings().redis_password, | |
| decode_responses=True, | |
| ) | |
| try: | |
| await redis_client.ping() # type: ignore | |
| except Exception: | |
| logging.debug("failed to ping the redis client.", exc_info=True) | |
| except Exception as exc: | |
| logging.warning("Failed to setup redis client: %s", str(exc)) | |
| redis_client = None | |
| # --- Startup task: download sample data if not present --- | |
| from pfun_cma_model.misc.pathdefs import PFunDataPaths | |
| pfun_data_paths = PFunDataPaths() | |
| pfun_data_paths.download_sample_data() | |
| # --- Startup task: initialize Admin database models --- | |
| await init_models() | |
| # --- | |
| # --- Shutdown tasks will be handled after this point --- | |
| # --- | |
| yield | |
| # --- | |
| # NOTE: Yes, these steps are technically unnecessary. | |
| # ...It's an extra guarantee when you're using hot reload. | |
| # --- Delete the templates instance --- | |
| templates = None # type: ignore | |
| # TODO: sample data needs to be loaded via db connection. | |
| # --- Delete the sample data --- | |
| pfun_data_paths.remove_sample_data() | |
| # --- Shutdown task: disconnect from Redis --- | |
| if redis_client is not None: | |
| await redis_client.aclose() | |
| logging.info("Redis client connection closed.") | |
| # --- Instantiate FastAPI app --- | |
| def generate_server_info() -> list[dict[str, str]]: | |
| """Generate server info for relevant environment(s).""" | |
| server_info = [ | |
| { | |
| "url": f"{get_settings().production_server_url}", | |
| "description": "production server.", | |
| }, | |
| { | |
| "url": f"{get_settings().server_scheme}://{get_settings().server_host}:{get_settings().server_port}", | |
| "description": "(sans-SSL) development server.", | |
| }, | |
| { | |
| "url": f"https://{get_settings().ssl_server_host}", | |
| "description": "(SSL-ready) development server.", | |
| }, | |
| ] | |
| return server_info | |
| app = FastAPI( | |
| app_name="PFun CMA Model Backend", | |
| lifespan=lifespan, | |
| servers=generate_server_info(), | |
| ) | |
| # --- Application Configuration --- | |
| # Set the application title and description | |
| app.title = "PFun CMA Model Routing API" | |
| app.description = ( | |
| "Server-side operations for operating the PFun CMA model; " | |
| + "schema definitions, data IO, model execution." | |
| ) | |
| # Set the application version based on the package version and file modification time | |
| def set_app_version(app: FastAPI = app) -> FastAPI: | |
| """Set the application version based on the package version and `app.py` file modification time.""" | |
| fmod_time = datetime.fromtimestamp(Path(__file__).stat().st_mtime).strftime( | |
| "%Y%m%d%H%M%S" | |
| ) | |
| app.version = str(pfun_cma_model_pkg_version) + f"-dev.{fmod_time}" | |
| logging.debug("pfun-cma-model version: %s", pfun_cma_model_pkg_version) | |
| logging.debug("FastAPI app version set to: %s", app.version) | |
| return app | |
| app = set_app_version(app=app) # set app version info | |
| # Mount the static directory to serve static files | |
| STATIC_DIR = Path(__file__).parent / "static" | |
| app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static") | |
| ### | |
| # --- Setup middleware --- | |
| ### | |
| ## | |
| # setup the security layer | |
| ## | |
| # Add middleware with rate limiting | |
| # extra line below for type hinting and clarity, since the config is defined in a separate module | |
| app.add_middleware(SecurityMiddleware, config=setup_security_config()) | |
| # Add client request tracking middleware (added first, executes last) | |
| app.add_middleware(BaseHTTPMiddleware, dispatch=track_client_request_middleware) | |
| # Add CORS middleware to allow cross-origin requests | |
| allow_all_origins = { | |
| True: ["*", "localhost", "127.0.0.1", "::1"], # for debug mode, allow all | |
| False: [ | |
| "localhost", | |
| "127.0.0.1", | |
| "pfun.run", | |
| "pfun.one", | |
| "pfun.me", | |
| "pfun.app", | |
| "cloud.tail38611b.ts.net", | |
| "gbot.tail38611b.ts.net", | |
| "nixos.tail38611b.ts.net", | |
| ], | |
| } | |
| # Convert to list to satisfy Sequence[str] type requirement | |
| allowed_hosts = allow_all_origins[debug_mode] | |
| if isinstance(allowed_hosts, set): | |
| allowed_hosts = list(allowed_hosts) | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=allowed_hosts, | |
| allow_headers=[ | |
| "Authorization", | |
| "Access-Control-Allow-Origin", | |
| "Content-Security-Policy", | |
| "Content-Type", | |
| ], | |
| allow_methods=["GET", "POST", "OPTIONS", "HEAD"], | |
| allow_credentials=True, | |
| max_age=300, | |
| ) | |
| # Add TrustedHost middleware | |
| app.add_middleware( | |
| TrustedHostMiddleware, | |
| allowed_hosts=allowed_hosts, | |
| ) | |
| # Add Session middleware (added last, executes first) | |
| app.add_middleware( | |
| SessionMiddleware, | |
| secret_key=get_settings().secret_key, | |
| ) | |
| ### | |
| # --- Setup Admin (sqladmin) --- | |
| ### | |
| from pfun_cma_model.admin.core import Session, engine | |
| from pfun_cma_model.admin.auth import authentication_backend | |
| from sqladmin import Admin | |
| from pfun_cma_model.admin.views import UserAdmin, ReportView | |
| # Configure the admin interface with the SQLAlchemy engine and register views | |
| admin = Admin( | |
| app, | |
| engine, | |
| session_maker=Session, | |
| authentication_backend=authentication_backend, | |
| title="PFun CMA Admin", | |
| logo_url="/static/icons/pfun-cutielogo-icon.png", | |
| favicon_url="/static/icons/pfun-cutielogo-icon.ico", | |
| ) | |
| # Import admin views to register them with the admin interface | |
| admin.add_view(UserAdmin) | |
| admin.add_view(ReportView) | |
| async def login_google(request: Request) -> Response: | |
| """Redirect the user to the Google login page.""" | |
| return RedirectResponse(url="/sso/auth/login") | |
| # Register the Google login route with the admin interface | |
| admin.app.router.add_route("/auth/google", login_google) | |
| ### | |
| # --- Include Routers --- | |
| app.include_router(auth_routes.router, tags=["auth"]) | |
| app.include_router(dexcom_routes.router, prefix="/dexcom", tags=["dexcom"]) | |
| app.include_router(data_routes.router, prefix="/data", tags=["data"]) | |
| app.include_router(params_routes.router, prefix="/params", tags=["params"]) | |
| app.include_router(sso_routes.router, prefix="/sso", tags=["sso"]) | |
| app.include_router(demo_routes.router, prefix="/demo", tags=["demo"]) | |
| app.include_router(llm_routes.router, prefix="/llm", tags=["llm"]) | |
| def health_check(): | |
| """Health check endpoint.""" | |
| logger.debug("Health check endpoint accessed.") | |
| return {"status": "ok", "message": "PFun CMA Model API is running."} | |
| def _get_templates() -> Jinja2Templates: | |
| """Get templates, raising HTTPException if not initialized.""" | |
| if templates is None: | |
| from fastapi import HTTPException | |
| raise HTTPException(status_code=503, detail="Templates not initialized") | |
| return templates | |
| def about_document(request: Request): | |
| """PFun Glucose about document.""" | |
| return _get_templates().TemplateResponse( | |
| request, "about-doc.html.jinja2", context={} | |
| ) | |
| def pitch_document(request: Request): | |
| """PFun Glucose pitch document.""" | |
| return _get_templates().TemplateResponse(request, "pitch-doc.html.jinja2") | |
| def root(request: Request, real_ip: str = Header(None, alias="X-Real-IP")): | |
| """Root endpoint to display the homepage.""" | |
| ts_msg = datetime.now().strftime("%Y-%m-%d %H:%M:%S") | |
| logger.debug("Root endpoint accessed at %s", ts_msg) | |
| # Render the index.html template | |
| return _get_templates().TemplateResponse( | |
| request, | |
| "index.html.jinja2", | |
| context=dict( | |
| year=datetime.now().year, message=f"Accessed at: {ts_msg}; from: {real_ip}" | |
| ), | |
| ) | |
| def login_sso_route(request: Request): | |
| return templates.TemplateResponse( | |
| request, "sqladmin/login.html", context={"admin": admin} | |
| ) | |
| def _read_favicon() -> bytes: | |
| """Read and cache the favicon file content.""" | |
| with open(STATIC_DIR / "icons" / "pfun-cutielogo-icon.ico", "rb") as f: | |
| return f.read() | |
| def favicon(): | |
| img = _read_favicon() | |
| return Response(content=img, media_type="image/x-icon") | |
| # -- CMA Model endpoints -- | |
| def get_model_instance(): | |
| """FastAPI dependency to get a singleton CMA model instance.""" | |
| # This function body runs only once, and the result is cached for subsequent calls. | |
| return CMASleepWakeModel() | |
| async def run_model( | |
| config: Annotated[CMAModelParams, Body()] | None = None, | |
| model: CMASleepWakeModel = Depends(get_model_instance), | |
| ): | |
| """Runs the CMA model.""" | |
| if config is not None: | |
| model.update(config) | |
| df = model.run() | |
| output = df.to_json() | |
| response = Response( | |
| content=output, | |
| status_code=200, | |
| headers={ | |
| "Content-Type": "application/json", | |
| "Access-Control-Allow-Origin": "*", | |
| }, | |
| ) | |
| if hasattr(response.body, "decode"): | |
| # maintain backward compatibility | |
| logger.debug("Response: %s", bytes(response.body).decode("utf-8")) | |
| return response | |
| async def run_at_time_route( | |
| t0: float | int, | |
| t1: float | int, | |
| n: int, | |
| # type: ignore | |
| config: Optional[CMAModelParams] = None, | |
| model: CMASleepWakeModel = Depends(get_model_instance), | |
| ): | |
| """Run the CMA model at a specific time. | |
| Parameters: | |
| - t0 (float | int): The start time (in decimal hours). | |
| - t1 (float | int): The end time (in decimal hours). | |
| - n (int): The number of samples. | |
| - config (CMAModelParams): The model configuration parameters. | |
| """ | |
| try: | |
| if config is None: | |
| config_obj = CMAModelParams() # type: ignore | |
| else: | |
| config_obj = config | |
| config_dict: Mapping = config_obj.model_dump() # type: ignore | |
| # Import local function to avoid circular dependency if I moved it to stream.py | |
| # But wait, stream.py imports cma which is fine. | |
| # Ideally I should import it from stream.py or a new ops.py | |
| # For now, I'll use the one I moved to stream.py | |
| from pfun_cma_model.stream import run_at_time_func | |
| output = await run_at_time_func(model, t0, t1, n, **config_dict) | |
| return output | |
| except Exception as err: | |
| logger.error("failed to run at time.", exc_info=True) | |
| error_response = Response( | |
| content=json.dumps( | |
| { | |
| "error": "failed to run at time. See error message on server log.", | |
| "exception": str(err), | |
| } | |
| ), | |
| status_code=500, | |
| ) | |
| return error_response | |
| async def run_at_time_stream_route( | |
| t0: float | int, | |
| t1: float | int, | |
| n: int, | |
| # type: ignore | |
| config: Optional[CMAModelParams] = None, | |
| model: CMASleepWakeModel = Depends(get_model_instance), | |
| ): | |
| """Streaming version of the run-at-time route.""" | |
| from pfun_cma_model.stream import stream_run_at_time_func | |
| async def iter_response(): | |
| try: | |
| config_obj = config | |
| if config_obj is None: | |
| config_obj = CMAModelParams() # type: ignore | |
| config_dict: Mapping = config_obj.model_dump() # type: ignore | |
| async for row in stream_run_at_time_func(model, t0, t1, n, **config_dict): | |
| yield row | |
| except Exception as err: | |
| # Log full exception details and stack trace on the server, | |
| # but return only a generic error message to the client. | |
| logger.error("failed to run at time.", exc_info=True) | |
| yield ( | |
| json.dumps( | |
| { | |
| "error": "failed to run at time. See error message on server log.", | |
| "status_code": 500, | |
| } | |
| ) | |
| + "\n" | |
| ) | |
| return StreamingResponse(iter_response(), media_type="application/x-ndjson") | |
| # -- WebSocket Routes -- | |
| # Import websockets module to register events | |
| PFunSocketIOSession = importlib.import_module( | |
| "pfun_cma_model.misc.sessions" | |
| ).PFunSocketIOSession | |
| PFunWebsocketNamespace = importlib.import_module( | |
| "pfun_cma_model.routes.ws" | |
| ).PFunWebsocketNamespace | |
| # Consolidated Socket.IO session instantiation | |
| socketio_session = PFunSocketIOSession(app=app, ns=PFunWebsocketNamespace()) | |
| pfun_sio_session = socketio_session # alias for backward compatibility | |
| async def health_check_run_at_time(): | |
| """Health check endpoint for the 'run-at-time' WebSocket functionality.""" | |
| logger.debug("Health check for 'run-at-time' WebSocket endpoint accessed.") | |
| # Simple check if the socketio server is set | |
| if socketio_session.sio is not None: | |
| return {"status": "ok", "message": "'run-at-time' WebSocket is running."} | |
| else: | |
| return Response( | |
| content=json.dumps( | |
| { | |
| "status": "error", | |
| "message": "'run-at-time' WebSocket is NOT running.", | |
| } | |
| ), | |
| status_code=503, | |
| headers={"Content-Type": "application/json"}, | |
| ) | |
| # -- Model Fitting Endpoints -- | |
| async def fit_model_to_data( | |
| # type: ignore | |
| data: dict | str, | |
| config: Optional[CMAModelParams | str] = None, | |
| ): | |
| from pandas import DataFrame | |
| from pfun_cma_model.data import read_sample_data | |
| from pfun_cma_model.engine.fit import fit_model as cma_fit_model | |
| if len(data) == 0: | |
| logger.debug("Sample data will be loaded as no data was provided in query.") | |
| data = read_sample_data(convert2json=False) # type: ignore | |
| logger.debug("...Sample data retrieved:\n'%s'\n\n", data[:100]) | |
| if isinstance(data, str): | |
| data = json.loads(data) | |
| cma_config: CMAModelParams # declare variable for type hinting | |
| if isinstance(config, str): | |
| logger.debug("Config received as string, parsing JSON.") | |
| # @note: config expected as JSON string | |
| config_dict = json.loads(config) | |
| # @note: config -> CMAModelParams object | |
| cma_config: CMAModelParams = CMAModelParams(**config_dict) # type: ignore | |
| try: | |
| df = DataFrame(data) | |
| fit_result = cma_fit_model(df, **cma_config.model_dump()) # type: ignore | |
| logger.debug("Model fitted successfully.") | |
| logger.debug("Fit result: %s", fit_result) | |
| if fit_result is None: | |
| raise ValueError("Fit result is None. Model fitting failed.") | |
| output = fit_result.model_dump_json() | |
| except (json.JSONDecodeError, ValueError) as exc: | |
| logger.error( | |
| "Validation/Decoding error. Failed to fit to data. Exception:\n%s", | |
| str(exc), | |
| exc_info=False, | |
| ) | |
| error_response = Response( | |
| content=json.dumps( | |
| { | |
| "error": "Failed to fit data due to invalid input or configuration.", | |
| "exception": str(exc), | |
| "exception_type": type(exc).__name__, | |
| } | |
| ), | |
| status_code=400, | |
| headers={"Content-Type": "application/json"}, | |
| ) | |
| return error_response | |
| except Exception as exc: | |
| logger.error( | |
| "Exception encountered. Failed to fit to data. Exception:\n%s", | |
| str(exc), | |
| exc_info=False, | |
| ) | |
| error_response = Response( | |
| content=json.dumps( | |
| { | |
| "error": "failed to fit data. See error message on server log.", | |
| "exception": str(exc), | |
| "exception_type": type(exc).__name__, | |
| } | |
| ), | |
| status_code=500, | |
| headers={"Content-Type": "application/json"}, | |
| ) | |
| return error_response | |
| response = Response( | |
| content=output, | |
| status_code=200, | |
| headers={"Content-Type": "application/json"}, | |
| ) | |
| return response | |
| from fastapi_mcp import FastApiMCP | |
| # setup MCP server | |
| mcp = FastApiMCP(app) | |
| mcp.mount_http() | |
Xet Storage Details
- Size:
- 19 kB
- Xet hash:
- 16bbf780b65be521ce41a1f95b01810162b2b91b2f8fd316638680bf50ff2a63
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.