Commit 41c2f196 authored by Weththasinghe A.S's avatar Weththasinghe A.S

Merge branch 'IT20140984-API' into 'master'

Completed the API development

See merge request !2
parents b5ce5117 9f27a630
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
# CKD-Research-Project-Backend
\ No newline at end of file
Month,Sales
2005-1-31,2815
2005-2-28,2672
2005-3-31,2755
2005-4-30,2721
2005-5-31,2946
2005-6-30,3036
2005-7-31,2282
2005-8-31,2212
2005-9-30,2922
2005-10-31,4301
2005-11-30,5764
2005-12-31,7312
2006-1-31,2541
2006-2-28,2475
2006-3-31,3031
2006-4-30,3266
2006-5-31,3776
2006-6-30,3230
2006-7-31,3028
2006-8-31,1759
2006-9-30,3595
2006-10-31,4474
2006-11-30,6838
2006-12-31,8357
2007-1-31,3113
2007-2-28,3006
2007-3-31,4047
2007-4-30,3523
2007-5-31,3937
2007-6-30,3986
2007-7-31,3260
2007-8-31,1573
2007-9-30,3528
2007-10-31,5211
2007-11-30,7614
2007-12-31,9254
2008-1-31,5375
2008-2-29,3088
2008-3-31,3718
2008-4-30,4514
2008-5-31,4520
2008-6-30,4539
2008-7-31,3663
2008-8-31,1643
2008-9-30,4739
2008-10-31,5428
2008-11-30,8314
2008-12-31,10651
2009-1-31,3633
2009-2-28,4292
2009-3-31,4154
2009-4-30,4121
2009-5-31,4647
2009-6-30,4753
2009-7-31,3965
2009-8-31,1723
2009-9-30,5048
2009-10-31,6922
2009-11-30,9858
2009-12-31,11331
2010-1-31,4016
2010-2-28,3957
2010-3-31,4510
2010-4-30,4276
2010-5-31,4968
2010-6-30,4677
2010-7-31,3523
2010-8-31,1821
2010-9-30,5222
2010-10-31,6872
2010-11-30,10803
2010-12-31,13916
2011-1-31,2639
2011-2-28,2899
2011-3-31,3370
2011-4-30,3740
2011-5-31,2927
2011-6-30,3986
2011-7-31,4217
2011-8-31,1738
2011-9-30,5221
2011-10-31,6424
2011-11-30,9842
2011-12-31,13076
2012-1-31,3934
2012-2-29,3162
2012-3-31,4286
2012-4-30,4676
2012-5-31,5010
2012-6-30,4874
2012-7-31,4633
2012-8-31,1659
2012-9-30,5951
\ No newline at end of file
import uvicorn
from fastapi import FastAPI,Depends,File, UploadFile
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
app = FastAPI()
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"}
@app.post("/predict_ckd")
async def predict_ckd(
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,
loaded_model=Depends(get_loaded_model)
):
data = pd.DataFrame({
'age': [age],
'blood_pressure': [blood_pressure],
'specific_gravity': [specific_gravity],
'albumin': [albumin],
'sugar': [sugar],
'red_blood_cells': [red_blood_cells],
'pus_cell': [pus_cell],
'pus_cell_clumps': [pus_cell_clumps],
'bacteria': [bacteria],
'blood_glucose_random': [blood_glucose_random],
'blood_urea': [blood_urea],
'serum_creatinine': [serum_creatinine],
'sodium': [sodium],
'potassium': [potassium],
'haemoglobin': [haemoglobin],
'packed_cell_volume': [packed_cell_volume],
'white_blood_cell_count': [white_blood_cell_count],
'red_blood_cell_count': [red_blood_cell_count],
'hypertension': [hypertension],
'diabetes_mellitus': [diabetes_mellitus],
'coronary_artery_disease': [coronary_artery_disease],
'appetite': [appetite],
'peda_edema': [peda_edema],
'aanemia': [aanemia]
})
new_pred_rf_clf = loaded_model.predict(data)
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
@app.post("/forecast")
def forecast_via_values(date:str,sales:int):
data = pd.DataFrame({'ds':[date],'y':[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."
@app.post("/Suggest_Diet_Plan")
def Suggest_Diet_Plan(
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,
loaded_model=Depends(get_DecisionTree_model)
):
patient_data = {
'Age': Age,
'Gender': Gender,
'BMI': BMI,
'Current Protein Intake (g)': Current_Protein_Intake,
'Current Sodium Intake (mg)': Current_Sodium_Intake,
'Current Potassium Intake (mg)': Current_Potassium_Intake,
'Current Phosphorus Intake (mg)': Current_Phosphorus_Intake,
'Other Conditions': Other_Conditions,
'GFR': GFR,
'Proteinuria':Proteinuria,
'Preferred Food': Preferred_Food,
}
suggesting = recommend_diet(patient_data,loaded_model)
return suggesting
class Symptoms(BaseModel):
Age: Optional[int]
Gender: str
AKIDiagnosis: str
AKISeverity: str
InitialCreatinine: float
PeakCreatinine: float
UrineOutput: int
# Swelling: str,
HasDisease: str
Underlying_Cause: str
Proteinuria: str
Edema: str
Albumin_Level: str
Cholesterol_Level: str
Infection_Count: int
Nephrotic_Syndrome: str
Change_in_Urination: bool
Swelling: bool
Fatigue_Weakness: bool
Skin_Rash_Itching: bool
Shortness_of_Breath: bool
Metallic_Taste_in_Mouth: bool
Feeling_Cold: bool
Dizziness_Trouble_Concentrating: bool
Pain_in_Back_or_Sides: bool
Nausea_Vomiting: bool
Disease: str
@app.post("/predict_diseas")
def predict_disease(
Age: int,
Gender: Optional[str] = None,
AKIDiagnosis: Optional[str] = None,
InitialCreatinine: Optional[float] = None,
PeakCreatinine: Optional[float] = None,
UrineOutput: Optional[int] = None,
Swelling: Optional[bool] = None,
Proteinuria: Optional[str] = None,
Edema: Optional[str] = None,
Albumin_Level: Optional[str] = None,
Change_in_Urination: Optional[bool] = None,
Metallic_Taste_in_Mouth: Optional[bool] = None,
Dizziness_Trouble_Concentrating: Optional[bool] = None,
Pain_in_Back_or_Sides: Optional[bool] = None,
Nausea_Vomiting: Optional[bool] = None,
Model1=Depends(AKI_model),
Model2=Depends(Nephrotic_model),
Model3=Depends(CKD_model),
):
if (
AKIDiagnosis is not None and
InitialCreatinine is not None and
PeakCreatinine is not None and
UrineOutput is not None and
Swelling is not None
):
patient_data = {
"AKIDiagnosis" :AKIDiagnosis,
"InitialCreatinine" :InitialCreatinine,
"PeakCreatinine" :PeakCreatinine,
"UrineOutput" :UrineOutput,
"Swelling" :Swelling,
}
results = Model_1(patient_data,Model1)
return results
elif (
Proteinuria is not None and
Edema is not None and
Albumin_Level is not None
):
patient_data = {
'Age':Age,
'Gender':Gender,
'Proteinuria':Proteinuria,
'Edema':Edema,
'Albumin_Level':Albumin_Level,
}
results = Model_2(patient_data,Model2)
return results
elif (
Change_in_Urination is not None or
Swelling is not None or
Metallic_Taste_in_Mouth is not None or
Dizziness_Trouble_Concentrating is not None or
Pain_in_Back_or_Sides is not None or
Nausea_Vomiting is not None
):
patient_data = {
'Change_in_Urination': Change_in_Urination,
'Metallic_Taste_in_Mouth': Metallic_Taste_in_Mouth,
'Dizziness_Trouble_Concentrating': Dizziness_Trouble_Concentrating,
'Pain_in_Back_or_Sides': Pain_in_Back_or_Sides,
'Nausea_Vomiting': Nausea_Vomiting,
}
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_2(patient_data,model):
patient_data = pd.DataFrame([patient_data])
gender_mapping = {'Female': 0, 'Male': 1}
proteinuria_mapping = {'Very High': 0, 'High': 1, 'Low': 2, 'Moderate': 3, 'Normal': 4}
edema_mapping = {'Yes': 0, 'No': 1}
albumin_mapping = {'Normal': 0, 'Low': 1, 'Very Low': 2}
patient_data['Gender'] = patient_data['Gender'].map(gender_mapping)
patient_data['Proteinuria'] = patient_data['Proteinuria'].map(proteinuria_mapping)
patient_data['Edema'] = patient_data['Edema'].map(edema_mapping)
patient_data['Albumin_Level'] = patient_data['Albumin_Level'].map(albumin_mapping)
results = model.predict(patient_data)
if results==0:
results = "Has nephrotic syndrome"
else:
results = "no nephrotic syndrome"
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")
\ No newline at end of file
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