main.py 9.39 KB
Newer Older
Hansika Kithmin L. Hewa's avatar
Hansika Kithmin L. Hewa committed
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 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
import uvicorn
from fastapi import FastAPI,Depends,File, UploadFile,HTTPException
from fastapi.middleware.cors import CORSMiddleware
import pandas as pd
import pickle
from model_loader import load_model,DecisionTree_model,Nephrotic_model,CKD_model,AKI_model
from prophet import Prophet
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
from typing import Optional
from pydantic import BaseModel,ValidationError

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
    allow_credentials=True,
)


def get_loaded_model():
    model = load_model()
    return model

def get_DecisionTree_model():
    model = DecisionTree_model()
    return model

@app.on_event("startup")
async def startup_event():
    app.loaded_model = get_loaded_model()

@app.get("/")
def read_root():
    return {"Hello": "World"}


class InputData(BaseModel):
    age: int
    blood_pressure: float
    specific_gravity: float
    albumin: float
    sugar: float
    red_blood_cells: int
    pus_cell: int
    pus_cell_clumps: int
    bacteria: int
    blood_glucose_random: float
    blood_urea: float
    serum_creatinine: float
    sodium: float
    potassium: float
    haemoglobin: float
    packed_cell_volume: float
    white_blood_cell_count: float
    red_blood_cell_count: float
    hypertension: int
    diabetes_mellitus: int
    coronary_artery_disease: int
    appetite: int
    peda_edema: int
    aanemia: int

@app.post("/predict_ckd/")
async def predict_ckd(input_data: InputData,loaded_model=Depends(get_loaded_model)):
    # Validate input_data using Pydantic models.
    print(input_data.age)
    print(input_data.blood_pressure)
    print(input_data.peda_edema)
    data = pd.DataFrame({
        'age': [input_data.age],
        'blood_pressure': [input_data.blood_pressure],
        'specific_gravity': [input_data.specific_gravity],
        'albumin': [input_data.albumin],
        'sugar': [input_data.sugar],
        'red_blood_cells': [input_data.red_blood_cells],
        'pus_cell': [input_data.pus_cell],
        'pus_cell_clumps': [input_data.pus_cell_clumps],
        'bacteria': [input_data.bacteria],
        'blood_glucose_random': [input_data.blood_glucose_random],
        'blood_urea': [input_data.blood_urea],
        'serum_creatinine': [input_data.serum_creatinine],
        'sodium': [input_data.sodium],
        'potassium': [input_data.potassium],
        'haemoglobin': [input_data.haemoglobin],
        'packed_cell_volume': [input_data.packed_cell_volume],
        'white_blood_cell_count': [input_data.white_blood_cell_count],
        'red_blood_cell_count': [input_data.red_blood_cell_count],
        'hypertension': [input_data.hypertension],
        'diabetes_mellitus': [input_data.diabetes_mellitus],
        'coronary_artery_disease': [input_data.coronary_artery_disease],
        'appetite': [input_data.appetite],
        'peda_edema': [input_data.peda_edema],
        'aanemia': [input_data.aanemia]
    })

    new_pred_rf_clf = loaded_model.predict(data)
    print(new_pred_rf_clf)
    return int(new_pred_rf_clf)


def Drg_forecast(df):
    m = Prophet()
    m.fit(df)
    future = m.make_future_dataframe(3, freq='MS')
    forecast = m.predict(future)
    forecast = forecast[['ds','yhat']].tail(3)
    # forecast.to_csv("last3.csv")
    result = []
    for index, row in forecast.iterrows():
        timestamp = pd.Timestamp(row['ds'])
        date_only = timestamp.date()
        rounded_yhat = round(row['yhat'])
        result.append({'date': str(date_only), 'prediction': rounded_yhat})
    return result

@app.post("/uploadcsv/")
def upload_csv(csv_file: UploadFile = File(...)):
    dataframe = pd.read_csv(csv_file.file)
    dataframe.columns = ['ds', 'y']
    predictions = Drg_forecast(dataframe)
    print(predictions)
    return predictions

class InputDataForecast(BaseModel):
    date:str
    sales:int

@app.post("/forecast/")
def forecast_via_values(inputdataF :InputDataForecast):
    data = pd.DataFrame({'ds':[inputdataF.date],'y':[inputdataF.sales]})
    df = pd.read_csv('drg1.csv')
    df.columns = ['ds', 'y']
    frames = [df, data]
    dataframe = pd.concat(frames)
    predictions = Drg_forecast(dataframe)
    print(predictions)
    return predictions

def recommend_diet(patient_data,loaded_model):  
    patient_df = pd.DataFrame([patient_data])
    
    gender_mapping = {'M': 0, 'F': 1}
    conditions_mapping = {'Hypertension': 0, 'Diabetes': 1, 'nan': 2}
    food_mapping = {'Low Sodium': 0, 'Low Potassium': 1, 'Balanced': 2}

    patient_df['Gender'] = patient_df['Gender'].map(gender_mapping)
    patient_df['Other Conditions'] = patient_df['Other Conditions'].map(conditions_mapping)
    patient_df['Preferred Food'] = patient_df['Preferred Food'].map(food_mapping)

    # Predict the kidney disease stage
    level = loaded_model.predict(patient_df)[0]
    print(level)

    if level == 1:
        return "Maintain a balanced diet. No specific restrictions but ensure a healthy intake of protein, sodium, potassium and phosphorus."
    elif level == 2:
        return "Start to monitor and limit the intake of protein, sodium, potassium and phosphorus to prevent further kidney damage."
    elif level == 3:
        return "Follow a diet low in protein, sodium, potassium and phosphorus. Consult a dietitian for a personalized diet plan."


