File size: 1,907 Bytes
1424118
 
 
 
 
d8afb70
1424118
1c7af52
1424118
 
 
54c349d
1424118
 
d826e4a
54c349d
1424118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# 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."
        )