Spaces:
Running
Running
File size: 5,678 Bytes
0a5c991 |
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 |
"""
Streamlit application for the medical chatbot
"""
import streamlit as st
import time
from embedding_service import EmbeddingService
from medical_chatbot import MedicalChatbot
import os
# Page configuration
st.set_page_config(
page_title="Medical Chatbot",
page_icon="π₯",
layout="wide"
)
# Initialize session state
if "chatbot" not in st.session_state:
st.session_state.chatbot = None
st.session_state.embeddings_initialized = False
st.session_state.messages = []
def initialize_chatbot():
"""Initialize the chatbot and embedding service"""
try:
if not st.session_state.embeddings_initialized:
with st.spinner("Initializing medical chatbot..."):
embedding_service = EmbeddingService()
st.session_state.chatbot = MedicalChatbot(embedding_service)
st.session_state.embeddings_initialized = True
except Exception as e:
st.error(f"Error initializing chatbot: {str(e)}")
st.error("Please check your API keys in the .env file")
st.stop()
# Initialize chatbot
initialize_chatbot()
# Header
st.title("π₯ Medical Chatbot")
st.markdown("Ask medical questions and get evidence-based answers with citations and confidence scores.")
# Sidebar
with st.sidebar:
st.header("βοΈ Settings")
st.markdown("### About")
st.info("""
This medical chatbot:
- Uses Sentence Transformers for embeddings
- Retrieves relevant information from medical databases
- Uses Gemini 1.5 Flash for generating responses
- Provides citations and confidence scores
**Important:** This is not a substitute for professional medical advice. Always consult with healthcare professionals for medical decisions.
""")
st.markdown("### Status")
if st.session_state.embeddings_initialized:
st.success("β Chatbot Initialized")
else:
st.error("β Not Initialized")
if st.button("π Reload Database"):
st.warning("This will reload the medical database. This may take a few minutes.")
st.session_state.embeddings_initialized = False
initialize_chatbot()
st.rerun()
# Display chat history
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Display confidence and citations if available
if "confidence" in message and "citations" in message:
st.markdown(f"**Confidence:** {message['confidence']} ({message['confidence_score']:.2f})")
if message["citations"]:
with st.expander("π View Sources"):
for cit_id, cit_info in message["citations"].items():
st.markdown(f"""
**{cit_id}**
- Source: {cit_info['metadata']['source']}
- Similarity: {cit_info['similarity_score']}
- Text: {cit_info['text']}
""")
# Chat input
if prompt := st.chat_input("Ask a medical question..."):
# Add user message to history
st.session_state.messages.append({"role": "user", "content": prompt})
# Display user message
with st.chat_message("user"):
st.markdown(prompt)
# Generate response
if st.session_state.chatbot:
with st.chat_message("assistant"):
with st.spinner("Thinking..."):
response = st.session_state.chatbot.generate_response(prompt)
# Display response
st.markdown(response['response'])
# Display confidence score with color
if response['confidence'] == "High":
confidence_color = "π’"
elif response['confidence'] == "Medium":
confidence_color = "π‘"
else:
confidence_color = "π΄"
st.markdown(f"{confidence_color} **Confidence:** {response['confidence']} ({response['confidence_score']:.2%})")
# Display citations
if response['citations']:
with st.expander("π Sources & Citations"):
for cit_id, cit_info in response['citations'].items():
col1, col2 = st.columns([3, 1])
with col1:
st.markdown(f"""
**{cit_id}** - {cit_info['metadata']['source']}
- Similarity: {cit_info['similarity_score']}
- Preview: {cit_info['text']}
""")
# Add disclaimer
st.warning("β οΈ This is not medical advice. Please consult with healthcare professionals for medical decisions.")
# Add assistant message to history
st.session_state.messages.append({
"role": "assistant",
"content": response['response'],
"confidence": response['confidence'],
"confidence_score": response['confidence_score'],
"citations": response['citations']
})
else:
st.error("Chatbot not initialized. Please check the sidebar for errors.")
# Footer
st.markdown("---")
st.markdown(
"""
<div style='text-align: center; color: gray;'>
<p>Powered by Gemini 1.5 Flash | Sentence Transformers | Pinecone DB</p>
<p>Not a substitute for professional medical advice</p>
</div>
""",
unsafe_allow_html=True
)
|