-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
197 lines (129 loc) · 5.65 KB
/
Copy pathmain.py
File metadata and controls
197 lines (129 loc) · 5.65 KB
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
from app import UserInput
import pandas as pd
from fastapi import FastAPI, Path, HTTPException, Query
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field, computed_field
from typing import Annotated, Literal, Optional
import json
import pickle
app = FastAPI()
with open('model.pkl', 'rb') as f:
model = pickle.load(f)
class Patient(BaseModel):
id: Annotated[str, Field(..., description='ID of the patient', examples=['P001'])]
name: Annotated[str, Field(..., description='Name of the patient')]
city: Annotated[str, Field(..., description='City where the patient is living')]
age: Annotated[int, Field(..., gt=0, lt=120, description='Age of the patient')]
gender: Annotated[Literal['male', 'female', 'others'], Field(..., description='Gender of the patient')]
height: Annotated[float, Field(..., gt=0, description='Height of the patient in mtrs')]
weight: Annotated[float, Field(..., gt=0, description='Weight of the patient in kgs')]
@computed_field
@property
def bmi(self) -> float:
bmi = round(self.weight/(self.height**2),2)
return bmi
@computed_field
@property
def verdict(self) -> str:
if self.bmi < 18.5:
return 'Underweight'
elif self.bmi < 25:
return 'Normal'
elif self.bmi < 30:
return 'Normal'
else:
return 'Obese'
class PatientUpdate(BaseModel):
name: Annotated[Optional[str], Field(default=None)]
city: Annotated[Optional[str], Field(default=None)]
age: Annotated[Optional[int], Field(default=None, gt=0)]
gender: Annotated[Optional[Literal['male', 'female']], Field(default=None)]
height: Annotated[Optional[float], Field(default=None, gt=0)]
weight: Annotated[Optional[float], Field(default=None, gt=0)]
def load_data():
with open('patients.json', 'r') as f:
data = json.load(f)
return data
def save_data(data):
with open('patients.json', 'w') as f:
json.dump(data, f)
@app.get("/")
def hello():
return {'message':'Patient Management System API'}
@app.get('/about')
def about():
return {'message': 'A fully functional API to manage your patient records'}
@app.get('/view')
def view():
data = load_data()
return data
@app.get('/patient/{patient_id}')
def view_patient(patient_id: str = Path(..., description='ID of the patient in the DB', example='P001')):
# load all the patients
data = load_data()
if patient_id in data:
return data[patient_id]
raise HTTPException(status_code=404, detail='Patient not found')
@app.get('/sort')
def sort_patients(sort_by: str = Query(..., description='Sort on the basis of height, weight or bmi'), order: str = Query('asc', description='sort in asc or desc order')):
valid_fields = ['height', 'weight', 'bmi']
if sort_by not in valid_fields:
raise HTTPException(status_code=400, detail=f'Invalid field select from {valid_fields}')
if order not in ['asc', 'desc']:
raise HTTPException(status_code=400, detail='Invalid order select between asc and desc')
data = load_data()
sort_order = True if order=='desc' else False
sorted_data = sorted(data.values(), key=lambda x: x.get(sort_by, 0), reverse=sort_order)
return sorted_data
@app.post('/create')
def create_patient(patient: Patient):
# load existing data
data = load_data()
# check if the patient already exists
if patient.id in data:
raise HTTPException(status_code=400, detail='Patient already exists')
# new patient add to the database
data[patient.id] = patient.model_dump(exclude=['id'])
# save into the json file
save_data(data)
return JSONResponse(status_code=201, content={'message':'patient created successfully'})
@app.put('/edit/{patient_id}')
def update_patient(patient_id: str, patient_update: PatientUpdate):
data = load_data()
if patient_id not in data:
raise HTTPException(status_code=404, detail='Patient not found')
existing_patient_info = data[patient_id]
updated_patient_info = patient_update.model_dump(exclude_unset=True)
for key, value in updated_patient_info.items():
existing_patient_info[key] = value
#existing_patient_info -> pydantic object -> updated bmi + verdict
existing_patient_info['id'] = patient_id
patient_pydandic_obj = Patient(**existing_patient_info)
#-> pydantic object -> dict
existing_patient_info = patient_pydandic_obj.model_dump(exclude='id')
# add this dict to data
data[patient_id] = existing_patient_info
# save data
save_data(data)
return JSONResponse(status_code=200, content={'message':'patient updated'})
@app.delete('/delete/{patient_id}')
def delete_patient(patient_id: str):
# load data
data = load_data()
if patient_id not in data:
raise HTTPException(status_code=404, detail='Patient not found')
del data[patient_id]
save_data(data)
return JSONResponse(status_code=200, content={'message':'patient deleted'})
@app.post('/predict')
def predict_premium(data:UserInput):
input_df = pd.DataFrame([{
'bmi': data.bmi,
'age_group': data.age_group,
'lifestyle_risk': data.lifestyle_risk,
'city_tier': data.city_tier,
'income_lpa': data.income_lpa,
'occupation': data.occupation
}])
prediction = model.predict(input_df)[0]
return JSONResponse(status_code=200, content={'predicted_category': prediction})