File size: 17,521 Bytes
64e6f22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import pandas as pd
from collections import Counter
from itertools import chain
import gradio as gr
import os
import subprocess
import sys
import re
# Install openpyxl if not already installed
def install(package):
    subprocess.check_call([sys.executable, "-m", "pip", "install", package])

install("openpyxl")
# Load Dataset
DATA_FILE = "_Independant Medical complex (1).xlsx"  # Ensure the file path is correct
try:
    df = pd.read_excel(DATA_FILE)
except FileNotFoundError:
    print(f"Error: File not found at {DATA_FILE}")
    exit()
# Helper Functions
def get_common_symptoms(presenting_problems):
    """Retrieve causes and associated symptoms for multiple presenting problems."""
    presenting_problems = [problem.strip().lower() for problem in presenting_problems.split(",")]
    presenting_problems_lower = df['Presenting Problems'].str.lower()
    associated_symptoms_col = next((col for col in df.columns if "associated symptoms" in col.lower()), None)

    if associated_symptoms_col is None:
        raise KeyError("Column 'Associated Symptoms' (or similar) not found in the data.")

    # Ensure the associated symptoms column is treated as strings
    df[associated_symptoms_col] = df[associated_symptoms_col].fillna("").astype(str)

    # Step 1: Find causes that include all presenting problems
    all_causes = set()
    symptoms_by_cause = {}
    symptom_explanations = {}
    all_symptoms = set()

    # Function to check if a cause includes all presenting problems
    def cause_includes_all_problems(cause_data, problems):
        for problem in problems:
            if not (cause_data['Presenting Problems'].str.lower().str.contains(problem).any() or
                    cause_data[associated_symptoms_col].str.lower().str.contains(problem).any()):
                return False
        return True

    # Function to check if a cause includes at least three presenting problems
    def cause_includes_at_least_three_problems(cause_data, problems):
        count = 0
        for problem in problems:
            if (cause_data['Presenting Problems'].str.lower().str.contains(problem).any() or
                cause_data[associated_symptoms_col].str.lower().str.contains(problem).any()):
                count += 1
                if count >= 3:
                    return True
        return False

    # Step 2: First, look for causes that include all presenting problems
    causes_data_all = df[df.apply(lambda row: cause_includes_all_problems(pd.DataFrame([row]), presenting_problems), axis=1)]
    if not causes_data_all.empty:
        causes = causes_data_all['Cause'].unique()
    else:
        # Step 3: If no cause includes all, look for causes that include at least three presenting problems
        causes_data_three = df[df.apply(lambda row: cause_includes_at_least_three_problems(pd.DataFrame([row]), presenting_problems), axis=1)]
        if not causes_data_three.empty:
            causes = causes_data_three['Cause'].unique()
        else:
            # Step 4: If no cause includes at least three, treat each presenting problem separately
            causes = set()
            for problem in presenting_problems:
                if problem in presenting_problems_lower.unique().tolist():
                    causes_data = df[presenting_problems_lower == problem]
                else:
                    symptoms_mask = df[associated_symptoms_col].str.lower().str.contains(problem, na=False)
                    if not symptoms_mask.any():
                        continue  # Skip if no data is found for this problem
                    causes_data = df[symptoms_mask]
                causes.update(causes_data['Cause'].unique())

    # Step 5: Extract symptoms for the selected causes
    for cause in causes:
        symptoms = df[df['Cause'] == cause][associated_symptoms_col].dropna().astype(str).unique()
        symptom_list = []
        for symptom in symptoms:
            # Use regex to split on commas with optional spaces
            symptom_parts = re.split(r'\s*,\s*', symptom)
            for part in symptom_parts:
                if ":" in part:
                    # Use the before-colon part for the "Select common Symptoms" list
                    symptom_name = part.split(":")[0].strip()
                    symptom_explanations[symptom_name] = part  # Store full symptom with explanation
                else:
                    # Use the entire symptom if no colon is present
                    symptom_name = part.strip()
                    symptom_explanations[symptom_name] = part  # Store full symptom with explanation
                symptom_list.append(symptom_name)
                all_symptoms.add(symptom_name)  # Add to the set of unique symptoms
        symptoms_by_cause[cause] = symptom_list

    # Step 6: Convert the set of unique symptoms to a sorted list
    common_symptoms = sorted(list(all_symptoms))

    # Debugging: Print symptoms_by_cause
    print("Symptoms by Cause:", symptoms_by_cause)
    print("Symptom Explanations:", symptom_explanations)

    return list(causes), symptoms_by_cause, common_symptoms, symptom_explanations
