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|
+
#!/usr/bin/env python
|
2 |
+
"""Streamlit app for the Drug Interaction System."""
|
3 |
+
|
4 |
+
import os
|
5 |
+
import sys
|
6 |
+
import streamlit as st
|
7 |
+
import matplotlib.pyplot as plt
|
8 |
+
import io
|
9 |
+
import base64
|
10 |
+
import networkx as nx
|
11 |
+
import uuid
|
12 |
+
|
13 |
+
# Add the current directory to the Python path
|
14 |
+
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
|
15 |
+
|
16 |
+
# Import the necessary components from your package
|
17 |
+
from src.models.chatbot import DrugInteractionChatbot
|
18 |
+
|
19 |
+
# Initialize the chatbot
|
20 |
+
@st.cache_resource
|
21 |
+
def get_chatbot():
|
22 |
+
"""Get or create the chatbot instance with caching."""
|
23 |
+
return DrugInteractionChatbot()
|
24 |
+
|
25 |
+
# Set page config
|
26 |
+
st.set_page_config(
|
27 |
+
page_title="Drug Interaction Assistant",
|
28 |
+
page_icon="💊",
|
29 |
+
layout="wide",
|
30 |
+
initial_sidebar_state="expanded"
|
31 |
+
)
|
32 |
+
|
33 |
+
# Title and description
|
34 |
+
st.title("Drug Interaction Assistant")
|
35 |
+
st.markdown("""
|
36 |
+
This application helps you analyze drug interactions, get information about medications,
|
37 |
+
and visualize drug interaction networks. Powered by biomedical language models.
|
38 |
+
""")
|
39 |
+
|
40 |
+
# Initialize session state for chat history
|
41 |
+
if "messages" not in st.session_state:
|
42 |
+
st.session_state.messages = []
|
43 |
+
|
44 |
+
# Sidebar with information
|
45 |
+
with st.sidebar:
|
46 |
+
st.header("About")
|
47 |
+
st.markdown("""
|
48 |
+
This Drug Interaction Assistant can:
|
49 |
+
- Analyze potential interactions between medications
|
50 |
+
- Provide detailed information about specific drugs
|
51 |
+
- Analyze clinical notes for drug mentions and interactions
|
52 |
+
- Generate visualizations of drug interaction networks
|
53 |
+
""")
|
54 |
+
|
55 |
+
st.header("Example Questions")
|
56 |
+
st.markdown("""
|
57 |
+
- "Can I take aspirin and warfarin together?"
|
58 |
+
- "Tell me about metformin"
|
59 |
+
- "Analyze this clinical note: Patient is taking..."
|
60 |
+
- "Show me a visualization for warfarin"
|
61 |
+
""")
|
62 |
+
|
63 |
+
# Main content area
|
64 |
+
col1, col2 = st.columns([2, 1])
|
65 |
+
|
66 |
+
with col1:
|
67 |
+
# Chat interface
|
68 |
+
st.header("Chat with the Assistant")
|
69 |
+
|
70 |
+
# Display chat history
|
71 |
+
for message in st.session_state.messages:
|
72 |
+
with st.chat_message(message["role"]):
|
73 |
+
st.markdown(message["content"])
|
74 |
+
|
75 |
+
# Chat input
|
76 |
+
if prompt := st.chat_input("Ask about drug interactions..."):
|
77 |
+
# Add user message to chat history
|
78 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
79 |
+
|
80 |
+
# Display user message
|
81 |
+
with st.chat_message("user"):
|
82 |
+
st.markdown(prompt)
|
83 |
+
|
84 |
+
# Get chatbot response
|
85 |
+
chatbot = get_chatbot()
|
86 |
+
response = chatbot.process_message(prompt)
|
87 |
+
|
88 |
+
# Check if we need to generate a visualization
|
89 |
+
visualization_needed = False
|
90 |
+
drug_name = None
|
91 |
+
|
92 |
+
if "interaction found between" in response:
|
93 |
+
# Extract drug name from response
|
94 |
+
import re
|
95 |
+
match = re.search(r'interaction found between (.+?) and', response)
|
96 |
+
if match:
|
97 |
+
drug_name = match.group(1)
|
98 |
+
visualization_needed = True
|
99 |
+
|
100 |
+
# Add assistant response to chat history
|
101 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
102 |
+
|
103 |
+
# Display assistant response
|
104 |
+
with st.chat_message("assistant"):
|
105 |
+
st.markdown(response)
|
106 |
+
|
107 |
+
# Generate and display visualization if needed
|
108 |
+
if visualization_needed and drug_name:
|
109 |
+
try:
|
110 |
+
G, error = chatbot.processor.generate_network(drug_name)
|
111 |
+
if not error:
|
112 |
+
# Create visualization
|
113 |
+
plt.figure(figsize=(10, 8))
|
114 |
+
|
115 |
+
# Get positions
|
116 |
+
pos = nx.spring_layout(G, seed=42)
|
117 |
+
|
118 |
+
# Draw nodes
|
119 |
+
node_sizes = [G.nodes[node].get('size', 10) for node in G.nodes()]
|
120 |
+
node_colors = [G.nodes[node].get('color', 'blue') for node in G.nodes()]
|
121 |
+
nx.draw_networkx_nodes(G, pos, node_size=node_sizes, node_color=node_colors, alpha=0.8)
|
122 |
+
|
123 |
+
# Draw edges with colors based on severity
|
124 |
+
edge_colors = []
|
125 |
+
edge_widths = []
|
126 |
+
for u, v, data in G.edges(data=True):
|
127 |
+
edge_colors.append(data.get('color', 'gray'))
|
128 |
+
edge_widths.append(data.get('weight', 1))
|
129 |
+
|
130 |
+
nx.draw_networkx_edges(G, pos, edge_color=edge_colors, width=edge_widths, alpha=0.7)
|
131 |
+
|
132 |
+
# Add labels
|
133 |
+
nx.draw_networkx_labels(G, pos, font_size=10, font_family="sans-serif")
|
134 |
+
|
135 |
+
# Save to BytesIO
|
136 |
+
buf = io.BytesIO()
|
137 |
+
plt.axis('off')
|
138 |
+
plt.tight_layout()
|
139 |
+
plt.savefig(buf, format='png', dpi=150)
|
140 |
+
buf.seek(0)
|
141 |
+
plt.close()
|
142 |
+
|
143 |
+
# Convert to base64 for display
|
144 |
+
img_str = base64.b64encode(buf.read()).decode('utf-8')
|
145 |
+
st.image(f"data:image/png;base64,{img_str}", caption=f"Interaction Network for {drug_name}")
|
146 |
+
except Exception as e:
|
147 |
+
st.error(f"Error generating visualization: {str(e)}")
|
148 |
+
|
149 |
+
with col2:
|
150 |
+
# Drug information section
|
151 |
+
st.header("Drug Information")
|
152 |
+
|
153 |
+
# Drug search
|
154 |
+
drug_search = st.text_input("Search for a drug", key="drug_search")
|
155 |
+
|
156 |
+
if drug_search:
|
157 |
+
chatbot = get_chatbot()
|
158 |
+
drug_info = chatbot.processor.get_drug_information(drug_search)
|
159 |
+
|
160 |
+
if drug_info:
|
161 |
+
st.subheader(drug_info.get("drug_name", drug_search))
|
162 |
+
|
163 |
+
if drug_info.get("drug_class") and drug_info["drug_class"] != "Information not available":
|
164 |
+
st.markdown(f"**Drug Class:** {drug_info['drug_class']}")
|
165 |
+
|
166 |
+
if drug_info.get("mechanism") and drug_info["mechanism"] != "Information not available":
|
167 |
+
st.markdown(f"**Mechanism of Action:** {drug_info['mechanism']}")
|
168 |
+
|
169 |
+
if drug_info.get("indications") and drug_info["indications"][0] != "Information not available":
|
170 |
+
st.markdown("**Common Indications:**")
|
171 |
+
for indication in drug_info["indications"]:
|
172 |
+
st.markdown(f"- {indication}")
|
173 |
+
|
174 |
+
if drug_info.get("side_effects") and drug_info["side_effects"][0] != "Information not available":
|
175 |
+
st.markdown("**Common Side Effects:**")
|
176 |
+
for effect in drug_info["side_effects"]:
|
177 |
+
st.markdown(f"- {effect}")
|
178 |
+
|
179 |
+
if drug_info.get("common_interactions") and drug_info["common_interactions"][0] != "Information not available":
|
180 |
+
st.markdown("**Common Interactions:**")
|
181 |
+
for interaction in drug_info["common_interactions"]:
|
182 |
+
st.markdown(f"- {interaction}")
|
183 |
+
|
184 |
+
if drug_info.get("contraindications") and drug_info["contraindications"][0] != "Information not available":
|
185 |
+
st.markdown("**Contraindications:**")
|
186 |
+
for contraindication in drug_info["contraindications"]:
|
187 |
+
st.markdown(f"- {contraindication}")
|
188 |
+
else:
|
189 |
+
st.warning(f"No information found for {drug_search}")
|
190 |
+
|
191 |
+
# Clinical note analysis section
|
192 |
+
st.header("Clinical Note Analysis")
|
193 |
+
clinical_note = st.text_area("Enter clinical note to analyze", height=150)
|
194 |
+
|
195 |
+
if clinical_note and st.button("Analyze Note"):
|
196 |
+
chatbot = get_chatbot()
|
197 |
+
results = chatbot.processor.extract_drugs_from_clinical_notes(clinical_note)
|
198 |
+
|
199 |
+
# Display medications
|
200 |
+
if results["medications"]:
|
201 |
+
st.subheader("Medications Identified")
|
202 |
+
for med in results["medications"]:
|
203 |
+
name = med.get("name", "Unknown")
|
204 |
+
dosage = med.get("dosage", "Not specified")
|
205 |
+
frequency = med.get("frequency", "Not specified")
|
206 |
+
|
207 |
+
if dosage != "Not specified" or frequency != "Not specified":
|
208 |
+
st.markdown(f"- **{name}**: {dosage} {frequency}")
|
209 |
+
else:
|
210 |
+
st.markdown(f"- **{name}**")
|
211 |
+
else:
|
212 |
+
st.info("No medications were identified in the clinical notes.")
|
213 |
+
|
214 |
+
# Display potential interactions
|
215 |
+
if results.get("potential_interactions"):
|
216 |
+
st.subheader("Potential Interactions")
|
217 |
+
for interaction in results["potential_interactions"]:
|
218 |
+
drug1 = interaction.get("drug1", "Unknown")
|
219 |
+
drug2 = interaction.get("drug2", "Unknown")
|
220 |
+
concern = interaction.get("concern", "Potential interaction")
|
221 |
+
|
222 |
+
st.markdown(f"- **{drug1}** + **{drug2}**: {concern}")
|
223 |
+
elif results.get("database_interactions"):
|
224 |
+
st.subheader("Potential Interactions")
|
225 |
+
for interaction in results["database_interactions"]:
|
226 |
+
drug1 = interaction.get("drug1", "Unknown")
|
227 |
+
drug2 = interaction.get("drug2", "Unknown")
|
228 |
+
desc = interaction.get("description", "Potential interaction")
|
229 |
+
severity = interaction.get("severity", "Unknown")
|
230 |
+
|
231 |
+
st.markdown(f"- **{drug1}** + **{drug2}**: {desc} ({severity})")
|
232 |
+
else:
|
233 |
+
st.info("No potential interactions were identified.")
|
234 |
+
|
235 |
+
# Footer
|
236 |
+
st.markdown("---")
|
237 |
+
st.markdown("""
|
238 |
+
<div style='text-align: center'>
|
239 |
+
<p>Drug Interaction Assistant | Powered by Biomedical Language Models</p>
|
240 |
+
<p><small>This information is for educational purposes only. Always consult a healthcare professional for medical advice.</small></p>
|
241 |
+
</div>
|
242 |
+
""", unsafe_allow_html=True)
|