KAITANY commited on
Commit
a18143a
·
1 Parent(s): 6351c61

add app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -0
app.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ import uvicorn
3
+ #from typing import List, Literal
4
+ from pydantic import BaseModel, Field
5
+ import pandas as pd
6
+ import pickle, os
7
+
8
+ #setup
9
+ # Get the directory of the current file (FastAPI application file)
10
+ DIRPATH = os.path.dirname(os.path.realpath(__file__))
11
+
12
+ # Construct the path to ml.pkl relative to the current file using forward slashes
13
+ ml_core_fp = os.path.join(DIRPATH, "../model/ml.pkl")
14
+
15
+
16
+ #useful functions
17
+ def load_ml_components(fp):
18
+ "load the ml components to re-use in app"
19
+ with open(fp, 'rb') as file:
20
+ obj = pickle.load(file)
21
+ return obj
22
+
23
+
24
+ # Loading: Execute and instantiate ml components
25
+ ml_components_dict = load_ml_components(fp = ml_core_fp)
26
+
27
+ pipeline = ml_components_dict["pipeline"]
28
+
29
+ encoder = ml_components_dict["encoder"]
30
+
31
+
32
+ # API
33
+ app = FastAPI(
34
+ title= "Sepsis classification API"
35
+ )
36
+
37
+ # Input for Modelling
38
+ class Sepsis_Pred(BaseModel):
39
+
40
+ PRG: int = Field(..., description='Plasma glucose')
41
+ PL: int = Field(..., description='Blood Work Result-1 (mu U/ml)')
42
+ PR: int = Field(..., description='Blood Pressure (mm Hg)')
43
+ SK: int = Field(..., description='Blood Work Result-2 (mm)')
44
+ TS: int = Field(..., description='Blood Work Result-3 (mu U/ml)')
45
+ M11: float = Field(..., description='Body mass index (weight in kg/(height in m)^2)')
46
+ BD2: float = Field(..., description='Blood Work Result-4 (mu U/ml)')
47
+ Age: int = Field(..., description='Patient age (years)')
48
+ Insurance: int = Field(..., description='If a patient holds a valid insurance card')
49
+
50
+
51
+ @app.get("/")
52
+ def root():
53
+ return {
54
+ "Info": "Sepsis classification API : This API classifies whether a patient will develop sepsis based on various test results"
55
+ }
56
+
57
+
58
+ @app.post("/classify_patient")
59
+ def sepsis_classification(sepsis_pred: Sepsis_Pred):
60
+
61
+ try:
62
+
63
+ #Dataframe creation
64
+ df = pd.DataFrame([sepsis_pred.model_dump()])
65
+
66
+ print(f'df: {df}')
67
+
68
+ # ML prediction
69
+ prediction = pipeline.predict(df)
70
+
71
+ # Get the index of the predicted class (0 or 1 in binary classification)
72
+ predicted_class_index = prediction[0]
73
+
74
+ confidence_score = pipeline.predict_proba(df)
75
+
76
+ # Retrieve the confidence score for the predicted class
77
+
78
+ confidence_score_predicted_class = confidence_score[0][predicted_class_index]
79
+
80
+
81
+ print(f"confidence_score: {confidence_score}")
82
+
83
+ execution_message = "Execution successful"
84
+
85
+
86
+ # encoded prediction
87
+ decoded_prediction = encoder.inverse_transform([prediction])[0]
88
+
89
+
90
+ return {"execution message": execution_message, "patient_diagnosis": decoded_prediction, "confidence_score": confidence_score_predicted_class}
91
+
92
+
93
+ except Exception as e:
94
+ raise HTTPException(status_code=500, detail=f"An error occurred during prediction {str(e)}")
95
+
96
+ if __name__ == "__main__":
97
+ uvicorn.run("main:app", reload=True)