class InputDataDiet_Plan(BaseModel):
    Age: int
    Gender: str
    BMI: int
    Current_Protein_Intake: int
    Current_Sodium_Intake: int
    Current_Potassium_Intake: int
    Current_Phosphorus_Intake: int
    Other_Conditions: str
    GFR: int
    Proteinuria: int
    Preferred_Food: str

@app.post("/Suggest_Diet_Plan/")
def Suggest_Diet_Plan(
    input_Data_Diet_Plan:InputDataDiet_Plan,
    loaded_model_1=Depends(get_DecisionTree_model)
):
    patient_data = {
    'Age': input_Data_Diet_Plan.Age,
    'Gender': input_Data_Diet_Plan.Gender,
    'BMI': input_Data_Diet_Plan.BMI,
    'Current Protein Intake (g)': input_Data_Diet_Plan.Current_Protein_Intake,
    'Current Sodium Intake (mg)': input_Data_Diet_Plan.Current_Sodium_Intake,
    'Current Potassium Intake (mg)': input_Data_Diet_Plan.Current_Potassium_Intake,
    'Current Phosphorus Intake (mg)': input_Data_Diet_Plan.Current_Phosphorus_Intake,
    'Other Conditions': input_Data_Diet_Plan.Other_Conditions,
    'GFR': input_Data_Diet_Plan.GFR,
    'Proteinuria':input_Data_Diet_Plan.Proteinuria,
    'Preferred Food': input_Data_Diet_Plan.Preferred_Food,
    }
    suggesting = recommend_diet(patient_data,loaded_model_1)
    print(suggesting)
    return suggesting

class Symptoms(BaseModel):
    Age: int
    Gender: str
    AKIDiagnosis: str
    InitialCreatinine: float
    PeakCreatinine: float
    UrineOutput: int

    Proteinuria: str
    Edema: str
    Albumin_Level: str

    Change_in_Urination: int
    Swelling: int

    Metallic_Taste_in_Mouth: int

    Dizziness_Trouble_Concentrating: int
    Pain_in_Back_or_Sides: int
    Nausea_Vomiting: int

@app.post("/predict_diseas/")
def predict_disease(
    inputDData:Symptoms,

    Model1=Depends(AKI_model),
    Model2=Depends(Nephrotic_model),
    Model3=Depends(CKD_model),
):
    if (
        inputDData.AKIDiagnosis != "" and
        inputDData.InitialCreatinine is not None and
        inputDData.PeakCreatinine is not None and
        inputDData.UrineOutput is not None and
        inputDData.Swelling is not None
    ):
        patient_data = {
            "AKIDiagnosis" :inputDData.AKIDiagnosis,
            "InitialCreatinine" :inputDData.InitialCreatinine,
            "PeakCreatinine" :inputDData.PeakCreatinine,
            "UrineOutput" :inputDData.UrineOutput,
            "Swelling" :inputDData.Swelling,
        }
        print("11")
        results = Model_1(patient_data,Model1)
        return results
    elif (
        inputDData.Change_in_Urination is not None or
        inputDData.Swelling is not None or
        inputDData.Metallic_Taste_in_Mouth is not None or
        inputDData.Dizziness_Trouble_Concentrating is not None or
        inputDData.Pain_in_Back_or_Sides is not None or
        inputDData.Nausea_Vomiting is not None
    ):    
        patient_data = {
            'Change_in_Urination': inputDData.Change_in_Urination,
            'Metallic_Taste_in_Mouth': inputDData.Metallic_Taste_in_Mouth,
            'Dizziness_Trouble_Concentrating': inputDData.Dizziness_Trouble_Concentrating,
            'Pain_in_Back_or_Sides': inputDData.Pain_in_Back_or_Sides,
            'Nausea_Vomiting': inputDData.Nausea_Vomiting,
        }
        print("11")
        results = Model_3(patient_data,Model3)
        return results
    else:
        return "Invalid input parameters"

def Model_1(patient_data,model):
    patient_data = pd.DataFrame([patient_data])
    AKIDiagnosis = {'Yes': 0, 'No': 1}
    # Swelling = {'Yes': 0, 'No': 1}
    patient_data['AKIDiagnosis'] = patient_data['AKIDiagnosis'].map(AKIDiagnosis)
    # patient_data['Swelling'] = patient_data['Swelling'].map(Swelling)
    results = model.predict(patient_data)
    if results==0:
        results = "Has AKI"
    else:
        results = "no AKI"
    return results

def Model_3(patient_data,model):
    patient_data = pd.DataFrame([patient_data])
    results = model.predict(patient_data)[0]
    if results==0:
        results = "Has CKD"
    else:
        results = "no CKD"
    return results

if __name__ == "__main__":
    uvicorn.run("main:app", host="127.0.0.1",port=8000, log_level="info")