Arghya Ghosh commited on
Commit
cf90603
·
verified ·
1 Parent(s): 8c1c12a

Update api/disease.py

Browse files
Files changed (1) hide show
  1. api/disease.py +288 -280
api/disease.py CHANGED
@@ -1,280 +1,288 @@
1
- # app/api/disease.py
2
- from fastapi import APIRouter, HTTPException
3
- from pydantic import BaseModel
4
- import numpy as np
5
- import pandas as pd
6
- import pickle
7
- import ast
8
- import os
9
-
10
- router = APIRouter()
11
-
12
- BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
13
- model_path = os.path.join(BASE_DIR, "models", "svc2.pkl")
14
-
15
- # Load models and data
16
- with open(model_path, "rb") as f:
17
- svc = pickle.load(f)
18
-
19
- # Load data files
20
- DATA_DIR = os.path.join(BASE_DIR, "data")
21
-
22
- description = pd.read_csv(os.path.join(DATA_DIR, "description.csv"))
23
- precautions = pd.read_csv(os.path.join(DATA_DIR, "precautions_df.csv"))
24
- medications = pd.read_csv(os.path.join(DATA_DIR, "medications.csv"))
25
- diets = pd.read_csv(os.path.join(DATA_DIR, "diets.csv"))
26
- workout = pd.read_csv(os.path.join(DATA_DIR, "workout_df.csv"))
27
-
28
- # Load symptoms dict and disease list
29
- symptoms_dict = {
30
- "itching": 0,
31
- "skin_rash": 1,
32
- "nodal_skin_eruptions": 2,
33
- "continuous_sneezing": 3,
34
- "shivering": 4,
35
- "chills": 5,
36
- "joint_pain": 6,
37
- "stomach_pain": 7,
38
- "acidity": 8,
39
- "ulcers_on_tongue": 9,
40
- "muscle_wasting": 10,
41
- "vomiting": 11,
42
- "burning_micturition": 12,
43
- "spotting_ urination": 13,
44
- "fatigue": 14,
45
- "weight_gain": 15,
46
- "anxiety": 16,
47
- "cold_hands_and_feets": 17,
48
- "mood_swings": 18,
49
- "weight_loss": 19,
50
- "restlessness": 20,
51
- "lethargy": 21,
52
- "patches_in_throat": 22,
53
- "irregular_sugar_level": 23,
54
- "cough": 24,
55
- "high_fever": 25,
56
- "sunken_eyes": 26,
57
- "breathlessness": 27,
58
- "sweating": 28,
59
- "dehydration": 29,
60
- "indigestion": 30,
61
- "headache": 31,
62
- "yellowish_skin": 32,
63
- "dark_urine": 33,
64
- "nausea": 34,
65
- "loss_of_appetite": 35,
66
- "pain_behind_the_eyes": 36,
67
- "back_pain": 37,
68
- "constipation": 38,
69
- "abdominal_pain": 39,
70
- "diarrhoea": 40,
71
- "mild_fever": 41,
72
- "yellow_urine": 42,
73
- "yellowing_of_eyes": 43,
74
- "acute_liver_failure": 44,
75
- "fluid_overload": 45,
76
- "swelling_of_stomach": 46,
77
- "swelled_lymph_nodes": 47,
78
- "malaise": 48,
79
- "blurred_and_distorted_vision": 49,
80
- "phlegm": 50,
81
- "throat_irritation": 51,
82
- "redness_of_eyes": 52,
83
- "sinus_pressure": 53,
84
- "runny_nose": 54,
85
- "congestion": 55,
86
- "chest_pain": 56,
87
- "weakness_in_limbs": 57,
88
- "fast_heart_rate": 58,
89
- "pain_during_bowel_movements": 59,
90
- "pain_in_anal_region": 60,
91
- "bloody_stool": 61,
92
- "irritation_in_anus": 62,
93
- "neck_pain": 63,
94
- "dizziness": 64,
95
- "cramps": 65,
96
- "bruising": 66,
97
- "obesity": 67,
98
- "swollen_legs": 68,
99
- "swollen_blood_vessels": 69,
100
- "puffy_face_and_eyes": 70,
101
- "enlarged_thyroid": 71,
102
- "brittle_nails": 72,
103
- "swollen_extremeties": 73,
104
- "excessive_hunger": 74,
105
- "extra_marital_contacts": 75,
106
- "drying_and_tingling_lips": 76,
107
- "slurred_speech": 77,
108
- "knee_pain": 78,
109
- "hip_joint_pain": 79,
110
- "muscle_weakness": 80,
111
- "stiff_neck": 81,
112
- "swelling_joints": 82,
113
- "movement_stiffness": 83,
114
- "spinning_movements": 84,
115
- "loss_of_balance": 85,
116
- "unsteadiness": 86,
117
- "weakness_of_one_body_side": 87,
118
- "loss_of_smell": 88,
119
- "bladder_discomfort": 89,
120
- "foul_smell_of urine": 90,
121
- "continuous_feel_of_urine": 91,
122
- "passage_of_gases": 92,
123
- "internal_itching": 93,
124
- "toxic_look_(typhos)": 94,
125
- "depression": 95,
126
- "irritability": 96,
127
- "muscle_pain": 97,
128
- "altered_sensorium": 98,
129
- "red_spots_over_body": 99,
130
- "belly_pain": 100,
131
- "abnormal_menstruation": 101,
132
- "dischromic _patches": 102,
133
- "watering_from_eyes": 103,
134
- "increased_appetite": 104,
135
- "polyuria": 105,
136
- "family_history": 106,
137
- "mucoid_sputum": 107,
138
- "rusty_sputum": 108,
139
- "lack_of_concentration": 109,
140
- "visual_disturbances": 110,
141
- "receiving_blood_transfusion": 111,
142
- "receiving_unsterile_injections": 112,
143
- "coma": 113,
144
- "stomach_bleeding": 114,
145
- "distention_of_abdomen": 115,
146
- "history_of_alcohol_consumption": 116,
147
- "fluid_overload.1": 117,
148
- "blood_in_sputum": 118,
149
- "prominent_veins_on_calf": 119,
150
- "palpitations": 120,
151
- "painful_walking": 121,
152
- "pus_filled_pimples": 122,
153
- "blackheads": 123,
154
- "scurring": 124,
155
- "skin_peeling": 125,
156
- "silver_like_dusting": 126,
157
- "small_dents_in_nails": 127,
158
- "inflammatory_nails": 128,
159
- "blister": 129,
160
- "red_sore_around_nose": 130,
161
- "yellow_crust_ooze": 131,
162
- } # Keep your full symptoms_dict here
163
-
164
- diseases_list = {
165
- 15: "Fungal infection",
166
- 4: "Allergy",
167
- 16: "GERD",
168
- 9: "Chronic cholestasis",
169
- 14: "Drug Reaction",
170
- 33: "Peptic ulcer diseae",
171
- 1: "AIDS",
172
- 12: "Diabetes ",
173
- 17: "Gastroenteritis",
174
- 6: "Bronchial Asthma",
175
- 23: "Hypertension ",
176
- 30: "Migraine",
177
- 7: "Cervical spondylosis",
178
- 32: "Paralysis (brain hemorrhage)",
179
- 28: "Jaundice",
180
- 29: "Malaria",
181
- 8: "Chicken pox",
182
- 11: "Dengue",
183
- 37: "Typhoid",
184
- 40: "hepatitis A",
185
- 19: "Hepatitis B",
186
- 20: "Hepatitis C",
187
- 21: "Hepatitis D",
188
- 22: "Hepatitis E",
189
- 3: "Alcoholic hepatitis",
190
- 36: "Tuberculosis",
191
- 10: "Common Cold",
192
- 34: "Pneumonia",
193
- 13: "Dimorphic hemmorhoids(piles)",
194
- 18: "Heart attack",
195
- 39: "Varicose veins",
196
- 26: "Hypothyroidism",
197
- 24: "Hyperthyroidism",
198
- 25: "Hypoglycemia",
199
- 31: "Osteoarthristis",
200
- 5: "Arthritis",
201
- 0: "(vertigo) Paroymsal Positional Vertigo",
202
- 2: "Acne",
203
- 38: "Urinary tract infection",
204
- 35: "Psoriasis",
205
- 27: "Impetigo",
206
- } # Keep your full diseases_list here
207
-
208
-
209
- display_to_actual = {sym.replace("_", " "): sym for sym in symptoms_dict.keys()}
210
-
211
-
212
- class SymptomsInput(BaseModel):
213
- symptoms: list[str]
214
-
215
-
216
- def get_predicted_value(symptom_list):
217
- input_vector = np.zeros(len(symptoms_dict))
218
- for sym in symptom_list:
219
- sym_clean = display_to_actual.get(sym)
220
- if sym_clean:
221
- input_vector[symptoms_dict[sym_clean]] = 1
222
- return diseases_list[svc.predict([input_vector])[0]]
223
-
224
-
225
- def helper(disease):
226
- desc = description[description["Disease"] == disease]["Description"]
227
- desc = desc.values[0] if not desc.empty else "Description not available."
228
-
229
- pre = precautions[precautions["Disease"] == disease].iloc[:, 1:].dropna(axis=1)
230
- pre = (
231
- pre.values.flatten().tolist()
232
- if not pre.empty
233
- else ["Precautions not available."]
234
- )
235
-
236
- med = medications[medications["Disease"] == disease]["Medication"]
237
- med = (
238
- ast.literal_eval(med.values[0])
239
- if not med.empty
240
- else ["Medications not available."]
241
- )
242
-
243
- die = diets[diets["Disease"] == disease]["Diet"]
244
- die = (
245
- ast.literal_eval(die.values[0])
246
- if not die.empty
247
- else ["Diet recommendations not available."]
248
- )
249
-
250
- wrkout = workout[workout["disease"] == disease]["workout"]
251
- wrkout = (
252
- wrkout.values.flatten().tolist()
253
- if not wrkout.empty
254
- else ["Workouts not available."]
255
- )
256
-
257
- return desc, pre, med, die, wrkout
258
-
259
-
260
- @router.post(
261
- "/predict", name="rog_dristi", description="Predict disease based on symptoms"
262
- )
263
- def predict_disease(data: SymptomsInput):
264
- if not data.symptoms:
265
- raise HTTPException(status_code=400, detail="No symptoms provided.")
266
-
267
- try:
268
- predicted_disease = get_predicted_value(data.symptoms)
269
- desc, pre, med, die, wrkout = helper(predicted_disease)
270
-
271
- return {
272
- "predicted_disease": predicted_disease,
273
- "description": desc,
274
- "precautions": pre,
275
- "medications": med,
276
- "diet": die,
277
- "workouts": wrkout,
278
- }
279
- except Exception as e:
280
- raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
 
 
 
 
 
