Blaiseboy commited on
Commit
9a148c4
Β·
verified Β·
1 Parent(s): fd4e71f

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +964 -0
app.py ADDED
@@ -0,0 +1,964 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 fallback"""
232
+ print("🧠 Loading BioGPT model...")
233
+
234
+ # Try more stable models first, then BioGPT
235
+ models_to_try = [
236
+ "microsoft/DialoGPT-medium", # More stable model first
237
+ "microsoft/BioGPT",
238
+ "microsoft/BioGPT-Large"
239
+ ]
240
+
241
+ for model_name in models_to_try:
242
+ try:
243
+ print(f" Trying {model_name}...")
244
+
245
+ # Setup quantization for memory efficiency
246
+ quantization_config = None
247
+ if self.use_8bit and "BioGPT" in model_name:
248
+ quantization_config = BitsAndBytesConfig(
249
+ load_in_8bit=True,
250
+ llm_int8_threshold=6.0,
251
+ )
252
+
253
+ # Load tokenizer
254
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name)
255
+ if self.tokenizer.pad_token is None:
256
+ self.tokenizer.pad_token = self.tokenizer.eos_token
257
+
258
+ # Load model
259
+ self.model = AutoModelForCausalLM.from_pretrained(
260
+ model_name,
261
+ quantization_config=quantization_config,
262
+ torch_dtype=torch.float16 if self.device == "cuda" else torch.float32,
263
+ device_map="auto" if self.device == "cuda" and quantization_config else None,
264
+ trust_remote_code=True
265
+ )
266
+
267
+ if self.device == "cuda" and quantization_config is None:
268
+ self.model = self.model.to(self.device)
269
+
270
+ print(f"βœ… Successfully loaded {model_name}!")
271
+ self.model_name = model_name
272
+ return
273
+
274
+ except Exception as e:
275
+ print(f"❌ Failed to load {model_name}: {e}")
276
+ continue
277
+
278
+ # If all models fail
279
+ print("❌ All models failed to load")
280
+ self.model = None
281
+ self.tokenizer = None
282
+ self.model_name = "None"
283
+
284
+ def load_default_medical_knowledge(self):
285
+ """Load comprehensive default medical knowledge base"""
286
+ default_knowledge = [
287
+ {
288
+ 'id': 0,
289
+ '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.",
290
+ 'medical_focus': 'pediatric_symptoms',
291
+ 'source': 'default_knowledge'
292
+ },
293
+ {
294
+ 'id': 1,
295
+ '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.",
296
+ 'medical_focus': 'pediatric_symptoms',
297
+ 'source': 'default_knowledge'
298
+ },
299
+ {
300
+ 'id': 2,
301
+ '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.",
302
+ 'medical_focus': 'pediatric_symptoms',
303
+ 'source': 'default_knowledge'
304
+ },
305
+ {
306
+ 'id': 3,
307
+ '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.",
308
+ 'medical_focus': 'emergency',
309
+ 'source': 'default_knowledge'
310
+ },
311
+ {
312
+ 'id': 4,
313
+ '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.",
314
+ 'medical_focus': 'prevention',
315
+ 'source': 'default_knowledge'
316
+ },
317
+ {
318
+ 'id': 5,
319
+ '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.",
320
+ 'medical_focus': 'pediatric_symptoms',
321
+ 'source': 'default_knowledge'
322
+ },
323
+ # Adding more default knowledge chunks for comprehensive coverage...
324
+ {
325
+ 'id': 6,
326
+ '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.",
327
+ 'medical_focus': 'pediatric_pulmonology',
328
+ 'source': 'default_knowledge'
329
+ },
330
+ {
331
+ 'id': 7,
332
+ '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.",
333
+ 'medical_focus': 'pediatric_pulmonology',
334
+ 'source': 'default_knowledge'
335
+ }
336
+ ]
337
+
338
+ self.knowledge_chunks = default_knowledge
339
+ print(f"πŸ“š Loaded {len(default_knowledge)} default medical knowledge chunks")
340
+
341
+ def retrieve_medical_context(self, query: str, n_results: int = 3) -> List[str]:
342
+ """Retrieve relevant medical context using improved keyword search with pulmonology priority"""
343
+ if not self.knowledge_chunks:
344
+ return []
345
+
346
+ query_lower = query.lower()
347
+ query_words = set(query_lower.split())
348
+ chunk_scores = []
349
+
350
+ # Enhanced medical keyword mapping with pulmonology emphasis
351
+ medical_keywords = {
352
+ 'pulmonology': ['asthma', 'pneumonia', 'bronchiolitis', 'croup', 'respiratory', 'lung', 'airway', 'breathing', 'cough', 'wheeze', 'stridor'],
353
+ 'fever': ['fever', 'temperature', 'hot', 'warm', 'burning'],
354
+ 'stomach': ['stomach', 'abdominal', 'belly', 'tummy', 'pain', 'ache'],
355
+ 'rash': ['rash', 'skin', 'red', 'spots', 'bumps', 'itchy'],
356
+ 'vomiting': ['vomit', 'vomiting', 'throw up', 'sick', 'nausea'],
357
+ 'diarrhea': ['diarrhea', 'loose', 'stool', 'bowel', 'poop'],
358
+ 'dehydration': ['dehydration', 'dehydrated', 'fluids', 'water', 'thirsty'],
359
+ 'emergency': ['emergency', 'urgent', 'serious', 'severe', 'hospital', 'doctor']
360
+ }
361
+
362
+ # Expand query with related medical terms
363
+ expanded_query_words = set(query_words)
364
+ for medical_term, synonyms in medical_keywords.items():
365
+ if any(word in query_lower for word in synonyms):
366
+ expanded_query_words.update(synonyms)
367
+
368
+ for chunk_info in self.knowledge_chunks:
369
+ chunk_text = chunk_info['text'].lower()
370
+
371
+ # Calculate relevance score with expanded terms
372
+ word_overlap = sum(1 for word in expanded_query_words if word in chunk_text)
373
+ base_score = word_overlap / len(expanded_query_words) if expanded_query_words else 0
374
+
375
+ # Strong boost for pulmonology content
376
+ medical_boost = 0
377
+ medical_focus = chunk_info.get('medical_focus', '')
378
+ source = chunk_info.get('source', '')
379
+
380
+ if medical_focus == 'pediatric_pulmonology':
381
+ medical_boost = 0.8 # Highest priority for pulmonology
382
+ elif source == 'pediatric_pulmonology_file':
383
+ medical_boost = 0.7 # High priority for your uploaded data
384
+ elif medical_focus == 'emergency':
385
+ medical_boost = 0.4
386
+ elif medical_focus in ['treatments', 'diagnosis']:
387
+ medical_boost = 0.3
388
+ elif medical_focus == 'pediatric_symptoms':
389
+ medical_boost = 0.5
390
+
391
+ final_score = base_score + medical_boost
392
+
393
+ if final_score > 0:
394
+ chunk_scores.append((final_score, chunk_info['text']))
395
+
396
+ # Return top matches - prioritize pulmonology content
397
+ chunk_scores.sort(reverse=True)
398
+ results = [chunk for _, chunk in chunk_scores[:n_results]]
399
+
400
+ # If no good matches, return some default medical chunks
401
+ if not results:
402
+ results = [chunk['text'] for chunk in self.knowledge_chunks[:2]]
403
+
404
+ return results
405
+
406
+ def generate_biogpt_response(self, context: str, query: str) -> str:
407
+ """Generate medical response using BioGPT with improved prompting and cleaning"""
408
+ if not self.model or not self.tokenizer:
409
+ return "Medical model not available. Please try again later."
410
+
411
+ try:
412
+ # Create a cleaner, more direct medical prompt
413
+ prompt = f"""Medical Context: {context[:500]}
414
+
415
+ Question: {query}
416
+
417
+ Answer:"""
418
+
419
+ # Add debug print to see what we're sending to the model
420
+ print(f"πŸ” Debug - Prompt sent to model: {prompt[:200]}...")
421
+
422
+ # Tokenize input with smaller context to leave more room for generation
423
+ inputs = self.tokenizer(
424
+ prompt,
425
+ return_tensors="pt",
426
+ truncation=True,
427
+ max_length=512, # Reduced significantly
428
+ padding=True
429
+ )
430
+
431
+ # Move inputs to device
432
+ if self.device == "cuda":
433
+ inputs = {k: v.to(self.device) for k, v in inputs.items()}
434
+
435
+ # Generate response with more conservative parameters
436
+ with torch.no_grad():
437
+ outputs = self.model.generate(
438
+ **inputs,
439
+ max_new_tokens=150, # Reduced for better quality
440
+ do_sample=True,
441
+ temperature=0.4, # Lower temperature for more focused responses
442
+ top_p=0.9,
443
+ top_k=50,
444
+ pad_token_id=self.tokenizer.eos_token_id,
445
+ eos_token_id=self.tokenizer.eos_token_id,
446
+ repetition_penalty=1.2,
447
+ no_repeat_ngram_size=3,
448
+ early_stopping=True # Stop when EOS token is generated
449
+ )
450
+
451
+ # Decode response
452
+ full_response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
453
+
454
+ # Add debug print to see raw model output
455
+ print(f"πŸ” Debug - Raw model output: {full_response}")
456
+
457
+ # Extract only the generated part after "Answer:"
458
+ if "Answer:" in full_response:
459
+ generated_response = full_response.split("Answer:")[-1].strip()
460
+ else:
461
+ # Fallback: remove the prompt
462
+ generated_response = full_response[len(prompt):].strip()
463
+
464
+ print(f"πŸ” Debug - Extracted response: {generated_response}")
465
+
466
+ # Enhanced cleaning
467
+ cleaned_response = self.enhanced_clean_response(generated_response)
468
+
469
+ print(f"πŸ” Debug - Cleaned response: {cleaned_response}")
470
+
471
+ # If cleaning results in very short or empty response, use fallback
472
+ if len(cleaned_response.strip()) < 20:
473
+ print("⚠️ Response too short, using fallback")
474
+ return self.fallback_response(context, query)
475
+
476
+ return cleaned_response
477
+
478
+ except Exception as e:
479
+ print(f"⚠️ BioGPT generation failed: {e}")
480
+ return self.fallback_response(context, query)
481
+
482
+ def enhanced_clean_response(self, response: str) -> str:
483
+ """Enhanced cleaning function to remove artifacts and improve readability"""
484
+
485
+ # Remove common formatting artifacts and XML-like tags
486
+ response = re.sub(r'<[^>]*>', '', response) # Remove any XML/HTML tags
487
+ response = re.sub(r'</?\s*FREETEXT\s*>', '', response, flags=re.IGNORECASE)
488
+ response = re.sub(r'</?\s*SECTION\s*>', '', response, flags=re.IGNORECASE)
489
+ response = re.sub(r'</?\s*TITLE\s*>', '', response, flags=re.IGNORECASE)
490
+
491
+ # Remove special characters and formatting artifacts
492
+ response = re.sub(r'[β–ƒβ–„β–…β–†β–‡β–ˆβ–‰β–Šβ–‹β–Œβ–β–Žβ–β–β–‘β–’β–“β–”β–•β––β–—β–˜β–™β–šβ–›β–œβ–β–žβ–Ÿ]', '', response)
493
+ response = re.sub(r'[►◄▲▼◀▢△▽◁▷]', '', response)
494
+ response = re.sub(r'/\s*FREETEXT\s*>', '', response, flags=re.IGNORECASE)
495
+ response = re.sub(r'>\s*β–ƒ', '', response)
496
+
497
+ # Remove incomplete tags and formatting
498
+ response = re.sub(r'[<>]{1,2}', '', response)
499
+ response = re.sub(r'\s*>\s*', ' ', response)
500
+ response = re.sub(r'\s*<\s*', ' ', response)
501
+
502
+ # Clean up extra whitespace and formatting
503
+ response = re.sub(r'\n\s*\n+', ' ', response) # Replace multiple newlines with space
504
+ response = re.sub(r'\s+', ' ', response) # Replace multiple spaces with single space
505
+
506
+ # Remove incomplete sentences at the beginning or end
507
+ response = re.sub(r'^[^A-Z]*', '', response) # Remove anything before first capital letter
508
+
509
+ # Split into sentences and keep only complete ones
510
+ sentences = re.split(r'[.!?]+', response)
511
+ clean_sentences = []
512
+
513
+ for sentence in sentences:
514
+ sentence = sentence.strip()
515
+ # Keep sentences that are substantial and properly formed
516
+ if (len(sentence) > 10 and
517
+ len(sentence.split()) >= 3 and # At least 3 words
518
+ not sentence.lower().startswith(('and', 'or', 'but', 'however')) and
519
+ not re.search(r'^[^a-zA-Z]*$', sentence)): # Not just special characters
520
+ clean_sentences.append(sentence)
521
+
522
+ # Limit to 3-4 good sentences for conciseness
523
+ if len(clean_sentences) >= 3:
524
+ break
525
+
526
+ if clean_sentences:
527
+ cleaned = '. '.join(clean_sentences)
528
+ if not cleaned.endswith('.'):
529
+ cleaned += '.'
530
+
531
+ # Ensure proper capitalization
532
+ if cleaned and cleaned[0].islower():
533
+ cleaned = cleaned[0].upper() + cleaned[1:]
534
+ else:
535
+ # If no good sentences found, try to salvage something
536
+ words = response.split()
537
+ if len(words) >= 5:
538
+ cleaned = ' '.join(words[:20]) + '.' # Take first 20 words
539
+ else:
540
+ cleaned = "I don't have enough information to provide a complete answer to your question."
541
+
542
+ return cleaned.strip()
543
+
544
+ def clean_and_improve_medical_response(self, response: str) -> str:
545
+ """Enhanced cleaning and improvement of medical response"""
546
+ return self.enhanced_clean_response(response)
547
+
548
+ def clean_medical_response(self, response: str) -> str:
549
+ """Clean medical response"""
550
+ sentences = re.split(r'[.!?]+', response)
551
+ clean_sentences = []
552
+
553
+ for sentence in sentences:
554
+ sentence = sentence.strip()
555
+ if len(sentence) > 10:
556
+ clean_sentences.append(sentence)
557
+ if len(clean_sentences) >= 3:
558
+ break
559
+
560
+ if clean_sentences:
561
+ cleaned = '. '.join(clean_sentences) + '.'
562
+ else:
563
+ cleaned = response[:200] + '...' if len(response) > 200 else response
564
+
565
+ return cleaned
566
+
567
+ def fallback_response(self, context: str, query: str) -> str:
568
+ """Improved fallback response when model fails"""
569
+
570
+ # Try to extract the most relevant sentence from context
571
+ context_sentences = [s.strip() for s in context.split('.') if len(s.strip()) > 30]
572
+
573
+ if context_sentences:
574
+ # Find the sentence most relevant to the query
575
+ query_words = set(query.lower().split())
576
+ best_sentence = ""
577
+ max_overlap = 0
578
+
579
+ for sentence in context_sentences[:5]: # Check first 5 sentences
580
+ sentence_words = set(sentence.lower().split())
581
+ overlap = len(query_words.intersection(sentence_words))
582
+ if overlap > max_overlap:
583
+ max_overlap = overlap
584
+ best_sentence = sentence
585
+
586
+ if best_sentence:
587
+ # Clean the best sentence
588
+ response = best_sentence.strip()
589
+ if not response.endswith('.'):
590
+ response += '.'
591
+
592
+ # Add a second sentence if available
593
+ remaining_sentences = [s for s in context_sentences if s != best_sentence]
594
+ if remaining_sentences:
595
+ response += ' ' + remaining_sentences[0].strip()
596
+ if not response.endswith('.'):
597
+ response += '.'
598
+
599
+ return response
600
+
601
+ # Ultimate fallback - generic medical response
602
+ medical_topics = {
603
+ 'fever': "Fever in children is usually caused by infections. Monitor temperature and ensure adequate hydration. Consult a healthcare provider if fever persists or is very high.",
604
+ 'cough': "Persistent cough in children can have various causes including viral infections, asthma, or allergies. If cough lasts more than a few weeks, medical evaluation is recommended.",
605
+ 'breathing': "Breathing difficulties in children should be evaluated promptly. Signs of respiratory distress include rapid breathing, chest retractions, or difficulty speaking.",
606
+ 'asthma': "Asthma is a common chronic condition in children affecting the airways. Proper management includes avoiding triggers and using prescribed medications as directed."
607
+ }
608
+
609
+ query_lower = query.lower()
610
+ for topic, response in medical_topics.items():
611
+ if topic in query_lower:
612
+ return response
613
+
614
+ return "Based on the available medical information, I recommend consulting with a healthcare provider for personalized advice about your specific question."
615
+
616
+ def handle_conversational_interactions(self, query: str) -> Optional[str]:
617
+ """Handle conversational interactions"""
618
+ query_lower = query.lower().strip()
619
+
620
+ # Greeting patterns
621
+ exact_greetings = [
622
+ 'hello', 'hi', 'hey', 'good morning', 'good afternoon',
623
+ 'good evening', 'how are you', 'how are you doing'
624
+ ]
625
+
626
+ if query_lower in exact_greetings:
627
+ 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?"
628
+
629
+ # Thanks patterns
630
+ thanks_only = ['thank you', 'thanks', 'thank you so much', 'thanks a lot']
631
+ if query_lower in thanks_only:
632
+ 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!"
633
+
634
+ # Help patterns
635
+ help_only = ['help', 'what can you do', 'what are you', 'who are you']
636
+ if query_lower in help_only:
637
+ return """πŸ€– **About BioGPT Pediatric Pulmonology Assistant**
638
+
639
+ I'm an AI medical assistant powered by BioGPT, specialized in pediatric pulmonology and respiratory medicine. I can help with:
640
+
641
+ 🫁 **Pediatric Pulmonology:**
642
+ β€’ Asthma, bronchiolitis, pneumonia, croup
643
+ β€’ Respiratory symptoms and breathing difficulties
644
+ β€’ Treatment guidance and management
645
+ β€’ When to seek medical care
646
+
647
+ ⚠️ **Important:** I provide educational information only. Always consult healthcare professionals for medical decisions."""
648
+
649
+ return None
650
+
651
+ def chat_interface(self, message: str, history: List[List[str]]) -> str:
652
+ """Main chat interface for Gradio"""
653
+ if not message.strip():
654
+ return "Hello! I'm BioGPT, your pediatric pulmonology AI assistant. How can I help you with children's respiratory health today?"
655
+
656
+ print(f"πŸ” Processing query: '{message}'")
657
+
658
+ # Handle conversational interactions
659
+ conversational_response = self.handle_conversational_interactions(message)
660
+ if conversational_response:
661
+ print(" Handled as conversational")
662
+ return conversational_response
663
+
664
+ print(" Processing as medical query")
665
+
666
+ # Process as medical query
667
+ context = self.retrieve_medical_context(message)
668
+
669
+ if not context:
670
+ return f"""🩺 **Medical Query:** {message}
671
+
672
+ ⚠️ I don't have specific information about this topic in my current medical database. However, I recommend:
673
+
674
+ 1. **Consult Healthcare Provider**: For personalized medical advice
675
+ 2. **Emergency Signs**: If symptoms are severe, seek immediate care
676
+ 3. **Pediatric Specialist**: For specialized concerns
677
+
678
+ **For urgent medical concerns, contact your healthcare provider or emergency services.**
679
+
680
+ πŸ’‘ **Try asking about**: asthma, breathing difficulties, cough, pneumonia, or other respiratory symptoms."""
681
+
682
+ # Generate medical response
683
+ main_context = '\n\n'.join(context)
684
+ response = self.generate_biogpt_response(main_context, message)
685
+
686
+ # Format as medical response
687
+ 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."
688
+
689
+ return final_response
690
+
691
+ def get_knowledge_stats(self) -> Dict:
692
+ """Get statistics about loaded knowledge"""
693
+ if not self.knowledge_chunks:
694
+ return {"total_chunks": 0}
695
+
696
+ stats = {
697
+ "total_chunks": len(self.knowledge_chunks),
698
+ "default_knowledge": len([c for c in self.knowledge_chunks if c.get('source') == 'default_knowledge']),
699
+ "pulmonology_file_data": len([c for c in self.knowledge_chunks if c.get('source') == 'pediatric_pulmonology_file']),
700
+ "pulmonology_focused": len([c for c in self.knowledge_chunks if c.get('medical_focus') == 'pediatric_pulmonology']),
701
+ "model_used": getattr(self, 'model_name', 'Unknown')
702
+ }
703
+ return stats
704
+
705
+ # Test function
706
+ def test_chatbot_responses():
707
+ """Test the chatbot with various queries"""
708
+ print("\nπŸ§ͺ Testing BioGPT Pediatric Pulmonology Chatbot...")
709
+ print("=" * 50)
710
+
711
+ test_queries = [
712
+ "hello",
713
+ "what is asthma in children",
714
+ "my child has breathing difficulties",
715
+ "help",
716
+ "treatment for pediatric pneumonia",
717
+ "thank you"
718
+ ]
719
+
720
+ for query in test_queries:
721
+ print(f"\nπŸ” Query: '{query}'")
722
+ response = chatbot.chat_interface(query, [])
723
+ response_type = 'CONVERSATIONAL' if any(word in response for word in ['Hello!', 'welcome!', 'About BioGPT']) else 'MEDICAL'
724
+ print(f"πŸ€– Response type: {response_type}")
725
+ print(f"πŸ“ Response: {response[:100]}...")
726
+ print("-" * 30)
727
+
728
+ # Initialize the chatbot globally
729
+ print("πŸš€ Initializing BioGPT Pediatric Pulmonology Chatbot...")
730
+ chatbot = BioGPTMedicalChatbot()
731
+
732
+ # Show knowledge statistics
733
+ print("\nπŸ“Š Knowledge Base Statistics:")
734
+ stats = chatbot.get_knowledge_stats()
735
+ for key, value in stats.items():
736
+ print(f" {key}: {value}")
737
+
738
+ # Run tests
739
+ test_chatbot_responses()
740
+
741
+ def create_gradio_interface():
742
+ """Create Gradio chat interface"""
743
+
744
+ # Get current knowledge stats for display
745
+ stats = chatbot.get_knowledge_stats()
746
+
747
+ # Custom CSS for medical theme
748
+ css = """
749
+ .gradio-container {
750
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
751
+ }
752
+ .chat-message {
753
+ background-color: #f8f9fa;
754
+ border-radius: 10px;
755
+ padding: 10px;
756
+ margin: 5px;
757
+ }
758
+ """
759
+
760
+ with gr.Blocks(
761
+ css=css,
762
+ title="BioGPT Pediatric Pulmonology Assistant",
763
+ theme=gr.themes.Soft()
764
+ ) as demo:
765
+
766
+ # Header
767
+ gr.HTML(f"""
768
+ <div style="text-align: center; padding: 20px; background: linear-gradient(90deg, #667eea, #764ba2); color: white; border-radius: 10px; margin-bottom: 20px;">
769
+ <h1>🫁 BioGPT Pediatric Pulmonology Assistant</h1>
770
+ <p>Specialized AI Medical Chatbot for Children's Respiratory Health</p>
771
+ <p><strong>Powered by BioGPT | {stats['total_chunks']} Medical Knowledge Chunks Loaded</strong></p>
772
+ <p><small>Model: {stats['model_used']} | Pulmonology Data: {stats['pulmonology_file_data']} chunks</small></p>
773
+ </div>
774
+ """)
775
+
776
+ # Important disclaimer
777
+ gr.HTML("""
778
+ <div style="background-color: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 15px; margin-bottom: 20px;">
779
+ <h3 style="color: #856404; margin-top: 0;">⚠️ Medical Disclaimer</h3>
780
+ <p style="color: #856404; margin-bottom: 0;">
781
+ This AI provides educational pediatric pulmonology information only and is NOT a substitute for professional medical advice,
782
+ diagnosis, or treatment. Always consult qualified healthcare providers for medical decisions.
783
+ <strong>In case of respiratory emergency, call emergency services immediately.</strong>
784
+ </p>
785
+ </div>
786
+ """)
787
+
788
+ # Chat interface
789
+ chatbot_interface = gr.ChatInterface(
790
+ fn=chatbot.chat_interface,
791
+ title="πŸ’¬ Chat with BioGPT Pulmonology Assistant",
792
+ description="Ask me about pediatric respiratory health, asthma, breathing difficulties, and pulmonology treatments.",
793
+ examples=[
794
+ "What is asthma in children?",
795
+ "My child has a persistent cough, what should I do?",
796
+ "How is bronchiolitis treated in infants?",
797
+ "When should I be worried about my child's breathing?",
798
+ "What are the signs of pneumonia in children?",
799
+ "How can I prevent respiratory infections?"
800
+ ],
801
+ retry_btn=None,
802
+ undo_btn=None,
803
+ clear_btn="πŸ—‘οΈ Clear Chat",
804
+ submit_btn="🫁 Ask BioGPT",
805
+ chatbot=gr.Chatbot(
806
+ height=500,
807
+ placeholder="<div style='text-align: center; color: #666;'>Start a conversation with BioGPT Pediatric Pulmonology Assistant</div>",
808
+ show_copy_button=True,
809
+ bubble_full_width=False
810
+ )
811
+ )
812
+
813
+ # Information tabs
814
+ with gr.Tabs():
815
+ with gr.Tab("ℹ️ About"):
816
+ gr.Markdown(f"""
817
+ ## About BioGPT Pediatric Pulmonology Assistant
818
+
819
+ This AI assistant is powered by **BioGPT**, specialized for pediatric pulmonology and respiratory medicine.
820
+
821
+ ### 🎯 Current Knowledge Base:
822
+ - **Total Chunks**: {stats['total_chunks']}
823
+ - **Default Medical Knowledge**: {stats['default_knowledge']} chunks
824
+ - **Pulmonology File Data**: {stats['pulmonology_file_data']} chunks
825
+ - **Pulmonology Focus**: {stats['pulmonology_focused']} chunks
826
+ - **Model**: {stats['model_used']}
827
+
828
+ ### 🫁 Specializations:
829
+ - **Pediatric Asthma**: Diagnosis, treatment, management
830
+ - **Respiratory Infections**: Pneumonia, bronchiolitis, croup
831
+ - **Breathing Difficulties**: Assessment and guidance
832
+ - **Chronic Respiratory Conditions**: Long-term management
833
+ - **Emergency Respiratory Care**: When to seek immediate help
834
+
835
+ ### πŸ”§ Technical Features:
836
+ - **Model**: Microsoft BioGPT (Medical AI)
837
+ - **Auto-Loading**: Automatically loads your pulmonology data file
838
+ - **Smart Retrieval**: Prioritizes pulmonology content
839
+ - **Fallback System**: Ensures reliability across different environments
840
+
841
+ ### πŸ“± How to Use:
842
+ 1. Type your pediatric respiratory question
843
+ 2. Be specific about symptoms or conditions
844
+ 3. Ask about treatments, diagnosis, or management
845
+ 4. Request guidance on when to seek care
846
+ """)
847
+
848
+ with gr.Tab("🫁 Pulmonology Topics"):
849
+ gr.Markdown("""
850
+ ## Pediatric Pulmonology Coverage
851
+
852
+ ### πŸ”΄ Common Respiratory Conditions:
853
+ - **Asthma**: Triggers, symptoms, management, action plans
854
+ - **Bronchiolitis**: RSV, treatment, when to hospitalize
855
+ - **Pneumonia**: Bacterial vs viral, antibiotics, recovery
856
+ - **Croup**: Barking cough, stridor, home treatment
857
+ - **Bronchitis**: Acute vs chronic, treatment approaches
858
+
859
+ ### 🟑 Respiratory Symptoms:
860
+ - **Cough**: Persistent, productive, dry, nocturnal
861
+ - **Wheezing**: Causes, assessment, treatment
862
+ - **Shortness of Breath**: Evaluation and management
863
+ - **Chest Pain**: When concerning in children
864
+ - **Stridor**: Upper airway obstruction signs
865
+
866
+ ### 🟒 Diagnostic & Treatment:
867
+ - **Pulmonary Function Tests**: When appropriate
868
+ - **Imaging**: X-rays, CT scans for respiratory issues
869
+ - **Medications**: Bronchodilators, steroids, antibiotics
870
+ - **Oxygen Therapy**: Indications and monitoring
871
+ - **Respiratory Support**: CPAP, ventilation considerations
872
+
873
+ ### πŸ”΅ Prevention & Management:
874
+ - **Trigger Avoidance**: Environmental controls
875
+ - **Vaccination**: Respiratory disease prevention
876
+ - **Exercise Guidelines**: For children with respiratory conditions
877
+ - **School Management**: Asthma action plans, inhaler use
878
+ """)
879
+
880
+ with gr.Tab("⚠️ Emergency & Safety"):
881
+ gr.Markdown("""
882
+ ## Respiratory Emergency Guidance
883
+
884
+ ### 🚨 CALL EMERGENCY SERVICES IMMEDIATELY:
885
+ - **Severe Breathing Difficulty**: Cannot speak in full sentences
886
+ - **Blue Lips or Fingernails**: Cyanosis indicating oxygen deprivation
887
+ - **Severe Wheezing**: With significant distress
888
+ - **Stridor at Rest**: High-pitched breathing sound
889
+ - **Unconsciousness**: Related to breathing problems
890
+ - **Severe Chest Retractions**: Pulling in around ribs/sternum
891
+
892
+ ### πŸ₯ SEEK IMMEDIATE MEDICAL CARE:
893
+ - **Persistent High Fever**: >104Β°F (40Β°C) with respiratory symptoms
894
+ - **Worsening Symptoms**: Despite treatment
895
+ - **Dehydration Signs**: With respiratory illness
896
+ - **Significant Behavior Changes**: Extreme lethargy, irritability
897
+ - **Inhaler Not Helping**: Asthma symptoms not responding
898
+
899
+ ### πŸ“ž CONTACT HEALTHCARE PROVIDER:
900
+ - **New Respiratory Symptoms**: Lasting more than a few days
901
+ - **Chronic Cough**: Persisting beyond 2-3 weeks
902
+ - **Asthma Questions**: About medications or management
903
+ - **Fever with Cough**: Especially if productive
904
+ - **Exercise Limitations**: Due to breathing difficulties
905
+
906
+ ### 🏠 HOME MONITORING:
907
+ - **Respiratory Rate**: Normal ranges by age
908
+ - **Oxygen Saturation**: If pulse oximeter available
909
+ - **Peak Flow**: For children with asthma
910
+ - **Symptom Tracking**: Using asthma diaries or apps
911
+ """)
912
+
913
+ with gr.Tab("πŸ“ Data Information"):
914
+ gr.Markdown(f"""
915
+ ## Knowledge Base Status
916
+
917
+ ### πŸ“Š Current Data Loaded:
918
+ - **Total Medical Chunks**: {stats['total_chunks']}
919
+ - **Default Knowledge**: {stats['default_knowledge']} chunks
920
+ - **Your Pulmonology File**: {stats['pulmonology_file_data']} chunks
921
+ - **Pulmonology Focused**: {stats['pulmonology_focused']} chunks
922
+ - **AI Model**: {stats['model_used']}
923
+
924
+ ### πŸ“ How Your Data Is Used:
925
+ 1. **Auto-Detection**: System automatically looks for 'Pediatric_cleaned.txt'
926
+ 2. **Smart Processing**: Breaks your file into medical chunks
927
+ 3. **Priority Ranking**: Pulmonology content gets highest priority
928
+ 4. **Context Retrieval**: Relevant chunks are used to answer questions
929
+
930
+ ### πŸ“‚ Expected File Formats:
931
+ - **Filename**: 'Pediatric_cleaned.txt' (case variations accepted)
932
+ - **Content**: Plain text with medical information
933
+ - **Structure**: Paragraphs, sections, or bullet points
934
+ - **Focus**: Pediatric pulmonology and respiratory medicine
935
+
936
+ ### πŸ”„ Upload Instructions:
937
+ 1. Go to your Hugging Face Space
938
+ 2. Click "Files" tab
939
+ 3. Upload your 'Pediatric_cleaned.txt' file
940
+ 4. Restart the Space to reload data
941
+
942
+ {"βœ… **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."}
943
+ """)
944
+
945
+ # Footer
946
+ gr.HTML("""
947
+ <div style="text-align: center; padding: 20px; margin-top: 30px; border-top: 1px solid #ddd; color: #666;">
948
+ <p>🫁 <strong>BioGPT Pediatric Pulmonology Assistant</strong> | Powered by Microsoft BioGPT</p>
949
+ <p>Specialized in Children's Respiratory Health β€’ Always consult healthcare professionals</p>
950
+ </div>
951
+ """)
952
+
953
+ return demo
954
+
955
+ # Create and launch the interface
956
+ demo = create_gradio_interface()
957
+
958
+ if __name__ == "__main__":
959
+ # Launch the app
960
+ demo.launch(
961
+ server_name="0.0.0.0",
962
+ server_port=7860,
963
+ share=False
964
+ )