# ta_ml/api/predict.py """ API endpoint for model prediction. """ import logging from fastapi import APIRouter, Depends, HTTPException from api.dependencies import get_prediction_service from models.api import PredictRequest, PredictResponse from services.prediction_service import PredictionService logger = logging.getLogger(__name__) router = APIRouter(prefix="/predict", tags=["Prediction"]) @router.post( "", response_model=PredictResponse, summary="Predict a transaction category", description="Predicts the category for a given transaction text using the currently loaded model.", responses={ 200: { "description": "Prediction was successful.", "content": { "application/json": { "example": { "predicted_label": "Groceries", "confidence": 0.9876, } } }, }, 400: {"description": "Invalid input, such as an empty transaction text."}, 422: {"description": "Validation error, e.g., the 'text' field is missing from the request body."}, 500: {"description": "An internal server error occurred during model inference."}, }, ) def predict_transaction( request: PredictRequest, prediction_service: PredictionService = Depends(get_prediction_service) ): try: result = prediction_service.predict(request.text) return PredictResponse(**result) except ValueError as e: logger.warning(f"Prediction failed due to invalid input: {e}") raise HTTPException(status_code=400, detail=str(e)) except Exception as e: logger.error( f"An unexpected error occurred during prediction: {e}", exc_info=True) raise HTTPException( status_code=500, detail="An internal error occurred during prediction." )