-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmain.py
65 lines (50 loc) · 1.9 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
import joblib
import pandas as pd
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from loguru import logger
from pydantic import BaseModel
# Initialize instance
app = FastAPI()
# Class to define the request body
class Diabetes_measures(BaseModel):
Pregnancies: int = 6 # Number of times pregnant
Glucose: int = (
148 # Plasma glucose concentration a 2 hours in an oral glucose tolerance test
)
BloodPressure: int = 72 # Diastolic blood pressure (mm Hg)
SkinThickness: int = 35 # Triceps skin fold thickness (mm)
Insulin: int = 0 # 2-Hour serum insulin
BMI: float = 33.6 # Body mass index
DiabetesPedigreeFunction: float = 0.627 # Diabetes pedigree function
Age: int = 50 # Age (years)
# Load model
model = joblib.load("./models/model.pkl")
# Create an endpoint to check api work or not
@app.get("/")
def check_health():
return {"status": "Oke"}
# Initialize cache
cache = {}
# Create an endpoint to make prediction
@app.post("/predict")
def predict(data: Diabetes_measures):
logger.info("Making predictions...")
logger.info(data)
logger.info(jsonable_encoder(data))
logger.info(pd.DataFrame(jsonable_encoder(data), index=[0]))
result = model.predict(pd.DataFrame(jsonable_encoder(data), index=[0]))[0]
return {"result": ["Normal", "Diabetes"][result]}
@app.post("/predict_cache")
def predict_cache(data: Diabetes_measures):
if str(data) in cache:
logger.info("Getting result from cache!")
return cache[str(data)]
else:
logger.info("Making predictions...")
logger.info(data)
logger.info(jsonable_encoder(data))
logger.info(pd.DataFrame(jsonable_encoder(data), index=[0]))
result = model.predict(pd.DataFrame(jsonable_encoder(data), index=[0]))[0]
cache[str(data)] = ["Normal", "Diabetes"][result]
return {"result": ["Normal", "Diabetes"][result]}