|
|
import streamlit as st |
|
|
import pandas as pd |
|
|
import numpy as np |
|
|
import joblib |
|
|
import pickle |
|
|
from PIL import Image |
|
|
import io |
|
|
import os |
|
|
import plotly.graph_objects as go |
|
|
import plotly.express as px |
|
|
from datetime import datetime |
|
|
import base64 |
|
|
from fpdf import FPDF |
|
|
import tempfile |
|
|
|
|
|
|
|
|
st.set_page_config( |
|
|
page_title="SehatAI - Smart Healthcare Triage", |
|
|
page_icon="🏥", |
|
|
layout="wide", |
|
|
initial_sidebar_state="collapsed" |
|
|
) |
|
|
|
|
|
|
|
|
def local_css(): |
|
|
st.markdown(""" |
|
|
<style> |
|
|
.main-header { |
|
|
font-size: 3.5rem; |
|
|
color: #1f77b4; |
|
|
text-align: center; |
|
|
margin-bottom: 0.5rem; |
|
|
font-weight: 800; |
|
|
background: linear-gradient(135deg, #00401A, #00612A, #008000); |
|
|
-webkit-background-clip: text; |
|
|
-webkit-text-fill-color: transparent; |
|
|
text-shadow: 0px 4px 8px rgba(0,0,0,0.2); |
|
|
font-family: 'Arial', sans-serif; |
|
|
} |
|
|
.quote-section { |
|
|
background: linear-gradient(135deg, #00401A 0%, #00612A 100%); |
|
|
color: white; |
|
|
padding: 25px; |
|
|
border-radius: 20px; |
|
|
text-align: center; |
|
|
margin: 20px 0; |
|
|
box-shadow: 0 8px 25px rgba(0,0,0,0.15); |
|
|
border: 3px solid #008000; |
|
|
} |
|
|
.quote-text { |
|
|
font-size: 1.4rem; |
|
|
font-weight: 600; |
|
|
margin-bottom: 10px; |
|
|
font-style: italic; |
|
|
} |
|
|
.quote-author { |
|
|
font-size: 1.1rem; |
|
|
opacity: 0.9; |
|
|
} |
|
|
.section-container { |
|
|
background: white; |
|
|
padding: 30px; |
|
|
border-radius: 20px; |
|
|
box-shadow: 0 8px 25px rgba(0,0,0,0.1); |
|
|
margin-bottom: 30px; |
|
|
border: 2px solid #e0e0e0; |
|
|
transition: all 0.3s ease; |
|
|
} |
|
|
.section-container:hover { |
|
|
box-shadow: 0 12px 35px rgba(0,0,0,0.15); |
|
|
transform: translateY(-2px); |
|
|
} |
|
|
.metric-card { |
|
|
background: linear-gradient(135deg, #00401A 0%, #00612A 100%); |
|
|
color: white; |
|
|
padding: 25px; |
|
|
border-radius: 15px; |
|
|
text-align: center; |
|
|
box-shadow: 0 6px 15px rgba(0,0,0,0.2); |
|
|
transition: all 0.3s ease; |
|
|
} |
|
|
.metric-card:hover { |
|
|
transform: translateY(-3px); |
|
|
box-shadow: 0 10px 25px rgba(0,0,0,0.3); |
|
|
} |
|
|
.risk-high { |
|
|
background: linear-gradient(135deg, #ff6b6b, #ee5a52); |
|
|
color: white; |
|
|
padding: 25px; |
|
|
border-radius: 15px; |
|
|
border-left: 8px solid #dc3545; |
|
|
box-shadow: 0 6px 15px rgba(220,53,69,0.4); |
|
|
} |
|
|
.risk-medium { |
|
|
background: linear-gradient(135deg, #ffd93d, #ffcd3c); |
|
|
color: #333; |
|
|
padding: 25px; |
|
|
border-radius: 15px; |
|
|
border-left: 8px solid #ffc107; |
|
|
box-shadow: 0 6px 15px rgba(255,193,7,0.4); |
|
|
} |
|
|
.risk-low { |
|
|
background: linear-gradient(135deg, #6bcf7f, #28a745); |
|
|
color: white; |
|
|
padding: 25px; |
|
|
border-radius: 15px; |
|
|
border-left: 8px solid #20c997; |
|
|
box-shadow: 0 6px 15px rgba(40,167,69,0.4); |
|
|
} |
|
|
.priority-box { |
|
|
border: 4px solid #00612A; |
|
|
padding: 30px; |
|
|
border-radius: 20px; |
|
|
margin: 20px 0; |
|
|
background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%); |
|
|
box-shadow: 0 8px 25px rgba(0,0,0,0.15); |
|
|
} |
|
|
.stButton button { |
|
|
width: 100%; |
|
|
background: linear-gradient(45deg, #00401A, #00612A); |
|
|
color: white; |
|
|
font-weight: bold; |
|
|
border: none; |
|
|
padding: 16px 32px; |
|
|
border-radius: 12px; |
|
|
font-size: 1.2rem; |
|
|
transition: all 0.3s ease; |
|
|
box-shadow: 0 6px 15px rgba(0,64,26,0.4); |
|
|
} |
|
|
.stButton button:hover { |
|
|
transform: translateY(-3px); |
|
|
box-shadow: 0 10px 25px rgba(0,64,26,0.5); |
|
|
background: linear-gradient(45deg, #00612A, #00401A); |
|
|
} |
|
|
.chat-message { |
|
|
padding: 15px; |
|
|
border-radius: 15px; |
|
|
margin: 10px 0; |
|
|
border: 2px solid #e0e0e0; |
|
|
} |
|
|
.user-message { |
|
|
background: linear-gradient(135deg, #00401A, #00612A); |
|
|
color: white; |
|
|
margin-left: 20%; |
|
|
text-align: right; |
|
|
} |
|
|
.bot-message { |
|
|
background: linear-gradient(135deg, #f8f9fa, #e9ecef); |
|
|
color: #333; |
|
|
margin-right: 20%; |
|
|
} |
|
|
.language-selector { |
|
|
position: absolute; |
|
|
top: 20px; |
|
|
right: 20px; |
|
|
z-index: 1000; |
|
|
} |
|
|
.pakistan-flag { |
|
|
background: linear-gradient(135deg, #00401A, #00612A, #FFFFFF); |
|
|
padding: 5px 15px; |
|
|
border-radius: 20px; |
|
|
color: white; |
|
|
font-weight: bold; |
|
|
margin: 0 10px; |
|
|
} |
|
|
</style> |
|
|
""", unsafe_allow_html=True) |
|
|
|
|
|
|
|
|
def init_session_state(): |
|
|
if 'patient_data' not in st.session_state: |
|
|
st.session_state.patient_data = {} |
|
|
if 'risk_scores' not in st.session_state: |
|
|
st.session_state.risk_scores = {} |
|
|
if 'assessment_history' not in st.session_state: |
|
|
st.session_state.assessment_history = [] |
|
|
if 'chat_history' not in st.session_state: |
|
|
st.session_state.chat_history = [] |
|
|
if 'current_language' not in st.session_state: |
|
|
st.session_state.current_language = 'English' |
|
|
|
|
|
|
|
|
HEALTHCARE_QUOTES = [ |
|
|
{ |
|
|
'english': "Health is the crown on the well person's head that only the ill can see.", |
|
|
'urdu': "صحت ایک تاج ہے جو تندرست انسان کے سر پر ہوتا ہے جسے صرف بیمار ہی دیکھ سکتے ہیں۔", |
|
|
'author': "Robin Sharma" |
|
|
}, |
|
|
{ |
|
|
'english': "The first wealth is health. Take care of your body, it's the only place you have to live.", |
|
|
'urdu': "پہلی دولت صحت ہے۔ اپنے جسم کا خیال رکھیں، یہ وہ واحد جگہ ہے جہاں آپ کو رہنا ہے۔", |
|
|
'author': "Ralph Waldo Emerson" |
|
|
}, |
|
|
{ |
|
|
'english': "A healthy outside starts from the inside. Prevention is better than cure.", |
|
|
'urdu': "ایک صحت مند باہر کی طرف اندر سے شروع ہوتی ہے۔ بچاؤ علاج سے بہتر ہے۔", |
|
|
'author': "Robert Urich" |
|
|
}, |
|
|
{ |
|
|
'english': "Your body hears everything your mind says. Stay positive for better health.", |
|
|
'urdu': "آپ کا جسم وہ سب کچھ سنتا ہے جو آپ کا دماغ کہتا ہے۔ بہتر صحت کے لیے مثبت رہیں۔", |
|
|
'author': "Naomi Judd" |
|
|
}, |
|
|
{ |
|
|
'english': "The greatest of follies is to sacrifice health for any other kind of happiness.", |
|
|
'urdu': "سب سے بڑی بیوقوفی صحت کو کسی دوسری قسم کی خوشی کے لیے قربان کرنا ہے۔", |
|
|
'author': "Arthur Schopenhauer" |
|
|
} |
|
|
] |
|
|
|
|
|
class HealthcareChatbot: |
|
|
def __init__(self): |
|
|
self.medical_knowledge_base = { |
|
|
'heart_disease': { |
|
|
'symptoms': ["Chest pain or discomfort", "Shortness of breath", "Pain in arms, neck, jaw", "Nausea", "Fatigue", "Dizziness"], |
|
|
'risk_factors': ["High blood pressure", "High cholesterol", "Smoking", "Diabetes", "Obesity", "Family history", "Physical inactivity"], |
|
|
'prevention': ["Healthy diet low in saturated fats", "Regular exercise 30 mins daily", "No smoking", "Weight management", "Stress management", "Regular check-ups"], |
|
|
'emergency_signs': ["Severe chest pain", "Difficulty breathing", "Fainting", "Rapid heartbeat", "Pain spreading to arms/shoulders"] |
|
|
}, |
|
|
'diabetes': { |
|
|
'symptoms': ["Increased thirst and hunger", "Frequent urination", "Fatigue", "Blurred vision", "Slow healing wounds", "Unexplained weight loss"], |
|
|
'risk_factors': ["Family history", "Overweight (BMI > 25)", "High blood pressure", "Physical inactivity", "Age over 45", "Gestational diabetes history"], |
|
|
'prevention': ["Balanced diet with controlled carbs", "Regular physical activity", "Weight management", "Blood sugar monitoring", "Regular health screenings"], |
|
|
'emergency_signs': ["Blood sugar >300 mg/dL or <70 mg/dL", "Confusion or disorientation", "Fruity breath odor", "Rapid breathing", "Loss of consciousness"] |
|
|
}, |
|
|
'hypertension': { |
|
|
'symptoms': ["Headaches", "Dizziness", "Blurred vision", "Shortness of breath", "Chest pain", "Nosebleeds"], |
|
|
'risk_factors': ["Family history", "Age over 65", "Obesity", "High salt intake", "Stress", "Alcohol consumption", "Smoking"], |
|
|
'prevention': ["DASH diet (low sodium)", "Regular aerobic exercise", "Weight management", "Stress reduction", "Limit alcohol", "No smoking"], |
|
|
'emergency_signs': ["Severe headache", "Chest pain", "Difficulty breathing", "Vision changes", "Confusion", "Seizures"] |
|
|
}, |
|
|
'general_health': { |
|
|
'nutrition': ["Eat 5-9 servings of fruits/vegetables daily", "Choose whole grains over refined", "Include lean proteins", "Stay hydrated (8-10 glasses water)", "Limit processed foods and sugar"], |
|
|
'exercise': ["150 mins moderate exercise weekly", "Strength training 2x weekly", "Stay active throughout day", "Include flexibility exercises", "Get adequate rest between workouts"], |
|
|
'lifestyle': ["7-9 hours quality sleep nightly", "Stress management techniques", "No smoking", "Limit alcohol to 1-2 drinks/day", "Regular health check-ups"], |
|
|
'prevention': ["Annual physical exams", "Vaccinations up to date", "Regular hand washing", "Sun protection", "Mental health care"] |
|
|
} |
|
|
} |
|
|
|
|
|
def get_response(self, user_input, language='English'): |
|
|
user_input = user_input.lower().strip() |
|
|
|
|
|
|
|
|
if any(word in user_input for word in ['hello', 'hi', 'hey', 'salam', 'السلام علیکم']): |
|
|
return self._format_greeting_response(language) |
|
|
|
|
|
|
|
|
if any(word in user_input for word in ['heart', 'cardiac', 'chest pain', 'cholesterol', 'دل', 'سینے میں درد']): |
|
|
return self._format_heart_response(language) |
|
|
|
|
|
|
|
|
elif any(word in user_input for word in ['diabetes', 'sugar', 'glucose', 'insulin', 'ذیابیطس', 'شوگر']): |
|
|
return self._format_diabetes_response(language) |
|
|
|
|
|
|
|
|
elif any(word in user_input for word in ['blood pressure', 'hypertension', 'bp', 'بلڈ پریشر', 'ہائی بلڈ پریشر']): |
|
|
return self._format_hypertension_response(language) |
|
|
|
|
|
|
|
|
elif any(word in user_input for word in ['diet', 'nutrition', 'food', 'eating', 'غذا', 'کھانا']): |
|
|
return self._format_nutrition_response(language) |
|
|
|
|
|
|
|
|
elif any(word in user_input for word in ['exercise', 'workout', 'fitness', 'gym', 'ورزش', 'جم']): |
|
|
return self._format_exercise_response(language) |
|
|
|
|
|
|
|
|
elif any(word in user_input for word in ['symptom', 'pain', 'fever', 'headache', 'علامت', 'درد']): |
|
|
return self._format_symptoms_response(language) |
|
|
|
|
|
|
|
|
elif any(word in user_input for word in ['medicine', 'medication', 'drug', 'treatment', 'دوا', 'علاج']): |
|
|
return self._format_medication_response(language) |
|
|
|
|
|
|
|
|
elif any(word in user_input for word in ['emergency', 'urgent', 'help', 'ہنگامی', 'فوری']): |
|
|
return self._format_emergency_response(language) |
|
|
|
|
|
|
|
|
elif any(word in user_input for word in ['health', 'wellness', 'prevention', 'صحت', 'تندرستی']): |
|
|
return self._format_general_health_response(language) |
|
|
|
|
|
|
|
|
else: |
|
|
return self._format_default_response(language) |
|
|
|
|
|
def _format_greeting_response(self, language): |
|
|
if language == 'English': |
|
|
return """ |
|
|
**🤖 Welcome to SehatAI Health Assistant!** |
|
|
|
|
|
I'm here to help you with: |
|
|
• Heart health and cardiovascular diseases |
|
|
• Diabetes and blood sugar management |
|
|
• Blood pressure and hypertension |
|
|
• Nutrition and diet advice |
|
|
• Exercise and fitness guidance |
|
|
• Symptom assessment |
|
|
• General health and wellness |
|
|
|
|
|
Please ask me specific health-related questions, and I'll provide detailed, helpful information. |
|
|
|
|
|
*Note: I'm an AI assistant. For serious medical concerns, always consult a qualified healthcare professional.* |
|
|
""" |
|
|
else: |
|
|
return """ |
|
|
**🤖 سیحت اے آئی ہیلتھ اسسٹنٹ میں خوش آمدید!** |
|
|
|
|
|
میں آپ کی مدد کے لیے یہاں ہوں: |
|
|
• دل کی صحت اور قلبی امراض |
|
|
• ذیابیطس اور بلڈ شوگر مینجمنٹ |
|
|
• بلڈ پریشر اور ہائی بلڈ پریشر |
|
|
• غذائیت اور غذا کے مشورے |
|
|
• ورزش اور فٹنس گائیڈنس |
|
|
• علامات کی تشخیص |
|
|
• عام صحت اور تندرستی |
|
|
|
|
|
براہ کرم مجھ سے مخصوص صحت سے متعلق سوالات پوچھیں، اور میں تفصیلی، مددگار معلومات فراہم کروں گا۔ |
|
|
|
|
|
*نوٹ: میں ایک AI اسسٹنٹ ہوں۔ سنگین طبی مسائل کے لیے، ہمیشہ کوالیفائیڈ ہیلتھ کیئر پروفیشنل سے مشورہ کریں۔* |
|
|
""" |
|
|
|
|
|
def _format_heart_response(self, language): |
|
|
knowledge = self.medical_knowledge_base['heart_disease'] |
|
|
if language == 'English': |
|
|
return f""" |
|
|
**❤️ Comprehensive Heart Health Information** |
|
|
|
|
|
**🚨 Common Symptoms:** |
|
|
{chr(10).join(['• ' + symptom for symptom in knowledge['symptoms']])} |
|
|
|
|
|
**⚠️ Risk Factors:** |
|
|
{chr(10).join(['• ' + factor for factor in knowledge['risk_factors']])} |
|
|
|
|
|
**🛡️ Prevention Strategies:** |
|
|
{chr(10).join(['• ' + tip for tip in knowledge['prevention']])} |
|
|
|
|
|
**🚑 Emergency Warning Signs (Seek Immediate Care):** |
|
|
{chr(10).join(['• ' + sign for sign in knowledge['emergency_signs']])} |
|
|
|
|
|
**📊 Recommended Monitoring:** |
|
|
• Regular blood pressure checks |
|
|
• Cholesterol levels annually if high risk |
|
|
• ECG if symptoms present |
|
|
• Stress test if recommended by doctor |
|
|
|
|
|
*🔬 Clinical Note: Early detection saves lives. Regular check-ups are crucial for heart health.* |
|
|
""" |
|
|
else: |
|
|
return f""" |
|
|
**❤️ دل کی صحت کی جامع معلومات** |
|
|
|
|
|
**🚨 عام علامات:** |
|
|
{chr(10).join(['• ' + symptom for symptom in ['سینے میں درد یا بے چینی', 'سانس لینے میں دشواری', 'بازوؤں، گردن، جبڑے میں درد', 'متلی', 'تھکاوٹ', 'چکر آنا']])} |
|
|
|
|
|
**⚠️ خطرے کے عوامل:** |
|
|
{chr(10).join(['• ' + factor for factor in ['ہائی بلڈ پریشر', 'ہائی کولیسٹرول', 'سگریٹ نوشی', 'ذیابیطس', 'موٹاپا', 'خاندانی تاریخ', 'جسمانی غیر فعالیت']])} |
|
|
|
|
|
**🛡️ بچاؤ کی حکمت عملی:** |
|
|
{chr(10).join(['• ' + tip for tip in ['سیر شدہ چکنائی سے پاک صحت مند غذا', 'روزانہ 30 منٹ باقاعدہ ورزش', 'سگریٹ نوشی سے پرہیز', 'وزن کا انتظام', 'تناؤ کا انتظام', 'باقاعدہ چیک اپ']])} |
|
|
|
|
|
**🚑 ہنگامی انتباہی علامات (فوری علاج حاصل کریں):** |
|
|
{chr(10).join(['• ' + sign for sign in ['شدید سینے میں درد', 'سانس لینے میں شدید دشواری', 'بیہوش ہونا', 'تیز دل کی دھڑکن', 'بازو/کندھوں میں پھیلنے والا درد']])} |
|
|
|
|
|
**📊 تجویز کردہ نگرانی:** |
|
|
• بلڈ پریشر کی باقاعدہ جانچ |
|
|
• اگر خطرہ زیادہ ہو تو سالانہ کولیسٹرول کی سطح |
|
|
• اگر علامات موجود ہوں تو ECG |
|
|
• اگر ڈاکٹر تجویز کرے تو اسٹریس ٹیسٹ |
|
|
|
|
|
*🔬 کلینیکل نوٹ: ابتدائی تشخیص جان بچاتی ہے۔ دل کی صحت کے لیے باقاعدہ چیک اپ بہت ضروری ہیں۔* |
|
|
""" |
|
|
|
|
|
def _format_diabetes_response(self, language): |
|
|
knowledge = self.medical_knowledge_base['diabetes'] |
|
|
if language == 'English': |
|
|
return f""" |
|
|
**🩺 Comprehensive Diabetes Information** |
|
|
|
|
|
**🚨 Common Symptoms:** |
|
|
{chr(10).join(['• ' + symptom for symptom in knowledge['symptoms']])} |
|
|
|
|
|
**⚠️ Risk Factors:** |
|
|
{chr(10).join(['• ' + factor for factor in knowledge['risk_factors']])} |
|
|
|
|
|
**🛡️ Prevention & Management:** |
|
|
{chr(10).join(['• ' + tip for tip in knowledge['prevention']])} |
|
|
|
|
|
**🚑 Emergency Signs (Seek Immediate Care):** |
|
|
{chr(10).join(['• ' + sign for sign in knowledge['emergency_signs']])} |
|
|
|
|
|
**📊 Monitoring Guidelines:** |
|
|
• Fasting blood sugar: 80-130 mg/dL |
|
|
• Post-meal blood sugar: <180 mg/dL |
|
|
• HbA1c: <7.0% (quarterly if uncontrolled) |
|
|
• Regular foot and eye examinations |
|
|
|
|
|
*🔬 Clinical Note: Consistent monitoring and lifestyle management are key to diabetes control.* |
|
|
""" |
|
|
else: |
|
|
return f""" |
|
|
**🩺 ذیابیطس کی جامع معلومات** |
|
|
|
|
|
**🚨 عام علامات:** |
|
|
{chr(10).join(['• ' + symptom for symptom in ['زیادہ پیاس اور بھوک لگنا', 'بار بار پیشاب آنا', 'تھکاوٹ', 'دھندلا نظر آنا', 'زخموں کا دیر سے بھرنا', 'بے وجہ وزن میں کمی']])} |
|
|
|
|
|
**⚠️ خطرے کے عوامل:** |
|
|
{chr(10).join(['• ' + factor for factor in ['خاندانی تاریخ', 'وزن زیادہ ہونا (BMI > 25)', 'ہائی بلڈ پریشر', 'جسمانی غیر فعالیت', '45 سال سے زیادہ عمر', 'حمل کی ذیابیطس کی تاریخ']])} |
|
|
|
|
|
**🛡️ بچاؤ اور انتظام:** |
|
|
{chr(10).join(['• ' + tip for tip in ['کنٹرول کاربوہائیڈریٹ کے ساتھ متوازن غذا', 'باقاعدہ جسمانی سرگرمی', 'وزن کا انتظام', 'بلڈ شوگر مانیٹرنگ', 'باقاعدہ صحت کی اسکریننگ']])} |
|
|
|
|
|
**🚑 ہنگامی علامات (فوری علاج حاصل کریں):** |
|
|
{chr(10).join(['• ' + sign for sign in ['بلڈ شوگر >300 mg/dL یا <70 mg/dL', 'الجھن یا بے ترتیبی', 'پھل کی سی بو والی سانس', 'تیز سانس لینا', 'ہوش کا ضیاع']])} |
|
|
|
|
|
**📊 نگرانی کے رہنما اصول:** |
|
|
• فاسٹنگ بلڈ شوگر: 80-130 mg/dL |
|
|
• کھانے کے بعد بلڈ شوگر: <180 mg/dL |
|
|
• HbA1c: <7.0% (اگر کنٹرول نہ ہو تو سہ ماہی) |
|
|
• پاؤں اور آنکھوں کا باقاعدہ معائنہ |
|
|
|
|
|
*🔬 کلینیکل نوٹ: مستقل نگرانی اور طرز زندگی کا انتظام ذیابیطس کے کنٹرول کی کلید ہے۔* |
|
|
""" |
|
|
|
|
|
def _format_hypertension_response(self, language): |
|
|
knowledge = self.medical_knowledge_base['hypertension'] |
|
|
if language == 'English': |
|
|
return f""" |
|
|
**💓 Comprehensive Blood Pressure Information** |
|
|
|
|
|
**🚨 Common Symptoms:** |
|
|
{chr(10).join(['• ' + symptom for symptom in knowledge['symptoms']])} |
|
|
|
|
|
**⚠️ Risk Factors:** |
|
|
{chr(10).join(['• ' + factor for factor in knowledge['risk_factors']])} |
|
|
|
|
|
**🛡️ Prevention & Control:** |
|
|
{chr(10).join(['• ' + tip for tip in knowledge['prevention']])} |
|
|
|
|
|
**🚑 Hypertensive Emergency Signs:** |
|
|
{chr(10).join(['• ' + sign for sign in knowledge['emergency_signs']])} |
|
|
|
|
|
**📊 Blood Pressure Classification:** |
|
|
• Normal: <120/80 mmHg |
|
|
• Elevated: 120-129/<80 mmHg |
|
|
• Stage 1 Hypertension: 130-139/80-89 mmHg |
|
|
• Stage 2 Hypertension: ≥140/90 mmHg |
|
|
|
|
|
*🔬 Clinical Note: Silent killer - often no symptoms. Regular monitoring is essential.* |
|
|
""" |
|
|
else: |
|
|
return f""" |
|
|
**💓 بلڈ پریشر کی جامع معلومات** |
|
|
|
|
|
**🚨 عام علامات:** |
|
|
{chr(10).join(['• ' + symptom for symptom in ['سر درد', 'چکر آنا', 'دھندلا نظر آنا', 'سانس لینے میں دشواری', 'سینے میں درد', 'ناک سے خون آنا']])} |
|
|
|
|
|
**⚠️ خطرے کے عوامل:** |
|
|
{chr(10).join(['• ' + factor for factor in ['خاندانی تاریخ', '65 سال سے زیادہ عمر', 'موٹاپا', 'زیادہ نمک کا استعمال', 'تناؤ', 'شراب کا استعمال', 'سگریٹ نوشی']])} |
|
|
|
|
|
**🛡️ بچاؤ اور کنٹرول:** |
|
|
{chr(10).join(['• ' + tip for tip in ['ڈیش ڈائٹ (کم سوڈیم)', 'باقاعدہ ایروبک ورزش', 'وزن کا انتظام', 'تناؤ میں کمی', 'شراب کو محدود کریں', 'سگریٹ نوشی سے پرہیز']])} |
|
|
|
|
|
**🚑 ہائی بلڈ پریشر کی ہنگامی علامات:** |
|
|
{chr(10).join(['• ' + sign for sign in ['شدید سر درد', 'سینے میں درد', 'سانس لینے میں دشواری', 'بینائی میں تبدیلی', 'الجھن', 'دورے']])} |
|
|
|
|
|
**📊 بلڈ پریشر کی درجہ بندی:** |
|
|
• نارمل: <120/80 mmHg |
|
|
• بلند: 120-129/<80 mmHg |
|
|
• اسٹیج 1 ہائی بلڈ پریشر: 130-139/80-89 mmHg |
|
|
• اسٹیج 2 ہائی بلڈ پریشر: ≥140/90 mmHg |
|
|
|
|
|
*🔬 کلینیکل نوٹ: خاموش قاتل - اکثر کوئی علامات نہیں ہوتیں۔ باقاعدہ نگرانی ضروری ہے۔* |
|
|
""" |
|
|
|
|
|
def _format_nutrition_response(self, language): |
|
|
knowledge = self.medical_knowledge_base['general_health'] |
|
|
if language == 'English': |
|
|
return f""" |
|
|
**🍎 Comprehensive Nutrition Guide** |
|
|
|
|
|
**🥦 Healthy Eating Principles:** |
|
|
{chr(10).join(['• ' + tip for tip in knowledge['nutrition']])} |
|
|
|
|
|
**🎯 Specific Recommendations:** |
|
|
• **Heart Health**: Mediterranean diet, omega-3 rich foods |
|
|
• **Diabetes**: Controlled carb intake, high fiber |
|
|
• **Hypertension**: Low sodium (<2300mg/day), potassium-rich foods |
|
|
• **Weight Management**: Calorie control, portion management |
|
|
|
|
|
**🚫 Foods to Limit:** |
|
|
• Processed and packaged foods |
|
|
• Sugary drinks and sweets |
|
|
• High sodium snacks |
|
|
• Saturated and trans fats |
|
|
|
|
|
**💡 Pakistani Dietary Adaptations:** |
|
|
• Choose whole wheat chapati over refined flour |
|
|
• Include lentils (daal) and legumes regularly |
|
|
• Use healthy cooking oils (canola, olive) |
|
|
• Limit ghee and butter usage |
|
|
|
|
|
*Remember: Balanced nutrition is foundation of good health.* |
|
|
""" |
|
|
else: |
|
|
return f""" |
|
|
**🍎 غذائیت کی جامع گائیڈ** |
|
|
|
|
|
**🥦 صحت مند کھانے کے اصول:** |
|
|
{chr(10).join(['• ' + tip for tip in ['روزانہ 5-9 سرونگ پھل/سبزیاں کھائیں', 'ریفائنڈ کی بجائے سارا اناج منتخب کریں', 'لیان پروٹین شامل کریں', 'ہائیڈریٹ رہیں (8-10 گلاس پانی)', 'پراسیسڈ فوڈز اور چینی کو محدود کریں']])} |
|
|
|
|
|
**🎯 مخصوص سفارشات:** |
|
|
• **دل کی صحت**: بحیرہ روم کی غذا، اومیگا 3 سے بھرپور غذائیں |
|
|
• **ذیابیطس**: کنٹرول کاربوہائیڈریٹ انٹیک، زیادہ فائبر |
|
|
• **ہائی بلڈ پریشر**: کم سوڈیم (<2300mg/day)، پوٹاشیم سے بھرپور غذائیں |
|
|
• **وزن کا انتظام**: کیلوری کنٹرول، حصے کا انتظام |
|
|
|
|
|
**🚫 محدود کرنے والی غذائیں:** |
|
|
• پراسیسڈ اور پیکجڈ فوڈز |
|
|
• میٹھے مشروبات اور مٹھائیاں |
|
|
• ہائی سوڈیم اسنیکس |
|
|
• سیر شدہ اور ٹرانس فیٹس |
|
|
|
|
|
**💡 پاکستانی غذائی موافقت:** |
|
|
• ریفائنڈ آٹے کی بجائے whole wheat چپاتی منتخب کریں |
|
|
• دالوں اور پھلیوں کو باقاعدہ شامل کریں |
|
|
• صحت مند ککنگ آئلز (کینولا، زیتون) استعمال کریں |
|
|
• گھی اور مکھن کے استعمال کو محدود کریں |
|
|
|
|
|
*یاد رکھیں: متوازن غذائیت اچھی صحت کی بنیاد ہے۔* |
|
|
""" |
|
|
|
|
|
def _format_exercise_response(self, language): |
|
|
knowledge = self.medical_knowledge_base['general_health'] |
|
|
if language == 'English': |
|
|
return f""" |
|
|
**💪 Comprehensive Exercise Guide** |
|
|
|
|
|
**🏃♂️ Exercise Recommendations:** |
|
|
{chr(10).join(['• ' + tip for tip in knowledge['exercise']])} |
|
|
|
|
|
**🎯 Disease-Specific Exercise:** |
|
|
• **Heart Health**: 30 mins moderate cardio daily |
|
|
• **Diabetes**: Combination of cardio and strength training |
|
|
• **Hypertension**: Regular aerobic exercise |
|
|
• **Weight Management**: 300+ mins moderate exercise weekly |
|
|
|
|
|
**🌞 Pakistani Climate Considerations:** |
|
|
• Exercise in cooler morning/evening hours |
|
|
• Stay hydrated with water and electrolytes |
|
|
• Wear light, breathable clothing |
|
|
• Listen to your body in hot weather |
|
|
|
|
|
**🔄 Exercise Types:** |
|
|
• **Cardio**: Walking, jogging, cycling, swimming |
|
|
• **Strength**: Weight training, resistance bands |
|
|
• **Flexibility**: Yoga, stretching |
|
|
• **Balance**: Tai chi, balance exercises |
|
|
|
|
|
*Important: Consult doctor before starting new exercise program.* |
|
|
""" |
|
|
else: |
|
|
return f""" |
|
|
**💪 ورزش کی جامع گائیڈ** |
|
|
|
|
|
**🏃♂️ ورزش کی سفارشات:** |
|
|
{chr(10).join(['• ' + tip for tip in ['ہفتے میں 150 منٹ اعتدال پسند ورزش', 'ہفتے میں 2 بار طاقت کی تربیت', 'پورے دن متحرک رہیں', 'لچک کی ورزشیں شامل کریں', 'ورک آؤٹس کے درمیان مناسب آرام حاصل کریں']])} |
|
|
|
|
|
**🎯 بیماری کی مخصوص ورزش:** |
|
|
• **دل کی صحت**: روزانہ 30 منٹ اعتدال پسند کارڈیو |
|
|
• **ذیابیطس**: کارڈیو اور طاقت کی تربیت کا مجموعہ |
|
|
• **ہائی بلڈ پریشر**: باقاعدہ ایروبک ورزش |
|
|
• **وزن کا انتظام**: ہفتے میں 300+ منٹ اعتدال پسند ورزش |
|
|
|
|
|
**🌞 پاکستانی آب و ہوا کے تحفظات:** |
|
|
• ٹھنڈے صبح/شام کے اوقات میں ورزش کریں |
|
|
• پانی اور الیکٹرولائٹس کے ساتھ ہائیڈریٹ رہیں |
|
|
• ہلکے، ہوا دار کپڑے پہنیں |
|
|
• گرم موسم میں اپنے جسم کی بات سنیں |
|
|
|
|
|
**🔄 ورزش کی اقسام:** |
|
|
• **کارڈیو**: چہل قدمی، جاگنگ، سائیکل چلانا، تیراکی |
|
|
• **طاقت**: وزن کی تربیت، مزاحمتی بینڈ |
|
|
• **لچک**: یوگا، اسٹریچنگ |
|
|
• **توازن**: تائی چی، توازن کی ورزشیں |
|
|
|
|
|
*اہم: نئی ورزش پروگرام شروع کرنے سے پہلے ڈاکٹر سے مشورہ کریں۔* |
|
|
""" |
|
|
|
|
|
def _format_symptoms_response(self, language): |
|
|
if language == 'English': |
|
|
return """ |
|
|
**🔍 Symptom Assessment Guidance** |
|
|
|
|
|
**🩺 When to Seek Medical Care:** |
|
|
• Persistent fever above 103°F (39.4°C) |
|
|
• Difficulty breathing or chest pain |
|
|
• Severe abdominal pain |
|
|
• Sudden dizziness, weakness, or confusion |
|
|
• Unexplained weight loss (>10% body weight) |
|
|
• Symptoms lasting more than 2 weeks |
|
|
• Worsening of chronic conditions |
|
|
|
|
|
**🏠 Self-Care Tips:** |
|
|
• Rest and adequate hydration |
|
|
• Monitor symptoms and temperature regularly |
|
|
• Use over-the-counter medications as directed |
|
|
• Apply cold/heat packs as appropriate |
|
|
• Maintain proper nutrition |
|
|
|
|
|
**🚨 Emergency Warning Signs (Go to ER):** |
|
|
• Difficulty breathing or shortness of breath |
|
|
• Chest pain or pressure lasting >5 minutes |
|
|
• Severe bleeding that doesn't stop |
|
|
• Sudden severe pain anywhere in body |
|
|
• Loss of consciousness or fainting |
|
|
• Sudden vision changes |
|
|
• Difficulty speaking or confusion |
|
|
|
|
|
*⚠️ Important: This is general guidance. Always consult healthcare professional for proper diagnosis.* |
|
|
""" |
|
|
else: |
|
|
return """ |
|
|
**🔍 علامات کی تشخیص کی رہنمائی** |
|
|
|
|
|
**🩺 طبی دیکھ بھال کب حاصل کریں:** |
|
|
• 103°F (39.4°C) سے اوپر مستقل بخار |
|
|
• سانس لینے میں دشواری یا سینے میں درد |
|
|
• شدید پیٹ کا درد |
|
|
• اچانک چکر آنا، کمزوری، یا الجھن |
|
|
• بے وجہ وزن میں کمی (>10% جسمانی وزن) |
|
|
• 2 ہفتے سے زیادہ علامات برقرار رہنا |
|
|
• دائمی حالات کا بگڑنا |
|
|
|
|
|
**🏠 خود کی دیکھ بھال کے نکات:** |
|
|
• آرام اور مناسب ہائیڈریشن |
|
|
• علامات اور درجہ حرارت کی باقاعدہ نگرانی |
|
|
• ہدایت کے مطابق اوور دی کاؤنٹر ادویات استعمال کریں |
|
|
• حسب مناسب کولڈ/ہیٹ پیکس لگائیں |
|
|
• مناسب غذائیت برقرار رکھیں |
|
|
|
|
|
**🚨 ہنگامی انتباہی علامات (ایمرجنسی روم جائیں):** |
|
|
• سانس لینے میں دشواری یا سانس کی قلت |
|
|
• 5 منٹ سے زیادہ سینے میں درد یا دباؤ |
|
|
• شدید خون بہنا جو رک نہیں رہا |
|
|
• جسم میں کہیں بھی اچانک شدید درد |
|
|
• ہوش کا ضیاع یا بیہوشی |
|
|
• اچانک بینائی میں تبدیلی |
|
|
• بولنے میں دشواری یا الجھن |
|
|
|
|
|
*⚠️ اہم: یہ عام رہنمائی ہے۔ مناسب تشخیص کے لیے ہمیشہ ہیلتھ کیئر پروفیشنل سے مشورہ کریں۔* |
|
|
""" |
|
|
|
|
|
def _format_medication_response(self, language): |
|
|
if language == 'English': |
|
|
return """ |
|
|
**💊 Medication Safety & Information** |
|
|
|
|
|
**📋 General Medication Guidelines:** |
|
|
• Take medications exactly as prescribed |
|
|
• Never share prescriptions with others |
|
|
• Keep updated medication list with you |
|
|
• Inform all doctors about all medications |
|
|
• Understand purpose and side effects of each medicine |
|
|
|
|
|
**⚠️ Common Medication Categories:** |
|
|
• **Heart**: Beta-blockers, ACE inhibitors, statins |
|
|
• **Diabetes**: Metformin, insulin, SGLT2 inhibitors |
|
|
• **Hypertension**: Diuretics, calcium channel blockers |
|
|
• **Pain**: NSAIDs, acetaminophen (use cautiously) |
|
|
|
|
|
**🚨 Medication Warning Signs:** |
|
|
• Severe allergic reactions (rash, swelling) |
|
|
• Difficulty breathing after taking medicine |
|
|
• Severe stomach pain or vomiting |
|
|
• Unusual bleeding or bruising |
|
|
• Confusion or hallucinations |
|
|
|
|
|
**💡 Important Reminders:** |
|
|
• Don't stop medications without doctor's advice |
|
|
• Report side effects to your doctor |
|
|
• Keep medications in original containers |
|
|
• Check expiration dates regularly |
|
|
|
|
|
*Note: Always follow your healthcare provider's specific instructions.* |
|
|
""" |
|
|
else: |
|
|
return """ |
|
|
**💊 دوائیوں کی حفاظت اور معلومات** |
|
|
|
|
|
**📋 عام دوائیوں کے رہنما اصول:** |
|
|
• دوائیں بالکل تجویز کردہ طریقے سے لیں |
|
|
• کبھی بھی دوسروں کے ساتھ نسخے شیئر نہ کریں |
|
|
• اپنے ساتھ اپ ڈیٹ شدہ دوائیوں کی فہرست رکھیں |
|
|
• تمام ڈاکٹروں کو تمام دوائیوں کے بارے میں بتائیں |
|
|
• ہر دوا کے مقصد اور مضر اثرات کو سمجھیں |
|
|
|
|
|
**⚠️ عام دوائیوں کی اقسام:** |
|
|
• **دل**: بیٹا بلاکرز، ACE inhibitors، statins |
|
|
• **ذیابیطس**: میٹفارمن، انسولین، SGLT2 inhibitors |
|
|
• **ہائی بلڈ پریشر**: ڈائیوریٹکس، کیلشیم چینل بلاکرز |
|
|
• **درد**: NSAIDs، acetaminophen (احتیاط سے استعمال کریں) |
|
|
|
|
|
**🚨 دوائیوں کی انتباہی علامات:** |
|
|
• شدید الرجک رد عمل (خارش، سوجن) |
|
|
• دوا لینے کے بعد سانس لینے میں دشواری |
|
|
• شدید پیٹ میں درد یا الٹی |
|
|
• غیر معمولی خون بہنا یا چوٹ لگنا |
|
|
• الجھن یا توہمات |
|
|
|
|
|
**💡 اہم یاد دہانیاں:** |
|
|
• ڈاکٹر کے مشورے کے بغیر دوائیں بند نہ کریں |
|
|
• اپنے ڈاکٹر کو مضر اثرات کی رپورٹ کریں |
|
|
• دوائیں اصل کنٹینرز میں رکھیں |
|
|
• میعاد ختم ہونے کی تاریخوں کو باقاعدگی سے چیک کریں |
|
|
|
|
|
*نوٹ: ہمیشہ اپنے ہیلتھ کیئر فراہم کرنے والے کی مخصوص ہدایات پر عمل کریں۔* |
|
|
""" |
|
|
|
|
|
def _format_emergency_response(self, language): |
|
|
if language == 'English': |
|
|
return """ |
|
|
**🚨 EMERGENCY MEDICAL GUIDANCE** |
|
|
|
|
|
**📞 Immediate Actions Required:** |
|
|
• Call emergency services (1122 in Pakistan) |
|
|
• Don't drive yourself to hospital |
|
|
• Keep patient calm and comfortable |
|
|
• Have medical information ready |
|
|
• Don't give food or drink |
|
|
|
|
|
**🏥 When to Go to Emergency Room:** |
|
|
• Chest pain or pressure |
|
|
• Difficulty breathing |
|
|
• Severe bleeding |
|
|
• Sudden weakness or paralysis |
|
|
• Severe burns |
|
|
• Poisoning or overdose |
|
|
• Seizures |
|
|
• Severe allergic reactions |
|
|
|
|
|
**🆘 First Aid Basics:** |
|
|
• **CPR**: Start if no breathing/pulse (30 compressions: 2 breaths) |
|
|
• **Bleeding**: Apply direct pressure |
|
|
• **Choking**: Perform Heimlich maneuver |
|
|
• **Burns**: Cool with running water |
|
|
• **Fainting**: Lay flat, elevate legs |
|
|
|
|
|
**📋 Emergency Preparedness:** |
|
|
• Keep emergency numbers handy |
|
|
• Know location of nearest hospital |
|
|
• Have medical history documented |
|
|
• Keep medications list updated |
|
|
|
|
|
*⚠️ THIS IS EMERGENCY GUIDANCE ONLY. SEEK PROFESSIONAL MEDICAL HELP IMMEDIATELY.* |
|
|
""" |
|
|
else: |
|
|
return """ |
|
|
**🚨 ہنگامی طبی رہنمائی** |
|
|
|
|
|
**📞 فوری کارروائی کی ضرورت ہے:** |
|
|
• ہنگامی خدمات کو کال کریں (پاکستان میں 1122) |
|
|
• خود ہسپتال نہ جائیں |
|
|
• مریض کو پرسکون اور آرام دہ رکھیں |
|
|
• طبی معلومات تیار رکھیں |
|
|
• کھانا یا پانی نہ دیں |
|
|
|
|
|
**🏥 ایمرجنسی روم کب جائیں:** |
|
|
• سینے میں درد یا دباؤ |
|
|
• سانس لینے میں دشواری |
|
|
• شدید خون بہنا |
|
|
• اچانک کمزوری یا فالج |
|
|
• شدید جلنے |
|
|
• زہر یا اوور ڈوز |
|
|
• دورے |
|
|
• شدید الرجک رد عمل |
|
|
|
|
|
**🆘 فرسٹ ایڈ کی بنیادی باتیں:** |
|
|
• **CPR**: اگر سانس/پلس نہ ہو تو شروع کریں (30 کمپریشن: 2 سانس) |
|
|
• **خون بہنا**: براہ راست دباؤ ڈالیں |
|
|
• **گلا گھٹنا**: ہیملک مانور انجام دیں |
|
|
• **جلنے**: پانی سے ٹھنڈا کریں |
|
|
• **بیہوشی**: سیدھا لیٹائیں، ٹانگیں اونچی کریں |
|
|
|
|
|
**📋 ہنگامی تیاری:** |
|
|
• ہنگامی نمبرز ہاتھ میں رکھیں |
|
|
• قریبی ہسپتال کا مقام جانیں |
|
|
• طبی تاریخ دستاویزی شکل میں رکھیں |
|
|
• دوائیوں کی فہرست اپ ڈیٹ رکھیں |
|
|
|
|
|
*⚠️ یہ صرف ہنگامی رہنمائی ہے۔ فوری طور پر پیشہ ورانہ طبی مدد حاصل کریں۔* |
|
|
""" |
|
|
|
|
|
def _format_general_health_response(self, language): |
|
|
knowledge = self.medical_knowledge_base['general_health'] |
|
|
if language == 'English': |
|
|
return f""" |
|
|
**🌿 Comprehensive Health & Wellness Guide** |
|
|
|
|
|
**💚 Lifestyle Recommendations:** |
|
|
{chr(10).join(['• ' + tip for tip in knowledge['lifestyle']])} |
|
|
|
|
|
**🛡️ Preventive Healthcare:** |
|
|
{chr(10).join(['• ' + tip for tip in knowledge['prevention']])} |
|
|
|
|
|
**🎯 Health Monitoring Schedule:** |
|
|
• **Daily**: Blood pressure (if hypertensive), blood sugar (if diabetic) |
|
|
• **Weekly**: Weight, exercise minutes |
|
|
• **Monthly**: Self-examinations (skin, breasts, testicles) |
|
|
• **Annual**: Complete physical, blood tests, dental checkup |
|
|
• **As recommended**: Cancer screenings, vision/hearing tests |
|
|
|
|
|
**🌟 Healthy Habits for Pakistan:** |
|
|
• Drink filtered/boiled water |
|
|
• Eat fresh, locally available fruits and vegetables |
|
|
• Practice good food hygiene |
|
|
• Get adequate sunlight exposure (vitamin D) |
|
|
• Maintain social connections and mental wellbeing |
|
|
|
|
|
*Remember: Small consistent changes lead to lasting health improvements!* |
|
|
""" |
|
|
else: |
|
|
return f""" |
|
|
**🌿 صحت اور تندرستی کی جامع گائیڈ** |
|
|
|
|
|
**💚 طرز زندگی کی سفارشات:** |
|
|
{chr(10).join(['• ' + tip for tip in ['رات میں 7-9 گھنٹے معیاری نیند', 'تناؤ کے انتظام کی تکنیکیں', 'سگریٹ نوشی سے پرہیز', 'شراب کو 1-2 ڈرنکس/دن تک محدود کریں', 'باقاعدہ صحت کی جانچ']])} |
|
|
|
|
|
**🛡️ احتیاطی ہیلتھ کیئر:** |
|
|
{chr(10).join(['• ' + tip for tip in ['سالانہ جسمانی امتحانات', 'ویکسینیشن اپ ڈیٹ', 'باقاعدہ ہاتھ دھونا', 'سورج سے تحفظ', 'ذہنی صحت کی دیکھ بھال']])} |
|
|
|
|
|
**🎯 صحت کی نگرانی کا شیڈول:** |
|
|
• **روزانہ**: بلڈ پریشر (اگر ہائی بلڈ پریشر ہو)، بلڈ شوگر (اگر ذیابیطس ہو) |
|
|
• **ہفتہ وار**: وزن، ورزش کے منٹ |
|
|
• **ماہانہ**: خود معائنہ (جلد، چھاتی، خصیے) |
|
|
• **سالانہ**: مکمل جسمانی، خون کے ٹیسٹ، دانتوں کا چیک اپ |
|
|
• **جیسا کہ تجویز کیا گیا ہے**: کینسر کی اسکریننگ، بینائی/سماعت کے ٹیسٹ |
|
|
|
|
|
**🌟 پاکستان کے لیے صحت مند عادات:** |
|
|
• فلٹر/ابلا ہوا پانی پیئیں |
|
|
• تازہ، مقامی طور پر دستیاب پھل اور سبزیاں کھائیں |
|
|
• اچھی غذا کی حفظان صحت کی مشق کریں |
|
|
• مناسب سورج کی روشنی (وٹامن ڈی) حاصل کریں |
|
|
• سماجی رابطے اور ذہنی تندرستی برقرار رکھیں |
|
|
|
|
|
*یاد رکھیں: چھوٹی مسلسل تبدیلیاں پائیدار صحت کی بہتری کا باعث بنتی ہیں!* |
|
|
""" |
|
|
|
|
|
def _format_default_response(self, language): |
|
|
if language == 'English': |
|
|
return """ |
|
|
**🤖 SehatAI Health Assistant** |
|
|
|
|
|
I understand you're asking about health topics. I'm specially trained to help with: |
|
|
|
|
|
**💚 Common Health Areas:** |
|
|
• Heart disease and cardiovascular health |
|
|
• Diabetes management and prevention |
|
|
• Blood pressure control |
|
|
• Nutrition and dietary guidance |
|
|
• Exercise and physical activity |
|
|
• Symptom assessment |
|
|
• Medication information |
|
|
• Emergency situations |
|
|
• General wellness and prevention |
|
|
|
|
|
**💡 How to Get Better Answers:** |
|
|
Please ask specific questions like: |
|
|
• "What are the symptoms of heart disease?" |
|
|
• "How to manage diabetes?" |
|
|
• "What foods help lower blood pressure?" |
|
|
• "Exercise recommendations for beginners" |
|
|
• "When to go to emergency room?" |
|
|
|
|
|
I'll provide detailed, accurate medical information to help you make informed health decisions. |
|
|
|
|
|
*⚠️ Remember: I'm an AI assistant. For personal medical advice, always consult qualified healthcare professionals.* |
|
|
""" |
|
|
else: |
|
|
return """ |
|
|
**🤖 سیحت اے آئی ہیلتھ اسسٹنٹ** |
|
|
|
|
|
میں سمجھتا ہوں کہ آپ صحت کے موضوعات کے بارے میں پوچھ رہے ہیں۔ میں خاص طور پر مدد کے لیے تربیت یافتہ ہوں: |
|
|
|
|
|
**💚 عام صحت کے شعبے:** |
|
|
• دل کی بیماری اور قلبی صحت |
|
|
• ذیابیطس کا انتظام اور روک تھام |
|
|
• بلڈ پریشر کنٹرول |
|
|
• غذائیت اور غذائی رہنمائی |
|
|
• ورزش اور جسمانی سرگرمی |
|
|
• علامات کی تشخیص |
|
|
• دوائیوں کی معلومات |
|
|
• ہنگامی حالات |
|
|
• عام تندرستی اور روک تھام |
|
|
|
|
|
**💡 بہتر جوابات کیسے حاصل کریں:** |
|
|
براہ کرم مخصوص سوالات پوچھیں جیسے: |
|
|
• "دل کی بیماری کی علامات کیا ہیں؟" |
|
|
• "ذیابیطس کا انتظام کیسے کریں؟" |
|
|
• "کون سی غذائیں بلڈ پریشر کم کرنے میں مدد کرتی ہیں؟" |
|
|
• "ابتدائی افراد کے لیے ورزش کی سفارشات" |
|
|
• "ایمرجنسی روم کب جائیں؟" |
|
|
|
|
|
میں آپ کو معلوماتی صحت کے فیصلے کرنے میں مدد کے لیے تفصیلی، درست طبی معلومات فراہم کروں گا۔ |
|
|
|
|
|
*⚠️ یاد رکھیں: میں ایک AI اسسٹنٹ ہوں۔ ذاتی طبی مشورے کے لیے، ہمیشہ کوالیفائیڈ ہیلتھ کیئر پروفیشنلز سے مشورہ کریں۔* |
|
|
""" |
|
|
|
|
|
class PDFReportGenerator: |
|
|
def __init__(self): |
|
|
self.pdf = FPDF() |
|
|
self.pdf.set_auto_page_break(auto=True, margin=15) |
|
|
|
|
|
def generate_report(self, patient_data, risk_scores, language='English'): |
|
|
self.pdf.add_page() |
|
|
|
|
|
|
|
|
self.pdf.set_font('Arial', 'B', 16) |
|
|
if language == 'English': |
|
|
self.pdf.cell(0, 10, 'SEHATAI MEDICAL ASSESSMENT REPORT', 0, 1, 'C') |
|
|
else: |
|
|
|
|
|
self.pdf.cell(0, 10, 'SEHATAI MEDICAL ASSESSMENT REPORT', 0, 1, 'C') |
|
|
|
|
|
self.pdf.ln(10) |
|
|
|
|
|
|
|
|
self.pdf.set_font('Arial', 'B', 12) |
|
|
self.pdf.cell(0, 10, 'Patient Information:', 0, 1) |
|
|
|
|
|
self.pdf.set_font('Arial', '', 10) |
|
|
patient_info = [ |
|
|
f"Name: {self._safe_encode(patient_data.get('name', 'Not provided'))}", |
|
|
f"Age: {patient_data.get('age', 'Not provided')} years", |
|
|
f"Gender: {self._safe_encode(patient_data.get('gender', 'Not provided'))}", |
|
|
f"Contact: {self._safe_encode(patient_data.get('contact', 'Not provided'))}" |
|
|
] |
|
|
|
|
|
for info in patient_info: |
|
|
self.pdf.cell(0, 8, info, 0, 1) |
|
|
|
|
|
self.pdf.ln(5) |
|
|
|
|
|
|
|
|
self.pdf.set_font('Arial', 'B', 12) |
|
|
self.pdf.cell(0, 10, 'Clinical Parameters:', 0, 1) |
|
|
|
|
|
self.pdf.set_font('Arial', '', 10) |
|
|
clinical_info = [ |
|
|
f"Blood Pressure: {patient_data.get('bp_systolic', 'N/A')}/{patient_data.get('bp_diastolic', 'N/A')} mmHg", |
|
|
f"Heart Rate: {patient_data.get('heart_rate', 'N/A')} bpm", |
|
|
f"Cholesterol: {patient_data.get('cholesterol', 'N/A')} mg/dL", |
|
|
f"Glucose: {patient_data.get('glucose', 'N/A')} mg/dL", |
|
|
f"BMI: {patient_data.get('bmi', 'N/A')}" |
|
|
] |
|
|
|
|
|
for info in clinical_info: |
|
|
self.pdf.cell(0, 8, info, 0, 1) |
|
|
|
|
|
self.pdf.ln(5) |
|
|
|
|
|
|
|
|
self.pdf.set_font('Arial', 'B', 12) |
|
|
self.pdf.cell(0, 10, 'Reported Symptoms:', 0, 1) |
|
|
|
|
|
self.pdf.set_font('Arial', '', 10) |
|
|
symptoms = patient_data.get('symptoms', {}) |
|
|
symptom_list = [ |
|
|
f"Chest Pain: {'Yes' if symptoms.get('chest_pain') else 'No'}", |
|
|
f"Shortness of Breath: {'Yes' if symptoms.get('shortness_breath') else 'No'}", |
|
|
f"Palpitations: {'Yes' if symptoms.get('palpitations') else 'No'}", |
|
|
f"Fatigue: {'Yes' if symptoms.get('fatigue') else 'No'}", |
|
|
f"Dizziness: {'Yes' if symptoms.get('dizziness') else 'No'}", |
|
|
f"Blurred Vision: {'Yes' if symptoms.get('blurred_vision') else 'No'}" |
|
|
] |
|
|
|
|
|
for symptom in symptom_list: |
|
|
self.pdf.cell(0, 8, symptom, 0, 1) |
|
|
|
|
|
self.pdf.ln(5) |
|
|
|
|
|
|
|
|
self.pdf.set_font('Arial', 'B', 12) |
|
|
self.pdf.cell(0, 10, 'Risk Assessment Results:', 0, 1) |
|
|
|
|
|
self.pdf.set_font('Arial', '', 10) |
|
|
risk_info = [ |
|
|
f"Heart Disease Risk: {risk_scores.get('heart', 0):.1%}", |
|
|
f"Diabetes Risk: {risk_scores.get('diabetes', 0):.1%}", |
|
|
f"Hypertension Risk: {risk_scores.get('hypertension', 0):.1%}", |
|
|
f"Overall Priority Score: {risk_scores.get('priority', 0):.1%}" |
|
|
] |
|
|
|
|
|
for info in risk_info: |
|
|
self.pdf.cell(0, 8, info, 0, 1) |
|
|
|
|
|
self.pdf.ln(5) |
|
|
|
|
|
|
|
|
self.pdf.set_font('Arial', 'B', 12) |
|
|
self.pdf.cell(0, 10, 'Clinical Recommendation:', 0, 1) |
|
|
|
|
|
self.pdf.set_font('Arial', '', 10) |
|
|
recommendation = self._safe_encode(risk_scores.get('recommendation', 'No recommendation available')) |
|
|
self.pdf.multi_cell(0, 8, recommendation) |
|
|
|
|
|
self.pdf.ln(10) |
|
|
|
|
|
|
|
|
self.pdf.set_font('Arial', 'I', 8) |
|
|
self.pdf.cell(0, 10, f'Generated by SehatAI on: {datetime.now().strftime("%Y-%m-%d %H:%M")}', 0, 1, 'C') |
|
|
|
|
|
return self.pdf.output(dest='S').encode('latin1', 'replace') |
|
|
|
|
|
def _safe_encode(self, text): |
|
|
"""Safely encode text for PDF generation""" |
|
|
if text is None: |
|
|
return "" |
|
|
try: |
|
|
return str(text) |
|
|
except: |
|
|
return "Encoding error" |
|
|
|
|
|
|
|
|
@st.cache_resource(show_spinner=False) |
|
|
def load_models(): |
|
|
models = {} |
|
|
scalers = {} |
|
|
|
|
|
try: |
|
|
|
|
|
if os.path.exists('heart_model.pkl'): |
|
|
models['heart'] = joblib.load('heart_model.pkl') |
|
|
st.success("✅ Heart disease model loaded successfully") |
|
|
else: |
|
|
st.warning("⚠️ Heart model file not found, using rule-based assessment") |
|
|
models['heart'] = None |
|
|
except Exception as e: |
|
|
st.warning(f"⚠️ Error loading heart model: {str(e)}") |
|
|
models['heart'] = None |
|
|
|
|
|
try: |
|
|
|
|
|
if os.path.exists('diabeties_model.pkl'): |
|
|
models['diabetes'] = joblib.load('diabeties_model.pkl') |
|
|
st.success("✅ Diabetes model loaded successfully") |
|
|
else: |
|
|
st.warning("⚠️ Diabetes model file not found, using rule-based assessment") |
|
|
models['diabetes'] = None |
|
|
except Exception as e: |
|
|
st.warning(f"⚠️ Error loading diabetes model: {str(e)}") |
|
|
models['diabetes'] = None |
|
|
|
|
|
try: |
|
|
|
|
|
if os.path.exists('hypertension_model.pkl'): |
|
|
models['hypertension'] = joblib.load('hypertension_model.pkl') |
|
|
st.success("✅ Hypertension model loaded successfully") |
|
|
else: |
|
|
st.warning("⚠️ Hypertension model file not found, using rule-based assessment") |
|
|
models['hypertension'] = None |
|
|
except Exception as e: |
|
|
st.warning(f"⚠️ Error loading hypertension model: {str(e)}") |
|
|
models['hypertension'] = None |
|
|
|
|
|
|
|
|
try: |
|
|
if os.path.exists('scaler.pkl'): |
|
|
scalers['default'] = joblib.load('scaler.pkl') |
|
|
st.success("✅ Scaler loaded successfully") |
|
|
except: |
|
|
st.warning("⚠️ Scaler not available, using standard scaling") |
|
|
scalers['default'] = None |
|
|
|
|
|
return models, scalers |
|
|
|
|
|
def calculate_priority_score(heart_risk, diabetes_risk, hypertension_risk): |
|
|
"""Calculate integrated priority score with clinical weighting""" |
|
|
|
|
|
priority = ( |
|
|
heart_risk * 0.45 + |
|
|
diabetes_risk * 0.25 + |
|
|
hypertension_risk * 0.30 |
|
|
) |
|
|
|
|
|
return min(1.0, priority) |
|
|
|
|
|
def get_priority_recommendation(priority_score, language='English'): |
|
|
"""Get priority-based recommendation with clinical thresholds""" |
|
|
if priority_score >= 0.75: |
|
|
if language == 'Urdu': |
|
|
return "EMERGENCY_CARE", "اعلی ترجیح - فوری ہنگامی علاج کی ضرورت", "risk-high" |
|
|
else: |
|
|
return "EMERGENCY_CARE", "High Priority - Immediate Emergency Care Required", "risk-high" |
|
|
elif priority_score >= 0.55: |
|
|
if language == 'Urdu': |
|
|
return "SAME_DAY_CONSULT", "درمیانی ترجیح - اسی دن مشورہ ضروری", "risk-medium" |
|
|
else: |
|
|
return "SAME_DAY_CONSULT", "Medium Priority - Same Day Consultation Required", "risk-medium" |
|
|
else: |
|
|
if language == 'Urdu': |
|
|
return "ROUTINE_APPOINTMENT", "کم ترجیح - روٹین اپائنٹمنٹ", "risk-low" |
|
|
else: |
|
|
return "ROUTINE_APPOINTMENT", "Low Priority - Routine Appointment", "risk-low" |
|
|
|
|
|
def validate_patient_data(age, bp_systolic, bp_diastolic, heart_rate): |
|
|
"""Validate patient data for realistic clinical values""" |
|
|
errors = [] |
|
|
|
|
|
if age < 1 or age > 120: |
|
|
errors.append("Age must be between 1 and 120 years") |
|
|
if bp_systolic < 70 or bp_systolic > 250: |
|
|
errors.append("Systolic BP must be between 70 and 250 mmHg") |
|
|
if bp_diastolic < 40 or bp_diastolic > 150: |
|
|
errors.append("Diastolic BP must be between 40 and 150 mmHg") |
|
|
if heart_rate < 30 or heart_rate > 200: |
|
|
errors.append("Heart rate must be between 30 and 200 bpm") |
|
|
|
|
|
return errors |
|
|
|
|
|
def predict_with_models(age, bp_systolic, bp_diastolic, heart_rate, cholesterol, glucose, bmi, symptoms, models, scalers): |
|
|
"""Predict risks using loaded ML models""" |
|
|
heart_risk, diabetes_risk, hypertension_risk = 0.0, 0.0, 0.0 |
|
|
|
|
|
try: |
|
|
|
|
|
if models['heart'] is not None: |
|
|
heart_features = np.array([[ |
|
|
age, bp_systolic, cholesterol, heart_rate, |
|
|
symptoms['chest_pain'], symptoms['shortness_breath'], |
|
|
symptoms['palpitations'], bmi, glucose |
|
|
]]) |
|
|
|
|
|
if scalers.get('default') is not None: |
|
|
heart_features = scalers['default'].transform(heart_features) |
|
|
|
|
|
heart_risk = models['heart'].predict_proba(heart_features)[0][1] |
|
|
else: |
|
|
heart_risk = predict_risk_rule_based_heart(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms) |
|
|
|
|
|
except Exception as e: |
|
|
heart_risk = predict_risk_rule_based_heart(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms) |
|
|
|
|
|
try: |
|
|
|
|
|
if models['diabetes'] is not None: |
|
|
diabetes_features = np.array([[ |
|
|
age, glucose, bmi, cholesterol, |
|
|
symptoms['fatigue'], symptoms['blurred_vision'], |
|
|
bp_systolic, heart_rate |
|
|
]]) |
|
|
|
|
|
if scalers.get('default') is not None: |
|
|
diabetes_features = scalers['default'].transform(diabetes_features) |
|
|
|
|
|
diabetes_risk = models['diabetes'].predict_proba(diabetes_features)[0][1] |
|
|
else: |
|
|
diabetes_risk = predict_risk_rule_based_diabetes(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms) |
|
|
|
|
|
except Exception as e: |
|
|
diabetes_risk = predict_risk_rule_based_diabetes(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms) |
|
|
|
|
|
try: |
|
|
|
|
|
if models['hypertension'] is not None: |
|
|
hypertension_features = np.array([[ |
|
|
age, bp_systolic, bp_diastolic, bmi, |
|
|
symptoms['dizziness'], symptoms['palpitations'], |
|
|
heart_rate, cholesterol |
|
|
]]) |
|
|
|
|
|
if scalers.get('default') is not None: |
|
|
hypertension_features = scalers['default'].transform(hypertension_features) |
|
|
|
|
|
hypertension_risk = models['hypertension'].predict_proba(hypertension_features)[0][1] |
|
|
else: |
|
|
hypertension_risk = predict_risk_rule_based_hypertension(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms) |
|
|
|
|
|
except Exception as e: |
|
|
hypertension_risk = predict_risk_rule_based_hypertension(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms) |
|
|
|
|
|
return heart_risk, diabetes_risk, hypertension_risk |
|
|
|
|
|
def predict_risk_rule_based_heart(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms): |
|
|
"""Rule-based heart risk prediction""" |
|
|
risk = 0.0 |
|
|
|
|
|
|
|
|
if age > 60: risk += 0.25 |
|
|
elif age > 45: risk += 0.15 |
|
|
elif age > 30: risk += 0.05 |
|
|
|
|
|
|
|
|
if bp_systolic > 180 or bp_diastolic > 120: risk += 0.30 |
|
|
elif bp_systolic > 140 or bp_diastolic > 90: risk += 0.20 |
|
|
elif bp_systolic > 130 or bp_diastolic > 85: risk += 0.10 |
|
|
|
|
|
|
|
|
if cholesterol > 240: risk += 0.20 |
|
|
elif cholesterol > 200: risk += 0.10 |
|
|
|
|
|
|
|
|
if bmi > 35: risk += 0.15 |
|
|
elif bmi > 30: risk += 0.10 |
|
|
elif bmi > 25: risk += 0.05 |
|
|
|
|
|
|
|
|
if glucose > 200: risk += 0.10 |
|
|
elif glucose > 126: risk += 0.05 |
|
|
|
|
|
|
|
|
if symptoms['chest_pain']: risk += 0.25 |
|
|
if symptoms['shortness_breath']: risk += 0.15 |
|
|
if symptoms['palpitations']: risk += 0.10 |
|
|
|
|
|
return min(0.95, risk) |
|
|
|
|
|
def predict_risk_rule_based_diabetes(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms): |
|
|
"""Rule-based diabetes risk prediction""" |
|
|
risk = 0.0 |
|
|
|
|
|
|
|
|
if age > 50: risk += 0.20 |
|
|
elif age > 40: risk += 0.10 |
|
|
elif age > 30: risk += 0.05 |
|
|
|
|
|
|
|
|
if glucose > 200: risk += 0.40 |
|
|
elif glucose > 126: risk += 0.30 |
|
|
elif glucose > 100: risk += 0.15 |
|
|
|
|
|
|
|
|
if bmi > 35: risk += 0.25 |
|
|
elif bmi > 30: risk += 0.15 |
|
|
elif bmi > 25: risk += 0.08 |
|
|
|
|
|
|
|
|
if bp_systolic > 140 or bp_diastolic > 90: risk += 0.10 |
|
|
|
|
|
|
|
|
if symptoms['fatigue']: risk += 0.10 |
|
|
if symptoms['blurred_vision']: risk += 0.08 |
|
|
|
|
|
return min(0.95, risk) |
|
|
|
|
|
def predict_risk_rule_based_hypertension(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms): |
|
|
"""Rule-based hypertension risk prediction""" |
|
|
risk = 0.0 |
|
|
|
|
|
|
|
|
if bp_systolic > 180 or bp_diastolic > 120: risk += 0.50 |
|
|
elif bp_systolic > 140 or bp_diastolic > 90: risk += 0.35 |
|
|
elif bp_systolic > 130 or bp_diastolic > 85: risk += 0.20 |
|
|
|
|
|
|
|
|
if age > 60: risk += 0.15 |
|
|
elif age > 45: risk += 0.08 |
|
|
|
|
|
|
|
|
if bmi > 30: risk += 0.15 |
|
|
elif bmi > 25: risk += 0.08 |
|
|
|
|
|
|
|
|
if symptoms['dizziness']: risk += 0.10 |
|
|
if symptoms['palpitations']: risk += 0.08 |
|
|
|
|
|
return min(0.95, risk) |
|
|
|
|
|
def create_download_link(pdf_data, filename, text): |
|
|
"""Create a download link for PDF""" |
|
|
b64 = base64.b64encode(pdf_data).decode() |
|
|
href = f'<a href="data:application/octet-stream;base64,{b64}" download="{filename}">{text}</a>' |
|
|
return href |
|
|
|
|
|
def main(): |
|
|
|
|
|
local_css() |
|
|
init_session_state() |
|
|
|
|
|
|
|
|
with st.spinner("🔄 Loading AI models..."): |
|
|
models, scalers = load_models() |
|
|
|
|
|
|
|
|
chatbot = HealthcareChatbot() |
|
|
|
|
|
|
|
|
col_lang, col_space = st.columns([1, 5]) |
|
|
with col_lang: |
|
|
st.markdown('<div class="pakistan-flag">🇵🇰</div>', unsafe_allow_html=True) |
|
|
language = st.selectbox("Language", ["English", "Urdu"], key="language_selector", label_visibility="collapsed") |
|
|
st.session_state.current_language = language |
|
|
|
|
|
|
|
|
st.markdown('<h1 class="main-header">🏥 SehatAI</h1>', unsafe_allow_html=True) |
|
|
if language == "English": |
|
|
st.markdown('<h3 style="text-align: center; color: #00612A; margin-bottom: 20px;">Smart Healthcare Triage & Risk Assessment System</h3>', unsafe_allow_html=True) |
|
|
else: |
|
|
st.markdown('<h3 style="text-align: center; color: #00612A; margin-bottom: 20px;">ذہین ہیلتھ کیئر ٹریج اور خطرے کی تشخیص کا نظام</h3>', unsafe_allow_html=True) |
|
|
|
|
|
|
|
|
import random |
|
|
quote = random.choice(HEALTHCARE_QUOTES) |
|
|
|
|
|
st.markdown(f''' |
|
|
<div class="quote-section"> |
|
|
<div class="quote-text">"{quote['english']}"</div> |
|
|
<div class="quote-text">"{quote['urdu']}"</div> |
|
|
<div class="quote-author">- {quote['author']}</div> |
|
|
</div> |
|
|
''', unsafe_allow_html=True) |
|
|
|
|
|
|
|
|
if language == "English": |
|
|
tab_names = ["Patient Assessment", "Health Assistant", "Medical Reports"] |
|
|
else: |
|
|
tab_names = ["مریض تشخیص", "ہیلتھ اسسٹنٹ", "طبی رپورٹس"] |
|
|
|
|
|
tab1, tab2, tab3 = st.tabs(tab_names) |
|
|
|
|
|
with tab1: |
|
|
|
|
|
st.markdown('<div class="section-container">', unsafe_allow_html=True) |
|
|
|
|
|
if language == "English": |
|
|
st.markdown('<h2 style="color: #00401A; border-bottom: 3px solid #00401A; padding-bottom: 10px;">👨⚕️ Comprehensive Patient Assessment</h2>', unsafe_allow_html=True) |
|
|
st.write("Complete the following form for comprehensive patient risk assessment and priority scoring") |
|
|
else: |
|
|
st.markdown('<h2 style="color: #00401A; border-bottom: 3px solid #00401A; padding-bottom: 10px;">👨⚕️ جامع مریض تشخیص</h2>', unsafe_allow_html=True) |
|
|
st.write("جامع مریض کے خطرے کی تشخیص اور ترجیحی اسکورنگ کے لیے درج ذیل فارم کو مکمل کریں") |
|
|
|
|
|
with st.form("patient_assessment_form"): |
|
|
col1, col2 = st.columns(2) |
|
|
|
|
|
with col1: |
|
|
|
|
|
if language == "English": |
|
|
st.subheader("Personal Information") |
|
|
name = st.text_input("Full Name", placeholder="Enter patient's full name") |
|
|
age = st.number_input("Age", min_value=1, max_value=120, value=45, |
|
|
help="Patient's age in years") |
|
|
gender = st.selectbox("Gender", ["Male", "Female", "Other"]) |
|
|
contact = st.text_input("Contact Number", placeholder="03XX-XXXXXXX") |
|
|
else: |
|
|
st.subheader("ذاتی معلومات") |
|
|
name = st.text_input("مکمل نام", placeholder="مریض کا مکمل نام درج کریں") |
|
|
age = st.number_input("عمر", min_value=1, max_value=120, value=45, |
|
|
help="مریض کی عمر سالوں میں") |
|
|
gender = st.selectbox("جنس", ["مرد", "عورت", "دیگر"]) |
|
|
contact = st.text_input("رابطہ نمبر", placeholder="03XX-XXXXXXX") |
|
|
|
|
|
with col2: |
|
|
|
|
|
if language == "English": |
|
|
st.subheader("Clinical Parameters") |
|
|
bp_systolic = st.slider("Blood Pressure (systolic)", |
|
|
min_value=70, max_value=250, value=120, |
|
|
help="Systolic blood pressure in mmHg") |
|
|
bp_diastolic = st.slider("Blood Pressure (diastolic)", |
|
|
min_value=40, max_value=150, value=80, |
|
|
help="Diastolic blood pressure in mmHg") |
|
|
heart_rate = st.slider("Heart Rate (bpm)", |
|
|
min_value=30, max_value=200, value=72, |
|
|
help="Heart beats per minute") |
|
|
cholesterol = st.slider("Cholesterol Level (mg/dL)", |
|
|
min_value=100, max_value=400, value=180) |
|
|
glucose = st.slider("Blood Glucose (mg/dL)", |
|
|
min_value=50, max_value=500, value=95) |
|
|
bmi = st.slider("BMI", min_value=15.0, max_value=40.0, value=23.5, step=0.1) |
|
|
else: |
|
|
st.subheader("کلینیکل پیرامیٹرز") |
|
|
bp_systolic = st.slider("بلڈ پریشر (سسٹولک)", |
|
|
min_value=70, max_value=250, value=120, |
|
|
help="سسٹولک بلڈ پریشر mmHg میں") |
|
|
bp_diastolic = st.slider("بلڈ پریشر (ڈائیسٹولک)", |
|
|
min_value=40, max_value=150, value=80, |
|
|
help="ڈائیسٹولک بلڈ پریشر mmHg میں") |
|
|
heart_rate = st.slider("دل کی دھڑکن (bpm)", |
|
|
min_value=30, max_value=200, value=72, |
|
|
help="دل کی دھڑکن فی منٹ") |
|
|
cholesterol = st.slider("کولیسٹرول کی سطح (mg/dL)", |
|
|
min_value=100, max_value=400, value=180) |
|
|
glucose = st.slider("خون میں گلوکوز (mg/dL)", |
|
|
min_value=50, max_value=500, value=95) |
|
|
bmi = st.slider("باڈی ماس انڈیکس", min_value=15.0, max_value=40.0, value=23.5, step=0.1) |
|
|
|
|
|
|
|
|
if language == "English": |
|
|
st.subheader("Reported Symptoms") |
|
|
col3, col4 = st.columns(2) |
|
|
with col3: |
|
|
chest_pain = st.checkbox("Chest Pain or Discomfort") |
|
|
shortness_breath = st.checkbox("Shortness of Breath") |
|
|
palpitations = st.checkbox("Heart Palpitations") |
|
|
with col4: |
|
|
fatigue = st.checkbox("Persistent Fatigue") |
|
|
dizziness = st.checkbox("Dizziness or Lightheadedness") |
|
|
blurred_vision = st.checkbox("Blurred Vision") |
|
|
else: |
|
|
st.subheader("رپورٹ کردہ علامات") |
|
|
col3, col4 = st.columns(2) |
|
|
with col3: |
|
|
chest_pain = st.checkbox("سینے میں درد یا بے چینی") |
|
|
shortness_breath = st.checkbox("سانس لینے میں دشواری") |
|
|
palpitations = st.checkbox("دل کی دھڑکن میں اضافہ") |
|
|
with col4: |
|
|
fatigue = st.checkbox("مسلسل تھکاوٹ") |
|
|
dizziness = st.checkbox("چکر آنا یا سر ہلکا محسوس ہونا") |
|
|
blurred_vision = st.checkbox("دھندلا نظر آنا") |
|
|
|
|
|
|
|
|
if language == "English": |
|
|
assess_button = st.form_submit_button("🚀 Calculate Risk Score & Priority", |
|
|
use_container_width=True) |
|
|
else: |
|
|
assess_button = st.form_submit_button("🚀 خطرے کا اسکور اور ترجیح معلوم کریں", |
|
|
use_container_width=True) |
|
|
|
|
|
if assess_button: |
|
|
|
|
|
validation_errors = validate_patient_data(age, bp_systolic, bp_diastolic, heart_rate) |
|
|
|
|
|
if validation_errors: |
|
|
for error in validation_errors: |
|
|
st.error(f"❌ {error}") |
|
|
else: |
|
|
try: |
|
|
with st.spinner("🔍 Analyzing patient data and calculating risks..."): |
|
|
|
|
|
symptoms_dict = { |
|
|
'chest_pain': chest_pain, |
|
|
'shortness_breath': shortness_breath, |
|
|
'palpitations': palpitations, |
|
|
'fatigue': fatigue, |
|
|
'dizziness': dizziness, |
|
|
'blurred_vision': blurred_vision |
|
|
} |
|
|
|
|
|
|
|
|
st.session_state.patient_data = { |
|
|
'name': name, |
|
|
'age': age, |
|
|
'gender': gender, |
|
|
'contact': contact, |
|
|
'bp_systolic': bp_systolic, |
|
|
'bp_diastolic': bp_diastolic, |
|
|
'heart_rate': heart_rate, |
|
|
'cholesterol': cholesterol, |
|
|
'glucose': glucose, |
|
|
'bmi': bmi, |
|
|
'symptoms': symptoms_dict |
|
|
} |
|
|
|
|
|
|
|
|
heart_risk, diabetes_risk, hypertension_risk = predict_with_models( |
|
|
age, bp_systolic, bp_diastolic, heart_rate, |
|
|
cholesterol, glucose, bmi, symptoms_dict, models, scalers |
|
|
) |
|
|
|
|
|
|
|
|
priority_score = calculate_priority_score( |
|
|
heart_risk, diabetes_risk, hypertension_risk |
|
|
) |
|
|
|
|
|
priority_level, recommendation, risk_class = get_priority_recommendation( |
|
|
priority_score, language |
|
|
) |
|
|
|
|
|
|
|
|
st.session_state.risk_scores = { |
|
|
'heart': heart_risk, |
|
|
'diabetes': diabetes_risk, |
|
|
'hypertension': hypertension_risk, |
|
|
'priority': priority_score, |
|
|
'recommendation': recommendation, |
|
|
'level': priority_level |
|
|
} |
|
|
|
|
|
|
|
|
st.session_state.assessment_history.append({ |
|
|
'timestamp': datetime.now(), |
|
|
'patient_data': st.session_state.patient_data.copy(), |
|
|
'risk_scores': st.session_state.risk_scores.copy() |
|
|
}) |
|
|
|
|
|
|
|
|
st.markdown("---") |
|
|
st.success("✅ Risk assessment completed successfully!") |
|
|
|
|
|
|
|
|
if language == "English": |
|
|
st.subheader("📊 Disease Risk Assessment Dashboard") |
|
|
else: |
|
|
st.subheader("📊 بیماری کے خطرے کی تشخیص ڈیش بورڈ") |
|
|
|
|
|
col5, col6, col7, col8 = st.columns(4) |
|
|
|
|
|
risk_metrics = [ |
|
|
(heart_risk, "Heart Disease", "❤️", "#FF6B6B"), |
|
|
(diabetes_risk, "Diabetes", "🩺", "#4ECDC4"), |
|
|
(hypertension_risk, "Hypertension", "💓", "#45B7D1"), |
|
|
(priority_score, "Priority Score", "🎯", "#96CEB4") |
|
|
] |
|
|
|
|
|
for (value, title, emoji, color), col in zip(risk_metrics, [col5, col6, col7, col8]): |
|
|
with col: |
|
|
fig = go.Figure(go.Indicator( |
|
|
mode = "gauge+number+delta", |
|
|
value = value, |
|
|
domain = {'x': [0, 1], 'y': [0, 1]}, |
|
|
title = {'text': f"{emoji} {title}", 'font': {'size': 14}}, |
|
|
gauge = { |
|
|
'axis': {'range': [0, 1], 'tickwidth': 1}, |
|
|
'bar': {'color': color}, |
|
|
'steps': [ |
|
|
{'range': [0, 0.3], 'color': "lightgreen"}, |
|
|
{'range': [0.3, 0.7], 'color': "yellow"}, |
|
|
{'range': [0.7, 1], 'color': "red"} |
|
|
], |
|
|
'threshold': { |
|
|
'line': {'color': "black", 'width': 4}, |
|
|
'thickness': 0.75, |
|
|
'value': 0.7 |
|
|
} |
|
|
} |
|
|
)) |
|
|
fig.update_layout(height=250, margin=dict(l=10, r=10, t=50, b=10)) |
|
|
st.plotly_chart(fig, use_container_width=True) |
|
|
|
|
|
|
|
|
st.markdown(f'<div class="priority-box {risk_class}">', unsafe_allow_html=True) |
|
|
if language == "English": |
|
|
st.markdown(f"## 🎯 Clinical Priority Recommendation") |
|
|
st.markdown(f"### {recommendation}") |
|
|
st.markdown(f"**Overall Risk Score:** `{priority_score:.3f}`") |
|
|
st.markdown(f"**Recommended Action:** `{priority_level.replace('_', ' ').title()}`") |
|
|
|
|
|
|
|
|
if priority_level == "EMERGENCY_CARE": |
|
|
st.warning("🚨 **Immediate Action Required:** Patient should be directed to emergency department without delay.") |
|
|
elif priority_level == "SAME_DAY_CONSULT": |
|
|
st.info("ℹ️ **Urgent Consultation:** Schedule appointment within 24 hours.") |
|
|
else: |
|
|
st.success("✅ **Routine Care:** Schedule within regular appointment system.") |
|
|
|
|
|
else: |
|
|
st.markdown(f"## 🎯 کلینیکل ترجیحی سفارش") |
|
|
st.markdown(f"### {recommendation}") |
|
|
st.markdown(f"**کل خطرے کا اسکور:** `{priority_score:.3f}`") |
|
|
st.markdown(f"**سفارش کردہ عمل:** `{priority_level.replace('_', ' ').title()}`") |
|
|
|
|
|
if priority_level == "EMERGENCY_CARE": |
|
|
st.warning("🚨 **فوری کارروائی ضروری:** مریض کو بغیر کسی تاخیر کے ایمرجنسی ڈیپارٹمنٹ بھیجا جائے۔") |
|
|
elif priority_level == "SAME_DAY_CONSULT": |
|
|
st.info("ℹ️ **فوری مشاورت:** 24 گھنٹے کے اندر اپائنٹمنٹ شیڈول کریں۔") |
|
|
else: |
|
|
st.success("✅ **روٹین کیئر:** معمول کی اپائنٹمنٹ سسٹم کے اندر شیڈول کریں۔") |
|
|
|
|
|
st.markdown('</div>', unsafe_allow_html=True) |
|
|
|
|
|
except Exception as e: |
|
|
st.error(f"❌ Error in risk assessment: {str(e)}") |
|
|
|
|
|
st.markdown('</div>', unsafe_allow_html=True) |
|
|
|
|
|
with tab2: |
|
|
|
|
|
st.markdown('<div class="section-container">', unsafe_allow_html=True) |
|
|
|
|
|
if language == "English": |
|
|
st.markdown('<h2 style="color: #00401A; border-bottom: 3px solid #00401A; padding-bottom: 10px;">💬 SehatAI Health Assistant</h2>', unsafe_allow_html=True) |
|
|
st.write("Ask health-related questions and get instant, reliable medical information") |
|
|
else: |
|
|
st.markdown('<h2 style="color: #00401A; border-bottom: 3px solid #00401A; padding-bottom: 10px;">💬 سیحت اے آئی ہیلتھ اسسٹنٹ</h2>', unsafe_allow_html=True) |
|
|
st.write("صحت سے متعلق سوالات پوچھیں اور فوری، قابل اعتماد طبی معلومات حاصل کریں") |
|
|
|
|
|
|
|
|
for message in st.session_state.chat_history: |
|
|
if message["role"] == "user": |
|
|
st.markdown(f'<div class="chat-message user-message"><strong>You:</strong> {message["content"]}</div>', unsafe_allow_html=True) |
|
|
else: |
|
|
st.markdown(f'<div class="chat-message bot-message"><strong>🤖 Health Assistant:</strong> {message["content"]}</div>', unsafe_allow_html=True) |
|
|
|
|
|
|
|
|
if prompt := st.chat_input( |
|
|
"Type your health question here..." if language == "English" |
|
|
else "اپنا صحت کا سوال یہاں ٹائپ کریں..." |
|
|
): |
|
|
|
|
|
st.session_state.chat_history.append({"role": "user", "content": prompt}) |
|
|
|
|
|
|
|
|
with st.spinner("💭 Analyzing your question..." if language == "English" else "💭 آپ کا سوال تجزیہ ہو رہا ہے..."): |
|
|
response = chatbot.get_response(prompt, language) |
|
|
st.session_state.chat_history.append({"role": "assistant", "content": response}) |
|
|
|
|
|
|
|
|
if len(st.session_state.chat_history) > 10: |
|
|
st.session_state.chat_history = st.session_state.chat_history[-10:] |
|
|
|
|
|
st.rerun() |
|
|
|
|
|
|
|
|
if language == "English": |
|
|
st.subheader("Quick Health Topics") |
|
|
else: |
|
|
st.subheader("فوری صحت کے موضوعات") |
|
|
|
|
|
col_qa1, col_qa2, col_qa3, col_qa4 = st.columns(4) |
|
|
|
|
|
with col_qa1: |
|
|
if st.button("❤️ Heart Health", use_container_width=True): |
|
|
st.session_state.chat_history.append({ |
|
|
"role": "user", |
|
|
"content": "Tell me about heart disease symptoms and prevention" |
|
|
}) |
|
|
st.rerun() |
|
|
|
|
|
with col_qa2: |
|
|
if st.button("🩺 Diabetes", use_container_width=True): |
|
|
st.session_state.chat_history.append({ |
|
|
"role": "user", |
|
|
"content": "What are diabetes symptoms and management strategies?" |
|
|
}) |
|
|
st.rerun() |
|
|
|
|
|
with col_qa3: |
|
|
if st.button("💓 Blood Pressure", use_container_width=True): |
|
|
st.session_state.chat_history.append({ |
|
|
"role": "user", |
|
|
"content": "How to control high blood pressure naturally?" |
|
|
}) |
|
|
st.rerun() |
|
|
|
|
|
with col_qa4: |
|
|
if st.button("🍎 Nutrition", use_container_width=True): |
|
|
st.session_state.chat_history.append({ |
|
|
"role": "user", |
|
|
"content": "What is a healthy diet for heart health?" |
|
|
}) |
|
|
st.rerun() |
|
|
|
|
|
|
|
|
col_qa5, col_qa6, col_qa7, col_qa8 = st.columns(4) |
|
|
|
|
|
with col_qa5: |
|
|
if st.button("💪 Exercise", use_container_width=True): |
|
|
st.session_state.chat_history.append({ |
|
|
"role": "user", |
|
|
"content": "Exercise recommendations for beginners" |
|
|
}) |
|
|
st.rerun() |
|
|
|
|
|
with col_qa6: |
|
|
if st.button("🔍 Symptoms", use_container_width=True): |
|
|
st.session_state.chat_history.append({ |
|
|
"role": "user", |
|
|
"content": "When should I seek emergency medical care?" |
|
|
}) |
|
|
st.rerun() |
|
|
|
|
|
with col_qa7: |
|
|
if st.button("💊 Medications", use_container_width=True): |
|
|
st.session_state.chat_history.append({ |
|
|
"role": "user", |
|
|
"content": "General medication safety guidelines" |
|
|
}) |
|
|
st.rerun() |
|
|
|
|
|
with col_qa8: |
|
|
if st.button("🚨 Emergency", use_container_width=True): |
|
|
st.session_state.chat_history.append({ |
|
|
"role": "user", |
|
|
"content": "What are emergency warning signs?" |
|
|
}) |
|
|
st.rerun() |
|
|
|
|
|
st.markdown('</div>', unsafe_allow_html=True) |
|
|
|
|
|
with tab3: |
|
|
|
|
|
st.markdown('<div class="section-container">', unsafe_allow_html=True) |
|
|
|
|
|
if language == "English": |
|
|
st.markdown('<h2 style="color: #00401A; border-bottom: 3px solid #00401A; padding-bottom: 10px;">📋 Medical Reports & Analytics</h2>', unsafe_allow_html=True) |
|
|
st.write("Download comprehensive medical reports and view assessment analytics") |
|
|
else: |
|
|
st.markdown('<h2 style="color: #00401A; border-bottom: 3px solid #00401A; padding-bottom: 10px;">📋 طبی رپورٹس اور تجزیات</h2>', unsafe_allow_html=True) |
|
|
st.write("جامع طبی رپورٹس ڈاؤن لوڈ کریں اور تشخیص کے تجزیات دیکھیں") |
|
|
|
|
|
if st.session_state.assessment_history: |
|
|
|
|
|
latest_assessment = st.session_state.assessment_history[-1] |
|
|
|
|
|
|
|
|
if language == "English": |
|
|
st.subheader("Download Patient Report") |
|
|
else: |
|
|
st.subheader("مریض رپورٹ ڈاؤن لوڈ کریں") |
|
|
|
|
|
pdf_generator = PDFReportGenerator() |
|
|
pdf_data = pdf_generator.generate_report( |
|
|
latest_assessment['patient_data'], |
|
|
latest_assessment['risk_scores'], |
|
|
language |
|
|
) |
|
|
|
|
|
if language == "English": |
|
|
st.markdown(create_download_link(pdf_data, "sehatai_medical_report.pdf", "📥 Download Medical Report (PDF)"), unsafe_allow_html=True) |
|
|
else: |
|
|
st.markdown(create_download_link(pdf_data, "sehatai_medical_report.pdf", "📥 طبی رپورٹ ڈاؤن لوڈ کریں (PDF)"), unsafe_allow_html=True) |
|
|
|
|
|
|
|
|
if language == "English": |
|
|
st.subheader("Assessment Analytics") |
|
|
else: |
|
|
st.subheader("تشخیص کے تجزیات") |
|
|
|
|
|
col_anal1, col_anal2, col_anal3 = st.columns(3) |
|
|
|
|
|
with col_anal1: |
|
|
st.metric( |
|
|
"Total Assessments" if language == "English" else "کل تشخیص", |
|
|
len(st.session_state.assessment_history) |
|
|
) |
|
|
|
|
|
with col_anal2: |
|
|
latest_priority = latest_assessment['risk_scores']['priority'] |
|
|
st.metric( |
|
|
"Current Priority Score" if language == "English" else "موجودہ ترجیحی اسکور", |
|
|
f"{latest_priority:.1%}" |
|
|
) |
|
|
|
|
|
with col_anal3: |
|
|
high_risk_count = sum(1 for assess in st.session_state.assessment_history |
|
|
if assess['risk_scores']['priority'] > 0.7) |
|
|
st.metric( |
|
|
"High Risk Cases" if language == "English" else "اعلی خطرہ والے معاملات", |
|
|
high_risk_count |
|
|
) |
|
|
|
|
|
|
|
|
if len(st.session_state.assessment_history) > 1: |
|
|
risk_data = pd.DataFrame([ |
|
|
{ |
|
|
'Heart Risk': assess['risk_scores']['heart'], |
|
|
'Diabetes Risk': assess['risk_scores']['diabetes'], |
|
|
'Hypertension Risk': assess['risk_scores']['hypertension'], |
|
|
'Assessment': i+1 |
|
|
} for i, assess in enumerate(st.session_state.assessment_history[-5:]) |
|
|
]) |
|
|
|
|
|
fig = px.line(risk_data, x='Assessment', y=['Heart Risk', 'Diabetes Risk', 'Hypertension Risk'], |
|
|
title="Risk Trend Analysis" if language == "English" else "خطرے کے رجحان کا تجزیہ", |
|
|
color_discrete_map={ |
|
|
'Heart Risk': '#FF6B6B', |
|
|
'Diabetes Risk': '#4ECDC4', |
|
|
'Hypertension Risk': '#45B7D1' |
|
|
}) |
|
|
st.plotly_chart(fig, use_container_width=True) |
|
|
|
|
|
else: |
|
|
if language == "English": |
|
|
st.info("👆 Complete a patient assessment to generate reports and view analytics") |
|
|
else: |
|
|
st.info("👆 رپورٹس تیار کرنے اور تجزیات دیکھنے کے لیے مریض کی تشخیص مکمل کریں") |
|
|
|
|
|
st.markdown('</div>', unsafe_allow_html=True) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
main() |