Blaiseboy commited on
Commit
42ed209
·
verified ·
1 Parent(s): 121e870

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -628
app.py DELETED
@@ -1,628 +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 Medical 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
39
- self.load_default_medical_knowledge()
40
-
41
- print("✅ BioGPT Medical Chatbot ready!")
42
-
43
- def setup_embeddings(self):
44
- """Setup medical embeddings"""
45
- try:
46
- print("🔧 Loading embeddings...")
47
- self.embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
48
- self.use_embeddings = True
49
- print("✅ Embeddings loaded successfully")
50
- except Exception as e:
51
- print(f"⚠️ Embeddings failed: {e}")
52
- self.embedding_model = None
53
- self.use_embeddings = False
54
-
55
- def setup_biogpt(self):
56
- """Setup BioGPT model with fallback"""
57
- print("🧠 Loading BioGPT model...")
58
-
59
- # Try BioGPT first, then fallback to smaller model
60
- models_to_try = [
61
- "microsoft/BioGPT-Large",
62
- "microsoft/BioGPT",
63
- "microsoft/DialoGPT-medium"
64
- ]
65
-
66
- for model_name in models_to_try:
67
- try:
68
- print(f" Trying {model_name}...")
69
-
70
- # Setup quantization for memory efficiency
71
- quantization_config = None
72
- if self.use_8bit and "BioGPT" in model_name:
73
- quantization_config = BitsAndBytesConfig(
74
- load_in_8bit=True,
75
- llm_int8_threshold=6.0,
76
- )
77
-
78
- # Load tokenizer
79
- self.tokenizer = AutoTokenizer.from_pretrained(model_name)
80
- if self.tokenizer.pad_token is None:
81
- self.tokenizer.pad_token = self.tokenizer.eos_token
82
-
83
- # Load model
84
- self.model = AutoModelForCausalLM.from_pretrained(
85
- model_name,
86
- quantization_config=quantization_config,
87
- torch_dtype=torch.float16 if self.device == "cuda" else torch.float32,
88
- device_map="auto" if self.device == "cuda" and quantization_config else None,
89
- trust_remote_code=True
90
- )
91
-
92
- if self.device == "cuda" and quantization_config is None:
93
- self.model = self.model.to(self.device)
94
-
95
- print(f"✅ Successfully loaded {model_name}!")
96
- self.model_name = model_name
97
- return
98
-
99
- except Exception as e:
100
- print(f"❌ Failed to load {model_name}: {e}")
101
- continue
102
-
103
- # If all models fail
104
- print("❌ All models failed to load")
105
- self.model = None
106
- self.tokenizer = None
107
- self.model_name = "None"
108
-
109
- def load_default_medical_knowledge(self):
110
- """Load comprehensive medical knowledge base"""
111
- default_knowledge = [
112
- {
113
- 'id': 0,
114
- '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.",
115
- 'medical_focus': 'pediatric_symptoms'
116
- },
117
- {
118
- 'id': 1,
119
- '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.",
120
- 'medical_focus': 'pediatric_symptoms'
121
- },
122
- {
123
- 'id': 2,
124
- '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.",
125
- 'medical_focus': 'pediatric_symptoms'
126
- },
127
- {
128
- 'id': 3,
129
- '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.",
130
- 'medical_focus': 'emergency'
131
- },
132
- {
133
- 'id': 4,
134
- '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.",
135
- 'medical_focus': 'prevention'
136
- },
137
- {
138
- 'id': 5,
139
- '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.",
140
- 'medical_focus': 'pediatric_symptoms'
141
- },
142
- {
143
- 'id': 6,
144
- 'text': "Skin rashes in children have many causes including viral infections (roseola, fifth disease), bacterial infections, eczema, allergic reactions, heat rash, or contact dermatitis. Most viral rashes are harmless and resolve on their own. Seek medical attention for rashes with high fever, rapidly spreading rashes, blistering, or signs of infection like pus or red streaking.",
145
- 'medical_focus': 'pediatric_symptoms'
146
- },
147
- {
148
- 'id': 7,
149
- 'text': "Stomach pain and abdominal pain in children can result from constipation, gas, viral gastroenteritis, food intolerance, appendicitis, or emotional stress. Most stomach aches are mild and resolve quickly with rest and clear fluids. Warning signs requiring immediate medical attention include severe pain, persistent vomiting, fever with abdominal pain, or pain preventing normal activities.",
150
- 'medical_focus': 'pediatric_symptoms'
151
- },
152
- {
153
- 'id': 8,
154
- 'text': "Sleep problems in children may include difficulty falling asleep, frequent night wakings, early morning awakening, or nightmares. Good sleep hygiene includes consistent bedtime routines, appropriate sleep environment (cool, dark, quiet), limiting screen time before bed, adequate physical activity during the day, and avoiding caffeine. Most sleep issues improve with consistent routines.",
155
- 'medical_focus': 'general_medical'
156
- },
157
- {
158
- 'id': 9,
159
- 'text': "Nutrition for children should include a variety of foods from all food groups: fruits, vegetables, whole grains, lean protein sources, and dairy or dairy alternatives. Limit processed foods, sugary drinks, and excessive snacks. Breastfeeding is recommended for infants for the first 6 months, with introduction of solid foods around 6 months while continuing breastfeeding.",
160
- 'medical_focus': 'prevention'
161
- },
162
- {
163
- 'id': 10,
164
- 'text': "Vomiting in children can be caused by viral gastroenteritis (stomach flu), food poisoning, motion sickness, or other illnesses. Most episodes are brief and resolve within 24-48 hours. Focus on preventing dehydration with small, frequent sips of clear fluids. Seek medical care for persistent vomiting, signs of dehydration, blood in vomit, or severe abdominal pain.",
165
- 'medical_focus': 'pediatric_symptoms'
166
- },
167
- {
168
- 'id': 11,
169
- 'text': "Diarrhea in children is often caused by viral infections, bacterial infections, food intolerance, or medications. Most cases resolve within a few days. Prevention of dehydration is key - offer clear fluids and oral rehydration solutions. Seek medical attention for bloody stools, signs of dehydration, persistent high fever, or diarrhea lasting more than a week.",
170
- 'medical_focus': 'pediatric_symptoms'
171
- },
172
- {
173
- 'id': 12,
174
- 'text': "Breathing difficulties in children can range from mild congestion to serious respiratory distress. Signs of serious breathing problems include rapid breathing, retractions (pulling in around ribs), wheezing, blue lips or fingernails, or extreme difficulty speaking. Mild congestion can be helped with humidified air and saline drops. Severe breathing difficulties require immediate medical attention.",
175
- 'medical_focus': 'emergency'
176
- },
177
- {
178
- 'id': 13,
179
- 'text': "Common childhood injuries include cuts, scrapes, bruises, and minor burns. Basic first aid includes cleaning wounds with soap and water, applying pressure to stop bleeding, and covering with clean bandages. Seek medical care for deep cuts requiring stitches, burns larger than a quarter, head injuries with loss of consciousness, or any injury causing severe pain or inability to move normally.",
180
- 'medical_focus': 'emergency'
181
- },
182
- {
183
- 'id': 14,
184
- 'text': "Ear infections are common in children and can cause ear pain, fever, irritability, and sometimes drainage from the ear. Many ear infections resolve on their own, but some require antibiotic treatment. Pain can be managed with appropriate pain relievers. Seek medical evaluation for severe ear pain, high fever, or symptoms lasting more than 2-3 days.",
185
- 'medical_focus': 'pediatric_symptoms'
186
- }
187
- ]
188
-
189
- self.knowledge_chunks = default_knowledge
190
- print(f"📚 Loaded {len(default_knowledge)} comprehensive medical knowledge chunks")
191
-
192
- def retrieve_medical_context(self, query: str, n_results: int = 3) -> List[str]:
193
- """Retrieve relevant medical context using improved keyword search"""
194
- if not self.knowledge_chunks:
195
- return []
196
-
197
- query_lower = query.lower()
198
- query_words = set(query_lower.split())
199
- chunk_scores = []
200
-
201
- # Enhanced medical keyword mapping
202
- medical_keywords = {
203
- 'fever': ['fever', 'temperature', 'hot', 'warm', 'burning'],
204
- 'cough': ['cough', 'coughing', 'respiratory', 'breathing'],
205
- 'stomach': ['stomach', 'abdominal', 'belly', 'tummy', 'pain', 'ache'],
206
- 'rash': ['rash', 'skin', 'red', 'spots', 'bumps', 'itchy'],
207
- 'vomiting': ['vomit', 'vomiting', 'throw up', 'sick', 'nausea'],
208
- 'diarrhea': ['diarrhea', 'loose', 'stool', 'bowel', 'poop'],
209
- 'dehydration': ['dehydration', 'dehydrated', 'fluids', 'water', 'thirsty'],
210
- 'breathing': ['breathing', 'breath', 'respiratory', 'lungs', 'airways'],
211
- 'emergency': ['emergency', 'urgent', 'serious', 'severe', 'hospital', 'doctor'],
212
- 'cold': ['cold', 'runny nose', 'congestion', 'sneezing'],
213
- 'sleep': ['sleep', 'sleeping', 'bedtime', 'insomnia', 'tired'],
214
- 'nutrition': ['nutrition', 'eating', 'food', 'diet', 'feeding'],
215
- 'vaccination': ['vaccine', 'vaccination', 'immunization', 'shot'],
216
- 'injury': ['injury', 'hurt', 'cut', 'burn', 'bruise', 'accident'],
217
- 'ear': ['ear', 'hearing', 'earache', 'infection']
218
- }
219
-
220
- # Expand query with related medical terms
221
- expanded_query_words = set(query_words)
222
- for medical_term, synonyms in medical_keywords.items():
223
- if any(word in query_lower for word in synonyms):
224
- expanded_query_words.update(synonyms)
225
-
226
- for chunk_info in self.knowledge_chunks:
227
- chunk_text = chunk_info['text'].lower()
228
-
229
- # Calculate relevance score with expanded terms
230
- word_overlap = sum(1 for word in expanded_query_words if word in chunk_text)
231
- base_score = word_overlap / len(expanded_query_words) if expanded_query_words else 0
232
-
233
- # Strong boost for medical focus alignment
234
- medical_boost = 0
235
- medical_focus = chunk_info.get('medical_focus', '')
236
-
237
- if medical_focus == 'pediatric_symptoms':
238
- medical_boost = 0.5
239
- elif medical_focus == 'emergency':
240
- medical_boost = 0.4
241
- elif medical_focus in ['treatments', 'diagnosis']:
242
- medical_boost = 0.3
243
- elif medical_focus == 'prevention':
244
- medical_boost = 0.2
245
-
246
- final_score = base_score + medical_boost
247
-
248
- if final_score > 0:
249
- chunk_scores.append((final_score, chunk_info['text']))
250
-
251
- # Return top matches - ensure we always have at least some context
252
- chunk_scores.sort(reverse=True)
253
- results = [chunk for _, chunk in chunk_scores[:n_results]]
254
-
255
- # If no good matches, return some default medical chunks
256
- if not results:
257
- results = [chunk['text'] for chunk in self.knowledge_chunks[:2]]
258
-
259
- return results
260
-
261
- def generate_biogpt_response(self, context: str, query: str) -> str:
262
- """Generate medical response using BioGPT"""
263
- if not self.model or not self.tokenizer:
264
- return "Medical model not available. Please try again later."
265
-
266
- try:
267
- # Create medical prompt
268
- prompt = f"""Medical Context: {context[:800]}
269
-
270
- Question: {query}
271
-
272
- Medical Answer:"""
273
-
274
- # Tokenize input
275
- inputs = self.tokenizer(
276
- prompt,
277
- return_tensors="pt",
278
- truncation=True,
279
- max_length=1024
280
- )
281
-
282
- # Move inputs to device
283
- if self.device == "cuda":
284
- inputs = {k: v.to(self.device) for k, v in inputs.items()}
285
-
286
- # Generate response
287
- with torch.no_grad():
288
- outputs = self.model.generate(
289
- **inputs,
290
- max_new_tokens=150,
291
- do_sample=True,
292
- temperature=0.7,
293
- top_p=0.9,
294
- pad_token_id=self.tokenizer.eos_token_id,
295
- repetition_penalty=1.1
296
- )
297
-
298
- # Decode response
299
- full_response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
300
-
301
- # Extract generated part
302
- if "Medical Answer:" in full_response:
303
- generated_response = full_response.split("Medical Answer:")[-1].strip()
304
- else:
305
- generated_response = full_response[len(prompt):].strip()
306
-
307
- return self.clean_medical_response(generated_response)
308
-
309
- except Exception as e:
310
- print(f"⚠️ BioGPT generation failed: {e}")
311
- return self.fallback_response(context, query)
312
-
313
- def clean_medical_response(self, response: str) -> str:
314
- """Clean medical response"""
315
- sentences = re.split(r'[.!?]+', response)
316
- clean_sentences = []
317
-
318
- for sentence in sentences:
319
- sentence = sentence.strip()
320
- if len(sentence) > 10:
321
- clean_sentences.append(sentence)
322
- if len(clean_sentences) >= 3:
323
- break
324
-
325
- if clean_sentences:
326
- cleaned = '. '.join(clean_sentences) + '.'
327
- else:
328
- cleaned = response[:200] + '...' if len(response) > 200 else response
329
-
330
- return cleaned
331
-
332
- def fallback_response(self, context: str, query: str) -> str:
333
- """Fallback response when model fails"""
334
- sentences = [s.strip() for s in context.split('.') if len(s.strip()) > 20]
335
-
336
- if sentences:
337
- response = sentences[0] + '.'
338
- if len(sentences) > 1:
339
- response += ' ' + sentences[1] + '.'
340
- else:
341
- response = context[:300] + '...'
342
-
343
- return response
344
-
345
- def handle_conversational_interactions(self, query: str) -> Optional[str]:
346
- """Handle conversational interactions - STRICT matching to avoid getting stuck"""
347
- query_lower = query.lower().strip()
348
-
349
- # VERY STRICT greeting patterns - only exact matches
350
- exact_greetings = [
351
- 'hello', 'hi', 'hey', 'good morning', 'good afternoon',
352
- 'good evening', 'how are you', 'how are you doing'
353
- ]
354
-
355
- if query_lower in exact_greetings:
356
- return "👋 Hello! I'm BioGPT, your AI medical assistant specialized in pediatric medicine. I provide evidence-based medical information. What health concern can I help you with today?"
357
-
358
- # STRICT thanks patterns - only if query is mostly thanks
359
- thanks_only = ['thank you', 'thanks', 'thank you so much', 'thanks a lot']
360
- if query_lower in thanks_only:
361
- return "🙏 You're welcome! I'm glad I could provide helpful medical information. Remember to always consult healthcare providers for personalized advice. Feel free to ask more questions!"
362
-
363
- # STRICT help patterns - only direct help requests
364
- help_only = ['help', 'what can you do', 'what are you', 'who are you']
365
- if query_lower in help_only:
366
- return """🤖 **About BioGPT Medical Assistant**
367
-
368
- I'm an AI medical assistant powered by BioGPT, specialized in pediatric medicine. I can help with:
369
-
370
- 🩺 **Medical Information:**
371
- • Pediatric symptoms and conditions
372
- • Treatment guidance
373
- • When to seek medical care
374
- • Prevention and wellness
375
-
376
- ⚠️ **Important:** I provide educational information only. Always consult healthcare professionals for medical decisions."""
377
-
378
- # Return None for everything else - let it go to medical processing
379
- return None
380
-
381
- def chat_interface(self, message: str, history: List[List[str]]) -> str:
382
- """Main chat interface for Gradio - FIXED to prevent greeting mode stuck"""
383
- if not message.strip():
384
- return "Hello! I'm BioGPT, your medical AI assistant. How can I help you with pediatric medical questions today?"
385
-
386
- print(f"🔍 Processing query: '{message}'") # Debug logging
387
-
388
- # Handle ONLY very specific conversational interactions
389
- conversational_response = self.handle_conversational_interactions(message)
390
- if conversational_response:
391
- print(" Handled as conversational") # Debug
392
- return conversational_response
393
-
394
- print(" Processing as medical query") # Debug
395
-
396
- # ALWAYS try to process as medical query if not a strict greeting
397
- context = self.retrieve_medical_context(message)
398
-
399
- if not context:
400
- # Even if no context found, provide a helpful medical response
401
- return f"""🩺 **Medical Query:** {message}
402
-
403
- ⚠️ I don't have specific information about this topic in my current medical database. However, I recommend:
404
-
405
- 1. **Consult Healthcare Provider**: For personalized medical advice
406
- 2. **Emergency Signs**: If symptoms are severe, seek immediate care
407
- 3. **Reliable Sources**: Check with pediatricians for children's health concerns
408
-
409
- **For urgent medical concerns, contact your healthcare provider or emergency services.**
410
-
411
- 💡 **Try asking about**: fever, cough, rash, dehydration, or other common pediatric symptoms."""
412
-
413
- # Generate medical response
414
- main_context = '\n\n'.join(context)
415
- response = self.generate_biogpt_response(main_context, message)
416
-
417
- # Always format as medical response
418
- final_response = f"🩺 **Medical Information:** {response}\n\n⚠️ **Important:** This information is for educational purposes only. Always consult qualified healthcare professionals for medical diagnosis, treatment, and personalized advice."
419
-
420
- return final_response
421
-
422
- # Test function to verify chatbot functionality
423
- def test_chatbot_responses():
424
- """Test the chatbot with various queries to ensure it's working properly"""
425
- print("\n🧪 Testing BioGPT Chatbot Responses...")
426
- print("=" * 50)
427
-
428
- test_queries = [
429
- "hello", # Should be conversational
430
- "what causes fever", # Should be medical
431
- "my child has a cough", # Should be medical
432
- "help", # Should be conversational
433
- "breathing problems in babies", # Should be medical
434
- "thank you" # Should be conversational
435
- ]
436
-
437
- for query in test_queries:
438
- print(f"\n🔍 Query: '{query}'")
439
- response = chatbot.chat_interface(query, [])
440
- response_type = 'CONVERSATIONAL' if any(word in response for word in ['Hello!', 'welcome!', 'About BioGPT']) else 'MEDICAL'
441
- print(f"🤖 Response type: {response_type}")
442
- print(f"📝 Response: {response[:100]}...")
443
- print("-" * 30)
444
-
445
- # Initialize the chatbot globally
446
- print("🚀 Initializing BioGPT Medical Chatbot for Gradio...")
447
- chatbot = BioGPTMedicalChatbot()
448
-
449
- # Run tests
450
- test_chatbot_responses()
451
-
452
- def create_gradio_interface():
453
- """Create Gradio chat interface"""
454
-
455
- # Custom CSS for medical theme
456
- css = """
457
- .gradio-container {
458
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
459
- }
460
- .chat-message {
461
- background-color: #f8f9fa;
462
- border-radius: 10px;
463
- padding: 10px;
464
- margin: 5px;
465
- }
466
- """
467
-
468
- with gr.Blocks(
469
- css=css,
470
- title="BioGPT Medical Assistant",
471
- theme=gr.themes.Soft()
472
- ) as demo:
473
-
474
- # Header
475
- gr.HTML("""
476
- <div style="text-align: center; padding: 20px; background: linear-gradient(90deg, #667eea, #764ba2); color: white; border-radius: 10px; margin-bottom: 20px;">
477
- <h1>🏥 BioGPT Medical Assistant</h1>
478
- <p>Professional AI Medical Chatbot powered by BioGPT</p>
479
- <p><strong>Specialized in Pediatric Medicine & Children's Health</strong></p>
480
- </div>
481
- """)
482
-
483
- # Important disclaimer
484
- gr.HTML("""
485
- <div style="background-color: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 15px; margin-bottom: 20px;">
486
- <h3 style="color: #856404; margin-top: 0;">⚠️ Medical Disclaimer</h3>
487
- <p style="color: #856404; margin-bottom: 0;">
488
- This AI provides educational medical information only and is NOT a substitute for professional medical advice,
489
- diagnosis, or treatment. Always consult qualified healthcare providers for medical decisions.
490
- <strong>In case of medical emergency, call emergency services immediately.</strong>
491
- </p>
492
- </div>
493
- """)
494
-
495
- # Chat interface
496
- chatbot_interface = gr.ChatInterface(
497
- fn=chatbot.chat_interface,
498
- title="💬 Chat with BioGPT",
499
- description="Ask me about pediatric health, symptoms, treatments, and medical guidance.",
500
- examples=[
501
- "What causes fever in children?",
502
- "How should I treat my child's cough?",
503
- "When should I be concerned about my baby's breathing?",
504
- "What are the signs of dehydration in infants?",
505
- "When should I call the doctor for my child's symptoms?",
506
- "How can I prevent common childhood illnesses?"
507
- ],
508
- retry_btn=None,
509
- undo_btn=None,
510
- clear_btn="🗑️ Clear Chat",
511
- submit_btn="🩺 Ask BioGPT",
512
- chatbot=gr.Chatbot(
513
- height=500,
514
- placeholder="<div style='text-align: center; color: #666;'>Start a conversation with BioGPT Medical Assistant</div>",
515
- show_copy_button=True,
516
- bubble_full_width=False
517
- )
518
- )
519
-
520
- # Information tabs
521
- with gr.Tabs():
522
- with gr.Tab("ℹ️ About"):
523
- gr.Markdown("""
524
- ## About BioGPT Medical Assistant
525
-
526
- This AI assistant is powered by **BioGPT**, a specialized medical language model trained on extensive medical literature.
527
-
528
- ### 🎯 Capabilities:
529
- - **Pediatric Medicine**: Specialized in children's health
530
- - **Symptom Analysis**: Understanding medical symptoms
531
- - **Treatment Guidance**: Evidence-based treatment information
532
- - **Medical Education**: Explaining medical concepts
533
- - **Emergency Guidance**: When to seek immediate care
534
-
535
- ### 🔧 Technical Features:
536
- - **Model**: Microsoft BioGPT (Medical AI)
537
- - **Specialization**: Medical and biomedical text
538
- - **Knowledge**: Based on medical literature and research
539
- - **Optimization**: Memory-efficient deployment
540
-
541
- ### 📱 How to Use:
542
- 1. Type your medical question in the chat
543
- 2. Be specific about symptoms or concerns
544
- 3. Ask about pediatric health topics
545
- 4. Request guidance on when to seek care
546
- """)
547
-
548
- with gr.Tab("🩺 Medical Topics"):
549
- gr.Markdown("""
550
- ## Supported Medical Topics
551
-
552
- ### 👶 Pediatric Specialties:
553
- - **Common Symptoms**: Fever, cough, rash, vomiting, diarrhea
554
- - **Respiratory**: Breathing issues, asthma, colds
555
- - **Digestive**: Stomach problems, feeding issues
556
- - **Skin**: Rashes, eczema, allergic reactions
557
- - **Development**: Growth and developmental concerns
558
-
559
- ### 🚨 Emergency Guidance:
560
- - When to call emergency services
561
- - Signs requiring immediate medical attention
562
- - First aid basics for children
563
-
564
- ### 💊 Treatment Information:
565
- - Evidence-based treatment options
566
- - Home care remedies
567
- - Safety considerations
568
- - Recovery expectations
569
-
570
- ### 🛡️ Prevention:
571
- - Vaccination information
572
- - Disease prevention
573
- - Healthy habits for children
574
- - Safety measures
575
- """)
576
-
577
- with gr.Tab("⚠️ Safety & Limitations"):
578
- gr.Markdown("""
579
- ## Important Safety Information
580
-
581
- ### 🚨 Emergency Situations - Call Emergency Services:
582
- - Difficulty breathing or choking
583
- - Severe allergic reactions
584
- - Unconsciousness or unresponsiveness
585
- - Severe injuries or accidents
586
- - Persistent high fever (>104°F/40°C)
587
-
588
- ### 🏥 When to Consult Healthcare Providers:
589
- - For diagnosis of medical conditions
590
- - Before starting any treatments
591
- - For prescription medications
592
- - When symptoms worsen or persist
593
- - For personalized medical advice
594
-
595
- ### 🤖 AI Limitations:
596
- - Cannot diagnose medical conditions
597
- - Cannot prescribe medications
598
- - Cannot replace professional medical judgment
599
- - May not have latest medical developments
600
- - Should not be used for emergency situations
601
-
602
- ### 📞 Additional Resources:
603
- - **Emergency**: Your local emergency number
604
- - **Poison Control**: Contact local poison control
605
- - **Pediatrician**: Your child's healthcare provider
606
- - **Nurse Hotline**: 24/7 nurse consultations (many insurance plans)
607
- """)
608
-
609
- # Footer
610
- gr.HTML("""
611
- <div style="text-align: center; padding: 20px; margin-top: 30px; border-top: 1px solid #ddd; color: #666;">
612
- <p>🤖 <strong>BioGPT Medical Assistant</strong> | Powered by Microsoft BioGPT</p>
613
- <p>For educational purposes only • Always consult healthcare professionals</p>
614
- </div>
615
- """)
616
-
617
- return demo
618
-
619
- # Create and launch the interface
620
- demo = create_gradio_interface()
621
-
622
- if __name__ == "__main__":
623
- # Launch the app
624
- demo.launch(
625
- server_name="0.0.0.0",
626
- server_port=7860,
627
- share=False
628
- )