|
|
import joblib |
|
|
from pydantic import BaseModel |
|
|
from fastapi import FastAPI, HTTPException |
|
|
import uvicorn |
|
|
import logging |
|
|
import os |
|
|
|
|
|
logging.basicConfig(level=logging.INFO) |
|
|
|
|
|
|
|
|
try: |
|
|
if os.path.exists('frauddetection.pkl'): |
|
|
model = joblib.load('frauddetection.pkl') |
|
|
else: |
|
|
raise FileNotFoundError("Model file 'frauddetection.pkl' not found.") |
|
|
except Exception as e: |
|
|
logging.error(f"Error loading model: {e}") |
|
|
model = None |
|
|
|
|
|
|
|
|
class InputData(BaseModel): |
|
|
Year: int |
|
|
Month: int |
|
|
UseChip: int |
|
|
Amount: int |
|
|
MerchantName: int |
|
|
MerchantCity: int |
|
|
MerchantState: int |
|
|
mcc: int |
|
|
|
|
|
|
|
|
app = FastAPI() |
|
|
|
|
|
@app.get('/') |
|
|
def welcome(): |
|
|
return {"Welcome": "This is the home page of the API"} |
|
|
|
|
|
|
|
|
@app.post('/predict/') |
|
|
async def predict(data: InputData): |
|
|
if model is None: |
|
|
raise HTTPException(status_code=500, detail="Model not loaded properly.") |
|
|
|
|
|
|
|
|
input_data = data.dict() |
|
|
|
|
|
|
|
|
feature_list = [ |
|
|
input_data['Year'], |
|
|
input_data['Month'], |
|
|
input_data['UseChip'], |
|
|
input_data['Amount'], |
|
|
input_data['MerchantName'], |
|
|
input_data['MerchantCity'], |
|
|
input_data['MerchantState'], |
|
|
input_data['mcc'] |
|
|
] |
|
|
|
|
|
try: |
|
|
|
|
|
prediction = model.predict([feature_list]) |
|
|
result = "Fraud" if prediction[0] == 1 else "Not a Fraud" |
|
|
return {"prediction": result} |
|
|
except Exception as e: |
|
|
logging.error(f"Prediction error: {e}") |
|
|
raise HTTPException(status_code=500, detail="An error occurred during prediction.") |
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__': |
|
|
uvicorn.run(app, host="127.0.0.1", port=8080) |
|
|
|