def determine_probable_causes(user_responses, symptoms_by_cause):
    """Determine the most likely causes based on user responses."""
    cause_scores = {}
    for cause, symptoms in symptoms_by_cause.items():
        cause_scores[cause] = sum(user_responses.get(symptom, False) for symptom in symptoms)
    probable_causes = sorted(cause_scores.items(), key=lambda x: -x[1])[:3]  # Top 3 causes
    return probable_causes


# Gradio Functions
def process_presenting_problem(presenting_problem, bp, pulse, respiratory_rate, temperature):
    """Process the presenting problem and provide a list of possible causes and symptoms."""
    # Validate inputs
    if not presenting_problem:
        return "Please enter a presenting problem.", [], None, {}, {}
    if not any([bp, pulse, respiratory_rate, temperature]):
        return "Please enter at least one vital sign.", [], None, {}, {}

    causes, symptoms_by_cause, common_symptoms, symptom_explanations = get_common_symptoms(presenting_problem)
    
    if causes is None or len(causes) == 0:  # Explicitly check if causes is empty
        return "Sorry, we don't have information on this presenting problem or symptom.", [], None, {}, {}

    # Convert causes to a list to avoid ambiguity in evaluation
    causes_list = list(causes)

    # Step 1: Automatically infer symptoms from vital signs
    inferred_symptoms = {}

    # Infer fever based on temperature
    if temperature is not None:
        if 98.6 <= temperature < 100:
            inferred_symptoms["Low-grade fever"] = True
            # Remove "Fever" from common symptoms if present
            common_symptoms = [symptom for symptom in common_symptoms if "fever" not in symptom.lower()]
        elif temperature >= 100:
            inferred_symptoms["High-grade fever"] = True
            # Remove "Fever" from common symptoms if present
            common_symptoms = [symptom for symptom in common_symptoms if "fever" not in symptom.lower()]

    # Infer blood pressure symptoms
    if bp is not None:
        try:
            # Split the BP input into systolic and diastolic values
            systolic, diastolic = map(float, bp.split('/'))
            if systolic < 90 or diastolic < 60:
                inferred_symptoms["Low blood pressure"] = True
                # Remove "Hypotension" from common symptoms if present
                common_symptoms = [symptom for symptom in common_symptoms if "hypotension" not in symptom.lower()]
            elif systolic > 120 or diastolic > 80:
                inferred_symptoms["High blood pressure"] = True
                # Remove "Hypertension" from common symptoms if present
                common_symptoms = [symptom for symptom in common_symptoms if "hypertension" not in symptom.lower()]
        except (ValueError, AttributeError):
            # Handle invalid BP input format
            print("Invalid BP input format. Please enter BP in the format 'systolic/diastolic' (e.g., '120/80').")

    # Infer pulse symptoms
    if pulse is not None:
        if pulse < 60:
            inferred_symptoms["Bradycardia"] = True
            # Remove "Low pulse" from common symptoms if present
            common_symptoms = [symptom for symptom in common_symptoms if "low pulse" not in symptom.lower()]
        elif pulse > 100:
            inferred_symptoms["Tachycardia"] = True
            # Remove "High pulse" from common symptoms if present
            common_symptoms = [symptom for symptom in common_symptoms if "high pulse" not in symptom.lower()]

    # Infer respiratory rate symptoms
    if respiratory_rate is not None:
        if respiratory_rate < 12:
            inferred_symptoms["Bradypnea"] = True
            # Remove "Low respiratory rate" from common symptoms if present
            common_symptoms = [symptom for symptom in common_symptoms if "low respiratory rate" not in symptom.lower()]
        elif respiratory_rate > 20:
            inferred_symptoms["Tachypnea"] = True
            # Remove "High respiratory rate" from common symptoms if present
            common_symptoms = [symptom for symptom in common_symptoms if "high respiratory rate" not in symptom.lower()]

    # Step 2: Exclude inferred symptoms from the "Select Symptoms" list
    common_symptoms = [symptom for symptom in common_symptoms if symptom not in inferred_symptoms]

    return f"Possible Causes: {', '.join(causes_list)}", common_symptoms, symptoms_by_cause, inferred_symptoms, symptom_explanations


