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

Delete medical_chatbot.py

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