Spaces:
Sleeping
Sleeping
Delete app.py
Browse files
app.py
DELETED
@@ -1,902 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import re
|
3 |
-
import torch
|
4 |
-
import warnings
|
5 |
-
import numpy as np
|
6 |
-
import gradio as gr
|
7 |
-
from transformers import (
|
8 |
-
AutoTokenizer,
|
9 |
-
AutoModelForCausalLM,
|
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
|
18 |
-
warnings.filterwarnings('ignore')
|
19 |
-
|
20 |
-
class BioGPTMedicalChatbot:
|
21 |
-
def __init__(self):
|
22 |
-
"""Initialize BioGPT chatbot for Gradio deployment"""
|
23 |
-
print("🏥 Initializing BioGPT Pediatric Pulmonology Chatbot...")
|
24 |
-
|
25 |
-
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
26 |
-
self.use_8bit = torch.cuda.is_available()
|
27 |
-
|
28 |
-
print(f"🖥️ Using device: {self.device}")
|
29 |
-
|
30 |
-
# Setup components
|
31 |
-
self.setup_embeddings()
|
32 |
-
self.setup_biogpt()
|
33 |
-
|
34 |
-
# Knowledge base and conversation tracking
|
35 |
-
self.knowledge_chunks = []
|
36 |
-
self.conversation_history = []
|
37 |
-
|
38 |
-
# Load default medical knowledge first
|
39 |
-
self.load_default_medical_knowledge()
|
40 |
-
|
41 |
-
# Try to load your specific pediatric pulmonology data
|
42 |
-
self.load_pediatric_pulmonology_data()
|
43 |
-
|
44 |
-
print("✅ BioGPT Pediatric Pulmonology Chatbot ready!")
|
45 |
-
|
46 |
-
def load_pediatric_pulmonology_data(self):
|
47 |
-
"""Auto-load pediatric pulmonology data from uploaded file"""
|
48 |
-
pulmonology_files = [
|
49 |
-
'Pediatric_cleaned.txt',
|
50 |
-
'pediatric_cleaned.txt',
|
51 |
-
'Pediatric_Cleaned.txt',
|
52 |
-
'pediatric_pulmonology.txt',
|
53 |
-
'pulmonology_data.txt'
|
54 |
-
]
|
55 |
-
|
56 |
-
for filename in pulmonology_files:
|
57 |
-
if os.path.exists(filename):
|
58 |
-
print(f"📖 Found pediatric pulmonology data: {filename}")
|
59 |
-
try:
|
60 |
-
success = self.load_medical_data(filename)
|
61 |
-
if success:
|
62 |
-
print(f"✅ Successfully loaded {filename} with pulmonology data!")
|
63 |
-
print(f"📊 Total knowledge chunks: {len(self.knowledge_chunks)}")
|
64 |
-
return True
|
65 |
-
except Exception as e:
|
66 |
-
print(f"⚠️ Failed to load {filename}: {e}")
|
67 |
-
continue
|
68 |
-
|
69 |
-
print("⚠️ No pediatric pulmonology data file found.")
|
70 |
-
print(" Expected files: Pediatric_cleaned.txt")
|
71 |
-
print(" Using default pediatric knowledge only.")
|
72 |
-
print(f"📊 Current knowledge chunks: {len(self.knowledge_chunks)}")
|
73 |
-
return False
|
74 |
-
|
75 |
-
def load_medical_data(self, file_path: str):
|
76 |
-
"""Load and process medical data from text file"""
|
77 |
-
print(f"📖 Loading medical data from {file_path}...")
|
78 |
-
|
79 |
-
try:
|
80 |
-
with open(file_path, 'r', encoding='utf-8') as f:
|
81 |
-
text = f.read()
|
82 |
-
print(f"📄 File loaded: {len(text):,} characters")
|
83 |
-
except FileNotFoundError:
|
84 |
-
print(f"❌ File {file_path} not found!")
|
85 |
-
return False
|
86 |
-
except Exception as e:
|
87 |
-
print(f"❌ Error reading file: {e}")
|
88 |
-
return False
|
89 |
-
|
90 |
-
# Create chunks optimized for medical content
|
91 |
-
print("📝 Creating pediatric pulmonology chunks...")
|
92 |
-
new_chunks = self.create_medical_chunks_from_text(text)
|
93 |
-
print(f"📋 Created {len(new_chunks)} new medical chunks from file")
|
94 |
-
|
95 |
-
# Add to existing knowledge chunks (don't replace, append)
|
96 |
-
starting_id = len(self.knowledge_chunks)
|
97 |
-
for i, chunk in enumerate(new_chunks):
|
98 |
-
chunk['id'] = starting_id + i
|
99 |
-
chunk['source'] = 'pediatric_pulmonology_file'
|
100 |
-
|
101 |
-
self.knowledge_chunks.extend(new_chunks)
|
102 |
-
|
103 |
-
print(f"✅ Medical data loaded successfully!")
|
104 |
-
print(f"📊 Total knowledge chunks: {len(self.knowledge_chunks)}")
|
105 |
-
return True
|
106 |
-
|
107 |
-
def create_medical_chunks_from_text(self, text: str, chunk_size: int = 400) -> List[Dict]:
|
108 |
-
"""Create medically-optimized text chunks from uploaded file"""
|
109 |
-
chunks = []
|
110 |
-
|
111 |
-
# Clean the text first - remove XML/HTML tags and formatting artifacts
|
112 |
-
cleaned_text = self.clean_medical_text(text)
|
113 |
-
|
114 |
-
# Split by medical sections first
|
115 |
-
medical_sections = self.split_by_medical_sections(cleaned_text)
|
116 |
-
|
117 |
-
for section in medical_sections:
|
118 |
-
if len(section.split()) > chunk_size:
|
119 |
-
# Split large sections by sentences
|
120 |
-
sentences = re.split(r'[.!?]+', section)
|
121 |
-
current_chunk = ""
|
122 |
-
|
123 |
-
for sentence in sentences:
|
124 |
-
sentence = sentence.strip()
|
125 |
-
if not sentence:
|
126 |
-
continue
|
127 |
-
|
128 |
-
if len(current_chunk.split()) + len(sentence.split()) < chunk_size:
|
129 |
-
current_chunk += sentence + ". "
|
130 |
-
else:
|
131 |
-
if current_chunk.strip():
|
132 |
-
chunks.append({
|
133 |
-
'text': current_chunk.strip(),
|
134 |
-
'medical_focus': self.identify_medical_focus(current_chunk)
|
135 |
-
})
|
136 |
-
current_chunk = sentence + ". "
|
137 |
-
|
138 |
-
if current_chunk.strip():
|
139 |
-
chunks.append({
|
140 |
-
'text': current_chunk.strip(),
|
141 |
-
'medical_focus': self.identify_medical_focus(current_chunk)
|
142 |
-
})
|
143 |
-
else:
|
144 |
-
if section.strip():
|
145 |
-
chunks.append({
|
146 |
-
'text': section.strip(),
|
147 |
-
'medical_focus': self.identify_medical_focus(section)
|
148 |
-
})
|
149 |
-
|
150 |
-
return chunks
|
151 |
-
|
152 |
-
def clean_medical_text(self, text: str) -> str:
|
153 |
-
"""Clean medical text from formatting artifacts and XML tags"""
|
154 |
-
# Remove XML/HTML tags like </FREETEXT>, </ABSTRACT>, <SECTION>, etc.
|
155 |
-
text = re.sub(r'<[^>]+>', '', text)
|
156 |
-
|
157 |
-
# Remove common document formatting artifacts
|
158 |
-
text = re.sub(r'</?\s*FREETEXT\s*>', '', text, flags=re.IGNORECASE)
|
159 |
-
text = re.sub(r'</?\s*ABSTRACT\s*>', '', text, flags=re.IGNORECASE)
|
160 |
-
text = re.sub(r'</?\s*SECTION\s*>', '', text, flags=re.IGNORECASE)
|
161 |
-
text = re.sub(r'</?\s*TITLE\s*>', '', text, flags=re.IGNORECASE)
|
162 |
-
|
163 |
-
# Remove excessive whitespace and newlines
|
164 |
-
text = re.sub(r'\n\s*\n\s*\n+', '\n\n', text)
|
165 |
-
text = re.sub(r'\s+', ' ', text)
|
166 |
-
|
167 |
-
# Remove special characters that might be formatting artifacts
|
168 |
-
text = re.sub(r'[^\w\s.,;:!?()\-\'/"]', ' ', text)
|
169 |
-
|
170 |
-
# Clean up multiple spaces
|
171 |
-
text = re.sub(r'\s+', ' ', text).strip()
|
172 |
-
|
173 |
-
return text
|
174 |
-
|
175 |
-
def split_by_medical_sections(self, text: str) -> List[str]:
|
176 |
-
"""Split text by medical sections"""
|
177 |
-
# Look for medical section headers
|
178 |
-
section_patterns = [
|
179 |
-
r'\n\s*(?:SYMPTOMS?|TREATMENT|DIAGNOSIS|CAUSES?|PREVENTION|MANAGEMENT).*?\n',
|
180 |
-
r'\n\s*\d+\.\s+', # Numbered sections
|
181 |
-
r'\n\n+' # Paragraph breaks
|
182 |
-
]
|
183 |
-
|
184 |
-
sections = [text]
|
185 |
-
for pattern in section_patterns:
|
186 |
-
new_sections = []
|
187 |
-
for section in sections:
|
188 |
-
splits = re.split(pattern, section, flags=re.IGNORECASE)
|
189 |
-
new_sections.extend([s.strip() for s in splits if len(s.strip()) > 100])
|
190 |
-
sections = new_sections
|
191 |
-
|
192 |
-
return sections
|
193 |
-
|
194 |
-
def identify_medical_focus(self, text: str) -> str:
|
195 |
-
"""Identify the medical focus of a text chunk with pulmonology emphasis"""
|
196 |
-
text_lower = text.lower()
|
197 |
-
|
198 |
-
# Enhanced medical categories with pulmonology focus
|
199 |
-
categories = {
|
200 |
-
'pediatric_pulmonology': [
|
201 |
-
'asthma', 'pneumonia', 'bronchiolitis', 'croup', 'respiratory', 'lung', 'airway',
|
202 |
-
'breathing', 'cough', 'wheeze', 'stridor', 'pneumothorax', 'pleural', 'ventilator',
|
203 |
-
'oxygen', 'respiratory distress', 'bronchitis', 'pulmonary', 'chest', 'inhaler'
|
204 |
-
],
|
205 |
-
'pediatric_symptoms': ['fever', 'rash', 'vomiting', 'diarrhea', 'pain'],
|
206 |
-
'treatments': ['treatment', 'therapy', 'medication', 'antibiotics', 'steroid'],
|
207 |
-
'diagnosis': ['diagnosis', 'diagnostic', 'symptoms', 'signs', 'test'],
|
208 |
-
'emergency': ['emergency', 'urgent', 'serious', 'hospital', 'icu'],
|
209 |
-
'prevention': ['prevention', 'vaccine', 'immunization', 'avoid']
|
210 |
-
}
|
211 |
-
|
212 |
-
for category, keywords in categories.items():
|
213 |
-
if any(keyword in text_lower for keyword in keywords):
|
214 |
-
return category
|
215 |
-
|
216 |
-
return 'general_medical'
|
217 |
-
|
218 |
-
def setup_embeddings(self):
|
219 |
-
"""Setup medical embeddings"""
|
220 |
-
try:
|
221 |
-
print("🔧 Loading embeddings...")
|
222 |
-
self.embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
|
223 |
-
self.use_embeddings = True
|
224 |
-
print("✅ Embeddings loaded successfully")
|
225 |
-
except Exception as e:
|
226 |
-
print(f"⚠️ Embeddings failed: {e}")
|
227 |
-
self.embedding_model = None
|
228 |
-
self.use_embeddings = False
|
229 |
-
|
230 |
-
def setup_biogpt(self):
|
231 |
-
"""Setup BioGPT model with better fallback strategy"""
|
232 |
-
print("🧠 Loading BioGPT model...")
|
233 |
-
|
234 |
-
# Try more stable models first
|
235 |
-
models_to_try = [
|
236 |
-
"microsoft/DialoGPT-medium", # Most stable conversational model
|
237 |
-
"microsoft/DialoGPT-small", # Smaller backup
|
238 |
-
"gpt2-medium", # General GPT-2 backup
|
239 |
-
"microsoft/BioGPT" # BioGPT if available
|
240 |
-
]
|
241 |
-
|
242 |
-
for model_name in models_to_try:
|
243 |
-
try:
|
244 |
-
print(f" Trying {model_name}...")
|
245 |
-
|
246 |
-
# Load tokenizer first
|
247 |
-
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
|
248 |
-
if self.tokenizer.pad_token is None:
|
249 |
-
self.tokenizer.pad_token = self.tokenizer.eos_token
|
250 |
-
|
251 |
-
# Load model with conservative settings
|
252 |
-
self.model = AutoModelForCausalLM.from_pretrained(
|
253 |
-
model_name,
|
254 |
-
torch_dtype=torch.float16 if self.device == "cuda" else torch.float32,
|
255 |
-
device_map="auto" if self.device == "cuda" else None,
|
256 |
-
trust_remote_code=True,
|
257 |
-
low_cpu_mem_usage=True
|
258 |
-
)
|
259 |
-
|
260 |
-
if self.device == "cuda":
|
261 |
-
self.model = self.model.to(self.device)
|
262 |
-
|
263 |
-
print(f"✅ Successfully loaded {model_name}!")
|
264 |
-
self.model_name = model_name
|
265 |
-
return
|
266 |
-
|
267 |
-
except Exception as e:
|
268 |
-
print(f"❌ Failed to load {model_name}: {e}")
|
269 |
-
continue
|
270 |
-
|
271 |
-
# If all models fail - use rule-based fallback
|
272 |
-
print("❌ All models failed to load - using rule-based responses")
|
273 |
-
self.model = None
|
274 |
-
self.tokenizer = None
|
275 |
-
self.model_name = "Rule-based fallback"
|
276 |
-
|
277 |
-
def load_default_medical_knowledge(self):
|
278 |
-
"""Load comprehensive default medical knowledge base"""
|
279 |
-
default_knowledge = [
|
280 |
-
{
|
281 |
-
'id': 0,
|
282 |
-
'text': "Fever in children is commonly caused by viral infections (most common), bacterial infections, immunizations, teething in infants, or overdressing. Normal body temperature ranges from 97°F to 100.4°F (36.1°C to 38°C). A fever is generally considered when oral temperature exceeds 100.4°F (38°C). Most fevers are not dangerous and help the body fight infection. Treatment includes rest, fluids, and fever reducers like acetaminophen or ibuprofen for comfort.",
|
283 |
-
'medical_focus': 'pediatric_symptoms',
|
284 |
-
'source': 'default_knowledge'
|
285 |
-
},
|
286 |
-
{
|
287 |
-
'id': 1,
|
288 |
-
'text': "Dehydration in infants and children can occur rapidly, especially during illness with vomiting or diarrhea. Warning signs include: dry mouth and tongue, decreased urination, lethargy or irritability, sunken eyes, and in infants under 12 months, sunken fontanelle (soft spot). Mild dehydration can be treated with oral rehydration solutions or clear fluids. Severe dehydration requires immediate medical attention.",
|
289 |
-
'medical_focus': 'pediatric_symptoms',
|
290 |
-
'source': 'default_knowledge'
|
291 |
-
},
|
292 |
-
{
|
293 |
-
'id': 2,
|
294 |
-
'text': "Common cold symptoms in children include runny or stuffy nose, cough, low-grade fever, sneezing, and general fussiness. Most colds are viral and resolve within 7-10 days without specific treatment. Treatment focuses on comfort measures: rest, adequate fluids, humidified air, and saline nasal drops for congestion. Antibiotics are not effective against viral colds.",
|
295 |
-
'medical_focus': 'pediatric_symptoms',
|
296 |
-
'source': 'default_knowledge'
|
297 |
-
},
|
298 |
-
{
|
299 |
-
'id': 3,
|
300 |
-
'text': "Emergency warning signs in children requiring immediate medical attention include: severe difficulty breathing, persistent high fever over 104°F (40°C), signs of severe dehydration, persistent vomiting preventing fluid intake, severe headache with neck stiffness, altered consciousness or extreme lethargy, severe abdominal pain, or any concerning change in behavior. When in doubt, seek medical care.",
|
301 |
-
'medical_focus': 'emergency',
|
302 |
-
'source': 'default_knowledge'
|
303 |
-
},
|
304 |
-
{
|
305 |
-
'id': 4,
|
306 |
-
'text': "Childhood vaccination schedules protect against serious diseases including measles, mumps, rubella, polio, hepatitis B, Haemophilus influenzae, pneumococcal disease, and others. Vaccines are rigorously tested for safety and effectiveness. Side effects are typically mild, such as low-grade fever or soreness at injection site. Following recommended vaccination schedules protects individual children and the community.",
|
307 |
-
'medical_focus': 'prevention',
|
308 |
-
'source': 'default_knowledge'
|
309 |
-
},
|
310 |
-
{
|
311 |
-
'id': 5,
|
312 |
-
'text': "Persistent cough in children can be caused by viral upper respiratory infections, asthma, allergies, bacterial infections, or irritants. Most coughs from colds resolve within 2-3 weeks. Seek medical evaluation for coughs lasting more than 3 weeks, coughs with blood, difficulty breathing, or coughs severely interfering with sleep. Treatment depends on the underlying cause.",
|
313 |
-
'medical_focus': 'pediatric_symptoms',
|
314 |
-
'source': 'default_knowledge'
|
315 |
-
},
|
316 |
-
{
|
317 |
-
'id': 6,
|
318 |
-
'text': "Asthma in children is a chronic respiratory condition affecting the airways, causing them to become inflamed, narrow, and produce excess mucus. Common triggers include viral infections, allergens (dust mites, pollen, pet dander), irritants (smoke, strong odors), cold air, and exercise. Symptoms include wheezing, cough (especially at night), shortness of breath, and chest tightness. Management includes avoiding triggers, using prescribed inhalers, and having an asthma action plan.",
|
319 |
-
'medical_focus': 'pediatric_pulmonology',
|
320 |
-
'source': 'default_knowledge'
|
321 |
-
},
|
322 |
-
{
|
323 |
-
'id': 7,
|
324 |
-
'text': "Bronchiolitis is a common respiratory infection in infants and young children, typically caused by respiratory syncytial virus (RSV). It affects the small airways (bronchioles) in the lungs, causing inflammation and mucus buildup. Symptoms include runny nose, cough, low-grade fever, and difficulty breathing. Most cases are mild and resolve with supportive care, but severe cases may require hospitalization for oxygen support.",
|
325 |
-
'medical_focus': 'pediatric_pulmonology',
|
326 |
-
'source': 'default_knowledge'
|
327 |
-
},
|
328 |
-
{
|
329 |
-
'id': 8,
|
330 |
-
'text': "Pneumonia in children is an infection that inflames air sacs in one or both lungs, which may fill with fluid. It can be caused by bacteria, viruses, or fungi. Symptoms include cough with phlegm, fever, chills, and difficulty breathing. Bacterial pneumonia often requires antibiotic treatment, while viral pneumonia typically resolves with supportive care. Seek medical attention for persistent fever, difficulty breathing, or worsening symptoms.",
|
331 |
-
'medical_focus': 'pediatric_pulmonology',
|
332 |
-
'source': 'default_knowledge'
|
333 |
-
},
|
334 |
-
{
|
335 |
-
'id': 9,
|
336 |
-
'text': "Croup is a respiratory condition that causes swelling around the vocal cords. It's most common in children between 6 months and 6 years old. Symptoms include a distinctive barking cough, stridor (harsh sound when breathing in), hoarse voice, and difficulty breathing. Most cases are mild and can be treated at home with humidified air and staying calm. Severe cases with significant breathing difficulty require immediate medical attention.",
|
337 |
-
'medical_focus': 'pediatric_pulmonology',
|
338 |
-
'source': 'default_knowledge'
|
339 |
-
}
|
340 |
-
]
|
341 |
-
|
342 |
-
self.knowledge_chunks = default_knowledge
|
343 |
-
print(f"📚 Loaded {len(default_knowledge)} default medical knowledge chunks")
|
344 |
-
|
345 |
-
def retrieve_medical_context(self, query: str, n_results: int = 3) -> List[str]:
|
346 |
-
"""Retrieve relevant medical context using improved keyword search with pulmonology priority"""
|
347 |
-
if not self.knowledge_chunks:
|
348 |
-
return []
|
349 |
-
|
350 |
-
query_lower = query.lower()
|
351 |
-
query_words = set(query_lower.split())
|
352 |
-
chunk_scores = []
|
353 |
-
|
354 |
-
# Enhanced medical keyword mapping with pulmonology emphasis
|
355 |
-
medical_keywords = {
|
356 |
-
'pulmonology': ['asthma', 'pneumonia', 'bronchiolitis', 'croup', 'respiratory', 'lung', 'airway', 'breathing', 'cough', 'wheeze', 'stridor'],
|
357 |
-
'fever': ['fever', 'temperature', 'hot', 'warm', 'burning'],
|
358 |
-
'stomach': ['stomach', 'abdominal', 'belly', 'tummy', 'pain', 'ache'],
|
359 |
-
'rash': ['rash', 'skin', 'red', 'spots', 'bumps', 'itchy'],
|
360 |
-
'vomiting': ['vomit', 'vomiting', 'throw up', 'sick', 'nausea'],
|
361 |
-
'diarrhea': ['diarrhea', 'loose', 'stool', 'bowel', 'poop'],
|
362 |
-
'dehydration': ['dehydration', 'dehydrated', 'fluids', 'water', 'thirsty'],
|
363 |
-
'emergency': ['emergency', 'urgent', 'serious', 'severe', 'hospital', 'doctor']
|
364 |
-
}
|
365 |
-
|
366 |
-
# Expand query with related medical terms
|
367 |
-
expanded_query_words = set(query_words)
|
368 |
-
for medical_term, synonyms in medical_keywords.items():
|
369 |
-
if any(word in query_lower for word in synonyms):
|
370 |
-
expanded_query_words.update(synonyms)
|
371 |
-
|
372 |
-
for chunk_info in self.knowledge_chunks:
|
373 |
-
chunk_text = chunk_info['text'].lower()
|
374 |
-
|
375 |
-
# Calculate relevance score with expanded terms
|
376 |
-
word_overlap = sum(1 for word in expanded_query_words if word in chunk_text)
|
377 |
-
base_score = word_overlap / len(expanded_query_words) if expanded_query_words else 0
|
378 |
-
|
379 |
-
# Strong boost for pulmonology content
|
380 |
-
medical_boost = 0
|
381 |
-
medical_focus = chunk_info.get('medical_focus', '')
|
382 |
-
source = chunk_info.get('source', '')
|
383 |
-
|
384 |
-
if medical_focus == 'pediatric_pulmonology':
|
385 |
-
medical_boost = 0.8 # Highest priority for pulmonology
|
386 |
-
elif source == 'pediatric_pulmonology_file':
|
387 |
-
medical_boost = 0.7 # High priority for your uploaded data
|
388 |
-
elif medical_focus == 'emergency':
|
389 |
-
medical_boost = 0.4
|
390 |
-
elif medical_focus in ['treatments', 'diagnosis']:
|
391 |
-
medical_boost = 0.3
|
392 |
-
elif medical_focus == 'pediatric_symptoms':
|
393 |
-
medical_boost = 0.5
|
394 |
-
|
395 |
-
final_score = base_score + medical_boost
|
396 |
-
|
397 |
-
if final_score > 0:
|
398 |
-
chunk_scores.append((final_score, chunk_info['text']))
|
399 |
-
|
400 |
-
# Return top matches - prioritize pulmonology content
|
401 |
-
chunk_scores.sort(reverse=True)
|
402 |
-
results = [chunk for _, chunk in chunk_scores[:n_results]]
|
403 |
-
|
404 |
-
# If no good matches, return some default medical chunks
|
405 |
-
if not results:
|
406 |
-
results = [chunk['text'] for chunk in self.knowledge_chunks[:2]]
|
407 |
-
|
408 |
-
return results
|
409 |
-
|
410 |
-
def generate_biogpt_response(self, context: str, query: str) -> str:
|
411 |
-
"""Generate medical response - with rule-based fallback if model fails"""
|
412 |
-
|
413 |
-
# If no model is loaded, use rule-based response
|
414 |
-
if not self.model or not self.tokenizer:
|
415 |
-
return self.generate_rule_based_response(context, query)
|
416 |
-
|
417 |
-
try:
|
418 |
-
# Create medical prompt
|
419 |
-
prompt = f"Medical Question: {query}\n\nMedical Information: {context[:300]}\n\nAnswer:"
|
420 |
-
|
421 |
-
# Tokenize with conservative limits
|
422 |
-
inputs = self.tokenizer(
|
423 |
-
prompt,
|
424 |
-
return_tensors="pt",
|
425 |
-
truncation=True,
|
426 |
-
max_length=400, # Very conservative
|
427 |
-
padding=True
|
428 |
-
)
|
429 |
-
|
430 |
-
# Move to device
|
431 |
-
if self.device == "cuda":
|
432 |
-
inputs = {k: v.to(self.device) for k, v in inputs.items()}
|
433 |
-
|
434 |
-
# Generate with conservative settings
|
435 |
-
with torch.no_grad():
|
436 |
-
outputs = self.model.generate(
|
437 |
-
**inputs,
|
438 |
-
max_new_tokens=100, # Conservative
|
439 |
-
do_sample=True,
|
440 |
-
temperature=0.3, # Low temperature
|
441 |
-
top_p=0.8,
|
442 |
-
top_k=30,
|
443 |
-
pad_token_id=self.tokenizer.eos_token_id,
|
444 |
-
eos_token_id=self.tokenizer.eos_token_id,
|
445 |
-
repetition_penalty=1.1,
|
446 |
-
early_stopping=True
|
447 |
-
)
|
448 |
-
|
449 |
-
# Decode response
|
450 |
-
full_response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
451 |
-
|
452 |
-
# Extract generated part
|
453 |
-
if "Answer:" in full_response:
|
454 |
-
generated_response = full_response.split("Answer:")[-1].strip()
|
455 |
-
else:
|
456 |
-
generated_response = full_response[len(prompt):].strip()
|
457 |
-
|
458 |
-
# Simple cleaning - less aggressive
|
459 |
-
cleaned_response = self.simple_clean_response(generated_response)
|
460 |
-
|
461 |
-
# If too short, use rule-based fallback
|
462 |
-
if len(cleaned_response.strip()) < 30:
|
463 |
-
return self.generate_rule_based_response(context, query)
|
464 |
-
|
465 |
-
return cleaned_response
|
466 |
-
|
467 |
-
except Exception as e:
|
468 |
-
print(f"⚠️ Model generation failed: {e}")
|
469 |
-
return self.generate_rule_based_response(context, query)
|
470 |
-
|
471 |
-
def simple_clean_response(self, response: str) -> str:
|
472 |
-
"""Simple, less aggressive cleaning"""
|
473 |
-
# Remove obvious artifacts
|
474 |
-
response = re.sub(r'<[^>]*>', '', response)
|
475 |
-
response = re.sub(r'[▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟]', '', response)
|
476 |
-
|
477 |
-
# Clean whitespace
|
478 |
-
response = re.sub(r'\s+', ' ', response).strip()
|
479 |
-
|
480 |
-
# Take first reasonable sentences
|
481 |
-
sentences = re.split(r'[.!?]+', response)
|
482 |
-
good_sentences = []
|
483 |
-
|
484 |
-
for sentence in sentences:
|
485 |
-
sentence = sentence.strip()
|
486 |
-
if len(sentence) > 5 and len(sentence.split()) >= 2:
|
487 |
-
good_sentences.append(sentence)
|
488 |
-
if len(good_sentences) >= 2: # Max 2 sentences
|
489 |
-
break
|
490 |
-
|
491 |
-
if good_sentences:
|
492 |
-
result = '. '.join(good_sentences)
|
493 |
-
if not result.endswith('.'):
|
494 |
-
result += '.'
|
495 |
-
return result
|
496 |
-
|
497 |
-
return response[:200] if response else ""
|
498 |
-
|
499 |
-
def generate_rule_based_response(self, context: str, query: str) -> str:
|
500 |
-
"""Generate rule-based medical response when model fails"""
|
501 |
-
query_lower = query.lower()
|
502 |
-
|
503 |
-
# Use the context to generate a response
|
504 |
-
if context:
|
505 |
-
# Find the most relevant sentence from context
|
506 |
-
context_sentences = [s.strip() for s in context.split('.') if len(s.strip()) > 20]
|
507 |
-
|
508 |
-
if context_sentences:
|
509 |
-
# Get first 1-2 relevant sentences
|
510 |
-
response_sentences = context_sentences[:2]
|
511 |
-
response = '. '.join(response_sentences)
|
512 |
-
if not response.endswith('.'):
|
513 |
-
response += '.'
|
514 |
-
|
515 |
-
# Add appropriate medical advice
|
516 |
-
if any(word in query_lower for word in ['emergency', 'urgent', 'severe', 'serious']):
|
517 |
-
response += " If symptoms are severe or concerning, seek immediate medical attention."
|
518 |
-
else:
|
519 |
-
response += " Always consult with a healthcare provider for personalized medical advice."
|
520 |
-
|
521 |
-
return response
|
522 |
-
|
523 |
-
# Fallback responses based on keywords
|
524 |
-
keyword_responses = {
|
525 |
-
'asthma': "Asthma in children is a chronic respiratory condition that causes airway inflammation and narrowing. Common symptoms include wheezing, cough, shortness of breath, and chest tightness. Management typically involves avoiding triggers, using prescribed medications like inhalers, and having an asthma action plan. Regular follow-up with healthcare providers is important for optimal control.",
|
526 |
-
|
527 |
-
'pneumonia': "Pneumonia is a lung infection that can be caused by bacteria, viruses, or other organisms. In children, symptoms may include fever, cough, difficulty breathing, and chest pain. Treatment depends on the cause - bacterial pneumonia typically requires antibiotics, while viral pneumonia is managed with supportive care. Seek medical evaluation for persistent fever or breathing difficulties.",
|
528 |
-
|
529 |
-
'bronchiolitis': "Bronchiolitis is a common respiratory infection in infants and young children, usually caused by viruses like RSV. It affects the small airways in the lungs. Symptoms include runny nose, cough, fever, and difficulty breathing. Most cases are mild and resolve with supportive care, but some children may need hospitalization for breathing support.",
|
530 |
-
|
531 |
-
'croup': "Croup causes swelling around the vocal cords and is characterized by a distinctive barking cough and harsh breathing sounds (stridor). It's most common in children 6 months to 6 years old. Most cases are mild and can be managed at home with humidified air. Seek immediate care if breathing becomes severely difficult.",
|
532 |
-
|
533 |
-
'fever': "Fever in children is usually a sign that the body is fighting an infection. Most fevers are not dangerous and can be managed with rest, fluids, and appropriate fever reducers if needed for comfort. Seek medical care for very high fevers (over 104°F), fevers in infants under 3 months, or if the child appears very ill.",
|
534 |
-
|
535 |
-
'cough': "Cough in children can have many causes including viral infections, asthma, allergies, or bacterial infections. Most coughs from colds resolve within 2-3 weeks. Seek medical evaluation for persistent coughs lasting more than 3 weeks, coughs with blood, or coughs that significantly interfere with sleep or daily activities."
|
536 |
-
}
|
537 |
-
|
538 |
-
# Check for keyword matches
|
539 |
-
for keyword, response in keyword_responses.items():
|
540 |
-
if keyword in query_lower:
|
541 |
-
return response
|
542 |
-
|
543 |
-
# Generic medical response
|
544 |
-
return "For specific medical concerns, it's important to consult with a qualified healthcare provider who can evaluate your child's individual situation. They can provide appropriate diagnosis, treatment recommendations, and guidance based on your child's specific symptoms and medical history."
|
545 |
-
|
546 |
-
def handle_conversational_interactions(self, query: str) -> Optional[str]:
|
547 |
-
"""Handle conversational interactions"""
|
548 |
-
query_lower = query.lower().strip()
|
549 |
-
|
550 |
-
# Greeting patterns
|
551 |
-
exact_greetings = [
|
552 |
-
'hello', 'hi', 'hey', 'good morning', 'good afternoon',
|
553 |
-
'good evening', 'how are you', 'how are you doing'
|
554 |
-
]
|
555 |
-
|
556 |
-
if query_lower in exact_greetings:
|
557 |
-
return "👋 Hello! I'm BioGPT, your AI medical assistant specialized in pediatric pulmonology. I provide evidence-based medical information about children's respiratory health. What can I help you with today?"
|
558 |
-
|
559 |
-
# Thanks patterns
|
560 |
-
thanks_only = ['thank you', 'thanks', 'thank you so much', 'thanks a lot']
|
561 |
-
if query_lower in thanks_only:
|
562 |
-
return "🙏 You're welcome! I'm glad I could provide helpful pediatric pulmonology information. Remember to always consult healthcare providers for personalized advice. Feel free to ask more questions!"
|
563 |
-
|
564 |
-
# Help patterns
|
565 |
-
help_only = ['help', 'what can you do', 'what are you', 'who are you']
|
566 |
-
if query_lower in help_only:
|
567 |
-
return """🤖 **About BioGPT Pediatric Pulmonology Assistant**
|
568 |
-
|
569 |
-
I'm an AI medical assistant powered by BioGPT, specialized in pediatric pulmonology and respiratory medicine. I can help with:
|
570 |
-
|
571 |
-
🫁 **Pediatric Pulmonology:**
|
572 |
-
• Asthma, bronchiolitis, pneumonia, croup
|
573 |
-
• Respiratory symptoms and breathing difficulties
|
574 |
-
• Treatment guidance and management
|
575 |
-
• When to seek medical care
|
576 |
-
|
577 |
-
⚠️ **Important:** I provide educational information only. Always consult healthcare professionals for medical decisions."""
|
578 |
-
|
579 |
-
return None
|
580 |
-
|
581 |
-
def chat_interface(self, message: str, history: List[List[str]]) -> str:
|
582 |
-
"""Main chat interface for Gradio"""
|
583 |
-
if not message.strip():
|
584 |
-
return "Hello! I'm BioGPT, your pediatric pulmonology AI assistant. How can I help you with children's respiratory health today?"
|
585 |
-
|
586 |
-
print(f"🔍 Processing query: '{message}'")
|
587 |
-
|
588 |
-
# Handle conversational interactions
|
589 |
-
conversational_response = self.handle_conversational_interactions(message)
|
590 |
-
if conversational_response:
|
591 |
-
print(" Handled as conversational")
|
592 |
-
return conversational_response
|
593 |
-
|
594 |
-
print(" Processing as medical query")
|
595 |
-
|
596 |
-
# Process as medical query
|
597 |
-
context = self.retrieve_medical_context(message)
|
598 |
-
|
599 |
-
if not context:
|
600 |
-
return f"""🩺 **Medical Query:** {message}
|
601 |
-
|
602 |
-
⚠️ I don't have specific information about this topic in my current medical database. However, I recommend:
|
603 |
-
|
604 |
-
1. **Consult Healthcare Provider**: For personalized medical advice
|
605 |
-
2. **Emergency Signs**: If symptoms are severe, seek immediate care
|
606 |
-
3. **Pediatric Specialist**: For specialized concerns
|
607 |
-
|
608 |
-
**For urgent medical concerns, contact your healthcare provider or emergency services.**
|
609 |
-
|
610 |
-
💡 **Try asking about**: asthma, breathing difficulties, cough, pneumonia, or other respiratory symptoms."""
|
611 |
-
|
612 |
-
# Generate medical response
|
613 |
-
main_context = '\n\n'.join(context)
|
614 |
-
response = self.generate_biogpt_response(main_context, message)
|
615 |
-
|
616 |
-
# Format as medical response
|
617 |
-
final_response = f"🩺 **BioGPT Medical Assistant:** {response}\n\n⚠️ **Important:** This information is for educational purposes only. Always consult qualified healthcare professionals for medical diagnosis, treatment, and personalized advice."
|
618 |
-
|
619 |
-
return final_response
|
620 |
-
|
621 |
-
def get_knowledge_stats(self) -> Dict:
|
622 |
-
"""Get statistics about loaded knowledge"""
|
623 |
-
if not self.knowledge_chunks:
|
624 |
-
return {"total_chunks": 0}
|
625 |
-
|
626 |
-
stats = {
|
627 |
-
"total_chunks": len(self.knowledge_chunks),
|
628 |
-
"default_knowledge": len([c for c in self.knowledge_chunks if c.get('source') == 'default_knowledge']),
|
629 |
-
"pulmonology_file_data": len([c for c in self.knowledge_chunks if c.get('source') == 'pediatric_pulmonology_file']),
|
630 |
-
"pulmonology_focused": len([c for c in self.knowledge_chunks if c.get('medical_focus') == 'pediatric_pulmonology']),
|
631 |
-
"model_used": getattr(self, 'model_name', 'Unknown')
|
632 |
-
}
|
633 |
-
return stats
|
634 |
-
|
635 |
-
# Test function
|
636 |
-
def test_chatbot_responses():
|
637 |
-
"""Test the chatbot with various queries"""
|
638 |
-
print("\n🧪 Testing BioGPT Pediatric Pulmonology Chatbot...")
|
639 |
-
print("=" * 50)
|
640 |
-
|
641 |
-
test_queries = [
|
642 |
-
"hello",
|
643 |
-
"what is asthma in children",
|
644 |
-
"my child has breathing difficulties",
|
645 |
-
"help",
|
646 |
-
"treatment for pediatric pneumonia",
|
647 |
-
"thank you"
|
648 |
-
]
|
649 |
-
|
650 |
-
for query in test_queries:
|
651 |
-
print(f"\n🔍 Query: '{query}'")
|
652 |
-
response = chatbot.chat_interface(query, [])
|
653 |
-
response_type = 'CONVERSATIONAL' if any(word in response for word in ['Hello!', 'welcome!', 'About BioGPT']) else 'MEDICAL'
|
654 |
-
print(f"🤖 Response type: {response_type}")
|
655 |
-
print(f"📝 Response: {response[:100]}...")
|
656 |
-
print("-" * 30)
|
657 |
-
|
658 |
-
# Initialize the chatbot globally
|
659 |
-
print("🚀 Initializing BioGPT Pediatric Pulmonology Chatbot...")
|
660 |
-
chatbot = BioGPTMedicalChatbot()
|
661 |
-
|
662 |
-
# Show knowledge statistics
|
663 |
-
print("\n📊 Knowledge Base Statistics:")
|
664 |
-
stats = chatbot.get_knowledge_stats()
|
665 |
-
for key, value in stats.items():
|
666 |
-
print(f" {key}: {value}")
|
667 |
-
|
668 |
-
# Run tests
|
669 |
-
test_chatbot_responses()
|
670 |
-
|
671 |
-
def create_gradio_interface():
|
672 |
-
"""Create Gradio chat interface"""
|
673 |
-
|
674 |
-
# Get current knowledge stats for display
|
675 |
-
stats = chatbot.get_knowledge_stats()
|
676 |
-
|
677 |
-
# Custom CSS for medical theme
|
678 |
-
css = """
|
679 |
-
.gradio-container {
|
680 |
-
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
681 |
-
}
|
682 |
-
.chat-message {
|
683 |
-
background-color: #f8f9fa;
|
684 |
-
border-radius: 10px;
|
685 |
-
padding: 10px;
|
686 |
-
margin: 5px;
|
687 |
-
}
|
688 |
-
"""
|
689 |
-
|
690 |
-
with gr.Blocks(
|
691 |
-
css=css,
|
692 |
-
title="BioGPT Pediatric Pulmonology Assistant",
|
693 |
-
theme=gr.themes.Soft()
|
694 |
-
) as demo:
|
695 |
-
|
696 |
-
# Header
|
697 |
-
gr.HTML(f"""
|
698 |
-
<div style="text-align: center; padding: 20px; background: linear-gradient(90deg, #667eea, #764ba2); color: white; border-radius: 10px; margin-bottom: 20px;">
|
699 |
-
<h1>🫁 BioGPT Pediatric Pulmonology Assistant</h1>
|
700 |
-
<p>Specialized AI Medical Chatbot for Children's Respiratory Health</p>
|
701 |
-
<p><strong>Powered by BioGPT | {stats['total_chunks']} Medical Knowledge Chunks Loaded</strong></p>
|
702 |
-
<p><small>Model: {stats['model_used']} | Pulmonology Data: {stats['pulmonology_file_data']} chunks</small></p>
|
703 |
-
</div>
|
704 |
-
""")
|
705 |
-
|
706 |
-
# Important disclaimer
|
707 |
-
gr.HTML("""
|
708 |
-
<div style="background-color: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 15px; margin-bottom: 20px;">
|
709 |
-
<h3 style="color: #856404; margin-top: 0;">⚠️ Medical Disclaimer</h3>
|
710 |
-
<p style="color: #856404; margin-bottom: 0;">
|
711 |
-
This AI provides educational pediatric pulmonology information only and is NOT a substitute for professional medical advice,
|
712 |
-
diagnosis, or treatment. Always consult qualified healthcare providers for medical decisions.
|
713 |
-
<strong>In case of respiratory emergency, call emergency services immediately.</strong>
|
714 |
-
</p>
|
715 |
-
</div>
|
716 |
-
""")
|
717 |
-
|
718 |
-
# Chat interface
|
719 |
-
chatbot_interface = gr.ChatInterface(
|
720 |
-
fn=chatbot.chat_interface,
|
721 |
-
title="💬 Chat with BioGPT Pulmonology Assistant",
|
722 |
-
description="Ask me about pediatric respiratory health, asthma, breathing difficulties, and pulmonology treatments.",
|
723 |
-
examples=[
|
724 |
-
"What is asthma in children?",
|
725 |
-
"My child has a persistent cough, what should I do?",
|
726 |
-
"How is bronchiolitis treated in infants?",
|
727 |
-
"When should I be worried about my child's breathing?",
|
728 |
-
"What are the signs of pneumonia in children?",
|
729 |
-
"How can I prevent respiratory infections?"
|
730 |
-
],
|
731 |
-
retry_btn=None,
|
732 |
-
undo_btn=None,
|
733 |
-
clear_btn="🗑️ Clear Chat",
|
734 |
-
submit_btn="🫁 Ask BioGPT",
|
735 |
-
chatbot=gr.Chatbot(
|
736 |
-
height=500,
|
737 |
-
placeholder="<div style='text-align: center; color: #666;'>Start a conversation with BioGPT Pediatric Pulmonology Assistant</div>",
|
738 |
-
show_copy_button=True,
|
739 |
-
bubble_full_width=False
|
740 |
-
)
|
741 |
-
)
|
742 |
-
|
743 |
-
# Information tabs
|
744 |
-
with gr.Tabs():
|
745 |
-
with gr.Tab("ℹ️ About"):
|
746 |
-
gr.Markdown(f"""
|
747 |
-
## About BioGPT Pediatric Pulmonology Assistant
|
748 |
-
|
749 |
-
This AI assistant is powered by **BioGPT**, specialized for pediatric pulmonology and respiratory medicine.
|
750 |
-
|
751 |
-
### 🎯 Current Knowledge Base:
|
752 |
-
- **Total Chunks**: {stats['total_chunks']}
|
753 |
-
- **Default Medical Knowledge**: {stats['default_knowledge']} chunks
|
754 |
-
- **Pulmonology File Data**: {stats['pulmonology_file_data']} chunks
|
755 |
-
- **Pulmonology Focus**: {stats['pulmonology_focused']} chunks
|
756 |
-
- **Model**: {stats['model_used']}
|
757 |
-
|
758 |
-
### 🫁 Specializations:
|
759 |
-
- **Pediatric Asthma**: Diagnosis, treatment, management
|
760 |
-
- **Respiratory Infections**: Pneumonia, bronchiolitis, croup
|
761 |
-
- **Breathing Difficulties**: Assessment and guidance
|
762 |
-
- **Chronic Respiratory Conditions**: Long-term management
|
763 |
-
- **Emergency Respiratory Care**: When to seek immediate help
|
764 |
-
|
765 |
-
### 🔧 Technical Features:
|
766 |
-
- **Model**: Microsoft BioGPT (Medical AI) with fallback systems
|
767 |
-
- **Auto-Loading**: Automatically loads your pulmonology data file
|
768 |
-
- **Smart Retrieval**: Prioritizes pulmonology content
|
769 |
-
- **Rule-Based Fallback**: Ensures reliable responses even if AI model fails
|
770 |
-
|
771 |
-
### 📱 How to Use:
|
772 |
-
1. Type your pediatric respiratory question
|
773 |
-
2. Be specific about symptoms or conditions
|
774 |
-
3. Ask about treatments, diagnosis, or management
|
775 |
-
4. Request guidance on when to seek care
|
776 |
-
""")
|
777 |
-
|
778 |
-
with gr.Tab("🫁 Pulmonology Topics"):
|
779 |
-
gr.Markdown("""
|
780 |
-
## Pediatric Pulmonology Coverage
|
781 |
-
|
782 |
-
### 🔴 Common Respiratory Conditions:
|
783 |
-
- **Asthma**: Triggers, symptoms, management, action plans
|
784 |
-
- **Bronchiolitis**: RSV, treatment, when to hospitalize
|
785 |
-
- **Pneumonia**: Bacterial vs viral, antibiotics, recovery
|
786 |
-
- **Croup**: Barking cough, stridor, home treatment
|
787 |
-
- **Bronchitis**: Acute vs chronic, treatment approaches
|
788 |
-
|
789 |
-
### 🟡 Respiratory Symptoms:
|
790 |
-
- **Cough**: Persistent, productive, dry, nocturnal
|
791 |
-
- **Wheezing**: Causes, assessment, treatment
|
792 |
-
- **Shortness of Breath**: Evaluation and management
|
793 |
-
- **Chest Pain**: When concerning in children
|
794 |
-
- **Stridor**: Upper airway obstruction signs
|
795 |
-
|
796 |
-
### 🟢 Diagnostic & Treatment:
|
797 |
-
- **Pulmonary Function Tests**: When appropriate
|
798 |
-
- **Imaging**: X-rays, CT scans for respiratory issues
|
799 |
-
- **Medications**: Bronchodilators, steroids, antibiotics
|
800 |
-
- **Oxygen Therapy**: Indications and monitoring
|
801 |
-
- **Respiratory Support**: CPAP, ventilation considerations
|
802 |
-
|
803 |
-
### 🔵 Prevention & Management:
|
804 |
-
- **Trigger Avoidance**: Environmental controls
|
805 |
-
- **Vaccination**: Respiratory disease prevention
|
806 |
-
- **Exercise Guidelines**: For children with respiratory conditions
|
807 |
-
- **School Management**: Asthma action plans, inhaler use
|
808 |
-
""")
|
809 |
-
|
810 |
-
with gr.Tab("⚠️ Emergency & Safety"):
|
811 |
-
gr.Markdown("""
|
812 |
-
## Respiratory Emergency Guidance
|
813 |
-
|
814 |
-
### 🚨 CALL EMERGENCY SERVICES IMMEDIATELY:
|
815 |
-
- **Severe Breathing Difficulty**: Cannot speak in full sentences
|
816 |
-
- **Blue Lips or Fingernails**: Cyanosis indicating oxygen deprivation
|
817 |
-
- **Severe Wheezing**: With significant distress
|
818 |
-
- **Stridor at Rest**: High-pitched breathing sound
|
819 |
-
- **Unconsciousness**: Related to breathing problems
|
820 |
-
- **Severe Chest Retractions**: Pulling in around ribs/sternum
|
821 |
-
|
822 |
-
### 🏥 SEEK IMMEDIATE MEDICAL CARE:
|
823 |
-
- **Persistent High Fever**: >104°F (40°C) with respiratory symptoms
|
824 |
-
- **Worsening Symptoms**: Despite treatment
|
825 |
-
- **Dehydration Signs**: With respiratory illness
|
826 |
-
- **Significant Behavior Changes**: Extreme lethargy, irritability
|
827 |
-
- **Inhaler Not Helping**: Asthma symptoms not responding
|
828 |
-
|
829 |
-
### 📞 CONTACT HEALTHCARE PROVIDER:
|
830 |
-
- **New Respiratory Symptoms**: Lasting more than a few days
|
831 |
-
- **Chronic Cough**: Persisting beyond 2-3 weeks
|
832 |
-
- **Asthma Questions**: About medications or management
|
833 |
-
- **Fever with Cough**: Especially if productive
|
834 |
-
- **Exercise Limitations**: Due to breathing difficulties
|
835 |
-
|
836 |
-
### 🏠 HOME MONITORING:
|
837 |
-
- **Respiratory Rate**: Normal ranges by age
|
838 |
-
- **Oxygen Saturation**: If pulse oximeter available
|
839 |
-
- **Peak Flow**: For children with asthma
|
840 |
-
- **Symptom Tracking**: Using asthma diaries or apps
|
841 |
-
""")
|
842 |
-
|
843 |
-
with gr.Tab("📁 Data Information"):
|
844 |
-
gr.Markdown(f"""
|
845 |
-
## Knowledge Base Status
|
846 |
-
|
847 |
-
### 📊 Current Data Loaded:
|
848 |
-
- **Total Medical Chunks**: {stats['total_chunks']}
|
849 |
-
- **Default Knowledge**: {stats['default_knowledge']} chunks
|
850 |
-
- **Your Pulmonology File**: {stats['pulmonology_file_data']} chunks
|
851 |
-
- **Pulmonology Focused**: {stats['pulmonology_focused']} chunks
|
852 |
-
- **AI Model**: {stats['model_used']}
|
853 |
-
|
854 |
-
### 📝 How Your Data Is Used:
|
855 |
-
1. **Auto-Detection**: System automatically looks for 'Pediatric_cleaned.txt'
|
856 |
-
2. **Smart Processing**: Breaks your file into medical chunks
|
857 |
-
3. **Priority Ranking**: Pulmonology content gets highest priority
|
858 |
-
4. **Context Retrieval**: Relevant chunks are used to answer questions
|
859 |
-
5. **Fallback Systems**: Multiple layers ensure reliable responses
|
860 |
-
|
861 |
-
### 📂 Expected File Formats:
|
862 |
-
- **Filename**: 'Pediatric_cleaned.txt' (case variations accepted)
|
863 |
-
- **Content**: Plain text with medical information
|
864 |
-
- **Structure**: Paragraphs, sections, or bullet points
|
865 |
-
- **Focus**: Pediatric pulmonology and respiratory medicine
|
866 |
-
|
867 |
-
### 🔄 Upload Instructions:
|
868 |
-
1. Go to your Hugging Face Space
|
869 |
-
2. Click "Files" tab
|
870 |
-
3. Upload your 'Pediatric_cleaned.txt' file
|
871 |
-
4. Restart the Space to reload data
|
872 |
-
|
873 |
-
{"✅ **Status**: Pulmonology data file loaded successfully!" if stats['pulmonology_file_data'] > 0 else "⚠️ **Status**: No pulmonology data file detected. Upload 'Pediatric_cleaned.txt' to enhance responses."}
|
874 |
-
|
875 |
-
### 🛡️ Reliability Features:
|
876 |
-
- **Multiple Model Support**: Tries BioGPT, DialoGPT, GPT-2 in order
|
877 |
-
- **Rule-Based Fallback**: If all AI models fail, uses knowledge-based responses
|
878 |
-
- **Conservative Generation**: Prevents problematic outputs
|
879 |
-
- **Medical Context Priority**: Always uses your medical knowledge first
|
880 |
-
""")
|
881 |
-
|
882 |
-
# Footer
|
883 |
-
gr.HTML("""
|
884 |
-
<div style="text-align: center; padding: 20px; margin-top: 30px; border-top: 1px solid #ddd; color: #666;">
|
885 |
-
<p>🫁 <strong>BioGPT Pediatric Pulmonology Assistant</strong> | Powered by Microsoft BioGPT</p>
|
886 |
-
<p>Specialized in Children's Respiratory Health • Always consult healthcare professionals</p>
|
887 |
-
</div>
|
888 |
-
""")
|
889 |
-
|
890 |
-
return demo
|
891 |
-
|
892 |
-
# Create and launch the interface
|
893 |
-
demo = create_gradio_interface()
|
894 |
-
|
895 |
-
if __name__ == "__main__":
|
896 |
-
# Launch the app
|
897 |
-
demo.launch(
|
898 |
-
server_name="0.0.0.0",
|
899 |
-
server_port=7860,
|
900 |
-
share=False
|
901 |
-
)
|
902 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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