File size: 11,708 Bytes
40aa75e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
    # st.markdown("""
    # ## Welcome to the **Early Prediction of Health & Lifestyle Diseases**!  
    # This tool provides **early prediction and analysis** for various health conditions using **Machine Learning & NLP**.
    
    # ### πŸ₯ Available Features:
    # - **🩸 Disease Predictors**:
    #   - Diabetes Prediction   
    #   - Hypertension Prediction  
    #   - Cardiovascular Disease Prediction 
    #   - Stroke Prediction
    #   - Asthma Prediction 
    #   - Sleep Health Analysis
    # # - **βœ… Checkbox-based Lifestyle Disease Predictor** using **BiomedNLP-PubMedBERT**  
    # - **πŸ€– Medical Consultant** (Ask health-related questions)  
    # # - **🧠 Mental Health Assessment**  
    # - **πŸ“Š Data Visualizer** (Analyze trends in health conditions)  
                
    # πŸ‘‰ Select an option from the sidebar to proceed!  
    # """)

    # with st.expander("πŸš€ Quick Start Guide"):
    #     st.write("""
    #     1. Select a **health prediction model** from the sidebar.
    #     2. Enter your details in the input fields.
    #     3. Click **Predict** to get your result.
    #     4. View personalized **health insights & recommendations**.
    #     """)


    # # Disclaimer Section
    # st.markdown("---")
    # # st.markdown("""
    # # **⚠️ Disclaimer:** This application has been developed using **real-world healthcare datasets** sourced from Kaggle:  

    # # - [Stroke Prediction Dataset](http://kaggle.com/code/chanchal24/stroke-prediction-using-python/input?select=healthcare-dataset-stroke-data.csv)  
    # # - [Asthma Analysis & Prediction](https://www.kaggle.com/code/bryamblasrimac/asthma-eda-prediction-f2score-85/input)  
    # # - [Diabetes Dataset](https://www.kaggle.com/datasets/mathchi/diabetes-data-set)  
    # # - [Cardiovascular Disease Dataset](https://www.kaggle.com/datasets/sulianova/cardiovascular-disease-dataset)  
    # # - [Sentiment Analysis for Mental Health](https://www.kaggle.com/datasets/suchintikasarkar/sentiment-analysis-for-mental-health)  
    # # - [Sleep Health Analysis](https://www.kaggle.com/datasets/uom190346a/sleep-health-and-lifestyle-dataset)
    # # \


    # st.markdown("""
    # The predictions are generated using **machine learning models** trained on these datasets, incorporating **evaluation metrics and graphical insights** to enhance interpretability.  

    # However, this tool has **not undergone clinical validation** and should be used **for informational and educational purposes only**. It is not intended to serve as a substitute for professional medical diagnosis or treatment. Always consult a qualified healthcare provider for medical advice.
    # """)



    # if selected == 'Medical Consultant':
#     st.title("🩺 Medical Consultant Chatbot")
#     st.markdown("### Discuss Your Health Concerns with Our AI-powered Chatbot")
#     st.write("Ask about **Diabetes, Asthma, Stroke, Cardiovascular Disease, or Mental Health.**")

#     genai.configure(api_key="AIzaSyAwyi9c5OdvLoWrv5lFi1jZDEYwuprQAKE")

#     # Custom Styling
#     st.markdown("""
#         <style>
#             .prompt-box { 
#                 background-color: #000000; 
#                 padding: 12px; 
#                 border-radius: 8px; 
#                 font-size: 14px; 
#                 font-family: sans-serif;
#                 margin-bottom: 10px;
#                 border: 1px solid #dee2e6;
#                 text-align: center;
#             }
#         </style>
#     """, unsafe_allow_html=True)

#     st.markdown("#### πŸ’‘ Common Health Queries")

#     prompt_options = [
#         ("Diabetes – Diet", "What foods should I eat if I have diabetes?"),
#         ("Diabetes – Exercise", "What type of workouts help control blood sugar levels?"),
#         ("Asthma – Triggers", "What are common asthma triggers?"),
#         ("Asthma – Treatment", "What are the best medications for asthma?"),
#         ("Stroke – Symptoms", "What are the early warning signs of a stroke?"),
#         ("Stroke – Prevention", "How can I reduce my risk of stroke?"),
#         ("Cardiovascular – Heart Health", "How can I reduce my risk of heart disease?"),
#         ("Cardiovascular – Blood Pressure", "What lifestyle changes can lower high blood pressure?"),
#         ("Mental Health – Stress Management", "How can I manage stress effectively?"),
#         ("Mental Health – Sleep Disorders", "What are the causes and treatments for sleep disorders?")
#     ]

#     # Display prompts in two columns (2 prompts per row)
#     cols = st.columns(2)
#     for i in range(0, len(prompt_options), 2):
#         with cols[0]: 
#             if i < len(prompt_options):
#                 label, prompt = prompt_options[i]
#                 st.markdown(f"""<div class="prompt-box"><strong>{label}</strong><br>{prompt}</div>""", unsafe_allow_html=True)

#         with cols[1]: 
#             if i+1 < len(prompt_options):
#                 label, prompt = prompt_options[i+1]
#                 st.markdown(f"""<div class="prompt-box"><strong>{label}</strong><br>{prompt}</div>""", unsafe_allow_html=True)

#     # Initialize chat history if not present
#     if "chat_history" not in st.session_state:
#         st.session_state.chat_history = []

#     # Display previous chat history
#     for message in st.session_state.chat_history:
#         with st.chat_message(message["role"]):
#             st.markdown(message["content"])

#     # User input field
#     user_prompt = st.chat_input("Ask about Diabetes, Asthma, Stroke, Cardiovascular Disease, or Mental Health...")

#     # List of allowed topics
#     allowed_keywords = ["diabetes", "asthma", "stroke", "cardiovascular", "heart", "blood pressure", 
#                         "mental health", "depression", "stress", "cholesterol", "sleep disorders"]

#     if user_prompt:
#         # Display user message
#         st.chat_message("user").markdown(user_prompt)
#         st.session_state.chat_history.append({"role": "user", "content": user_prompt})

#         # Restriction: Only process if related to health topics
#         if any(keyword in user_prompt.lower() for keyword in allowed_keywords):
#             model = genai.GenerativeModel("gemini-2.0-flash")
#             response = model.generate_content(user_prompt)

#             if response and hasattr(response, "text"):
#                 assistant_response = response.text
#             else:
#                 assistant_response = "I'm sorry, I couldn't generate a response."

#             st.session_state.chat_history.append({"role": "assistant", "content": assistant_response})

#             # Display assistant's response
#             with st.chat_message("assistant"):
#                 st.markdown(assistant_response)
#         else:
#             # Restriction message
#             restriction_msg = "**⚠️ This chatbot only responds to health-related topics.**\nPlease ask about Diabetes, Asthma, Stroke, Cardiovascular Disease, or Mental Health."
#             st.session_state.chat_history.append({"role": "assistant", "content": restriction_msg})
            
#             with st.chat_message("assistant"):
#                 st.markdown(restriction_msg)



# if selected == 'Checkbox-to-disease-predictor':
# # Load transformer model
#     classifier = pipeline("zero-shot-classification", model="microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract")
#     # Use a pipeline as a high-level helper

#     # from transformers import pipeline

#     # pipe = pipeline("fill-mask", model="microsoft/BiomedNLP-BiomedBERT-base-uncased-abstract-fulltext")


#     # Define symptoms for each disease
#     diseases = {
#         "Diabetes": ["Frequent urination", "Increased thirst", "Unexplained weight loss", "Fatigue", "Blurred vision"],
#         "Hypertension": ["Headache", "Dizziness", "Chest pain", "Shortness of breath", "Nosebleeds"],
#         "Obesity": ["Excess body fat", "Breathlessness", "Joint pain", "Increased sweating", "Low energy levels"],
#         "Cardiovascular Disease": ["Chest pain", "Shortness of breath", "Dizziness", "Irregular heartbeat", "Fatigue"],
#         "COPD": ["Chronic cough", "Shortness of breath", "Wheezing", "Chest tightness", "Frequent respiratory infections"],
#         "Liver Disease": ["Jaundice", "Abdominal pain", "Swelling in legs", "Chronic fatigue", "Nausea"],
#         "Kidney Disease": ["Swelling in legs", "Fatigue", "Loss of appetite", "Changes in urination", "Muscle cramps"],
#         "Metabolic Syndrome": ["High blood sugar", "High blood pressure", "Increased waist size", "High cholesterol", "Fatigue"],
#         "Osteoarthritis": ["Joint pain", "Stiffness", "Swelling", "Reduced flexibility", "Bone spurs"],
#         "Gastroesophageal Reflux Disease": ["Heartburn", "Acid reflux", "Difficulty swallowing", "Chronic cough", "Sore throat"],
#         "Depression": ["Persistent sadness", "Loss of interest", "Sleep disturbances", "Fatigue", "Difficulty concentrating"],
#         "Sleep Apnea": ["Loud snoring", "Pauses in breathing", "Daytime drowsiness", "Morning headaches", "Irritability"],
#     }

#     # Streamlit UI
#     st.title("🩺 Hybrid Symptom Checker")
#     st.write("Select your symptoms and get AI-powered predictions!")

#     selected_symptoms = []

#     # Create symptom selection with markdown separation and three columns
#     disease_keys = list(diseases.keys())

#     for i in range(0, len(disease_keys), 3):
#         cols = st.columns(3)
#         for j in range(3):
#             if i + j < len(disease_keys):
#                 disease = disease_keys[i + j]
#                 with cols[j]:
#                     st.markdown(f"### {disease}")
#                     for symptom in diseases[disease]:
#                         if st.checkbox(symptom, key=f"{disease}_{symptom}"):
#                             selected_symptoms.append(symptom)

#     if st.button("πŸ” Predict Disease"):
#         if selected_symptoms:
#             user_input = ", ".join(selected_symptoms)  # Convert symptoms to text

#             # 1️⃣ Custom Symptom Matching Approach
#             disease_scores = {disease: 0 for disease in diseases.keys()}
#             for disease, symptoms in diseases.items():
#                 matches = sum(symptom in selected_symptoms for symptom in symptoms)
#                 disease_scores[disease] = matches / len(symptoms)  # Normalize by symptom count

#             # Normalize to percentage
#             symptom_match_scores = {d: round(score * 100, 2) for d, score in disease_scores.items()}

#             # 2️⃣ AI Model Prediction
#             ai_results = classifier(user_input, list(diseases.keys()))
#             ai_scores = {ai_results["labels"][i]: round(ai_results["scores"][i] * 100, 2) for i in range(len(ai_results["labels"]))}

#             # 3️⃣ Hybrid Score Calculation (Average of Both Scores)
#             final_scores = {}
#             for disease in diseases.keys():
#                 symptom_score = symptom_match_scores.get(disease, 0)
#                 ai_score = ai_scores.get(disease, 0)
#                 final_scores[disease] = round((symptom_score + ai_score) / 2, 2)  # Averaging

#             # Sort by final score
#             sorted_final_scores = sorted(final_scores.items(), key=lambda x: x[1], reverse=True)

#             # Display results
#             st.write("### πŸ”¬ Possible Conditions (Hybrid Model Prediction):")
#             for disease, score in sorted_final_scores:
#                 if score > 0:
#                     st.write(f"🩺 {disease}: {score}% match")
#         else:
#             st.write("⚠️ Please select at least one symptom.")