sunbal7 commited on
Commit
fe88653
·
verified ·
1 Parent(s): 5190a0b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +797 -730
app.py CHANGED
@@ -10,13 +10,18 @@ import os
10
  import plotly.graph_objects as go
11
  import plotly.express as px
12
  from datetime import datetime
 
 
 
 
 
13
 
14
  # Set page config first
15
  st.set_page_config(
16
- page_title="AI-Priority OPD System",
17
  page_icon="🏥",
18
  layout="wide",
19
- initial_sidebar_state="expanded"
20
  )
21
 
22
  # Professional CSS Styling
@@ -24,71 +29,94 @@ def local_css():
24
  st.markdown("""
25
  <style>
26
  .main-header {
27
- font-size: 3rem;
28
  color: #1f77b4;
29
  text-align: center;
30
- margin-bottom: 1rem;
31
- font-weight: 700;
32
- background: linear-gradient(135deg, #1f77b4, #2e86ab);
33
  -webkit-background-clip: text;
34
  -webkit-text-fill-color: transparent;
35
- text-shadow: 0px 2px 4px rgba(0,0,0,0.1);
 
36
  }
37
- .sub-header {
38
- font-size: 1.5rem;
39
- color: #2e86ab;
40
- margin-bottom: 1rem;
 
 
 
 
 
 
 
 
41
  font-weight: 600;
42
- border-bottom: 2px solid #1f77b4;
43
- padding-bottom: 0.5rem;
 
 
 
 
44
  }
45
  .section-container {
46
  background: white;
47
- padding: 25px;
48
- border-radius: 15px;
49
- box-shadow: 0 4px 12px rgba(0,0,0,0.1);
50
- margin-bottom: 25px;
51
- border: 1px solid #e0e0e0;
 
 
 
 
 
52
  }
53
  .metric-card {
54
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
55
  color: white;
56
- padding: 20px;
57
- border-radius: 12px;
58
  text-align: center;
59
- box-shadow: 0 4px 8px rgba(0,0,0,0.2);
 
 
 
 
 
60
  }
61
  .risk-high {
62
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
63
  color: white;
64
- padding: 20px;
65
- border-radius: 12px;
66
- border-left: 6px solid #dc3545;
67
- box-shadow: 0 4px 8px rgba(220,53,69,0.3);
68
  }
69
  .risk-medium {
70
  background: linear-gradient(135deg, #ffd93d, #ffcd3c);
71
  color: #333;
72
- padding: 20px;
73
- border-radius: 12px;
74
- border-left: 6px solid #ffc107;
75
- box-shadow: 0 4px 8px rgba(255,193,7,0.3);
76
  }
77
  .risk-low {
78
  background: linear-gradient(135deg, #6bcf7f, #28a745);
79
  color: white;
80
- padding: 20px;
81
- border-radius: 12px;
82
- border-left: 6px solid #20c997;
83
- box-shadow: 0 4px 8px rgba(40,167,69,0.3);
84
  }
85
  .priority-box {
86
- border: 3px solid #2E86AB;
87
- padding: 25px;
88
- border-radius: 15px;
89
- margin: 15px 0;
90
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
91
- box-shadow: 0 6px 15px rgba(0,0,0,0.1);
92
  }
93
  .stButton button {
94
  width: 100%;
@@ -96,58 +124,40 @@ def local_css():
96
  color: white;
97
  font-weight: bold;
98
  border: none;
99
- padding: 14px 28px;
100
- border-radius: 10px;
101
- font-size: 1.1rem;
102
  transition: all 0.3s ease;
103
- box-shadow: 0 4px 8px rgba(31,119,180,0.3);
104
  }
105
  .stButton button:hover {
106
- transform: translateY(-2px);
107
- box-shadow: 0 6px 12px rgba(31,119,180,0.4);
108
  background: linear-gradient(45deg, #2e86ab, #1f77b4);
109
  }
110
- .dataframe {
111
- border-radius: 10px;
112
- overflow: hidden;
113
- box-shadow: 0 4px 8px rgba(0,0,0,0.1);
114
- }
115
- .dataframe th {
116
- background: linear-gradient(135deg, #1f77b4, #2e86ab);
117
- color: white;
118
- font-weight: bold;
119
- padding: 12px;
120
- }
121
- .dataframe td {
122
- padding: 10px;
123
- border-bottom: 1px solid #e0e0e0;
124
- }
125
- .dataframe tr:nth-child(even) {
126
- background-color: #f8f9fa;
127
- }
128
- .dataframe tr:hover {
129
- background-color: #e3f2fd;
130
- }
131
- .sidebar .sidebar-content {
132
- background: linear-gradient(180deg, #1f77b4 0%, #2e86ab 100%);
133
- }
134
  .chat-message {
135
- padding: 1rem;
136
- border-radius: 0.5rem;
137
- margin-bottom: 1rem;
138
- display: flex;
139
- flex-direction: column;
140
  }
141
- .chat-message.user {
142
- background-color: #2b5797;
143
  color: white;
144
  margin-left: 20%;
 
145
  }
146
- .chat-message.assistant {
147
- background-color: #f0f2f6;
148
  color: #333;
149
  margin-right: 20%;
150
  }
 
 
 
 
 
 
151
  </style>
152
  """, unsafe_allow_html=True)
153
 
@@ -159,233 +169,452 @@ def init_session_state():
159
  st.session_state.risk_scores = {}
160
  if 'assessment_history' not in st.session_state:
161
  st.session_state.assessment_history = []
 
 
 
 
162
 
163
- # Load trained models
164
- @st.cache_resource(show_spinner=False)
165
- def load_models():
166
- try:
167
- # Try to load models with multiple possible file extensions
168
- model_files = {
169
- 'heart': [
170
- 'heart_disease_model.pkl', 'heart_model.pkl', 'heart_disease_model.joblib',
171
- 'models/heart_disease_model.pkl', 'models/heart_model.pkl'
172
- ],
173
- 'diabetes': [
174
- 'diabetes_model.pkl', 'diabetes_model.joblib',
175
- 'models/diabetes_model.pkl', 'models/diabetes_model.joblib'
176
- ],
177
- 'hypertension': [
178
- 'hypertension_model.pkl', 'hypertension_model.joblib',
179
- 'models/hypertension_model.pkl', 'models/hypertension_model.joblib'
180
- ]
181
- }
182
-
183
- def find_and_load_model(file_list, model_name):
184
- for file_path in file_list:
185
- if os.path.exists(file_path):
186
- try:
187
- if file_path.endswith('.pkl'):
188
- return joblib.load(file_path)
189
- elif file_path.endswith('.joblib'):
190
- return joblib.load(file_path)
191
- except Exception as e:
192
- st.warning(f"Warning loading {model_name} from {file_path}: {str(e)}")
193
- continue
194
- return None
195
-
196
- heart_model = find_and_load_model(model_files['heart'], "Heart Disease")
197
- diabetes_model = find_and_load_model(model_files['diabetes'], "Diabetes")
198
- hypertension_model = find_and_load_model(model_files['hypertension'], "Hypertension")
199
-
200
- # If no models found, create simple rule-based models as fallback
201
- if heart_model is None:
202
- st.info("🔍 Using rule-based heart disease assessment")
203
- heart_model = "rule_based"
204
- if diabetes_model is None:
205
- st.info("🔍 Using rule-based diabetes assessment")
206
- diabetes_model = "rule_based"
207
- if hypertension_model is None:
208
- st.info("🔍 Using rule-based hypertension assessment")
209
- hypertension_model = "rule_based"
210
-
211
- return heart_model, diabetes_model, hypertension_model
212
-
213
- except Exception as e:
214
- st.error(f"❌ Error loading models: {str(e)}")
215
- # Return rule-based fallback
216
- return "rule_based", "rule_based", "rule_based"
217
 
218
- class HealthcareAssistant:
219
  def __init__(self):
220
- # Comprehensive medical knowledge base
221
- self.medical_knowledge = {
222
- 'heart_health': {
223
- 'English': """
224
- **Heart Health Management Guidelines:**
225
-
226
- **Risk Factors to Monitor:**
227
- • High blood pressure (>140/90 mmHg)
228
- • Elevated cholesterol levels (>200 mg/dL)
229
- • Smoking and tobacco use
230
- • Diabetes and pre-diabetes
231
- • Obesity (BMI > 30)
232
- • Physical inactivity
233
- • Family history of heart disease
234
-
235
- **Preventive Measures:**
236
- • Regular exercise (30 mins, 5 days/week)
237
- • Heart-healthy diet (Mediterranean diet recommended)
238
- • Maintain healthy weight
239
- • Regular blood pressure monitoring
240
- • Annual cholesterol checks
241
- • Stress management techniques
242
-
243
- **Warning Signs - Seek Immediate Care:**
244
- • Chest pain or discomfort
245
- • Shortness of breath
246
- • Pain radiating to arm, neck, or jaw
247
- • Dizziness or fainting
248
- • Irregular heartbeat
249
- """,
250
- 'Urdu': """
251
- **دل کی صحت کے انتظام کے رہنما اصول:**
252
-
253
- **نگرانی کرنے والے خطرے کے عوامل:**
254
- • ہائی بلڈ پریشر (>140/90 mmHg)
255
- • کولیسٹرول کی بلند سطح (>200 mg/dL)
256
- • سگریٹ نوشی اور تمباکو کا استعمال
257
- • ذیابیطس اور پیش ذیابیطس
258
- • موٹاپا (BMI > 30)
259
- • جسمانی غیر فعالیت
260
- • دل کی بیماری کی خاندانی تاریخ
261
-
262
- **احتیاطی تدابیر:**
263
- • باقاعدہ ورزش (30 منٹ، ہفتے میں 5 دن)
264
- • دل کی صحت کے لیے مفید غذا (بحیرہ روم کی غذا تجویز کردہ)
265
- • صحت مند وزن برقرار رکھیں
266
- • بلڈ پریشر کی باقاعدہ نگرانی
267
- • سالانہ کولیسٹرول چیک
268
- • تناؤ کے انتظام کی تکنیکیں
269
-
270
- **انتباہی علامات - فوری دیکھ بھال حاصل کریں:**
271
- • سینے میں درد یا بے چینی
272
- • سانس لینے میں دشواری
273
- • بازو، گردن یا جبڑے میں پھیلنے والا درد
274
- • چکر آنا یا بیہوش ہونا
275
- • بے قاعدہ دل کی دھڑکن
276
- """
277
  },
278
  'diabetes': {
279
- 'English': """
280
- **Diabetes Management Protocol:**
281
-
282
- **Key Monitoring Parameters:**
283
- • Fasting blood sugar: 80-130 mg/dL
284
- • Post-meal blood sugar: <180 mg/dL
285
- • HbA1c: <7.0%
286
- • Blood pressure: <140/90 mmHg
287
- • Cholesterol levels (LDL <100 mg/dL)
288
-
289
- **Management Strategies:**
290
- • Regular glucose monitoring
291
- • Balanced carbohydrate intake
292
- • Regular physical activity
293
- • Medication adherence
294
- • Foot care and examination
295
- • Regular eye examinations
296
-
297
- **Emergency Symptoms:**
298
- • Blood sugar >300 mg/dL or <70 mg/dL
299
- • Confusion or disorientation
300
- • Excessive thirst and urination
301
- • Blurred vision
302
- • Fruity breath odor
303
- """,
304
- 'Urdu': """
305
- **ذیابیطس کے انتظام کا پروٹوکول:**
306
-
307
- **اہم نگرانی کے پیرامیٹرز:**
308
- • فاسٹنگ بلڈ شوگر: 80-130 mg/dL
309
- • کھانے کے بعد بلڈ شوگر: <180 mg/dL
310
- • HbA1c: <7.0%
311
- • بلڈ پریشر: <140/90 mmHg
312
- • کولیسٹرول کی سطح (LDL <100 mg/dL)
313
-
314
- **انتظام کی حکمت عملی:**
315
- • گلوکوز کی باقاعدہ نگرانی
316
- • متوازن کاربوہائیڈریٹ کی مقدار
317
- • باقاعدہ جسمانی سرگرمی
318
- • ادویات کی پابندی
319
- • پاؤں کی دیکھ بھال اور معائنہ
320
- • باقاعدہ آنکھوں کے معائنے
321
-
322
- **ہنگامی علامات:**
323
- • بلڈ شوگر >300 mg/dL یا <70 mg/dL
324
- • الجھن یا بے ترتیبی
325
- • ضرورت سے زیادہ پیاس اور پیشاب
326
- • دھندلا نظر آنا
327
- • پھل کی سی بو والی سانس
328
- """
329
  },
330
  'hypertension': {
331
- 'English': """
332
- **Hypertension Control Guidelines:**
333
-
334
- **Blood Pressure Classification:**
335
- • Normal: <120/80 mmHg
336
- • Elevated: 120-129/<80 mmHg
337
- • Stage 1: 130-139/80-89 mmHg
338
- • Stage 2: ≥140/90 mmHg
339
-
340
- **Lifestyle Modifications:**
341
- • DASH diet (Dietary Approaches to Stop Hypertension)
342
- • Sodium restriction (<2,300 mg/day)
343
- • Regular aerobic exercise
344
- • Weight management
345
- • Alcohol moderation
346
- • Stress reduction techniques
347
-
348
- **Monitoring Schedule:**
349
- • Daily BP monitoring if uncontrolled
350
- • Weekly if well-controlled
351
- • Regular medication review
352
- • Annual kidney function tests
353
- """,
354
- 'Urdu': """
355
- **ہائی بلڈ پریشر کنٹرول گائیڈ لائنز:**
356
-
357
- **بلڈ پریشر کی درجہ بندی:**
358
- • نارمل: <120/80 mmHg
359
- • بلند: 120-129/<80 mmHg
360
- • اسٹیج 1: 130-139/80-89 mmHg
361
- • اسٹیج 2: ≥140/90 mmHg
362
-
363
- **طرز زندگی میں تبدیلیاں:**
364
- • ڈیش ڈائٹ (ہائی بلڈ پریشر روکنے کے لیے غذائی طریقے)
365
- • سوڈیم کی پابندی (<2,300 mg/day)
366
- • باقاعدہ ایروبک ورزش
367
- • وزن کا انتظام
368
- • شراب میں اعتدال
369
- • تناؤ میں کمی کی تکنیکیں
370
-
371
- **نگرانی کا شیڈول:**
372
- • روزانہ بی پی مانیٹرنگ اگر کنٹرول نہ ہو
373
- • ہفتہ وار اگر اچھی طرح کنٹرول ہو
374
- • ادویات کی باقاعدہ جائزہ
375
- • سالانہ گردے کے فنکشن ٹیسٹ
376
- """
377
  }
378
  }
