sunbal7 commited on
Commit
e93f833
·
verified ·
1 Parent(s): ab03acd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +240 -323
app.py CHANGED
@@ -12,6 +12,8 @@ from datetime import datetime
12
  import base64
13
  from fpdf import FPDF
14
  import tempfile
 
 
15
 
16
  # Set page config first
17
  st.set_page_config(
@@ -163,6 +165,13 @@ def local_css():
163
  font-weight: bold;
164
  margin: 0 10px;
165
  }
 
 
 
 
 
 
 
166
  </style>
167
  """, unsafe_allow_html=True)
168
 
@@ -178,6 +187,8 @@ def init_session_state():
178
  st.session_state.chat_history = []
179
  if 'current_language' not in st.session_state:
180
  st.session_state.current_language = 'English'
 
 
181
 
182
  # Healthcare quotes database
183
  HEALTHCARE_QUOTES = [
@@ -208,8 +219,38 @@ HEALTHCARE_QUOTES = [
208
  }
209
  ]
210
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
  class HealthcareChatbot:
212
- def __init__(self):
 
213
  self.medical_knowledge_base = {
214
  'heart_disease': {
215
  'symptoms': ["Chest pain or discomfort", "Shortness of breath", "Pain in arms, neck, jaw", "Nausea", "Fatigue", "Dizziness"],
@@ -228,16 +269,55 @@ class HealthcareChatbot:
228
  'risk_factors': ["Family history", "Age over 65", "Obesity", "High salt intake", "Stress", "Alcohol consumption", "Smoking"],
229
  'prevention': ["DASH diet (low sodium)", "Regular aerobic exercise", "Weight management", "Stress reduction", "Limit alcohol", "No smoking"],
230
  'emergency_signs': ["Severe headache", "Chest pain", "Difficulty breathing", "Vision changes", "Confusion", "Seizures"]
231
- },
232
- 'general_health': {
233
- 'nutrition': ["Eat 5-9 servings of fruits/vegetables daily", "Choose whole grains over refined", "Include lean proteins", "Stay hydrated (8-10 glasses water)", "Limit processed foods and sugar"],
234
- 'exercise': ["150 mins moderate exercise weekly", "Strength training 2x weekly", "Stay active throughout day", "Include flexibility exercises", "Get adequate rest between workouts"],
235
- 'lifestyle': ["7-9 hours quality sleep nightly", "Stress management techniques", "No smoking", "Limit alcohol to 1-2 drinks/day", "Regular health check-ups"],
236
- 'prevention': ["Annual physical exams", "Vaccinations up to date", "Regular hand washing", "Sun protection", "Mental health care"]
237
  }
238
  }
239
 
240
  def get_response(self, user_input, language='English'):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  user_input = user_input.lower().strip()
242
 
243
  # Greeting patterns
@@ -362,12 +442,6 @@ Please ask me specific health-related questions, and I'll provide detailed, help
362
  **🚑 ہنگامی انتباہی علامات (فوری علاج حاصل کریں):**
363
  {chr(10).join(['• ' + sign for sign in ['شدید سینے میں درد', 'سانس لینے میں شدید دشواری', 'بیہوش ہونا', 'تیز دل کی دھڑکن', 'بازو/کندھوں میں پھیلنے والا درد']])}
364
 
365
- **📊 تجویز کردہ نگرانی:**
366
- • بلڈ پریشر کی باقاعدہ جانچ
367
- • اگر خطرہ زیادہ ہو تو سالانہ کولیسٹرول کی سطح
368
- • اگر علامات موجود ہوں تو ECG
369
- • اگر ڈاکٹر تجویز کرے تو اسٹریس ٹیسٹ
370
-
371
  *🔬 کلینیکل نوٹ: ابتدائی تشخیص جان بچاتی ہے۔ دل کی صحت کے لیے باقاعدہ چیک اپ بہت ضروری ہیں۔*
372
  """
373
 
@@ -413,12 +487,6 @@ Please ask me specific health-related questions, and I'll provide detailed, help
413
  **🚑 ہنگامی علامات (فوری علاج حاصل کریں):**
414
  {chr(10).join(['• ' + sign for sign in ['بلڈ شوگر >300 mg/dL یا <70 mg/dL', 'الجھن یا بے ترتیبی', 'پھل کی سی بو والی سانس', 'تیز سانس لینا', 'ہوش کا ضیاع']])}
415
 
416
- **📊 نگرانی کے رہنما اصول:**
417
- • فاسٹنگ بلڈ شوگر: 80-130 mg/dL
418
- • کھانے کے بعد بلڈ شوگر: <180 mg/dL
419
- • HbA1c: <7.0% (اگر کنٹرول نہ ہو تو سہ ماہی)
420
- • پاؤں اور آنکھوں کا باقاعدہ معائنہ
421
-
422
  *🔬 کلینیکل نوٹ: مستقل نگرانی اور طرز زندگی کا انتظام ذیابیطس کے کنٹرول کی کلید ہے۔*
423
  """
424
 
@@ -464,35 +532,25 @@ Please ask me specific health-related questions, and I'll provide detailed, help
464
  **🚑 ہائی بلڈ پریشر کی ہنگامی علامات:**
465
  {chr(10).join(['• ' + sign for sign in ['شدید سر درد', 'سینے میں درد', 'سانس لینے میں دشواری', 'بینائی میں تبدیلی', 'الجھن', 'دورے']])}
466
 
467
- **📊 بلڈ پریشر کی درجہ بندی:**
468
- • نارمل: <120/80 mmHg
469
- • بلند: 120-129/<80 mmHg
470
- • اسٹیج 1 ہائی بلڈ پریشر: 130-139/80-89 mmHg
471
- • اسٹیج 2 ہائی بلڈ پریشر: ≥140/90 mmHg
472
-
473
  *🔬 کلینیکل نوٹ: خاموش قاتل - اکثر کوئی علامات نہیں ہوتیں۔ باقاعدہ نگرانی ضروری ہے۔*
474
  """
475
 
476
  def _format_nutrition_response(self, language):
477
- knowledge = self.medical_knowledge_base['general_health']
478
  if language == 'English':
479
- return f"""
480
  **🍎 Comprehensive Nutrition Guide**
481
 
482
  **🥦 Healthy Eating Principles:**
483
- {chr(10).join(['' + tip for tip in knowledge['nutrition']])}
 
 
 
 
484
 
485
  **🎯 Specific Recommendations:**
486
  • **Heart Health**: Mediterranean diet, omega-3 rich foods
487
  • **Diabetes**: Controlled carb intake, high fiber
488
  • **Hypertension**: Low sodium (<2300mg/day), potassium-rich foods
489
- • **Weight Management**: Calorie control, portion management
490
-
491
- **🚫 Foods to Limit:**
492
- • Processed and packaged foods
493
- • Sugary drinks and sweets
494
- • High sodium snacks
495
- • Saturated and trans fats
496
 
497
  **💡 Pakistani Dietary Adaptations:**
498
  • Choose whole wheat chapati over refined flour
@@ -503,23 +561,20 @@ Please ask me specific health-related questions, and I'll provide detailed, help
503
  *Remember: Balanced nutrition is foundation of good health.*
504
  """
505
  else:
506
- return f"""
507
  **🍎 غذائیت کی جامع گائیڈ**
508
 
509
  **🥦 صحت مند کھانے کے اصول:**
510
- {chr(10).join(['' + tip for tip in ['روزانہ 5-9 سرونگ پھل/سبزیاں کھائیں', 'ریفائنڈ کی بجائے سارا اناج منتخب کریں', 'لیان پروٹین شامل کریں', 'ہائیڈریٹ رہیں (8-10 گلاس پانی)', 'پراسیسڈ فوڈز اور چینی کو محدود کریں']])}
 
 
 
 
511
 
512
  **🎯 مخصوص سفارشات:**
513
  • **دل کی صحت**: بحیرہ روم کی غذا، اومیگا 3 سے بھرپور غذائیں
514
  • **ذیابیطس**: کنٹرول کاربوہائیڈریٹ انٹیک، زیادہ فائبر
515
  • **ہائی بلڈ پریشر**: کم سوڈیم (<2300mg/day)، پوٹاشیم سے بھرپور غذائیں
516
- • **وزن کا انتظام**: کیلوری کنٹرول، حصے کا انتظام
517
-
518
- **🚫 محدود کرنے والی غذائیں:**
519
- • پراسیسڈ اور پیکجڈ فوڈز
520
- • میٹھے مشروبات اور مٹھائیاں
521
- • ہائی سوڈیم اسنیکس
522
- • سیر شدہ اور ٹرانس فیٹس
523
 
524
  **💡 پاکستانی غذائی موافقت:**
525
  • ریفائنڈ آٹے کی بجائے whole wheat چپاتی منتخب کریں
@@ -531,58 +586,49 @@ Please ask me specific health-related questions, and I'll provide detailed, help
531
  """
