-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamlit_app.py
More file actions
279 lines (243 loc) · 9.77 KB
/
Copy pathstreamlit_app.py
File metadata and controls
279 lines (243 loc) · 9.77 KB
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
import streamlit as st
import logging
import time
from datetime import datetime
from config import Config
from model import medical_chatbot
from data_loader import medical_data_loader
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Page configuration
st.set_page_config(
page_title="🏥 Medical Chatbot",
page_icon="🩺",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for better styling
st.markdown("""
<style>
.main-header {
background: linear-gradient(90deg, #4CAF50, #45a049);
padding: 1rem;
border-radius: 10px;
color: white;
text-align: center;
margin-bottom: 2rem;
}
.disclaimer {
background-color: #fff3cd;
border: 1px solid #ffecb5;
color: #856404;
padding: 1rem;
border-radius: 8px;
margin: 1rem 0;
}
.chat-message {
padding: 1rem;
border-radius: 10px;
margin-bottom: 1rem;
border-left: 4px solid #4CAF50;
background-color: #f8f9fa;
}
.user-message {
background-color: #e3f2fd;
border-left-color: #2196F3;
}
.bot-message {
background-color: #f1f8e9;
border-left-color: #4CAF50;
}
</style>
""", unsafe_allow_html=True)
# Initialize session state
if "messages" not in st.session_state:
st.session_state.messages = []
if "chatbot_initialized" not in st.session_state:
st.session_state.chatbot_initialized = False
if "initialization_time" not in st.session_state:
st.session_state.initialization_time = None
def initialize_chatbot():
"""Initialize the chatbot if not already done."""
if not st.session_state.chatbot_initialized:
with st.spinner("🔄 Initializing Medical Chatbot... This may take a few minutes..."):
try:
start_time = time.time()
medical_chatbot.create_qa_chain()
end_time = time.time()
st.session_state.chatbot_initialized = True
st.session_state.initialization_time = end_time - start_time
st.success(f"✅ Medical Chatbot initialized successfully in {st.session_state.initialization_time:.1f} seconds!")
return True
except Exception as e:
st.error(f"❌ Error initializing chatbot: {e}")
logger.error(f"Chatbot initialization error: {e}")
return False
return True
def process_query(user_input):
"""Process user query and get response."""
if not st.session_state.chatbot_initialized:
st.error("❌ Chatbot not initialized. Please wait for initialization to complete.")
return None
try:
with st.spinner("🤔 Processing your question..."):
result = medical_chatbot.query(user_input)
return result
except Exception as e:
st.error(f"❌ Error processing query: {e}")
logger.error(f"Query processing error: {e}")
return None
def main():
# Header
st.markdown("""
<div class="main-header">
<h1>🏥 Medical Information Chatbot</h1>
<p>Your AI-powered healthcare information assistant</p>
</div>
""", unsafe_allow_html=True)
# Sidebar
with st.sidebar:
st.header("⚙️ Settings")
# Model selection
config = Config()
available_models = list(config.LLM_PROVIDERS.keys())
selected_model = st.selectbox(
"🤖 Select LLM Provider",
available_models,
index=available_models.index(config.DEFAULT_LLM_PROVIDER)
)
# Initialize button
if st.button("🚀 Initialize Chatbot", type="primary"):
st.session_state.chatbot_initialized = False
initialize_chatbot()
# Status
st.subheader("📊 Status")
if st.session_state.chatbot_initialized:
st.success("✅ Chatbot Ready")
if st.session_state.initialization_time:
st.info(f"⏱️ Init Time: {st.session_state.initialization_time:.1f}s")
else:
st.warning("⏳ Chatbot Not Initialized")
# Statistics
if st.session_state.messages:
st.subheader("📈 Chat Statistics")
total_messages = len(st.session_state.messages)
user_messages = len([m for m in st.session_state.messages if m["role"] == "user"])
col1, col2 = st.columns(2)
with col1:
st.metric("Total Messages", total_messages)
with col2:
st.metric("Q&A Pairs", user_messages)
# Clear chat button
if st.button("🗑️ Clear Chat History"):
st.session_state.messages = []
st.rerun()
# Main content area
col1, col2 = st.columns([2, 1])
with col1:
# Chat interface
st.subheader("💬 Chat with Medical Assistant")
# Display chat messages
chat_container = st.container()
with chat_container:
for message in st.session_state.messages:
if message["role"] == "user":
st.markdown(f"""
<div class="chat-message user-message">
<strong>👤 You:</strong><br>
{message["content"]}
</div>
""", unsafe_allow_html=True)
else:
st.markdown(f"""
<div class="chat-message bot-message">
<strong>🩺 Medical Assistant:</strong><br>
{message["content"]}
</div>
""", unsafe_allow_html=True)
# Show sources if available
if "sources" in message:
with st.expander(f"📚 Sources ({len(message['sources'])} documents)"):
for i, source in enumerate(message["sources"], 1):
st.write(f"**Source {i}:**")
st.write(source["content"])
if source.get("metadata"):
st.caption(f"Metadata: {source['metadata']}")
st.divider()
# Input area
user_input = st.text_area(
"Ask your medical question:",
placeholder="e.g., What are the symptoms of diabetes?",
key="user_input",
height=100
)
col_a, col_b = st.columns([1, 4])
with col_a:
send_button = st.button("📤 Send", type="primary")
# Process input
if send_button and user_input.strip():
if not st.session_state.chatbot_initialized:
initialize_chatbot()
if st.session_state.chatbot_initialized:
# Add user message
st.session_state.messages.append({
"role": "user",
"content": user_input,
"timestamp": datetime.now()
})
# Process and add bot response
result = process_query(user_input)
if result:
bot_message = {
"role": "assistant",
"content": result.get("result", "I apologize, but I couldn't generate a response."),
"timestamp": datetime.now()
}
# Add sources if available
if result.get("source_documents"):
sources = []
for doc in result["source_documents"][:3]:
sources.append({
"content": doc.page_content[:300] + "..." if len(doc.page_content) > 300 else doc.page_content,
"metadata": doc.metadata
})
bot_message["sources"] = sources
st.session_state.messages.append(bot_message)
# Clear input and rerun
st.rerun()
with col2:
# Information panel
st.subheader("ℹ️ Information")
# Sample questions
st.markdown("**💡 Sample Questions:**")
sample_questions = [
"What are the symptoms of diabetes?",
"How does the cardiovascular system work?",
"What is hypertension?",
"What are the causes of headaches?",
"How can I maintain a healthy diet?"
]
for question in sample_questions:
if st.button(f"💭 {question}", key=f"sample_{hash(question)}"):
st.session_state["user_input"] = question
st.rerun()
# Model information
with st.expander("🤖 Model Information"):
st.write(f"**LLM Provider:** {selected_model}")
st.write(f"**Embedding Model:** {config.EMBEDDING_MODEL}")
st.write(f"**Retrieval Documents:** {config.RETRIEVAL_K}")
# Disclaimer
st.markdown("""
<div class="disclaimer">
<strong>⚠️ Important Disclaimer:</strong><br>
This chatbot provides general medical information for educational purposes only.
It is not a substitute for professional medical advice, diagnosis, or treatment.
Always consult qualified healthcare professionals for medical concerns.
</div>
""", unsafe_allow_html=True)
# Footer
st.markdown("---")
st.markdown("🏥 **Medical Chatbot** | Powered by LangChain & Hugging Face | Built with ❤️ for Healthcare")
if __name__ == "__main__":
main()