Pranith06 commited on
Commit
05e9d12
·
verified ·
1 Parent(s): 53e07b1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -129
app.py CHANGED
@@ -3,145 +3,105 @@ from transformers import pipeline
3
 
4
  class HealthAssistant:
5
  def __init__(self):
6
- # Initialize with smaller models for faster loading
7
- self.symptom_checker = pipeline("text-classification", model="distilbert-base-uncased")
8
- self.medical_qa = pipeline("text-generation", model="gpt2")
 
 
9
 
10
- # Knowledge base (in production, connect to a medical database)
11
- self.disease_db = {
12
- "flu": {
13
- "symptoms": ["fever", "cough", "sore throat", "muscle aches", "headache", "fatigue"],
14
- "advice": """1. Get plenty of rest
15
- 2. Stay hydrated
16
- 3. Use over-the-counter fever reducers like acetaminophen
17
- 4. See a doctor if symptoms worsen or last more than 10 days""",
18
- "precautions": [
19
- "Get annual flu vaccine",
20
- "Wash hands frequently with soap",
21
- "Avoid close contact with sick individuals",
22
- "Cover coughs and sneezes"
23
- ]
24
- },
25
- "common cold": {
26
- "symptoms": ["runny nose", "sneezing", "congestion", "sore throat", "cough", "mild headache"],
27
- "advice": """1. Rest and hydrate
28
- 2. Use saline nasal drops
29
- 3. Gargle with warm salt water for sore throat
30
- 4. Over-the-counter cold medicines may help""",
31
- "precautions": [
32
- "Wash hands often with soap and water",
33
- "Avoid touching your face with unwashed hands",
34
- "Stay away from people who are sick",
35
- "Disinfect frequently touched surfaces"
36
- ]
37
  },
38
- "migraine": {
39
- "symptoms": ["severe headache", "nausea", "sensitivity to light", "sensitivity to sound", "aura"],
40
- "advice": """1. Rest in a quiet, dark room
41
- 2. Apply cold compress to forehead
42
- 3. Take prescribed migraine medication
43
- 4. Try relaxation techniques""",
44
- "precautions": [
45
- "Identify and avoid triggers (certain foods, stress, etc.)",
46
- "Maintain regular sleep schedule",
47
- "Stay hydrated",
48
- "Consider preventive medications if frequent"
49
- ]
50
  }
51
  }
52
 
53
  def predict_disease(self, symptoms):
54
- symptoms = symptoms.lower()
55
- matched = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
- # Simple matching for demo (replace with actual model in production)
58
- for disease, data in self.disease_db.items():
59
- symptom_count = sum(1 for s in data["symptoms"] if s in symptoms)
60
- if symptom_count >= 2:
61
- matched.append((disease, symptom_count))
 
 
 
62
 
