|
| 1 | +"""FastAPI app factory for serving BlueCast pipelines.""" |
| 2 | + |
| 3 | +import logging |
| 4 | +import traceback |
| 5 | +from typing import Any, Dict, List |
| 6 | + |
| 7 | +import numpy as np |
| 8 | +import pandas as pd |
| 9 | + |
| 10 | +from bluecast.serve.schemas import ( |
| 11 | + _get_class_problem, |
| 12 | + _has_conformal, |
| 13 | + build_request_model, |
| 14 | + build_schema_response, |
| 15 | +) |
| 16 | + |
| 17 | +logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | + |
| 20 | +def _format_prediction(raw_result: Any, class_problem: str) -> Dict[str, Any]: |
| 21 | + """Format a single prediction result into a JSON-friendly dict.""" |
| 22 | + if class_problem in ("binary", "multiclass"): |
| 23 | + if isinstance(raw_result, tuple) and len(raw_result) == 2: |
| 24 | + probs, classes = raw_result |
| 25 | + prob_val = probs.tolist() if hasattr(probs, "tolist") else probs |
| 26 | + class_val = classes.tolist() if hasattr(classes, "tolist") else classes |
| 27 | + if isinstance(prob_val, list) and len(prob_val) == 1: |
| 28 | + prob_val = prob_val[0] |
| 29 | + if isinstance(class_val, list) and len(class_val) == 1: |
| 30 | + class_val = class_val[0] |
| 31 | + return {"probabilities": prob_val, "predicted_class": class_val} |
| 32 | + else: |
| 33 | + val = raw_result.tolist() if hasattr(raw_result, "tolist") else raw_result |
| 34 | + return {"prediction": val} |
| 35 | + else: |
| 36 | + if isinstance(raw_result, (np.ndarray, pd.Series)): |
| 37 | + val = raw_result.tolist() |
| 38 | + if isinstance(val, list) and len(val) == 1: |
| 39 | + val = val[0] |
| 40 | + return {"prediction": val} |
| 41 | + return {"prediction": raw_result} |
| 42 | + |
| 43 | + |
| 44 | +def _format_batch_prediction(raw_result: Any, class_problem: str) -> Dict[str, Any]: |
| 45 | + """Format batch predictions.""" |
| 46 | + if class_problem in ("binary", "multiclass"): |
| 47 | + if isinstance(raw_result, tuple) and len(raw_result) == 2: |
| 48 | + probs, classes = raw_result |
| 49 | + return { |
| 50 | + "probabilities": probs.tolist() if hasattr(probs, "tolist") else list(probs), |
| 51 | + "predicted_classes": ( |
| 52 | + classes.tolist() if hasattr(classes, "tolist") else list(classes) |
| 53 | + ), |
| 54 | + "count": len(probs) if hasattr(probs, "__len__") else 1, |
| 55 | + } |
| 56 | + if isinstance(raw_result, (np.ndarray, pd.Series)): |
| 57 | + return {"predictions": raw_result.tolist(), "count": len(raw_result)} |
| 58 | + return {"predictions": raw_result} |
| 59 | + |
| 60 | + |
| 61 | +def create_app(pipeline: Any) -> Any: |
| 62 | + """Create a FastAPI application from a trained BlueCast pipeline. |
| 63 | +
|
| 64 | + The app auto-generates request schemas from the pipeline's column metadata |
| 65 | + and provides prediction, health, schema, and metrics endpoints. |
| 66 | +
|
| 67 | + :param pipeline: A trained BlueCast pipeline (any variant). |
| 68 | + :returns: A FastAPI application instance. |
| 69 | + """ |
| 70 | + try: |
| 71 | + from fastapi import FastAPI, HTTPException |
| 72 | + except ImportError: |
| 73 | + raise ImportError( |
| 74 | + "FastAPI is required for bluecast.serve. " |
| 75 | + "Install with: pip install 'bluecast[serve]'" |
| 76 | + ) |
| 77 | + |
| 78 | + class_problem = _get_class_problem(pipeline) |
| 79 | + has_conformal = _has_conformal(pipeline) |
| 80 | + |
| 81 | + RequestModel = build_request_model(pipeline) |
| 82 | + |
| 83 | + app = FastAPI( |
| 84 | + title="BlueCast Model API", |
| 85 | + description=( |
| 86 | + f"Auto-generated API for a BlueCast {class_problem} model. " |
| 87 | + f"Conformal prediction: {'enabled' if has_conformal else 'disabled'}." |
| 88 | + ), |
| 89 | + version="1.0.0", |
| 90 | + ) |
| 91 | + |
| 92 | + @app.get("/health") |
| 93 | + def health() -> Dict[str, Any]: |
| 94 | + return { |
| 95 | + "status": "healthy", |
| 96 | + "model_type": class_problem, |
| 97 | + "conformal_prediction": has_conformal, |
| 98 | + } |
| 99 | + |
| 100 | + @app.get("/schema") |
| 101 | + def schema() -> Dict[str, Any]: |
| 102 | + return build_schema_response(pipeline) |
| 103 | + |
| 104 | + @app.get("/metrics") |
| 105 | + def metrics() -> Dict[str, Any]: |
| 106 | + eval_metrics = getattr(pipeline, "eval_metrics", None) |
| 107 | + if hasattr(pipeline, "_inner"): |
| 108 | + eval_metrics = getattr(pipeline._inner, "eval_metrics", eval_metrics) |
| 109 | + if eval_metrics is None: |
| 110 | + return {"message": "No evaluation metrics available. Use fit_eval() to generate."} |
| 111 | + serializable = {} |
| 112 | + for k, v in eval_metrics.items(): |
| 113 | + if isinstance(v, (int, float, str, bool)): |
| 114 | + serializable[k] = v |
| 115 | + elif isinstance(v, (np.floating, np.integer)): |
| 116 | + serializable[k] = float(v) |
| 117 | + return serializable |
| 118 | + |
| 119 | + @app.post("/predict") |
| 120 | + def predict(request: RequestModel) -> Dict[str, Any]: # type: ignore[valid-type] |
| 121 | + try: |
| 122 | + data = request.model_dump() |
| 123 | + data = {k: v for k, v in data.items() if k != "_placeholder"} |
| 124 | + df = pd.DataFrame([data]) |
| 125 | + result = pipeline.predict(df) |
| 126 | + return _format_prediction(result, class_problem) |
| 127 | + except Exception as e: |
| 128 | + logger.error(f"Prediction failed: {e}\n{traceback.format_exc()}") |
| 129 | + raise HTTPException(status_code=400, detail=str(e)) |
| 130 | + |
| 131 | + @app.post("/predict/batch") |
| 132 | + def predict_batch(requests: List[RequestModel]) -> Dict[str, Any]: # type: ignore[valid-type] |
| 133 | + try: |
| 134 | + data_list = [] |
| 135 | + for req in requests: |
| 136 | + d = req.model_dump() |
| 137 | + d = {k: v for k, v in d.items() if k != "_placeholder"} |
| 138 | + data_list.append(d) |
| 139 | + df = pd.DataFrame(data_list) |
| 140 | + result = pipeline.predict(df) |
| 141 | + return _format_batch_prediction(result, class_problem) |
| 142 | + except Exception as e: |
| 143 | + logger.error(f"Batch prediction failed: {e}\n{traceback.format_exc()}") |
| 144 | + raise HTTPException(status_code=400, detail=str(e)) |
| 145 | + |
| 146 | + return app |
0 commit comments