PearlIsa commited on
Commit
9454822
1 Parent(s): 2392b19

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1003 -54
app.py CHANGED
@@ -1,64 +1,1013 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
 
 
 
 
 
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import keras
4
+ from datasets import load_dataset
5
+ import tensorflow as tf
6
+ from huggingface_hub import login
7
+ import torch
8
+ from transformers import ( AutoTokenizer, AutoModelForCausalLM)
9
+ from sentence_transformers import SentenceTransformer
10
+ from typing import List, Dict, Union, Tuple
11
+ import faiss
12
+ import numpy as np
13
+ from datasets import Dataset
14
+ import torch.nn.functional as F
15
+ from torch.cuda.amp import autocast
16
+ import gc
17
+ from peft import ( LoraConfig, get_peft_model, prepare_model_for_kbit_training, TaskType, PeftModel)
18
+ from tqdm.auto import tqdm
19
+ from torch.utils.data import DataLoader
20
+ import logging
21
+ import wandb
22
+ from pathlib import Path
23
+ from typing import List, Dict, Union, Optional, Any
24
+ import torch.nn as nn
25
+ from dataclasses import dataclass, field
26
+ import time
27
+ import asyncio
28
+ import pytest
29
+ from unittest.mock import Mock, patch
30
+ from sklearn.metrics import classification_report, confusion_matrix
31
  import gradio as gr
32
+ import matplotlib.pyplot as plt
33
+ from datetime import datetime
34
+ import requests
35
+ import pandas as pd
36
+ import seaborn as sns
37
+ import traceback
38
+ from matplotlib.gridspec import GridSpec
39
 
40
+ from google.colab import userdata
41
+
42
+ # Retrieve secrets securely from environment variables
43
+ kaggle_username = os.getenv("KAGGLE_USERNAME")
44
+ kaggle_key = os.getenv("KAGGLE_KEY")
45
+ hf_token = os.getenv("HF_TOKEN")
46
+ wandb_key = os.getenv("WANDB_API_KEY")
47
+
48
+ # Log in to Hugging Face
49
+ login(token=hf_token)
50
+
51
+ # Set up WandB if needed
52
+ wandb.login(key=wandb_key)
53
+
54
+ # Setup logging
55
+ logging.basicConfig(
56
+ level=logging.INFO,
57
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
58
+ )
59
+ logger = logging.getLogger(__name__)
60
+
61
+ @dataclass
62
+ class MedicalConfig:
63
+ """Enhanced configuration for medical chatbot"""
64
+ # LoRA parameters
65
+ LORA_WEIGHTS_PATH: str = "medical_lora_weights"
66
+ LORA_R: int = 16
67
+ LORA_ALPHA: int = 32
68
+ LORA_DROPOUT: float = 0.1
69
+ LORA_TARGET_MODULES: List[str] = field(default_factory=lambda: ["q_proj", "v_proj", "k_proj", "o_proj"])
70
+
71
+ # Training parameters
72
+ TRAINING_BATCH_SIZE: int = 4
73
+ LEARNING_RATE: float = 2e-5
74
+ NUM_EPOCHS: int = 3
75
+ MAX_LENGTH: int = 2048
76
+ INDEX_BATCH_SIZE: int = 32
77
+
78
+ # Medical specific parameters
79
+ EMERGENCY_KEYWORDS: List[str] = field(default_factory=lambda: [
80
+ 'chest pain', 'breathing difficulty', 'stroke', 'heart attack', 'unconscious',
81
+ 'severe bleeding', 'seizure', 'anaphylaxis', 'severe burn', 'choking',
82
+ 'severe head injury', 'spinal injury', 'drowning', 'electric shock',
83
+ 'severe allergic reaction', 'poisoning', 'overdose', 'self-harm',
84
+ 'suicidal thoughts', 'severe trauma'
85
+ ])
86
+
87
+ URGENT_KEYWORDS: List[str] = field(default_factory=lambda: [
88
+ 'infection', 'high fever', 'severe pain', 'vomiting', 'dehydration',
89
+ 'anxiety attack', 'panic attack', 'mental health crisis', 'broken bone',
90
+ 'deep cut', 'asthma attack', 'migraine', 'severe rash', 'eye injury',
91
+ 'dental emergency', 'pregnancy complications', 'severe back pain',
92
+ 'severe abdominal pain', 'concussion', 'severe allergies'
93
+ ])
94
+
95
+ # UK Healthcare specific
96
+ EMERGENCY_NUMBERS: List[str] = field(default_factory=lambda: ["999", "112", "111"])
97
+ GP_SERVICES: Dict[str, Dict[str, str]] = field(default_factory=lambda: {
98
+ "EMERGENCY": {
99
+ "name": "A&E",
100
+ "wait_time": "4 hours target",
101
+ "when_to_use": "Life-threatening emergencies"
102
+ },
103
+ "URGENT": {
104
+ "name": "Urgent Care Center",
105
+ "wait_time": "2-4 hours typically",
106
+ "when_to_use": "Urgent but not life-threatening conditions"
107
+ },
108
+ "NON_URGENT": {
109
+ "name": "GP Practice",
110
+ "wait_time": "Same day to 2 weeks",
111
+ "when_to_use": "Routine medical care"
112
+ }
113
+ })
114
+
115
+ # Cultural considerations
116
+ CULTURAL_CONTEXTS: List[Dict[str, str]] = field(default_factory=lambda: [
117
+ {
118
+ "group": "South Asian",
119
+ "considerations": [
120
+ "Different presentation of skin conditions",
121
+ "Higher diabetes risk",
122
+ "Cultural dietary practices",
123
+ "Language preferences"
124
+ ]
125
+ },
126
+ {
127
+ "group": "African/Caribbean",
128
+ "considerations": [
129
+ "Different presentation of skin conditions",
130
+ "Higher hypertension risk",
131
+ "Specific hair/scalp conditions",
132
+ "Cultural health beliefs"
133
+ ]
134
+ },
135
+ {
136
+ "group": "Middle Eastern",
137
+ "considerations": [
138
+ "Cultural modesty requirements",
139
+ "Ramadan considerations",
140
+ "Gender preferences for healthcare providers",
141
+ "Traditional medicine practices"
142
+ ]
143
+ }
144
+ ])
145
+ class GPUOptimizedRAG:
146
+ def __init__(
147
+ self,
148
+ model_path: str = "google/gemma-7b",
149
+ embedding_model: str = "sentence-transformers/all-MiniLM-L6-v2",
150
+ config: MedicalConfig = MedicalConfig(),
151
+ use_cpu_fallback: bool = False
152
  ):
 
