-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.py
146 lines (107 loc) · 3.87 KB
/
main.py
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
from fastapi import FastAPI , File, UploadFile
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
import uvicorn
import numpy as np
import pandas as pd
from fastapi.middleware.cors import CORSMiddleware
from prediction_model.predict import generate_predictions,generate_predictions_batch
from prediction_model.config import config
import mlflow
import io
import boto3
from datetime import datetime
from prometheus_fastapi_instrumentator import Instrumentator
def upload_to_s3(file_content, filename):
s3 = boto3.client('s3')
current_date = datetime.now().strftime("%Y-%m-%d")
if filename.endswith('.csv'):
filename = filename[:-4]
current_datetime = datetime.now().strftime("%Y-%m-%d_%H:%M:%S")
folder_path = f"{config.FOLDER}/{current_date}"
filename_with_datetime = f"{filename}_{current_datetime}.csv"
s3_key = f"{folder_path}/{filename_with_datetime}"
response = s3.put_object(Bucket=config.S3_BUCKET, Key=s3_key, Body=file_content)
return s3_key
# mlflow.set_tracking_uri("http://localhost:5000")
mlflow.set_tracking_uri(config.TRACKING_URI)
app = FastAPI(
title="Loan Prediction App using FastAPI - MLOps",
description = "MLOps Demo",
version='1.0'
)
origins=[
"*"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
Instrumentator().instrument(app).expose(app)
class LoanPrediction(BaseModel):
Gender: str
Married: str
Dependents: str
Education: str
Self_Employed: str
ApplicantIncome: float
CoapplicantIncome: float
LoanAmount: float
Loan_Amount_Term: float
Credit_History: float
Property_Area: str
@app.get("/")
def index():
return {"message":"Welcome to the MLOps Loan Prediction app" }
@app.post("/prediction_api")
def predict(loan_details: LoanPrediction):
data = loan_details.model_dump()
prediction = generate_predictions([data])["prediction"][0]
if prediction == "Y":
pred = "Approved"
else:
pred = "Rejected"
return {"status":pred}
@app.post("/prediction_ui")
def predict_gui(Gender: str,
Married: str,
Dependents: str,
Education: str,
Self_Employed: str,
ApplicantIncome: float,
CoapplicantIncome: float,
LoanAmount: float,
Loan_Amount_Term: float,
Credit_History: float,
Property_Area: str):
input_data = [Gender, Married,Dependents, Education, Self_Employed,ApplicantIncome,
CoapplicantIncome,LoanAmount, Loan_Amount_Term,Credit_History, Property_Area ]
cols = ['Gender', 'Married', 'Dependents', 'Education',
'Self_Employed', 'ApplicantIncome', 'CoapplicantIncome', 'LoanAmount',
'Loan_Amount_Term', 'Credit_History', 'Property_Area']
data_dict = dict(zip(cols,input_data))
prediction = generate_predictions([data_dict])["prediction"][0]
if prediction == "Y":
pred = "Approved"
else:
pred = "Rejected"
return {"status":pred}
@app.post("/batch_prediction")
async def batch_predict(file: UploadFile = File(...)):
content = await file.read()
df = pd.read_csv(io.BytesIO(content),index_col=False)
print(df)
# Ensure the CSV file contains the required features
required_columns = config.FEATURES
if not all(column in df.columns for column in required_columns):
return {"error": "CSV file does not contain the required columns."}
predictions = generate_predictions_batch(df)["prediction"]
df['Prediction'] = predictions
result = df.to_csv(index=False)
s3_key = upload_to_s3(result.encode('utf-8'), file.filename)
return StreamingResponse(io.BytesIO(result.encode('utf-8')), media_type="text/csv", headers={"Content-Disposition":"attachment; filename=predictions.csv"})
if __name__== "__main__":
uvicorn.run(app, host="0.0.0.0",port=8005)