532
 
533
  def _format_exercise_response(self, language):
534
- knowledge = self.medical_knowledge_base['general_health']
535
  if language == 'English':
536
- return f"""
537
  **💪 Comprehensive Exercise Guide**
538
 
539
  **🏃‍♂️ Exercise Recommendations:**
540
- {chr(10).join(['' + tip for tip in knowledge['exercise']])}
 
 
 
 
541
 
542
  **🎯 Disease-Specific Exercise:**
543
  • **Heart Health**: 30 mins moderate cardio daily
544
  • **Diabetes**: Combination of cardio and strength training
545
  • **Hypertension**: Regular aerobic exercise
546
- • **Weight Management**: 300+ mins moderate exercise weekly
547
 
548
  **🌞 Pakistani Climate Considerations:**
549
  • Exercise in cooler morning/evening hours
550
  • Stay hydrated with water and electrolytes
551
  • Wear light, breathable clothing
552
- • Listen to your body in hot weather
553
-
554
- **🔄 Exercise Types:**
555
- • **Cardio**: Walking, jogging, cycling, swimming
556
- • **Strength**: Weight training, resistance bands
557
- • **Flexibility**: Yoga, stretching
558
- • **Balance**: Tai chi, balance exercises
559
 
560
  *Important: Consult doctor before starting new exercise program.*
561
  """
562
  else:
563
- return f"""
564
  **💪 ورزش کی جامع گائیڈ**
565
 
566
  **🏃‍♂️ ورزش کی سفارشات:**
567
- {chr(10).join(['' + tip for tip in ['ہفتے میں 150 منٹ اعتدال پسند ورزش', 'ہفتے میں 2 بار طاقت کی تربیت', 'پورے دن متحرک رہیں', 'لچک کی ورزشیں شامل کریں', 'ورک آؤٹس کے درمیان مناسب آرام حاصل کریں']])}
 
 
 
 
568
 
569
  **🎯 بیماری کی مخصوص ورزش:**
570
  • **دل کی صحت**: روزانہ 30 منٹ اعتدال پسند کارڈیو
571
  • **ذیابیطس**: کارڈیو اور طاقت کی تربیت کا مجموعہ
572
  • **ہائی بلڈ پریشر**: باقاعدہ ایروبک ورزش
573
- • **وزن کا انتظام**: ہفتے میں 300+ منٹ اعتدال پسند ورزش
574
 
575
  **🌞 پاکستانی آب و ہوا کے تحفظات:**
576
  • ٹھنڈے صبح/شام کے اوقات میں ورزش کریں
577
  • پانی اور الیکٹرولائٹس کے ساتھ ہائیڈریٹ رہیں
578
  • ہلکے، ہوا دار کپڑے پہنیں
579
- • گرم موسم میں اپنے جسم کی بات سنیں
580
-
581
- **🔄 ورزش کی اقسام:**
582
- • **کارڈیو**: چہل قدمی، جاگنگ، سائیکل چلانا، تیراکی
583
- • **طاقت**: وزن کی تربیت، مزاحمتی بینڈ
584
- • **لچک**: یوگا، اسٹریچنگ
585
- • **توازن**: تائی چی، توازن کی ورزشیں
586
 
587
  *اہم: نئی ورزش پروگرام شروع کرنے سے پہلے ڈاکٹر سے مشورہ کریں۔*
588
  """
@@ -599,14 +645,6 @@ Please ask me specific health-related questions, and I'll provide detailed, help
599
  • Sudden dizziness, weakness, or confusion
600
  • Unexplained weight loss (>10% body weight)
601
  • Symptoms lasting more than 2 weeks
602
- • Worsening of chronic conditions
603
-
604
- **🏠 Self-Care Tips:**
605
- • Rest and adequate hydration
606
- • Monitor symptoms and temperature regularly
607
- • Use over-the-counter medications as directed
608
- • Apply cold/heat packs as appropriate
609
- • Maintain proper nutrition
610
 
611
  **🚨 Emergency Warning Signs (Go to ER):**
612
  • Difficulty breathing or shortness of breath
@@ -614,8 +652,6 @@ Please ask me specific health-related questions, and I'll provide detailed, help
614
  • Severe bleeding that doesn't stop
615
  • Sudden severe pain anywhere in body
616
  • Loss of consciousness or fainting
617
- • Sudden vision changes
618
- • Difficulty speaking or confusion
619
 
620
  *⚠️ Important: This is general guidance. Always consult healthcare professional for proper diagnosis.*
621
  """
@@ -630,14 +666,6 @@ Please ask me specific health-related questions, and I'll provide detailed, help
630
  • اچانک چکر آنا، کمزوری، یا الجھن
631
  • بے وجہ وزن میں کمی (>10% جسمانی وزن)
632
  • 2 ہفتے سے زیادہ علامات برقرار رہنا
633
- • دائمی حالات کا بگڑنا
634
-
635
- **🏠 خود کی دیکھ بھال کے نکات:**
636
- • آرام اور مناسب ہائیڈریشن
637
- • علامات اور درجہ حرارت کی باقاعدہ نگرانی
638
- • ہدایت کے مطابق اوور دی کاؤنٹر ادویات استعمال کریں
639
- • حسب مناسب کولڈ/ہیٹ پیکس لگائیں
640
- • مناسب غذائیت برقرار رکھیں
641
 
642
  **🚨 ہنگامی انتباہی علامات (ایمرجنسی روم جائیں):**
643
  • سانس لینے میں دشواری یا سانس کی قلت
@@ -645,8 +673,6 @@ Please ask me specific health-related questions, and I'll provide detailed, help
645
  • شدید خون بہنا جو رک نہیں رہا
646
  • جسم میں کہیں بھی اچانک شدید درد
647
  • ہوش کا ضیاع یا بیہوشی
648
- • اچانک بینائی میں تبدیلی
649
- • بولنے میں دشواری یا الجھن
650
 
651
  *⚠️ اہم: یہ عام رہنمائی ہے۔ مناسب تشخیص کے لیے ہمیشہ ہیلتھ کیئر پروفیشنل سے مشورہ کریں۔*
652
  """
@@ -663,12 +689,6 @@ Please ask me specific health-related questions, and I'll provide detailed, help
663
  • Inform all doctors about all medications
664
  • Understand purpose and side effects of each medicine
665
 
666
- **⚠️ Common Medication Categories:**
667
- • **Heart**: Beta-blockers, ACE inhibitors, statins
668
- • **Diabetes**: Metformin, insulin, SGLT2 inhibitors
669
- • **Hypertension**: Diuretics, calcium channel blockers
670
- • **Pain**: NSAIDs, acetaminophen (use cautiously)
671
-
672
  **🚨 Medication Warning Signs:**
673
  • Severe allergic reactions (rash, swelling)
674
  • Difficulty breathing after taking medicine
@@ -676,12 +696,6 @@ Please ask me specific health-related questions, and I'll provide detailed, help
676
  • Unusual bleeding or bruising
677
  • Confusion or hallucinations
678
 
679
- **💡 Important Reminders:**
680
- • Don't stop medications without doctor's advice
681
- • Report side effects to your doctor
682
- • Keep medications in original containers
683
- • Check expiration dates regularly
684
-
685
  *Note: Always follow your healthcare provider's specific instructions.*
686
  """
687
  else:
@@ -695,12 +709,6 @@ Please ask me specific health-related questions, and I'll provide detailed, help
695
  • تمام ڈاکٹروں کو تمام دوائیوں کے بارے میں بتائیں
696
  • ہر دوا کے مقصد اور مضر اثرات کو سمجھیں
697
 
698
- **⚠️ عام دوائیوں کی اقسام:**
699
- • **دل**: بیٹا بلاکرز، ACE inhibitors، statins
700
- • **ذیابیطس**: میٹفارمن، انسولین، SGLT2 inhibitors
701
- • **ہائی بلڈ پریشر**: ڈائیوریٹکس، کیلشیم چینل بلاکرز
702
- • **درد**: NSAIDs، acetaminophen (احتیاط سے استعمال کریں)
703
-
704
  **🚨 دوائیوں کی انتباہی علامات:**
705
  • شدید الرجک رد عمل (خارش، سوجن)
706
  • دوا لینے کے بعد سانس لینے میں دشواری
@@ -708,12 +716,6 @@ Please ask me specific health-related questions, and I'll provide detailed, help
708
  • غیر معمولی خون بہنا یا چوٹ لگنا
709
  • الجھن یا توہمات
710
 
711
- **💡 اہم یاد دہانیاں:**
712
- • ڈاکٹر کے مشورے کے بغیر دوائیں بند نہ کریں
713
- • اپنے ڈاکٹر کو مضر اثرات کی رپورٹ کریں
714
- • دوائیں اصل کنٹینرز میں رکھیں
715
- • میعاد ختم ہونے کی تاریخوں کو باقاعدگی سے چیک کریں
716
-
717
  *نوٹ: ہمیشہ اپنے ہیلتھ کیئر فراہم کرنے والے کی مخصوص ہدایات پر عمل کریں۔*
718
  """
