File size: 2,031 Bytes
ca726f5
 
669c133
ca726f5
 
669c133
 
 
ca726f5
 
669c133
 
 
 
 
 
 
 
ca726f5
 
 
669c133
 
 
 
 
 
 
 
ca726f5
 
 
669c133
ca726f5
 
 
 
 
 
 
669c133
 
 
ca726f5
 
 
 
669c133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca726f5
669c133
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
import joblib
from pydantic import BaseModel
from fastapi import FastAPI, HTTPException
import uvicorn
import logging
import os

logging.basicConfig(level=logging.INFO)

# 1. Load the trained model
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

# 2. Define the input data schema using Pydantic BaseModel
class InputData(BaseModel):
    Year: int
    Month: int
    UseChip: int
    Amount: int
    MerchantName: int
    MerchantCity: int
    MerchantState: int
    mcc: int

# 3. Create a FastAPI app
app = FastAPI()

@app.get('/')
def welcome():
    return {"Welcome": "This is the home page of the API"}

# 4. Define the prediction route
@app.post('/predict/')
async def predict(data: InputData):
    if model is None:
        raise HTTPException(status_code=500, detail="Model not loaded properly.")

    # Convert the input data to a dictionary
    input_data = data.dict()

    # Extract the input features from the dictionary
    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:
        # Perform the prediction using the loaded model
        prediction = model.predict([feature_list])  # Ensure model expects the correct number of features
        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.")

# 5. Run the API with uvicorn
#    Will run on http://127.0.0.1:8080
if __name__ == '__main__':
    uvicorn.run(app, host="127.0.0.1", port=8080)