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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import time
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
import spacy
|
| 5 |
+
|
| 6 |
+
# Load the symptom-to-disease mapping
|
| 7 |
+
symptom_data = {
|
| 8 |
+
"Shortness of breath": {
|
| 9 |
+
"questions": [
|
| 10 |
+
"Do you also have chest pain?",
|
| 11 |
+
"Do you feel fatigued often?",
|
| 12 |
+
"Have you noticed swelling in your legs?"
|
| 13 |
+
],
|
| 14 |
+
"diseases": ["Atelectasis", "Emphysema", "Edema"],
|
| 15 |
+
"weights_yes": [30, 30, 40],
|
| 16 |
+
"weights_no": [10, 20, 30]
|
| 17 |
+
},
|
| 18 |
+
"Persistent cough": {
|
| 19 |
+
"questions": [
|
| 20 |
+
"Is your cough dry or with mucus?",
|
| 21 |
+
"Do you experience fever?",
|
| 22 |
+
"Do you have difficulty breathing?"
|
| 23 |
+
],
|
| 24 |
+
"diseases": ["Pneumonia", "Fibrosis", "Infiltration"],
|
| 25 |
+
"weights_yes": [35, 30, 35],
|
| 26 |
+
"weights_no": [10, 15, 20]
|
| 27 |
+
},
|
| 28 |
+
"Sharp chest pain": {
|
| 29 |
+
"questions": [
|
| 30 |
+
"Does it worsen with deep breaths?",
|
| 31 |
+
"Do you feel lightheaded?",
|
| 32 |
+
"Have you had recent trauma or surgery?"
|
| 33 |
+
],
|
| 34 |
+
"diseases": ["Pneumothorax", "Effusion", "Cardiomegaly"],
|
| 35 |
+
"weights_yes": [40, 30, 30],
|
| 36 |
+
"weights_no": [15, 20, 25]
|
| 37 |
+
},
|
| 38 |
+
"Fatigue & swelling": {
|
| 39 |
+
"questions": [
|
| 40 |
+
"Do you feel breathless when lying down?",
|
| 41 |
+
"Have you gained weight suddenly?",
|
| 42 |
+
"Do you experience irregular heartbeat?"
|
| 43 |
+
],
|
| 44 |
+
"diseases": ["Edema", "Cardiomegaly"],
|
| 45 |
+
"weights_yes": [50, 30, 20],
|
| 46 |
+
"weights_no": [20, 15, 15]
|
| 47 |
+
},
|
| 48 |
+
"Chronic wheezing": {
|
| 49 |
+
"questions": [
|
| 50 |
+
"Do you have a history of smoking?",
|
| 51 |
+
"Do you feel tightness in your chest?",
|
| 52 |
+
"Do you have frequent lung infections?"
|
| 53 |
+
],
|
| 54 |
+
"diseases": ["Emphysema", "Fibrosis"],
|
| 55 |
+
"weights_yes": [40, 30, 30],
|
| 56 |
+
"weights_no": [15, 25, 20]
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
# Load spaCy model for NLP
|
| 61 |
+
nlp = spacy.load("en_core_web_lg")
|
| 62 |
+
|
| 63 |
+
# Function to extract key symptom from user input
|
| 64 |
+
def extract_symptom(user_input):
|
| 65 |
+
# Define the symptoms that the chatbot recognizes
|
| 66 |
+
known_symptoms = list(symptom_data.keys())
|
| 67 |
+
|
| 68 |
+
# Process the input with spaCy NLP model
|
| 69 |
+
user_doc = nlp(user_input.lower())
|
| 70 |
+
|
| 71 |
+
# Check if any of the known symptoms are in the user input
|
| 72 |
+
for symptom in known_symptoms:
|
| 73 |
+
if symptom.lower() in user_input.lower():
|
| 74 |
+
return symptom
|
| 75 |
+
|
| 76 |
+
# If no direct match, use similarity to find the closest symptom
|
| 77 |
+
similarities = {}
|
| 78 |
+
for symptom in known_symptoms:
|
| 79 |
+
symptom_doc = nlp(symptom.lower())
|
| 80 |
+
similarity = user_doc.similarity(symptom_doc)
|
| 81 |
+
similarities[symptom] = similarity
|
| 82 |
+
|
| 83 |
+
# Return the symptom with the highest similarity
|
| 84 |
+
return max(similarities, key=similarities.get)
|
| 85 |
+
|
| 86 |
+
# Mapping of unrecognized symptoms to similar known ones
|
| 87 |
+
synonym_mapping = {
|
| 88 |
+
"chest pain": "Sharp chest pain",
|
| 89 |
+
"pain in chest": "Sharp chest pain",
|
| 90 |
+
"wheezing": "Chronic wheezing",
|
| 91 |
+
"cough": "Persistent cough",
|
| 92 |
+
"shortness of breath": "Shortness of breath",
|
| 93 |
+
"fatigue": "Fatigue & swelling"
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
# Global variables to track user state
|
| 97 |
+
user_state = {}
|
| 98 |
+
|
| 99 |
+
def chatbot(user_input):
|
| 100 |
+
if "state" not in user_state:
|
| 101 |
+
user_state["state"] = "greet"
|
| 102 |
+
|
| 103 |
+
if user_state["state"] == "greet":
|
| 104 |
+
user_state["state"] = "ask_symptom"
|
| 105 |
+
return "Hello! I'm a medical AI assistant. Please describe your primary symptom."
|
| 106 |
+
|
| 107 |
+
elif user_state["state"] == "ask_symptom":
|
| 108 |
+
# Check if the symptom contains any synonym or keyword
|
| 109 |
+
matched_symptom = None
|
| 110 |
+
|
| 111 |
+
for synonym, recognized_symptom in synonym_mapping.items():
|
| 112 |
+
if synonym in user_input.lower():
|
| 113 |
+
matched_symptom = recognized_symptom
|
| 114 |
+
break
|
| 115 |
+
|
| 116 |
+
# If no synonym found, extract the symptom using NLP
|
| 117 |
+
if not matched_symptom:
|
| 118 |
+
matched_symptom = extract_symptom(user_input)
|
| 119 |
+
|
| 120 |
+
# If the symptom is recognized, proceed to the next step
|
| 121 |
+
if matched_symptom not in symptom_data:
|
| 122 |
+
user_state["state"] = "ask_feeling"
|
| 123 |
+
return "I'm sorry, I don't recognize that symptom. How do you feel?"
|
| 124 |
+
|
| 125 |
+
user_state["symptom"] = matched_symptom
|
| 126 |
+
user_state["state"] = "ask_duration"
|
| 127 |
+
return "How long have you been experiencing this symptom? (Less than a week / More than a week)"
|
| 128 |
+
|
| 129 |
+
elif user_state["state"] == "ask_feeling":
|
| 130 |
+
# If the symptom is not recognized, ask how they feel
|
| 131 |
+
return "Can you describe your symptoms in more detail?"
|
| 132 |
+
|
| 133 |
+
elif user_state["state"] == "ask_duration":
|
| 134 |
+
if user_input.lower() == "less than a week":
|
| 135 |
+
user_state.clear()
|
| 136 |
+
return "It might be a temporary issue. Please monitor your symptoms and consult a doctor if they persist."
|
| 137 |
+
elif user_input.lower() == "more than a week":
|
| 138 |
+
user_state["state"] = "follow_up"
|
| 139 |
+
user_state["current_question"] = 0
|
| 140 |
+
user_state["disease_scores"] = defaultdict(int)
|
| 141 |
+
return symptom_data[user_state["symptom"]]["questions"][0]
|
| 142 |
+
else:
|
| 143 |
+
return "Please respond with 'Less than a week' or 'More than a week'."
|
| 144 |
+
|
| 145 |
+
elif user_state["state"] == "follow_up":
|
| 146 |
+
symptom = user_state["symptom"]
|
| 147 |
+
question_index = user_state["current_question"]
|
| 148 |
+
|
| 149 |
+
# Update probabilities
|
| 150 |
+
if user_input.lower() == "yes":
|
| 151 |
+
for i, disease in enumerate(symptom_data[symptom]["diseases"]):
|
| 152 |
+
user_state["disease_scores"][disease] += symptom_data[symptom]["weights_yes"][i]
|
| 153 |
+
else:
|
| 154 |
+
for i, disease in enumerate(symptom_data[symptom]["diseases"]):
|
| 155 |
+
user_state["disease_scores"][disease] += symptom_data[symptom]["weights_no"][i]
|
| 156 |
+
|
| 157 |
+
# Move to the next question or finish
|
| 158 |
+
user_state["current_question"] += 1
|
| 159 |
+
if user_state["current_question"] < len(symptom_data[symptom]["questions"]):
|
| 160 |
+
return symptom_data[symptom]["questions"][user_state["current_question"]]
|
| 161 |
+
|
| 162 |
+
# Final diagnosis
|
| 163 |
+
probable_disease = max(user_state["disease_scores"], key=user_state["disease_scores"].get)
|
| 164 |
+
user_state.clear()
|
| 165 |
+
return f"Based on your symptoms, the most likely condition is: {probable_disease}. Please consult a doctor for confirmation."
|
| 166 |
+
|
| 167 |
+
# Gradio Chatbot UI with improved features
|
| 168 |
+
with gr.Blocks() as demo:
|
| 169 |
+
gr.Markdown("# Conversational Image Recognition Assistant: AI-Powered X-ray Diagnosis for Healthcare")
|
| 170 |
+
chatbot_ui = gr.Chatbot()
|
| 171 |
+
user_input = gr.Textbox(placeholder="Enter your response...", label="Your Message")
|
| 172 |
+
submit = gr.Button("Send")
|
| 173 |
+
clear_chat = gr.Button("Clear Chat")
|
| 174 |
+
|
| 175 |
+
def respond(user_message, history):
|
| 176 |
+
history.append((user_message, "Thinking...")) # Show thinking message
|
| 177 |
+
yield history, "" # Immediate update
|
| 178 |
+
|
| 179 |
+
time.sleep(1.5) # Simulate processing delay
|
| 180 |
+
bot_response = chatbot(user_message)
|
| 181 |
+
history[-1] = (user_message, bot_response) # Update with real response
|
| 182 |
+
yield history, ""
|
| 183 |
+
|
| 184 |
+
submit.click(respond, [user_input, chatbot_ui], [chatbot_ui, user_input])
|
| 185 |
+
user_input.submit(respond, [user_input, chatbot_ui], [chatbot_ui, user_input])
|
| 186 |
+
clear_chat.click(lambda: ([], ""), outputs=[chatbot_ui, user_input])
|
| 187 |
+
|
| 188 |
+
demo.launch()
|