Pranith06 commited on
Commit
b8fdad3
Β·
verified Β·
1 Parent(s): be652e1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +125 -67
app.py CHANGED
@@ -1,107 +1,165 @@
1
  import gradio as gr
2
  from transformers import pipeline
 
3
 
4
- class HealthAssistant:
5
  def __init__(self):
6
- # Using an officially available medical model
7
  self.symptom_checker = pipeline(
8
- "text-classification",
9
- model="emilyalsentzer/Bio_ClinicalBERT"
10
  )
11
 
12
- # Simplified mapping for demo purposes
13
- self.label_mapping = {
14
- "LABEL_0": "Respiratory Infection",
15
- "LABEL_1": "Gastrointestinal Issue",
16
- "LABEL_2": "Neurological Condition",
17
- "LABEL_3": "Musculoskeletal Problem",
18
- "LABEL_4": "General Viral Infection"
19
- }
20
 
21
- # Enhanced knowledge base
22
- self.disease_info = {
23
- "Respiratory Infection": {
24
- "symptoms": ["cough", "shortness of breath", "sore throat", "congestion"],
25
- "advice": "Rest, stay hydrated, use humidifier, monitor breathing",
26
- "precautions": ["Good hand hygiene", "Avoid smoking", "Get flu vaccine"]
27
  },
28
- "Gastrointestinal Issue": {
29
- "symptoms": ["nausea", "vomiting", "diarrhea", "stomach pain"],
30
- "advice": "Stay hydrated, BRAT diet, avoid dairy, monitor for dehydration",
31
- "precautions": ["Proper food handling", "Hand washing", "Avoid contaminated water"]
32
  }
33
  }
34
 
35
- def predict_disease(self, symptoms):
 
36
  try:
