ShoaibAI commited on
Commit
62c2f3b
·
verified ·
1 Parent(s): 1354a06

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -386
app.py DELETED
@@ -1,386 +0,0 @@
1
- import pandas as pd
2
- from collections import Counter
3
- from itertools import chain
4
- import gradio as gr
5
- import os
6
- import subprocess
7
- import sys
8
- import re
9
-
10
- # Install openpyxl if not already installed
11
- def install(package):
12
- subprocess.check_call([sys.executable, "-m", "pip", "install", package])
13
-
14
- install("openpyxl")
15
-
16
- # Load Dataset
17
- DATA_FILE = "_Independant Medical complex (1).xlsx" # Ensure the file path is correct
18
- try:
19
- df = pd.read_excel(DATA_FILE)
20
- except FileNotFoundError:
21
- print(f"Error: File not found at {DATA_FILE}")
22
- exit()
23
-
24
- # Helper Functions
25
- def get_common_symptoms(presenting_problems):
26
- """Retrieve causes and associated symptoms for multiple presenting problems."""
27
- presenting_problems = [problem.strip().lower() for problem in presenting_problems.split(",")]
28
- presenting_problems_lower = df['Presenting Problems'].str.lower()
29
- associated_symptoms_col = next((col for col in df.columns if "associated symptoms" in col.lower()), None)
30
-
31
- if associated_symptoms_col is None:
32
- raise KeyError("Column 'Associated Symptoms' (or similar) not found in the data.")
33
-
34
- # Ensure the associated symptoms column is treated as strings
35
- df[associated_symptoms_col] = df[associated_symptoms_col].fillna("").astype(str)
36
-
37
- # Step 1: Find causes that include all presenting problems
38
- all_causes = set()
39
- symptoms_by_cause = {}
40
- symptom_explanations = {}
41
- all_symptoms = set()
42
-
43
- # Function to check if a cause includes all presenting problems
44
- def cause_includes_all_problems(cause_data, problems):
45
- for problem in problems:
46
- if not (cause_data['Presenting Problems'].str.lower().str.contains(problem).any() or
47
- cause_data[associated_symptoms_col].str.lower().str.contains(problem).any()):
48
- return False
49
- return True
50
-
51
- # Function to check if a cause includes at least three presenting problems
52
- def cause_includes_at_least_three_problems(cause_data, problems):
53
- count = 0
54
- for problem in problems:
55
- if (cause_data['Presenting Problems'].str.lower().str.contains(problem).any() or
56
- cause_data[associated_symptoms_col].str.lower().str.contains(problem).any()):
57
- count += 1
58
- if count >= 3:
59
- return True
60
- return False
61
-
62
- # Step 2: First, look for causes that include all presenting problems
63
- causes_data_all = df[df.apply(lambda row: cause_includes_all_problems(pd.DataFrame([row]), presenting_problems), axis=1)]
64
- if not causes_data_all.empty:
65
- causes = causes_data_all['Cause'].unique()
66
- else:
67
- # Step 3: If no cause includes all, look for causes that include at least three presenting problems
68
- causes_data_three = df[df.apply(lambda row: cause_includes_at_least_three_problems(pd.DataFrame([row]), presenting_problems), axis=1)]
69
- if not causes_data_three.empty:
70
- causes = causes_data_three['Cause'].unique()
71
- else:
72
- # Step 4: If no cause includes at least three, treat each presenting problem separately
73
- causes = set()
74
- for problem in presenting_problems:
75
- if problem in presenting_problems_lower.unique().tolist():
76
- causes_data = df[presenting_problems_lower == problem]
77
- else:
78
- symptoms_mask = df[associated_symptoms_col].str.lower().str.contains(problem, na=False)
79
- if not symptoms_mask.any():
80
- continue # Skip if no data is found for this problem
81
- causes_data = df[symptoms_mask]
82
- causes.update(causes_data['Cause'].unique())
83
-
84
- # Step 5: Extract symptoms for the selected causes
85
- for cause in causes:
86
- symptoms = df[df['Cause'] == cause][associated_symptoms_col].dropna().astype(str).unique()
87
- symptom_list = []
88
- for symptom in symptoms:
89
- # Use regex to split on commas with optional spaces
90
- symptom_parts = re.split(r'\s*,\s*', symptom)
91
- for part in symptom_parts:
92
- if ":" in part:
93
- # Use the before-colon part for the "Select common Symptoms" list
94
- symptom_name = part.split(":")[0].strip()
95
- symptom_explanations[symptom_name] = part # Store full symptom with explanation
96
- else:
97
- # Use the entire symptom if no colon is present
98
- symptom_name = part.strip()
99
- symptom_explanations[symptom_name] = part # Store full symptom with explanation
100
- symptom_list.append(symptom_name)
101
- all_symptoms.add(symptom_name) # Add to the set of unique symptoms
102
- symptoms_by_cause[cause] = symptom_list
103
-
104
- # Step 6: Convert the set of unique symptoms to a sorted list
105
- common_symptoms = sorted(list(all_symptoms))
106
-
107
- # Debugging: Print symptoms_by_cause
108
- print("Symptoms by Cause:", symptoms_by_cause)
109
- print("Symptom Explanations:", symptom_explanations)
110
-
111
- return list(causes), symptoms_by_cause, common_symptoms, symptom_explanations
112
-
113
- def determine_probable_causes(user_responses, symptoms_by_cause):
114
- """Determine the most likely causes based on user responses."""
115
- cause_scores = {}
116
- for cause, symptoms in symptoms_by_cause.items():
117
- cause_scores[cause] = sum(user_responses.get(symptom, False) for symptom in symptoms)
118
- probable_causes = sorted(cause_scores.items(), key=lambda x: -x[1])[:3] # Top 3 causes
119
- return probable_causes
120
-
121
- # Gradio Functions
122
- def process_presenting_problem(presenting_problem, bp, pulse, respiratory_rate, temperature):
123
- """Process the presenting problem and provide a list of possible causes and symptoms."""
124
- # Validate inputs
125
- if not presenting_problem:
126
- return "Please enter a presenting problem.", [], None, {}, {}
127
- if not any([bp, pulse, respiratory_rate, temperature]):
128
- return "Please enter at least one vital sign.", [], None, {}, {}
129
-
130
- causes, symptoms_by_cause, common_symptoms, symptom_explanations = get_common_symptoms(presenting_problem)
131
-
132
- if causes is None or len(causes) == 0: # Explicitly check if causes is empty
133
- return "Sorry, we don't have information on this presenting problem or symptom.", [], None, {}, {}
134
-
135
- # Convert causes to a list to avoid ambiguity in evaluation
136
- causes_list = list(causes)
137
-
138
- # Step 1: Automatically infer symptoms from vital signs
139
- inferred_symptoms = {}
140
-
141
- # Infer fever based on temperature
142
- if temperature is not None:
143
- if 98.6 <= temperature < 100:
144
- inferred_symptoms["Low-grade fever"] = True
145
- # Remove "Fever" from common symptoms if present
146
- common_symptoms = [symptom for symptom in common_symptoms if "fever" not in symptom.lower()]
147
- elif temperature >= 100:
148
- inferred_symptoms["High-grade fever"] = True
149
- # Remove "Fever" from common symptoms if present
150
- common_symptoms = [symptom for symptom in common_symptoms if "fever" not in symptom.lower()]
151
-
152
- # Infer blood pressure symptoms
153
- if bp is not None:
154
- try:
155
- # Split the BP input into systolic and diastolic values
156
- systolic, diastolic = map(float, bp.split('/'))
157
- if systolic < 90 or diastolic < 60:
158
- inferred_symptoms["Low blood pressure"] = True
159
- # Remove "Hypotension" from common symptoms if present
160
- common_symptoms = [symptom for symptom in common_symptoms if "hypotension" not in symptom.lower()]
161
- elif systolic > 120 or diastolic > 80:
162
- inferred_symptoms["High blood pressure"] = True
163
- # Remove "Hypertension" from common symptoms if present
164
- common_symptoms = [symptom for symptom in common_symptoms if "hypertension" not in symptom.lower()]
165
- except (ValueError, AttributeError):
166
- # Handle invalid BP input format
167
- print("Invalid BP input format. Please enter BP in the format 'systolic/diastolic' (e.g., '120/80').")
168
-
169
- # Infer pulse symptoms
170
- if pulse is not None:
171
- if pulse < 60:
172
- inferred_symptoms["Bradycardia"] = True
173
- # Remove "Low pulse" from common symptoms if present
174
- common_symptoms = [symptom for symptom in common_symptoms if "low pulse" not in symptom.lower()]
175
- elif pulse > 100:
176
- inferred_symptoms["Tachycardia"] = True
177
- # Remove "High pulse" from common symptoms if present
178
- common_symptoms = [symptom for symptom in common_symptoms if "high pulse" not in symptom.lower()]
179
-
180
- # Infer respiratory rate symptoms
181
- if respiratory_rate is not None:
182
- if respiratory_rate < 12:
183
- inferred_symptoms["Bradypnea"] = True
184
- # Remove "Low respiratory rate" from common symptoms if present
185
- common_symptoms = [symptom for symptom in common_symptoms if "low respiratory rate" not in symptom.lower()]
186
- elif respiratory_rate > 20:
187
- inferred_symptoms["Tachypnea"] = True
188
- # Remove "High respiratory rate" from common symptoms if present
189
- common_symptoms = [symptom for symptom in common_symptoms if "high respiratory rate" not in symptom.lower()]
190
-
191
- # Step 2: Exclude inferred symptoms from the "Select Symptoms" list
192
- common_symptoms = [symptom for symptom in common_symptoms if symptom not in inferred_symptoms]
193
-
194
- return f"Possible Causes: {', '.join(causes_list)}", common_symptoms, symptoms_by_cause, inferred_symptoms, symptom_explanations
195
-
196
- def process_symptoms(selected_symptoms, symptoms_by_cause, inferred_symptoms):
197
- """Process user-selected symptoms to determine probable causes."""
198
- # Combine user-selected symptoms and inferred symptoms
199
- user_responses = {symptom: True for symptom in selected_symptoms}
200
- user_responses.update(inferred_symptoms)
201
-
202
- # Determine probable causes
203
- cause_scores = {}
204
- for cause, symptoms in symptoms_by_cause.items():
205
- cause_scores[cause] = sum(user_responses.get(symptom, False) for symptom in symptoms)
206
-
207
- # Sort causes by score (descending) and get the top 3
208
- probable_causes = sorted(cause_scores.items(), key=lambda x: -x[1])[:3]
209
-
210
- # Debugging: Print probable causes
211
- print("Probable Causes:", probable_causes)
212
-
213
- if not probable_causes:
214
- return "No probable causes found based on your symptoms.", []
215
-
216
- probable_causes_list = [cause for cause, _ in probable_causes]
217
- return f"Probable Causes: {', '.join(probable_causes_list)}", probable_causes_list
218
-
219
- def get_next_steps(cause):
220
- """Provide examinations, investigations, and management plans for a specific cause."""
221
- physical_exam = (
222
- df[df['Cause'] == cause]['Physical Examinations'].iloc[0]
223
- if 'Physical Examinations' in df.columns else "No data available"
224
- )
225
- investigations = (
226
- df[df['Cause'] == cause]['Investigations'].iloc[0]
227
- if 'Investigations' in df.columns else "No data available"
228
- )
229
- management = (
230
- df[df['Cause'] == cause]['Management Plans'].iloc[0]
231
- if 'Management Plans' in df.columns else "No data available"
232
- )
233
-
234
- # Split management plan into two parts
235
- if "Alternative medicines" in management:
236
- management_part1, management_part2 = management.split("Alternative medicines", 1)
237
- else:
238
- management_part1, management_part2 = management, "No alternative medicines information available."
239
-
240
- return f"Physical Examination: {physical_exam}", f"Investigations: {investigations}", management_part1, management_part2
241
-
242
- # Define Gradio Interface
243
- with gr.Blocks(css="""
244
- .scrollable-checkboxgroup {
245
- max-height: 300px;
246
- overflow-y: auto;
247
- border: 1px solid #e2e2e2;
248
- padding: 10px;
249
- border-radius: 4px;
250
- }
251
- .scrollable-checkboxgroup label {
252
- display: block;
253
- margin-bottom: 5px;
254
- }
255
- """) as demo:
256
- gr.Markdown("# Healthcare Assistant")
257
-
258
- # Step 1: Input Presenting Problem and Vital Signs
259
- presenting_problem_input = gr.Textbox(label="Enter Presenting Problem")
260
-
261
- # Add new fields for B.P, Pulse, Respiratory Rate, and Temperature
262
- bp_input = gr.Textbox(label="B.P (mmHg)", placeholder="Enter in the format 'systolic/diastolic' (e.g., 120/80)")
263
- pulse_input = gr.Textbox(label="Pulse (bpm)")
264
- respiratory_rate_input = gr.Textbox(label="Respiratory Rate (breaths/min)")
265
- temperature_input = gr.Textbox(label="Temperature (°F)")
266
-
267
- # Outputs
268
- top_causes_output = gr.Textbox(label="Possible Causes", interactive=False)
269
- common_symptoms_output = gr.CheckboxGroup(
270
- label="Select Your Symptoms",
271
- elem_classes=["scrollable-checkboxgroup"] # Add a class for styling
272
- )
273
- symptoms_by_cause_state = gr.State()
274
- inferred_symptoms_state = gr.State()
275
- symptom_explanations_state = gr.State()
276
-
277
- # Step 2: Explain Symptoms
278
- explanation_output = gr.Textbox(label="Symptom Explanation", interactive=False)
279
- explanation_button = gr.Button("Explain Symptoms")
280
-
281
- # Step 3: Process Symptoms
282
- probable_causes_output = gr.Textbox(label="Probable Causes", interactive=False)
283
- probable_causes_list_state = gr.State()
284
-
285
- # Step 4: Select Cause for Next Steps
286
- cause_dropdown = gr.Dropdown(label="Select a Cause for Next Steps")
287
- physical_exam_output = gr.Textbox(label="Physical Examination", interactive=False)
288
- investigations_output = gr.Textbox(label="Investigations", interactive=False)
289
- management_output = gr.Textbox(label="Management Plan", interactive=False)
290
-
291
- # Step 5: Alternative Medicines
292
- alternative_medicines_output = gr.Textbox(
293
- label="Alternative Medicines",
294
- interactive=False,
295
- visible=False, # Initially hidden
296
- lines=5 # Set the number of visible lines to 5
297
- )
298
- alternative_medicines_button = gr.Button("Alternative Medicines")
299
-
300
- # Button to process presenting problem
301
- def update_symptoms(presenting_problem, bp, pulse, respiratory_rate, temperature):
302
- # Handle inputs for vital signs correctly (they may be empty or invalid)
303
- try:
304
- # Convert pulse, respiratory rate, and temperature to float
305
- pulse = float(pulse) if pulse else None
306
- respiratory_rate = float(respiratory_rate) if respiratory_rate else None
307
- temperature = float(temperature) if temperature else None
308
- except ValueError:
309
- return "Invalid vital sign input. Please ensure that all values are numeric.", [], None, {}, {}
310
-
311
- causes_text, common_symptoms_list, symptoms_by_cause, inferred_symptoms, symptom_explanations = process_presenting_problem(presenting_problem, bp, pulse, respiratory_rate, temperature)
312
-
313
- # Debugging: Print outputs
314
- print("Causes Text:", causes_text)
315
- print("Common Symptoms List:", common_symptoms_list)
316
- print("Symptoms by Cause:", symptoms_by_cause)
317
- print("Inferred Symptoms:", inferred_symptoms)
318
- print("Symptom Explanations:", symptom_explanations)
319
-
320
- # Update the CheckboxGroup choices
321
- return causes_text, gr.update(choices=common_symptoms_list), symptoms_by_cause, inferred_symptoms, symptom_explanations
322
-
323
- presenting_problem_input.submit(
324
- fn=update_symptoms,
325
- inputs=[presenting_problem_input, bp_input, pulse_input, respiratory_rate_input, temperature_input],
326
- outputs=[top_causes_output, common_symptoms_output, symptoms_by_cause_state, inferred_symptoms_state, symptom_explanations_state],
327
- )
328
-
329
- # Button to explain symptoms
330
- def explain_symptoms(selected_symptoms, symptom_explanations):
331
- explanations = []
332
- for symptom in selected_symptoms:
333
- if symptom in symptom_explanations:
334
- explanations.append(symptom_explanations[symptom])
335
- return "\n".join(explanations) if explanations else "No explanations available for selected symptoms."
336
-
337
- explanation_button.click(
338
- fn=explain_symptoms,
339
- inputs=[common_symptoms_output, symptom_explanations_state],
340
- outputs=[explanation_output],
341
- )
342
-
343
- # Button to process symptoms
344
- def update_probable_causes(selected_symptoms, symptoms_by_cause, inferred_symptoms):
345
- probable_causes_text, probable_causes_list = process_symptoms(selected_symptoms, symptoms_by_cause, inferred_symptoms)
346
- return probable_causes_text, probable_causes_list
347
-
348
- common_symptoms_output.change(
349
- fn=update_probable_causes,
350
- inputs=[common_symptoms_output, symptoms_by_cause_state, inferred_symptoms_state],
351
- outputs=[probable_causes_output, probable_causes_list_state],
352
- )
353
-
354
- # Button to get next steps
355
- def update_next_steps(cause):
356
- physical_exam, investigations, management_part1, management_part2 = get_next_steps(cause)
357
- return physical_exam, investigations, management_part1, management_part2
358
-
359
- cause_dropdown.change(
360
- fn=update_next_steps,
361
- inputs=[cause_dropdown],
362
- outputs=[physical_exam_output, investigations_output, management_output, alternative_medicines_output],
363
- )
364
-
365
- # Button to show alternative medicines
366
- def show_alternative_medicines(alternative_medicines):
367
- return gr.update(value=alternative_medicines, visible=True) # Show the textbox and populate it
368
-
369
- alternative_medicines_button.click(
370
- fn=show_alternative_medicines,
371
- inputs=[alternative_medicines_output],
372
- outputs=[alternative_medicines_output],
373
- )
374
-
375
- # Sync dropdown with probable causes
376
- def sync_dropdown(probable_causes_list):
377
- return gr.update(choices=probable_causes_list)
378
-
379
- probable_causes_list_state.change(
380
- fn=sync_dropdown,
381
- inputs=[probable_causes_list_state],
382
- outputs=[cause_dropdown],
383
- )
384
-
385
- # Run the Gradio Interface with a public link
386
- demo.launch(share=True)