sunbal7 commited on
Commit
7496748
·
verified ·
1 Parent(s): d3db942

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +262 -315
app.py CHANGED
@@ -8,8 +8,6 @@ import io
8
  import cv2
9
  import easyocr
10
  import os
11
- from sklearn.ensemble import RandomForestClassifier
12
- from sklearn.datasets import make_classification
13
  import plotly.graph_objects as go
14
  import plotly.express as px
15
  from datetime import datetime
@@ -17,9 +15,7 @@ import requests
17
  import json
18
  import base64
19
  import tempfile
20
- import transformers
21
- from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
22
- import torch
23
 
24
  # Set page config first
25
  st.set_page_config(
@@ -104,71 +100,54 @@ def init_session_state():
104
  st.session_state.risk_scores = {}
105
  if 'chat_history' not in st.session_state:
106
  st.session_state.chat_history = []
 
 
107
 
108
  # Load trained models
109
  @st.cache_resource(show_spinner=False)
110
  def load_models():
111
  try:
112
- # Try to load pre-trained models
113
- # For demonstration, we'll create realistic trained models
114
- # In production, you would load your actual trained models
115
 
116
- # Create realistic trained models with medical features
117
- def create_trained_heart_model():
118
- # Simulate a trained heart disease model
119
- model = RandomForestClassifier(n_estimators=100, random_state=42, max_depth=10)
120
- # Train on synthetic medical data
121
- X_heart = np.random.randn(1000, 8) # 8 features for heart disease
122
- y_heart = (X_heart[:, 0] + X_heart[:, 1] * 0.5 + X_heart[:, 2] * 0.3 +
123
- np.random.randn(1000) * 0.1 > 0).astype(int)
124
- model.fit(X_heart, y_heart)
125
- return model
126
-
127
- def create_trained_diabetes_model():
128
- # Simulate a trained diabetes model
129
- model = RandomForestClassifier(n_estimators=100, random_state=42, max_depth=10)
130
- X_diabetes = np.random.randn(1000, 7) # 7 features for diabetes
131
- y_diabetes = (X_diabetes[:, 0] * 0.8 + X_diabetes[:, 1] * 0.6 +
132
- X_diabetes[:, 2] * 0.4 + np.random.randn(1000) * 0.1 > 0).astype(int)
133
- model.fit(X_diabetes, y_diabetes)
134
- return model
135
 
136
- def create_trained_hypertension_model():
137
- # Simulate a trained hypertension model
138
- model = RandomForestClassifier(n_estimators=100, random_state=42, max_depth=10)
139
- X_hypertension = np.random.randn(1000, 6) # 6 features for hypertension
140
- y_hypertension = (X_hypertension[:, 0] * 0.7 + X_hypertension[:, 1] * 0.5 +
141
- X_hypertension[:, 2] * 0.3 + np.random.randn(1000) * 0.1 > 0).astype(int)
142
- model.fit(X_hypertension, y_hypertension)
143
- return model
144
 
145
- heart_model = create_trained_heart_model()
146
- diabetes_model = create_trained_diabetes_model()
147
- hypertension_model = create_trained_hypertension_model()
 
 
 
 
148
 
149
- return heart_model, diabetes_model, hypertension_model
150
 
151
  except Exception as e:
152
  st.error(f"❌ Error loading models: {str(e)}")
153
  return None, None, None
154
 
155
- # Load healthcare chatbot model
156
- @st.cache_resource(show_spinner=False)
157
- def load_chatbot_model():
158
  try:
159
- # Using a small, efficient model for healthcare chatbot
160
- # Microsoft's BioGPT is good for medical conversations but might be large
161
- # Using a smaller model for demonstration
162
- chatbot = pipeline(
163
- "text-generation",
164
- model="microsoft/DialoGPT-small",
165
- tokenizer="microsoft/DialoGPT-small",
166
- torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
167
- device=0 if torch.cuda.is_available() else -1
168
- )
169
- return chatbot
170
  except Exception as e:
171
- st.warning(f"Chatbot model loading failed: {str(e)}. Using rule-based fallback.")
172
  return None
173
 
174
  # Urdu translations
@@ -283,97 +262,57 @@ class OCRProcessor:
283
  return min(95, accuracy) # Cap at 95% for realistic estimates
284
 
285
  class HealthcareChatbot:
286
- def __init__(self):
287
- self.model = load_chatbot_model()
288
- self.medical_knowledge_base = {
289
- 'heart_disease': {
290
- 'symptoms': ['chest pain', 'shortness of breath', 'fatigue', 'palpitations'],
291
- 'advice': 'Consult a cardiologist for proper diagnosis and treatment.',
292
- 'prevention': 'Maintain healthy diet, exercise regularly, avoid smoking.'
293
- },
294
- 'diabetes': {
295
- 'symptoms': ['frequent urination', 'increased thirst', 'fatigue', 'blurred vision'],
296
- 'advice': 'Monitor blood sugar levels and follow medical advice.',
297
- 'prevention': 'Maintain healthy weight and balanced diet.'
298
- },
299
- 'hypertension': {
300
- 'symptoms': ['headache', 'dizziness', 'blurred vision', 'chest pain'],
301
- 'advice': 'Regular blood pressure monitoring and medication adherence.',
302
- 'prevention': 'Reduce salt intake, exercise, manage stress.'
303
- }
304
- }
305
 
306
- def get_medical_response(self, query):
307
- """Generate medical response using AI model with safety guidelines"""
308
  try:
309
- if self.model is None:
310
- return "I'm currently learning about healthcare. Please consult a doctor for medical advice."
311
-
312
- # Medical context prompt
313
- medical_prompt = f"""As a healthcare assistant, provide helpful but cautious information about: {query}
314
-
315
- Important guidelines:
316
- - Always recommend consulting healthcare professionals
317
- - Provide general wellness information
318
- - Do not diagnose or prescribe medication
319
- - Focus on prevention and healthy habits
320
 
321
- Response:"""
322
-
323
- # Generate response
324
- response = self.model(
325
- medical_prompt,
326
- max_length=150,
327
- num_return_sequences=1,
328
- temperature=0.7,
329
- do_sample=True,
330
- pad_token_id=50256
331
- )[0]['generated_text']
332
-
333
- # Extract only the new generated part
334
- response = response.replace(medical_prompt, "").strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
335
 
336
- # Add medical disclaimer
337
- disclaimer = "\n\n*Note: This is AI-generated information. Please consult healthcare professionals for medical advice.*"
338
- return response + disclaimer
339
 
340
  except Exception as e:
341
- return f"I apologize, but I'm having trouble generating a response. Please consult a healthcare professional for advice on: {query}"
342
-
343
- def get_response(self, query, language='English'):
344
- """Main response handler with language support"""
345
- query_lower = query.lower()
346
-
347
- # Detect medical conditions
348
- if any(word in query_lower for word in ['heart', 'cardiac', 'chest pain', 'cholesterol']):
349
- condition = 'heart_disease'
350
- elif any(word in query_lower for word in ['diabetes', 'sugar', 'glucose', 'insulin']):
351
- condition = 'diabetes'
352
- elif any(word in query_lower for word in ['blood pressure', 'hypertension', 'bp']):
353
- condition = 'hypertension'
354
- else:
355
- condition = None
356
-
357
- if condition and language == 'English':
358
- # Use medical knowledge base for specific conditions
359
- info = self.medical_knowledge_base[condition]
360
- response = f"**About {condition.replace('_', ' ').title()}:**\n\n"
361
- response += f"**Common symptoms:** {', '.join(info['symptoms'])}\n\n"
362
- response += f"**General advice:** {info['advice']}\n\n"
363
- response += f"**Prevention tips:** {info['prevention']}\n\n"
364
- response += "*Consult a healthcare professional for proper diagnosis and treatment.*"
365
- return response
366
- elif condition and language == 'Urdu':
367
- # Urdu responses for medical conditions
368
- urdu_responses = {
369
- 'heart_disease': "دل کی بیماری کے بارے میں: عام علامات میں سینے میں درد، سانس لینے میں دشواری، تھکاوٹ شامل ہیں۔ براہ کرم ماہر امراض قلب سے مشورہ کریں۔",
370
- 'diabetes': "ذیابیطس کے بارے میں: عام علامات میں بار بار پیشاب آنا، پیاس لگنا، تھکاوٹ شامل ہیں۔ اپنے ڈاکٹر سے رابطہ کریں۔",
371
- 'hypertension': "ہائی بلڈ پریشر کے بارے میں: عام علامات میں سر درد، چکر آنا، دھندلا نظر آنا شامل ہیں۔ باقاعدہ چیک اپ کروائیں۔"
372
- }
373
- return urdu_responses.get(condition, "براہ کرم ڈاکٹر سے مشورہ کریں۔")
374
- else:
375
- # Use AI model for general questions
376
- return self.get_medical_response(query)
377
 
378
  def calculate_priority_score(heart_risk, diabetes_risk, hypertension_risk):
379
  """Calculate integrated priority score with clinical weighting"""
@@ -419,40 +358,44 @@ def validate_patient_data(age, bp_systolic, bp_diastolic, heart_rate):
419
 
420
  return errors
421
 
422
- def extract_features_from_patient_data(age, bp_systolic, bp_diastolic, heart_rate, cholesterol, glucose, bmi, symptoms):
423
- """Extract features for model prediction"""
424
- # Heart disease features
 
425
  heart_features = np.array([[
426
- age,
427
  bp_systolic,
428
  cholesterol,
429
  heart_rate,
 
 
 
430
  bmi,
431
- 1 if symptoms.get('chest_pain') else 0,
432
- 1 if symptoms.get('shortness_breath') else 0,
433
- 1 if symptoms.get('palpitations') else 0
434
  ]])
435
 
436
- # Diabetes features
437
  diabetes_features = np.array([[
438
  age,
439
  glucose,
440
  bmi,
441
  cholesterol,
442
- 1 if symptoms.get('fatigue') else 0,
443
- 1 if symptoms.get('blurred_vision') else 0,
444
- 1 if symptoms.get('dizziness') else 0
 
445
  ]])
446
 
447
- # Hypertension features
448
  hypertension_features = np.array([[
449
  age,
450
  bp_systolic,
451
  bp_diastolic,
452
  bmi,
 
 
453
  heart_rate,
454
- 1 if symptoms.get('dizziness') else 0,
455
- 1 if symptoms.get('palpitations') else 0
456
  ]])
457
 
458
  return heart_features, diabetes_features, hypertension_features
@@ -468,13 +411,28 @@ def main():
468
 
469
  # Initialize processors
470
  ocr_processor = OCRProcessor()
471
- chatbot = HealthcareChatbot()
472
 
473
  # Language selector in sidebar
474
  with st.sidebar:
475
  st.markdown("<h2 style='text-align: center; color: #2E86AB;'>🏥 AI-Priority OPD</h2>",
476
  unsafe_allow_html=True)
477
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478
  language = st.radio(
479
  "Select Language / زبان منتخب کریں",
480
  ["English", "Urdu"],
@@ -490,14 +448,6 @@ def main():
490
  st.session_state.risk_scores = {}
491
  st.session_state.chat_history = []
492
  st.rerun()
493
-
494
- st.info("""
495
- **System Features:**
496
- - Patient Risk Assessment
497
- - Prescription OCR
498
- - Health Assistant
499
- - Clinical Analytics
500
- """)
501
  else:
502
  st.subheader("فوری اقدامات")
503
  if st.button("🆕 نیا مریض تشخیص", use_container_width=True):
@@ -505,14 +455,6 @@ def main():
505
  st.session_state.risk_scores = {}
506
  st.session_state.chat_history = []
507
  st.rerun()
508
-
509
- st.info("""
510
- **سسٹم کی خصوصیات:**
511
- - مریض کے خطرے کا اندازہ
512
- - نسخہ OCR
513
- - ہیلتھ اسسٹنٹ
514
- - کلینیکل تجزیات
515
- """)
516
 
517
  # Main header
518
  if language == "English":
@@ -582,10 +524,10 @@ def main():
582
  help="سسٹولک بلڈ پریشر mmHg میں")
583
  bp_diastolic = st.number_input("بلڈ پریشر (ڈائیسٹولک)",
584
  min_value=40, max_value=150, value=80,
585
- help="ڈائیسٹولک بلڈ پریشر mmHg میں")
586
  heart_rate = st.number_input("دل کی دھڑکن (bpm)",
587
  min_value=30, max_value=200, value=72,
588
- help="دل کی دھڑکن فی منٹ")
589
  cholesterol = st.number_input("کولیسٹرول کی سطح (mg/dL)",
590
  min_value=100, max_value=400, value=180)
591
  glucose = st.number_input("خون میں گلوکوز (mg/dL)",
@@ -631,21 +573,23 @@ def main():
631
  if validation_errors:
632
  for error in validation_errors:
633
  st.error(f"❌ {error}")
 
 
634
  else:
635
  try:
636
  with st.spinner("🔍 Analyzing patient data and calculating risks..."):
637
  # Prepare symptoms dictionary
638
  symptoms_dict = {
639
- 'chest_pain': chest_pain,
640
- 'shortness_breath': shortness_breath,
641
- 'palpitations': palpitations,
642
- 'fatigue': fatigue,
643
- 'dizziness': dizziness,
644
- 'blurred_vision': blurred_vision
645
  }
646
 
647
- # Extract features for model prediction
648
- heart_features, diabetes_features, hypertension_features = extract_features_from_patient_data(
649
  age, bp_systolic, bp_diastolic, heart_rate, cholesterol, glucose, bmi, symptoms_dict
650
  )
651
 
@@ -654,26 +598,16 @@ def main():
654
  diabetes_risk_proba = diabetes_model.predict_proba(diabetes_features)[0][1]
655
  hypertension_risk_proba = hypertension_model.predict_proba(hypertension_features)[0][1]
656
 
657
- # Apply symptom modifiers based on clinical importance
658
  if chest_pain:
659
  heart_risk_proba = min(1.0, heart_risk_proba * 1.3)
660
  if shortness_breath:
661
  heart_risk_proba = min(1.0, heart_risk_proba * 1.2)
662
- if palpitations:
663
- heart_risk_proba = min(1.0, heart_risk_proba * 1.15)
664
- hypertension_risk_proba = min(1.0, hypertension_risk_proba * 1.1)
665
-
666
  if fatigue:
667
  diabetes_risk_proba = min(1.0, diabetes_risk_proba * 1.2)
668
- heart_risk_proba = min(1.0, heart_risk_proba * 1.1)
669
-
670
  if dizziness:
671
  hypertension_risk_proba = min(1.0, hypertension_risk_proba * 1.3)
672
 
673
- if blurred_vision:
674
- diabetes_risk_proba = min(1.0, diabetes_risk_proba * 1.25)
675
- hypertension_risk_proba = min(1.0, hypertension_risk_proba * 1.15)
676
-
677
  # Calculate integrated priority score
678
  priority_score = calculate_priority_score(
679
  heart_risk_proba, diabetes_risk_proba, hypertension_risk_proba
@@ -770,7 +704,7 @@ def main():
770
 
771
  except Exception as e:
772
  st.error(f"❌ Error in risk assessment: {str(e)}")
773
- st.info("💡 Please ensure all required parameters are filled correctly.")
774
 
775
  with tab2:
776
  # Prescription OCR
@@ -845,142 +779,155 @@ def main():
845
  # Healthcare Chatbot
846
  if language == "English":
847
  st.header("💬 Healthcare Assistant Chatbot")
848
- st.write("Ask health-related questions and get AI-powered responses")
849
  else:
850
  st.header("💬 ہیلتھ کیئر اسسٹنٹ چیٹ بوٹ")
851
- st.write("صحت سے متعلق سوالات پوچھیں اور AI سے طاقتور جوابات حاصل کریں")
852
 
853
- # Display chat history
854
- for message in st.session_state.chat_history:
855
- with st.chat_message(message["role"]):
856
- if message["role"] == "user":
857
- st.markdown(message["content"])
858
- else:
859
- # Format bot response with better styling
860
- st.markdown(f"**🤖 Healthcare Assistant:**\n\n{message['content']}")
861
-
862
- # Chat input
863
- if prompt := st.chat_input(
864
- "Type your health question here..." if language == "English"
865
- else "اپنا صحت کا سوال یہاں ٹائپ کریں..."
866
- ):
867
- # Add user message to chat history
868
- st.session_state.chat_history.append({"role": "user", "content": prompt})
869
-
870
- # Generate bot response
871
- with st.chat_message("assistant"):
872
- with st.spinner("💭 Analyzing your question..." if language == "English" else "💭 آپ کا سوال تجزیہ ہو رہا ہے..."):
873
- response = chatbot.get_response(prompt, language)
874
- st.markdown(f"**🤖 Healthcare Assistant:**\n\n{response}")
875
-
876
- # Add assistant response to chat history
877
- st.session_state.chat_history.append({"role": "assistant", "content": response})
878
-
879
- # Limit chat history to last 10 messages
880
- if len(st.session_state.chat_history) > 10:
881
- st.session_state.chat_history = st.session_state.chat_history[-10:]
882
-
883
- # Quick action buttons
884
- if language == "English":
885
- st.subheader("Quick Health Topics")
886
  else:
887
- st.subheader("فوری صحت کے موضوعات")
888
-
889
- col_qa1, col_qa2, col_qa3 = st.columns(3)
890
-
891
- with col_qa1:
892
- if st.button("❤️ Heart Health", use_container_width=True):
893
- st.session_state.chat_history.append({
894
- "role": "user",
895
- "content": "Tell me about heart disease prevention and symptoms"
896
- })
897
- st.rerun()
898
-
899
- with col_qa2:
900
- if st.button("🩺 Diabetes", use_container_width=True):
901
- st.session_state.chat_history.append({
902
- "role": "user",
903
- "content": "What are the symptoms and management of diabetes?"
904
- })
905
- st.rerun()
906
-
907
- with col_qa3:
908
- if st.button("💓 Blood Pressure", use_container_width=True):
909
- st.session_state.chat_history.append({
910
- "role": "user",
911
- "content": "How to manage high blood pressure?"
912
- })
913
- st.rerun()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
914
 
915
  with tab4:
916
  # Analytics Dashboard
917
  if language == "English":
918
- st.header("📈 Clinical Analytics & Insights")
919
  else:
920
- st.header("📈 کلینیکل تجزیات اور بصیرتیں")
921
-
922
- # Model Performance
923
- if language == "English":
924
- st.subheader("Model Performance Metrics")
 
 
 
 
 
 
 
 
 
 
925
  else:
926
- st.subheader("ماڈل کارکردگی کے پیمانے")
927
-
928
- performance_data = pd.DataFrame({
929
- 'Model': ['Heart Disease', 'Diabetes', 'Hypertension', 'Integrated'],
930
- 'Accuracy': ['88.2%', '85.7%', '86.1%', '87.3%'],
931
- 'Precision': ['86.5%', '83.2%', '85.4%', '84.8%'],
932
- 'Recall': ['89.1%', '84.3%', '87.2%', '86.5%'],
933
- 'AUC Score': ['0.891', '0.843', '0.872', '0.865']
934
- })
935
-
936
- st.dataframe(performance_data, use_container_width=True)
937
-
938
- # Risk Distribution
939
- col_chart1, col_chart2 = st.columns(2)
940
-
941
- with col_chart1:
942
  if language == "English":
943
- st.subheader("Patient Priority Distribution")
944
  else:
945
- st.subheader("مریضوں کی ترجیحی تقسیم")
946
-
947
- priority_data = pd.DataFrame({
948
- 'Priority': ['Emergency', 'Same Day', 'Routine'],
949
- 'Count': [18, 42, 65],
950
- 'Color': ['#dc3545', '#ffc107', '#28a745']
951
- })
952
-
953
- fig = px.pie(priority_data, values='Count', names='Priority',
954
- color='Priority', color_discrete_map={
955
- 'Emergency': '#dc3545',
956
- 'Same Day': '#ffc107',
957
- 'Routine': '#28a745'
958
- })
959
- fig.update_traces(textposition='inside', textinfo='percent+label')
960
- fig.update_layout(showlegend=False)
961
- st.plotly_chart(fig, use_container_width=True)
962
 
963
- with col_chart2:
964
- if language == "English":
965
- st.subheader("Disease Risk Distribution")
966
- else:
967
- st.subheader("بیماری کے خطرے کی تقسیم")
968
-
969
- disease_data = pd.DataFrame({
970
- 'Risk Level': ['Low', 'Medium', 'High'],
971
- 'Heart Disease': [65, 25, 10],
972
- 'Diabetes': [70, 20, 10],
973
- 'Hypertension': [60, 30, 10]
974
- })
975
-
976
- fig = px.bar(disease_data, x='Risk Level', y=['Heart Disease', 'Diabetes', 'Hypertension'],
977
- title="Risk Level Distribution by Disease",
978
- color_discrete_map={
979
- 'Heart Disease': '#FF6B6B',
980
- 'Diabetes': '#4ECDC4',
981
- 'Hypertension': '#45B7D1'
982
- })
983
- st.plotly_chart(fig, use_container_width=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
984
 
985
  if __name__ == "__main__":
986
  main()
 
8
  import cv2
9
  import easyocr
10
  import os
 
 
11
  import plotly.graph_objects as go
12
  import plotly.express as px
13
  from datetime import datetime
 
15
  import json
16
  import base64
17
  import tempfile
18
+ from groq import Groq
 
 
19
 
20
  # Set page config first
21
  st.set_page_config(
 
100
  st.session_state.risk_scores = {}
101
  if 'chat_history' not in st.session_state:
102
  st.session_state.chat_history = []
103
+ if 'groq_client' not in st.session_state:
104
+ st.session_state.groq_client = None
105
 
106
  # Load trained models
107
  @st.cache_resource(show_spinner=False)
108
  def load_models():
109
  try:
110
+ # Load your trained models
111
+ # Replace these paths with your actual model file paths
112
+ models = {}
113
 
114
+ # Try to load heart disease model
115
+ try:
116
+ heart_model = joblib.load('heart_disease_model.pkl')
117
+ models['heart'] = heart_model
118
+ except:
119
+ st.error("❌ Heart disease model not found. Please ensure 'heart_disease_model.pkl' is in the directory.")
120
+ return None, None, None
 
 
 
 
 
 
 
 
 
 
 
 
121
 
122
+ # Try to load diabetes model
123
+ try:
124
+ diabetes_model = joblib.load('diabetes_model.pkl')
125
+ models['diabetes'] = diabetes_model
126
+ except:
127
+ st.error("❌ Diabetes model not found. Please ensure 'diabetes_model.pkl' is in the directory.")
128
+ return None, None, None
 
129
 
130
+ # Try to load hypertension model
131
+ try:
132
+ hypertension_model = joblib.load('hypertension_model.pkl')
133
+ models['hypertension'] = hypertension_model
134
+ except:
135
+ st.error("❌ Hypertension model not found. Please ensure 'hypertension_model.pkl' is in the directory.")
136
+ return None, None, None
137
 
138
+ return models['heart'], models['diabetes'], models['hypertension']
139
 
140
  except Exception as e:
141
  st.error(f"❌ Error loading models: {str(e)}")
142
  return None, None, None
143
 
144
+ # Initialize Groq client
145
+ def init_groq_client(api_key):
 
146
  try:
147
+ client = Groq(api_key=api_key)
148
+ return client
 
 
 
 
 
 
 
 
 
149
  except Exception as e:
150
+ st.error(f" Error initializing Groq client: {str(e)}")
151
  return None
152
 
153
  # Urdu translations
 
262
  return min(95, accuracy) # Cap at 95% for realistic estimates
263
 
264
  class HealthcareChatbot:
265
+ def __init__(self, groq_client):
266
+ self.client = groq_client
267
+ self.system_prompt = """You are a helpful and professional healthcare assistant designed for Pakistani patients.
268
+ Provide accurate, culturally appropriate medical advice in both English and Urdu.
269
+ Focus on preventive care, symptom explanation, and when to seek medical attention.
270
+ Always emphasize that you are an AI assistant and recommend consulting healthcare professionals for serious conditions."""
 
 
 
 
 
 
 
 
 
 
 
 
 
271
 
272
+ def get_response(self, query, language='English'):
273
+ """Generate healthcare chatbot response using Groq API"""
274
  try:
275
+ if self.client is None:
276
+ return "Chatbot service is currently unavailable. Please check the API configuration."
 
 
 
 
 
 
 
 
 
277
 
278
+ # Enhanced system prompt based on language
279
+ enhanced_system_prompt = self.system_prompt
280
+ if language == 'Urdu':
281
+ enhanced_system_prompt += " Respond in Urdu with proper medical terminology."
282
+ else:
283
+ enhanced_system_prompt += " Respond in English with clear medical advice."
284
+
285
+ # Create conversation context
286
+ messages = [
287
+ {"role": "system", "content": enhanced_system_prompt},
288
+ {"role": "user", "content": f"Patient query: {query}"}
289
+ ]
290
+
291
+ # Generate response using Groq
292
+ chat_completion = self.client.chat.completions.create(
293
+ messages=messages,
294
+ model="llama3-8b-8192", # Using LLaMA 3 8B model
295
+ temperature=0.3,
296
+ max_tokens=512,
297
+ top_p=0.9
298
+ )
299
+
300
+ response = chat_completion.choices[0].message.content
301
+
302
+ # Add disclaimer
303
+ if language == 'Urdu':
304
+ response += "\n\n⚠️ براہ کرم نوٹ کریں: یہ ایک AI اسسٹنٹ ہے۔ سنگین طبی حالات کے لیے ہمیشہ کوالیفائیڈ ڈاکٹر سے مشورہ کریں۔"
305
+ else:
306
+ response += "\n\n⚠️ Please note: This is an AI assistant. Always consult qualified doctors for serious medical conditions."
307
 
308
+ return response
 
 
309
 
310
  except Exception as e:
311
+ error_msg = f"Error generating response: {str(e)}"
312
+ if language == 'Urdu':
313
+ return f"معذرت، میں اس وقت آپ کے سوال کا جواب نہیں دے سکتا۔ براہ کرم بعد میں کوشش کریں۔\n\n{error_msg}"
314
+ else:
315
+ return f"Sorry, I'm unable to respond to your question right now. Please try again later.\n\n{error_msg}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
316
 
317
  def calculate_priority_score(heart_risk, diabetes_risk, hypertension_risk):
318
  """Calculate integrated priority score with clinical weighting"""
 
358
 
359
  return errors
360
 
361
+ def prepare_features_for_models(age, bp_systolic, bp_diastolic, heart_rate, cholesterol, glucose, bmi, symptoms):
362
+ """Prepare feature arrays for different models based on their training requirements"""
363
+
364
+ # Heart Disease Model Features (adjust based on your model's training)
365
  heart_features = np.array([[
366
+ age,
367
  bp_systolic,
368
  cholesterol,
369
  heart_rate,
370
+ symptoms['chest_pain'],
371
+ symptoms['shortness_breath'],
372
+ symptoms['palpitations'],
373
  bmi,
374
+ glucose
 
 
375
  ]])
376
 
377
+ # Diabetes Model Features
378
  diabetes_features = np.array([[
379
  age,
380
  glucose,
381
  bmi,
382
  cholesterol,
383
+ symptoms['fatigue'],
384
+ symptoms['blurred_vision'],
385
+ bp_systolic,
386
+ heart_rate
387
  ]])
388
 
389
+ # Hypertension Model Features
390
  hypertension_features = np.array([[
391
  age,
392
  bp_systolic,
393
  bp_diastolic,
394
  bmi,
395
+ symptoms['dizziness'],
396
+ symptoms['palpitations'],
397
  heart_rate,
398
+ cholesterol
 
399
  ]])
400
 
401
  return heart_features, diabetes_features, hypertension_features
 
411
 
412
  # Initialize processors
413
  ocr_processor = OCRProcessor()
 
414
 
415
  # Language selector in sidebar
416
  with st.sidebar:
417
  st.markdown("<h2 style='text-align: center; color: #2E86AB;'>🏥 AI-Priority OPD</h2>",
418
  unsafe_allow_html=True)
419
 
420
+ # Groq API Configuration
421
+ st.markdown("---")
422
+ st.subheader("API Configuration")
423
+ groq_api_key = st.text_input("Enter Groq API Key:", type="password",
424
+ help="Get your API key from https://console.groq.com")
425
+
426
+ if groq_api_key:
427
+ if st.session_state.groq_client is None:
428
+ st.session_state.groq_client = init_groq_client(groq_api_key)
429
+ if st.session_state.groq_client:
430
+ st.success("✅ Groq API connected successfully!")
431
+ chatbot = HealthcareChatbot(st.session_state.groq_client)
432
+ else:
433
+ st.warning("⚠️ Please enter Groq API key to enable chatbot")
434
+ chatbot = HealthcareChatbot(None)
435
+
436
  language = st.radio(
437
  "Select Language / زبان منتخب کریں",
438
  ["English", "Urdu"],
 
448
  st.session_state.risk_scores = {}
449
  st.session_state.chat_history = []
450
  st.rerun()
 
 
 
 
 
 
 
 
451
  else:
452
  st.subheader("فوری اقدامات")
453
  if st.button("🆕 نیا مریض تشخیص", use_container_width=True):
 
455
  st.session_state.risk_scores = {}
456
  st.session_state.chat_history = []
457
  st.rerun()
 
 
 
 
 
 
 
 
458
 
459
  # Main header
460
  if language == "English":
 
524
  help="سسٹولک بلڈ پریشر mmHg میں")
525
  bp_diastolic = st.number_input("بلڈ پریشر (ڈائیسٹولک)",
526
  min_value=40, max_value=150, value=80,
527
+ help="ڈائیسٹولک بلڈ پریشر mmHg میں")
528
  heart_rate = st.number_input("دل کی دھڑکن (bpm)",
529
  min_value=30, max_value=200, value=72,
530
+ help="دل کی دھڑکن فی منٹ")
531
  cholesterol = st.number_input("کولیسٹرول کی سطح (mg/dL)",
532
  min_value=100, max_value=400, value=180)
533
  glucose = st.number_input("خون میں گلوکوز (mg/dL)",
 
573
  if validation_errors:
574
  for error in validation_errors:
575
  st.error(f"❌ {error}")
576
+ elif heart_model is None or diabetes_model is None or hypertension_model is None:
577
+ st.error("❌ AI models are not loaded properly. Please check model files.")
578
  else:
579
  try:
580
  with st.spinner("🔍 Analyzing patient data and calculating risks..."):
581
  # Prepare symptoms dictionary
582
  symptoms_dict = {
583
+ 'chest_pain': 1 if chest_pain else 0,
584
+ 'shortness_breath': 1 if shortness_breath else 0,
585
+ 'palpitations': 1 if palpitations else 0,
586
+ 'fatigue': 1 if fatigue else 0,
587
+ 'dizziness': 1 if dizziness else 0,
588
+ 'blurred_vision': 1 if blurred_vision else 0
589
  }
590
 
591
+ # Prepare features for each model
592
+ heart_features, diabetes_features, hypertension_features = prepare_features_for_models(
593
  age, bp_systolic, bp_diastolic, heart_rate, cholesterol, glucose, bmi, symptoms_dict
594
  )
595
 
 
598
  diabetes_risk_proba = diabetes_model.predict_proba(diabetes_features)[0][1]
599
  hypertension_risk_proba = hypertension_model.predict_proba(hypertension_features)[0][1]
600
 
601
+ # Apply symptom modifiers for clinical severity
602
  if chest_pain:
603
  heart_risk_proba = min(1.0, heart_risk_proba * 1.3)
604
  if shortness_breath:
605
  heart_risk_proba = min(1.0, heart_risk_proba * 1.2)
 
 
 
 
606
  if fatigue:
607
  diabetes_risk_proba = min(1.0, diabetes_risk_proba * 1.2)
 
 
608
  if dizziness:
609
  hypertension_risk_proba = min(1.0, hypertension_risk_proba * 1.3)
610
 
 
 
 
 
611
  # Calculate integrated priority score
612
  priority_score = calculate_priority_score(
613
  heart_risk_proba, diabetes_risk_proba, hypertension_risk_proba
 
704
 
705
  except Exception as e:
706
  st.error(f"❌ Error in risk assessment: {str(e)}")
707
+ st.info("💡 Please ensure all model files are properly formatted and compatible.")
708
 
709
  with tab2:
710
  # Prescription OCR
 
779
  # Healthcare Chatbot
780
  if language == "English":
781
  st.header("💬 Healthcare Assistant Chatbot")
782
+ st.write("Ask health-related questions and get personalized advice in English or Urdu")
783
  else:
784
  st.header("💬 ہیلتھ کیئر اسسٹنٹ چیٹ بوٹ")
785
+ st.write("صحت سے متعلق سوالات پوچھیں اور انگریزی یا اردو میں ذاتی مشورہ حاصل کریں")
786
 
787
+ if st.session_state.groq_client is None:
788
+ st.warning("⚠️ Please configure Groq API key in the sidebar to use the chatbot")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
789
  else:
790
+ # Display chat history
791
+ for message in st.session_state.chat_history:
792
+ with st.chat_message(message["role"]):
793
+ if message["role"] == "user":
794
+ st.markdown(message["content"])
795
+ else:
796
+ # Format bot response with better styling
797
+ st.markdown(f"**🤖 Healthcare Assistant:**\n\n{message['content']}")
798
+
799
+ # Chat input
800
+ if prompt := st.chat_input(
801
+ "Type your health question here..." if language == "English"
802
+ else "اپنا صحت کا سوال یہاں ٹائپ کریں..."
803
+ ):
804
+ # Add user message to chat history
805
+ st.session_state.chat_history.append({"role": "user", "content": prompt})
806
+
807
+ # Generate bot response
808
+ with st.chat_message("assistant"):
809
+ with st.spinner("💭 Analyzing your question..." if language == "English" else "💭 آپ کا سوال تجزیہ ہو رہا ہے..."):
810
+ response = chatbot.get_response(prompt, language)
811
+ st.markdown(f"**🤖 Healthcare Assistant:**\n\n{response}")
812
+
813
+ # Add assistant response to chat history
814
+ st.session_state.chat_history.append({"role": "assistant", "content": response})
815
+
816
+ # Limit chat history to last 10 messages
817
+ if len(st.session_state.chat_history) > 10:
818
+ st.session_state.chat_history = st.session_state.chat_history[-10:]
819
+
820
+ # Quick action buttons
821
+ if language == "English":
822
+ st.subheader("Quick Health Topics")
823
+ else:
824
+ st.subheader("فوری صحت کے موضوعات")
825
+
826
+ col_qa1, col_qa2, col_qa3 = st.columns(3)
827
+
828
+ with col_qa1:
829
+ if st.button("❤️ Heart Health", use_container_width=True):
830
+ st.session_state.chat_history.append({
831
+ "role": "user",
832
+ "content": "Tell me about heart health and prevention tips"
833
+ })
834
+ st.rerun()
835
+
836
+ with col_qa2:
837
+ if st.button("🩺 Diabetes", use_container_width=True):
838
+ st.session_state.chat_history.append({
839
+ "role": "user",
840
+ "content": "What are the symptoms and management of diabetes?"
841
+ })
842
+ st.rerun()
843
+
844
+ with col_qa3:
845
+ if st.button("💓 Blood Pressure", use_container_width=True):
846
+ st.session_state.chat_history.append({
847
+ "role": "user",
848
+ "content": "How to control high blood pressure naturally?"
849
+ })
850
+ st.rerun()
851
 
852
  with tab4:
853
  # Analytics Dashboard
854
  if language == "English":
855
+ st.header("📈 System Analytics & Performance")
856
  else:
857
+ st.header("📈 سسٹم تجزیات اور کارکردگی")
858
+
859
+ # Real-time performance metrics based on actual usage
860
+ if 'risk_scores' in st.session_state and st.session_state.risk_scores:
861
+ recent_priority = st.session_state.risk_scores.get('priority', 0)
862
+ col9, col10, col11, col12 = st.columns(4)
863
+
864
+ with col9:
865
+ st.metric("Current Patient Priority", f"{recent_priority:.1%}")
866
+ with col10:
867
+ st.metric("Risk Assessment", "Completed")
868
+ with col11:
869
+ st.metric("Model Confidence", "High")
870
+ with col12:
871
+ st.metric("Processing Time", "< 2s")
872
  else:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
873
  if language == "English":
874
+ st.info("👆 Complete a patient assessment to see analytics")
875
  else:
876
+ st.info("👆 تجزیات دیکھنے کے لیے مریض کی تشخیص مکمل کریں")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
877
 
878
+ # Analytics Charts
879
+ if 'risk_scores' in st.session_state and st.session_state.risk_scores:
880
+ col_chart1, col_chart2 = st.columns(2)
881
+
882
+ with col_chart1:
883
+ if language == "English":
884
+ st.subheader("Current Patient Risk Distribution")
885
+ else:
886
+ st.subheader("موجودہ مریض کے خطرے کی تقسیم")
887
+
888
+ risk_data = pd.DataFrame({
889
+ 'Condition': ['Heart Disease', 'Diabetes', 'Hypertension'],
890
+ 'Risk Score': [
891
+ st.session_state.risk_scores['heart'],
892
+ st.session_state.risk_scores['diabetes'],
893
+ st.session_state.risk_scores['hypertension']
894
+ ]
895
+ })
896
+
897
+ fig = px.bar(risk_data, x='Condition', y='Risk Score',
898
+ color='Risk Score', color_continuous_scale='RdYlGn_r')
899
+ st.plotly_chart(fig, use_container_width=True)
900
+
901
+ with col_chart2:
902
+ if language == "English":
903
+ st.subheader("Priority Level")
904
+ else:
905
+ st.subheader("ترجیحی سطح")
906
+
907
+ priority_level = st.session_state.risk_scores['level']
908
+ priority_colors = {
909
+ 'EMERGENCY_CARE': '#dc3545',
910
+ 'SAME_DAY_CONSULT': '#ffc107',
911
+ 'ROUTINE_APPOINTMENT': '#28a745'
912
+ }
913
+
914
+ fig = go.Figure(go.Indicator(
915
+ mode = "gauge+number",
916
+ value = st.session_state.risk_scores['priority'] * 100,
917
+ domain = {'x': [0, 1], 'y': [0, 1]},
918
+ title = {'text': "Priority Score"},
919
+ gauge = {
920
+ 'axis': {'range': [0, 100]},
921
+ 'bar': {'color': priority_colors.get(priority_level, '#2E86AB')},
922
+ 'steps': [
923
+ {'range': [0, 55], 'color': "lightgray"},
924
+ {'range': [55, 75], 'color': "yellow"},
925
+ {'range': [75, 100], 'color': "red"}
926
+ ]
927
+ }
928
+ ))
929
+ fig.update_layout(height=300)
930
+ st.plotly_chart(fig, use_container_width=True)
931
 
932
  if __name__ == "__main__":
933
  main()