Blaiseboy commited on
Commit
a8da25c
·
verified ·
1 Parent(s): 7bd6654

Delete medical_chatbot.py

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