File size: 3,301 Bytes
523415f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from .predictor import predict_interest, get_questions, is_model_loaded
from .models import PredictionRequest, PredictionResponse, QuestionsResponse, HealthResponse

app = FastAPI(
    title="Travellers Interest Predictions",
    description="A FastAPI server with integrated ML model for interest category prediction",
    version="1.0.0"
)

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Configure this for production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/", response_model=dict)
def read_root():
    """Root endpoint to check if the server is running."""
    return {"message": "Travellers Interest Predictions is running!"}


@app.get("/health", response_model=HealthResponse)
def health_check():
    """Health check endpoint to verify server and model status."""
    model_loaded = is_model_loaded()
    return HealthResponse(
        status="healthy" if model_loaded else "degraded",
        model_loaded=model_loaded,
        message="Model loaded successfully" if model_loaded else "Model not loaded - predictions unavailable"
    )


@app.get("/questions", response_model=QuestionsResponse)
def get_survey_questions():
    """Get the list of survey questions for the ML model."""
    questions = get_questions()
    return QuestionsResponse(
        questions=questions,
        total_questions=len(questions)
    )


@app.post("/predict", response_model=PredictionResponse)
def predict_category(request: PredictionRequest):
    """
    Predict interest category based on survey answers.
    
    Args:
        request: PredictionRequest containing a list of 10 answers (integers from 1 to 5)
    
    Returns:
        PredictionResponse with the predicted category
    """
    if not is_model_loaded():
        raise HTTPException(
            status_code=503, 
            detail="ML model is not loaded. Cannot make predictions."
        )
    
    try:
        prediction = predict_interest(request.answers)
        
        # Check if prediction is an error message
        if prediction.startswith("Error:") or prediction.startswith("Model is not loaded"):
            return PredictionResponse(
                success=False,
                prediction="",
                message=prediction
            )
        
        return PredictionResponse(
            success=True,
            prediction=prediction,
            message="Prediction successful"
        )
    
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Error during prediction: {str(e)}"
        )


@app.get("/predict/sample")
def get_sample_prediction():
    """
    Get a sample prediction request format for testing.
    """
    return {
        "example_request": {
            "answers": [3, 4, 2, 5, 3, 2, 4, 1, 3, 4]
        },
        "description": "Send a POST request to /predict with answers array containing 10 integers (1-5)",
        "questions_endpoint": "/questions"
    }


if __name__ == "__main__":
    import uvicorn
    # Use the correct module path when running as a module
    uvicorn.run("src.main:app", host="0.0.0.0", port=8000, reload=True)