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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
import torch
|
| 4 |
+
from medical_chatbot import ColabBioGPTChatbot
|
| 5 |
+
|
| 6 |
+
def initialize_chatbot():
|
| 7 |
+
"""Initialize the chatbot with proper error handling"""
|
| 8 |
+
try:
|
| 9 |
+
print("🚀 Initializing Medical Chatbot...")
|
| 10 |
+
|
| 11 |
+
# Check if GPU is available but use CPU for stability on HF Spaces
|
| 12 |
+
use_gpu = torch.cuda.is_available()
|
| 13 |
+
use_8bit = use_gpu # Only use 8-bit if GPU is available
|
| 14 |
+
|
| 15 |
+
chatbot = ColabBioGPTChatbot(use_gpu=use_gpu, use_8bit=use_8bit)
|
| 16 |
+
|
| 17 |
+
# Try to load medical data
|
| 18 |
+
medical_file = "Pediatric_cleaned.txt"
|
| 19 |
+
if os.path.exists(medical_file):
|
| 20 |
+
chatbot.load_medical_data(medical_file)
|
| 21 |
+
status = f"✅ Medical file '{medical_file}' loaded successfully! Ready to chat!"
|
| 22 |
+
success = True
|
| 23 |
+
else:
|
| 24 |
+
status = f"❌ Medical file '{medical_file}' not found. Please ensure the file is in the same directory."
|
| 25 |
+
success = False
|
| 26 |
+
|
| 27 |
+
return chatbot, status, success
|
| 28 |
+
|
| 29 |
+
except Exception as e:
|
| 30 |
+
error_msg = f"❌ Failed to initialize chatbot: {str(e)}"
|
| 31 |
+
print(error_msg)
|
| 32 |
+
return None, error_msg, False
|
| 33 |
+
|
| 34 |
+
# Check if file exists
|
| 35 |
+
medical_file = "Pediatric_cleaned.txt"
|
| 36 |
+
print(f"Debug: Looking for file: {medical_file}")
|
| 37 |
+
print(f"Debug: File exists: {os.path.exists(medical_file)}")
|
| 38 |
+
if os.path.exists(medical_file):
|
| 39 |
+
with open(medical_file, 'r') as f:
|
| 40 |
+
content = f.read()
|
| 41 |
+
print(f"Debug: File size: {len(content)} characters")
|
| 42 |
+
|
| 43 |
+
# Initialize chatbot at startup
|
| 44 |
+
print("🏥 Starting Pediatric Medical Assistant...")
|
| 45 |
+
chatbot, startup_status, medical_file_loaded = initialize_chatbot()
|
| 46 |
+
|
| 47 |
+
def generate_response(user_input, history):
|
| 48 |
+
"""Generate response with proper error handling"""
|
| 49 |
+
if not chatbot:
|
| 50 |
+
return history + [("System Error", "❌ Chatbot failed to initialize. Please refresh the page and try again.")], ""
|
| 51 |
+
|
| 52 |
+
if not medical_file_loaded:
|
| 53 |
+
return history + [(user_input, "⚠️ Medical data failed to load. The chatbot may not have access to the full medical knowledge base.")], ""
|
| 54 |
+
|
| 55 |
+
if not user_input.strip():
|
| 56 |
+
return history, ""
|
| 57 |
+
|
| 58 |
+
try:
|
| 59 |
+
# Generate response
|
| 60 |
+
bot_response = chatbot.chat(user_input)
|
| 61 |
+
|
| 62 |
+
# Add to history
|
| 63 |
+
history = history + [(user_input, bot_response)]
|
| 64 |
+
|
| 65 |
+
return history, ""
|
| 66 |
+
|
| 67 |
+
except Exception as e:
|
| 68 |
+
error_response = f"⚠️ Sorry, I encountered an error: {str(e)}. Please try rephrasing your question."
|
| 69 |
+
history = history + [(user_input, error_response)]
|
| 70 |
+
return history, ""
|
| 71 |
+
|
| 72 |
+
# Initialize chatbot at startup
|
| 73 |
+
print("🏥 Starting Pediatric Medical Assistant...")
|
| 74 |
+
chatbot, startup_status, medical_file_loaded = initialize_chatbot()
|
| 75 |
+
|
| 76 |
+
# debug section:
|
| 77 |
+
print(f"Debug: Medical file loaded = {medical_file_loaded}")
|
| 78 |
+
if chatbot and hasattr(chatbot, 'knowledge_chunks'):
|
| 79 |
+
print(f"Debug: Number of knowledge chunks = {len(chatbot.knowledge_chunks)}")
|
| 80 |
+
if chatbot.knowledge_chunks:
|
| 81 |
+
print(f"Debug: First chunk preview = {chatbot.knowledge_chunks[0]['text'][:100]}...")
|
| 82 |
+
else:
|
| 83 |
+
print("Debug: No knowledge_chunks attribute found")
|
| 84 |
+
|
| 85 |
+
# Create custom CSS for better styling
|
| 86 |
+
custom_css = """
|
| 87 |
+
.gradio-container {
|
| 88 |
+
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
.chatbot {
|
| 92 |
+
height: 500px !important;
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
.message {
|
| 96 |
+
padding: 10px;
|
| 97 |
+
margin: 5px;
|
| 98 |
+
border-radius: 10px;
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
.user-message {
|
| 102 |
+
background-color: #e3f2fd;
|
| 103 |
+
margin-left: 20%;
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
.bot-message {
|
| 107 |
+
background-color: #f5f5f5;
|
| 108 |
+
margin-right: 20%;
|
| 109 |
+
}
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
# Create Gradio interface
|
| 113 |
+
with gr.Blocks(css=custom_css, title="Pediatric Medical Assistant") as demo:
|
| 114 |
+
gr.Markdown(
|
| 115 |
+
"""
|
| 116 |
+
# 🩺 Pediatric Medical Assistant
|
| 117 |
+
|
| 118 |
+
Welcome to your AI-powered pediatric medical assistant! This chatbot uses advanced medical AI (BioGPT)
|
| 119 |
+
to provide evidence-based information about children's health and medical conditions.
|
| 120 |
+
|
| 121 |
+
**⚠️ Important Disclaimer:** This tool provides educational information only.
|
| 122 |
+
Always consult qualified healthcare professionals for medical diagnosis, treatment, and personalized advice.
|
| 123 |
+
"""
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
# Display startup status
|
| 127 |
+
gr.Markdown(f"**System Status:** {startup_status}")
|
| 128 |
+
|
| 129 |
+
# Chat interface
|
| 130 |
+
with gr.Row():
|
| 131 |
+
with gr.Column(scale=4):
|
| 132 |
+
chatbot_ui = gr.Chatbot(
|
| 133 |
+
label="💬 Chat with Medical AI",
|
| 134 |
+
height=500,
|
| 135 |
+
show_label=True,
|
| 136 |
+
avatar_images=("👤", "🤖")
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
with gr.Row():
|
| 140 |
+
user_input = gr.Textbox(
|
| 141 |
+
placeholder="Ask a pediatric health question... (e.g., 'What causes fever in children?')",
|
| 142 |
+
lines=2,
|
| 143 |
+
max_lines=5,
|
| 144 |
+
show_label=False,
|
| 145 |
+
scale=4
|
| 146 |
+
)
|
| 147 |
+
submit_btn = gr.Button("Send 📤", variant="primary", scale=1)
|
| 148 |
+
|
| 149 |
+
with gr.Column(scale=1):
|
| 150 |
+
gr.Markdown(
|
| 151 |
+
"""
|
| 152 |
+
### 💡 Example Questions:
|
| 153 |
+
|
| 154 |
+
- "What causes fever in children?"
|
| 155 |
+
- "How to treat a child's cough?"
|
| 156 |
+
- "When should I call the doctor?"
|
| 157 |
+
- "What are signs of dehydration?"
|
| 158 |
+
- "How to prevent common infections?"
|
| 159 |
+
|
| 160 |
+
### 🔧 System Info:
|
| 161 |
+
- **Model:** BioGPT (Medical AI)
|
| 162 |
+
- **Specialization:** Pediatric Medicine
|
| 163 |
+
- **Search:** Vector + Keyword
|
| 164 |
+
"""
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
# Event handlers
|
| 168 |
+
def submit_message(user_msg, history):
|
| 169 |
+
return generate_response(user_msg, history)
|
| 170 |
+
|
| 171 |
+
# Connect events
|
| 172 |
+
user_input.submit(
|
| 173 |
+
fn=submit_message,
|
| 174 |
+
inputs=[user_input, chatbot_ui],
|
| 175 |
+
outputs=[chatbot_ui, user_input],
|
| 176 |
+
show_progress=True
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
submit_btn.click(
|
| 180 |
+
fn=submit_message,
|
| 181 |
+
inputs=[user_input, chatbot_ui],
|
| 182 |
+
outputs=[chatbot_ui, user_input],
|
| 183 |
+
show_progress=True
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
# Footer
|
| 187 |
+
gr.Markdown(
|
| 188 |
+
"""
|
| 189 |
+
---
|
| 190 |
+
**🏥 Medical AI Assistant** | Powered by BioGPT | For Educational Purposes Only
|
| 191 |
+
|
| 192 |
+
**Remember:** Always consult healthcare professionals for medical emergencies and personalized medical advice.
|
| 193 |
+
"""
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
# Launch configuration for Hugging Face Spaces
|
| 197 |
+
if __name__ == "__main__":
|
| 198 |
+
# For Hugging Face Spaces deployment
|
| 199 |
+
demo.launch(
|
| 200 |
+
server_name="0.0.0.0", # Required for HF Spaces
|
| 201 |
+
server_port=7860, # Default port for HF Spaces
|
| 202 |
+
show_error=True # Show errors for debugging
|
| 203 |
+
)
|
medical_chatbot.py
ADDED
|
@@ -0,0 +1,730 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
| 10 |
+
BitsAndBytesConfig
|
| 11 |
+
)
|
| 12 |
+
from sentence_transformers import SentenceTransformer
|
| 13 |
+
from typing import List, Dict, Optional
|
| 14 |
+
import time
|
| 15 |
+
from datetime import datetime
|
| 16 |
+
|
| 17 |
+
# Suppress warnings for cleaner output
|
| 18 |
+
warnings.filterwarnings('ignore')
|
| 19 |
+
|
| 20 |
+
class ColabBioGPTChatbot:
|
| 21 |
+
def __init__(self, use_gpu=True, use_8bit=True):
|
| 22 |
+
"""Initialize BioGPT chatbot optimized for Hugging Face Spaces"""
|
| 23 |
+
print("🏥 Initializing Medical Chatbot...")
|
| 24 |
+
self.use_gpu = use_gpu
|
| 25 |
+
self.use_8bit = use_8bit
|
| 26 |
+
self.device = "cuda" if torch.cuda.is_available() and use_gpu else "cpu"
|
| 27 |
+
print(f"🖥️ Using device: {self.device}")
|
| 28 |
+
|
| 29 |
+
self.tokenizer = None
|
| 30 |
+
self.model = None
|
| 31 |
+
self.knowledge_chunks = []
|
| 32 |
+
self.conversation_history = []
|
| 33 |
+
self.embedding_model = None
|
| 34 |
+
self.faiss_index = None
|
| 35 |
+
self.faiss_ready = False
|
| 36 |
+
self.use_embeddings = True
|
| 37 |
+
|
| 38 |
+
# Initialize components
|
| 39 |
+
self.setup_biogpt()
|
| 40 |
+
self.load_sentence_transformer()
|
| 41 |
+
|
| 42 |
+
def setup_biogpt(self):
|
| 43 |
+
"""Setup BioGPT model with fallback to base BioGPT if Large fails"""
|
| 44 |
+
print("🧠 Loading BioGPT model...")
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
# Try BioGPT-Large first
|
| 48 |
+
model_name = "microsoft/BioGPT-Large"
|
| 49 |
+
print(f"Attempting to load {model_name}...")
|
| 50 |
+
|
| 51 |
+
if self.use_8bit and self.device == "cuda":
|
| 52 |
+
quantization_config = BitsAndBytesConfig(
|
| 53 |
+
load_in_8bit=True,
|
| 54 |
+
llm_int8_threshold=6.0,
|
| 55 |
+
llm_int8_has_fp16_weight=False,
|
| 56 |
+
)
|
| 57 |
+
else:
|
| 58 |
+
quantization_config = None
|
| 59 |
+
|
| 60 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 61 |
+
if self.tokenizer.pad_token is None:
|
| 62 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 63 |
+
|
| 64 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 65 |
+
model_name,
|
| 66 |
+
quantization_config=quantization_config,
|
| 67 |
+
torch_dtype=torch.float16 if self.device == "cuda" else torch.float32,
|
| 68 |
+
device_map="auto" if self.device == "cuda" else None,
|
| 69 |
+
trust_remote_code=True,
|
| 70 |
+
low_cpu_mem_usage=True
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
if self.device == "cuda" and quantization_config is None:
|
| 74 |
+
self.model = self.model.to(self.device)
|
| 75 |
+
|
| 76 |
+
print("✅ BioGPT-Large loaded successfully!")
|
| 77 |
+
|
| 78 |
+
except Exception as e:
|
| 79 |
+
print(f"❌ BioGPT-Large loading failed: {e}")
|
| 80 |
+
print("🔁 Falling back to base BioGPT...")
|
| 81 |
+
self.setup_fallback_biogpt()
|
| 82 |
+
|
| 83 |
+
def setup_fallback_biogpt(self):
|
| 84 |
+
"""Fallback to microsoft/BioGPT if BioGPT-Large fails"""
|
| 85 |
+
try:
|
| 86 |
+
model_name = "microsoft/BioGPT"
|
| 87 |
+
print(f"Loading fallback model: {model_name}")
|
| 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 |
+
torch_dtype=torch.float32,
|
| 96 |
+
trust_remote_code=True,
|
| 97 |
+
low_cpu_mem_usage=True
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
if self.device == "cuda":
|
| 101 |
+
self.model = self.model.to(self.device)
|
| 102 |
+
|
| 103 |
+
print("✅ Base BioGPT model loaded successfully!")
|
| 104 |
+
|
| 105 |
+
except Exception as e:
|
| 106 |
+
print(f"❌ Failed to load fallback BioGPT: {e}")
|
| 107 |
+
self.model = None
|
| 108 |
+
self.tokenizer = None
|
| 109 |
+
|
| 110 |
+
def load_sentence_transformer(self):
|
| 111 |
+
"""Load sentence transformer for embeddings"""
|
| 112 |
+
try:
|
| 113 |
+
print("🔮 Loading sentence transformer...")
|
| 114 |
+
self.embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 115 |
+
|
| 116 |
+
# Initialize FAISS index (will be populated when data is loaded)
|
| 117 |
+
embedding_dim = 384 # Dimension for all-MiniLM-L6-v2
|
| 118 |
+
self.faiss_index = faiss.IndexFlatL2(embedding_dim)
|
| 119 |
+
self.faiss_ready = True
|
| 120 |
+
print("✅ Sentence transformer and FAISS index ready!")
|
| 121 |
+
|
| 122 |
+
except Exception as e:
|
| 123 |
+
print(f"❌ Failed to load sentence transformer: {e}")
|
| 124 |
+
self.use_embeddings = False
|
| 125 |
+
self.faiss_ready = False
|
| 126 |
+
|
| 127 |
+
def load_medical_data(self, file_path):
|
| 128 |
+
"""Load and process medical data"""
|
| 129 |
+
print(f"📖 Loading medical data from {file_path}...")
|
| 130 |
+
|
| 131 |
+
try:
|
| 132 |
+
if not os.path.exists(file_path):
|
| 133 |
+
raise FileNotFoundError(f"File {file_path} not found")
|
| 134 |
+
|
| 135 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 136 |
+
text = f.read()
|
| 137 |
+
print(f"📄 File loaded: {len(text):,} characters")
|
| 138 |
+
|
| 139 |
+
except Exception as e:
|
| 140 |
+
print(f"❌ Error loading file: {e}")
|
| 141 |
+
raise ValueError(f"Failed to load medical data: {e}")
|
| 142 |
+
|
| 143 |
+
# Create chunks
|
| 144 |
+
print("📝 Creating medical chunks...")
|
| 145 |
+
chunks = self.create_medical_chunks(text)
|
| 146 |
+
print(f"📋 Created {len(chunks)} medical chunks")
|
| 147 |
+
|
| 148 |
+
self.knowledge_chunks = chunks
|
| 149 |
+
|
| 150 |
+
# Generate embeddings if available
|
| 151 |
+
if self.use_embeddings and self.embedding_model and self.faiss_ready:
|
| 152 |
+
try:
|
| 153 |
+
self.generate_embeddings_with_progress(chunks)
|
| 154 |
+
print("✅ Medical data loaded with embeddings!")
|
| 155 |
+
except Exception as e:
|
| 156 |
+
print(f"⚠️ Embedding generation failed: {e}")
|
| 157 |
+
print("✅ Medical data loaded (keyword search mode)")
|
| 158 |
+
else:
|
| 159 |
+
print("✅ Medical data loaded (keyword search mode)")
|
| 160 |
+
|
| 161 |
+
def create_medical_chunks(self, text: str, chunk_size: int = 400) -> List[Dict]:
|
| 162 |
+
"""Create medically-optimized text chunks"""
|
| 163 |
+
chunks = []
|
| 164 |
+
|
| 165 |
+
# Split by paragraphs first
|
| 166 |
+
paragraphs = [p.strip() for p in text.split('\n\n') if len(p.strip()) > 50]
|
| 167 |
+
|
| 168 |
+
chunk_id = 0
|
| 169 |
+
for paragraph in paragraphs:
|
| 170 |
+
if len(paragraph.split()) <= chunk_size:
|
| 171 |
+
chunks.append({
|
| 172 |
+
'id': chunk_id,
|
| 173 |
+
'text': paragraph,
|
| 174 |
+
'medical_focus': self.identify_medical_focus(paragraph)
|
| 175 |
+
})
|
| 176 |
+
chunk_id += 1
|
| 177 |
+
else:
|
| 178 |
+
# Split large paragraphs by sentences
|
| 179 |
+
sentences = re.split(r'[.!?]+', paragraph)
|
| 180 |
+
current_chunk = ""
|
| 181 |
+
|
| 182 |
+
for sentence in sentences:
|
| 183 |
+
sentence = sentence.strip()
|
| 184 |
+
if not sentence:
|
| 185 |
+
continue
|
| 186 |
+
|
| 187 |
+
if len(current_chunk.split()) + len(sentence.split()) <= chunk_size:
|
| 188 |
+
current_chunk += sentence + ". "
|
| 189 |
+
else:
|
| 190 |
+
if current_chunk.strip():
|
| 191 |
+
chunks.append({
|
| 192 |
+
'id': chunk_id,
|
| 193 |
+
'text': current_chunk.strip(),
|
| 194 |
+
'medical_focus': self.identify_medical_focus(current_chunk)
|
| 195 |
+
})
|
| 196 |
+
chunk_id += 1
|
| 197 |
+
current_chunk = sentence + ". "
|
| 198 |
+
|
| 199 |
+
if current_chunk.strip():
|
| 200 |
+
chunks.append({
|
| 201 |
+
'id': chunk_id,
|
| 202 |
+
'text': current_chunk.strip(),
|
| 203 |
+
'medical_focus': self.identify_medical_focus(current_chunk)
|
| 204 |
+
})
|
| 205 |
+
chunk_id += 1
|
| 206 |
+
|
| 207 |
+
return chunks
|
| 208 |
+
|
| 209 |
+
def identify_medical_focus(self, text: str) -> str:
|
| 210 |
+
"""Identify the medical focus of a text chunk"""
|
| 211 |
+
text_lower = text.lower()
|
| 212 |
+
|
| 213 |
+
categories = {
|
| 214 |
+
'pediatric_symptoms': ['fever', 'cough', 'rash', 'vomiting', 'diarrhea'],
|
| 215 |
+
'treatments': ['treatment', 'therapy', 'medication', 'antibiotics'],
|
| 216 |
+
'diagnosis': ['diagnosis', 'diagnostic', 'symptoms', 'signs'],
|
| 217 |
+
'emergency': ['emergency', 'urgent', 'serious', 'hospital'],
|
| 218 |
+
'prevention': ['prevention', 'vaccine', 'immunization', 'avoid']
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
for category, keywords in categories.items():
|
| 222 |
+
if any(keyword in text_lower for keyword in keywords):
|
| 223 |
+
return category
|
| 224 |
+
|
| 225 |
+
return 'general_medical'
|
| 226 |
+
|
| 227 |
+
def generate_embeddings_with_progress(self, chunks: List[Dict]):
|
| 228 |
+
"""Generate embeddings and add to FAISS index"""
|
| 229 |
+
print("🔮 Generating embeddings...")
|
| 230 |
+
|
| 231 |
+
try:
|
| 232 |
+
texts = [chunk['text'] for chunk in chunks]
|
| 233 |
+
|
| 234 |
+
# Generate embeddings in batches
|
| 235 |
+
batch_size = 32
|
| 236 |
+
all_embeddings = []
|
| 237 |
+
|
| 238 |
+
for i in range(0, len(texts), batch_size):
|
| 239 |
+
batch_texts = texts[i:i+batch_size]
|
| 240 |
+
batch_embeddings = self.embedding_model.encode(batch_texts, show_progress_bar=False)
|
| 241 |
+
all_embeddings.extend(batch_embeddings)
|
| 242 |
+
|
| 243 |
+
progress = min(i + batch_size, len(texts))
|
| 244 |
+
print(f" Progress: {progress}/{len(texts)} chunks processed", end='\r')
|
| 245 |
+
|
| 246 |
+
print(f"\n ✅ Generated embeddings for {len(texts)} chunks")
|
| 247 |
+
|
| 248 |
+
# Add to FAISS index
|
| 249 |
+
embeddings_array = np.array(all_embeddings).astype('float32')
|
| 250 |
+
self.faiss_index.add(embeddings_array)
|
| 251 |
+
print("✅ Embeddings added to FAISS index!")
|
| 252 |
+
|
| 253 |
+
except Exception as e:
|
| 254 |
+
print(f"❌ Embedding generation failed: {e}")
|
| 255 |
+
raise
|
| 256 |
+
|
| 257 |
+
def retrieve_medical_context(self, query: str, n_results: int = 3) -> List[str]:
|
| 258 |
+
"""Retrieve relevant medical context"""
|
| 259 |
+
if self.use_embeddings and self.embedding_model and self.faiss_ready and self.faiss_index.ntotal > 0:
|
| 260 |
+
try:
|
| 261 |
+
# Generate query embedding
|
| 262 |
+
query_embedding = self.embedding_model.encode([query])
|
| 263 |
+
|
| 264 |
+
# Search FAISS index
|
| 265 |
+
distances, indices = self.faiss_index.search(
|
| 266 |
+
np.array(query_embedding).astype('float32'),
|
| 267 |
+
min(n_results, self.faiss_index.ntotal)
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
# Get relevant chunks
|
| 271 |
+
context_chunks = []
|
| 272 |
+
for idx in indices[0]:
|
| 273 |
+
if idx != -1 and idx < len(self.knowledge_chunks):
|
| 274 |
+
context_chunks.append(self.knowledge_chunks[idx]['text'])
|
| 275 |
+
|
| 276 |
+
if context_chunks:
|
| 277 |
+
return context_chunks
|
| 278 |
+
|
| 279 |
+
except Exception as e:
|
| 280 |
+
print(f"⚠️ Embedding search failed: {e}")
|
| 281 |
+
|
| 282 |
+
# Fallback to keyword search
|
| 283 |
+
return self.keyword_search_medical(query, n_results)
|
| 284 |
+
|
| 285 |
+
def keyword_search_medical(self, query: str, n_results: int) -> List[str]:
|
| 286 |
+
"""Medical-focused keyword search"""
|
| 287 |
+
if not self.knowledge_chunks:
|
| 288 |
+
return []
|
| 289 |
+
|
| 290 |
+
query_words = set(query.lower().split())
|
| 291 |
+
chunk_scores = []
|
| 292 |
+
|
| 293 |
+
for chunk_info in self.knowledge_chunks:
|
| 294 |
+
chunk_text = chunk_info['text']
|
| 295 |
+
chunk_words = set(chunk_text.lower().split())
|
| 296 |
+
|
| 297 |
+
# Calculate relevance score
|
| 298 |
+
word_overlap = len(query_words.intersection(chunk_words))
|
| 299 |
+
base_score = word_overlap / len(query_words) if query_words else 0
|
| 300 |
+
|
| 301 |
+
# Boost medical content
|
| 302 |
+
medical_boost = 0
|
| 303 |
+
if chunk_info.get('medical_focus') in ['pediatric_symptoms', 'treatments', 'diagnosis']:
|
| 304 |
+
medical_boost = 0.3
|
| 305 |
+
|
| 306 |
+
final_score = base_score + medical_boost
|
| 307 |
+
|
| 308 |
+
if final_score > 0:
|
| 309 |
+
chunk_scores.append((final_score, chunk_text))
|
| 310 |
+
|
| 311 |
+
# Return top matches
|
| 312 |
+
chunk_scores.sort(reverse=True)
|
| 313 |
+
return [chunk for _, chunk in chunk_scores[:n_results]]
|
| 314 |
+
|
| 315 |
+
def generate_biogpt_response(self, context: str, query: str) -> str:
|
| 316 |
+
"""Generate medical response using context directly (BioGPT bypass)"""
|
| 317 |
+
# BioGPT is giving poor responses, so use the retrieved context directly
|
| 318 |
+
return self.create_context_based_response(context, query)
|
| 319 |
+
|
| 320 |
+
def create_context_based_response(self, context: str, query: str) -> str:
|
| 321 |
+
"""Create response directly from medical context"""
|
| 322 |
+
if not context:
|
| 323 |
+
return "I don't have specific information about this topic in my medical database."
|
| 324 |
+
|
| 325 |
+
# Split context into sentences
|
| 326 |
+
sentences = [s.strip() + '.' for s in context.split('.') if len(s.strip()) > 15]
|
| 327 |
+
|
| 328 |
+
# Find sentences most relevant to the query
|
| 329 |
+
query_words = set(query.lower().split())
|
| 330 |
+
scored_sentences = []
|
| 331 |
+
|
| 332 |
+
for sentence in sentences[:20]: # Increased from 15 to 20
|
| 333 |
+
sentence_words = set(sentence.lower().split())
|
| 334 |
+
# Score based on word overlap
|
| 335 |
+
score = len(query_words.intersection(sentence_words))
|
| 336 |
+
if score > 0:
|
| 337 |
+
scored_sentences.append((score, sentence))
|
| 338 |
+
|
| 339 |
+
# Sort by relevance and take top sentences
|
| 340 |
+
scored_sentences.sort(reverse=True)
|
| 341 |
+
|
| 342 |
+
if scored_sentences:
|
| 343 |
+
# Take top 3-4 most relevant sentences for better coverage
|
| 344 |
+
response_sentences = [sent for _, sent in scored_sentences[:4]]
|
| 345 |
+
response = ' '.join(response_sentences)
|
| 346 |
+
else:
|
| 347 |
+
# Fallback to first few sentences
|
| 348 |
+
response = ' '.join(sentences[:3])
|
| 349 |
+
|
| 350 |
+
# Clean up the response
|
| 351 |
+
response = re.sub(r'\s+', ' ', response).strip()
|
| 352 |
+
|
| 353 |
+
return response[:500] + '...' if len(response) > 500 else response # Increased from 400
|
| 354 |
+
|
| 355 |
+
def clean_medical_response(self, response: str) -> str:
|
| 356 |
+
"""Clean and format medical response"""
|
| 357 |
+
# Remove training artifacts and unwanted symbols
|
| 358 |
+
response = re.sub(r'<[^>]*>', '', response) # Remove HTML-like tags
|
| 359 |
+
response = re.sub(r'▃+', '', response) # Remove block symbols
|
| 360 |
+
response = re.sub(r'FREETEXT|INTRO|/FREETEXT|/INTRO', '', response) # Remove training markers
|
| 361 |
+
response = re.sub(r'\s+', ' ', response) # Clean up whitespace
|
| 362 |
+
response = response.strip()
|
| 363 |
+
|
| 364 |
+
# Split into sentences and keep only complete, relevant ones
|
| 365 |
+
sentences = re.split(r'[.!?]+', response)
|
| 366 |
+
clean_sentences = []
|
| 367 |
+
|
| 368 |
+
for sentence in sentences:
|
| 369 |
+
sentence = sentence.strip()
|
| 370 |
+
# Skip very short sentences and those with artifacts
|
| 371 |
+
if len(sentence) > 15 and not any(artifact in sentence.lower() for artifact in ['▃', '<', '>', 'freetext']):
|
| 372 |
+
clean_sentences.append(sentence)
|
| 373 |
+
if len(clean_sentences) >= 2: # Limit to 2 good sentences
|
| 374 |
+
break
|
| 375 |
+
|
| 376 |
+
if clean_sentences:
|
| 377 |
+
cleaned = '. '.join(clean_sentences) + '.'
|
| 378 |
+
else:
|
| 379 |
+
# Fallback to first 150 characters if no good sentences found
|
| 380 |
+
cleaned = response[:150].strip()
|
| 381 |
+
if cleaned and not cleaned.endswith('.'):
|
| 382 |
+
cleaned += '.'
|
| 383 |
+
|
| 384 |
+
return cleaned
|
| 385 |
+
|
| 386 |
+
def fallback_response(self, context: str, query: str) -> str:
|
| 387 |
+
"""Fallback response when BioGPT fails"""
|
| 388 |
+
sentences = [s.strip() for s in context.split('.') if len(s.strip()) > 20]
|
| 389 |
+
|
| 390 |
+
if sentences:
|
| 391 |
+
response = sentences[0] + '.'
|
| 392 |
+
if len(sentences) > 1:
|
| 393 |
+
response += ' ' + sentences[1] + '.'
|
| 394 |
+
else:
|
| 395 |
+
response = context[:300] + '...'
|
| 396 |
+
|
| 397 |
+
return response
|
| 398 |
+
|
| 399 |
+
def handle_conversational_interactions(self, query: str) -> Optional[str]:
|
| 400 |
+
"""Handle conversational interactions"""
|
| 401 |
+
query_lower = query.lower().strip()
|
| 402 |
+
|
| 403 |
+
# Only match very specific greeting patterns (must be standalone)
|
| 404 |
+
if re.match(r'^\s*(hello|hi|hey)\s*$', query_lower):
|
| 405 |
+
return "👋 Hello! I'm your pediatric medical AI assistant. How can I help you with medical questions today?"
|
| 406 |
+
|
| 407 |
+
if re.match(r'^\s*(good morning|good afternoon|good evening)\s*$', query_lower):
|
| 408 |
+
return "👋 Hello! I'm your pediatric medical AI assistant. How can I help you with medical questions today?"
|
| 409 |
+
|
| 410 |
+
# Only match very specific thanks patterns (must be standalone)
|
| 411 |
+
if re.match(r'^\s*(thank you|thanks|thx)\s*$', query_lower):
|
| 412 |
+
return "🙏 You're welcome! I'm glad I could help. Remember to consult healthcare professionals for medical decisions. What else can I help you with?"
|
| 413 |
+
|
| 414 |
+
# Only match very specific goodbye patterns (must be standalone)
|
| 415 |
+
if re.match(r'^\s*(bye|goodbye)\s*$', query_lower):
|
| 416 |
+
return "👋 Goodbye! Take care and remember to consult healthcare professionals for any medical concerns. Stay healthy!"
|
| 417 |
+
|
| 418 |
+
return None
|
| 419 |
+
|
| 420 |
+
def chat(self, query: str) -> str:
|
| 421 |
+
"""Main chat function"""
|
| 422 |
+
if not query.strip():
|
| 423 |
+
return "Hello! I'm your pediatric medical AI assistant. How can I help you today?"
|
| 424 |
+
|
| 425 |
+
# Handle conversational interactions
|
| 426 |
+
conversational_response = self.handle_conversational_interactions(query)
|
| 427 |
+
if conversational_response:
|
| 428 |
+
return conversational_response
|
| 429 |
+
|
| 430 |
+
if not self.knowledge_chunks:
|
| 431 |
+
return "Please load medical data first to access the medical knowledge base."
|
| 432 |
+
|
| 433 |
+
if not self.model or not self.tokenizer:
|
| 434 |
+
return "Medical model not available. Please check the setup and try again."
|
| 435 |
+
|
| 436 |
+
# Retrieve context
|
| 437 |
+
context = self.retrieve_medical_context(query)
|
| 438 |
+
|
| 439 |
+
if not context:
|
| 440 |
+
return "I don't have specific information about this topic in my medical database. Please consult with a healthcare professional for personalized medical advice."
|
| 441 |
+
|
| 442 |
+
# Generate response
|
| 443 |
+
main_context = '\n\n'.join(context)
|
| 444 |
+
response = self.generate_biogpt_response(main_context, query)
|
| 445 |
+
|
| 446 |
+
# Format final response
|
| 447 |
+
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."
|
| 448 |
+
|
| 449 |
+
return final_response,
|
| 450 |
+
r'^\s*(good morning|good afternoon|good evening)\s*$',
|
| 451 |
+
|
| 452 |
+
def chat(self, query: str) -> str:
|
| 453 |
+
"""Main chat function"""
|
| 454 |
+
if not query.strip():
|
| 455 |
+
return "Hello! I'm your pediatric medical AI assistant. How can I help you today?"
|
| 456 |
+
|
| 457 |
+
# Handle conversational interactions
|
| 458 |
+
conversational_response = self.handle_conversational_interactions(query)
|
| 459 |
+
if conversational_response:
|
| 460 |
+
return conversational_response
|
| 461 |
+
|
| 462 |
+
if not self.knowledge_chunks:
|
| 463 |
+
return "Please load medical data first to access the medical knowledge base."
|
| 464 |
+
|
| 465 |
+
if not self.model or not self.tokenizer:
|
| 466 |
+
return "Medical model not available. Please check the setup and try again."
|
| 467 |
+
|
| 468 |
+
# Retrieve context
|
| 469 |
+
context = self.retrieve_medical_context(query)
|
| 470 |
+
|
| 471 |
+
if not context:
|
| 472 |
+
return "I don't have specific information about this topic in my medical database. Please consult with a healthcare professional for personalized medical advice."
|
| 473 |
+
|
| 474 |
+
# Generate response
|
| 475 |
+
main_context = '\n\n'.join(context)
|
| 476 |
+
response = self.generate_biogpt_response(main_context, query)
|
| 477 |
+
|
| 478 |
+
# Format final response
|
| 479 |
+
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."
|
| 480 |
+
|
| 481 |
+
return final_response,
|
| 482 |
+
r'^\s*(hi there|hello there)\s*$'
|
| 483 |
+
|
| 484 |
+
def chat(self, query: str) -> str:
|
| 485 |
+
"""Main chat function"""
|
| 486 |
+
if not query.strip():
|
| 487 |
+
return "Hello! I'm your pediatric medical AI assistant. How can I help you today?"
|
| 488 |
+
|
| 489 |
+
# Handle conversational interactions
|
| 490 |
+
conversational_response = self.handle_conversational_interactions(query)
|
| 491 |
+
if conversational_response:
|
| 492 |
+
return conversational_response
|
| 493 |
+
|
| 494 |
+
if not self.knowledge_chunks:
|
| 495 |
+
return "Please load medical data first to access the medical knowledge base."
|
| 496 |
+
|
| 497 |
+
if not self.model or not self.tokenizer:
|
| 498 |
+
return "Medical model not available. Please check the setup and try again."
|
| 499 |
+
|
| 500 |
+
# Retrieve context
|
| 501 |
+
context = self.retrieve_medical_context(query)
|
| 502 |
+
|
| 503 |
+
if not context:
|
| 504 |
+
return "I don't have specific information about this topic in my medical database. Please consult with a healthcare professional for personalized medical advice."
|
| 505 |
+
|
| 506 |
+
# Generate response
|
| 507 |
+
main_context = '\n\n'.join(context)
|
| 508 |
+
response = self.generate_biogpt_response(main_context, query)
|
| 509 |
+
|
| 510 |
+
# Format final response
|
| 511 |
+
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."
|
| 512 |
+
|
| 513 |
+
return final_response
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
for pattern in greeting_patterns:
|
| 517 |
+
if re.match(pattern, query_lower):
|
| 518 |
+
return "👋 Hello! I'm your pediatric medical AI assistant. How can I help you with medical questions today?"
|
| 519 |
+
|
| 520 |
+
# Only match very specific thanks patterns (must be standalone)
|
| 521 |
+
thanks_patterns = [
|
| 522 |
+
r'^\s*(thank you|thanks|thx)\s*$'
|
| 523 |
+
]
|
| 524 |
+
|
| 525 |
+
def chat(self, query: str) -> str:
|
| 526 |
+
"""Main chat function"""
|
| 527 |
+
if not query.strip():
|
| 528 |
+
return "Hello! I'm your pediatric medical AI assistant. How can I help you today?"
|
| 529 |
+
|
| 530 |
+
# Handle conversational interactions
|
| 531 |
+
conversational_response = self.handle_conversational_interactions(query)
|
| 532 |
+
if conversational_response:
|
| 533 |
+
return conversational_response
|
| 534 |
+
|
| 535 |
+
if not self.knowledge_chunks:
|
| 536 |
+
return "Please load medical data first to access the medical knowledge base."
|
| 537 |
+
|
| 538 |
+
if not self.model or not self.tokenizer:
|
| 539 |
+
return "Medical model not available. Please check the setup and try again."
|
| 540 |
+
|
| 541 |
+
# Retrieve context
|
| 542 |
+
context = self.retrieve_medical_context(query)
|
| 543 |
+
|
| 544 |
+
if not context:
|
| 545 |
+
return "I don't have specific information about this topic in my medical database. Please consult with a healthcare professional for personalized medical advice."
|
| 546 |
+
|
| 547 |
+
# Generate response
|
| 548 |
+
main_context = '\n\n'.join(context)
|
| 549 |
+
response = self.generate_biogpt_response(main_context, query)
|
| 550 |
+
|
| 551 |
+
# Format final response
|
| 552 |
+
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."
|
| 553 |
+
|
| 554 |
+
return final_response,
|
| 555 |
+
r'^\s*(thank you so much|thanks a lot)\s*$'
|
| 556 |
+
|
| 557 |
+
def chat(self, query: str) -> str:
|
| 558 |
+
"""Main chat function"""
|
| 559 |
+
if not query.strip():
|
| 560 |
+
return "Hello! I'm your pediatric medical AI assistant. How can I help you today?"
|
| 561 |
+
|
| 562 |
+
# Handle conversational interactions
|
| 563 |
+
conversational_response = self.handle_conversational_interactions(query)
|
| 564 |
+
if conversational_response:
|
| 565 |
+
return conversational_response
|
| 566 |
+
|
| 567 |
+
if not self.knowledge_chunks:
|
| 568 |
+
return "Please load medical data first to access the medical knowledge base."
|
| 569 |
+
|
| 570 |
+
if not self.model or not self.tokenizer:
|
| 571 |
+
return "Medical model not available. Please check the setup and try again."
|
| 572 |
+
|
| 573 |
+
# Retrieve context
|
| 574 |
+
context = self.retrieve_medical_context(query)
|
| 575 |
+
|
| 576 |
+
if not context:
|
| 577 |
+
return "I don't have specific information about this topic in my medical database. Please consult with a healthcare professional for personalized medical advice."
|
| 578 |
+
|
| 579 |
+
# Generate response
|
| 580 |
+
main_context = '\n\n'.join(context)
|
| 581 |
+
response = self.generate_biogpt_response(main_context, query)
|
| 582 |
+
|
| 583 |
+
# Format final response
|
| 584 |
+
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."
|
| 585 |
+
|
| 586 |
+
return final_response
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
for pattern in thanks_patterns:
|
| 590 |
+
if re.match(pattern, query_lower):
|
| 591 |
+
return "🙏 You're welcome! I'm glad I could help. Remember to consult healthcare professionals for medical decisions. What else can I help you with?"
|
| 592 |
+
|
| 593 |
+
# Only match very specific goodbye patterns (must be standalone)
|
| 594 |
+
goodbye_patterns = [
|
| 595 |
+
r'^\s*(bye|goodbye)\s*$'
|
| 596 |
+
]
|
| 597 |
+
|
| 598 |
+
def chat(self, query: str) -> str:
|
| 599 |
+
"""Main chat function"""
|
| 600 |
+
if not query.strip():
|
| 601 |
+
return "Hello! I'm your pediatric medical AI assistant. How can I help you today?"
|
| 602 |
+
|
| 603 |
+
# Handle conversational interactions
|
| 604 |
+
conversational_response = self.handle_conversational_interactions(query)
|
| 605 |
+
if conversational_response:
|
| 606 |
+
return conversational_response
|
| 607 |
+
|
| 608 |
+
if not self.knowledge_chunks:
|
| 609 |
+
return "Please load medical data first to access the medical knowledge base."
|
| 610 |
+
|
| 611 |
+
if not self.model or not self.tokenizer:
|
| 612 |
+
return "Medical model not available. Please check the setup and try again."
|
| 613 |
+
|
| 614 |
+
# Retrieve context
|
| 615 |
+
context = self.retrieve_medical_context(query)
|
| 616 |
+
|
| 617 |
+
if not context:
|
| 618 |
+
return "I don't have specific information about this topic in my medical database. Please consult with a healthcare professional for personalized medical advice."
|
| 619 |
+
|
| 620 |
+
# Generate response
|
| 621 |
+
main_context = '\n\n'.join(context)
|
| 622 |
+
response = self.generate_biogpt_response(main_context, query)
|
| 623 |
+
|
| 624 |
+
# Format final response
|
| 625 |
+
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."
|
| 626 |
+
|
| 627 |
+
return final_response,
|
| 628 |
+
r'^\s*(see you later|see ya)\s*$'
|
| 629 |
+
|
| 630 |
+
def chat(self, query: str) -> str:
|
| 631 |
+
"""Main chat function"""
|
| 632 |
+
if not query.strip():
|
| 633 |
+
return "Hello! I'm your pediatric medical AI assistant. How can I help you today?"
|
| 634 |
+
|
| 635 |
+
# Handle conversational interactions
|
| 636 |
+
conversational_response = self.handle_conversational_interactions(query)
|
| 637 |
+
if conversational_response:
|
| 638 |
+
return conversational_response
|
| 639 |
+
|
| 640 |
+
if not self.knowledge_chunks:
|
| 641 |
+
return "Please load medical data first to access the medical knowledge base."
|
| 642 |
+
|
| 643 |
+
if not self.model or not self.tokenizer:
|
| 644 |
+
return "Medical model not available. Please check the setup and try again."
|
| 645 |
+
|
| 646 |
+
# Retrieve context
|
| 647 |
+
context = self.retrieve_medical_context(query)
|
| 648 |
+
|
| 649 |
+
if not context:
|
| 650 |
+
return "I don't have specific information about this topic in my medical database. Please consult with a healthcare professional for personalized medical advice."
|
| 651 |
+
|
| 652 |
+
# Generate response
|
| 653 |
+
main_context = '\n\n'.join(context)
|
| 654 |
+
response = self.generate_biogpt_response(main_context, query)
|
| 655 |
+
|
| 656 |
+
# Format final response
|
| 657 |
+
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."
|
| 658 |
+
|
| 659 |
+
return final_response,
|
| 660 |
+
r'^\s*(have a good day|take care)\s*$'
|
| 661 |
+
|
| 662 |
+
def chat(self, query: str) -> str:
|
| 663 |
+
"""Main chat function"""
|
| 664 |
+
if not query.strip():
|
| 665 |
+
return "Hello! I'm your pediatric medical AI assistant. How can I help you today?"
|
| 666 |
+
|
| 667 |
+
# Handle conversational interactions
|
| 668 |
+
conversational_response = self.handle_conversational_interactions(query)
|
| 669 |
+
if conversational_response:
|
| 670 |
+
return conversational_response
|
| 671 |
+
|
| 672 |
+
if not self.knowledge_chunks:
|
| 673 |
+
return "Please load medical data first to access the medical knowledge base."
|
| 674 |
+
|
| 675 |
+
if not self.model or not self.tokenizer:
|
| 676 |
+
return "Medical model not available. Please check the setup and try again."
|
| 677 |
+
|
| 678 |
+
# Retrieve context
|
| 679 |
+
context = self.retrieve_medical_context(query)
|
| 680 |
+
|
| 681 |
+
if not context:
|
| 682 |
+
return "I don't have specific information about this topic in my medical database. Please consult with a healthcare professional for personalized medical advice."
|
| 683 |
+
|
| 684 |
+
# Generate response
|
| 685 |
+
main_context = '\n\n'.join(context)
|
| 686 |
+
response = self.generate_biogpt_response(main_context, query)
|
| 687 |
+
|
| 688 |
+
# Format final response
|
| 689 |
+
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."
|
| 690 |
+
|
| 691 |
+
return final_response
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
for pattern in goodbye_patterns:
|
| 695 |
+
if re.match(pattern, query_lower):
|
| 696 |
+
return "👋 Goodbye! Take care and remember to consult healthcare professionals for any medical concerns. Stay healthy!"
|
| 697 |
+
|
| 698 |
+
return None
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
def chat(self, query: str) -> str:
|
| 702 |
+
"""Main chat function"""
|
| 703 |
+
if not query.strip():
|
| 704 |
+
return "Hello! I'm your pediatric medical AI assistant. How can I help you today?"
|
| 705 |
+
|
| 706 |
+
# Handle conversational interactions
|
| 707 |
+
conversational_response = self.handle_conversational_interactions(query)
|
| 708 |
+
if conversational_response:
|
| 709 |
+
return conversational_response
|
| 710 |
+
|
| 711 |
+
if not self.knowledge_chunks:
|
| 712 |
+
return "Please load medical data first to access the medical knowledge base."
|
| 713 |
+
|
| 714 |
+
if not self.model or not self.tokenizer:
|
| 715 |
+
return "Medical model not available. Please check the setup and try again."
|
| 716 |
+
|
| 717 |
+
# Retrieve context
|
| 718 |
+
context = self.retrieve_medical_context(query)
|
| 719 |
+
|
| 720 |
+
if not context:
|
| 721 |
+
return "I don't have specific information about this topic in my medical database. Please consult with a healthcare professional for personalized medical advice."
|
| 722 |
+
|
| 723 |
+
# Generate response
|
| 724 |
+
main_context = '\n\n'.join(context)
|
| 725 |
+
response = self.generate_biogpt_response(main_context, query)
|
| 726 |
+
|
| 727 |
+
# Format final response
|
| 728 |
+
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."
|
| 729 |
+
|
| 730 |
+
return final_response
|
requirements.txt
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Core ML and NLP libraries
|
| 2 |
+
torch>=2.0.0,<2.2.0
|
| 3 |
+
transformers>=4.30.0,<4.40.0
|
| 4 |
+
sentence-transformers>=2.2.0,<3.0.0
|
| 5 |
+
accelerate>=0.20.0,<0.25.0
|
| 6 |
+
|
| 7 |
+
# Quantization support (for GPU optimization)
|
| 8 |
+
bitsandbytes>=0.41.0,<0.43.0
|
| 9 |
+
|
| 10 |
+
# Vector search (CPU version for HF Spaces compatibility)
|
| 11 |
+
faiss-cpu>=1.7.4,<1.8.0
|
| 12 |
+
|
| 13 |
+
# Scientific computing
|
| 14 |
+
numpy>=1.21.0,<1.26.0
|
| 15 |
+
scipy>=1.9.0,<1.12.0
|
| 16 |
+
|
| 17 |
+
# Gradio for web interface (stable version)
|
| 18 |
+
gradio>=4.0.0,<5.0.0
|
| 19 |
+
|
| 20 |
+
# Essential utilities
|
| 21 |
+
tqdm>=4.64.0
|
| 22 |
+
requests>=2.28.0
|
| 23 |
+
packaging>=21.0
|
| 24 |
+
|
| 25 |
+
# Tokenization support
|
| 26 |
+
tokenizers>=0.13.0,<0.16.0
|
| 27 |
+
|
| 28 |
+
# System monitoring
|
| 29 |
+
psutil>=5.9.0
|
| 30 |
+
|
| 31 |
+
# Additional stability packages
|
| 32 |
+
safetensors>=0.3.0
|
| 33 |
+
huggingface-hub>=0.15.0
|
| 34 |
+
|
| 35 |
+
# Required for BioGPT tokenizer
|
| 36 |
+
sacremoses>=0.0.53
|