File size: 13,485 Bytes
19aaa42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
#!/usr/bin/env python3
"""
Maternal Health RAG Chatbot - Gradio Interface
Complete chatbot interface for Sri Lankan maternal health guidelines
"""

import gradio as gr
import json
import time
from typing import List, Tuple, Dict, Any
from datetime import datetime
from pathlib import Path

from maternal_health_rag import MaternalHealthRAG, QueryResponse

class MaternalHealthChatbot:
    """Maternal Health Chatbot with Gradio interface"""
    
    def __init__(self):
        self.rag_system = None
        self.chat_history = []
        self.session_stats = {
            'queries_processed': 0,
            'total_response_time': 0.0,
            'session_start': datetime.now()
        }
        
        # Initialize RAG system
        self.initialize_chatbot()
    
    def initialize_chatbot(self):
        """Initialize the RAG system for the chatbot"""
        try:
            print("πŸš€ Initializing Maternal Health RAG Chatbot...")
            self.rag_system = MaternalHealthRAG(use_mock_llm=True)
            print("βœ… Chatbot initialized successfully!")
        except Exception as e:
            print(f"❌ Failed to initialize chatbot: {e}")
            raise
    
    def process_query(self, message: str, history: List[List[str]]) -> Tuple[str, List[List[str]]]:
        """Process user query and return response with updated history"""
        
        if not message.strip():
            return "", history
        
        try:
            # Process query through RAG system
            response = self.rag_system.query(message)
            
            # Update session statistics
            self.session_stats['queries_processed'] += 1
            self.session_stats['total_response_time'] += response.response_time
            
            # Format response with metadata
            formatted_response = self.format_response(response)
            
            # Update chat history
            history.append([message, formatted_response])
            
            return "", history
            
        except Exception as e:
            error_response = f"I apologize, but I encountered an error: {str(e)}. Please try rephrasing your question."
            history.append([message, error_response])
            return "", history
    
    def format_response(self, response: QueryResponse) -> str:
        """Format the RAG response for display"""
        
        # Main answer
        formatted_answer = f"**πŸ₯ Clinical Response:**\n{response.answer}\n\n"
        
        # Confidence and metadata
        confidence_emoji = "🟒" if response.confidence >= 0.7 else "🟑" if response.confidence >= 0.4 else "πŸ”΄"
        formatted_answer += f"**πŸ“Š Response Metadata:**\n"
        formatted_answer += f"{confidence_emoji} Confidence: {response.confidence:.1%}\n"
        formatted_answer += f"⏱️ Response Time: {response.response_time:.2f}s\n"
        formatted_answer += f"πŸ“š Sources: {response.metadata['num_sources']} guidelines\n"
        
        if response.metadata['content_types']:
            content_types = ", ".join(response.metadata['content_types'])
            formatted_answer += f"πŸ“‹ Content Types: {content_types}\n"
        
        # Source details (for high-confidence responses)
        if response.confidence >= 0.6 and response.sources:
            formatted_answer += f"\n**πŸ“– Key Sources:**\n"
            for i, source in enumerate(response.sources[:3], 1):  # Show top 3 sources
                source_preview = source.content[:150] + "..." if len(source.content) > 150 else source.content
                formatted_answer += f"{i}. **{source.chunk_type.title()}** (Score: {source.score:.2f})\n"
                formatted_answer += f"   {source_preview}\n\n"
        
        # Safety disclaimer
        formatted_answer += "\n---\n"
        formatted_answer += "⚠️ **Medical Disclaimer:** This information is based on Sri Lankan maternal health guidelines and is for educational purposes only. Always consult with qualified healthcare professionals for medical decisions."
        
        return formatted_answer
    
    def get_example_queries(self) -> List[str]:
        """Get example queries for the interface"""
        return [
            "What is the recommended dosage of magnesium sulfate for preeclampsia?",
            "How should postpartum hemorrhage be managed in emergency situations?",
            "What are the signs and symptoms of puerperal sepsis?",
            "What is the normal fetal heart rate range during labor?",
            "When is cesarean section indicated during delivery?",
            "How to manage gestational diabetes during pregnancy?",
            "What are the contraindications for vaginal delivery?",
            "How to recognize and manage eclampsia?",
            "What is the proper management of prolonged labor?",
            "How to handle breech presentation during delivery?"
        ]
    
    def clear_chat(self) -> List[List[str]]:
        """Clear chat history"""
        self.chat_history = []
        return []
    
    def get_system_info(self) -> str:
        """Get system information and statistics"""
        if not self.rag_system:
            return "❌ RAG system not initialized"
        
        stats = self.rag_system.get_system_stats()
        session_time = (datetime.now() - self.session_stats['session_start']).total_seconds()
        
        avg_response_time = (
            self.session_stats['total_response_time'] / self.session_stats['queries_processed']
            if self.session_stats['queries_processed'] > 0 else 0
        )
        
        info = f"""
## πŸ₯ Maternal Health RAG Assistant - System Information

### πŸ“Š Knowledge Base Statistics
- **Total Medical Chunks:** {stats['vector_store']['total_chunks']:,}
- **Embedding Model:** {stats['vector_store']['embedding_model']}
- **Vector Store Size:** {stats['vector_store']['vector_store_size_mb']:.1f} MB
- **Clinical Content Types:** {len(stats['vector_store']['chunk_type_distribution'])}

### 🧠 RAG Configuration
- **Default Results:** {stats['rag_config']['default_k']} sources per query
- **Context Length:** {stats['rag_config']['max_context_length']:,} characters max
- **LLM Type:** {stats['rag_config']['llm_type'].title()}

### πŸ“ˆ Session Statistics
- **Queries Processed:** {self.session_stats['queries_processed']}
- **Average Response Time:** {avg_response_time:.2f}s
- **Session Duration:** {session_time:.0f}s
- **System Status:** {stats['status'].title()}

### πŸ“š Document Coverage
This assistant covers **15 Sri Lankan maternal health guidelines** including:
- National Guidelines for Maternal Care
- SLJOG Clinical Guidelines
- Emergency Management Protocols
- Dosage and Treatment Guidelines
- Postnatal Care Guidelines
"""
        return info