379
 
380
- def get_medical_advice(self, topic, language='English'):
381
- """Provide structured medical advice based on topic"""
382
- if topic in self.medical_knowledge:
383
- return self.medical_knowledge[topic][language]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
384
  else:
385
- if language == 'English':
386
- return "**General Health Advice:**\n\n• Maintain regular health check-ups\n• Follow a balanced diet\n• Stay physically active\n• Get adequate sleep (7-9 hours)\n• Manage stress effectively\n• Avoid smoking and limit alcohol\n• Stay hydrated with 8-10 glasses of water daily"
387
- else:
388
- return "**عام صحت کے مشورے:**\n\n• باقاعدہ صحت کی جانچ برقرار رکھیں\n• متوازن غذا کی پیروی کریں\n• جسمانی طور پر متحرک رہیں\n• مناسب نیند لیں (7-9 گھنٹے)\n• تناؤ کو مؤثر طریقے سے منظم کریں\n• تمباکو نوشی سے پرہیز کریں اور شراب کو محدود کریں\n• روزانہ 8-10 گلاس پانی پی کر ہائیڈریٹ رہیں"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
389
 
390
  def calculate_priority_score(heart_risk, diabetes_risk, hypertension_risk):
391
  """Calculate integrated priority score with clinical weighting"""
@@ -432,260 +661,133 @@ def validate_patient_data(age, bp_systolic, bp_diastolic, heart_rate):
432
  return errors
433
 
434
  def predict_risk_rule_based(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms):
435
- """Rule-based risk prediction as fallback when models are not available"""
436
 
437
- # Heart disease risk calculation
438
  heart_risk = 0.0
439
- heart_risk += min(0.3, (age - 30) / 200) # Age factor
440
- heart_risk += min(0.2, (bp_systolic - 120) / 300) # BP factor
441
- heart_risk += min(0.2, (cholesterol - 150) / 500) # Cholesterol factor
442
- heart_risk += min(0.3, (bmi - 20) / 50) # BMI factor
443
- if symptoms['chest_pain']:
444
- heart_risk += 0.3
445
- if symptoms['shortness_breath']:
446
- heart_risk += 0.2
447
- if symptoms['palpitations']:
448
- heart_risk += 0.1
449
-
450
- # Diabetes risk calculation
451
  diabetes_risk = 0.0
452
- diabetes_risk += min(0.3, (age - 30) / 200)
453
- diabetes_risk += min(0.4, (glucose - 80) / 300)
454
- diabetes_risk += min(0.3, (bmi - 20) / 50)
455
- if symptoms['fatigue']:
456
- diabetes_risk += 0.2
457
- if symptoms['blurred_vision']:
458
- diabetes_risk += 0.1
459
-
460
- # Hypertension risk calculation
461
  hypertension_risk = 0.0
462
- hypertension_risk += min(0.3, (age - 30) / 200)
463
- hypertension_risk += min(0.4, (bp_systolic - 120) / 200)
464
- hypertension_risk += min(0.3, (bmi - 20) / 50)
465
- if symptoms['dizziness']:
466
- hypertension_risk += 0.2
467
- if symptoms['palpitations']:
468
- hypertension_risk += 0.1
469
 
470
- return min(1.0, heart_risk), min(1.0, diabetes_risk), min(1.0, hypertension_risk)
471
-
472
- def prepare_features_for_models(age, bp_systolic, bp_diastolic, heart_rate, cholesterol, glucose, bmi, symptoms):
473
- """Prepare feature arrays for different models based on their training requirements"""
 
 
 
 
 
 
 
 
 
474
 
475
- # Heart Disease Model Features
476
- heart_features = np.array([[
477
- age,
478
- bp_systolic,
479
- cholesterol,
480
- heart_rate,
481
- symptoms['chest_pain'],
482
- symptoms['shortness_breath'],
483
- symptoms['palpitations'],
484
- bmi,
485
- glucose
486
- ]])
487
 
488
- # Diabetes Model Features
489
- diabetes_features = np.array([[
490
- age,
491
- glucose,
492
- bmi,
493
- cholesterol,
494
- symptoms['fatigue'],
495
- symptoms['blurred_vision'],
496
- bp_systolic,
497
- heart_rate
498
- ]])
499
 
500
- # Hypertension Model Features
501
- hypertension_features = np.array([[
502
- age,
503
- bp_systolic,
504
- bp_diastolic,
505
- bmi,
506
- symptoms['dizziness'],
507
- symptoms['palpitations'],
508
- heart_rate,
509
- cholesterol
510
- ]])
511
 
512
- return heart_features, diabetes_features, hypertension_features
513
-
514
- def create_patient_report(patient_data, risk_scores, language='English'):
515
- """Generate comprehensive patient report"""
516
- report = {}
 
 
 
 
517
 
518
- if language == 'English':
519
- report['header'] = "PATIENT ASSESSMENT REPORT"
520
- report['patient_info'] = f"""
521
- **Patient Details:**
522
- - Name: {patient_data.get('name', 'Not provided')}
523
- - Age: {patient_data.get('age', 'Not provided')} years
524
- - Gender: {patient_data.get('gender', 'Not provided')}
525
- - Contact: {patient_data.get('contact', 'Not provided')}
526
- """
527
-
528
- report['clinical_findings'] = f"""
529
- **Clinical Parameters:**
530
- - Blood Pressure: {patient_data.get('bp_systolic', 'N/A')}/{patient_data.get('bp_diastolic', 'N/A')} mmHg
531
- - Heart Rate: {patient_data.get('heart_rate', 'N/A')} bpm
532
- - Cholesterol: {patient_data.get('cholesterol', 'N/A')} mg/dL
533
- - Glucose: {patient_data.get('glucose', 'N/A')} mg/dL
534
- - BMI: {patient_data.get('bmi', 'N/A')}
535
- """
536
-
537
- report['risk_assessment'] = f"""
538
- **Risk Assessment Results:**
539
- - Heart Disease Risk: {risk_scores.get('heart', 0):.1%}
540
- - Diabetes Risk: {risk_scores.get('diabetes', 0):.1%}
541
- - Hypertension Risk: {risk_scores.get('hypertension', 0):.1%}
542
- - Overall Priority Score: {risk_scores.get('priority', 0):.1%}
543
- """
544
-
545
- report['recommendation'] = f"""
546
- **Clinical Recommendation:**
547
- {risk_scores.get('recommendation', 'No recommendation available')}
548
- """
549
- else:
550
- report['header'] = "مریض تشخیص رپورٹ"
551
- report['patient_info'] = f"""
552
- **مریض کی تفصیلات:**
553
- - نام: {patient_data.get('name', 'فراہم نہیں کیا گیا')}
554
- - عمر: {patient_data.get('age', 'فراہم نہیں کیا گیا')} سال
555
- - جنس: {patient_data.get('gender', 'فراہم نہیں کیا گیا')}
556
- - رابطہ: {patient_data.get('contact', 'فراہم نہیں کیا گیا')}
557
- """
558
-
559
- report['clinical_findings'] = f"""
560
- **کلینیکل پیرامیٹرز:**
561
- - بلڈ پریشر: {patient_data.get('bp_systolic', 'N/A')}/{patient_data.get('bp_diastolic', 'N/A')} mmHg
562
- - دل کی دھڑکن: {patient_data.get('heart_rate', 'N/A')} bpm
563
- - کولیسٹرول: {patient_data.get('cholesterol', 'N/A')} mg/dL
564
- - گلوکوز: {patient_data.get('glucose', 'N/A')} mg/dL
565
- - BMI: {patient_data.get('bmi', 'N/A')}
566
- """
567
-
568
- report['risk_assessment'] = f"""
569
- **خطرے کے تشخیص کے نتائج:**
570
- - دل کی بیماری کا خطرہ: {risk_scores.get('heart', 0):.1%}
571
- - ذیابیطس کا خطرہ: {risk_scores.get('diabetes', 0):.1%}
572
- - ہائی بلڈ پریشر کا خطرہ: {risk_scores.get('hypertension', 0):.1%}
573
- - مجموعی ترجیحی اسکور: {risk_scores.get('priority', 0):.1%}
574
- """
575
-
576
- report['recommendation'] = f"""
577
- **کلینیکل سفارش:**
578
- {risk_scores.get('recommendation', 'کوئی سفارش دستیاب نہیں')}
579
- """
580
 
581
- return report
 
 
 
 
 
 
 
 
 
 
 
582
 
583
  def main():
584
  # Load custom CSS
585
  local_css()
586
  init_session_state()
587
 
