InduwaraR's picture
deploy ml model
523415f
Raw History Blame Contribute Delete
3.3 kB
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)