def create_chatbot_interface():
    """Create the Gradio chatbot interface"""
    
    # Initialize chatbot
    chatbot = MaternalHealthChatbot()
    
    # Create Gradio interface
    with gr.Blocks(
        title="Maternal Health Assistant", 
        theme=gr.themes.Soft(),
        css="""
        .gradio-container {
            font-family: 'Arial', sans-serif;
        }
        .chat-message {
            font-size: 16px;
            line-height: 1.5;
        }
        """
    ) as demo:
        
        # Header
        gr.Markdown("""
        # πŸ₯ Sri Lankan Maternal Health RAG Assistant
        
        **Your AI assistant for Sri Lankan maternal health guidelines**
        
        Ask questions about:
        - πŸ’Š Medication dosages and protocols
        - 🚨 Emergency management procedures  
        - 🀱 Maternal and fetal care guidelines
        - πŸ“‹ Clinical decision-making support
        - πŸ”¬ Diagnostic criteria and procedures
        
        *Based on official Sri Lankan maternal health guidelines and SLJOG recommendations*
        """)
        
        with gr.Tab("πŸ’¬ Chat Assistant"):
            # Chat interface
            chatbot_interface = gr.Chatbot(
                label="Maternal Health Assistant",
                height=500,
                elem_classes=["chat-message"]
            )
            
            msg = gr.Textbox(
                label="Your Question",
                placeholder="Ask me about maternal health guidelines, emergency protocols, dosages, or clinical procedures...",
                lines=2
            )
            
            with gr.Row():
                submit_btn = gr.Button("πŸ” Ask Question", variant="primary")
                clear_btn = gr.Button("πŸ—‘οΈ Clear Chat", variant="secondary")
            
            # Example queries
            gr.Markdown("### πŸ’‘ Example Questions:")
            with gr.Row():
                examples = chatbot.get_example_queries()
                for i in range(0, len(examples), 2):
                    with gr.Column():
                        if i < len(examples):
                            gr.Button(
                                examples[i], 
                                variant="outline",
                                size="sm"
                            ).click(
                                lambda x=examples[i]: x,
                                outputs=msg
                            )
                        if i+1 < len(examples):
                            gr.Button(
                                examples[i+1], 
                                variant="outline",
                                size="sm"
                            ).click(
                                lambda x=examples[i+1]: x,
                                outputs=msg
                            )
        
        with gr.Tab("πŸ“Š System Information"):
            system_info = gr.Markdown(
                chatbot.get_system_info(),
                label="System Information"
            )
            
            refresh_btn = gr.Button("πŸ”„ Refresh Stats", variant="secondary")
            refresh_btn.click(
                chatbot.get_system_info,
                outputs=system_info
            )
        
        with gr.Tab("ℹ️ About"):
            gr.Markdown("""
            ## About This Assistant
            
            This **Maternal Health RAG Assistant** provides information based on official Sri Lankan maternal health guidelines using Retrieval-Augmented Generation (RAG) technology.
            
            ### πŸ”§ Technical Features
            - **Vector-based search** through 542 medical content chunks
            - **Semantic similarity** using all-MiniLM-L6-v2 embeddings
            - **Clinical importance scoring** for prioritizing critical information
            - **Medical context filtering** by content type (dosage, emergency, procedure, etc.)
            - **Sub-second response times** with confidence scoring
            
            ### πŸ“š Knowledge Base
            - **15 comprehensive documents** covering maternal health
            - **479 pages** of clinical guidelines processed
            - **48 clinical tables** with dosage and protocol information
            - **107,010 words** of medical content indexed
            
            ### ⚠️ Important Disclaimers
            1. **For Educational Use Only:** This tool provides information based on guidelines but should not replace professional medical judgment
            2. **Always Consult Healthcare Professionals:** Medical decisions should always involve qualified healthcare providers
            3. **Regular Updates:** Guidelines may change - always verify with the latest official sources
            4. **Emergency Situations:** In medical emergencies, contact emergency services immediately
            
            ### πŸ—οΈ Built With
            - **LangChain** for RAG pipeline orchestration
            - **FAISS** for efficient vector similarity search
            - **Sentence Transformers** for medical text embeddings
            - **Gradio** for the user interface
            - **pdfplumber** for medical document processing
            
            ---
            *Developed for educational and clinical reference purposes*
            """)
        
        # Event handlers
        submit_btn.click(
            chatbot.process_query,
            inputs=[msg, chatbot_interface],
            outputs=[msg, chatbot_interface]
        )
        
        msg.submit(
            chatbot.process_query,
            inputs=[msg, chatbot_interface],
            outputs=[msg, chatbot_interface]
        )
        
        clear_btn.click(
            chatbot.clear_chat,
            outputs=chatbot_interface
        )
    
    return demo

def main():
    """Main function to launch the chatbot"""
    print("πŸš€ Launching Maternal Health RAG Chatbot...")
    
    try:
        # Create and launch interface
        demo = create_chatbot_interface()
        
        print("βœ… Chatbot interface created successfully!")
        print("🌐 Launching on http://localhost:7860")
        print("πŸ“± Access from other devices using the public link")
        
        # Launch with public sharing for easier access
        demo.launch(
            server_name="0.0.0.0",  # Allow external access
            server_port=7860,
            share=True,  # Create public link
            show_error=True,
            quiet=False
        )
        
    except Exception as e:
        print(f"❌ Failed to launch chatbot: {e}")
        raise

if __name__ == "__main__":
    main()