def process_symptoms(selected_symptoms, symptoms_by_cause, inferred_symptoms):
    """Process user-selected symptoms to determine probable causes."""
    # Combine user-selected symptoms and inferred symptoms
    user_responses = {symptom: True for symptom in selected_symptoms}
    user_responses.update(inferred_symptoms)

    # Determine probable causes
    cause_scores = {}
    for cause, symptoms in symptoms_by_cause.items():
        cause_scores[cause] = sum(user_responses.get(symptom, False) for symptom in symptoms)

    # Sort causes by score (descending) and get the top 3
    probable_causes = sorted(cause_scores.items(), key=lambda x: -x[1])[:3]

    # Debugging: Print probable causes
    print("Probable Causes:", probable_causes)

    if not probable_causes:
        return "No probable causes found based on your symptoms.", []

    probable_causes_list = [cause for cause, _ in probable_causes]
    return f"Probable Causes: {', '.join(probable_causes_list)}", probable_causes_list


def get_next_steps(cause):
    """Provide examinations, investigations, and management plans for a specific cause."""
    physical_exam = (
        df[df['Cause'] == cause]['Physical Examinations'].iloc[0]
        if 'Physical Examinations' in df.columns else "No data available"
    )
    investigations = (
        df[df['Cause'] == cause]['Investigations'].iloc[0]
        if 'Investigations' in df.columns else "No data available"
    )
    management = (
        df[df['Cause'] == cause]['Management Plans'].iloc[0]
        if 'Management Plans' in df.columns else "No data available"
    )

    # Split management plan into two parts
    if "Alternative medicines" in management:
        management_part1, management_part2 = management.split("Alternative medicines", 1)
    else:
        management_part1, management_part2 = management, "No alternative medicines information available."

    return f"Physical Examination: {physical_exam}", f"Investigations: {investigations}", management_part1, management_part2