719
 
@@ -737,20 +739,6 @@ Please ask me specific health-related questions, and I'll provide detailed, help
737
  • Severe burns
738
  • Poisoning or overdose
739
  • Seizures
740
- • Severe allergic reactions
741
-
742
- **🆘 First Aid Basics:**
743
- • **CPR**: Start if no breathing/pulse (30 compressions: 2 breaths)
744
- • **Bleeding**: Apply direct pressure
745
- • **Choking**: Perform Heimlich maneuver
746
- • **Burns**: Cool with running water
747
- • **Fainting**: Lay flat, elevate legs
748
-
749
- **📋 Emergency Preparedness:**
750
- • Keep emergency numbers handy
751
- • Know location of nearest hospital
752
- • Have medical history documented
753
- • Keep medications list updated
754
 
755
  *⚠️ THIS IS EMERGENCY GUIDANCE ONLY. SEEK PROFESSIONAL MEDICAL HELP IMMEDIATELY.*
756
  """
@@ -773,75 +761,60 @@ Please ask me specific health-related questions, and I'll provide detailed, help
773
  • شدید جلنے
774
  • زہر یا اوور ڈوز
775
  • دورے
776
- • شدید الرجک رد عمل
777
-
778
- **🆘 فرسٹ ایڈ کی بنیادی باتیں:**
779
- • **CPR**: اگر سانس/پلس نہ ہو تو شروع کریں (30 کمپریشن: 2 سانس)
780
- • **خون بہنا**: براہ راست دباؤ ڈالیں
781
- • **گلا گھٹنا**: ہیملک مانور انجام دیں
782
- • **جلنے**: پانی سے ٹھنڈا کریں
783
- • **بیہوشی**: سیدھا لیٹائیں، ٹانگیں اونچی کریں
784
-
785
- **📋 ہنگامی تیاری:**
786
- • ہنگامی نمبرز ہاتھ میں رکھیں
787
- • قریبی ہسپتال کا مقام جانیں
788
- • طبی تاریخ دستاویزی شکل میں رکھیں
789
- • دوائیوں کی فہرست اپ ڈیٹ رکھیں
790
 
791
  *⚠️ یہ صرف ہنگامی رہنمائی ہے۔ فوری طور پر پیشہ ورانہ طبی مدد حاصل کریں۔*
792
  """
793
 
794
  def _format_general_health_response(self, language):
795
- knowledge = self.medical_knowledge_base['general_health']
796
  if language == 'English':
797
- return f"""
798
  **🌿 Comprehensive Health & Wellness Guide**
799
 
800
  **💚 Lifestyle Recommendations:**
801
- {chr(10).join(['' + tip for tip in knowledge['lifestyle']])}
 
 
 
 
802
 
803
  **🛡️ Preventive Healthcare:**
804
- {chr(10).join(['' + tip for tip in knowledge['prevention']])}
805
-
806
- **🎯 Health Monitoring Schedule:**
807
- **Daily**: Blood pressure (if hypertensive), blood sugar (if diabetic)
808
- **Weekly**: Weight, exercise minutes
809
- • **Monthly**: Self-examinations (skin, breasts, testicles)
810
- • **Annual**: Complete physical, blood tests, dental checkup
811
- • **As recommended**: Cancer screenings, vision/hearing tests
812
 
813
  **🌟 Healthy Habits for Pakistan:**
814
  • Drink filtered/boiled water
815
  • Eat fresh, locally available fruits and vegetables
816
  • Practice good food hygiene
817
  • Get adequate sunlight exposure (vitamin D)
818
- • Maintain social connections and mental wellbeing
819
 
820
  *Remember: Small consistent changes lead to lasting health improvements!*
821
  """
822
  else:
823
- return f"""
824
  **🌿 صحت اور تندرستی کی جامع گائیڈ**
825
 
826
  **💚 طرز زندگی کی سفارشات:**
827
- {chr(10).join(['' + tip for tip in ['رات میں 7-9 گھنٹے معیاری نیند', 'تناؤ کے انتظام کی تکنیکیں', 'سگریٹ نوشی سے پرہیز', 'شراب کو 1-2 ڈرنکس/دن تک محدود کریں', 'باقاعدہ صحت کی جانچ']])}
 
 
 
 
828
 
829
  **🛡️ احتیاطی ہیلتھ کیئر:**
830
- {chr(10).join(['' + tip for tip in ['سالانہ جسمانی امتحانات', 'ویکسینیشن اپ ڈیٹ', 'باقاعدہ ہاتھ دھونا', 'سورج سے تحفظ', 'ذہنی صحت کی دیکھ بھال']])}
831
-
832
- **🎯 صحت کی نگرانی کا شیڈول:**
833
- **روزانہ**: بلڈ پریشر (اگر ہائی بلڈ پریشر ہو)، بلڈ شوگر (اگر ذیابیطس ہو)
834
- **ہفتہ وار**: وزن، ورزش کے منٹ
835
- • **ماہانہ**: خود معائنہ (جلد، چھاتی، خصیے)
836
- • **سالانہ**: مکمل جسمانی، خون کے ٹیسٹ، دانتوں کا چیک اپ
837
- • **جیسا کہ تجویز کیا گیا ہے**: کینسر کی اسکریننگ، بینائی/سماعت کے ٹیسٹ
838
 
839
  **🌟 پاکستان کے لیے صحت مند عادات:**
840
  • فلٹر/ابلا ہوا پانی پیئیں
841
  • تازہ، مقامی طور پر دستیاب پھل اور سبزیاں کھائیں
842
  • اچھی غذا کی حفظان صحت کی مشق کریں
843
  • مناسب سورج کی روشنی (وٹامن ڈی) حاصل کریں
844
- • سماجی رابطے اور ذہنی تندرستی برقرار رکھیں
845
 
846
  *یاد رکھیں: چھوٹی مسلسل تبدیلیاں پائیدار صحت کی بہتری کا باعث بنتی ہیں!*
847
  """
@@ -864,15 +837,7 @@ I understand you're asking about health topics. I'm specially trained to help wi
864
  • Emergency situations
865
  • General wellness and prevention
866
 
867
- **💡 How to Get Better Answers:**
868
- Please ask specific questions like:
869
- • "What are the symptoms of heart disease?"
870
- • "How to manage diabetes?"
871
- • "What foods help lower blood pressure?"
872
- • "Exercise recommendations for beginners"
873
- • "When to go to emergency room?"
874
-
875
- I'll provide detailed, accurate medical information to help you make informed health decisions.
876
 
877
  *⚠️ Remember: I'm an AI assistant. For personal medical advice, always consult qualified healthcare professionals.*
878
  """
@@ -893,15 +858,7 @@ I'll provide detailed, accurate medical information to help you make informed he
893
  • ہنگامی حالات
894
  • عام تندرستی اور روک تھام
895
 
896
- **💡 بہتر جوابات کیسے حاصل کریں:**
897
- براہ کرم مخصوص سوالات پوچھیں جیسے:
898
- • "دل کی بیماری کی علامات کیا ہیں؟"
899
- • "ذیابیطس کا انتظام کیسے کریں؟"
900
- • "کون سی غذائیں بلڈ پریشر کم کرنے میں مدد کرتی ہیں؟"
901
- • "ابتدائی افراد کے لیے ورزش کی سفارشات"
902
- • "ایمرجنسی روم کب جائیں؟"
903
-
904
- میں آپ کو معلوماتی صحت کے فیصلے کرنے میں مدد کے لیے تفصیلی، درست طبی معلومات فراہم کروں گا۔
905
 
906
  *⚠️ یاد رکھیں: میں ایک AI اسسٹنٹ ہوں۔ ذاتی طبی مشورے کے لیے، ہمیشہ کوالیفائیڈ ہیلتھ کیئر پروفیشنلز سے مشورہ کریں۔*
907
  """
@@ -919,7 +876,6 @@ class PDFReportGenerator:
919
  if language == 'English':
920
  self.pdf.cell(0, 10, 'SEHATAI MEDICAL ASSESSMENT REPORT', 0, 1, 'C')
921
  else:
