HelpMe / app.py
ShoaibAI's picture
Upload app.py
06a3200 verified
Raw History Blame Contribute Delete
17.9 kB
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(css="""
.scrollable-checkboxgroup {
max-height: 300px;
overflow-y: auto;
border: 1px solid #e2e2e2;
padding: 10px;
border-radius: 4px;
}
.scrollable-checkboxgroup label {
display: block;
margin-bottom: 5px;
}
""") 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",
elem_classes=["scrollable-checkboxgroup"] # Add a class for styling
)
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)