# Define Gradio Interface
with gr.Blocks() as demo:
    gr.Markdown("# Healthcare Assistant")

    # Step 1: Input Presenting Problem and Vital Signs
    presenting_problem_input = gr.Textbox(label="Enter Presenting Problem")
    
    # Add new fields for B.P, Pulse, Respiratory Rate, and Temperature
    bp_input = gr.Textbox(label="B.P (mmHg)", placeholder="Enter in the format 'systolic/diastolic' (e.g., 120/80)")
    pulse_input = gr.Textbox(label="Pulse (bpm)")
    respiratory_rate_input = gr.Textbox(label="Respiratory Rate (breaths/min)")
    temperature_input = gr.Textbox(label="Temperature (°F)")

    # Outputs
    top_causes_output = gr.Textbox(label="Possible Causes", interactive=False)
    common_symptoms_output = gr.CheckboxGroup(label="Select Your Symptoms")
    symptoms_by_cause_state = gr.State()
    inferred_symptoms_state = gr.State()
    symptom_explanations_state = gr.State()

    # Step 2: Explain Symptoms
    explanation_output = gr.Textbox(label="Symptom Explanation", interactive=False)
    explanation_button = gr.Button("Explain Symptoms")

    # Step 3: Process Symptoms
    probable_causes_output = gr.Textbox(label="Probable Causes", interactive=False)
    probable_causes_list_state = gr.State()

    # Step 4: Select Cause for Next Steps
    cause_dropdown = gr.Dropdown(label="Select a Cause for Next Steps")
    physical_exam_output = gr.Textbox(label="Physical Examination", interactive=False)
    investigations_output = gr.Textbox(label="Investigations", interactive=False)
    management_output = gr.Textbox(label="Management Plan", interactive=False)

    # Step 5: Alternative Medicines
    alternative_medicines_output = gr.Textbox(
        label="Alternative Medicines", 
        interactive=False, 
        visible=False,  # Initially hidden
        lines=5  # Set the number of visible lines to 5
    )
    alternative_medicines_button = gr.Button("Alternative Medicines")

    # Button to process presenting problem
    def update_symptoms(presenting_problem, bp, pulse, respiratory_rate, temperature):
        # Handle inputs for vital signs correctly (they may be empty or invalid)
        try:
            # Convert pulse, respiratory rate, and temperature to float
            pulse = float(pulse) if pulse else None
            respiratory_rate = float(respiratory_rate) if respiratory_rate else None
            temperature = float(temperature) if temperature else None
        except ValueError:
            return "Invalid vital sign input. Please ensure that all values are numeric.", [], None, {}, {}

        causes_text, common_symptoms_list, symptoms_by_cause, inferred_symptoms, symptom_explanations = process_presenting_problem(presenting_problem, bp, pulse, respiratory_rate, temperature)
        
        # Debugging: Print outputs
        print("Causes Text:", causes_text)
        print("Common Symptoms List:", common_symptoms_list)
        print("Symptoms by Cause:", symptoms_by_cause)
        print("Inferred Symptoms:", inferred_symptoms)
        print("Symptom Explanations:", symptom_explanations)

        # Update the CheckboxGroup choices
        return causes_text, gr.update(choices=common_symptoms_list), symptoms_by_cause, inferred_symptoms, symptom_explanations

    presenting_problem_input.submit(
        fn=update_symptoms,
        inputs=[presenting_problem_input, bp_input, pulse_input, respiratory_rate_input, temperature_input],
        outputs=[top_causes_output, common_symptoms_output, symptoms_by_cause_state, inferred_symptoms_state, symptom_explanations_state],
    )

    # Button to explain symptoms
    def explain_symptoms(selected_symptoms, symptom_explanations):
        explanations = []
        for symptom in selected_symptoms:
            if symptom in symptom_explanations:
                explanations.append(symptom_explanations[symptom])
        return "\n".join(explanations) if explanations else "No explanations available for selected symptoms."

    explanation_button.click(
        fn=explain_symptoms,
        inputs=[common_symptoms_output, symptom_explanations_state],
        outputs=[explanation_output],
    )

    # Button to process symptoms
    def update_probable_causes(selected_symptoms, symptoms_by_cause, inferred_symptoms):
        probable_causes_text, probable_causes_list = process_symptoms(selected_symptoms, symptoms_by_cause, inferred_symptoms)
        return probable_causes_text, probable_causes_list

    common_symptoms_output.change(
        fn=update_probable_causes,
        inputs=[common_symptoms_output, symptoms_by_cause_state, inferred_symptoms_state],
        outputs=[probable_causes_output, probable_causes_list_state],
    )

    # Button to get next steps
    def update_next_steps(cause):
        physical_exam, investigations, management_part1, management_part2 = get_next_steps(cause)
        return physical_exam, investigations, management_part1, management_part2

    cause_dropdown.change(
        fn=update_next_steps,
        inputs=[cause_dropdown],
        outputs=[physical_exam_output, investigations_output, management_output, alternative_medicines_output],
    )

    # Button to show alternative medicines
    def show_alternative_medicines(alternative_medicines):
        return gr.update(value=alternative_medicines, visible=True)  # Show the textbox and populate it

    alternative_medicines_button.click(
        fn=show_alternative_medicines,
        inputs=[alternative_medicines_output],
        outputs=[alternative_medicines_output],
    )

    # Sync dropdown with probable causes
    def sync_dropdown(probable_causes_list):
        return gr.update(choices=probable_causes_list)

    probable_causes_list_state.change(
        fn=sync_dropdown,
        inputs=[probable_causes_list_state],
        outputs=[cause_dropdown],
    )
#Run the Gradio Interface with a public link
demo.launch(share=True)