922
- # For Urdu, we'll use English to avoid encoding issues
923
  self.pdf.cell(0, 10, 'SEHATAI MEDICAL ASSESSMENT REPORT', 0, 1, 'C')
924
 
925
  self.pdf.ln(10)
@@ -1010,7 +966,8 @@ class PDFReportGenerator:
1010
  self.pdf.set_font('Arial', 'I', 8)
1011
  self.pdf.cell(0, 10, f'Generated by SehatAI on: {datetime.now().strftime("%Y-%m-%d %H:%M")}', 0, 1, 'C')
1012
 
1013
- return self.pdf.output(dest='S').encode('latin1', 'replace')
 
1014
 
1015
  def _safe_encode(self, text):
1016
  """Safely encode text for PDF generation"""
@@ -1021,58 +978,39 @@ class PDFReportGenerator:
1021
  except:
1022
  return "Encoding error"
1023
 
1024
- # Load ML models with error handling
1025
  @st.cache_resource(show_spinner=False)
1026
  def load_models():
1027
  models = {}
1028
- scalers = {}
1029
 
1030
- try:
1031
- # Load heart disease model
1032
- if os.path.exists('heart_model.pkl'):
1033
- models['heart'] = joblib.load('heart_model.pkl')
1034
- st.success("✅ Heart disease model loaded successfully")
1035
- else:
1036
- st.warning("⚠️ Heart model file not found, using rule-based assessment")
1037
- models['heart'] = None
1038
- except Exception as e:
1039
- st.warning(f"⚠️ Error loading heart model: {str(e)}")
1040
- models['heart'] = None
1041
 
1042
- try:
1043
- # Load diabetes model
1044
- if os.path.exists('diabeties_model.pkl'):
1045
- models['diabetes'] = joblib.load('diabeties_model.pkl')
1046
- st.success("✅ Diabetes model loaded successfully")
1047
- else:
1048
- st.warning("⚠️ Diabetes model file not found, using rule-based assessment")
1049
- models['diabetes'] = None
1050
- except Exception as e:
1051
- st.warning(f"⚠️ Error loading diabetes model: {str(e)}")
1052
- models['diabetes'] = None
1053
 
1054
- try:
1055
- # Load hypertension model
1056
- if os.path.exists('hypertension_model.pkl'):
1057
- models['hypertension'] = joblib.load('hypertension_model.pkl')
1058
- st.success("✅ Hypertension model loaded successfully")
1059
- else:
1060
- st.warning("⚠️ Hypertension model file not found, using rule-based assessment")
1061
- models['hypertension'] = None
1062
- except Exception as e:
1063
- st.warning(f"⚠️ Error loading hypertension model: {str(e)}")
1064
- models['hypertension'] = None
1065
 
1066
- # Load scalers
1067
- try:
1068
- if os.path.exists('scaler.pkl'):
1069
- scalers['default'] = joblib.load('scaler.pkl')
1070
- st.success("✅ Scaler loaded successfully")
1071
- except:
1072
- st.warning("⚠️ Scaler not available, using standard scaling")
1073
- scalers['default'] = None
1074
 
1075
- return models, scalers
1076
 
1077
  def calculate_priority_score(heart_risk, diabetes_risk, hypertension_risk):
1078
  """Calculate integrated priority score with clinical weighting"""
@@ -1118,71 +1056,56 @@ def validate_patient_data(age, bp_systolic, bp_diastolic, heart_rate):
1118
 
1119
  return errors
1120
 
1121
- def predict_with_models(age, bp_systolic, bp_diastolic, heart_rate, cholesterol, glucose, bmi, symptoms, models, scalers):
1122
- """Predict risks using loaded ML models"""
1123
  heart_risk, diabetes_risk, hypertension_risk = 0.0, 0.0, 0.0
1124
 
1125
- try:
1126
- # Prepare features for heart model
1127
- if models['heart'] is not None:
1128
  heart_features = np.array([[
1129
  age, bp_systolic, cholesterol, heart_rate,
1130
  symptoms['chest_pain'], symptoms['shortness_breath'],
1131
  symptoms['palpitations'], bmi, glucose
1132
  ]])
1133
-
1134
- if scalers.get('default') is not None:
1135
- heart_features = scalers['default'].transform(heart_features)
1136
-
1137
  heart_risk = models['heart'].predict_proba(heart_features)[0][1]
