Blaiseboy commited on
Commit
16cceb0
·
verified ·
1 Parent(s): 36a650f

Upload medical_chatbot.py

Browse files
Files changed (1) hide show
  1. medical_chatbot.py +856 -0
medical_chatbot.py ADDED
@@ -0,0 +1,856 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Setup and Installation
3
+
4
+ import torch
5
+ print("🖥️ System Check:")
6
+ print(f"CUDA available: {torch.cuda.is_available()}")
7
+ if torch.cuda.is_available():
8
+ print(f"GPU device: {torch.cuda.get_device_name(0)}")
9
+ print(f"GPU memory: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB")
10
+ else:
11
+ print("⚠️ No GPU detected - BioGPT will run on CPU (much slower)")
12
+
13
+ print("\n🔧 Installing required packages...")
14
+
15
+ # Import Libraries
16
+
17
+ import os
18
+ import re
19
+ import torch
20
+ import warnings
21
+ import numpy as np
22
+ import faiss # FAISS for vector search
23
+ from transformers import (
24
+ AutoTokenizer,
25
+ AutoModelForCausalLM,
26
+ pipeline,
27
+ BitsAndBytesConfig
28
+ )
29
+ from sentence_transformers import SentenceTransformer
30
+ from typing import List, Dict, Optional
31
+ import time
32
+ from datetime import datetime
33
+ import json
34
+ import pickle
35
+
36
+ # Suppress warnings for cleaner output
37
+ warnings.filterwarnings('ignore')
38
+
39
+ print("📚 Libraries imported successfully!")
40
+ print(f"🔍 FAISS version: {faiss.__version__}")
41
+ print("🎯 Using FAISS for vector search (ChromaDB completely removed)")
42
+
43
+ # File Upload Helper
44
+
45
+ from google.colab import files
46
+ import io
47
+
48
+ def upload_medical_data():
49
+ """Upload your Pediatric_cleaned.txt file"""
50
+ print("📁 Please upload your Pediatric_cleaned.txt file:")
51
+ uploaded = files.upload()
52
+
53
+ # Get the uploaded file
54
+ filename = list(uploaded.keys())[0]
55
+ print(f"✅ File '{filename}' uploaded successfully!")
56
+
57
+ # Read the content
58
+ content = uploaded[filename].decode('utf-8')
59
+
60
+ # Save it locally in Colab
61
+ with open('Pediatric_cleaned.txt', 'w', encoding='utf-8') as f:
62
+ f.write(content)
63
+
64
+ print(f"📝 File saved as 'Pediatric_cleaned.txt' ({len(content)} characters)")
65
+ return 'Pediatric_cleaned.txt'
66
+
67
+ medical_file = 'Pediatric_cleaned.txt'
68
+
69
+ # BioGPT Medical Chatbot Class
70
+
71
+ from typing import List, Dict, Optional # Import List, Dict, Optional
72
+
73
+ class ColabBioGPTChatbot:
74
+ def setup_biogpt(self):
75
+ """Setup BioGPT model with fallback to base BioGPT if Large fails"""
76
+ print("🧠 Attempting to load BioGPT-Large...")
77
+ model_name = "microsoft/BioGPT-Large"
78
+
79
+ try:
80
+ if self.use_8bit:
81
+ quantization_config = BitsAndBytesConfig(
82
+ load_in_8bit=True,
83
+ llm_int8_threshold=6.0,
84
+ llm_int8_has_fp16_weight=False,
85
+ )
86
+ else:
87
+ quantization_config = None
88
+
89
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name)
90
+ if self.tokenizer.pad_token is None:
91
+ self.tokenizer.pad_token = self.tokenizer.eos_token
92
+
93
+ self.model = AutoModelForCausalLM.from_pretrained(
94
+ model_name,
95
+ quantization_config=quantization_config,
96
+ torch_dtype=torch.float16 if self.device == "cuda" else torch.float32,
97
+ device_map="auto" if self.device == "cuda" else None,
98
+ trust_remote_code=True
99
+ )
100
+
101
+ if self.device == "cuda" and quantization_config is None:
102
+ self.model = self.model.to(self.device)
103
+
104
+ print("✅ BioGPT-Large loaded successfully!")
105
+ self.test_biogpt()
106
+
107
+ except Exception as e:
108
+ print(f"❌ BioGPT-Large loading failed: {e}")
109
+ print("🔁 Falling back to base model: microsoft/BioGPT")
110
+ self.setup_fallback_biogpt()
111
+
112
+ def fallback_biogpt():
113
+ """Fallback to microsoft/BioGPT if BioGPT-Large fails"""
114
+ print("Loading fallback model: microsoft/BioGPT")
115
+ # You can implement the actual fallback loading here later
116
+ pass
117
+
118
+ model_name = "microsoft/BioGPT"
119
+
120
+ try:
121
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name)
122
+ if self.tokenizer.pad_token is None:
123
+ self.tokenizer.pad_token = self.tokenizer.eos_token
124
+
125
+ self.model = AutoModelForCausalLM.from_pretrained(
126
+ model_name,
127
+ torch_dtype=torch.float32,
128
+ trust_remote_code=True
129
+ )
130
+ self.model = self.model.to(self.device)
131
+
132
+ print("✅ Base BioGPT model loaded as fallback.")
133
+ self.test_biogpt()
134
+
135
+ except Exception as e:
136
+ print(f"❌ Failed to load fallback BioGPT: {e}")
137
+ self.model = None
138
+ self.tokenizer = None
139
+
140
+ (self):
141
+ if self.tokenizer is None or self.model is None:
142
+ print("⚠️ Skipping test — model or tokenizer not available.")
143
+ return
144
+ print("🧪 Testing BioGPT...")
145
+ try:
146
+ input_text = "What is pneumonia?"
147
+ inputs = self.tokenizer(input_text, return_tensors="pt").to(self.device)
148
+ outputs = self.model.generate(**inputs, max_new_tokens=30)
149
+ response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
150
+ print(f"🧠 Model output: {response}")
151
+ except Exception as e:
152
+ print(f"⚠️ BioGPT test failed: {e}")
153
+
154
+ def __init__(self, use_gpu=True, use_8bit=True):
155
+ """Initialize BioGPT chatbot optimized for Google Colab"""
156
+ print("🏥 Initializing...")
157
+ self.use_gpu = use_gpu
158
+ self.use_8bit = use_8bit
159
+ self.device = "cuda" if torch.cuda.is_available() and use_gpu else "cpu"
160
+ print(f"🖥️ System Check:\nCUDA available: {torch.cuda.is_available()}\nUsing device: {self.device}")
161
+ self.tokenizer = None
162
+ self.model = None
163
+ self.vectorstore = None
164
+ self.history = []
165
+ self.embeddings = None
166
+
167
+ print("🔧 Installing required packages...")
168
+
169
+ try:
170
+ import transformers
171
+ import faiss
172
+ print("📚 Libraries imported successfully!")
173
+ print(f"🔍 FAISS version: {faiss.__version__}")
174
+ except ImportError as e:
175
+ print(f"❌ Missing package: {e}")
176
+
177
+ self.setup_biogpt()
178
+ self.load_sentence_transformer()
179
+ self.vectorstore = None
180
+
181
+ def setup_biogpt(self):
182
+ """Setup BioGPT model with fallback to base BioGPT if Large fails"""
183
+ print("🧠 Attempting to load BioGPT-Large...")
184
+ model_name = "microsoft/BioGPT-Large"
185
+ try:
186
+ if self.use_8bit and self.device == "cuda":
187
+ from transformers import BitsAndBytesConfig
188
+ bnb_config = BitsAndBytesConfig(load_in_8bit=True)
189
+ self.model = AutoModelForCausalLM.from_pretrained(model_name, quantization_config=bnb_config, device_map="auto")
190
+ else:
191
+ self.model = AutoModelForCausalLM.from_pretrained(model_name).to(self.device)
192
+
193
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name)
194
+ print("✅ BioGPT-Large loaded successfully.")
195
+ except Exception as e:
196
+ print(f"❌ BioGPT-Large loading failed: {e}")
197
+ print("🔁 Falling back to base model: microsoft/BioGPT")
198
+ self.setup_fallback_biogpt()
199
+
200
+ def setup_fallback_biogpt(self):
201
+ """Fallback to microsoft/BioGPT if BioGPT-Large fails"""
202
+ print("Loading fallback model: microsoft/BioGPT")
203
+ model_name = "microsoft/BioGPT"
204
+ self.model = AutoModelForCausalLM.from_pretrained(model_name).to(self.device)
205
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name)
206
+ print("✅ Fallback BioGPT model loaded.")
207
+
208
+ def test_biogpt(self):
209
+ """Test BioGPT with a simple medical query"""
210
+ print("🧪 Testing BioGPT...")
211
+ if not self.model or not self.tokenizer:
212
+ print("⚠️ BioGPT not properly initialized.")
213
+ return
214
+
215
+ input_text = "What are symptoms of measles?"
216
+ inputs = self.tokenizer(input_text, return_tensors="pt").to(self.device)
217
+ outputs = self.model.generate(**inputs, max_new_tokens=50)
218
+ response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
219
+ print(f"💬 Test response: {response}")
220
+
221
+
222
+ def load_medical_data(self, file_path):
223
+ """Load and process medical data with progress tracking"""
224
+ print(f"📖 Loading medical data from {file_path}...")
225
+
226
+ try:
227
+ with open(file_path, 'r', encoding='utf-8') as f:
228
+ text = f.read()
229
+ print(f"📄 File loaded: {len(text):,} characters")
230
+ except FileNotFoundError:
231
+ print(f"❌ File {file_path} not found!")
232
+ raise ValueError("Failed to load medical data")
233
+
234
+ # Create chunks optimized for medical content
235
+ print("📝 Creating medical-optimized chunks...")
236
+ chunks = self.create_medical_chunks(text)
237
+ print(f"📋 Created {len(chunks)} medical chunks")
238
+
239
+ self.knowledge_chunks = chunks
240
+
241
+ # Generate embeddings with progress and add to FAISS index
242
+ if self.use_embeddings and self.embedding_model and self.faiss_ready:
243
+ return self.generate_embeddings_with_progress(chunks)
244
+
245
+ print("✅ Medical data loaded (text search mode)")
246
+ return
247
+
248
+ def create_medical_chunks(self, text: str, chunk_size: int = 400) -> List[Dict]:
249
+ """Create medically-optimized text chunks"""
250
+ chunks = []
251
+
252
+ # Split by medical sections first
253
+ medical_sections = self.split_by_medical_sections(text)
254
+
255
+ chunk_id = 0
256
+ for section in medical_sections:
257
+ if len(section.split()) > chunk_size:
258
+ # Split large sections by sentences
259
+ sentences = re.split(r'[.!?]+', section)
260
+ current_chunk = ""
261
+
262
+ for sentence in sentences:
263
+ sentence = sentence.strip()
264
+ if not sentence:
265
+ continue
266
+
267
+ if len(current_chunk.split()) + len(sentence.split()) < chunk_size:
268
+ current_chunk += sentence + ". "
269
+ else:
270
+ if current_chunk.strip():
271
+ chunks.append({
272
+ 'id': chunk_id,
273
+ 'text': current_chunk.strip(),
274
+ 'medical_focus': self.identify_medical_focus(current_chunk)
275
+ })
276
+ chunk_id += 1
277
+ current_chunk = sentence + ". "
278
+
279
+ if current_chunk.strip():
280
+ chunks.append({
281
+ 'id': chunk_id,
282
+ 'text': current_chunk.strip(),
283
+ 'medical_focus': self.identify_medical_focus(current_chunk)
284
+ })
285
+ chunk_id += 1
286
+ else:
287
+ chunks.append({
288
+ 'id': chunk_id,
289
+ 'text': section,
290
+ 'medical_focus': self.identify_medical_focus(section)
291
+ })
292
+ chunk_id += 1
293
+
294
+ return chunks
295
+
296
+ def split_by_medical_sections(self, text: str) -> List[str]:
297
+ """Split text by medical sections"""
298
+ # Look for medical section headers
299
+ section_patterns = [
300
+ r'\n\s*(?:SYMPTOMS?|TREATMENT|DIAGNOSIS|CAUSES?|PREVENTION|MANAGEMENT).*?\n',
301
+ r'\n\s*\d+\.\s+', # Numbered sections
302
+ r'\n\n+' # Paragraph breaks
303
+ ]
304
+
305
+ sections = [text]
306
+ for pattern in section_patterns:
307
+ new_sections = []
308
+ for section in sections:
309
+ splits = re.split(pattern, section, flags=re.IGNORECASE)
310
+ new_sections.extend([s.strip() for s in splits if len(s.strip()) > 100])
311
+ sections = new_sections
312
+
313
+ return sections
314
+
315
+ def identify_medical_focus(self, text: str) -> str:
316
+ """Identify the medical focus of a text chunk"""
317
+ text_lower = text.lower()
318
+
319
+ # Medical categories
320
+ categories = {
321
+ 'pediatric_symptoms': ['fever', 'cough', 'rash', 'vomiting', 'diarrhea'],
322
+ 'treatments': ['treatment', 'therapy', 'medication', 'antibiotics'],
323
+ 'diagnosis': ['diagnosis', 'diagnostic', 'symptoms', 'signs'],
324
+ 'emergency': ['emergency', 'urgent', 'serious', 'hospital'],
325
+ 'prevention': ['prevention', 'vaccine', 'immunization', 'avoid']
326
+ }
327
+
328
+ for category, keywords in categories.items():
329
+ if any(keyword in text_lower for keyword in keywords):
330
+ return category
331
+
332
+ return 'general_medical'
333
+
334
+ def generate_embeddings_with_progress(self, chunks: List[Dict]) -> bool:
335
+ """Generate embeddings with progress tracking and add to FAISS index"""
336
+ print("🔮 Generating medical embeddings and adding to FAISS index...")
337
+
338
+ if not self.embedding_model or not self.faiss_index:
339
+ print("❌ Embedding model or FAISS index not available.")
340
+ raise ValueError("Failed to load medical data")
341
+
342
+ try:
343
+ texts = [chunk['text'] for chunk in chunks]
344
+
345
+ # Generate embeddings in batches with progress
346
+ batch_size = 32
347
+ all_embeddings = []
348
+
349
+ for i in range(0, len(texts), batch_size):
350
+ batch_texts = texts[i:i+batch_size]
351
+ batch_embeddings = self.embedding_model.encode(batch_texts, show_progress_bar=False)
352
+ all_embeddings.extend(batch_embeddings)
353
+
354
+ # Show progress
355
+ progress = min(i + batch_size, len(texts))
356
+ print(f" Progress: {progress}/{len(texts)} chunks processed", end='\r')
357
+
358
+ print(f"\n ✅ Generated embeddings for {len(texts)} chunks")
359
+
360
+ # Add embeddings to FAISS index
361
+ print("💾 Adding embeddings to FAISS index...")
362
+ self.faiss_index.add(np.array(all_embeddings))
363
+
364
+ print("✅ Medical embeddings added to FAISS index successfully!")
365
+ return True
366
+
367
+ except Exception as e:
368
+ print(f"❌ Embedding generation or FAISS add failed: {e}")
369
+ raise ValueError("Failed to load medical data")
370
+
371
+
372
+ def retrieve_medical_context(self, query: str, n_results: int = 3) -> List[str]:
373
+ """Retrieve relevant medical context using embeddings or keyword search"""
374
+ if self.use_embeddings and self.embedding_model and self.faiss_ready:
375
+ try:
376
+ # Generate query embedding
377
+ query_embedding = self.embedding_model.encode([query])
378
+
379
+ # Search for similar content in FAISS index
380
+ distances, indices = self.faiss_index.search(np.array(query_embedding), n_results)
381
+
382
+ # Retrieve the corresponding chunks
383
+ context_chunks = [self.knowledge_chunks[i]['text'] for i in indices[0] if i != -1]
384
+
385
+ if context_chunks:
386
+ return context_chunks
387
+
388
+ except Exception as e:
389
+ print(f"⚠️ Embedding search failed: {e}")
390
+
391
+ # Fallback to keyword search
392
+ print("⚠️ Falling back to keyword search.")
393
+ return self.keyword_search_medical(query, n_results)
394
+
395
+
396
+ def keyword_search_medical(self, query: str, n_results: int) -> List[str]:
397
+ """Medical-focused keyword search"""
398
+ if not self.knowledge_chunks:
399
+ return []
400
+
401
+ query_words = set(query.lower().split())
402
+ chunk_scores = []
403
+
404
+ for chunk_info in self.knowledge_chunks:
405
+ chunk_text = chunk_info['text']
406
+ chunk_words = set(chunk_text.lower().split())
407
+
408
+ # Calculate relevance score
409
+ word_overlap = len(query_words.intersection(chunk_words))
410
+ base_score = word_overlap / len(query_words) if query_words else 0
411
+
412
+ # Boost medical content
413
+ medical_boost = 0
414
+ if chunk_info.get('medical_focus') in ['pediatric_symptoms', 'treatments', 'diagnosis']:
415
+ medical_boost = 0.5
416
+
417
+ final_score = base_score + medical_boost
418
+
419
+ if final_score > 0:
420
+ chunk_scores.append((final_score, chunk_text))
421
+
422
+ # Return top matches
423
+ chunk_scores.sort(reverse=True)
424
+ return [chunk for _, chunk in chunk_scores[:n_results]]
425
+
426
+ def generate_biogpt_response(self, context: str, query: str) -> str:
427
+ """Generate medical response using BioGPT"""
428
+ if not self.model or not self.tokenizer:
429
+ return "Medical model not available. Please check the setup."
430
+
431
+ try:
432
+ # Create medical-focused prompt
433
+ prompt = f"""Medical Context: {context[:800]}
434
+
435
+ Question: {query}
436
+
437
+ Medical Answer:"""
438
+
439
+ # Tokenize input
440
+ inputs = self.tokenizer(
441
+ prompt,
442
+ return_tensors="pt",
443
+ truncation=True,
444
+ max_length=1024
445
+ )
446
+
447
+ # Move inputs to the correct device
448
+ if self.device == "cuda":
449
+ inputs = {k: v.to(self.device) for k, v in inputs.items()}
450
+
451
+ # Generate response
452
+ with torch.no_grad():
453
+ outputs = self.model.generate(
454
+ **inputs,
455
+ max_new_tokens=150,
456
+ do_sample=True,
457
+ temperature=0.7,
458
+ top_p=0.9,
459
+ pad_token_id=self.tokenizer.eos_token_id,
460
+ repetition_penalty=1.1
461
+ )
462
+
463
+ # Decode response
464
+ full_response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
465
+
466
+ # Extract just the generated part
467
+ if "Medical Answer:" in full_response:
468
+ generated_response = full_response.split("Medical Answer:")[-1].strip()
469
+ else:
470
+ generated_response = full_response[len(prompt):].strip()
471
+
472
+ # Clean up response
473
+ cleaned_response = self.clean_medical_response(generated_response)
474
+
475
+ return cleaned_response
476
+
477
+ except Exception as e:
478
+ print(f"⚠️ BioGPT generation failed: {e}")
479
+ return self.fallback_response(context, query)
480
+
481
+ def clean_medical_response(self, response: str) -> str:
482
+ """Clean and format medical response"""
483
+ # Remove incomplete sentences and limit length
484
+ sentences = re.split(r'[.!?]+', response)
485
+ clean_sentences = []
486
+
487
+ for sentence in sentences:
488
+ sentence = sentence.strip()
489
+ if len(sentence) > 10 and not sentence.endswith(('and', 'or', 'but', 'however')):
490
+ clean_sentences.append(sentence)
491
+ if len(clean_sentences) >= 3: # Limit to 3 sentences
492
+ break
493
+
494
+ if clean_sentences:
495
+ cleaned = '. '.join(clean_sentences) + '.'
496
+ else:
497
+ cleaned = response[:200] + '...' if len(response) > 200 else response
498
+
499
+ return cleaned
500
+
501
+ def fallback_response(self, context: str, query: str) -> str:
502
+ """Fallback response when BioGPT fails"""
503
+ # Extract key sentences from context
504
+ sentences = [s.strip() for s in context.split('.') if len(s.strip()) > 20]
505
+
506
+ if sentences:
507
+ response = sentences[0] + '.'
508
+ if len(sentences) > 1:
509
+ response += ' ' + sentences[1] + '.'
510
+ else:
511
+ response = context[:300] + '...'
512
+
513
+ return response
514
+
515
+ def handle_conversational_interactions(self, query: str) -> Optional[str]:
516
+ """Handle comprehensive conversational interactions"""
517
+ query_lower = query.lower().strip()
518
+
519
+ # Use more specific patterns for greetings
520
+ greeting_patterns = [
521
+ r'^\s*(hello|hi|hey|hiya|howdy)\s*$',
522
+ r'^\s*(good morning|good afternoon|good evening|good day)\s*$',
523
+ r'^\s*(what\'s up|whats up|sup|yo)\s*$',
524
+ r'^\s*(greetings|salutations)\s*$',
525
+ r'^\s*(how are you|how are you doing|how\'s it going|hows it going)\s*$',
526
+ r'^\s*(good to meet you|nice to meet you|pleased to meet you)\s*$'
527
+ ]
528
+
529
+ for pattern in greeting_patterns:
530
+ if re.match(pattern, query_lower):
531
+ responses = [
532
+ "👋 Hello! I'm BioGPT, your professional medical AI assistant specialized in pediatric medicine. I'm here to provide evidence-based medical information. What health concern can I help you with today?",
533
+ "🏥 Hi there! I'm a medical AI assistant powered by BioGPT, trained on medical literature. I can help answer questions about children's health and medical conditions. How can I assist you?",
534
+ "👋 Greetings! I'm your AI medical consultant, ready to help with pediatric health questions using the latest medical knowledge. What would you like to know about?"
535
+ ]
536
+ return np.random.choice(responses)
537
+
538
+ # ===== THANKS & APPRECIATION =====
539
+ thanks_patterns = [
540
+ ['thank you', 'thanks', 'thx', 'ty', 'thank you so much', 'thanks a lot', 'much appreciated', 'really appreciate it', 'i appreciate it', 'grateful', 'that was helpful', 'very helpful', 'awesome', 'perfect', 'great', 'excellent', 'wonderful', 'that helped', 'exactly what i needed', 'very informative', 'good information']
541
+ ]
542
+
543
+ for pattern_group in thanks_patterns:
544
+ if any(keyword in query_lower for keyword in pattern_group):
545
+ responses = [
546
+ "🙏 You're very welcome! I'm glad I could provide helpful medical information. Remember, this is educational guidance - always consult your healthcare provider for personalized medical advice. Feel free to ask more questions!",
547
+ "😊 Happy to help! Providing accurate medical information is what I'm here for. If you have any other pediatric health questions, don't hesitate to ask.",
548
+ "🤗 You're most welcome! I'm pleased the medical information was useful. Please remember to consult with healthcare professionals for any medical decisions. What else can I help you with?"
549
+ ]
550
+ return np.random.choice(responses)
551
+
552
+ # ===== GOODBYES =====
553
+ goodbye_patterns = [
554
+ ['bye', 'goodbye', 'farewell', 'see you', 'later', 'see ya', 'catch you later', 'talk to you later', 'ttyl', 'have a good day', 'have a great day', 'take care', 'until next time', 'i need to go', 'that\'s all for now', 'no more questions']
555
+ ]
556
+
557
+ for pattern_group in goodbye_patterns:
558
+ if any(keyword in query_lower for keyword in pattern_group):
559
+ responses = [
560
+ "👋 Goodbye! Take excellent care of yourself and your little ones. Remember, I'm here whenever you need reliable pediatric medical information. Stay healthy! 🏥",
561
+ "🌟 Farewell! Wishing you and your family good health. Don't hesitate to return if you have more medical questions. Take care!",
562
+ "👋 See you later! Hope the medical information was helpful. Remember to always consult healthcare professionals for medical decisions. Stay well!"
563
+ ]
564
+ return np.random.choice(responses)
565
+
566
+ # ===== ABOUT/HELP QUESTIONS =====
567
+ about_patterns = [
568
+ ['what are you', 'who are you', 'tell me about yourself', 'what do you do', 'what can you help with', 'what can you do', 'how can you help', 'what are your capabilities', 'help', 'help me', 'i need help', 'can you help', 'how do i use this', 'how does this work', 'what should i ask']
569
+ ]
570
+
571
+ for pattern_group in about_patterns:
572
+ if any(keyword in query_lower for keyword in pattern_group):
573
+ return """🤖 **About BioGPT Medical Assistant**
574
+
575
+ I'm an AI medical assistant powered by BioGPT-Large, a specialized medical AI model trained on extensive medical literature. Here's what I can help you with:
576
+
577
+ 🩺 **Medical Specialties:**
578
+ • Pediatric medicine and children's health
579
+ • Symptom explanation and medical conditions
580
+ • Treatment options and medical procedures
581
+ • When to seek medical care
582
+ • Prevention and wellness guidance
583
+
584
+ 🎯 **How to Use Me:**
585
+ • Ask specific medical questions: "What causes fever in children?"
586
+ • Describe symptoms: "My child has a persistent cough"
587
+ • Seek guidance: "When should I call the doctor?"
588
+ • Get information: "How do I treat dehydration?"
589
+
590
+ ⚠️ **Important Reminder:**
591
+ I provide educational medical information based on medical literature, but I'm not a substitute for professional medical advice. Always consult qualified healthcare providers for:
592
+ • Medical emergencies
593
+ • Diagnosis and treatment decisions
594
+ • Personalized medical advice
595
+ • Medication guidance
596
+
597
+ 💡 **Tip:** Be specific in your questions for the most helpful responses!
598
+
599
+ What pediatric health topic would you like to explore?"""
600
+
601
+ # ===== SMALL TALK & PERSONAL QUESTIONS =====
602
+ personal_patterns = [
603
+ ['how are you feeling', 'are you okay', 'how\'s your day', 'are you smart', 'are you intelligent', 'do you know everything', 'are you human', 'are you real', 'are you a robot', 'are you ai', 'you\'re smart', 'you\'re helpful', 'good job', 'well done', 'impressive']
604
+ ]
605
+
606
+ for pattern_group in personal_patterns:
607
+ if any(keyword in query_lower for keyword in pattern_group):
608
+ responses = [
609
+ "🤖 I'm an AI medical assistant, so I don't have feelings, but I'm functioning well and ready to help with medical questions! My purpose is to provide reliable pediatric health information. What can I help you with?",
610
+ "😊 Thank you for asking! As an AI, I'm always ready to assist with medical information. I'm designed to help with pediatric health questions using evidence-based medical knowledge. How can I help you today?",
611
+ "🎯 I'm doing what I do best - providing medical information! I'm an AI trained on medical literature to help with pediatric health questions. What medical topic interests you?"
612
+ ]
613
+ return np.random.choice(responses)
614
+
615
+ # ===== CONFUSED/UNCLEAR INPUT =====
616
+ confusion_patterns = [
617
+ ['i don\'t know', 'not sure', 'confused', 'unclear', 'help me understand', 'what do you mean', 'i don\'t understand', 'can you explain', 'huh', 'i\'m lost', 'i\'m confused', 'this is confusing']
618
+ ]
619
+
620
+ for pattern_group in confusion_patterns:
621
+ if any(keyword in query_lower for keyword in pattern_group):
622
+ return """🤔 **I understand it can be confusing!** Let me help you get started.
623
+
624
+ 💡 **Try asking questions like:**
625
+
626
+ 🩺 **Symptoms:**
627
+ • "What causes [symptom] in children?"
628
+ • "My child has [symptom], what should I do?"
629
+
630
+ 💊 **Treatments:**
631
+ • "How do I treat [condition] in children?"
632
+ • "What are treatment options for [condition]?"
633
+
634
+ 🚨 **Urgency:**
635
+ • "When should I call the doctor about [symptom]?"
636
+ • "Is [symptom] serious in children?"
637
+
638
+ 🛡️ **Prevention:**
639
+ • "How can I prevent [condition]?"
640
+ • "What are the warning signs of [condition]?"
641
+
642
+ **What specific aspect of your child's health would you like to understand better?**"""
643
+
644
+ # ===== APOLOGIES & POLITENESS =====
645
+ polite_patterns = [
646
+ ['sorry', 'excuse me', 'pardon me', 'my apologies', 'please help', 'could you please', 'would you mind', 'if you don\'t mind', 'sorry to bother you']
647
+ ]
648
+
649
+ for pattern_group in polite_patterns:
650
+ if any(keyword in query_lower for keyword in pattern_group):
651
+ return "😊 No need to apologize! I'm here to help with medical questions. Please feel free to ask anything about pediatric health - that's exactly what I'm designed for. What can I help you with?"
652
+
653
+ # ===== TESTING & VERIFICATION =====
654
+ test_patterns = [
655
+ ['test', 'testing', 'hello world', 'can you hear me', 'are you working', 'do you work', 'are you there', 'are you online', 'check', 'verify', 'ping']
656
+ ]
657
+
658
+ for pattern_group in test_patterns:
659
+ if any(keyword in query_lower for keyword in pattern_group):
660
+ return "✅ **System Check:** I'm working perfectly and ready to assist! BioGPT medical AI is online and functioning optimally. Ready to help with pediatric medical questions. What would you like to know?"
661
+
662
+ # Return None if no conversational pattern matches
663
+ return None
664
+
665
+
666
+ def chat(self, query: str) -> str:
667
+ """Main chat function with BioGPT and comprehensive conversational handling"""
668
+ if not query.strip():
669
+ return "Hello! I'm BioGPT, your professional medical AI assistant. How can I help you with pediatric medical questions today?"
670
+
671
+ # Handle comprehensive conversational interactions first
672
+ conversational_response = self.handle_conversational_interactions(query)
673
+ if conversational_response:
674
+ # Add to conversation history
675
+ self.conversation_history.append({
676
+ 'query': query,
677
+ 'response': conversational_response,
678
+ 'timestamp': datetime.now().isoformat(),
679
+ 'type': 'conversational'
680
+ })
681
+ return conversational_response
682
+
683
+ if not self.knowledge_chunks:
684
+ return "Please load medical data first to access the medical knowledge base."
685
+
686
+ if not self.model or not self.tokenizer:
687
+ return "Medical model not available. Please check the setup."
688
+
689
+ print(f"🔍 Processing medical query: {query}")
690
+
691
+ # Retrieve relevant medical context using FAISS or keyword search
692
+ start_time = time.time()
693
+ context = self.retrieve_medical_context(query)
694
+ retrieval_time = time.time() - start_time
695
+
696
+ if not context:
697
+ return "I don't have specific information about this topic in my medical database. Please consult with a healthcare professional for personalized medical advice."
698
+
699
+ print(f" 📚 Context retrieved ({retrieval_time:.2f}s)")
700
+
701
+ # Generate response with BioGPT
702
+ start_time = time.time()
703
+ main_context = '\n\n'.join(context)
704
+ response = self.generate_biogpt_response(main_context, query)
705
+ generation_time = time.time() - start_time
706
+
707
+ print(f" 🧠 Response generated ({generation_time:.2f}s)")
708
+
709
+ # Format final response
710
+ final_response = f"🩺 **Medical Information:** {response}\n\n⚠️ **Important:** This information is for educational purposes only. Always consult with qualified healthcare professionals for medical diagnosis, treatment, and personalized advice."
711
+
712
+ # Add to conversation history
713
+ self.conversation_history.append({
714
+ 'query': query,
715
+ 'response': final_response,
716
+ 'timestamp': datetime.now().isoformat(),
717
+ 'retrieval_time': retrieval_time,
718
+ 'generation_time': generation_time,
719
+ 'type': 'medical'
720
+ })
721
+
722
+ return final_response
723
+
724
+ def get_conversation_summary(self) -> Dict:
725
+ """Get conversation statistics"""
726
+ if not self.conversation_history:
727
+ return {"message": "No conversations yet"}
728
+
729
+ # Filter medical conversations for performance stats
730
+ medical_conversations = [h for h in self.conversation_history if h.get('type') == 'medical']
731
+
732
+ model_info = "BioGPT-Large" if self.model else "Model Not Loaded"
733
+
734
+ if not medical_conversations:
735
+ return {
736
+ "total_conversations": len(self.conversation_history),
737
+ "medical_conversations": 0,
738
+ "conversational_interactions": len(self.conversation_history),
739
+ "model_info": model_info,
740
+ "vector_search": "FAISS CPU" if self.faiss_ready else "Keyword Search",
741
+ "device": self.device
742
+ }
743
+
744
+ avg_retrieval_time = sum(h.get('retrieval_time', 0) for h in medical_conversations) / len(medical_conversations)
745
+ avg_generation_time = sum(h.get('generation_time', 0) for h in medical_conversations) / len(medical_conversations)
746
+
747
+ return {
748
+ "total_conversations": len(self.conversation_history),
749
+ "medical_conversations": len(medical_conversations),
750
+ "conversational_interactions": len(self.conversation_history) - len(medical_conversations),
751
+ "avg_retrieval_time": f"{avg_retrieval_time:.2f}s",
752
+ "avg_generation_time": f"{avg_generation_time:.2f}s",
753
+ "model_info": model_info,
754
+ "vector_search": "FAISS CPU" if self.faiss_ready else "Keyword Search",
755
+ "device": self.device,
756
+ "quantization": "8-bit" if self.use_8bit else "16-bit/32-bit"
757
+ }
758
+
759
+ # Create and Test BioGPT Chatbot
760
+
761
+ def create_biogpt_chatbot():
762
+ """Create and initialize the BioGPT chatbot"""
763
+ print("🚀 Creating Professional BioGPT Medical Chatbot")
764
+ print("=" * 60)
765
+
766
+ # Create chatbot
767
+ chatbot = ColabBioGPTChatbot(use_gpu=True, use_8bit=True)
768
+
769
+ return chatbot
770
+
771
+ def test_biogpt_chatbot(chatbot, test_file='Pediatric_cleaned.txt'):
772
+ """Test the BioGPT chatbot"""
773
+ print("\n📚 Loading medical data...")
774
+ success = chatbot.load_medical_data(test_file)
775
+
776
+ if not success:
777
+ print("❌ Failed to load medical data. Please check the file.")
778
+ return None
779
+
780
+ print("\n🧪 Testing BioGPT Medical Chatbot:")
781
+ print("=" * 50)
782
+
783
+ # Test queries
784
+ test_queries = [
785
+ "What causes fever in children?",
786
+ "How should I treat my child's cough?",
787
+ "When should I be concerned about my baby's breathing?",
788
+ "What are the signs of dehydration in infants?"
789
+ ]
790
+
791
+ for i, query in enumerate(test_queries, 1):
792
+ print(f"\n{i}️⃣ Testing: {query}")
793
+ print("-" * 40)
794
+
795
+ response = chatbot.chat(query)
796
+ print(f"🤖 BioGPT Response:\n{response}")
797
+ print("=" * 50)
798
+
799
+ # Show conversation summary
800
+ summary = chatbot.get_conversation_summary()
801
+ print("\n📊 Performance Summary:")
802
+ for key, value in summary.items():
803
+ print(f" {key}: {value}")
804
+
805
+ return chatbot
806
+
807
+ # Interactive Chat Interface
808
+
809
+ def interactive_biogpt_chat(chatbot):
810
+ """Interactive chat with BioGPT"""
811
+ print("\n💬 Interactive BioGPT Medical Chat")
812
+ print("=" * 50)
813
+ print("You're now chatting with BioGPT, a professional medical AI!")
814
+ print("Type 'quit' to exit, 'summary' to see stats")
815
+ print("-" * 50)
816
+
817
+ while True:
818
+ user_input = input("\n👤 You: ").strip()
819
+
820
+ if user_input.lower() in ['quit', 'exit', 'bye']:
821
+ print("\n👋 Thank you for using BioGPT Medical Assistant!")
822
+ # Show final summary
823
+ summary = chatbot.get_conversation_summary()
824
+ print("\n📊 Final Session Summary:")
825
+ for key, value in summary.items():
826
+ print(f" {key}: {value}")
827
+ break
828
+
829
+ elif user_input.lower() == 'summary':
830
+ summary = chatbot.get_conversation_summary()
831
+ print("\n📊 Current Session Summary:")
832
+ for key, value in summary.items():
833
+ print(f" {key}: {value}")
834
+ continue
835
+
836
+ elif not user_input:
837
+ continue
838
+
839
+ print(f"\n🤖 BioGPT: ", end="")
840
+ response = chatbot.chat(user_input)
841
+ print(response)
842
+
843
+ # Main Execution - Initialization
844
+
845
+ import torch
846
+
847
+ # Create the BioGPT chatbot
848
+ chatbot = create_biogpt_chatbot()
849
+
850
+ print("\n" + "="*60)
851
+ print("🎯 NEXT STEPS:")
852
+ print("1. Upload your medical data file by running the next cell.")
853
+ print("2. Test the chatbot by running the cell after the upload.")
854
+ print("3. Start interactive chat by running the final cell.")
855
+ print("="*60)
856
+