Commit 79b69bc9 authored by Weththasinghe A.S's avatar Weththasinghe A.S

Merge branch 'IT20151010-API' into 'master'

completed API

See merge request !11
parents 83039b7c c63c76cd
name: ClassificationModels
channels:
- conda-forge
- defaults
dependencies:
- asttokens=2.0.5=pyhd3eb1b0_0
- backcall=0.2.0=pyhd3eb1b0_0
- blas=1.0=mkl
- bottleneck=1.3.5=py39h080aedc_0
- brotli=1.0.9=h2bbff1b_7
- brotli-bin=1.0.9=h2bbff1b_7
- ca-certificates=2023.05.30=haa95532_0
- certifi=2023.7.22=py39haa95532_0
- cmdstan=2.31.0=h58f7c43_0
- cmdstanpy=1.1.0=py39haa95532_0
- colorama=0.4.6=py39haa95532_0
- comm=0.1.2=py39haa95532_0
- convertdate=2.3.2=pyhd3eb1b0_0
- cycler=0.11.0=pyhd3eb1b0_0
- debugpy=1.6.7=py39hd77b12b_0
- decorator=5.1.1=pyhd3eb1b0_0
- ephem=4.1.2=py39h2bbff1b_0
- executing=0.8.3=pyhd3eb1b0_0
- freetype=2.12.1=ha860e81_0
- giflib=5.2.1=h8cc25b3_3
- glib=2.69.1=h5dc1a3c_2
- gst-plugins-base=1.18.5=h9e645db_0
- gstreamer=1.18.5=hd78058f_0
- holidays=0.29=py39haa95532_0
- icu=58.2=ha925a31_3
- importlib-metadata=6.0.0=py39haa95532_0
- importlib_metadata=6.0.0=hd3eb1b0_0
- importlib_resources=5.2.0=pyhd3eb1b0_1
- intel-openmp=2023.1.0=h59b6b97_46319
- ipykernel=6.25.0=pyh6817e22_0
- ipython=8.12.2=py39haa95532_0
- jedi=0.18.1=py39haa95532_1
- jpeg=9e=h2bbff1b_1
- jupyter_client=8.1.0=py39haa95532_0
- jupyter_core=5.3.0=py39haa95532_0
- kiwisolver=1.4.4=py39hd77b12b_0
- krb5=1.19.4=h5b6d351_0
- lerc=3.0=hd77b12b_0
- libbrotlicommon=1.0.9=h2bbff1b_7
- libbrotlidec=1.0.9=h2bbff1b_7
- libbrotlienc=1.0.9=h2bbff1b_7
- libclang=14.0.6=default_hb5a9fac_1
- libclang13=14.0.6=default_h8e68704_1
- libdeflate=1.17=h2bbff1b_0
- libffi=3.4.4=hd77b12b_0
- libiconv=1.16=h2bbff1b_2
- libogg=1.3.5=h2bbff1b_1
- libpng=1.6.39=h8cc25b3_0
- libsodium=1.0.18=h62dcd97_0
- libtiff=4.5.0=h6c2663c_2
- libvorbis=1.3.7=he774522_0
- libwebp=1.2.4=hbc33d0d_1
- libwebp-base=1.2.4=h2bbff1b_1
- libxml2=2.10.3=h0ad7f3c_0
- libxslt=1.1.37=h2bbff1b_0
- lunarcalendar=0.0.9=pyhd3eb1b0_0
- lz4-c=1.9.4=h2bbff1b_0
- m2-bash=4.3.042=5
- m2-coreutils=8.25=102
- m2-filesystem=2016.04=4
- m2-gcc-libs=5.3.0=4
- m2-gmp=6.1.0=3
- m2-libiconv=1.14=3
- m2-libintl=0.19.7=4
- m2-msys2-runtime=2.5.0.17080.65c939c=3
- m2-sed=4.2.2=3
- m2w64-binutils=2.25.1=5
- m2w64-bzip2=1.0.6=6
- m2w64-crt-git=5.0.0.4636.2595836=2
- m2w64-gcc=5.3.0=6
- m2w64-gcc-ada=5.3.0=6
- m2w64-gcc-fortran=5.3.0=6
- m2w64-gcc-libgfortran=5.3.0=6
- m2w64-gcc-libs=5.3.0=7
- m2w64-gcc-libs-core=5.3.0=7
- m2w64-gcc-objc=5.3.0=6
- m2w64-gmp=6.1.0=2
- m2w64-headers-git=5.0.0.4636.c0ad18a=2
- m2w64-isl=0.16.1=2
- m2w64-libiconv=1.14=6
- m2w64-libmangle-git=5.0.0.4509.2e5a9a2=2
- m2w64-libwinpthread-git=5.0.0.4634.697f757=2
- m2w64-make=4.1.2351.a80a8b8=2
- m2w64-mpc=1.0.3=3
- m2w64-mpfr=3.1.4=4
- m2w64-pkg-config=0.29.1=2
- m2w64-toolchain=5.3.0=7
- m2w64-toolchain_win-64=2.4.0=0
- m2w64-tools-git=5.0.0.4592.90b8472=2
- m2w64-windows-default-manifest=6.4=3
- m2w64-winpthreads-git=5.0.0.4634.697f757=2
- m2w64-zlib=1.2.8=10
- matplotlib-base=3.7.1=py39hf11a4ad_1
- matplotlib-inline=0.1.6=py39haa95532_0
- mkl=2023.1.0=h6b88ed4_46357
- mkl-service=2.4.0=py39h2bbff1b_1
- mkl_fft=1.3.6=py39hf11a4ad_1
- mkl_random=1.2.2=py39hf11a4ad_1
- msys2-conda-epoch=20160418=1
- munkres=1.1.4=py_0
- nest-asyncio=1.5.6=py39haa95532_0
- numexpr=2.8.4=py39h7b80656_1
- numpy=1.25.2=py39h055cbcc_0
- numpy-base=1.25.2=py39h65a83cf_0
- openssl=1.1.1v=h2bbff1b_0
- packaging=23.0=py39haa95532_0
- parso=0.8.3=pyhd3eb1b0_0
- pcre=8.45=hd77b12b_0
- pickleshare=0.7.5=pyhd3eb1b0_1003
- pip=23.2.1=py39haa95532_0
- platformdirs=2.5.2=py39haa95532_0
- ply=3.11=py39haa95532_0
- prompt-toolkit=3.0.36=py39haa95532_0
- prophet=1.1.4=py39h28ab207_0
- psutil=5.9.0=py39h2bbff1b_0
- pure_eval=0.2.2=pyhd3eb1b0_0
- pygments=2.15.1=py39haa95532_1
- pymeeus=0.5.11=pyhd3eb1b0_1
- pyparsing=3.0.9=py39haa95532_0
- pyqt=5.15.7=py39hd77b12b_0
- pyqt5-sip=12.11.0=py39hd77b12b_0
- python=3.9.17=h6244533_0
- python-dateutil=2.8.2=pyhd3eb1b0_0
- pytz=2022.7=py39haa95532_0
- pywin32=305=py39h2bbff1b_0
- pyzmq=25.1.0=py39hd77b12b_0
- qt-main=5.15.2=he8e5bd7_8
- qt-webengine=5.15.9=hb9a9bb5_5
- qtwebkit=5.212=h2bbfb41_5
- setuptools=68.0.0=py39haa95532_0
- sip=6.6.2=py39hd77b12b_0
- six=1.16.0=pyhd3eb1b0_1
- sqlite=3.41.2=h2bbff1b_0
- stack_data=0.2.0=pyhd3eb1b0_0
- tbb=2021.8.0=h59b6b97_0
- tk=8.6.12=h2bbff1b_0
- toml=0.10.2=pyhd3eb1b0_0
- tornado=6.3.2=py39h2bbff1b_0
- tqdm=4.65.0=py39hd4e2768_0
- traitlets=5.7.1=py39haa95532_0
- typing_extensions=4.7.1=py39haa95532_0
- vc=14.2=h21ff451_1
- vs2015_runtime=14.27.29016=h5e58377_2
- wcwidth=0.2.5=pyhd3eb1b0_0
- wheel=0.38.4=py39haa95532_0
- xz=5.4.2=h8cc25b3_0
- zeromq=4.3.4=hd77b12b_0
- zipp=3.11.0=py39haa95532_0
- zlib=1.2.13=h8cc25b3_0
- zstd=1.5.5=hd43e919_0
- pip:
- annotated-types==0.5.0
- anyio==3.7.1
- catboost==1.2
- charset-normalizer==3.2.0
- click==8.1.6
- contourpy==1.1.0
- exceptiongroup==1.1.2
- faker==19.3.0
- fastapi==0.101.0
- fonttools==4.42.0
- h11==0.14.0
- idna==3.4
- imbalanced-learn==0.11.0
- imblearn==0.0
- importlib-resources==6.0.0
- ipywidgets==8.1.0
- joblib==1.3.1
- jupyterlab-widgets==3.0.8
- matplotlib==3.7.2
- pandas==2.0.3
- pillow==10.0.0
- plotly==5.15.0
- pydantic==2.1.1
- pydantic-core==2.4.0
- python-graphviz==0.20.1
- python-multipart==0.0.6
- requests==2.31.0
- scikit-learn==1.3.0
- scipy==1.11.1
- seaborn==0.12.2
- sniffio==1.3.0
- starlette==0.27.0
- svm==0.1.0
- tenacity==8.2.2
- threadpoolctl==3.2.0
- tzdata==2023.3
- urllib3==2.0.4
- uvicorn==0.23.2
- widgetsnbextension==4.0.8
- xgboost==1.7.6
- xmltodict==0.13.0
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")
import pickle
def load_model():
with open('rf_clf_model.pkl', 'rb') as model_file:
model = pickle.load(model_file)
return model
def DecisionTree_model():
with open('DTC_model.pkl', 'rb') as model_file:
model = pickle.load(model_file)
return model
def Nephrotic_model():
with open('Random Forest_Nephrotic_model.pkl', 'rb') as model_file:
model = pickle.load(model_file)
return model
def CKD_model():
with open('SVM_model.pkl', 'rb') as model_file:
model = pickle.load(model_file)
return model
def AKI_model():
with open('Random Forest_Aki_model.pkl', 'rb') as model_file:
model = pickle.load(model_file)
return model
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment