# 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(""" # # """, 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"""
{label}
{prompt}
""", unsafe_allow_html=True) # with cols[1]: # if i+1 < len(prompt_options): # label, prompt = prompt_options[i+1] # st.markdown(f"""
{label}
{prompt}
""", 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.")