1
+ # app/api/disease.py
2
+ from fastapi import APIRouter, HTTPException
3
+ from pydantic import BaseModel
4
+ import numpy as np
5
+ import pandas as pd
6
+ import pickle
7
+ import ast
8
+ import os
9
+ from huggingface_hub import hf_hub_download
10
+
11
+ router = APIRouter()
12
+
13
+ # HF Repo
14
+ REPO_ID = "uiuxarghya/test-store"
15
+ REPO_TYPE = "dataset"
16
+
17
+ # Download files from Hugging Face
18
+ svc_path = hf_hub_download(repo_id=REPO_ID, filename="models/svc2.pkl", repo_type=REPO_TYPE)
19
+ description_path = hf_hub_download(repo_id=REPO_ID, filename="data/description.csv", repo_type=REPO_TYPE)
20
+ precautions_path = hf_hub_download(repo_id=REPO_ID, filename="data/precautions_df.csv", repo_type=REPO_TYPE)
21
+ medications_path = hf_hub_download(repo_id=REPO_ID, filename="data/medications.csv", repo_type=REPO_TYPE)
22
+ diets_path = hf_hub_download(repo_id=REPO_ID, filename="data/diets.csv", repo_type=REPO_TYPE)
23
+ workout_path = hf_hub_download(repo_id=REPO_ID, filename="data/workout_df.csv", repo_type=REPO_TYPE)
24
+
25
+ # Load model
26
+ with open(svc_path, "rb") as f:
27
+ svc = pickle.load(f)
28
+
29
+ # Load dataframes
30
+ description = pd.read_csv(description_path)
31
+ precautions = pd.read_csv(precautions_path)
32
+ medications = pd.read_csv(medications_path)
33
+ diets = pd.read_csv(diets_path)
34
+ workout = pd.read_csv(workout_path)
35
+
36
+ # Load symptoms dict and disease list
37
+ symptoms_dict = {
38
+ "itching": 0,
39
+ "skin_rash": 1,
40
+ "nodal_skin_eruptions": 2,
41
+ "continuous_sneezing": 3,
42
+ "shivering": 4,
43
+ "chills": 5,
44
+ "joint_pain": 6,
45
+ "stomach_pain": 7,
46
+ "acidity": 8,
47
+ "ulcers_on_tongue": 9,
48
+ "muscle_wasting": 10,
49
+ "vomiting": 11,
50
+ "burning_micturition": 12,
51
+ "spotting_ urination": 13,
52
+ "fatigue": 14,
53
+ "weight_gain": 15,
54
+ "anxiety": 16,
55
+ "cold_hands_and_feets": 17,
56
+ "mood_swings": 18,
57
+ "weight_loss": 19,
58
+ "restlessness": 20,
59
+ "lethargy": 21,
60
+ "patches_in_throat": 22,
61
+ "irregular_sugar_level": 23,
62
+ "cough": 24,
63
+ "high_fever": 25,
64
+ "sunken_eyes": 26,
65
+ "breathlessness": 27,
66
+ "sweating": 28,
67
+ "dehydration": 29,
68
+ "indigestion": 30,
69
+ "headache": 31,
70
+ "yellowish_skin": 32,
71
+ "dark_urine": 33,
72
+ "nausea": 34,
73
+ "loss_of_appetite": 35,
74
+ "pain_behind_the_eyes": 36,
75
+ "back_pain": 37,
76
+ "constipation": 38,
77
+ "abdominal_pain": 39,
78
+ "diarrhoea": 40,
79
+ "mild_fever": 41,
80
+ "yellow_urine": 42,
81
+ "yellowing_of_eyes": 43,
82
+ "acute_liver_failure": 44,
83
+ "fluid_overload": 45,
84
+ "swelling_of_stomach": 46,
85
+ "swelled_lymph_nodes": 47,
86
+ "malaise": 48,
87
+ "blurred_and_distorted_vision": 49,
88
+ "phlegm": 50,
89
+ "throat_irritation": 51,
90
+ "redness_of_eyes": 52,
91
+ "sinus_pressure": 53,
92
+ "runny_nose": 54,
93
+ "congestion": 55,
94
+ "chest_pain": 56,
95
+ "weakness_in_limbs": 57,
96
+ "fast_heart_rate": 58,
97
+ "pain_during_bowel_movements": 59,
98
+ "pain_in_anal_region": 60,
99
+ "bloody_stool": 61,
100
+ "irritation_in_anus": 62,
101
+ "neck_pain": 63,
102
+ "dizziness": 64,
103
+ "cramps": 65,
104
+ "bruising": 66,
105
+ "obesity": 67,
106
+ "swollen_legs": 68,
107
+ "swollen_blood_vessels": 69,
108
+ "puffy_face_and_eyes": 70,
109
+ "enlarged_thyroid": 71,
110
+ "brittle_nails": 72,
111
+ "swollen_extremeties": 73,
112
+ "excessive_hunger": 74,
113
+ "extra_marital_contacts": 75,
114
+ "drying_and_tingling_lips": 76,
115
+ "slurred_speech": 77,
116
+ "knee_pain": 78,
117
+ "hip_joint_pain": 79,
118
+ "muscle_weakness": 80,
119
+ "stiff_neck": 81,
120
+ "swelling_joints": 82,
121
+ "movement_stiffness": 83,
122
+ "spinning_movements": 84,
123
+ "loss_of_balance": 85,
124
+ "unsteadiness": 86,
125
+ "weakness_of_one_body_side": 87,
126
+ "loss_of_smell": 88,
127
+ "bladder_discomfort": 89,
128
+ "foul_smell_of urine": 90,
129
+ "continuous_feel_of_urine": 91,
130
+ "passage_of_gases": 92,
131
+ "internal_itching": 93,
132
+ "toxic_look_(typhos)": 94,
133
+ "depression": 95,
134
+ "irritability": 96,
135
+ "muscle_pain": 97,
136
+ "altered_sensorium": 98,
137
+ "red_spots_over_body": 99,
138
+ "belly_pain": 100,
139
+ "abnormal_menstruation": 101,
140
+ "dischromic _patches": 102,
141
+ "watering_from_eyes": 103,
142
+ "increased_appetite": 104,
143
+ "polyuria": 105,
144
+ "family_history": 106,
145
+ "mucoid_sputum": 107,
146
+ "rusty_sputum": 108,
147
+ "lack_of_concentration": 109,
148
+ "visual_disturbances": 110,
149
+ "receiving_blood_transfusion": 111,
150
+ "receiving_unsterile_injections": 112,
151
+ "coma": 113,
152
+ "stomach_bleeding": 114,
153
+ "distention_of_abdomen": 115,
154
+ "history_of_alcohol_consumption": 116,
155
+ "fluid_overload.1": 117,
156
+ "blood_in_sputum": 118,
157
+ "prominent_veins_on_calf": 119,
158
+ "palpitations": 120,
159
+ "painful_walking": 121,
160
+ "pus_filled_pimples": 122,
161
+ "blackheads": 123,
162
+ "scurring": 124,
163
+ "skin_peeling": 125,
164
+ "silver_like_dusting": 126,
165
+ "small_dents_in_nails": 127,
166
+ "inflammatory_nails": 128,
167
+ "blister": 129,
168
+ "red_sore_around_nose": 130,
169
+ "yellow_crust_ooze": 131,
170
+ } # Keep your full symptoms_dict here
171
+
172
+ diseases_list = {
173
+ 15: "Fungal infection",
174
+ 4: "Allergy",
175
+ 16: "GERD",
176
+ 9: "Chronic cholestasis",
177
+ 14: "Drug Reaction",
178
+ 33: "Peptic ulcer diseae",
179
+ 1: "AIDS",
180
+ 12: "Diabetes ",
181
+ 17: "Gastroenteritis",
182
+ 6: "Bronchial Asthma",
183
+ 23: "Hypertension ",
184
+ 30: "Migraine",
185
+ 7: "Cervical spondylosis",
186
+ 32: "Paralysis (brain hemorrhage)",
187
+ 28: "Jaundice",
188
+ 29: "Malaria",
189
+ 8: "Chicken pox",
190
+ 11: "Dengue",
191
+ 37: "Typhoid",
192
+ 40: "hepatitis A",
193
+ 19: "Hepatitis B",
194
+ 20: "Hepatitis C",
195
+ 21: "Hepatitis D",
196
+ 22: "Hepatitis E",
197
+ 3: "Alcoholic hepatitis",
198
+ 36: "Tuberculosis",
199
+ 10: "Common Cold",
200
+ 34: "Pneumonia",
201
+ 13: "Dimorphic hemmorhoids(piles)",
202
+ 18: "Heart attack",
203
+ 39: "Varicose veins",
204
+ 26: "Hypothyroidism",
205
+ 24: "Hyperthyroidism",
206
+ 25: "Hypoglycemia",
207
+ 31: "Osteoarthristis",
208
+ 5: "Arthritis",
209
+ 0: "(vertigo) Paroymsal Positional Vertigo",
210
+ 2: "Acne",
211
+ 38: "Urinary tract infection",
212
+ 35: "Psoriasis",
213
+ 27: "Impetigo",
214
+ } # Keep your full diseases_list here
215
+
216
+
217
+ display_to_actual = {sym.replace("_", " "): sym for sym in symptoms_dict.keys()}
218
+
219
+
220
+ class SymptomsInput(BaseModel):
221
+ symptoms: list[str]
222
+
223
+
224
+ def get_predicted_value(symptom_list):
225
+ input_vector = np.zeros(len(symptoms_dict))
226
+ for sym in symptom_list:
227
+ sym_clean = display_to_actual.get(sym)
228
+ if sym_clean:
229
+ input_vector[symptoms_dict[sym_clean]] = 1
230
+ return diseases_list[svc.predict([input_vector])[0]]
231
+
232
+
233
+ def helper(disease):
234
+ desc = description[description["Disease"] == disease]["Description"]
235
+ desc = desc.values[0] if not desc.empty else "Description not available."
236
+
237
+ pre = precautions[precautions["Disease"] == disease].iloc[:, 1:].dropna(axis=1)
238
+ pre = (
239
+ pre.values.flatten().tolist()
240
+ if not pre.empty
241
+ else ["Precautions not available."]
242
+ )
243
+
244
+ med = medications[medications["Disease"] == disease]["Medication"]
245
+ med = (
246
+ ast.literal_eval(med.values[0])
247
+ if not med.empty
248
+ else ["Medications not available."]
249
+ )
250
+
251
+ die = diets[diets["Disease"] == disease]["Diet"]
252
+ die = (
253
+ ast.literal_eval(die.values[0])
254
+ if not die.empty
255
+ else ["Diet recommendations not available."]
256
+ )
257
+
258
+ wrkout = workout[workout["disease"] == disease]["workout"]
259
+ wrkout = (
260
+ wrkout.values.flatten().tolist()
261
+ if not wrkout.empty
262
+ else ["Workouts not available."]
263
+ )
264
+
265
+ return desc, pre, med, die, wrkout
266
+
267
+
268
+ @router.post(
269
+ "/predict", name="rog_dristi", description="Predict disease based on symptoms"
270
+ )
271
+ def predict_disease(data: SymptomsInput):
272
+ if not data.symptoms:
273
+ raise HTTPException(status_code=400, detail="No symptoms provided.")
274
+
275
+ try:
276
+ predicted_disease = get_predicted_value(data.symptoms)
277
+ desc, pre, med, die, wrkout = helper(predicted_disease)
278
+
279
+ return {
280
+ "predicted_disease": predicted_disease,
281
+ "description": desc,
282
+ "precautions": pre,
283
+ "medications": med,
284
+ "diet": die,
285
+ "workouts": wrkout,
286
+ }
287
+ except Exception as e:
288
+ raise HTTPException(status_code=500, detail=str(e))