-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
217 lines (180 loc) · 6.86 KB
/
Copy pathmain.py
File metadata and controls
217 lines (180 loc) · 6.86 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
import streamlit as st
from app.ui import pdf_uploader
from app.pdf_utils import extract_text_from_pdf
from app.vectorstore_utils import create_faiss_index,retrive_relevant_docs
from app.chat_utils import get_chat_model, ask_chat_model
from langchain_text_splitters import RecursiveCharacterTextSplitter
from dotenv import load_dotenv
import os
import time
from datetime import datetime
from zoneinfo import ZoneInfo
load_dotenv()
EURI_API_KEY = os.getenv("EURI_API_KEY")
st.set_page_config(
page_title="DocQuery AI",
page_icon="🏥",
layout="wide",
initial_sidebar_state="expanded"
)
st.markdown("""
<style>
.chat-message {
padding: 1rem;
border-radius: 0.5rem;
margin-bottom: 1rem;
display: flex;
flex-direction: column;
}
.chat-message.user {
background-color: #2b313e;
color: white;
}
.chat-message.assistant {
background-color: #f0f2f6;
color: black;
}
.chat-message .avatar {
width: 2rem;
height: 2rem;
border-radius: 50%;
margin-right: 0.5rem;
}
.chat-message .message {
flex: 1;
}
.chat-message .timestamp {
font-size: 0.8rem;
opacity: 0.7;
margin-top: 0.5rem;
}
.stButton > button {
background-color: #ff4b4b;
color: white;
border-radius: 0.5rem;
border: none;
padding: 0.5rem 1rem;
font-weight: bold;
}
.stButton > button:hover {
background-color: #ff3333;
}
.upload-section {
background-color: #f8f9fa;
padding: 1rem;
border-radius: 0.5rem;
margin-bottom: 1rem;
}
.status-success {
background-color: #d4edda;
color: #155724;
padding: 0.5rem;
border-radius: 0.25rem;
margin: 0.5rem 0;
}
</style>
""", unsafe_allow_html=True)
if "messages" not in st.session_state:
st.session_state.messages = []
if "vectorstore" not in st.session_state:
st.session_state.vectorstore = None
if "chat_model" not in st.session_state:
st.session_state.chat_model = None
st.markdown("""
<div style="text-align: center; padding: 2rem 0;">
<h1 style="color: #ff4b4b; font-size: 3rem; margin-bottom: 0.5rem;">🏥 DocQuery AI</h1>
<p style="font-size: 1.2rem; color: #666; margin-bottom: 2rem;">Your Intelligent Medical Document Assistant</p>
</div>
""", unsafe_allow_html=True)
# Sidebar for document upload
with st.sidebar:
st.markdown("### 📁 Document Upload")
st.markdown("Upload your medical documents to start chatting!")
uploaded_files = pdf_uploader()
if uploaded_files:
st.success(f"📄 {len(uploaded_files)} document(s) uploaded")
# Process documents
if st.button("🚀 Process Documents", type="primary"):
with st.spinner("Processing your medical documents..."):
# Extract text from all PDFs
all_texts = []
for file in uploaded_files:
text = extract_text_from_pdf(file)
all_texts.append(text)
# Split texts into chunks
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200,
length_function=len,
)
chunks = []
for text in all_texts:
chunks.extend(text_splitter.split_text(text))
# Create FAISS index
vectorstore = create_faiss_index(chunks)
st.session_state.vectorstore = vectorstore
# Initialize chat model
chat_model = get_chat_model(EURI_API_KEY)
st.session_state.chat_model = chat_model
st.success("✅ Documents processed successfully!")
st.balloons()
# Main chat interface
st.markdown("### 💬 Chat with Your Medical Documents")
# Display chat messages
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
st.caption(message["timestamp"])
# Chat input
if prompt := st.chat_input("Ask about your medical documents..."):
# Add user message to chat history
# timestamp = time.strftime("%H:%M")
timestamp = datetime.now(ZoneInfo("Asia/Kolkata")).strftime("%H:%M")
st.session_state.messages.append({
"role": "user",
"content": prompt,
"timestamp": timestamp
})
# Display user message
with st.chat_message("user"):
st.markdown(prompt)
st.caption(timestamp)
# Generate response
if st.session_state.vectorstore and st.session_state.chat_model:
with st.chat_message("assistant"):
with st.spinner("🔍 Searching documents..."):
# Retrieve relevant documents
relevant_docs = retrive_relevant_docs(st.session_state.vectorstore, prompt)
# Create context from relevant documents
context = "\n\n".join([doc.page_content for doc in relevant_docs])
# Create prompt with context
system_prompt = f"""You are MediChat Pro, an intelligent medical document assistant.
Based on the following medical documents, provide accurate and helpful answers.
If the information is not in the documents, clearly state that.
when you are giving an answer make sure that try to take help of llm and give me a full diagnosis of the problem.
Medical Documents:
{context}
User Question: {prompt}
Answer:"""
response = ask_chat_model(st.session_state.chat_model, system_prompt)
st.markdown(response)
st.caption(timestamp)
# Add assistant message to chat history
st.session_state.messages.append({
"role": "assistant",
"content": response,
"timestamp": timestamp
})
else:
with st.chat_message("assistant"):
st.error("⚠️ Please upload and process documents first!")
st.caption(timestamp)
# Footer
st.markdown("---")
st.markdown("""
<div style="text-align: center; color: #666; font-size: 0.9rem;">
<p>🤖 Powered by Euri AI & LangChain | 🏥 Medical Document Intelligence</p>
<p>Built with care and crafted by Tanish Rajput.</p>
<p>Released under the MIT License</p>
</div>
""", unsafe_allow_html=True)