588
- # Load models
589
- with st.spinner("🔄 Loading AI models..."):
590
- heart_model, diabetes_model, hypertension_model = load_models()
591
 
592
- # Initialize healthcare assistant
593
- healthcare_assistant = HealthcareAssistant()
 
 
 
594
 
595
- # Professional sidebar
596
- with st.sidebar:
597
- st.markdown("""
598
- <div style='text-align: center; padding: 20px; background: linear-gradient(135deg, #1f77b4, #2e86ab);
599
- border-radius: 15px; color: white; margin-bottom: 20px;'>
600
- <h2 style='margin: 0; font-size: 1.8rem;'>🏥 AI-Priority OPD</h2>
601
- <p style='margin: 5px 0; font-size: 0.9rem;'>Smart Patient Triage System</p>
602
- </div>
603
- """, unsafe_allow_html=True)
604
-
605
- # Language selector
606
- language = st.radio(
607
- "Select Language / زبان منتخب کریں",
608
- ["English", "Urdu"],
609
- key="language_selector",
610
- index=0
611
- )
612
-
613
- st.markdown("---")
614
-
615
- # Quick actions
616
- if language == "English":
617
- st.subheader("🚀 Quick Actions")
618
- col1, col2 = st.columns(2)
619
-
620
- with col1:
621
- if st.button("🆕 New Patient", use_container_width=True):
622
- st.session_state.patient_data = {}
623
- st.session_state.risk_scores = {}
624
- st.rerun()
625
-
626
- with col2:
627
- if st.button("📊 Dashboard", use_container_width=True):
628
- st.rerun()
629
-
630
- st.markdown("---")
631
- st.subheader("📈 System Status")
632
-
633
- # System metrics
634
- metrics_col1, metrics_col2 = st.columns(2)
635
-
636
- with metrics_col1:
637
- st.metric("Models Loaded", "3/3", "100%")
638
-
639
- with metrics_col2:
640
- st.metric("Assessments", len(st.session_state.assessment_history))
641
-
642
- st.info("✅ System Ready for Patient Assessment")
643
-
644
- else:
645
- st.subheader("🚀 فوری اقدامات")
646
- col1, col2 = st.columns(2)
647
-
648
- with col1:
649
- if st.button("🆕 نیا مریض", use_container_width=True):
650
- st.session_state.patient_data = {}
651
- st.session_state.risk_scores = {}
652
- st.rerun()
653
-
654
- with col2:
655
- if st.button("📊 ڈیش بورڈ", use_container_width=True):
656
- st.rerun()
657
-
658
- st.markdown("---")
659
- st.subheader("📈 سسٹم کی حالت")
660
-
661
- # System metrics
662
- metrics_col1, metrics_col2 = st.columns(2)
663
-
664
- with metrics_col1:
665
- st.metric("ماڈل لوڈ ہو گئے", "3/3", "100%")
666
-
667
- with metrics_col2:
668
- st.metric("تشخیص", len(st.session_state.assessment_history))
669
-
670
- st.info("✅ سسٹم مریض کی تشخیص کے لیے تیار ہے")
671
 
672
- # Main header with professional design
673
- st.markdown("""
674
- <div style='background: linear-gradient(135deg, #1f77b4, #2e86ab); padding: 30px;
675
- border-radius: 15px; text-align: center; color: white; margin-bottom: 30px;
676
- box-shadow: 0 8px 25px rgba(31,119,180,0.3);'>
677
- <h1 class='main-header' style='color: white; margin: 0;'>🏥 AI-Priority OPD System</h1>
678
- <p style='font-size: 1.2rem; margin: 10px 0 0 0; opacity: 0.9;'>
679
- Smart Patient Triage and Priority Management for Healthcare Excellence
680
- </p>
681
  </div>
682
- """, unsafe_allow_html=True)
683
 
684
  # Create tabs
685
  if language == "English":
686
- tab_names = ["Patient Assessment", "Medical Guidelines", "Analytics Dashboard"]
687
  else:
688
- tab_names = ["مریض تشخیص", "طبی رہنما خطوط", "تجزیاتی ڈیش بورڈ"]
689
 
690
  tab1, tab2, tab3 = st.tabs(tab_names)
691
 
@@ -694,10 +796,10 @@ def main():
694
  st.markdown('<div class="section-container">', unsafe_allow_html=True)
695
 
696
  if language == "English":
697
- st.markdown('<div class="sub-header">👨‍⚕️ Comprehensive Patient Assessment</div>', unsafe_allow_html=True)
698
  st.write("Complete the following form for comprehensive patient risk assessment and priority scoring")
699
  else:
700
- st.markdown('<div class="sub-header">👨‍⚕️ جامع مریض تشخیص</div>', unsafe_allow_html=True)
701
  st.write("جامع مریض کے خطرے کی تشخیص اور ترجیحی اسکورنگ کے لیے درج ذیل فارم کو مکمل کریں")
702
 
703
  with st.form("patient_assessment_form"):
@@ -706,14 +808,14 @@ def main():
706
  with col1:
707
  # Basic Information
708
  if language == "English":
709
- st.markdown("**Personal Information**")
710
  name = st.text_input("Full Name", placeholder="Enter patient's full name")
711
  age = st.number_input("Age", min_value=1, max_value=120, value=45,
712
  help="Patient's age in years")
713
  gender = st.selectbox("Gender", ["Male", "Female", "Other"])
714
  contact = st.text_input("Contact Number", placeholder="03XX-XXXXXXX")
715
  else:
716
- st.markdown("**ذاتی معلومات**")
717
  name = st.text_input("مکمل نام", placeholder="مریض کا مکمل نام درج کریں")
718
  age = st.number_input("عمر", min_value=1, max_value=120, value=45,
719
  help="مریض کی عمر سالوں میں")
@@ -723,41 +825,41 @@ def main():
723
  with col2:
724
  # Vital Signs
725
  if language == "English":
726
- st.markdown("**Clinical Parameters**")
727
- bp_systolic = st.number_input("Blood Pressure (systolic)",
728
- min_value=70, max_value=250, value=120,
729
- help="Systolic blood pressure in mmHg")
730
- bp_diastolic = st.number_input("Blood Pressure (diastolic)",
731
- min_value=40, max_value=150, value=80,
732
- help="Diastolic blood pressure in mmHg")
733
- heart_rate = st.number_input("Heart Rate (bpm)",
734
- min_value=30, max_value=200, value=72,
735
- help="Heart beats per minute")
736
- cholesterol = st.number_input("Cholesterol Level (mg/dL)",
737
- min_value=100, max_value=400, value=180)
738
- glucose = st.number_input("Blood Glucose (mg/dL)",
739
- min_value=50, max_value=500, value=95)
740
  bmi = st.slider("BMI", min_value=15.0, max_value=40.0, value=23.5, step=0.1)
741
  else:
742
- st.markdown("**کلینیکل پیرامیٹرز**")
743
- bp_systolic = st.number_input("بلڈ پریشر (سسٹولک)",
744
- min_value=70, max_value=250, value=120,
745
- help="سسٹولک بلڈ پریشر mmHg میں")
746
- bp_diastolic = st.number_input("بلڈ پریشر (ڈائیسٹولک)",
747
- min_value=40, max_value=150, value=80,
748
- help="ڈائیسٹولک بلڈ پریشر mmHg میں")
749
- heart_rate = st.number_input("دل کی دھڑکن (bpm)",
750
- min_value=30, max_value=200, value=72,
751
- help="دل کی دھڑکن فی منٹ")
752
- cholesterol = st.number_input("کولیسٹرول کی سطح (mg/dL)",
753
- min_value=100, max_value=400, value=180)
754
- glucose = st.number_input("خون میں گلوکوز (mg/dL)",
755
- min_value=50, max_value=500, value=95)
756
  bmi = st.slider("باڈی ماس انڈیکس", min_value=15.0, max_value=40.0, value=23.5, step=0.1)
757
 
758
  # Symptoms Section
759
  if language == "English":
760
- st.markdown("**Reported Symptoms**")
761
  col3, col4 = st.columns(2)
762
  with col3:
763
  chest_pain = st.checkbox("Chest Pain or Discomfort")
@@ -768,7 +870,7 @@ def main():
768
  dizziness = st.checkbox("Dizziness or Lightheadedness")
769
  blurred_vision = st.checkbox("Blurred Vision")
770
  else:
771
- st.markdown("**رپورٹ کردہ علامات**")
772
  col3, col4 = st.columns(2)
773
  with col3:
774
  chest_pain = st.checkbox("سینے میں درد یا بے چینی")
@@ -799,12 +901,12 @@ def main():
799
  with st.spinner("🔍 Analyzing patient data and calculating risks..."):
800
  # Prepare symptoms dictionary
801
  symptoms_dict = {
802
- 'chest_pain': 1 if chest_pain else 0,
803
- 'shortness_breath': 1 if shortness_breath else 0,
804
- 'palpitations': 1 if palpitations else 0,
805
- 'fatigue': 1 if fatigue else 0,
806
- 'dizziness': 1 if dizziness else 0,
807
- 'blurred_vision': 1 if blurred_vision else 0
808
  }
809
 
810
  # Store patient data
@@ -822,31 +924,10 @@ def main():
822
  'symptoms': symptoms_dict
823
  }
824
 
825
- # Get predictions based on available models
826
- if heart_model != "rule_based" and diabetes_model != "rule_based" and hypertension_model != "rule_based":
827
- # Use trained models
828
- heart_features, diabetes_features, hypertension_features = prepare_features_for_models(
829
- age, bp_systolic, bp_diastolic, heart_rate, cholesterol, glucose, bmi, symptoms_dict
830
- )
831
-
832
- heart_risk_proba = heart_model.predict_proba(heart_features)[0][1]
833
- diabetes_risk_proba = diabetes_model.predict_proba(diabetes_features)[0][1]
834
- hypertension_risk_proba = hypertension_model.predict_proba(hypertension_features)[0][1]
835
- else:
836
- # Use rule-based prediction
837
- heart_risk_proba, diabetes_risk_proba, hypertension_risk_proba = predict_risk_rule_based(
838
- age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms_dict
839
- )
840
-
841
- # Apply symptom modifiers for clinical severity
842
- if chest_pain:
843
- heart_risk_proba = min(1.0, heart_risk_proba * 1.3)
844
- if shortness_breath:
845
- heart_risk_proba = min(1.0, heart_risk_proba * 1.2)
846
- if fatigue:
847
- diabetes_risk_proba = min(1.0, diabetes_risk_proba * 1.2)
848
- if dizziness:
849
- hypertension_risk_proba = min(1.0, hypertension_risk_proba * 1.3)
850
 
851
  # Calculate integrated priority score