63
- matched.sort(key=lambda x: x[1], reverse=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
- if matched:
66
- return f"Possible conditions:\n" + "\n".join(
67
- f"- {disease} ({count} matching symptoms)"
68
- for disease, count in matched[:3] # Show top 3
69
- )
 
 
 
 
70
 
71
- # Fallback to model if no matches
72
- result = self.symptom_checker(symptoms)
73
- return f"The model suggests this might be related to: {result[0]['label']} (confidence: {result[0]['score']:.2f})"
74
-
75
- def get_symptoms(self, disease):
76
- disease = disease.lower()
77
- if disease in self.disease_db:
78
- return "Common symptoms:\n" + "\n".join(
79
- f"- {symptom}" for symptom in self.disease_db[disease]["symptoms"]
80
- )
81
 
82
- # Fallback to model
83
- prompt = f"What are the common symptoms of {disease}?"
84
- result = self.medical_qa(prompt, max_length=100)
85
- return result[0]["generated_text"]
 
86
 
87
- def get_advice(self, condition):
88
- condition = condition.lower()
89
- if condition in self.disease_db:
90
- data = self.disease_db[condition]
91
- return (
92
- "Medical Advice:\n" + data["advice"] + "\n\n" +
93
- "Precautions:\n" + "\n".join(f"- {p}" for p in data["precautions"])
94
- )
95
-
96
- # Fallback to model
97
- prompt = f"What is the recommended medical advice and precautions for {condition}?"
98
- result = self.medical_qa(prompt, max_length=200)
99
- return result[0]["generated_text"]
100
-
101
- # Initialize assistant
102
- assistant = HealthAssistant()
103
-
104
- # Create Gradio interface
105
- with gr.Blocks(title="AI Health Assistant", theme=gr.themes.Soft()) as demo:
106
- gr.Markdown("# 🤖 AI Health Assistant")
107
- gr.Markdown("Describe your symptoms or ask about a disease to get information.")
108
-
109
- with gr.Tab("Diagnose from Symptoms"):
110
- symptom_input = gr.Textbox(label="Describe your symptoms (e.g., headache, fever, cough)")
111
- symptom_output = gr.Textbox(label="Possible Conditions", interactive=False)
112
- symptom_button = gr.Button("Analyze Symptoms")
113
-
114
- with gr.Tab("Disease Information"):
115
- disease_input = gr.Textbox(label="Enter a disease name")
116
- disease_symptoms = gr.Textbox(label="Common Symptoms", interactive=False)
117
- disease_advice = gr.Textbox(label="Medical Advice", interactive=False)
118
- disease_button = gr.Button("Get Disease Info")
119
-
120
- # Event handlers
121
- symptom_button.click(
122
- fn=assistant.predict_disease,
123
- inputs=symptom_input,
124
- outputs=symptom_output
125
- )
126
-
127
- disease_button.click(
128
- fn=assistant.get_symptoms,
129
- inputs=disease_input,
130
- outputs=disease_symptoms
131
- )
132
-
133
- disease_button.click(
134
- fn=assistant.get_advice,
135
- inputs=disease_input,
136
- outputs=disease_advice
137
- )
138
-
139
- # Disclaimer
140
- gr.Markdown("""
141
- ## ⚠️ Important Disclaimer
142
- This AI assistant provides general health information only and is not a substitute for professional medical advice.
143
- Always consult with a qualified healthcare provider for diagnosis and treatment.
144
- """)
145
 
146
- # For Hugging Face Spaces
147
- demo.launch()
 
 
3
 
4
  class HealthAssistant:
5
  def __init__(self):
6
+ # Using a medical-specific model
7
+ self.symptom_checker = pipeline(
8
+ "text-classification",
9
+ model="palaksharma/bert-base-uncased-medical"
10
+ )
11
 
12
+ # Disease mapping for readable outputs
13
+ self.label_mapping = {
14
+ "LABEL_0": "Common Cold",
15
+ "LABEL_1": "Influenza (Flu)",
16
+ "LABEL_2": "Migraine",
17
+ "LABEL_3": "Allergic Rhinitis",
18
+ "LABEL_4": "Gastroenteritis"
19
+ }
20
+
21
+ # Enhanced knowledge base
22
+ self.disease_info = {
23
+ "Common Cold": {
24
+ "symptoms": ["runny nose", "sneezing", "congestion", "sore throat"],
25
+ "advice": "Rest, hydration, OTC cold medicines",
26
+ "precautions": ["Hand hygiene", "Disinfect surfaces"]
 
 
 
 
 
 
 
 
 
 
 
 
27
  },
28
+ "Influenza (Flu)": {
29
+ "symptoms": ["fever", "cough", "body aches", "fatigue"],
30
+ "advice": "Antivirals if prescribed, rest, fluids",
31
+ "precautions": ["Flu vaccine", "Avoid crowds during outbreaks"]
 
 
 
 
 
 
 
 
32
  }
33
  }
34
 
35
  def predict_disease(self, symptoms):
36
+ try:
37
+ # Get model prediction
38
+ result = self.symptom_checker(symptoms)
39
+
40
+ # Map label to readable name
41
+ label = result[0]['label']
42
+ disease_name = self.label_mapping.get(label, "Unknown Condition")
43
+ confidence = result[0]['score']
44
+
45
+ # Get additional info if available
46
+ info = self.disease_info.get(disease_name, {})
47
+
48
+ response = f"Possible condition: {disease_name} (confidence: {confidence:.2f})\n\n"
49
+
50
+ if info:
51
+ response += f"Common symptoms:\n- " + "\n- ".join(info.get('symptoms', [])) + "\n\n"
52
+ response += f"Recommended actions:\n{info.get('advice', 'Consult a doctor')}"
53
+
54
+ return response
55
 
56
+ except Exception as e:
57
+ return f"Error analyzing symptoms: {str(e)}"
58
+
59
+ def create_interface():
60
+ assistant = HealthAssistant()
61
+
62
+ with gr.Blocks(title="Medical Symptom Checker", theme=gr.themes.Soft()) as demo:
63
+ gr.Markdown("# 🏥 AI Symptom Checker")
64
 
65
+ with gr.Row():
66
+ with gr.Column():
67
+ symptoms = gr.Textbox(
68
+ label="Describe your symptoms",
69
+ placeholder="E.g. headache, fever, cough...",
70
+ lines=3
71
+ )
72
+ analyze_btn = gr.Button("Analyze Symptoms")
73
+
74
+ with gr.Column():
75
+ output = gr.Textbox(
76
+ label="Analysis Result",
77
+ interactive=False,
78
+ lines=10
79
+ )
80
 
81
+ # Examples
82
+ gr.Examples(
83
+ examples=[
84
+ ["headache, fever, body aches"],
85
+ ["runny nose, sneezing, sore throat"],
86
+ ["nausea, vomiting, diarrhea"]
87
+ ],
88
+ inputs=symptoms
89
+ )
90
 
91
+ analyze_btn.click(
92
+ fn=assistant.predict_disease,
93
+ inputs=symptoms,
94
+ outputs=output
95
+ )
 
 
 
 
 
96
 
97
+ gr.Markdown("""
98
+ ## ⚠️ Important Disclaimer
99
+ This AI tool provides general information only and is not a substitute for professional medical advice.
100
+ Always consult with a qualified healthcare provider for diagnosis and treatment.
101
+ """)
102
 
103
+ return demo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
+ if __name__ == "__main__":
106
+ demo = create_interface()
107
+ demo.launch()