153
 
154
+ self.conversation_memory = {
155
+ 'name': 'Pearly',
156
+ 'role': 'GP Medical Assistant',
157
+ 'style': 'professional, empathetic, and clear',
158
+ 'system_prompt': None,
159
+ 'past_interactions': []
160
+ }
161
+ """Initialize RAG with enhanced configuration, LoRA support, and memory optimization"""
162
+ self.config = config
163
+ self.use_cpu_fallback = use_cpu_fallback
164
 
165
+ # Determine device with memory check
166
+ if torch.cuda.is_available() and not use_cpu_fallback:
167
+ try:
168
+ # Check available GPU memory
169
+ gpu_memory = torch.cuda.get_device_properties(0).total_memory
170
+ if gpu_memory < 8e9: # Less than 8GB
171
+ logger.warning("Limited GPU memory, falling back to CPU")
172
+ self.device = torch.device("cpu")
173
+ else:
174
+ self.device = torch.device("cuda")
175
+ except Exception as e:
176
+ logger.warning(f"GPU initialization error: {e}, falling back to CPU")
177
+ self.device = torch.device("cpu")
178
+ else:
179
+ self.device = torch.device("cpu")
180
 
181
+ # Add conversation memory for consistent persona
182
+ self.conversation_memory = {
183
+ 'name': 'Pearly',
184
+ 'role': 'GP Medical Assistant',
185
+ 'style': 'professional, empathetic, and clear',
186
+ 'past_interactions': []
187
+ }
188
+
189
+ # Add clinical quality metrics
190
+ self.clinical_metrics = {
191
+ 'terminology_accuracy': 0.0,
192
+ 'assessment_accuracy': 0.0,
193
+ 'guideline_adherence': 0.0,
194
+ 'symptom_recognition': 0.0
195
+ }
196
+
197
+ # Initialize models with memory optimization
198
+ try:
199
+ self.tokenizer = AutoTokenizer.from_pretrained(model_path)
200
+ self.model = AutoModelForCausalLM.from_pretrained(
201
+ model_path,
202
+ torch_dtype=torch.float16 if self.device.type == "cuda" else torch.float32,
203
+ device_map="auto" if self.device.type == "cuda" else None,
204
+ low_cpu_mem_usage=True
205
+ )
206
+
207
+ # Apply LoRA configuration
208
+ self.setup_lora()
209
+
210
+ # Initialize embedding model with memory considerations
211
+ self.embedding_model = SentenceTransformer(embedding_model)
212
+ if self.device.type == "cuda":
213
+ self.embedding_model = self.embedding_model.half().to(self.device)
214
+ else:
215
+ self.embedding_model = self.embedding_model.to(self.device)
216
+
217
+ # Setup FAISS index with CPU fallback
218
+ self.embedding_dim = self.embedding_model.get_sentence_embedding_dimension()
219
+ if self.device.type == "cuda" and not use_cpu_fallback:
220
+ try:
221
+ self.index = faiss.IndexFlatIP(self.embedding_dim)
222
+ res = faiss.StandardGpuResources()
223
+ # Limit temp memory for GPU index
224
+ res.setTempMemory(64 * 1024 * 1024) # 64MB temp memory
225
+ self.index = faiss.index_cpu_to_gpu(res, 0, self.index)
226
+ except Exception as e:
227
+ logger.warning(f"GPU FAISS initialization failed: {e}, using CPU index")
228
+ self.index = faiss.IndexFlatIP(self.embedding_dim)
229
+ else:
230
+ self.index = faiss.IndexFlatIP(self.embedding_dim)
231
+
232
+ logger.info(f"RAG system initialized successfully on {self.device}")
233
+
234
+ except Exception as e:
235
+ logger.error(f"Error initializing RAG system: {e}")
236
+ raise
237
+
238
+ def setup_lora(self):
239
+ """Configure and apply LoRA to the model with memory optimization"""
240
+ try:
241
+ lora_config = LoraConfig(
242
+ r=self.config.LORA_R,
243
+ lora_alpha=self.config.LORA_ALPHA,
244
+ target_modules=self.config.LORA_TARGET_MODULES,
245
+ lora_dropout=self.config.LORA_DROPOUT,
246
+ bias="none",
247
+ task_type=TaskType.CAUSAL_LM
248
+ )
249
+
250
+ self.model = get_peft_model(self.model, lora_config)
251
+ logger.info("LoRA configuration applied successfully")
252
+
253
+ except Exception as e:
254
+ logger.error(f"Error setting up LoRA: {e}")
255
+ raise
256
+
257
+ def evaluate_clinical_quality(self, response: str, expected_elements: List[str]) -> Dict[str, float]:
258
+ """Add clinical quality evaluation matching test requirements"""
259
+ quality_metrics = {
260
+ 'terminology_accuracy': self._evaluate_terminology(response, expected_elements),
261
+ 'assessment_accuracy': self._evaluate_assessment(response),
262
+ 'guideline_adherence': self._evaluate_guidelines(response),
263
+ 'symptom_recognition': self._evaluate_symptoms(response, expected_elements)
264
+ }
265
+ return quality_metrics
266
+
267
+ def prepare_documents(self, documents: List[Dict]):
268
+ """Enhanced document preparation with improved batching and memory management"""
269
+ self.documents = documents
270
+ embeddings = []
271
+
272
+ try:
273
+ for i in tqdm(range(0, len(documents), self.config.INDEX_BATCH_SIZE),
274
+ desc="Processing documents"):
275
+ batch = documents[i:i + self.config.INDEX_BATCH_SIZE]
276
+ texts = [doc['text'] for doc in batch]
277
+
278
+ with torch.amp.autocast(device_type='cuda'):
279
+ batch_embeddings = self.embedding_model.encode(
280
+ texts,
281
+ convert_to_tensor=True,
282
+ show_progress_bar=False,
283
+ batch_size=8
284
+ )
285
+
286
+ embeddings.append(batch_embeddings.cpu().numpy())
287
+
288
+ all_embeddings = np.vstack(embeddings)
289
+ self.index.add(all_embeddings)
290
+ logger.info(f"Indexed {len(documents)} documents successfully")
291
+
292
+ except Exception as e:
293
+ logger.error(f"Error preparing documents: {e}")
294
+ raise
295
+
296
+ def assess_urgency(self, symptoms: str) -> Dict[str, Any]:
297
+ """Enhanced symptom assessment with detailed analysis"""
298
+ symptoms_lower = symptoms.lower()
299
+
300
+ # Initialize response
301
+ assessment = {
302
+ 'level': 'NON-URGENT',
303
+ 'reasons': [],
304
+ 'recommendations': [],
305
+ 'follow_up_needed': False
306
+ }
307
+
308
+ # Check emergency keywords
309
+ emergency_matches = [kw for kw in self.config.EMERGENCY_KEYWORDS
310
+ if kw in symptoms_lower]
311
+ if emergency_matches:
312
+ assessment.update({
313
+ 'level': 'EMERGENCY',
314
+ 'reasons': emergency_matches,
315
+ 'recommendations': [
316
+ 'Call 999 immediately',
317
+ 'Do not move if spinal injury suspected',
318
+ 'Stay on the line for guidance'
319
+ ],
320
+ 'follow_up_needed': True
321
+ })
322
+ return assessment
323
+
324
+ # Check urgent keywords
325
+ urgent_matches = [kw for kw in self.config.URGENT_KEYWORDS
326
+ if kw in symptoms_lower]
327
+ if urgent_matches:
328
+ assessment.update({
329
+ 'level': 'URGENT',
330
+ 'reasons': urgent_matches,
331
+ 'recommendations': [
332
+ 'Visit urgent care center',
333
+ 'Book emergency GP appointment',
334
+ 'Monitor symptoms closely'
335
+ ],
336
+ 'follow_up_needed': True
337
+ })
338
+ return assessment
339
+
340
+ # Non-urgent default
341
+ assessment.update({
342
+ 'recommendations': [
343
+ 'Book routine GP appointment',
344
+ 'Monitor symptoms',
345
+ 'Try self-care measures'
346
+ ],
347
+ 'follow_up_needed': False
348
+ })
349
+ return assessment
350
+
351
+ def generate_cultural_considerations(self, symptoms: str) -> List[str]:
352
+ """Generate culturally-aware medical considerations"""
353
+ considerations = []
354
+ symptoms_lower = symptoms.lower()
355
+
356
+ for context in self.config.CULTURAL_CONTEXTS:
357
+ relevant_considerations = [
358
+ cons for cons in context['considerations']
359
+ if any(keyword in symptoms_lower for keyword in cons.lower().split())
360
+ ]
361
+
362
+ if relevant_considerations:
363
+ considerations.extend([
364
+ f"{context['group']}: {consideration}"
365
+ for consideration in relevant_considerations
366
+ ])
367
+
368
+ return considerations if considerations else ["No specific cultural considerations identified"]
369
+
370
+ def get_booking_template(self, urgency_level: str) -> str:
371
+ """Get appropriate booking template based on urgency level"""
372
+ service_info = self.config.GP_SERVICES[urgency_level]
373
+
374
+ templates = {
375
+ "EMERGENCY": f"""
376
+ 🚨 EMERGENCY SERVICES REQUIRED 🚨
377
+
378
+ Service: {service_info['name']}
379
+ Target Wait Time: {service_info['wait_time']}
380
+ When to Use: {service_info['when_to_use']}
381
+
382
+ IMMEDIATE ACTIONS:
383
+ 1. 🚑 Call 999 (or 112)
384
+ 2. 🏥 Nearest A&E: [Location Placeholder]
385
+ 3. 🚨 Stay on line for guidance
386
+
387
+ Type '999' to initiate emergency call
388
+ """,
389
+ "URGENT": f"""
390
+ ⚡ URGENT CARE NEEDED ⚡
391
+
392
+ Service: {service_info['name']}
393
+ Expected Wait: {service_info['wait_time']}
394
+ When to Use: {service_info['when_to_use']}
395
+
396
+ OPTIONS:
397
+ 1. 🏥 Find nearest urgent care
398
+ 2. 📅 Book urgent GP slot
399
+ 3. 🔍 Locate walk-in clinic
400
+
401
+ Reply with option number (1-3)
402
+ """,
403
+ "NON_URGENT": f"""
404
+ 📋 ROUTINE CARE BOOKING 📋
405
+
406
+ Service: {service_info['name']}
407
+ Typical Wait: {service_info['wait_time']}
408
+ When to Use: {service_info['when_to_use']}
409
+
410
+ OPTIONS:
411
+ 1. 📅 Schedule GP visit
412
+ 2. 👨‍⚕️ Find local GP
413
+ 3. ℹ️ Self-care advice
414
+
415
+ Reply with option number (1-3)
416
  """
417
+ }
418
+
419
+ return templates.get(urgency_level, templates["NON_URGENT"])
420
+
421
+ def generate_response(self, query: str, chat_history: List[tuple] = None) -> Dict[str, Any]:
422
+ """Generate response with enhanced conversational context"""
423
+ try:
424
+ # Placeholder for response generation logic
425
+ urgency_assessment = {'level': 'NORMAL'} # Placeholder urgency assessment
426
+ response_text = "This is a placeholder response."
427
+
428
+ # Example cultural considerations
429
+ cultural_considerations = ["Consider patient background"]
430
+
431
+ return {
432
+ 'response': response_text,
433
+ 'urgency_assessment': urgency_assessment,
434
+ 'cultural_considerations': cultural_considerations
435
+ }
436
+ except Exception as e:
437
+ logger.error(f"Error generating response: {e}")
438
+ return {
439
+ 'response': "I apologize, but I encountered an error. If this is an emergency, please call 999 immediately.",
440
+ 'urgency_assessment': {'level': 'UNKNOWN'},
441
+ 'cultural_considerations': []
442
+ }
443
+
444
+ def prepare_documents(self, documents):
445
+ """Prepare and index documents for RAG system"""
446
+ pass # Placeholder for document preparation logic
447
+
448
+ def retrieve(self, query: str, k: int = 5) -> List[Dict]:
449
+ """Retrieve relevant documents"""
450
+ try:
451
+ return [] # Placeholder for document retrieval
452
+ except Exception as e:
453
+ logger.error(f"Error in retrieval: {e}")
454
+ return []
455
+
456
+ def generate_report(self, results: Dict) -> Dict:
457
+ """Generate a simple summary report of the test results."""
458
+ total_cases = sum(cat['total'] for cat in results.values())
459
+ total_correct = sum(cat['correct'] for cat in results.values())
460
+
461
+ return {
462
+ 'timestamp': datetime.now().isoformat(),
463
+ 'triage_performance': {
464
+ 'emergency_accuracy': results['emergency']['correct'] / results['emergency']['total'],
465
+ 'urgent_accuracy': results['urgent']['correct'] / results['urgent']['total'],
466
+ 'non_urgent_accuracy': results['non_urgent']['correct'] / results['non_urgent']['total'],
467
+ 'overall_accuracy': total_correct / total_cases
468
+ }
469
+ }
470
+
471
+ def enhance_response_generation(self):
472
+ """Add test-aligned response enhancement"""
473
+ self.response_enhancers = {
474
+ 'demographic_sensitivity': self._enhance_demographic_sensitivity,
475
+ 'cultural_competency': self._enhance_cultural_competency,
476
+ 'clinical_quality': self._enhance_clinical_quality,
477
+ 'follow_up_generation': self._enhance_follow_up
478
+ }
479
+
480
+ def _enhance_demographic_sensitivity(self, response: str, demographic: str) -> str:
481
+ """Add demographic-specific enhancements matching test requirements"""
482
+ demographic_patterns = {
483
+ 'pediatric': ['age-appropriate', 'child-friendly', 'developmental'],
484
+ 'elderly': ['mobility', 'cognitive', 'fall risk'],
485
+ 'pregnant': ['trimester', 'fetal', 'pregnancy-safe'],
486
+ 'chronic_condition': ['management', 'monitoring', 'ongoing care']
487
+ }
488
+ return response # Placeholder implementation
489
+
490
+ def process_appointment_booking(message, patient_info):
491
+ """Process appointment booking queries"""
492
+ return "I can help you book an appointment. Please provide further details."
493
+
494
+ def create_gradio_interface(rag_system: GPUOptimizedRAG):
495
+ """Create enhanced Gradio interface with appointment booking capabilities"""
496
+ SYSTEM_MESSAGE = "You are Pearly, a friendly medical triaging Chatbot."
497
+
498
+ def process_chat_response(response_data: Dict[str, Any], message: str, history: List[tuple]) -> str:
499
+ """Format chat response based on context, handle appointments, and maintain persona"""
500
+ try:
501
+ if not history or message.lower().startswith(("hi", "hello", "hey", "good")):
502
+ return "Hi! I'm Pearly, your medical triaging assistant. I'm here to help assess your symptoms and provide guidance. How may I assist you today?"
503
+
504
+ urgency_level = response_data['urgency_assessment']['level']
505
+ response_text = response_data['response']
506
+
507
+ if urgency_level == "EMERGENCY":
508
+ return f"🚨 EMERGENCY ALERT 🚨\n\n{response_text}\n\nWould you like me to help connect you to emergency services?"
509
+ elif urgency_level == "URGENT":
510
+ return f"⚠️ URGENT CARE NEEDED ⚠️\n\n{response_text}\n\nWould you like help finding your nearest urgent care center?"
511
+ else:
512
+ return f"{response_text}\n\nWould you like help booking a GP appointment or finding more NHS resources?"
513
+ except Exception as e:
514
+ logger.error(f"Error processing chat response: {e}")
515
+ return (
516
+ "I'm Pearly, and I apologize for the technical difficulty. For your safety:\n\n"
517
+ "- Call 999 for emergencies\n"
518
+ "- Call 111 for urgent medical advice\n"
519
+ "- Visit NHS 111 online for non-urgent concerns\n\n"
520
+ "Would you like to try asking your question again?"
521
+ )
522
+
523
+ def chat(message: str, history: List[tuple]) -> tuple[str, List[tuple]]:
524
+ """Enhanced chat function with better error handling and context awareness"""
525
+ try:
526
+ response_data = rag_system.generate_response(message, history)
527
+ response = process_chat_response(response_data, message, history)
528
+ history.append((message, response))
529
+ return history
530
+ except Exception as e:
531
+ logger.error(f"Error in chat: {e}")
532
+ emergency_response = (
533
+ "I apologize for the technical difficulty. For your safety:\n\n"
534
+ "- Call 999 for emergencies\n"
535
+ "- Call 111 for urgent medical advice\n"
536
+ "- Visit NHS 111 online for non-urgent concerns\n\n"
537
+ "Would you like to try asking your question again?"
538
+ )
539
+ history.append((message, emergency_response))
540
+ return history
541
+
542
+ # Define interface for the chatbot
543
+ with gr.Blocks() as interface:
544
+ gr.HTML("<h1>Pearly Medical Assistant</h1><p>Hi! I'm Pearly, your GP medical assistant.</p>")
545
+ chatbot = gr.Chatbot(value=[(None, "Hi! I'm Pearly, your GP medical assistant. How can I help you today?")])
546
+ msg = gr.Textbox(label="Your Message")
547
+ submit = gr.Button("Send")
548
+
549
+ submit.click(chat, inputs=[msg, chatbot], outputs=chatbot)
550
 