852
  priority_score = calculate_priority_score(
@@ -880,9 +961,9 @@ def main():
880
 
881
  # Risk Scores Visualization
882
  if language == "English":
883
- st.markdown('<div class="sub-header">📊 Disease Risk Assessment Dashboard</div>', unsafe_allow_html=True)
884
  else:
885
- st.markdown('<div class="sub-header">📊 بیماری کے خطرے کی تشخیص ڈیش بورڈ</div>', unsafe_allow_html=True)
886
 
887
  col5, col6, col7, col8 = st.columns(4)
888
 
@@ -948,21 +1029,6 @@ def main():
948
  st.success("✅ **روٹین کیئر:** معمول کی اپائنٹمنٹ سسٹم کے اندر شیڈول کریں۔")
949
 
950
  st.markdown('</div>', unsafe_allow_html=True)
951
-
952
- # Generate and display patient report
953
- if language == "English":
954
- st.markdown('<div class="sub-header">📋 Patient Assessment Report</div>', unsafe_allow_html=True)
955
- else:
956
- st.markdown('<div class="sub-header">📋 مریض تشخیص رپورٹ</div>', unsafe_allow_html=True)
957
-
958
- report = create_patient_report(st.session_state.patient_data, st.session_state.risk_scores, language)
959
-
960
- with st.expander("View Complete Patient Report" if language == "English" else "مکمل مریض ��پورٹ دیکھیں", expanded=True):
961
- st.markdown(f"**{report['header']}**")
962
- st.markdown(report['patient_info'])
963
- st.markdown(report['clinical_findings'])
964
- st.markdown(report['risk_assessment'])
965
- st.markdown(report['recommendation'])
966
 
967
  except Exception as e:
968
  st.error(f"❌ Error in risk assessment: {str(e)}")
@@ -970,165 +1036,166 @@ def main():
970
  st.markdown('</div>', unsafe_allow_html=True)
971
 
972
  with tab2:
973
- # Medical Guidelines
974
  st.markdown('<div class="section-container">', unsafe_allow_html=True)
975
 
976
  if language == "English":
977
- st.markdown('<div class="sub-header">📚 Medical Guidelines & Health Information</div>', unsafe_allow_html=True)
978
- st.write("Access comprehensive medical guidelines and health information for better patient care")
979
  else:
980
- st.markdown('<div class="sub-header">📚 طبی رہنما خطوط اور صحت کی معلومات</div>', unsafe_allow_html=True)
981
- st.write("بہتر مریض کی دیکھ بھال کے لیے جامع طبی رہنما خطوط اور صحت کی معلومات تک رسائی حاصل کریں")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
982
 
983
- # Medical topics selection
984
  if language == "English":
985
- topic = st.selectbox(
986
- "Select Medical Topic",
987
- ["Heart Health", "Diabetes Management", "Hypertension Control", "General Health"]
988
- )
989
  else:
990
- topic = st.selectbox(
991
- "طبی موضوع منتخب کریں",
992
- ["دل کی صحت", "ذیابیطس کا انتظام", "ہائی بلڈ پریشر کنٹرول", "عام صحت"]
993
- )
994
 
995
- # Display medical information based on selected topic
996
- if topic == "Heart Health" or topic == "دل کی صحت":
997
- advice = healthcare_assistant.get_medical_advice('heart_health', language)
998
- elif topic == "Diabetes Management" or topic == "ذیابیطس کا انتظام":
999
- advice = healthcare_assistant.get_medical_advice('diabetes', language)
1000
- elif topic == "Hypertension Control" or topic == "ہائی بلڈ پریشر کنٹرول":
1001
- advice = healthcare_assistant.get_medical_advice('hypertension', language)
1002
- else:
1003
- advice = healthcare_assistant.get_medical_advice('general', language)
1004
 
1005
- st.markdown(advice)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1006
 
1007
  st.markdown('</div>', unsafe_allow_html=True)
1008
 
1009
  with tab3:
1010
- # Analytics Dashboard
1011
  st.markdown('<div class="section-container">', unsafe_allow_html=True)
1012
 
1013
  if language == "English":
1014
- st.markdown('<div class="sub-header">📈 System Analytics & Performance Dashboard</div>', unsafe_allow_html=True)
1015
- st.write("Comprehensive analytics and performance metrics for the OPD system")
1016
  else:
1017
- st.markdown('<div class="sub-header">📈 سسٹم تجزیات اور کارکردگی ڈیش بورڈ</div>', unsafe_allow_html=True)
1018
- st.write("OPD سسٹم کے لیے جامع تجزیات اور کارکردگی کے پیمانے")
1019
 
1020
- # Real-time performance metrics
1021
- col9, col10, col11, col12 = st.columns(4)
1022
-
1023
- with col9:
1024
- st.markdown('<div class="metric-card">', unsafe_allow_html=True)
1025
- if language == "English":
1026
- st.metric("Total Assessments", len(st.session_state.assessment_history), "Patients")
1027
- else:
1028
- st.metric("کل تشخیص", len(st.session_state.assessment_history), "مریض")
1029
- st.markdown('</div>', unsafe_allow_html=True)
1030
-
1031
- with col10:
1032
- st.markdown('<div class="metric-card">', unsafe_allow_html=True)
1033
  if language == "English":
1034
- st.metric("System Uptime", "99.8%", "0.2%")
1035
  else:
1036
- st.metric("سسٹم اپ ٹائم", "99.8%", "0.2%")
1037
- st.markdown('</div>', unsafe_allow_html=True)
1038
-
1039
- with col11:
1040
- st.markdown('<div class="metric-card">', unsafe_allow_html=True)
 
 
 
 
1041
  if language == "English":
1042
- st.metric("Model Accuracy", "96.2%", "AI Models")
1043
  else:
1044
- st.metric("ماڈل درستگی", "96.2%", "AI ماڈل")
1045
- st.markdown('</div>', unsafe_allow_html=True)
1046
-
1047
- with col12:
1048
- st.markdown('<div class="metric-card">', unsafe_allow_html=True)
1049
  if language == "English":
1050
- st.metric("Avg. Processing", "< 2s", "Fast")
1051
  else:
1052
- st.metric("اوسط پروسیسنگ", "< 2s", "تیز")
1053
- st.markdown('</div>', unsafe_allow_html=True)
1054
-
1055
- # Analytics Charts
1056
- if st.session_state.assessment_history:
1057
- col_chart1, col_chart2 = st.columns(2)
1058
 
1059
- with col_chart1:
1060
- if language == "English":
1061
- st.subheader("Risk Distribution Analysis")
1062
- else:
1063
- st.subheader("خطرے کی تقسیم کا تجزیہ")
1064
-
1065
- # Get the latest assessment
1066
- latest_assessment = st.session_state.assessment_history[-1]
1067
- risk_data = pd.DataFrame({
1068
- 'Condition': ['Heart Disease', 'Diabetes', 'Hypertension'],
1069
- 'Risk Score': [
1070
- latest_assessment['risk_scores']['heart'],
1071
- latest_assessment['risk_scores']['diabetes'],
1072
- latest_assessment['risk_scores']['hypertension']
1073
- ]
1074
- })
1075
-
1076
- fig = px.bar(risk_data, x='Condition', y='Risk Score',
1077
- color='Risk Score', color_continuous_scale='RdYlGn_r',
1078
- title="Current Patient Risk Distribution")
1079
- st.plotly_chart(fig, use_container_width=True)
1080
 
1081
- with col_chart2:
1082
- if language == "English":
1083
- st.subheader("Priority Level Distribution")
1084
- else:
1085
- st.subheader("ترجیحی سطح کی تقسیم")
1086
-
1087
- # Calculate priority distribution from history
1088
- if len(st.session_state.assessment_history) > 1:
1089
- priorities = [assess['risk_scores']['level'] for assess in st.session_state.assessment_history]
1090
- priority_counts = pd.Series(priorities).value_counts()
1091
-
1092
- fig_pie = px.pie(values=priority_counts.values,
1093
- names=priority_counts.index,
1094
- title="Historical Priority Distribution")
1095
- st.plotly_chart(fig_pie, use_container_width=True)
1096
- else:
1097
- if language == "English":
1098
- st.info("Complete more assessments to view priority distribution")
1099
- else:
1100
- st.info("ترجیحی تقسیم دیکھنے کے لیے مزید تشخیص مکمل کریں")
1101
 
1102
- # Assessment History Table
1103
- if language == "English":
1104
- st.subheader("Assessment History")
1105
- else:
1106
- st.subheader("تشخیص کی تاریخ")
 
1107
 
1108
- history_data = []
1109
- for i, assessment in enumerate(st.session_state.assessment_history[-5:]): # Show last 5
1110
- history_data.append({
1111
- 'Date': assessment['timestamp'].strftime('%Y-%m-%d %H:%M'),
1112
- 'Patient': assessment['patient_data'].get('name', 'Unknown'),
1113
- 'Heart Risk': f"{assessment['risk_scores']['heart']:.1%}",
1114
- 'Diabetes Risk': f"{assessment['risk_scores']['diabetes']:.1%}",
1115
- 'Priority': assessment['risk_scores']['level']
1116
- })
1117
 
1118
- if history_data:
1119
- df_history = pd.DataFrame(history_data)
1120
- st.dataframe(df_history, use_container_width=True)
1121
- else:
1122
- if language == "English":
1123
- st.info("No assessment history available")
1124
- else:
1125
- st.info("تشخیص کی تاریخ دستیاب نہیں ہے")
 
 
 
 
 
 
1126
 
1127
  else:
1128
  if language == "English":
1129
- st.info("👆 Complete patient assessments to view analytics and performance metrics")
1130
  else:
1131
- st.info("👆 تجزیات اور کارکردگی کے پیمانے دیکھنے کے لیے مریض کی تشخیص مکمل کریں")
1132
 
1133
  st.markdown('</div>', unsafe_allow_html=True)
1134
 
 
10
  import plotly.graph_objects as go
11
  import plotly.express as px
12
  from datetime import datetime
13
+ import requests
14
+ import json
15
+ import base64
16
+ from fpdf import FPDF
17
+ import tempfile
18
 
19
  # Set page config first
20
  st.set_page_config(
21
+ page_title="MediPriority AI - Smart Healthcare Triage",
22
  page_icon="🏥",
23
  layout="wide",
24
+ initial_sidebar_state="collapsed"
25
  )
26
 
27
  # Professional CSS Styling
 
29
  st.markdown("""
30
  <style>
31
  .main-header {
32
+ font-size: 3.5rem;
33
  color: #1f77b4;
34
  text-align: center;
35
+ margin-bottom: 0.5rem;
36
+ font-weight: 800;
37
+ background: linear-gradient(135deg, #1f77b4, #2e86ab, #A23B72);
38
  -webkit-background-clip: text;
39
  -webkit-text-fill-color: transparent;
40
+ text-shadow: 0px 4px 8px rgba(0,0,0,0.2);
41
+ font-family: 'Arial', sans-serif;
42
  }
43
+ .quote-section {
44
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
45
+ color: white;
46
+ padding: 25px;
47
+ border-radius: 20px;
48
+ text-align: center;
49
+ margin: 20px 0;
50
+ box-shadow: 0 8px 25px rgba(0,0,0,0.15);
51
+ border: 3px solid #1f77b4;
52
+ }
53
+ .quote-text {
54
+ font-size: 1.4rem;
55
  font-weight: 600;
56
+ margin-bottom: 10px;
57
+ font-style: italic;
58
+ }
59
+ .quote-author {
60
+ font-size: 1.1rem;
61
+ opacity: 0.9;
62
  }
63
  .section-container {
64
  background: white;
65
+ padding: 30px;
66
+ border-radius: 20px;
67
+ box-shadow: 0 8px 25px rgba(0,0,0,0.1);
68
+ margin-bottom: 30px;
69
+ border: 2px solid #e0e0e0;
70
+ transition: all 0.3s ease;
71
+ }
72
+ .section-container:hover {
73
+ box-shadow: 0 12px 35px rgba(0,0,0,0.15);
74
+ transform: translateY(-2px);
75
  }
76
  .metric-card {
77
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
78
  color: white;
79
+ padding: 25px;
80
+ border-radius: 15px;
81
  text-align: center;
82
+ box-shadow: 0 6px 15px rgba(0,0,0,0.2);
83
+ transition: all 0.3s ease;
84
+ }
85
+ .metric-card:hover {
86
+ transform: translateY(-3px);
87
+ box-shadow: 0 10px 25px rgba(0,0,0,0.3);
88
  }
89
  .risk-high {
90
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
91
  color: white;
92
+ padding: 25px;
93
+ border-radius: 15px;
94
+ border-left: 8px solid #dc3545;
95
+ box-shadow: 0 6px 15px rgba(220,53,69,0.4);
96
  }
97
  .risk-medium {
98
  background: linear-gradient(135deg, #ffd93d, #ffcd3c);
99
  color: #333;
100
+ padding: 25px;
101
+ border-radius: 15px;
102
+ border-left: 8px solid #ffc107;
103
+ box-shadow: 0 6px 15px rgba(255,193,7,0.4);
104
  }
105
  .risk-low {
106
  background: linear-gradient(135deg, #6bcf7f, #28a745);
107
  color: white;
108
+ padding: 25px;
109
+ border-radius: 15px;
110
+ border-left: 8px solid #20c997;
111
+ box-shadow: 0 6px 15px rgba(40,167,69,0.4);
112
  }
113
  .priority-box {
114
+ border: 4px solid #2E86AB;
115
+ padding: 30px;
116
+ border-radius: 20px;
117
+ margin: 20px 0;
118
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
119
+ box-shadow: 0 8px 25px rgba(0,0,0,0.15);
120
  }
121
  .stButton button {
122
  width: 100%;
 
124
  color: white;
125
  font-weight: bold;
126
  border: none;
127
+ padding: 16px 32px;
128
+ border-radius: 12px;
129
+ font-size: 1.2rem;
130
  transition: all 0.3s ease;
131
+ box-shadow: 0 6px 15px rgba(31,119,180,0.4);
132
  }
133
  .stButton button:hover {
134
+ transform: translateY(-3px);
135
+ box-shadow: 0 10px 25px rgba(31,119,180,0.5);
136
  background: linear-gradient(45deg, #2e86ab, #1f77b4);
137
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  .chat-message {
139
+ padding: 15px;
140
+ border-radius: 15px;
141
+ margin: 10px 0;
142
+ border: 2px solid #e0e0e0;
 
143
  }
144
+ .user-message {
145
+ background: linear-gradient(135deg, #1f77b4, #2e86ab);
146
  color: white;
147
  margin-left: 20%;
148
+ text-align: right;
149
  }
150
+ .bot-message {
151
+ background: linear-gradient(135deg, #f8f9fa, #e9ecef);
152
  color: #333;
153
  margin-right: 20%;
154
  }
155
+ .language-selector {
156
+ position: absolute;
157
+ top: 20px;
158
+ right: 20px;
159
+ z-index: 1000;
160
+ }
161
  </style>
162
  """, unsafe_allow_html=True)
163
 
 
169
  st.session_state.risk_scores = {}
170
  if 'assessment_history' not in st.session_state:
171
  st.session_state.assessment_history = []
172
+ if 'chat_history' not in st.session_state:
173
+ st.session_state.chat_history = []
174
+ if 'current_language' not in st.session_state:
175
+ st.session_state.current_language = 'English'
176
 
177
+ # Healthcare quotes database
178
+ HEALTHCARE_QUOTES = [
179
+ {
180
+ 'english': "The art of medicine consists of amusing the patient while nature cures the disease.",
181
+ 'urdu': "طب کا فن مریض کو خوش رکھتے ہوئے فطرت کی بیماری کے علاج کا انتظار کرنا ہے۔",
182
+ 'author': "Voltaire"
183
+ },
184
+ {
185
+ 'english': "Health is the greatest gift, contentment the greatest wealth, faithfulness the best relationship.",
186
+ 'urdu': "صحت سب سے بڑی نعمت ہے، قناعت سب سے بڑی دولت ہے، اور وفا سب سے بہرا رشتہ ہے۔",
187
+ 'author': "Buddha"
188
+ },
189
+ {
190
+ 'english': "The doctor of the future will give no medication, but will interest his patients in the care of the human frame, diet and in the cause and prevention of disease.",
191
+ 'urdu': "مستقبل کا ڈاکٹر دوائی نہیں دے گا، بلکہ اپنے مریضوں کو انسانی جسم کی دیکھ بھال، غذا اور بیماریوں کی وجوہات اور روک تھام میں دلچسپی لے گا۔",
192
+ 'author': "Thomas Edison"
193
+ },
194
+ {
195
+ 'english': "Prevention is better than cure.",
196
+ 'urdu': "بچاؤ علاج سے بہتر ہے۔",
197
+ 'author': "Desiderius Erasmus"
198
+ },
199
+ {
200
+ 'english': "A healthy outside starts from the inside.",
201
+ 'urdu': "ایک صحت مند باہر کی طرف اندر سے شروع ہوتی ہے۔",
202
+ 'author': "Robert Urich"
203
+ }
204
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
 
206
+ class HealthcareChatbot:
207
  def __init__(self):
208
+ self.medical_knowledge_base = {
209
+ 'heart_disease': {
210
+ 'symptoms': ["Chest pain", "Shortness of breath", "Palpitations", "Fatigue", "Dizziness"],
211
+ 'risk_factors': ["High blood pressure", "High cholesterol", "Smoking", "Diabetes", "Obesity", "Family history"],
212
+ 'prevention': ["Healthy diet", "Regular exercise", "No smoking", "Weight management", "Stress management"],
213
+ 'emergency_signs': ["Severe chest pain", "Difficulty breathing", "Fainting", "Rapid heartbeat"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  },
215
  'diabetes': {
216
+ 'symptoms': ["Increased thirst", "Frequent urination", "Fatigue", "Blurred vision", "Slow healing"],
217
+ 'risk_factors': ["Family history", "Obesity", "High blood pressure", "Physical inactivity", "Age"],
218
+ 'prevention': ["Healthy eating", "Regular exercise", "Weight control", "Blood sugar monitoring"],
219
+ 'emergency_signs': ["Very high blood sugar", "Confusion", "Fruity breath", "Rapid breathing"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  },
221
  'hypertension': {
222
+ 'symptoms': ["Headaches", "Dizziness", "Blurred vision", "Shortness of breath", "Chest pain"],
223
+ 'risk_factors': ["Family history", "Age", "Obesity", "High salt intake", "Stress", "Alcohol"],
224
+ 'prevention': ["Low salt diet", "Regular exercise", "Weight management", "Stress reduction", "Limit alcohol"],
225
+ 'emergency_signs': ["Severe headache", "Chest pain", "Difficulty breathing", "Vision changes"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
  }
227
  }
228
 
229
+ def get_response(self, user_input, language='English'):
230
+ user_input = user_input.lower()
231
+
232
+ # Heart disease related queries
233
+ if any(word in user_input for word in ['heart', 'cardiac', 'chest pain', 'cholesterol']):
234
+ return self._format_heart_response(language)
235
+
236
+ # Diabetes related queries
237
+ elif any(word in user_input for word in ['diabetes', 'sugar', 'glucose', 'insulin']):
238
+ return self._format_diabetes_response(language)
239
+
240
+ # Hypertension related queries
241
+ elif any(word in user_input for word in ['blood pressure', 'hypertension', 'bp']):
242
+ return self._format_hypertension_response(language)
243
+
244
+ # General health queries
245
+ elif any(word in user_input for word in ['health', 'diet', 'exercise', 'fitness']):
246
+ return self._format_general_health_response(language)
247
+
248
+ # Symptoms assessment
249
+ elif any(word in user_input for word in ['symptom', 'pain', 'fever', 'headache']):
250
+ return self._format_symptoms_response(language)
251
+
252
+ # Default response
253
  else:
254
+ return self._format_default_response(language)
255
+
256
+ def _format_heart_response(self, language):
257
+ if language == 'English':
258
+ return f"""
259
+ **❤️ Heart Health Information**
260
+
261
+ **Common Symptoms:**
262
+ {chr(10).join(['• ' + symptom for symptom in self.medical_knowledge_base['heart_disease']['symptoms']])}
263
+
264
+ **Risk Factors:**
265
+ {chr(10).join(['• ' + factor for factor in self.medical_knowledge_base['heart_disease']['risk_factors']])}
266
+
267
+ **Prevention Tips:**
268
+ {chr(10).join(['• ' + tip for tip in self.medical_knowledge_base['heart_disease']['prevention']])}
269
+
270
+ **🚨 Seek Immediate Medical Attention for:**
271
+ {chr(10).join(['• ' + sign for sign in self.medical_knowledge_base['heart_disease']['emergency_signs']])}
272
+
273
+ *Note: This is general information. Consult a healthcare professional for personalized advice.*
274
+ """
275
+ else:
276
+ return f"""
277
+ **❤️ دل کی صحت کی معلومات**
278
+
279
+ **عام علامات:**
280
+ {chr(10).join(['• ' + symptom for symptom in ['سینے میں درد', 'سانس لینے میں دشواری', 'دل کی دھڑکن میں اضافہ', 'تھکاوٹ', 'چکر آنا']])}
281
+
282
+ **خطرے کے عوامل:**
283
+ {chr(10).join(['• ' + factor for factor in ['ہائی بلڈ پریشر', 'ہائی کولیسٹرول', 'سگریٹ نوشی', 'ذیابیطس', 'موٹاپا', 'خاندانی تاریخ']])}
284
+
285
+ **بچاؤ کے نکات:**
286
+ {chr(10).join(['• ' + tip for tip in ['صحت مند غذا', 'باقاعدہ ورزش', 'سگریٹ نوشی سے پرہیز', 'وزن کا انتظام', 'تناؤ کا انتظام']])}
287
+
288
+ **🚨 فوری طبی امداد حاصل کریں اگر:**
289
+ {chr(10).join(['• ' + sign for sign in ['شدید سینے میں درد', 'سانس لینے میں شدید دشواری', 'بیہوش ہونا', 'تیز دل کی دھڑکن']])}
290
+
291
+ *نوٹ: یہ عام معلومات ہیں۔ ذاتی مشورے کے لیے ہیلتھ کیئر پروفیشنل سے مشورہ کریں۔*
292
+ """
293
+
294
+ def _format_diabetes_response(self, language):
295
+ if language == 'English':
296
+ return f"""
297
+ **🩺 Diabetes Information**
298
+
299
+ **Common Symptoms:**
300
+ {chr(10).join(['• ' + symptom for symptom in self.medical_knowledge_base['diabetes']['symptoms']])}
301
+
302
+ **Risk Factors:**
303
+ {chr(10).join(['• ' + factor for factor in self.medical_knowledge_base['diabetes']['risk_factors']])}
304
+
305
+ **Prevention Tips:**
306
+ {chr(10).join(['• ' + tip for tip in self.medical_knowledge_base['diabetes']['prevention']])}
307
+
308
+ **🚨 Emergency Signs:**
309
+ {chr(10).join(['• ' + sign for sign in self.medical_knowledge_base['diabetes']['emergency_signs']])}
310
+
311
+ *Note: Regular monitoring and medical consultation are essential for diabetes management.*
312
+ """
313
+ else:
314
+ return f"""
315
+ **🩺 ذیابیطس کی معلومات**
316
+
317
+ **عام علامات:**
318
+ {chr(10).join(['• ' + symptom for symptom in ['زیادہ پیاس لگنا', 'بار بار پیشاب آنا', 'تھکاوٹ', 'دھندلا نظر آنا', 'زخموں کا دیر سے بھرنا']])}
319
+
320
+ **خطرے کے عوامل:**
321
+ {chr(10).join(['• ' + factor for factor in ['خاندانی تاریخ', 'موٹاپا', 'ہائی بلڈ پریشر', 'جسمانی غیر فعالیت', 'عمر']])}
322
+
323
+ **بچاؤ کے نکات:**
324
+ {chr(10).join(['• ' + tip for tip in ['صحت مند کھانا', 'باقاعدہ ورزش', 'وزن پر قابو', 'بلڈ شوگر مانیٹرنگ']])}
325
+
326
+ **🚨 ہنگامی علامات:**
327
+ {chr(10).join(['• ' + sign for sign in ['بہت زیادہ بلڈ شوگر', 'الجھن', 'پھل کی سی بو والی سانس', 'تیز سانس لینا']])}
328
+
329
+ *نوٹ: ذیابیطس کے انتظام کے لیے باقاعدہ نگرانی اور طبی مشورہ ضروری ہے۔*
330
+ """
331
+
332
+ def _format_hypertension_response(self, language):
333
+ if language == 'English':
334
+ return f"""
335
+ **💓 Blood Pressure Information**
336
+
337
+ **Common Symptoms:**
338
+ {chr(10).join(['• ' + symptom for symptom in self.medical_knowledge_base['hypertension']['symptoms']])}
339
+
340
+ **Risk Factors:**
341
+ {chr(10).join(['• ' + factor for factor in self.medical_knowledge_base['hypertension']['risk_factors']])}
342
+
343
+ **Prevention Tips:**
344
+ {chr(10).join(['• ' + tip for tip in self.medical_knowledge_base['hypertension']['prevention']])}
345
+
346
+ **🚨 Emergency Signs:**
347
+ {chr(10).join(['• ' + sign for sign in self.medical_knowledge_base['hypertension']['emergency_signs']])}
348
+
349
+ *Note: Regular blood pressure monitoring is crucial for early detection and management.*
350
+ """
351
+ else:
352
+ return f"""
353
+ **💓 بلڈ پریشر کی معلومات**
354
+
355
+ **عام علامات:**
356
+ {chr(10).join(['• ' + symptom for symptom in ['سر درد', 'چکر آنا', 'دھندلا نظر آنا', 'سانس لینے میں دشواری', 'سینے میں درد']])}
357
+
358
+ **خطرے کے عوامل:**
359
+ {chr(10).join(['• ' + factor for factor in ['خاندانی تاریخ', 'عمر', 'موٹاپا', 'زیادہ نمک کا استعمال', 'تناؤ', 'شراب']])}
360
+
361
+ **بچاؤ کے نکات:**
362
+ {chr(10).join(['• ' + tip for tip in ['کم نمک والی غذا', 'باقاعدہ ورزش', 'وزن کا انتظام', 'تناؤ میں کمی', 'شراب کو محدود کریں']])}
363
+
364
+ **🚨 ہنگامی علامات:**
365
+ {chr(10).join(['• ' + sign for sign in ['شدید سر درد', 'سینے میں درد', 'سانس لینے میں دشواری', 'بینائی میں تبدیلی']])}
366
+
367
+ *نوٹ: ابتدائی تشخیص اور انتظام کے لیے بلڈ پریشر کی باقاعدہ نگرانی بہت ضروری ہے۔*
368
+ """
369
+
370
+ def _format_general_health_response(self, language):
371
+ if language == 'English':
372
+ return """
373
+ **🌿 General Health & Wellness Tips**
374
+
375
+ **Nutrition:**
376
+ • Eat a balanced diet with fruits and vegetables
377
+ • Stay hydrated (8-10 glasses of water daily)
378
+ • Limit processed foods and sugar
379
+ • Include lean proteins and whole grains
380
+
381
+ **Exercise:**
382
+ • 30 minutes of moderate exercise daily
383
+ • Include both cardio and strength training
384
+ • Stay active throughout the day
385
+ • Get adequate rest and recovery
386
+
387
+ **Lifestyle:**
388
+ • Get 7-9 hours of quality sleep
389
+ • Manage stress through meditation or hobbies
390
+ • Avoid smoking and limit alcohol
391
+ • Regular health check-ups
392
+
393
+ **Prevention:**
394
+ • Wash hands regularly
395
+ • Maintain healthy weight
396
+ • Stay up to date with vaccinations
397
+ • Practice good hygiene
398
+
399
+ *Remember: Small consistent changes lead to big health improvements!*
400
+ """
401
+ else:
402
+ return """
403
+ **🌿 عام صحت اور تندرستی کے نکات**
404
+
405
+ **غذائیت:**
406
+ • پھلوں اور سبزیوں کے ساتھ متوازن غذا کھائیں
407
+ • ہائیڈریٹ رہیں (روزانہ 8-10 گلاس پانی)
408
+ • پراسیسڈ فوڈز اور چینی کو محدود کریں
409
+ • لیان پروٹین اور سارا اناج شامل کریں
410
+
411
+ **ورزش:**
412
+ • روزانہ 30 منٹ کی اعتدال پسند ورزش
413
+ • کارڈیو اور طاقت کی تربیت دونوں شامل کریں
414
+ • پورے دن متحرک رہیں
415
+ • مناسب آرام اور بحالی حاصل کریں
416
+
417
+ **طرز زندگی:**
418
+ • 7-9 گھنٹے کی معیاری نیند لیں
419
+ • مراقبہ یا شوق کے ذریعے تناؤ کا انتظام کریں
420
+ • تمباکو نوشی سے پرہیز کریں اور شراب کو محدود کریں
421
+ • باقاعدہ صحت کی جانچ
422
+
423
+ **بچاؤ:**
424
+ • ہاتھوں کو باقاعدگی سے دھوئیں
425
+ • صحت مند وزن ب��قرار رکھیں
426
+ • ویکسینیشن کے ساتھ اپ ڈیٹ رہیں
427
+ • اچھی حفظان صحت کی مشق کریں
428
+
429
+ *یاد رکھیں: چھوٹے مسلسل تبدیلیاں بڑی صحت کی بہتری کا باعث بنتی ہیں!*
430
+ """
431
+
432
+ def _format_symptoms_response(self, language):
433
+ if language == 'English':
434
+ return """
435
+ **🔍 Symptom Assessment Guidance**
436
+
437
+ **When to Seek Medical Care:**
438
+ • Persistent fever above 103°F (39.4°C)
439
+ • Difficulty breathing or chest pain
440
+ • Severe abdominal pain
441
+ • Sudden dizziness or confusion
442
+ • Unexplained weight loss
443
+ • Symptoms lasting more than 2 weeks
444
+
445
+ **Self-Care Tips:**
446
+ • Rest and stay hydrated
447
+ • Monitor symptoms and temperature
448
+ • Use over-the-counter medications as directed
449
+ • Apply cold/heat packs as needed
450
+
451
+ **🚨 Emergency Warning Signs:**
452
+ • Difficulty breathing
453
+ • Chest pain or pressure
454
+ • Severe bleeding
455
+ • Sudden severe pain
456
+ • Loss of consciousness
457
+
458
+ *Important: This is general guidance. Always consult a healthcare professional for proper diagnosis and treatment.*
459
+ """
460
+ else:
461
+ return """
462
+ **🔍 علامات کی تشخیص کی رہنمائی**
463
+
464
+ **طبی دیکھ بھال کب حاصل کریں:**
465
+ • 103°F (39.4°C) سے اوپر مستقل بخار
466
+ • سانس لینے میں دشواری یا سینے میں درد
467
+ • شدید پیٹ کا درد
468
+ • اچانک چکر آنا یا الجھن
469
+ • بے وجہ وزن میں کمی
470
+ • 2 ہفتے سے زیادہ علامات برقرار رہنا
471
+
472
+ **خود کی دیکھ بھال کے نکات:**
473
+ • آرام کریں اور ہائیڈریٹ رہیں
474
+ • علامات اور درجہ حرارت کی نگرانی کریں
475
+ • ہدایت کے مطابق اوور دی کاؤنٹر ادویات استعمال کریں
476
+ • حسب ضرورت کولڈ/ہیٹ پیکس لگائیں
477
+
478
+ **🚨 ہنگامی انتباہی علامات:**
479
+ • سانس لینے میں دشواری
480
+ • سینے میں درد یا دباؤ
481
+ • شدید خون بہنا
482
+ • اچانک شدید درد
483
+ • ہوش کا ضیاع
484
+
485
+ *اہم: یہ عام رہنمائی ہے۔ مناسب تشخیص اور علاج کے لیے ہمیشہ ہیلتھ کیئر پروفیشنل سے مشورہ کریں۔*
486
+ """
487
+
488
+ def _format_default_response(self, language):
489
+ if language == 'English':
490
+ return """
491
+ **🤖 Healthcare Assistant**
492
+
493
+ I'm here to help you with health-related questions about:
494
+ • Heart health and cardiovascular diseases
495
+ • Diabetes and blood sugar management
496
+ • Blood pressure and hypertension
497
+ • General health and wellness tips
498
+ • Symptom assessment guidance
499
+
500
+ Please ask me specific questions about these topics, and I'll provide detailed, helpful information based on medical knowledge.
501
+
502
+ *Remember: I'm an AI assistant. For serious medical concerns, always consult a qualified healthcare professional.*
503
+ """
504
+ else:
505
+ return """
506
+ **🤖 ہیلتھ کیئر اسسٹنٹ**
507
+
508
+ میں آپ کی صحت سے متعلق سوالات میں مدد کے لیے یہاں ہوں:
509
+ • دل کی صحت اور قلبی امراض
510
+ • ذیابیطس اور بلڈ شوگر مینجمنٹ
511
+ • بلڈ پریشر اور ہائی بلڈ پریشر
512
+ • عام صحت اور تندرستی کے نکات
513
+ • علامات کی تشخیص کی رہنمائی
514
+
515
+ براہ کرم ان موضوعات کے بارے میں مخصوص سوالات پوچھیں، اور میں طبی علم کی بنیاد پر تفصیلی، مددگار معلومات فراہم کروں گا۔
516
+
517
+ *یاد رکھیں: میں ایک AI اسسٹنٹ ہوں۔ سنگین طبی مسائل کے لیے، ہمیشہ کوالیفائیڈ ہیلتھ کیئر پروفیشنل سے مشورہ کریں۔*
518
+ """
519
+
520
+ class PDFReportGenerator:
521
+ def __init__(self):
522
+ self.pdf = FPDF()
523
+
524
+ def generate_report(self, patient_data, risk_scores, language='English'):
525
+ self.pdf.add_page()
526
+
527
+ # Title
528
+ self.pdf.set_font('Arial', 'B', 16)
529
+ if language == 'English':
530
+ self.pdf.cell(0, 10, 'MEDICAL ASSESSMENT REPORT', 0, 1, 'C')
531
+ else:
532
+ self.pdf.cell(0, 10, 'طبی تشخیص رپورٹ', 0, 1, 'C')
533
+
534
+ self.pdf.ln(10)
535
+
536
+ # Patient Information
537
+ self.pdf.set_font('Arial', 'B', 12)
538
+ if language == 'English':
539
+ self.pdf.cell(0, 10, 'Patient Information:', 0, 1)
540
+ else:
541
+ self.pdf.cell(0, 10, 'مریض کی معلومات:', 0, 1)
542
+
543
+ self.pdf.set_font('Arial', '', 10)
544
+ patient_info = [
545
+ f"Name: {patient_data.get('name', 'Not provided')}",
546
+ f"Age: {patient_data.get('age', 'Not provided')} years",
547
+ f"Gender: {patient_data.get('gender', 'Not provided')}",
548
+ f"Contact: {patient_data.get('contact', 'Not provided')}"
549
+ ]
550
+
551
+ for info in patient_info:
552
+ self.pdf.cell(0, 8, info, 0, 1)
553
+
554
+ self.pdf.ln(5)
555
+
556
+ # Clinical Parameters
557
+ self.pdf.set_font('Arial', 'B', 12)
558
+ if language == 'English':
559
+ self.pdf.cell(0, 10, 'Clinical Parameters:', 0, 1)
560
+ else:
561
+ self.pdf.cell(0, 10, 'کلینیکل پیرامیٹرز:', 0, 1)
562
+
563
+ self.pdf.set_font('Arial', '', 10)
564
+ clinical_info = [
565
+ f"Blood Pressure: {patient_data.get('bp_systolic', 'N/A')}/{patient_data.get('bp_diastolic', 'N/A')} mmHg",
566
+ f"Heart Rate: {patient_data.get('heart_rate', 'N/A')} bpm",
567
+ f"Cholesterol: {patient_data.get('cholesterol', 'N/A')} mg/dL",
568
+ f"Glucose: {patient_data.get('glucose', 'N/A')} mg/dL",
569
+ f"BMI: {patient_data.get('bmi', 'N/A')}"
570
+ ]
571
+
572
+ for info in clinical_info:
573
+ self.pdf.cell(0, 8, info, 0, 1)
574
+
575
+ self.pdf.ln(5)
576
+
577
+ # Risk Assessment
578
+ self.pdf.set_font('Arial', 'B', 12)
579
+ if language == 'English':
580
+ self.pdf.cell(0, 10, 'Risk Assessment:', 0, 1)
581
+ else:
582
+ self.pdf.cell(0, 10, 'خطرے کی تشخیص:', 0, 1)
583
+
584
+ self.pdf.set_font('Arial', '', 10)
585
+ risk_info = [
586
+ f"Heart Disease Risk: {risk_scores.get('heart', 0):.1%}",
587
+ f"Diabetes Risk: {risk_scores.get('diabetes', 0):.1%}",
588
+ f"Hypertension Risk: {risk_scores.get('hypertension', 0):.1%}",
589
+ f"Overall Priority Score: {risk_scores.get('priority', 0):.1%}"
590
+ ]
591
+
592
+ for info in risk_info:
593
+ self.pdf.cell(0, 8, info, 0, 1)
594
+
595
+ self.pdf.ln(5)
596
+
597
+ # Recommendation
598
+ self.pdf.set_font('Arial', 'B', 12)
599
+ if language == 'English':
600
+ self.pdf.cell(0, 10, 'Clinical Recommendation:', 0, 1)
601
+ else:
602
+ self.pdf.cell(0, 10, 'کلینیکل سفارش:', 0, 1)
603
+
604
+ self.pdf.set_font('Arial', '', 10)
605
+ recommendation = risk_scores.get('recommendation', 'No recommendation available')
606
+ self.pdf.multi_cell(0, 8, recommendation)
607
+
608
+ self.pdf.ln(10)
609
+
610
+ # Footer
611
+ self.pdf.set_font('Arial', 'I', 8)
612
+ if language == 'English':
613
+ self.pdf.cell(0, 10, f'Generated on: {datetime.now().strftime("%Y-%m-%d %H:%M")}', 0, 1, 'C')
614
+ else:
615
+ self.pdf.cell(0, 10, f'تاریخ پیدائش: {datetime.now().strftime("%Y-%m-%d %H:%M")}', 0, 1, 'C')
616
+
617
+ return self.pdf.output(dest='S').encode('latin1')
618
 
619
  def calculate_priority_score(heart_risk, diabetes_risk, hypertension_risk):
620
  """Calculate integrated priority score with clinical weighting"""
 
661
  return errors
662
 
663
  def predict_risk_rule_based(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms):
664
+ """Advanced rule-based risk prediction with clinical accuracy"""
665
 
666
+ # Base risks
667
  heart_risk = 0.0
 
 
 
 
 
 
 
 
 
 
 
 
668
  diabetes_risk = 0.0
 
 
 
 
 
 
 
 
 
669
  hypertension_risk = 0.0
 
 
 
 
 
 
 
670
 
671
+ # Age factors (increasing risk with age)
672
+ if age > 50:
673
+ heart_risk += 0.15
674
+ diabetes_risk += 0.10
675
+ hypertension_risk += 0.12
676
+ elif age > 40:
677
+ heart_risk += 0.10
678
+ diabetes_risk += 0.07
679
+ hypertension_risk += 0.08
680
+ elif age > 30:
681
+ heart_risk += 0.05
682
+ diabetes_risk += 0.04
683
+ hypertension_risk += 0.05
684
 
685
+ # Blood Pressure factors
686
+ if bp_systolic > 140 or bp_diastolic > 90:
687
+ heart_risk += 0.25
688
+ hypertension_risk += 0.30
689
+ elif bp_systolic > 130 or bp_diastolic > 85:
690
+ heart_risk += 0.15
691
+ hypertension_risk += 0.20
 
 
 
 
 
692
 
693
+ # Cholesterol factors
694
+ if cholesterol > 240:
695
+ heart_risk += 0.20
696
+ elif cholesterol > 200:
697
+ heart_risk += 0.12
 
 
 
 
 
 
698
 
699
+ # Glucose factors
700
+ if glucose > 126: # Diabetic range
701
+ diabetes_risk += 0.35
702
+ heart_risk += 0.15
703
+ elif glucose > 100: # Pre-diabetic range
704
+ diabetes_risk += 0.20
705
+ heart_risk += 0.08
 
 
 
 
706
 
707
+ # BMI factors
708
+ if bmi > 30: # Obese
709
+ heart_risk += 0.15
710
+ diabetes_risk += 0.20
711
+ hypertension_risk += 0.15
712
+ elif bmi > 25: # Overweight
713
+ heart_risk += 0.08
714
+ diabetes_risk += 0.12
715
+ hypertension_risk += 0.10
716
 
717
+ # Symptom factors
718
+ if symptoms['chest_pain']:
719
+ heart_risk += 0.25
720
+ if symptoms['shortness_breath']:
721
+ heart_risk += 0.15
722
+ hypertension_risk += 0.10
723
+ if symptoms['palpitations']:
724
+ heart_risk += 0.10
725
+ hypertension_risk += 0.08
726
+ if symptoms['fatigue']:
727
+ diabetes_risk += 0.12
728
+ heart_risk += 0.08
729
+ if symptoms['dizziness']:
730
+ hypertension_risk += 0.15
731
+ if symptoms['blurred_vision']:
732
+ diabetes_risk += 0.10
733
+ hypertension_risk += 0.08
734
+
735
+ # Ensure risks are within bounds
736
+ heart_risk = min(0.95, heart_risk)
737
+ diabetes_risk = min(0.95, diabetes_risk)
738
+ hypertension_risk = min(0.95, hypertension_risk)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
739
 
740
+ # Add some randomness to simulate real prediction variability
741
+ heart_risk += np.random.normal(0, 0.02)
742
+ diabetes_risk += np.random.normal(0, 0.02)
743
+ hypertension_risk += np.random.normal(0, 0.02)
744
+
745
+ return max(0.05, heart_risk), max(0.05, diabetes_risk), max(0.05, hypertension_risk)
746
+
747
+ def create_download_link(pdf_data, filename, text):
748
+ """Create a download link for PDF"""
749
+ b64 = base64.b64encode(pdf_data).decode()
750
+ href = f'<a href="data:application/octet-stream;base64,{b64}" download="{filename}">{text}</a>'
751
+ return href
752
 
753
  def main():
754
  # Load custom CSS
755
  local_css()
756
  init_session_state()
757
 
758
+ # Initialize chatbot
759
+ chatbot = HealthcareChatbot()
 
760
 
761
+ # Language selector at top right
762
+ col_lang, col_space = st.columns([1, 5])
763
+ with col_lang:
764
+ language = st.selectbox("Language", ["English", "Urdu"], key="language_selector", label_visibility="collapsed")
765
+ st.session_state.current_language = language
766
 
767
+ # Main header
768
+ st.markdown('<h1 class="main-header">🏥 MediPriority AI</h1>', unsafe_allow_html=True)
769
+ if language == "English":
770
+ st.markdown('<h3 style="text-align: center; color: #2e86ab; margin-bottom: 20px;">Smart Healthcare Triage & Risk Assessment System</h3>', unsafe_allow_html=True)
771
+ else:
772
+ st.markdown('<h3 style="text-align: center; color: #2e86ab; margin-bottom: 20px;">ذہین ہیلتھ کیئر ٹریج اور خطرے کی تشخیص کا نظام</h3>', unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
773
 
774
+ # Display random healthcare quote
775
+ import random
776
+ quote = random.choice(HEALTHCARE_QUOTES)
777
+
778
+ st.markdown(f'''
779
+ <div class="quote-section">
780
+ <div class="quote-text">"{quote['english']}"</div>
781
+ <div class="quote-text">"{quote['urdu']}"</div>
782
+ <div class="quote-author">- {quote['author']}</div>
783
  </div>
784
+ ''', unsafe_allow_html=True)
785
 
786
  # Create tabs
787
  if language == "English":
788
+ tab_names = ["Patient Assessment", "Health Assistant", "Medical Reports"]
789
  else:
790
+ tab_names = ["مریض تشخیص", "ہیلتھ اسسٹنٹ", "طبی رپورٹس"]
791
 
792
  tab1, tab2, tab3 = st.tabs(tab_names)
793
 
 
796
  st.markdown('<div class="section-container">', unsafe_allow_html=True)
797
 
798
  if language == "English":
799
+ st.markdown('<h2 style="color: #1f77b4; border-bottom: 3px solid #1f77b4; padding-bottom: 10px;">👨‍⚕️ Comprehensive Patient Assessment</h2>', unsafe_allow_html=True)
800
  st.write("Complete the following form for comprehensive patient risk assessment and priority scoring")
801
  else:
802
+ st.markdown('<h2 style="color: #1f77b4; border-bottom: 3px solid #1f77b4; padding-bottom: 10px;">👨‍⚕️ جامع مریض تشخیص</h2>', unsafe_allow_html=True)
803
  st.write("جامع مریض کے خطرے کی تشخیص اور ترجیحی اسکورنگ کے لیے درج ذیل فارم کو مکمل کریں")
804
 
805
  with st.form("patient_assessment_form"):
 
808
  with col1:
809
  # Basic Information
810
  if language == "English":
811
+ st.subheader("Personal Information")
812
  name = st.text_input("Full Name", placeholder="Enter patient's full name")
813
  age = st.number_input("Age", min_value=1, max_value=120, value=45,
814
  help="Patient's age in years")
815
  gender = st.selectbox("Gender", ["Male", "Female", "Other"])
816
  contact = st.text_input("Contact Number", placeholder="03XX-XXXXXXX")
817
  else:
818
+ st.subheader("ذاتی معلومات")
819
  name = st.text_input("مکمل نام", placeholder="مریض کا مکمل نام درج کریں")
820
  age = st.number_input("عمر", min_value=1, max_value=120, value=45,
821
  help="مریض کی عمر سالوں میں")
 
825
  with col2:
826
  # Vital Signs
827
  if language == "English":
828
+ st.subheader("Clinical Parameters")
829
+ bp_systolic = st.slider("Blood Pressure (systolic)",
830
+ min_value=70, max_value=250, value=120,
831
+ help="Systolic blood pressure in mmHg")
832
+ bp_diastolic = st.slider("Blood Pressure (diastolic)",
833
+ min_value=40, max_value=150, value=80,
834
+ help="Diastolic blood pressure in mmHg")
835
+ heart_rate = st.slider("Heart Rate (bpm)",
836
+ min_value=30, max_value=200, value=72,
837
+ help="Heart beats per minute")
838
+ cholesterol = st.slider("Cholesterol Level (mg/dL)",
839
+ min_value=100, max_value=400, value=180)
840
+ glucose = st.slider("Blood Glucose (mg/dL)",
841
+ min_value=50, max_value=500, value=95)
842
  bmi = st.slider("BMI", min_value=15.0, max_value=40.0, value=23.5, step=0.1)
843
  else:
844
+ st.subheader("کلینیکل پیرامیٹرز")
845
+ bp_systolic = st.slider("بلڈ پریشر (سسٹولک)",
846
+ min_value=70, max_value=250, value=120,
847
+ help="سسٹولک بلڈ پریشر mmHg میں")
848
+ bp_diastolic = st.slider("بلڈ پریشر (ڈائیسٹولک)",
849
+ min_value=40, max_value=150, value=80,
850
+ help="ڈائیسٹولک بلڈ پریشر mmHg میں")
851
+ heart_rate = st.slider("دل کی دھڑکن (bpm)",
852
+ min_value=30, max_value=200, value=72,
853
+ help="دل کی دھڑکن فی منٹ")
854
+ cholesterol = st.slider("کولیسٹرول کی سطح (mg/dL)",
855
+ min_value=100, max_value=400, value=180)
856
+ glucose = st.slider("خون میں گلوکوز (mg/dL)",
857
+ min_value=50, max_value=500, value=95)
858
  bmi = st.slider("باڈی ماس انڈیکس", min_value=15.0, max_value=40.0, value=23.5, step=0.1)
859
 
860
  # Symptoms Section
861
  if language == "English":
862
+ st.subheader("Reported Symptoms")
863
  col3, col4 = st.columns(2)
864
  with col3:
865
  chest_pain = st.checkbox("Chest Pain or Discomfort")
 
870
  dizziness = st.checkbox("Dizziness or Lightheadedness")
871
  blurred_vision = st.checkbox("Blurred Vision")
872
  else:
873
+ st.subheader("رپورٹ کردہ علامات")
874
  col3, col4 = st.columns(2)
875
  with col3:
876
  chest_pain = st.checkbox("سینے میں درد یا بے چینی")
 
901
  with st.spinner("🔍 Analyzing patient data and calculating risks..."):
902
  # Prepare symptoms dictionary
903
  symptoms_dict = {
904
+ 'chest_pain': chest_pain,
905
+ 'shortness_breath': shortness_breath,
906
+ 'palpitations': palpitations,
907
+ 'fatigue': fatigue,
908
+ 'dizziness': dizziness,
909
+ 'blurred_vision': blurred_vision
910
  }
911
 
912
  # Store patient data
 
924
  'symptoms': symptoms_dict
925
  }
926
 
927
+ # Use advanced rule-based prediction
928
+ heart_risk_proba, diabetes_risk_proba, hypertension_risk_proba = predict_risk_rule_based(
929
+ age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms_dict
930
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
931
 
932
  # Calculate integrated priority score
933
  priority_score = calculate_priority_score(
 
961
 
962
  # Risk Scores Visualization
963
  if language == "English":
964
+ st.subheader("📊 Disease Risk Assessment Dashboard")
965
  else:
966
+ st.subheader("📊 بیماری کے خطرے کی تشخیص ڈیش بورڈ")
967
 
968
  col5, col6, col7, col8 = st.columns(4)
969
 
 
1029
  st.success("✅ **روٹین کیئر:** معمول کی اپائنٹمنٹ سسٹم کے اندر شیڈول کریں۔")
1030
 
1031
  st.markdown('</div>', unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1032
 
1033
  except Exception as e:
1034
  st.error(f"❌ Error in risk assessment: {str(e)}")
 
1036
  st.markdown('</div>', unsafe_allow_html=True)
1037
 
1038
  with tab2:
1039
+ # Healthcare Chatbot
1040
  st.markdown('<div class="section-container">', unsafe_allow_html=True)
1041
 
1042
  if language == "English":
1043
+ st.markdown('<h2 style="color: #1f77b4; border-bottom: 3px solid #1f77b4; padding-bottom: 10px;">💬 Health Assistant</h2>', unsafe_allow_html=True)
1044
+ st.write("Ask health-related questions and get instant, reliable medical information")
1045
  else:
1046
+ st.markdown('<h2 style="color: #1f77b4; border-bottom: 3px solid #1f77b4; padding-bottom: 10px;">💬 ہیلتھ اسسٹنٹ</h2>', unsafe_allow_html=True)
1047
+ st.write("صحت سے متعلق سوالات پوچھیں اور فوری، قابل اعتماد طبی معلومات حاصل کریں")
1048
+
1049
+ # Display chat history
1050
+ for message in st.session_state.chat_history:
1051
+ if message["role"] == "user":
1052
+ st.markdown(f'<div class="chat-message user-message"><strong>You:</strong> {message["content"]}</div>', unsafe_allow_html=True)
1053
+ else:
1054
+ st.markdown(f'<div class="chat-message bot-message"><strong>🤖 Health Assistant:</strong> {message["content"]}</div>', unsafe_allow_html=True)
1055
+
1056
+ # Chat input
1057
+ if prompt := st.chat_input(
1058
+ "Type your health question here..." if language == "English"
1059
+ else "اپنا صحت کا سوال یہاں ٹائپ کریں..."
1060
+ ):
1061
+ # Add user message to chat history
1062
+ st.session_state.chat_history.append({"role": "user", "content": prompt})
1063
+
1064
+ # Generate bot response
1065
+ with st.spinner("💭 Analyzing your question..." if language == "English" else "💭 آپ کا سوال تجزیہ ہو رہا ہے..."):
1066
+ response = chatbot.get_response(prompt, language)
1067
+ st.session_state.chat_history.append({"role": "assistant", "content": response})
1068
+
1069
+ # Limit chat history to last 10 messages
1070
+ if len(st.session_state.chat_history) > 10:
1071
+ st.session_state.chat_history = st.session_state.chat_history[-10:]
1072
+
1073
+ st.rerun()
1074
 
1075
+ # Quick action buttons
1076
  if language == "English":
1077
+ st.subheader("Quick Health Topics")
 
 
 
1078
  else:
1079
+ st.subheader("فوری صحت کے موضوعات")
 
 
 
1080
 
1081
+ col_qa1, col_qa2, col_qa3, col_qa4 = st.columns(4)
 
 
 
 
 
 
 
 
1082
 
1083
+ with col_qa1:
1084
+ if st.button("❤️ Heart Health", use_container_width=True):
1085
+ st.session_state.chat_history.append({
1086
+ "role": "user",
1087
+ "content": "Tell me about heart health and prevention"
1088
+ })
1089
+ st.rerun()
1090
+
1091
+ with col_qa2:
1092
+ if st.button("🩺 Diabetes", use_container_width=True):
1093
+ st.session_state.chat_history.append({
1094
+ "role": "user",
1095
+ "content": "What are diabetes symptoms and management?"
1096
+ })
1097
+ st.rerun()
1098
+
1099
+ with col_qa3:
1100
+ if st.button("💓 Blood Pressure", use_container_width=True):
1101
+ st.session_state.chat_history.append({
1102
+ "role": "user",
1103
+ "content": "How to control high blood pressure?"
1104
+ })
1105
+ st.rerun()
1106
+
1107
+ with col_qa4:
1108
+ if st.button("🌿 General Health", use_container_width=True):
1109
+ st.session_state.chat_history.append({
1110
+ "role": "user",
1111
+ "content": "General health and wellness tips"
1112
+ })
1113
+ st.rerun()
1114
 
1115
  st.markdown('</div>', unsafe_allow_html=True)
1116
 
1117
  with tab3:
1118
+ # Medical Reports
1119
  st.markdown('<div class="section-container">', unsafe_allow_html=True)
1120
 
1121
  if language == "English":
1122
+ st.markdown('<h2 style="color: #1f77b4; border-bottom: 3px solid #1f77b4; padding-bottom: 10px;">📋 Medical Reports & Analytics</h2>', unsafe_allow_html=True)
1123
+ st.write("Download comprehensive medical reports and view assessment analytics")
1124
  else:
1125
+ st.markdown('<h2 style="color: #1f77b4; border-bottom: 3px solid #1f77b4; padding-bottom: 10px;">📋 طبی رپورٹس اور تجزیات</h2>', unsafe_allow_html=True)
1126
+ st.write("جامع طبی رپورٹس ڈاؤن لوڈ کریں اور تشخیص کے تجزیات دیکھیں")
1127
 
1128
+ if st.session_state.assessment_history:
1129
+ # Latest assessment
1130
+ latest_assessment = st.session_state.assessment_history[-1]
1131
+
1132
+ # Download PDF report
 
 
 
 
 
 
 
 
1133
  if language == "English":
1134
+ st.subheader("Download Patient Report")
1135
  else:
1136
+ st.subheader("مریض رپورٹ ڈاؤن لوڈ کریں")
1137
+
1138
+ pdf_generator = PDFReportGenerator()
1139
+ pdf_data = pdf_generator.generate_report(
1140
+ latest_assessment['patient_data'],
1141
+ latest_assessment['risk_scores'],
1142
+ language
1143
+ )
1144
+
1145
  if language == "English":
1146
+ st.markdown(create_download_link(pdf_data, "medical_report.pdf", "📥 Download Medical Report (PDF)"), unsafe_allow_html=True)
1147
  else:
1148
+ st.markdown(create_download_link(pdf_data, "medical_report.pdf", "📥 طبی رپورٹ ڈاؤن لوڈ کریں (PDF)"), unsafe_allow_html=True)
1149
+
1150
+ # Analytics Section
 
 
1151
  if language == "English":
1152
+ st.subheader("Assessment Analytics")
1153
  else:
1154
+ st.subheader("تشخیص کے تجزیات")
 
 
 
 
 
1155
 
1156
+ col_anal1, col_anal2, col_anal3 = st.columns(3)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1157
 
1158
+ with col_anal1:
1159
+ st.metric(
1160
+ "Total Assessments" if language == "English" else "کل تشخیص",
1161
+ len(st.session_state.assessment_history)
1162
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1163
 
1164
+ with col_anal2:
1165
+ latest_priority = latest_assessment['risk_scores']['priority']
1166
+ st.metric(
1167
+ "Current Priority Score" if language == "English" else "موجودہ ترجیحی اسکور",
1168
+ f"{latest_priority:.1%}"
1169
+ )
1170
 
1171
+ with col_anal3:
1172
+ high_risk_count = sum(1 for assess in st.session_state.assessment_history
1173
+ if assess['risk_scores']['priority'] > 0.7)
1174
+ st.metric(
1175
+ "High Risk Cases" if language == "English" else "اعلی خطرہ والے معاملات",
1176
+ high_risk_count
1177
+ )
 
 
1178
 
1179
+ # Risk distribution chart
1180
+ if len(st.session_state.assessment_history) > 1:
1181
+ risk_data = pd.DataFrame([
1182
+ {
1183
+ 'Heart Risk': assess['risk_scores']['heart'],
1184
+ 'Diabetes Risk': assess['risk_scores']['diabetes'],
1185
+ 'Hypertension Risk': assess['risk_scores']['hypertension'],
1186
+ 'Assessment': i+1
1187
+ } for i, assess in enumerate(st.session_state.assessment_history[-5:])
1188
+ ])
1189
+
1190
+ fig = px.line(risk_data, x='Assessment', y=['Heart Risk', 'Diabetes Risk', 'Hypertension Risk'],
1191
+ title="Risk Trend Analysis" if language == "English" else "خطرے کے رجحان کا تجزیہ")
1192
+ st.plotly_chart(fig, use_container_width=True)
1193
 
1194
  else:
1195
  if language == "English":
1196
+ st.info("👆 Complete a patient assessment to generate reports and view analytics")
1197
  else:
1198
+ st.info("👆 رپورٹس تیار کرنے اور تجزیات دیکھنے کے لیے مریض کی تشخیص مکمل کریں")
1199
 
1200
  st.markdown('</div>', unsafe_allow_html=True)
1201