1138
- else:
1139
  heart_risk = predict_risk_rule_based_heart(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
1140
-
1141
- except Exception as e:
1142
  heart_risk = predict_risk_rule_based_heart(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
1143
 
1144
- try:
1145
- # Prepare features for diabetes model
1146
- if models['diabetes'] is not None:
1147
  diabetes_features = np.array([[
1148
  age, glucose, bmi, cholesterol,
1149
  symptoms['fatigue'], symptoms['blurred_vision'],
1150
  bp_systolic, heart_rate
1151
  ]])
1152
-
1153
- if scalers.get('default') is not None:
1154
- diabetes_features = scalers['default'].transform(diabetes_features)
1155
-
1156
  diabetes_risk = models['diabetes'].predict_proba(diabetes_features)[0][1]
1157
- else:
1158
  diabetes_risk = predict_risk_rule_based_diabetes(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
1159
-
1160
- except Exception as e:
1161
  diabetes_risk = predict_risk_rule_based_diabetes(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
1162
 
1163
- try:
1164
- # Prepare features for hypertension model
1165
- if models['hypertension'] is not None:
1166
  hypertension_features = np.array([[
1167
  age, bp_systolic, bp_diastolic, bmi,
1168
  symptoms['dizziness'], symptoms['palpitations'],
1169
  heart_rate, cholesterol
1170
  ]])
1171
-
1172
- if scalers.get('default') is not None:
1173
- hypertension_features = scalers['default'].transform(hypertension_features)
1174
-
1175
  hypertension_risk = models['hypertension'].predict_proba(hypertension_features)[0][1]
1176
- else:
1177
  hypertension_risk = predict_risk_rule_based_hypertension(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
1178
-
1179
- except Exception as e:
1180
  hypertension_risk = predict_risk_rule_based_hypertension(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
1181
 
1182
  return heart_risk, diabetes_risk, hypertension_risk
1183
 
1184
  def predict_risk_rule_based_heart(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms):
1185
- """Rule-based heart risk prediction"""
1186
  risk = 0.0
1187
 
1188
  # Age factor
@@ -1213,10 +1136,10 @@ def predict_risk_rule_based_heart(age, bp_systolic, bp_diastolic, cholesterol, g
1213
  if symptoms['shortness_breath']: risk += 0.15
1214
  if symptoms['palpitations']: risk += 0.10
1215
 
1216
- return min(0.95, risk)
1217
 
1218
  def predict_risk_rule_based_diabetes(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms):
1219
- """Rule-based diabetes risk prediction"""
1220
  risk = 0.0
1221
 
1222
  # Age factor
@@ -1241,10 +1164,10 @@ def predict_risk_rule_based_diabetes(age, bp_systolic, bp_diastolic, cholesterol
1241
  if symptoms['fatigue']: risk += 0.10
1242
  if symptoms['blurred_vision']: risk += 0.08
1243
 
1244
- return min(0.95, risk)
1245
 
1246
  def predict_risk_rule_based_hypertension(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms):
1247
- """Rule-based hypertension risk prediction"""
1248
  risk = 0.0
1249
 
1250
  # Blood pressure factor (most important)
@@ -1264,11 +1187,11 @@ def predict_risk_rule_based_hypertension(age, bp_systolic, bp_diastolic, cholest
1264
  if symptoms['dizziness']: risk += 0.10
1265
  if symptoms['palpitations']: risk += 0.08
1266
 
1267
- return min(0.95, risk)
1268
 
1269
- def create_download_link(pdf_data, filename, text):
1270
  """Create a download link for PDF"""
1271
- b64 = base64.b64encode(pdf_data).decode()
1272
  href = f'<a href="data:application/octet-stream;base64,{b64}" download="{filename}">{text}</a>'
1273
  return href
1274
 
@@ -1279,10 +1202,7 @@ def main():
1279
 
1280
  # Load ML models
1281
  with st.spinner("🔄 Loading AI models..."):
1282
- models, scalers = load_models()
1283
-
1284
- # Initialize chatbot
1285
- chatbot = HealthcareChatbot()
1286
 
1287
  # Language selector at top right with Pakistan flag colors
1288
  col_lang, col_space = st.columns([1, 5])
@@ -1454,7 +1374,7 @@ def main():
1454
  # Predict risks using ML models
1455
  heart_risk, diabetes_risk, hypertension_risk = predict_with_models(
1456
  age, bp_systolic, bp_diastolic, heart_rate,
1457
- cholesterol, glucose, bmi, symptoms_dict, models, scalers
1458
  )
1459
 
1460
  # Calculate integrated priority score
@@ -1574,6 +1494,34 @@ def main():
1574
  st.markdown('<h2 style="color: #00401A; border-bottom: 3px solid #00401A; padding-bottom: 10px;">💬 سیحت اے آئی ہیلتھ اسسٹنٹ</h2>', unsafe_allow_html=True)
1575
  st.write("صحت سے متعلق سوالات پوچھیں اور فوری، قابل اعتماد طبی معلومات حاصل کریں")
1576
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1577
  # Display chat history
1578
  for message in st.session_state.chat_history:
1579
  if message["role"] == "user":
@@ -1610,69 +1558,38 @@ def main():
1610
 
1611
  with col_qa1:
1612
  if st.button("❤️ Heart Health", use_container_width=True):
1613
- st.session_state.chat_history.append({
1614
- "role": "user",
1615
- "content": "Tell me about heart disease symptoms and prevention"
1616
- })
 
1617
  st.rerun()
1618
 
1619
  with col_qa2:
1620
  if st.button("🩺 Diabetes", use_container_width=True):
1621
- st.session_state.chat_history.append({
1622
- "role": "user",
1623
- "content": "What are diabetes symptoms and management strategies?"
1624
- })
 
1625
  st.rerun()
1626
 
1627
  with col_qa3:
1628
  if st.button("💓 Blood Pressure", use_container_width=True):
1629
- st.session_state.chat_history.append({
1630
- "role": "user",
1631
- "content": "How to control high blood pressure naturally?"
1632
- })
 
1633
  st.rerun()
1634
 
1635
  with col_qa4:
1636
  if st.button("🍎 Nutrition", use_container_width=True):
1637
- st.session_state.chat_history.append({
1638
- "role": "user",
1639
- "content": "What is a healthy diet for heart health?"
1640
- })
1641
- st.rerun()
1642
-
1643
- # Additional quick actions
1644
- col_qa5, col_qa6, col_qa7, col_qa8 = st.columns(4)
1645
-
1646
- with col_qa5:
1647
- if st.button("💪 Exercise", use_container_width=True):
1648
- st.session_state.chat_history.append({
1649
- "role": "user",
1650
- "content": "Exercise recommendations for beginners"
1651
- })
1652
- st.rerun()
1653
-
1654
- with col_qa6:
1655
- if st.button("🔍 Symptoms", use_container_width=True):
1656
- st.session_state.chat_history.append({
1657
- "role": "user",
1658
- "content": "When should I seek emergency medical care?"
1659
- })
1660
- st.rerun()
1661
-
1662
- with col_qa7:
1663
- if st.button("💊 Medications", use_container_width=True):
1664
- st.session_state.chat_history.append({
1665
- "role": "user",
1666
- "content": "General medication safety guidelines"
1667
- })
1668
- st.rerun()
1669
-
1670
- with col_qa8:
1671
- if st.button("🚨 Emergency", use_container_width=True):
1672
- st.session_state.chat_history.append({
1673
- "role": "user",
1674
- "content": "What are emergency warning signs?"
1675
- })
1676
  st.rerun()
1677
 
1678
  st.markdown('</div>', unsafe_allow_html=True)
@@ -1699,16 +1616,16 @@ def main():
1699
  st.subheader("مریض رپورٹ ڈاؤن لوڈ کریں")
1700
 
1701
  pdf_generator = PDFReportGenerator()
1702
- pdf_data = pdf_generator.generate_report(
1703
  latest_assessment['patient_data'],
1704
  latest_assessment['risk_scores'],
1705
  language
1706
  )
1707
 
1708
  if language == "English":
1709
- st.markdown(create_download_link(pdf_data, "sehatai_medical_report.pdf", "📥 Download Medical Report (PDF)"), unsafe_allow_html=True)
1710
  else:
1711
- st.markdown(create_download_link(pdf_data, "sehatai_medical_report.pdf", "📥 طبی رپورٹ ڈاؤن لوڈ کریں (PDF)"), unsafe_allow_html=True)
1712
 
1713
  # Analytics Section
1714
  if language == "English":
 
12
  import base64
13
  from fpdf import FPDF
14
  import tempfile
15
+ import requests
16
+ import json
17
 
18
  # Set page config first
19
  st.set_page_config(
 
165
  font-weight: bold;
166
  margin: 0 10px;
167
  }
168
+ .api-key-section {
169
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
170
+ padding: 15px;
171
+ border-radius: 10px;
172
+ margin: 10px 0;
173
+ color: white;
174
+ }
175
  </style>
176
  """, unsafe_allow_html=True)
177
 
 
187
  st.session_state.chat_history = []
188
  if 'current_language' not in st.session_state:
189
  st.session_state.current_language = 'English'
190
+ if 'groq_api_key' not in st.session_state:
191
+ st.session_state.groq_api_key = ''
192
 
193
  # Healthcare quotes database
194
  HEALTHCARE_QUOTES = [
 
219
  }
220
  ]
221
 
222
+ class GroqClient:
223
+ def __init__(self, api_key):
224
+ self.api_key = api_key
225
+ self.base_url = "https://api.groq.com/openai/v1"
226
+ self.headers = {
227
+ "Authorization": f"Bearer {api_key}",
228
+ "Content-Type": "application/json"
229
+ }
230
+
231
+ def chat_completions_create(self, messages, model="llama3-8b-8192", temperature=0.3, max_tokens=1024):
232
+ try:
233
+ url = f"{self.base_url}/chat/completions"
234
+ data = {
235
+ "messages": messages,
236
+ "model": model,
237
+ "temperature": temperature,
238
+ "max_tokens": max_tokens,
239
+ "top_p": 0.9
240
+ }
241
+
242
+ response = requests.post(url, headers=self.headers, json=data, timeout=30)
243
+ response.raise_for_status()
244
+
245
+ result = response.json()
246
+ return result
247
+
248
+ except Exception as e:
249
+ raise Exception(f"Groq API error: {str(e)}")
250
+
251
  class HealthcareChatbot:
252
+ def __init__(self, groq_client=None):
253
+ self.groq_client = groq_client
254
  self.medical_knowledge_base = {
255
  'heart_disease': {
256
  'symptoms': ["Chest pain or discomfort", "Shortness of breath", "Pain in arms, neck, jaw", "Nausea", "Fatigue", "Dizziness"],
 
269
  'risk_factors': ["Family history", "Age over 65", "Obesity", "High salt intake", "Stress", "Alcohol consumption", "Smoking"],
270
  'prevention': ["DASH diet (low sodium)", "Regular aerobic exercise", "Weight management", "Stress reduction", "Limit alcohol", "No smoking"],
271
  'emergency_signs': ["Severe headache", "Chest pain", "Difficulty breathing", "Vision changes", "Confusion", "Seizures"]
 
 
 
 
 
 
272
  }
273
  }
274
 
275
  def get_response(self, user_input, language='English'):
276
+ # If Groq client is available, use it for more intelligent responses
277
+ if self.groq_client:
278
+ try:
279
+ return self._get_groq_response(user_input, language)
280
+ except Exception as e:
281
+ st.error(f"Groq API error: {str(e)}. Using rule-based response.")
282
+
283
+ # Fallback to rule-based responses
284
+ return self._get_rule_based_response(user_input, language)
285
+
286
+ def _get_groq_response(self, user_input, language):
287
+ system_prompt = """You are SehatAI, a professional healthcare assistant designed for Pakistani patients.
288
+ Provide accurate, culturally appropriate medical advice in a compassionate manner.
289
+ Focus on preventive care, symptom explanation, and when to seek medical attention.
290
+ Always emphasize that you are an AI assistant and recommend consulting healthcare professionals for serious conditions.
291
+ Be specific, practical, and provide actionable advice."""
292
+
293
+ if language == 'Urdu':
294
+ system_prompt += " Respond in Urdu with proper medical terminology and cultural sensitivity."
295
+ else:
296
+ system_prompt += " Respond in English with clear, professional medical advice."
297
+
298
+ messages = [
299
+ {"role": "system", "content": system_prompt},
300
+ {"role": "user", "content": user_input}
301
+ ]
302
+
303
+ response = self.groq_client.chat_completions_create(
304
+ messages=messages,
305
+ model="llama3-8b-8192",
306
+ temperature=0.3,
307
+ max_tokens=1024
308
+ )
309
+
310
+ bot_response = response['choices'][0]['message']['content']
311
+
312
+ # Add disclaimer
313
+ if language == 'Urdu':
314
+ bot_response += "\n\n⚠️ براہ کرم نوٹ کریں: یہ ایک AI اسسٹنٹ ہے۔ سنگین طبی حالات کے لیے ہمیشہ کوالیفائیڈ ڈاکٹر سے مشورہ کریں۔"
315
+ else:
316
+ bot_response += "\n\n⚠️ Please note: This is an AI assistant. Always consult qualified doctors for serious medical conditions."
317
+
318
+ return bot_response
319
+
320
+ def _get_rule_based_response(self, user_input, language):
321
  user_input = user_input.lower().strip()
322
 
323
  # Greeting patterns
 
442
  **🚑 ہنگامی انتباہی علامات (فوری علاج حاصل کریں):**
443
  {chr(10).join(['• ' + sign for sign in ['شدید سینے میں درد', 'سانس لینے میں شدید دشواری', 'بیہوش ہونا', 'تیز دل کی دھڑکن', 'بازو/کندھوں میں پھیلنے والا درد']])}
444
 
 
 
 
 
 
 
445
  *🔬 کلینیکل نوٹ: ابتدائی تشخیص جان بچاتی ہے۔ دل کی صحت کے لیے باقاعدہ چیک اپ بہت ضروری ہیں۔*
446
  """
447
 
 
487
  **🚑 ہنگامی علامات (فوری علاج حاصل کریں):**
488
  {chr(10).join(['• ' + sign for sign in ['بلڈ شوگر >300 mg/dL یا <70 mg/dL', 'الجھن یا بے ترتیبی', 'پھل کی سی بو والی سانس', 'تیز سانس لینا', 'ہوش کا ضیاع']])}
489
 
 
 
 
 
 
 
490
  *🔬 کلینیکل نوٹ: مستقل نگرانی اور طرز زندگی کا انتظام ذیابیطس کے کنٹرول کی کلید ہے۔*
491
  """
492
 
 
532
  **🚑 ہائی بلڈ پریشر کی ہنگامی علامات:**
533
  {chr(10).join(['• ' + sign for sign in ['شدید سر درد', 'سینے میں درد', 'سانس لینے میں دشواری', 'بینائی میں تبدیلی', 'الجھن', 'دورے']])}
534
 
 
 
 
 
 
 
535
  *🔬 کلینیکل نوٹ: خاموش قاتل - اکثر کوئی علامات نہیں ہوتیں۔ باقاعدہ نگرانی ضروری ہے۔*
536
  """
537
 
538
  def _format_nutrition_response(self, language):
 
539
  if language == 'English':
540
+ return """
541
  **🍎 Comprehensive Nutrition Guide**
542
 
543
  **🥦 Healthy Eating Principles:**
544
+ Eat 5-9 servings of fruits/vegetables daily
545
+ • Choose whole grains over refined
546
+ • Include lean proteins
547
+ • Stay hydrated (8-10 glasses water)
548
+ • Limit processed foods and sugar
549
 
550
  **🎯 Specific Recommendations:**
551
  • **Heart Health**: Mediterranean diet, omega-3 rich foods
552
  • **Diabetes**: Controlled carb intake, high fiber
553
  • **Hypertension**: Low sodium (<2300mg/day), potassium-rich foods
 
 
 
 
 
 
 
554
 
555
  **💡 Pakistani Dietary Adaptations:**
556
  • Choose whole wheat chapati over refined flour
 
561
  *Remember: Balanced nutrition is foundation of good health.*
562
  """
563
  else:
564
+ return """
565
  **🍎 غذائیت کی جامع گائیڈ**
566
 
567
  **🥦 صحت مند کھانے کے اصول:**
568
+ • روزانہ 5-9 سرونگ پھل/سبزیاں کھائیں
569
+ • ریفائنڈ کی بجائے سارا اناج منتخب کریں
570
+ • لیان پروٹین شامل کریں
571
+ • ہائیڈریٹ رہیں (8-10 گلاس پانی)
572
+ • پراسیسڈ فوڈز اور چینی کو محدود کریں
573
 
574
  **🎯 مخصوص سفارشات:**
575
  • **دل کی صحت**: بحیرہ روم کی غذا، اومیگا 3 سے بھرپور غذائیں
576
  • **ذیابیطس**: کنٹرول کاربوہائیڈریٹ انٹیک، زیادہ فائبر
577
  • **ہائی بلڈ پریشر**: کم سوڈیم (<2300mg/day)، پوٹاشیم سے بھرپور غذائیں
 
 
 
 
 
 
 
578
 
579
  **💡 پاکستانی غذائی موافقت:**
580
  • ریفائنڈ آٹے کی بجائے whole wheat چپاتی منتخب کریں
 
586
  """
587
 
588
  def _format_exercise_response(self, language):
 
589
  if language == 'English':
590
+ return """
591
  **💪 Comprehensive Exercise Guide**
592
 
593
  **🏃‍♂️ Exercise Recommendations:**
594
+ 150 mins moderate exercise weekly
595
+ • Strength training 2x weekly
596
+ • Stay active throughout day
597
+ • Include flexibility exercises
598
+ • Get adequate rest between workouts
599
 
600
  **🎯 Disease-Specific Exercise:**
601
  • **Heart Health**: 30 mins moderate cardio daily
602
  • **Diabetes**: Combination of cardio and strength training
603
  • **Hypertension**: Regular aerobic exercise
 
604
 
605
  **🌞 Pakistani Climate Considerations:**
606
  • Exercise in cooler morning/evening hours
607
  • Stay hydrated with water and electrolytes
608
  • Wear light, breathable clothing
 
 
 
 
 
 
 
609
 
610
  *Important: Consult doctor before starting new exercise program.*
611
  """
612
  else:
613
+ return """
614
  **💪 ورزش کی جامع گائیڈ**
615
 
616
  **🏃‍♂️ ورزش کی سفارشات:**
617
+ • ہفتے میں 150 منٹ اعتدال پسند ورزش
618
+ • ہفتے میں 2 بار طاقت کی تربیت
619
+ • پورے دن متحرک رہیں
620
+ • لچک کی ورزشیں شامل کریں
621
+ • ورک آؤٹس کے درمیان مناسب آرام حاصل کریں
622
 
623
  **🎯 بیماری کی مخصوص ورزش:**
624
  • **دل کی صحت**: روزانہ 30 منٹ اعتدال پسند کارڈیو
625
  • **ذیابیطس**: کارڈیو اور طاقت کی تربیت کا مجموعہ
626
  • **ہائی بلڈ پریشر**: باقاعدہ ایروبک ورزش
 
627
 
628
  **🌞 پاکستانی آب و ہوا کے تحفظات:**
629
  • ٹھنڈے صبح/شام کے اوقات میں ورزش کریں
630
  • پانی اور الیکٹرولائٹس کے ساتھ ہائیڈریٹ رہیں
631
  • ہلکے، ہوا دار کپڑے پہنیں
 
 
 
 
 
 
 
632
 
633
  *اہم: نئی ورزش پروگرام شروع کرنے سے پہلے ڈاکٹر سے مشورہ کریں۔*
634
  """
 
645
  • Sudden dizziness, weakness, or confusion
646
  • Unexplained weight loss (>10% body weight)
647
  • Symptoms lasting more than 2 weeks
 
 
 
 
 
 
 
 
648
 
649
  **🚨 Emergency Warning Signs (Go to ER):**
650
  • Difficulty breathing or shortness of breath
 
652
  • Severe bleeding that doesn't stop
653
  • Sudden severe pain anywhere in body
654
  • Loss of consciousness or fainting
 
 
655
 
656
  *⚠️ Important: This is general guidance. Always consult healthcare professional for proper diagnosis.*
657
  """
 
666
  • اچانک چکر آنا، کمزوری، یا الجھن
667
  • بے وجہ وزن میں کمی (>10% جسمانی وزن)
668
  • 2 ہفتے سے زیادہ علامات برقرار رہنا
 
 
 
 
 
 
 
 
669
 
670
  **🚨 ہنگامی انتباہی علامات (ایمرجنسی روم جائیں):**
671
  • سانس لینے میں دشواری یا سانس کی قلت
 
673
  • شدید خون بہنا جو رک نہیں رہا
674
  • جسم میں کہیں بھی اچانک شدید درد
675
  • ہوش کا ضیاع یا بیہوشی
 
 
676
 
677
  *⚠️ اہم: یہ عام رہنمائی ہے۔ مناسب تشخیص کے لیے ہمیشہ ہیلتھ کیئر پروفیشنل سے مشورہ کریں۔*
678
  """
 
689
  • Inform all doctors about all medications
690
  • Understand purpose and side effects of each medicine
691
 
 
 
 
 
 
 
692
  **🚨 Medication Warning Signs:**
693
  • Severe allergic reactions (rash, swelling)
694
  • Difficulty breathing after taking medicine
 
696
  • Unusual bleeding or bruising
697
  • Confusion or hallucinations
698
 
 
 
 
 
 
 
699
  *Note: Always follow your healthcare provider's specific instructions.*
700
  """
701
  else:
 
709
  • تمام ڈاکٹروں کو تمام دوائیوں کے بارے میں بتائیں
710
  • ہر دوا کے مقصد اور مضر اثرات کو سمجھیں
711
 
 
 
 
 
 
 
712
  **🚨 دوائیوں کی انتباہی علامات:**
713
  • شدید الرجک رد عمل (خارش، سوجن)
714
  • دوا لینے کے بعد سانس لینے میں دشواری
 
716
  • غیر معمولی خون بہنا یا چوٹ لگنا
717
  • الجھن یا توہمات
718
 
 
 
 
 
 
 
719
  *نوٹ: ہمیشہ اپنے ہیلتھ کیئر فراہم کرنے والے کی مخصوص ہدایات پر عمل کریں۔*
720
  """
721
 
 
739
  • Severe burns
740
  • Poisoning or overdose
741
  • Seizures
 
 
 
 
 
 
 
 
 
 
 
 
 
 
742
 
743
  *⚠️ THIS IS EMERGENCY GUIDANCE ONLY. SEEK PROFESSIONAL MEDICAL HELP IMMEDIATELY.*
744
  """
 
761
  • شدید جلنے
762
  • زہر یا اوور ڈوز
763
  • دورے
 
 
 
 
 
 
 
 
 
 
 
 
 
 
764
 
765
  *⚠️ یہ صرف ہنگامی رہنمائی ہے۔ فوری طور پر پیشہ ورانہ طبی مدد حاصل کریں۔*
766
  """
767
 
768
  def _format_general_health_response(self, language):
 
769
  if language == 'English':
770
+ return """
771
  **🌿 Comprehensive Health & Wellness Guide**
772
 
773
  **💚 Lifestyle Recommendations:**
774
+ 7-9 hours quality sleep nightly
775
+ • Stress management techniques
776
+ • No smoking
777
+ • Limit alcohol to 1-2 drinks/day
778
+ • Regular health check-ups
779
 
780
  **🛡️ Preventive Healthcare:**
781
+ Annual physical exams
782
+ • Vaccinations up to date
783
+ Regular hand washing
784
+ Sun protection
785
+ Mental health care
 
 
 
786
 
787
  **🌟 Healthy Habits for Pakistan:**
788
  • Drink filtered/boiled water
789
  • Eat fresh, locally available fruits and vegetables
790
  • Practice good food hygiene
791
  • Get adequate sunlight exposure (vitamin D)
 
792
 
793
  *Remember: Small consistent changes lead to lasting health improvements!*
794
  """
795
  else:
796
+ return """
797
  **🌿 صحت اور تندرستی کی جامع گائیڈ**
798
 
799
  **💚 طرز زندگی کی سفارشات:**
800
+ • رات میں 7-9 گھنٹے معیاری نیند
801
+ • تناؤ کے انتظام کی تکنیکیں
802
+ • سگریٹ نوشی سے پرہیز
803
+ • شراب کو 1-2 ڈرنکس/دن تک محدود کریں
804
+ • باقاعدہ صحت کی جانچ
805
 
806
  **🛡️ احتیاطی ہیلتھ کیئر:**
807
+ • سالانہ جسمانی امتحانات
808
+ • ویکسینیشن اپ ڈیٹ
809
+ باقاعدہ ہاتھ دھونا
810
+ سورج سے تحفظ
811
+ ذہنی صحت کی دیکھ بھال
 
 
 
812
 
813
  **🌟 پاکستان کے لیے صحت مند عادات:**
814
  • فلٹر/ابلا ہوا پانی پیئیں
815
  • تازہ، مقامی طور پر دستیاب پھل اور سبزیاں کھائیں
816
  • اچھی غذا کی حفظان صحت کی مشق کریں
817
  • مناسب سورج کی روشنی (وٹامن ڈی) حاصل کریں
 
818
 
819
  *یاد رکھیں: چھوٹی مسلسل تبدیلیاں پائیدار صحت کی بہتری کا باعث بنتی ہیں!*
820
  """
 
837
  • Emergency situations
838
  • General wellness and prevention
839
 
840
+ Please ask specific questions for detailed medical information.
 
 
 
 
 
 
 
 
841
 
842
  *⚠️ Remember: I'm an AI assistant. For personal medical advice, always consult qualified healthcare professionals.*
843
  """
 
858
  • ہنگامی حالات
859
  • عام تندرستی اور روک تھام
860
 
861
+ براہ کرم تفصیلی طبی معلومات کے لیے مخصوص سوالات پوچھیں۔
 
 
 
 
 
 
 
 
862
 
863
  *⚠️ یاد رکھیں: میں ایک AI اسسٹنٹ ہوں۔ ذاتی طبی مشورے کے لیے، ہمیشہ کوالیفائیڈ ہیلتھ کیئر پروفیشنلز سے مشورہ کریں۔*
864
  """
 
876
  if language == 'English':
877
  self.pdf.cell(0, 10, 'SEHATAI MEDICAL ASSESSMENT REPORT', 0, 1, 'C')
878
  else:
 
879
  self.pdf.cell(0, 10, 'SEHATAI MEDICAL ASSESSMENT REPORT', 0, 1, 'C')
880
 
881
  self.pdf.ln(10)
 
966
  self.pdf.set_font('Arial', 'I', 8)
967
  self.pdf.cell(0, 10, f'Generated by SehatAI on: {datetime.now().strftime("%Y-%m-%d %H:%M")}', 0, 1, 'C')
968
 
969
+ # Return the PDF as bytes
970
+ return self.pdf.output()
971
 
972
  def _safe_encode(self, text):
973
  """Safely encode text for PDF generation"""
 
978
  except:
979
  return "Encoding error"
980
 
981
+ # Load ML models with enhanced error handling
982
  @st.cache_resource(show_spinner=False)
983
  def load_models():
984
  models = {}
 
985
 
986
+ # Try multiple approaches to load models
987
+ model_files = {
988
+ 'heart': ['heart_model.pkl', 'heart_disease_model.pkl', 'models/heart_model.pkl'],
989
+ 'diabetes': ['diabetes_model.pkl', 'diabetes_model.pkl', 'models/diabetes_model.pkl'],
990
+ 'hypertension': ['hypertension_model.pkl', 'models/hypertension_model.pkl']
991
+ }
 
 
 
 
 
992
 
993
+ def try_load_model(model_name, file_list):
994
+ for file_path in file_list:
995
+ if os.path.exists(file_path):
996
+ try:
997
+ model = joblib.load(file_path)
998
+ st.success(f"✅ {model_name} model loaded successfully from {file_path}")
999
+ return model
1000
+ except Exception as e:
1001
+ st.warning(f"⚠️ Error loading {model_name} from {file_path}: {str(e)}")
1002
+ continue
1003
+ return None
1004
 
1005
+ models['heart'] = try_load_model("Heart Disease", model_files['heart'])
1006
+ models['diabetes'] = try_load_model("Diabetes", model_files['diabetes'])
1007
+ models['hypertension'] = try_load_model("Hypertension", model_files['hypertension'])
 
 
 
 
 
 
 
 
1008
 
1009
+ # If no models found, use rule-based
1010
+ if not any(models.values()):
1011
+ st.info("🔍 Using advanced rule-based assessment (no ML models found)")
 
 
 
 
 
1012
 
1013
+ return models
1014
 
1015
  def calculate_priority_score(heart_risk, diabetes_risk, hypertension_risk):
1016
  """Calculate integrated priority score with clinical weighting"""
 
1056
 
1057
  return errors
1058
 
1059
+ def predict_with_models(age, bp_systolic, bp_diastolic, heart_rate, cholesterol, glucose, bmi, symptoms, models):
1060
+ """Predict risks using loaded ML models with fallback to rule-based"""
1061
  heart_risk, diabetes_risk, hypertension_risk = 0.0, 0.0, 0.0
1062
 
1063
+ # Heart disease prediction
1064
+ if models.get('heart') is not None:
1065
+ try:
1066
  heart_features = np.array([[
1067
  age, bp_systolic, cholesterol, heart_rate,
1068
  symptoms['chest_pain'], symptoms['shortness_breath'],
1069
  symptoms['palpitations'], bmi, glucose
1070
  ]])
 
 
 
 
1071
  heart_risk = models['heart'].predict_proba(heart_features)[0][1]
1072
+ except Exception as e:
1073
  heart_risk = predict_risk_rule_based_heart(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
1074
+ else:
 
1075
  heart_risk = predict_risk_rule_based_heart(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
1076
 
1077
+ # Diabetes prediction
1078
+ if models.get('diabetes') is not None:
1079
+ try:
1080
  diabetes_features = np.array([[
1081
  age, glucose, bmi, cholesterol,
1082
  symptoms['fatigue'], symptoms['blurred_vision'],
1083
  bp_systolic, heart_rate
1084
  ]])
 
 
 
 
1085
  diabetes_risk = models['diabetes'].predict_proba(diabetes_features)[0][1]
1086
+ except Exception as e:
1087
  diabetes_risk = predict_risk_rule_based_diabetes(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
1088
+ else:
 
1089
  diabetes_risk = predict_risk_rule_based_diabetes(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
1090
 
1091
+ # Hypertension prediction
1092
+ if models.get('hypertension') is not None:
1093
+ try:
1094
  hypertension_features = np.array([[
1095
  age, bp_systolic, bp_diastolic, bmi,
1096
  symptoms['dizziness'], symptoms['palpitations'],
1097
  heart_rate, cholesterol
1098
  ]])
 
 
 
 
1099
  hypertension_risk = models['hypertension'].predict_proba(hypertension_features)[0][1]
1100
+ except Exception as e:
1101
  hypertension_risk = predict_risk_rule_based_hypertension(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
1102
+ else:
 
1103
  hypertension_risk = predict_risk_rule_based_hypertension(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
1104
 
1105
  return heart_risk, diabetes_risk, hypertension_risk
1106
 
1107
  def predict_risk_rule_based_heart(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms):
1108
+ """Advanced rule-based heart risk prediction"""
1109
  risk = 0.0
1110
 
1111
  # Age factor
 
1136
  if symptoms['shortness_breath']: risk += 0.15
1137
  if symptoms['palpitations']: risk += 0.10
1138
 
1139
+ return min(0.95, max(0.05, risk))
1140
 
1141
  def predict_risk_rule_based_diabetes(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms):
1142
+ """Advanced rule-based diabetes risk prediction"""
1143
  risk = 0.0
1144
 
1145
  # Age factor
 
1164
  if symptoms['fatigue']: risk += 0.10
1165
  if symptoms['blurred_vision']: risk += 0.08
1166
 
1167
+ return min(0.95, max(0.05, risk))
1168
 
1169
  def predict_risk_rule_based_hypertension(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms):
1170
+ """Advanced rule-based hypertension risk prediction"""
1171
  risk = 0.0
1172
 
1173
  # Blood pressure factor (most important)
 
1187
  if symptoms['dizziness']: risk += 0.10
1188
  if symptoms['palpitations']: risk += 0.08
1189
 
1190
+ return min(0.95, max(0.05, risk))
1191
 
1192
+ def create_download_link(pdf_bytes, filename, text):
1193
  """Create a download link for PDF"""
1194
+ b64 = base64.b64encode(pdf_bytes).decode()
1195
  href = f'<a href="data:application/octet-stream;base64,{b64}" download="{filename}">{text}</a>'
1196
  return href
1197
 
 
1202
 
1203
  # Load ML models
1204
  with st.spinner("🔄 Loading AI models..."):
1205
+ models = load_models()
 
 
 
1206
 
1207
  # Language selector at top right with Pakistan flag colors
1208
  col_lang, col_space = st.columns([1, 5])
 
1374
  # Predict risks using ML models
1375
  heart_risk, diabetes_risk, hypertension_risk = predict_with_models(
1376
  age, bp_systolic, bp_diastolic, heart_rate,
1377
+ cholesterol, glucose, bmi, symptoms_dict, models
1378
  )
1379
 
1380
  # Calculate integrated priority score
 
1494
  st.markdown('<h2 style="color: #00401A; border-bottom: 3px solid #00401A; padding-bottom: 10px;">💬 سیحت اے آئی ہیلتھ اسسٹنٹ</h2>', unsafe_allow_html=True)
1495
  st.write("صحت سے متعلق سوالات پوچھیں اور فوری، قابل اعتماد طبی معلومات حاصل کریں")
1496
 
1497
+ # Groq API Configuration
1498
+ with st.expander("🔑 AI Assistant Configuration", expanded=False):
1499
+ st.markdown('<div class="api-key-section">', unsafe_allow_html=True)
1500
+ if language == "English":
1501
+ groq_api_key = st.text_input("Enter Groq API Key:", type="password",
1502
+ value=st.session_state.groq_api_key,
1503
+ help="Get your API key from https://console.groq.com")
1504
+ st.caption("💡 Using Groq API enhances response quality with advanced AI. Leave empty for basic rule-based responses.")
1505
+ else:
1506
+ groq_api_key = st.text_input("Groq API کلید درج کریں:", type="password",
1507
+ value=st.session_state.groq_api_key,
1508
+ help="API کلید حاصل کریں https://console.groq.com سے")
1509
+ st.caption("💡 Groq API کا استعمال جدید AI کے ساتھ جوابات کی معیار کو بہتر بناتا ہے۔ بنیادی رول بیسڈ جوابات کے لیے خالی چھوڑ دیں۔")
1510
+ st.markdown('</div>', unsafe_allow_html=True)
1511
+
1512
+ if groq_api_key:
1513
+ st.session_state.groq_api_key = groq_api_key
1514
+ try:
1515
+ groq_client = GroqClient(groq_api_key)
1516
+ chatbot = HealthcareChatbot(groq_client)
1517
+ st.success("✅ Groq API configured successfully! Using advanced AI responses.")
1518
+ except Exception as e:
1519
+ st.error(f"❌ Error configuring Groq API: {str(e)}")
1520
+ chatbot = HealthcareChatbot()
1521
+ else:
1522
+ chatbot = HealthcareChatbot()
1523
+ st.info("ℹ️ Using rule-based health assistant. For enhanced responses, add Groq API key.")
1524
+
1525
  # Display chat history
1526
  for message in st.session_state.chat_history:
1527
  if message["role"] == "user":
 
1558
 
1559
  with col_qa1:
1560
  if st.button("❤️ Heart Health", use_container_width=True):
1561
+ if language == "English":
1562
+ query = "Tell me about heart disease symptoms and prevention"
1563
+ else:
1564
+ query = "دل کی بیماری کی علامات اور بچاؤ کے بارے میں بتائیں"
1565
+ st.session_state.chat_history.append({"role": "user", "content": query})
1566
  st.rerun()
1567
 
1568
  with col_qa2:
1569
  if st.button("🩺 Diabetes", use_container_width=True):
1570
+ if language == "English":
1571
+ query = "What are diabetes symptoms and management strategies?"
1572
+ else:
1573
+ query = "ذیابیطس کی علامات اور انتظام کی حکمت عملی کیا ہیں؟"
1574
+ st.session_state.chat_history.append({"role": "user", "content": query})
1575
  st.rerun()
1576
 
1577
  with col_qa3:
1578
  if st.button("💓 Blood Pressure", use_container_width=True):
1579
+ if language == "English":
1580
+ query = "How to control high blood pressure naturally?"
1581
+ else:
1582
+ query = "قدرتی طور پر ہائی بلڈ پریشر کو کیسے کنٹرول کریں؟"
1583
+ st.session_state.chat_history.append({"role": "user", "content": query})
1584
  st.rerun()
1585
 
1586
  with col_qa4:
1587
  if st.button("🍎 Nutrition", use_container_width=True):
1588
+ if language == "English":
1589
+ query = "What is a healthy diet for heart health?"
1590
+ else:
1591
+ query = "دل کی صحت کے لیے صحت مند غذا کیا ہے؟"
1592
+ st.session_state.chat_history.append({"role": "user", "content": query})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1593
  st.rerun()
1594
 
1595
  st.markdown('</div>', unsafe_allow_html=True)
 
1616
  st.subheader("مریض رپورٹ ڈاؤن لوڈ کریں")
1617
 
1618
  pdf_generator = PDFReportGenerator()
1619
+ pdf_bytes = pdf_generator.generate_report(
1620
  latest_assessment['patient_data'],
1621
  latest_assessment['risk_scores'],
1622
  language
1623
  )
1624
 
1625
  if language == "English":
1626
+ st.markdown(create_download_link(pdf_bytes, "sehatai_medical_report.pdf", "📥 Download Medical Report (PDF)"), unsafe_allow_html=True)
1627
  else:
1628
+ st.markdown(create_download_link(pdf_bytes, "sehatai_medical_report.pdf", "📥 طبی رپورٹ ڈاؤن لوڈ کریں (PDF)"), unsafe_allow_html=True)
1629
 
1630
  # Analytics Section
1631
  if language == "English":