551
+ return interface
552
+
553
+ def prepare_medical_documents():
554
+ """Prepare medical knowledge base documents with enhanced conversation flow"""
555
+ try:
556
+ logger.info("Loading medical and persona datasets...")
557
+ datasets = {
558
+ "persona": load_dataset("AlekseyKorshuk/persona-chat", split="train[:500]"),
559
+ "medqa": load_dataset("medalpaca/medical_meadow_medqa", split="train[:500]"),
560
+ "meddia": load_dataset("wasiqnauman/medical-diagnosis-synthetic", split="train[:500]")
561
+ }
562
+
563
+ documents = []
564
+
565
+ # Process Persona dataset for enhanced conversational style
566
+ logger.info("Processing persona dataset...")
567
+ for item in datasets["persona"]:
568
+ if isinstance(item.get('personality'), list):
569
+ personality = " ".join(item['personality'])
570
+ documents.append({
571
+ 'text': f"""
572
+ Conversation Style Guide:
573
+ Personality: {personality}
574
+ Role: Pearly - Medical Assistant
575
+ Core Traits: Professional, empathetic, clear
576
+ Key Behaviors:
577
+ - Always introduce as Pearly
578
+ - Show empathy for symptoms
579
+ - Ask relevant follow-up questions
580
+ - Offer practical assistance
581
+ - Maintain professional tone while being approachable
582
+ """,
583
+ 'type': 'persona'
584
+ })
585
+
586
+ # Process conversation examples with enhanced structure
587
+ if isinstance(item.get('utterances'), list):
588
+ for utterance in item['utterances']:
589
+ if isinstance(utterance, dict) and 'history' in utterance:
590
+ conversation = ' '.join(utterance['history'])
591
+ documents.append({
592
+ 'text': f"""
593
+ Medical Consultation Pattern:
594
+ Conversation: {conversation}
595
+ Key Elements:
596
+ - Show understanding of symptoms
597
+ - Ask clarifying questions
598
+ - Provide clear guidance
599
+ - Offer next steps
600
+ - Check if assistance needed
601
+ """,
602
+ 'type': 'conversation_pattern'
603
+ })
604
+
605
+ # Process MedQA dataset with enhanced medical context
606
+ logger.info("Processing medical QA dataset...")
607
+ for item in datasets["medqa"]:
608
+ if 'input' in item and 'output' in item:
609
+ input_text = item['input']
610
+ if input_text.startswith('Q:'):
611
+ input_text = input_text[2:]
612
+
613
+ documents.append({
614
+ 'text': f"""
615
+ Medical Knowledge Base:
616
+ Question: {input_text}
617
+ Answer: {item['output']}
618
+ Application:
619
+ - Use information to inform recommendations
620
+ - Adapt to patient's situation
621
+ - Maintain clinical accuracy
622
+ - Explain in clear terms
623
+ """,
624
+ 'type': 'medical_qa'
625
+ })
626
+
627
+ # Process diagnosis dataset with structured guidance
628
+ logger.info("Processing diagnosis dataset...")
629
+ for item in datasets["meddia"]:
630
+ if 'input' in item and 'output' in item:
631
+ documents.append({
632
+ 'text': f"""
633
+ Clinical Assessment Framework:
634
+ Symptoms: {item['input']}
635
+ Assessment and Plan: {item['output']}
636
+ Response Structure:
637
+ 1. Acknowledge symptoms
638
+ 2. Ask about severity and duration
639
+ 3. Inquire about related symptoms
640
+ 4. Provide clear recommendations
641
+ 5. Offer assistance with next steps
642
+ """,
643
+ 'type': 'diagnosis_guidance'
644
+ })
645
+
646
+ # Add enhanced conversation templates
647
+ conversation_templates = [
648
+ {
649
+ 'text': """
650
+ Consultation Framework:
651
+ 1. Initial Response:
652
+ - Acknowledge the concern
653
+ - Show empathy
654
+ - Ask about duration/severity
655
+
656
+ 2. Follow-up Questions:
657
+ - Ask specific, relevant questions
658
+ - Clarify symptoms
659
+ - Check for related issues
660
+
661
+ 3. Assessment:
662
+ - Summarize findings
663
+ - Explain reasoning
664
+ - State level of concern
665
+
666
+ 4. Recommendations:
667
+ - Provide clear guidance
668
+ - List specific actions
669
+ - Offer assistance
670
+
671
+ 5. Next Steps:
672
+ - Suggest appropriate care level
673
+ - Offer to help with appointments
674
+ - Provide relevant resources
675
+
676
+ 6. Safety Checks:
677
+ - Verify understanding
678
+ - Confirm action plan
679
+ - Ensure patient comfort
680
+
681
+ Response Patterns:
682
+ Emergency:
683
+ "I understand you're experiencing [symptom]. This requires immediate attention..."
684
+
685
+ Urgent:
686
+ "I'm concerned about [symptom]. To better assess the urgency..."
687
+
688
+ Non-urgent:
689
+ "I hear you about [symptom]. Let's understand this better..."
690
+
691
+ Follow-ups:
692
+ "Would you like help with [specific assistance]?"
693
+ "Shall I help you [book/find/connect]?"
694
+
695
+ Guidance Structure:
696
+ 1. Acknowledge
697
+ 2. Assess
698
+ 3. Advise
699
+ 4. Assist
700
+ 5. Arrange follow-up
701
+ """,
702
+ 'type': 'conversation_framework'
703
+ }
704
+ ]
705
+ documents.extend(conversation_templates)
706
+
707
+ # Add your existing GP templates
708
+ # Define GP templates inside the function
709
+ GP_templates = [
710
+ {
711
+ 'text': """
712
+ Role: GP Medical Assistant
713
+ Context: Emergency situation - Chest Pain
714
+ Style: Calm, clear, and authoritative
715
+ Conversation Pattern:
716
+
717
+ Patient Input: Chest pain symptoms
718
+ Response Framework:
719
+ 1. Initial acknowledgment
720
+ 2. Immediate triage questions:
721
+ - Duration of pain
722
+ - Pain characteristics
723
+ - Associated symptoms
724
+ 3. Emergency guidance
725
+ 4. Clear action steps
726
+
727
+ Example Flow:
728
+ Patient: I'm having chest pain
729
+ Pearly: I understand you're experiencing chest pain. This requires immediate attention. How long have you been experiencing this pain?
730
+
731
+ Patient: About 30 minutes now
732
+ Pearly: Thank you for letting me know. Is the pain sharp or dull, and where exactly is it located? Also, are you experiencing any other symptoms like shortness of breath or sweating?
733
+
734
+ Patient: It's sharp and in the center of my chest. Yes, I'm sweating a lot
735
+ Pearly: Given your symptoms, this could be a serious cardiac event requiring immediate emergency care.
736
+
737
+ IMMEDIATE ACTIONS:
738
+ 1. Call 999 immediately - I can help you do this
739
+ 2. Sit down and try to stay calm
740
+ 3. If available and you're not allergic, take one adult aspirin (300mg)
741
+ 4. Loosen any tight clothing
742
+ 5. Keep the line open - I'll stay with you until help arrives
743
+
744
+ Would you like me to connect you to emergency services now?
745
+ """,
746
+ 'type': 'GP_template'
747
+ },
748
+ {
749
+ 'text': """
750
+ Role: GP Medical Assistant
751
+ Context: Non-emergency consultation - Persistent Cough
752
+ Style: Empathetic and thorough
753
+ Conversation Pattern:
754
+
755
+ Patient Input: Cough symptoms
756
+ Response Framework:
757
+ 1. Show empathy
758
+ 2. Gather specific details:
759
+ - Type of cough
760
+ - Duration
761
+ - Associated symptoms
762
+ 3. Risk assessment
763
+ 4. Clear recommendations
764
+
765
+ Example Flow:
766
+ Patient: I've had a cough for 5 days now
767
+ Pearly: I'm sorry to hear you've been unwell. To better understand your condition, is it a dry cough or are you producing any phlegm?
768
+
769
+ Patient: It's mostly dry but sometimes I cough up clear phlegm
770
+ Pearly: Thank you for that detail. Have you experienced any fever, and are you having any difficulty breathing?
771
+
772
+ Patient: No fever but I feel a bit short of breath sometimes
773
+ Pearly: I understand. A few more important questions:
774
+ 1. Have you been exposed to anyone with COVID-19 or other respiratory infections?
775
+ 2. Do you have any underlying health conditions?
776
+ 3. Are your symptoms worse at any particular time of day?
777
+
778
+ Would you like help booking an appointment with your GP?
779
+ """,
780
+ 'type': 'GP_template'
781
+ },
782
+ {
783
+ 'text': """
784
+ Role: GP Medical Assistant
785
+ Context: Mental Health Support
786
+ Style: Empathetic, patient, and supportive
787
+ Conversation Pattern:
788
+
789
+ Patient Input: Mental health concerns
790
+ Response Framework:
791
+ 1. Validate feelings
792
+ 2. Gentle exploration:
793
+ - Duration
794
+ - Impact on daily life
795
+ - Support systems
796
+ 3. Clear support options
797
+ 4. Immediate resources
798
+
799
+ Example Flow:
800
+ Patient: I've been feeling really anxious and can't sleep
801
+ Pearly: I hear you, and I want you to know it's brave to speak up about this. How long have you been experiencing these feelings?
802
+
803
+ Patient: About a month now, getting worse
804
+ Pearly: Thank you for sharing that. To better understand your situation:
805
+ 1. Are there any specific triggers you've noticed?
806
+ 2. How is this affecting your daily activities?
807
+ 3. Have you had any previous mental health support?
808
+
809
+ Would you like information about immediate support services or help booking a GP appointment?
810
+ """,
811
+ 'type': 'GP_template'
812
+ }
813
+ ]
814
+
815
+ # Add all templates to documents
816
+ documents.extend(GP_templates)
817
+
818
+ logger.info(f"Prepared {len(documents)} documents including:")
819
+ logger.info(f"- {len([d for d in documents if d['type'] == 'persona'])} persona guides")
820
+ logger.info(f"- {len([d for d in documents if d['type'] == 'conversation_pattern'])} conversation patterns")
821
+ logger.info(f"- {len([d for d in documents if d['type'] == 'medical_qa'])} medical QA pairs")
822
+ logger.info(f"- {len([d for d in documents if d['type'] == 'diagnosis_guidance'])} diagnosis guidelines")
823
+ logger.info(f"- {len([d for d in documents if d['type'] == 'conversation_framework'])} conversation frameworks")
824
+ logger.info(f"- {len([d for d in documents if d['type'] == 'GP_template'])} GP templates")
825
+
826
+ return documents
827
+
828
+ except Exception as e:
829
+ logger.error(f"Error preparing medical documents: {e}")
830
+ # Print sample data for debugging
831
+ for dataset_name, dataset in datasets.items():
832
+ try:
833
+ sample = dataset[0]
834
+ logger.error(f"\nSample from {dataset_name}:")
835
+ logger.error(f"Keys: {list(sample.keys())}")
836
+ logger.error(f"Sample content: {str(sample)[:500]}")
837
+ except Exception as debug_e:
838
+ logger.error(f"Error inspecting {dataset_name}: {debug_e}")
839
+ raise
840
+
841
+ def generate_response(self, query: str, chat_history: List[tuple] = None) -> Dict[str, Any]:
842
+ """Generate response with enhanced conversational context and persona"""
843
+ try:
844
+ # Update conversation memory
845
+ if chat_history:
846
+ self.conversation_memory['past_interactions'] = chat_history[-3:]
847
+
848
+ # Retrieve relevant documents with boosted weights for persona matches
849
+ retrieved_docs = self.retrieve(query, k=7)
850
+
851
+ # Separate documents by type
852
+ medical_docs = [doc for doc in retrieved_docs if doc['document']['type'] in ['medical_qa', 'diagnosis']]
853
+ persona_docs = [doc for doc in retrieved_docs if doc['document']['type'] in ['persona', 'conversation', 'GP_template']]
854
+
855
+ # Build context with weighted emphasis on different document types
856
+ medical_context = " ".join([doc['document']['text'] for doc in medical_docs])
857
+ persona_context = " ".join([doc['document']['text'] for doc in persona_docs])
858
+
859
+ # Assess urgency and get considerations
860
+ urgency_assessment = self.assess_urgency(query)
861
+ cultural_considerations = self.generate_cultural_considerations(query)
862
+
863
+ # Build conversation history context
864
+ history_context = ""
865
+ if chat_history:
866
+ history_context = "\n".join([f"Human: {h}\nPearly: {a}" for h, a in chat_history[-3:]])
867
+
868
+ # Add persona reminder
869
+ persona_reminder = f"""
870
+ I am {self.conversation_memory['name']}, a {self.conversation_memory['role']}.
871
+ My communication style is {self.conversation_memory['style']}.
872
+ """
873
+
874
+ # Create enhanced prompt with persona integration
875
+ prompt = f"""Context:
876
+ Medical Information: {medical_context}
877
+
878
+ {persona_reminder}
879
+
880
+ Previous Interactions:
881
+ {history_context}
882
+
883
+ Current Query: {query}
884
+
885
+ Maintain my identity as {self.conversation_memory['name']}, the {self.conversation_memory['role']},
886
+ providing clear, professional guidance following NHS protocols.
887
+ Urgency Level: {urgency_assessment['level']}
888
+ Cultural Considerations: {', '.join(cultural_considerations)}
889
+
890
+ Respond in a clear, caring manner, always referring to myself as {self.conversation_memory['name']}.
891
+
892
+ Response:"""
893
+
894
+ # Generate response
895
+ inputs = self.tokenizer(
896
+ prompt,
897
+ return_tensors="pt",
898
+ max_length=self.config.MAX_LENGTH,
899
+ truncation=True
900
+ ).to(self.device)
901
+
902
+ with torch.amp.autocast(device_type='cuda'):
903
+ outputs = self.model.generate(
904
+ **inputs,
905
+ max_new_tokens=512,
906
+ do_sample=True,
907
+ top_p=0.9,
908
+ temperature=0.7,
909
+ num_return_sequences=1,
910
+ pad_token_id=self.tokenizer.eos_token_id
911
+ )
912
+
913
+ response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
914
+ response = response.split("Response:")[-1].strip()
915
+
916
+ # Add booking template for emergency/urgent cases
917
+ if urgency_assessment['level'] in ["EMERGENCY", "URGENT"]:
918
+ booking_template = self.get_booking_template(urgency_assessment['level'])
919
+ response = f"{response}\n\n{booking_template}"
920
+
921
+ return {
922
+ 'response': response,
923
+ 'urgency_assessment': urgency_assessment,
924
+ 'cultural_considerations': cultural_considerations
925
+ }
926
+
927
+ except Exception as e:
928
+ logger.error(f"Error generating response: {e}")
929
+ return {
930
+ 'response': "I apologize, but I encountered an error. If this is an emergency, please call 999 immediately.",
931
+ 'urgency_assessment': {'level': 'UNKNOWN'},
932
+ 'cultural_considerations': []
933
+ }
934
+
935
+ def check_urgency_accuracy(self, predicted: str, expected: str) -> float:
936
+ """Check if urgency level matches expected"""
937
+ return 1.0 if predicted == expected else 0.0
938
+
939
+ def check_action_accuracy(self, response: str, expected_actions: List[str]) -> float:
940
+ """Check if recommended actions match expected"""
941
+ if not expected_actions:
942
+ return 1.0
943
+ found_actions = sum(1 for action in expected_actions
944
+ if action.lower() in response.lower())
945
+ return found_actions / len(expected_actions)
946
+
947
+ def assess_conversation_quality(self, response: str) -> float:
948
+ """Assess conversation quality metrics"""
949
+ metrics = {
950
+ 'empathy': any(word in response.lower()
951
+ for word in ['understand', 'hear you', 'sorry']),
952
+ 'clarity': len(response.split('.')) <= 5, # Check for concise sentences
953
+ 'follow_up': '?' in response, # Check for follow-up questions
954
+ 'structure': any(word in response.lower()
955
+ for word in ['first', 'then', 'next', 'finally'])
956
+ }
957
+ return sum(metrics.values()) / len(metrics)
958
+
959
+ def check_cultural_sensitivity(self, response_data: Dict, context: str) -> float:
960
+ """Check cultural sensitivity of response"""
961
+ if not context:
962
+ return 1.0
963
+
964
+ cultural_considerations = response_data.get('cultural_considerations', [])
965
+ return 1.0 if any(context.lower() in cons.lower()
966
+ for cons in cultural_considerations) else 0.0
967
+
968
+ def setup_wandb(config: MedicalConfig):
969
+ """Setup Weights & Biases tracking"""
970
+ try:
971
+ wandb.init(
972
+ project="medical-chatbot",
973
+ config={
974
+ "learning_rate": config.LEARNING_RATE,
975
+ "epochs": config.NUM_EPOCHS,
976
+ "batch_size": config.TRAINING_BATCH_SIZE,
977
+ "lora_r": config.LORA_R,
978
+ "lora_alpha": config.LORA_ALPHA
979
+ }
980
+ )
981
+ logger.info("Weights & Biases initialized successfully")
982
+ except Exception as e:
983
+ logger.warning(f"Failed to initialize Weights & Biases: {e}")
984
+ logger.warning("Continuing without wandb tracking")
985
 
986
  if __name__ == "__main__":
987
+ try:
988
+ # Initialize configuration
989
+ config = MedicalConfig()
990
+
991
+ # Setup wandb tracking
992
+ setup_wandb(config)
993
+
994
+ # Initialize RAG system
995
+ logger.info("Initializing RAG system...")
996
+ rag_system = GPUOptimizedRAG(config=config)
997
+
998
+ # Prepare and index documents
999
+ logger.info("Preparing medical knowledge base...")
1000
+ medical_documents = prepare_medical_documents()
1001
+ rag_system.prepare_documents(medical_documents)
1002
+
1003
+ # Create and launch Gradio interface
1004
+ interface = create_gradio_interface(rag_system)
1005
+ if interface is None:
1006
+ raise ValueError("Failed to create Gradio interface - interface object is None")
1007
+
1008
+ # Launch the interface
1009
+ interface.launch(server_name="0.0.0.0", server_port=7860, share=True)
1010
+ except Exception as e:
1011
+ logger.error(f"Application startup error: {e}")
1012
+ raise
1013
+