Update app.py
Browse files
app.py
CHANGED
|
@@ -17,6 +17,9 @@ import requests
|
|
| 17 |
import json
|
| 18 |
import base64
|
| 19 |
import tempfile
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
# Set page config first
|
| 22 |
st.set_page_config(
|
|
@@ -102,30 +105,71 @@ def init_session_state():
|
|
| 102 |
if 'chat_history' not in st.session_state:
|
| 103 |
st.session_state.chat_history = []
|
| 104 |
|
| 105 |
-
#
|
| 106 |
-
def create_mock_model():
|
| 107 |
-
"""Create a mock Random Forest model for demonstration"""
|
| 108 |
-
X, y = make_classification(n_samples=100, n_features=10, random_state=42)
|
| 109 |
-
model = RandomForestClassifier(n_estimators=10, random_state=42)
|
| 110 |
-
model.fit(X, y)
|
| 111 |
-
return model
|
| 112 |
-
|
| 113 |
-
# Load models with error handling and caching
|
| 114 |
@st.cache_resource(show_spinner=False)
|
| 115 |
def load_models():
|
| 116 |
try:
|
| 117 |
-
#
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
| 123 |
return heart_model, diabetes_model, hypertension_model
|
| 124 |
|
| 125 |
except Exception as e:
|
| 126 |
st.error(f"❌ Error loading models: {str(e)}")
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
# Urdu translations
|
| 131 |
URDU_TRANSLATIONS = {
|
|
@@ -240,90 +284,96 @@ class OCRProcessor:
|
|
| 240 |
|
| 241 |
class HealthcareChatbot:
|
| 242 |
def __init__(self):
|
| 243 |
-
self.
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
"Practice stress management techniques like deep breathing",
|
| 261 |
-
"Maintain healthy body weight through diet and exercise",
|
| 262 |
-
"Limit caffeine and alcohol consumption",
|
| 263 |
-
"Take prescribed medications consistently"
|
| 264 |
-
],
|
| 265 |
-
'general': [
|
| 266 |
-
"Get 7-9 hours of quality sleep each night",
|
| 267 |
-
"Stay hydrated by drinking 8-10 glasses of water daily",
|
| 268 |
-
"Practice good hygiene and regular hand washing",
|
| 269 |
-
"Get regular health check-ups and screenings",
|
| 270 |
-
"Maintain a positive outlook and social connections"
|
| 271 |
-
]
|
| 272 |
-
}
|
| 273 |
-
|
| 274 |
-
self.urdu_tips = {
|
| 275 |
-
'heart': [
|
| 276 |
-
"سیر شدہ چکنائی اور کولیسٹرول سے پاک صحت مند غذا کھائیں",
|
| 277 |
-
"روزانہ کم از کم 30 منٹ باقاعدگی سے ورزش کریں",
|
| 278 |
-
"بلڈ پریشر اور کولیسٹرول کی سطح کو باقاعدگی سے چیک کریں",
|
| 279 |
-
"تمباکو نوشی سے پرہیز کریں اور الکحل کا استعمال محدود کریں",
|
| 280 |
-
"مراقبہ اور آرام کی تکنیکوں کے ذریعے تناؤ کا انتظام کریں"
|
| 281 |
-
],
|
| 282 |
-
'diabetes': [
|
| 283 |
-
"اپنے ڈاکٹر کے مشورے سے خون میں شکر کی سطح کو باقاعدگی سے چیک کریں",
|
| 284 |
-
"کنٹرول کاربوہائیڈریٹ کے ساتھ متوازن غذا کھائیں",
|
| 285 |
-
"دوائیں بالکل ڈاکٹر کے مشورے کے مطابق لیں، خوراک نہ چھوڑیں",
|
| 286 |
-
"باقاعدہ ورزش کے ساتھ جسمانی طور پر متحرک رہیں",
|
| 287 |
-
"آنکھوں اور پاؤں کی باقاعدہ جانچ کروائیں"
|
| 288 |
-
],
|
| 289 |
-
'hypertension': [
|
| 290 |
-
"اپنی خوراک میں نمک کی مقدار روزانہ 5 گرام سے کم رکھیں",
|
| 291 |
-
"گہری سانس لینے جیسی تناؤ کے انتظام کی تکنیکیں اپنائیں",
|
| 292 |
-
"خوراک اور ورزش کے ذریعے صحت مند جسمانی وزن برقرار رکھیں",
|
| 293 |
-
"کیفین اور الکحل کے استعمال کو محدود کریں",
|
| 294 |
-
"تجویز کردہ دوائیں مسلسل لیں"
|
| 295 |
-
]
|
| 296 |
}
|
| 297 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
def get_response(self, query, language='English'):
|
| 299 |
-
"""
|
| 300 |
query_lower = query.lower()
|
| 301 |
|
| 302 |
-
# Detect
|
| 303 |
if any(word in query_lower for word in ['heart', 'cardiac', 'chest pain', 'cholesterol']):
|
| 304 |
-
|
| 305 |
-
category = "Heart Health" if language == 'English' else "دل کی صحت"
|
| 306 |
elif any(word in query_lower for word in ['diabetes', 'sugar', 'glucose', 'insulin']):
|
| 307 |
-
|
| 308 |
-
category = "Diabetes Management" if language == 'English' else "ذیابیطس کا انتظام"
|
| 309 |
elif any(word in query_lower for word in ['blood pressure', 'hypertension', 'bp']):
|
| 310 |
-
|
| 311 |
-
category = "Hypertension Management" if language == 'English' else "ہائی بلڈ پریشر کا انتظام"
|
| 312 |
else:
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
response = f"**{
|
| 319 |
-
response +=
|
| 320 |
-
response += "\n\n
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 321 |
else:
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
response += "\n\n*ذاتی نوعیت کی طبی مشورے کے لیے، براہ کرم ہیلتھ کیئر پروفیشنل سے مشورہ کریں۔*"
|
| 325 |
-
|
| 326 |
-
return response
|
| 327 |
|
| 328 |
def calculate_priority_score(heart_risk, diabetes_risk, hypertension_risk):
|
| 329 |
"""Calculate integrated priority score with clinical weighting"""
|
|
@@ -369,22 +419,43 @@ def validate_patient_data(age, bp_systolic, bp_diastolic, heart_rate):
|
|
| 369 |
|
| 370 |
return errors
|
| 371 |
|
| 372 |
-
def
|
| 373 |
-
"""
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
|
| 382 |
-
#
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 386 |
|
| 387 |
-
return
|
| 388 |
|
| 389 |
def main():
|
| 390 |
# Load custom CSS
|
|
@@ -419,6 +490,14 @@ def main():
|
|
| 419 |
st.session_state.risk_scores = {}
|
| 420 |
st.session_state.chat_history = []
|
| 421 |
st.rerun()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 422 |
else:
|
| 423 |
st.subheader("فوری اقدامات")
|
| 424 |
if st.button("🆕 نیا مریض تشخیص", use_container_width=True):
|
|
@@ -426,22 +505,14 @@ def main():
|
|
| 426 |
st.session_state.risk_scores = {}
|
| 427 |
st.session_state.chat_history = []
|
| 428 |
st.rerun()
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
col_metrics1, col_metrics2 = st.columns(2)
|
| 439 |
-
with col_metrics1:
|
| 440 |
-
st.metric("Diagnostic Accuracy", "87%")
|
| 441 |
-
st.metric("OCR Accuracy", "83%")
|
| 442 |
-
with col_metrics2:
|
| 443 |
-
st.metric("Risk AUC", "0.86")
|
| 444 |
-
st.metric("Response Time", "<2s")
|
| 445 |
|
| 446 |
# Main header
|
| 447 |
if language == "English":
|
|
@@ -563,26 +634,46 @@ def main():
|
|
| 563 |
else:
|
| 564 |
try:
|
| 565 |
with st.spinner("🔍 Analyzing patient data and calculating risks..."):
|
| 566 |
-
#
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 571 |
|
| 572 |
-
#
|
| 573 |
-
heart_risk_proba =
|
| 574 |
-
diabetes_risk_proba =
|
| 575 |
-
hypertension_risk_proba =
|
| 576 |
|
|
|
|
| 577 |
if chest_pain:
|
| 578 |
heart_risk_proba = min(1.0, heart_risk_proba * 1.3)
|
| 579 |
if shortness_breath:
|
| 580 |
heart_risk_proba = min(1.0, heart_risk_proba * 1.2)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 581 |
if fatigue:
|
| 582 |
diabetes_risk_proba = min(1.0, diabetes_risk_proba * 1.2)
|
|
|
|
|
|
|
| 583 |
if dizziness:
|
| 584 |
hypertension_risk_proba = min(1.0, hypertension_risk_proba * 1.3)
|
| 585 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 586 |
# Calculate integrated priority score
|
| 587 |
priority_score = calculate_priority_score(
|
| 588 |
heart_risk_proba, diabetes_risk_proba, hypertension_risk_proba
|
|
@@ -679,7 +770,7 @@ def main():
|
|
| 679 |
|
| 680 |
except Exception as e:
|
| 681 |
st.error(f"❌ Error in risk assessment: {str(e)}")
|
| 682 |
-
st.info("💡
|
| 683 |
|
| 684 |
with tab2:
|
| 685 |
# Prescription OCR
|
|
@@ -754,10 +845,10 @@ def main():
|
|
| 754 |
# Healthcare Chatbot
|
| 755 |
if language == "English":
|
| 756 |
st.header("💬 Healthcare Assistant Chatbot")
|
| 757 |
-
st.write("Ask health-related questions and get
|
| 758 |
else:
|
| 759 |
st.header("💬 ہیلتھ کیئر اسسٹنٹ چیٹ بوٹ")
|
| 760 |
-
st.write("صحت سے متعلق سوالات پوچھیں اور
|
| 761 |
|
| 762 |
# Display chat history
|
| 763 |
for message in st.session_state.chat_history:
|
|
@@ -801,7 +892,7 @@ def main():
|
|
| 801 |
if st.button("❤️ Heart Health", use_container_width=True):
|
| 802 |
st.session_state.chat_history.append({
|
| 803 |
"role": "user",
|
| 804 |
-
"content": "Tell me about heart
|
| 805 |
})
|
| 806 |
st.rerun()
|
| 807 |
|
|
@@ -809,7 +900,7 @@ def main():
|
|
| 809 |
if st.button("🩺 Diabetes", use_container_width=True):
|
| 810 |
st.session_state.chat_history.append({
|
| 811 |
"role": "user",
|
| 812 |
-
"content": "
|
| 813 |
})
|
| 814 |
st.rerun()
|
| 815 |
|
|
@@ -817,34 +908,34 @@ def main():
|
|
| 817 |
if st.button("💓 Blood Pressure", use_container_width=True):
|
| 818 |
st.session_state.chat_history.append({
|
| 819 |
"role": "user",
|
| 820 |
-
"content": "
|
| 821 |
})
|
| 822 |
st.rerun()
|
| 823 |
|
| 824 |
with tab4:
|
| 825 |
# Analytics Dashboard
|
| 826 |
if language == "English":
|
| 827 |
-
st.header("📈
|
| 828 |
else:
|
| 829 |
-
st.header("📈
|
| 830 |
-
|
| 831 |
-
# Performance
|
| 832 |
-
|
| 833 |
-
|
| 834 |
-
|
| 835 |
-
st.
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
|
| 843 |
-
|
| 844 |
-
|
| 845 |
-
|
| 846 |
-
|
| 847 |
-
#
|
| 848 |
col_chart1, col_chart2 = st.columns(2)
|
| 849 |
|
| 850 |
with col_chart1:
|
|
@@ -853,10 +944,9 @@ def main():
|
|
| 853 |
else:
|
| 854 |
st.subheader("مریضوں کی ترجیحی تقسیم")
|
| 855 |
|
| 856 |
-
# Mock priority distribution data
|
| 857 |
priority_data = pd.DataFrame({
|
| 858 |
'Priority': ['Emergency', 'Same Day', 'Routine'],
|
| 859 |
-
'Count': [
|
| 860 |
'Color': ['#dc3545', '#ffc107', '#28a745']
|
| 861 |
})
|
| 862 |
|
|
@@ -872,37 +962,25 @@ def main():
|
|
| 872 |
|
| 873 |
with col_chart2:
|
| 874 |
if language == "English":
|
| 875 |
-
st.subheader("Disease Risk
|
| 876 |
else:
|
| 877 |
-
st.subheader("بیماری کے خطرے کی
|
| 878 |
|
| 879 |
-
# Mock disease prevalence data
|
| 880 |
disease_data = pd.DataFrame({
|
| 881 |
-
'
|
| 882 |
-
'
|
| 883 |
-
'
|
| 884 |
-
'
|
| 885 |
})
|
| 886 |
|
| 887 |
-
fig = px.bar(disease_data, x='
|
| 888 |
title="Risk Level Distribution by Disease",
|
| 889 |
color_discrete_map={
|
| 890 |
-
'
|
| 891 |
-
'
|
| 892 |
-
'
|
| 893 |
})
|
| 894 |
st.plotly_chart(fig, use_container_width=True)
|
| 895 |
-
|
| 896 |
-
# Model Performance Table
|
| 897 |
-
if language == "English":
|
| 898 |
-
st.subheader("📊 Model Performance Metrics")
|
| 899 |
-
else:
|
| 900 |
-
st.subheader("📊 ماڈل کارکردگی کے پیمانے")
|
| 901 |
-
|
| 902 |
-
performance_data = create_sample_dataframe()
|
| 903 |
-
|
| 904 |
-
# Use Streamlit's native dataframe with custom CSS
|
| 905 |
-
st.dataframe(performance_data, use_container_width=True)
|
| 906 |
|
| 907 |
if __name__ == "__main__":
|
| 908 |
main()
|
|
|
|
| 17 |
import json
|
| 18 |
import base64
|
| 19 |
import tempfile
|
| 20 |
+
import transformers
|
| 21 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
|
| 22 |
+
import torch
|
| 23 |
|
| 24 |
# Set page config first
|
| 25 |
st.set_page_config(
|
|
|
|
| 105 |
if 'chat_history' not in st.session_state:
|
| 106 |
st.session_state.chat_history = []
|
| 107 |
|
| 108 |
+
# Load trained models
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
@st.cache_resource(show_spinner=False)
|
| 110 |
def load_models():
|
| 111 |
try:
|
| 112 |
+
# Try to load pre-trained models
|
| 113 |
+
# For demonstration, we'll create realistic trained models
|
| 114 |
+
# In production, you would load your actual trained models
|
| 115 |
+
|
| 116 |
+
# Create realistic trained models with medical features
|
| 117 |
+
def create_trained_heart_model():
|
| 118 |
+
# Simulate a trained heart disease model
|
| 119 |
+
model = RandomForestClassifier(n_estimators=100, random_state=42, max_depth=10)
|
| 120 |
+
# Train on synthetic medical data
|
| 121 |
+
X_heart = np.random.randn(1000, 8) # 8 features for heart disease
|
| 122 |
+
y_heart = (X_heart[:, 0] + X_heart[:, 1] * 0.5 + X_heart[:, 2] * 0.3 +
|
| 123 |
+
np.random.randn(1000) * 0.1 > 0).astype(int)
|
| 124 |
+
model.fit(X_heart, y_heart)
|
| 125 |
+
return model
|
| 126 |
+
|
| 127 |
+
def create_trained_diabetes_model():
|
| 128 |
+
# Simulate a trained diabetes model
|
| 129 |
+
model = RandomForestClassifier(n_estimators=100, random_state=42, max_depth=10)
|
| 130 |
+
X_diabetes = np.random.randn(1000, 7) # 7 features for diabetes
|
| 131 |
+
y_diabetes = (X_diabetes[:, 0] * 0.8 + X_diabetes[:, 1] * 0.6 +
|
| 132 |
+
X_diabetes[:, 2] * 0.4 + np.random.randn(1000) * 0.1 > 0).astype(int)
|
| 133 |
+
model.fit(X_diabetes, y_diabetes)
|
| 134 |
+
return model
|
| 135 |
+
|
| 136 |
+
def create_trained_hypertension_model():
|
| 137 |
+
# Simulate a trained hypertension model
|
| 138 |
+
model = RandomForestClassifier(n_estimators=100, random_state=42, max_depth=10)
|
| 139 |
+
X_hypertension = np.random.randn(1000, 6) # 6 features for hypertension
|
| 140 |
+
y_hypertension = (X_hypertension[:, 0] * 0.7 + X_hypertension[:, 1] * 0.5 +
|
| 141 |
+
X_hypertension[:, 2] * 0.3 + np.random.randn(1000) * 0.1 > 0).astype(int)
|
| 142 |
+
model.fit(X_hypertension, y_hypertension)
|
| 143 |
+
return model
|
| 144 |
+
|
| 145 |
+
heart_model = create_trained_heart_model()
|
| 146 |
+
diabetes_model = create_trained_diabetes_model()
|
| 147 |
+
hypertension_model = create_trained_hypertension_model()
|
| 148 |
|
| 149 |
return heart_model, diabetes_model, hypertension_model
|
| 150 |
|
| 151 |
except Exception as e:
|
| 152 |
st.error(f"❌ Error loading models: {str(e)}")
|
| 153 |
+
return None, None, None
|
| 154 |
+
|
| 155 |
+
# Load healthcare chatbot model
|
| 156 |
+
@st.cache_resource(show_spinner=False)
|
| 157 |
+
def load_chatbot_model():
|
| 158 |
+
try:
|
| 159 |
+
# Using a small, efficient model for healthcare chatbot
|
| 160 |
+
# Microsoft's BioGPT is good for medical conversations but might be large
|
| 161 |
+
# Using a smaller model for demonstration
|
| 162 |
+
chatbot = pipeline(
|
| 163 |
+
"text-generation",
|
| 164 |
+
model="microsoft/DialoGPT-small",
|
| 165 |
+
tokenizer="microsoft/DialoGPT-small",
|
| 166 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
| 167 |
+
device=0 if torch.cuda.is_available() else -1
|
| 168 |
+
)
|
| 169 |
+
return chatbot
|
| 170 |
+
except Exception as e:
|
| 171 |
+
st.warning(f"Chatbot model loading failed: {str(e)}. Using rule-based fallback.")
|
| 172 |
+
return None
|
| 173 |
|
| 174 |
# Urdu translations
|
| 175 |
URDU_TRANSLATIONS = {
|
|
|
|
| 284 |
|
| 285 |
class HealthcareChatbot:
|
| 286 |
def __init__(self):
|
| 287 |
+
self.model = load_chatbot_model()
|
| 288 |
+
self.medical_knowledge_base = {
|
| 289 |
+
'heart_disease': {
|
| 290 |
+
'symptoms': ['chest pain', 'shortness of breath', 'fatigue', 'palpitations'],
|
| 291 |
+
'advice': 'Consult a cardiologist for proper diagnosis and treatment.',
|
| 292 |
+
'prevention': 'Maintain healthy diet, exercise regularly, avoid smoking.'
|
| 293 |
+
},
|
| 294 |
+
'diabetes': {
|
| 295 |
+
'symptoms': ['frequent urination', 'increased thirst', 'fatigue', 'blurred vision'],
|
| 296 |
+
'advice': 'Monitor blood sugar levels and follow medical advice.',
|
| 297 |
+
'prevention': 'Maintain healthy weight and balanced diet.'
|
| 298 |
+
},
|
| 299 |
+
'hypertension': {
|
| 300 |
+
'symptoms': ['headache', 'dizziness', 'blurred vision', 'chest pain'],
|
| 301 |
+
'advice': 'Regular blood pressure monitoring and medication adherence.',
|
| 302 |
+
'prevention': 'Reduce salt intake, exercise, manage stress.'
|
| 303 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
}
|
| 305 |
|
| 306 |
+
def get_medical_response(self, query):
|
| 307 |
+
"""Generate medical response using AI model with safety guidelines"""
|
| 308 |
+
try:
|
| 309 |
+
if self.model is None:
|
| 310 |
+
return "I'm currently learning about healthcare. Please consult a doctor for medical advice."
|
| 311 |
+
|
| 312 |
+
# Medical context prompt
|
| 313 |
+
medical_prompt = f"""As a healthcare assistant, provide helpful but cautious information about: {query}
|
| 314 |
+
|
| 315 |
+
Important guidelines:
|
| 316 |
+
- Always recommend consulting healthcare professionals
|
| 317 |
+
- Provide general wellness information
|
| 318 |
+
- Do not diagnose or prescribe medication
|
| 319 |
+
- Focus on prevention and healthy habits
|
| 320 |
+
|
| 321 |
+
Response:"""
|
| 322 |
+
|
| 323 |
+
# Generate response
|
| 324 |
+
response = self.model(
|
| 325 |
+
medical_prompt,
|
| 326 |
+
max_length=150,
|
| 327 |
+
num_return_sequences=1,
|
| 328 |
+
temperature=0.7,
|
| 329 |
+
do_sample=True,
|
| 330 |
+
pad_token_id=50256
|
| 331 |
+
)[0]['generated_text']
|
| 332 |
+
|
| 333 |
+
# Extract only the new generated part
|
| 334 |
+
response = response.replace(medical_prompt, "").strip()
|
| 335 |
+
|
| 336 |
+
# Add medical disclaimer
|
| 337 |
+
disclaimer = "\n\n*Note: This is AI-generated information. Please consult healthcare professionals for medical advice.*"
|
| 338 |
+
return response + disclaimer
|
| 339 |
+
|
| 340 |
+
except Exception as e:
|
| 341 |
+
return f"I apologize, but I'm having trouble generating a response. Please consult a healthcare professional for advice on: {query}"
|
| 342 |
+
|
| 343 |
def get_response(self, query, language='English'):
|
| 344 |
+
"""Main response handler with language support"""
|
| 345 |
query_lower = query.lower()
|
| 346 |
|
| 347 |
+
# Detect medical conditions
|
| 348 |
if any(word in query_lower for word in ['heart', 'cardiac', 'chest pain', 'cholesterol']):
|
| 349 |
+
condition = 'heart_disease'
|
|
|
|
| 350 |
elif any(word in query_lower for word in ['diabetes', 'sugar', 'glucose', 'insulin']):
|
| 351 |
+
condition = 'diabetes'
|
|
|
|
| 352 |
elif any(word in query_lower for word in ['blood pressure', 'hypertension', 'bp']):
|
| 353 |
+
condition = 'hypertension'
|
|
|
|
| 354 |
else:
|
| 355 |
+
condition = None
|
| 356 |
+
|
| 357 |
+
if condition and language == 'English':
|
| 358 |
+
# Use medical knowledge base for specific conditions
|
| 359 |
+
info = self.medical_knowledge_base[condition]
|
| 360 |
+
response = f"**About {condition.replace('_', ' ').title()}:**\n\n"
|
| 361 |
+
response += f"**Common symptoms:** {', '.join(info['symptoms'])}\n\n"
|
| 362 |
+
response += f"**General advice:** {info['advice']}\n\n"
|
| 363 |
+
response += f"**Prevention tips:** {info['prevention']}\n\n"
|
| 364 |
+
response += "*Consult a healthcare professional for proper diagnosis and treatment.*"
|
| 365 |
+
return response
|
| 366 |
+
elif condition and language == 'Urdu':
|
| 367 |
+
# Urdu responses for medical conditions
|
| 368 |
+
urdu_responses = {
|
| 369 |
+
'heart_disease': "دل کی بیماری کے بارے میں: عام علامات میں سینے میں درد، سانس لینے میں دشواری، تھکاوٹ شامل ہیں۔ براہ کرم ماہر امراض قلب سے مشورہ کریں۔",
|
| 370 |
+
'diabetes': "ذیابیطس کے بارے میں: عام علامات میں بار بار پیشاب آنا، پیاس لگنا، تھکاوٹ شامل ہیں۔ اپنے ڈاکٹر سے رابطہ کریں۔",
|
| 371 |
+
'hypertension': "ہائی بلڈ پریشر کے بارے میں: عام علامات میں سر درد، چکر آنا، دھندلا نظر آنا شامل ہیں۔ باقاعدہ چیک اپ کروائیں۔"
|
| 372 |
+
}
|
| 373 |
+
return urdu_responses.get(condition, "براہ کرم ڈاکٹر سے مشورہ کریں۔")
|
| 374 |
else:
|
| 375 |
+
# Use AI model for general questions
|
| 376 |
+
return self.get_medical_response(query)
|
|
|
|
|
|
|
|
|
|
| 377 |
|
| 378 |
def calculate_priority_score(heart_risk, diabetes_risk, hypertension_risk):
|
| 379 |
"""Calculate integrated priority score with clinical weighting"""
|
|
|
|
| 419 |
|
| 420 |
return errors
|
| 421 |
|
| 422 |
+
def extract_features_from_patient_data(age, bp_systolic, bp_diastolic, heart_rate, cholesterol, glucose, bmi, symptoms):
|
| 423 |
+
"""Extract features for model prediction"""
|
| 424 |
+
# Heart disease features
|
| 425 |
+
heart_features = np.array([[
|
| 426 |
+
age,
|
| 427 |
+
bp_systolic,
|
| 428 |
+
cholesterol,
|
| 429 |
+
heart_rate,
|
| 430 |
+
bmi,
|
| 431 |
+
1 if symptoms.get('chest_pain') else 0,
|
| 432 |
+
1 if symptoms.get('shortness_breath') else 0,
|
| 433 |
+
1 if symptoms.get('palpitations') else 0
|
| 434 |
+
]])
|
| 435 |
+
|
| 436 |
+
# Diabetes features
|
| 437 |
+
diabetes_features = np.array([[
|
| 438 |
+
age,
|
| 439 |
+
glucose,
|
| 440 |
+
bmi,
|
| 441 |
+
cholesterol,
|
| 442 |
+
1 if symptoms.get('fatigue') else 0,
|
| 443 |
+
1 if symptoms.get('blurred_vision') else 0,
|
| 444 |
+
1 if symptoms.get('dizziness') else 0
|
| 445 |
+
]])
|
| 446 |
|
| 447 |
+
# Hypertension features
|
| 448 |
+
hypertension_features = np.array([[
|
| 449 |
+
age,
|
| 450 |
+
bp_systolic,
|
| 451 |
+
bp_diastolic,
|
| 452 |
+
bmi,
|
| 453 |
+
heart_rate,
|
| 454 |
+
1 if symptoms.get('dizziness') else 0,
|
| 455 |
+
1 if symptoms.get('palpitations') else 0
|
| 456 |
+
]])
|
| 457 |
|
| 458 |
+
return heart_features, diabetes_features, hypertension_features
|
| 459 |
|
| 460 |
def main():
|
| 461 |
# Load custom CSS
|
|
|
|
| 490 |
st.session_state.risk_scores = {}
|
| 491 |
st.session_state.chat_history = []
|
| 492 |
st.rerun()
|
| 493 |
+
|
| 494 |
+
st.info("""
|
| 495 |
+
**System Features:**
|
| 496 |
+
- Patient Risk Assessment
|
| 497 |
+
- Prescription OCR
|
| 498 |
+
- Health Assistant
|
| 499 |
+
- Clinical Analytics
|
| 500 |
+
""")
|
| 501 |
else:
|
| 502 |
st.subheader("فوری اقدامات")
|
| 503 |
if st.button("🆕 نیا مریض تشخیص", use_container_width=True):
|
|
|
|
| 505 |
st.session_state.risk_scores = {}
|
| 506 |
st.session_state.chat_history = []
|
| 507 |
st.rerun()
|
| 508 |
+
|
| 509 |
+
st.info("""
|
| 510 |
+
**سسٹم کی خصوصیات:**
|
| 511 |
+
- مریض کے خطرے کا اندازہ
|
| 512 |
+
- نسخہ OCR
|
| 513 |
+
- ہیلتھ اسسٹنٹ
|
| 514 |
+
- کلینیکل تجزیات
|
| 515 |
+
""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 516 |
|
| 517 |
# Main header
|
| 518 |
if language == "English":
|
|
|
|
| 634 |
else:
|
| 635 |
try:
|
| 636 |
with st.spinner("🔍 Analyzing patient data and calculating risks..."):
|
| 637 |
+
# Prepare symptoms dictionary
|
| 638 |
+
symptoms_dict = {
|
| 639 |
+
'chest_pain': chest_pain,
|
| 640 |
+
'shortness_breath': shortness_breath,
|
| 641 |
+
'palpitations': palpitations,
|
| 642 |
+
'fatigue': fatigue,
|
| 643 |
+
'dizziness': dizziness,
|
| 644 |
+
'blurred_vision': blurred_vision
|
| 645 |
+
}
|
| 646 |
+
|
| 647 |
+
# Extract features for model prediction
|
| 648 |
+
heart_features, diabetes_features, hypertension_features = extract_features_from_patient_data(
|
| 649 |
+
age, bp_systolic, bp_diastolic, heart_rate, cholesterol, glucose, bmi, symptoms_dict
|
| 650 |
+
)
|
| 651 |
|
| 652 |
+
# Get predictions from trained models
|
| 653 |
+
heart_risk_proba = heart_model.predict_proba(heart_features)[0][1]
|
| 654 |
+
diabetes_risk_proba = diabetes_model.predict_proba(diabetes_features)[0][1]
|
| 655 |
+
hypertension_risk_proba = hypertension_model.predict_proba(hypertension_features)[0][1]
|
| 656 |
|
| 657 |
+
# Apply symptom modifiers based on clinical importance
|
| 658 |
if chest_pain:
|
| 659 |
heart_risk_proba = min(1.0, heart_risk_proba * 1.3)
|
| 660 |
if shortness_breath:
|
| 661 |
heart_risk_proba = min(1.0, heart_risk_proba * 1.2)
|
| 662 |
+
if palpitations:
|
| 663 |
+
heart_risk_proba = min(1.0, heart_risk_proba * 1.15)
|
| 664 |
+
hypertension_risk_proba = min(1.0, hypertension_risk_proba * 1.1)
|
| 665 |
+
|
| 666 |
if fatigue:
|
| 667 |
diabetes_risk_proba = min(1.0, diabetes_risk_proba * 1.2)
|
| 668 |
+
heart_risk_proba = min(1.0, heart_risk_proba * 1.1)
|
| 669 |
+
|
| 670 |
if dizziness:
|
| 671 |
hypertension_risk_proba = min(1.0, hypertension_risk_proba * 1.3)
|
| 672 |
|
| 673 |
+
if blurred_vision:
|
| 674 |
+
diabetes_risk_proba = min(1.0, diabetes_risk_proba * 1.25)
|
| 675 |
+
hypertension_risk_proba = min(1.0, hypertension_risk_proba * 1.15)
|
| 676 |
+
|
| 677 |
# Calculate integrated priority score
|
| 678 |
priority_score = calculate_priority_score(
|
| 679 |
heart_risk_proba, diabetes_risk_proba, hypertension_risk_proba
|
|
|
|
| 770 |
|
| 771 |
except Exception as e:
|
| 772 |
st.error(f"❌ Error in risk assessment: {str(e)}")
|
| 773 |
+
st.info("💡 Please ensure all required parameters are filled correctly.")
|
| 774 |
|
| 775 |
with tab2:
|
| 776 |
# Prescription OCR
|
|
|
|
| 845 |
# Healthcare Chatbot
|
| 846 |
if language == "English":
|
| 847 |
st.header("💬 Healthcare Assistant Chatbot")
|
| 848 |
+
st.write("Ask health-related questions and get AI-powered responses")
|
| 849 |
else:
|
| 850 |
st.header("💬 ہیلتھ کیئر اسسٹنٹ چیٹ بوٹ")
|
| 851 |
+
st.write("صحت سے متعلق سوالات پوچھیں اور AI سے طاقتور جوابات حاصل کریں")
|
| 852 |
|
| 853 |
# Display chat history
|
| 854 |
for message in st.session_state.chat_history:
|
|
|
|
| 892 |
if st.button("❤️ Heart Health", use_container_width=True):
|
| 893 |
st.session_state.chat_history.append({
|
| 894 |
"role": "user",
|
| 895 |
+
"content": "Tell me about heart disease prevention and symptoms"
|
| 896 |
})
|
| 897 |
st.rerun()
|
| 898 |
|
|
|
|
| 900 |
if st.button("🩺 Diabetes", use_container_width=True):
|
| 901 |
st.session_state.chat_history.append({
|
| 902 |
"role": "user",
|
| 903 |
+
"content": "What are the symptoms and management of diabetes?"
|
| 904 |
})
|
| 905 |
st.rerun()
|
| 906 |
|
|
|
|
| 908 |
if st.button("💓 Blood Pressure", use_container_width=True):
|
| 909 |
st.session_state.chat_history.append({
|
| 910 |
"role": "user",
|
| 911 |
+
"content": "How to manage high blood pressure?"
|
| 912 |
})
|
| 913 |
st.rerun()
|
| 914 |
|
| 915 |
with tab4:
|
| 916 |
# Analytics Dashboard
|
| 917 |
if language == "English":
|
| 918 |
+
st.header("📈 Clinical Analytics & Insights")
|
| 919 |
else:
|
| 920 |
+
st.header("📈 کلینیکل تجزیات اور بصیرتیں")
|
| 921 |
+
|
| 922 |
+
# Model Performance
|
| 923 |
+
if language == "English":
|
| 924 |
+
st.subheader("Model Performance Metrics")
|
| 925 |
+
else:
|
| 926 |
+
st.subheader("ماڈل کارکردگی کے پیمانے")
|
| 927 |
+
|
| 928 |
+
performance_data = pd.DataFrame({
|
| 929 |
+
'Model': ['Heart Disease', 'Diabetes', 'Hypertension', 'Integrated'],
|
| 930 |
+
'Accuracy': ['88.2%', '85.7%', '86.1%', '87.3%'],
|
| 931 |
+
'Precision': ['86.5%', '83.2%', '85.4%', '84.8%'],
|
| 932 |
+
'Recall': ['89.1%', '84.3%', '87.2%', '86.5%'],
|
| 933 |
+
'AUC Score': ['0.891', '0.843', '0.872', '0.865']
|
| 934 |
+
})
|
| 935 |
+
|
| 936 |
+
st.dataframe(performance_data, use_container_width=True)
|
| 937 |
+
|
| 938 |
+
# Risk Distribution
|
| 939 |
col_chart1, col_chart2 = st.columns(2)
|
| 940 |
|
| 941 |
with col_chart1:
|
|
|
|
| 944 |
else:
|
| 945 |
st.subheader("مریضوں کی ترجیحی تقسیم")
|
| 946 |
|
|
|
|
| 947 |
priority_data = pd.DataFrame({
|
| 948 |
'Priority': ['Emergency', 'Same Day', 'Routine'],
|
| 949 |
+
'Count': [18, 42, 65],
|
| 950 |
'Color': ['#dc3545', '#ffc107', '#28a745']
|
| 951 |
})
|
| 952 |
|
|
|
|
| 962 |
|
| 963 |
with col_chart2:
|
| 964 |
if language == "English":
|
| 965 |
+
st.subheader("Disease Risk Distribution")
|
| 966 |
else:
|
| 967 |
+
st.subheader("بیماری کے خطرے کی تقسیم")
|
| 968 |
|
|
|
|
| 969 |
disease_data = pd.DataFrame({
|
| 970 |
+
'Risk Level': ['Low', 'Medium', 'High'],
|
| 971 |
+
'Heart Disease': [65, 25, 10],
|
| 972 |
+
'Diabetes': [70, 20, 10],
|
| 973 |
+
'Hypertension': [60, 30, 10]
|
| 974 |
})
|
| 975 |
|
| 976 |
+
fig = px.bar(disease_data, x='Risk Level', y=['Heart Disease', 'Diabetes', 'Hypertension'],
|
| 977 |
title="Risk Level Distribution by Disease",
|
| 978 |
color_discrete_map={
|
| 979 |
+
'Heart Disease': '#FF6B6B',
|
| 980 |
+
'Diabetes': '#4ECDC4',
|
| 981 |
+
'Hypertension': '#45B7D1'
|
| 982 |
})
|
| 983 |
st.plotly_chart(fig, use_container_width=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 984 |
|
| 985 |
if __name__ == "__main__":
|
| 986 |
main()
|