37
- # Get model prediction
38
- result = self.symptom_checker(symptoms[:512]) # Limit input length
39
-
40
- # Map label to readable name
41
- label = result[0]['label']
42
- disease_name = self.label_mapping.get(label, "Medical 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', 'Please consult a healthcare professional')}"
53
 
54
- return response
 
 
 
55
 
56
  except Exception as e:
57
- return f"System is currently analyzing your symptoms. For now, please consult a doctor about: {symptoms}"
 
 
 
 
 
 
 
 
 
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 (Demo)")
 
 
 
 
 
 
 
 
 
 
 
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
- ["nausea, vomiting, diarrhea"],
86
- ["shortness of breath, cough"]
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()
 
1
  import gradio as gr
2
  from transformers import pipeline
3
+ import requests
4
 
5
+ class AIHealthAssistant:
6
  def __init__(self):
7
+ # Initialize symptom checker model
8
  self.symptom_checker = pipeline(
9
+ "text-classification",
10
+ model="microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract-fulltext"
11
  )
12
 
13
+ # Initialize medical QA model
14
+ self.medical_qa = pipeline(
15
+ "question-answering",
16
+ model="deepset/roberta-base-squad2"
17
+ )
 
 
 
18
 
19
+ # Knowledge base (can be replaced with API calls)
20
+ self.disease_db = {
21
+ "influenza": {
22
+ "symptoms": ["fever", "cough", "sore throat", "runny nose", "body aches"],
23
+ "advice": "Rest, stay hydrated, take fever reducers like acetaminophen",
24
+ "precautions": ["Annual flu vaccine", "Frequent hand washing", "Avoid close contact"]
25
  },
26
+ "migraine": {
27
+ "symptoms": ["severe headache", "nausea", "sensitivity to light", "aura"],
28
+ "advice": "Rest in dark room, take prescribed medication, apply cold compress",
29
+ "precautions": ["Identify triggers", "Maintain sleep schedule", "Stay hydrated"]
30
  }
31
  }
32
 
33
+ def get_disease_from_symptoms(self, symptoms):
34
+ """Predict disease from symptoms using Hugging Face model"""
35
  try:
36
+ # For production, replace with a proper medical model
37
+ result = self.symptom_checker(symptoms)
 
 
 
 
 
38
 
39
+ # Map to diseases in our database
40
+ for disease in self.disease_db:
41
+ if disease in symptoms.lower():
42
+ return disease
43
 
44
+ # Fallback to first disease (in real app, use proper mapping)
45
+ return list(self.disease_db.keys())[0]
46
+
47
+ except Exception as e:
48
+ print(f"Model error: {e}")
49
+ return "unknown"
50
+
51
+ def get_medical_info(self, disease, info_type):
52
+ """Get medical information from database or API"""
53
+ disease = disease.lower()
54
+
55
+ # Check local database first
56
+ if disease in self.disease_db:
57
+ return self.disease_db[disease].get(info_type, "Information not available")
58
+
59
+ # Fallback to API (example using hypothetical medical API)
60
+ try:
61
+ if info_type == "symptoms":
62
+ prompt = f"What are the symptoms of {disease}?"
63
+ elif info_type == "advice":
64
+ prompt = f"What is the treatment for {disease}?"
65
+ else:
66
+ prompt = f"What precautions should be taken for {disease}?"
67
 
68
+ # In a real app, replace with actual API call:
69
+ # response = requests.get(f"https://medical-api.example.com/{disease}")
70
+ # return response.json().get(info_type)
71
 
72
+ # For demo, using the QA model
73
+ context = f"{disease} is a medical condition. {self.get_medical_advice_from_api(disease)}"
74
+ result = self.medical_qa(question=prompt, context=context)
75
+ return result['answer']
76
 
77
  except Exception as e:
78
+ print(f"API error: {e}")
79
+ return "Information not available"
80
+
81
+ def get_medical_advice_from_api(self, disease):
82
+ """Simulate API response for demo purposes"""
83
+ api_responses = {
84
+ "diabetes": "Diabetes requires blood sugar monitoring, insulin therapy, and dietary changes.",
85
+ "hypertension": "Hypertension management includes medication, low-salt diet, and regular exercise."
86
+ }
87
+ return api_responses.get(disease.lower(), "Consult a healthcare professional for proper diagnosis and treatment.")
88
 
89
+ def create_demo():
90
+ assistant = AIHealthAssistant()
91
 
92
+ def process_input(user_input, mode):
93
+ if mode == "Symptoms to Disease":
94
+ disease = assistant.get_disease_from_symptoms(user_input)
95
+ symptoms = assistant.get_medical_info(disease, "symptoms")
96
+ advice = assistant.get_medical_info(disease, "advice")
97
+ precautions = assistant.get_medical_info(disease, "precautions")
98
+
99
+ output = (
100
+ f"πŸ” Possible Condition: {disease.capitalize()}\n\n"
101
+ f"πŸ“‹ Symptoms:\n- " + "\n- ".join(symptoms) + "\n\n"
102
+ f"πŸ’Š Recommended Actions:\n{advice}\n\n"
103
+ f"πŸ›‘οΈ Precautions:\n- " + "\n- ".join(precautions)
104
+ )
105
 
106
+ elif mode == "Disease to Symptoms":
107
+ symptoms = assistant.get_medical_info(user_input, "symptoms")
108
+ advice = assistant.get_medical_info(user_input, "advice")
 
 
 
 
 
109
 
110
+ output = (
111
+ f"πŸ“‹ Symptoms of {user_input.capitalize()}:\n- " + "\n- ".join(symptoms) + "\n\n"
112
+ f"πŸ’Š Recommended Actions:\n{advice}"
113
+ )
114
+
115
+ return output
116
+
117
+ with gr.Blocks(title="AI Health Assistant") as demo:
118
+ gr.Markdown("# πŸ₯ AI Health Assistant")
119
+ gr.Markdown("Enter symptoms or a disease name to get medical information")
120
+
121
+ with gr.Row():
122
+ input_mode = gr.Radio(
123
+ choices=["Symptoms to Disease", "Disease to Symptoms"],
124
+ label="Input Mode"
125
+ )
126
+ user_input = gr.Textbox(
127
+ label="Input",
128
+ placeholder="Enter symptoms or disease name..."
129
+ )
130
+
131
+ submit_btn = gr.Button("Get Medical Information")
132
+ output = gr.Textbox(label="Result", interactive=False, lines=10)
133
 
134
+ # Example inputs
135
  gr.Examples(
136
  examples=[
137
+ ["headache, nausea, sensitivity to light", "Symptoms to Disease"],
138
+ ["influenza", "Disease to Symptoms"],
139
+ ["fever, cough, sore throat", "Symptoms to Disease"]
140
  ],
141
+ inputs=[user_input, input_mode],
142
+ outputs=output,
143
+ fn=process_input,
144
+ cache_examples=True
145
  )
146
 
147
+ submit_btn.click(
148
+ fn=process_input,
149
+ inputs=[user_input, input_mode],
150
  outputs=output
151
  )
152
 
153
  gr.Markdown("""
154
  ## ⚠️ Important Disclaimer
155
+ This AI assistant provides general health information only and is not a substitute
156
+ for professional medical advice, diagnosis, or treatment.
157
+ Always seek the advice of your physician or other qualified health provider
158
+ with any questions you may have regarding a medical condition.
159
  """)
160
 
161
  return demo
162
 
163
  if __name__ == "__main__":
164
+ demo = create_demo()
165
  demo.launch()