File size: 8,162 Bytes
1c7a288
6c9740a
 
e6bfac3
24ba781
6c9740a
 
ba3ef77
 
 
6c9740a
 
ba3ef77
6c9740a
 
 
 
 
6648f74
 
ba3ef77
6c9740a
 
ba3ef77
 
 
 
 
 
 
6c9740a
ba3ef77
 
6c9740a
 
 
 
 
 
 
 
 
ba3ef77
6c9740a
 
 
 
 
ba3ef77
6c9740a
 
 
ba3ef77
6c9740a
 
 
 
ba3ef77
6c9740a
 
 
ba3ef77
6c9740a
ba3ef77
6c9740a
ba3ef77
6c9740a
 
 
 
ba3ef77
6c9740a
 
 
 
ba3ef77
 
 
 
 
 
 
 
6c9740a
 
 
 
 
 
 
ba3ef77
6c9740a
 
 
ba3ef77
6c9740a
ba3ef77
6c9740a
 
 
ba3ef77
6c9740a
ba3ef77
 
6c9740a
 
ba3ef77
 
 
6c9740a
ba3ef77
 
 
 
 
 
 
 
 
 
 
 
6c9740a
 
 
 
ba3ef77
 
6c9740a
ba3ef77
 
 
 
 
 
 
 
 
 
6c9740a
66d14e0
 
 
 
 
 
 
6c9740a
 
 
 
 
 
 
 
 
 
 
 
 
 
ba3ef77
 
 
 
6c9740a
 
 
 
 
 
 
 
ba3ef77
6c9740a
 
ba3ef77
 
6c9740a
ba3ef77
6c9740a
ba3ef77
6c9740a
 
 
 
 
ba3ef77
66d14e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c9740a
ba3ef77
 
 
6c9740a
 
ba3ef77
 
 
 
 
e6bfac3
6c9740a
ba3ef77
24ba781
66d14e0
 
 
 
 
 
 
 
 
6c9740a
ba3ef77
 
 
 
 
6c9740a
24ba781
ba3ef77
 
6c9740a
 
 
66d14e0
 
 
6c9740a
ba3ef77
 
 
 
 
6c9740a
ba3ef77
 
 
 
 
 
 
 
6c9740a
ba3ef77
66d14e0
 
 
 
ba3ef77
 
 
 
 
 
 
 
 
66d14e0
 
 
 
 
ba3ef77
 
 
 
6c9740a
ba3ef77
6c9740a
 
ba3ef77
 
66d14e0
ba3ef77
 
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
import streamlit as st
import os
import tempfile
from langchain_community.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import FAISS
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain.chains import ConversationalRetrievalChain
from langchain.memory import ConversationBufferMemory
from langchain_community.llms import HuggingFaceHub
import base64

# Set page config with light purple theme
st.set_page_config(
    page_title="EduQuery - Smart PDF Assistant",
    page_icon="πŸ“š",
    layout="wide",
    initial_sidebar_state="collapsed"
)

# Embedded CSS for light purple UI
st.markdown("""
<style>
:root {
    --primary: #8a4fff;
    --secondary: #d0bcff;
    --light: #f3edff;
    --dark: #4a2b80;
}

body {
    background-color: #f8f5ff;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.stApp {
    max-width: 1200px;
    margin: 0 auto;
    padding: 2rem;
}

.header {
    background: linear-gradient(135deg, var(--primary) 0%, var(--dark) 100%);
    color: white;
    padding: 2rem;
    border-radius: 15px;
    margin-bottom: 2rem;
    text-align: center;
    box-shadow: 0 4px 20px rgba(138, 79, 255, 0.2);
}

.header h1 {
    font-size: 2.8rem;
    margin-bottom: 0.5rem;
}

.stButton>button {
    background: linear-gradient(135deg, var(--primary) 0%, var(--dark) 100%);
    color: white;
    border: none;
    border-radius: 25px;
    padding: 0.75rem 2rem;
    font-weight: bold;
    font-size: 1rem;
    transition: all 0.3s ease;
    margin-top: 1rem;
}

.stButton>button:hover {
    transform: scale(1.05);
    box-shadow: 0 5px 15px rgba(138, 79, 255, 0.3);
}

.stTextInput>div>div>input {
    border-radius: 25px;
    padding: 0.9rem 1.5rem;
    border: 1px solid var(--secondary);
    background-color: var(--light);
}

.stTextInput>div>div>input:focus {
    border-color: var(--primary);
    box-shadow: 0 0 0 2px rgba(138, 79, 255, 0.2);
}

.stChatMessage {
    padding: 1.5rem;
    border-radius: 20px;
    margin-bottom: 1rem;
    max-width: 80%;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
}

.stChatMessage[data-testid="user"] {
    background: linear-gradient(135deg, #d0bcff 0%, #b8a1ff 100%);
    margin-left: auto;
    color: #4a2b80;
}

.stChatMessage[data-testid="assistant"] {
    background: linear-gradient(135deg, #e6dcff 0%, #f3edff 100%);
    margin-right: auto;
    color: #4a2b80;
    border: 1px solid var(--secondary);
}

.upload-area {
    background: linear-gradient(135deg, #f3edff 0%, #e6dcff 100%);
    padding: 2rem;
    border-radius: 15px;
    text-align: center;
    border: 2px dashed var(--primary);
    margin-bottom: 2rem;
}

.chat-area {
    background: white;
    padding: 2rem;
    border-radius: 15px;
    box-shadow: 0 4px 20px rgba(138, 79, 255, 0.1);
    height: 500px;
    overflow-y: auto;
}

.footer {
    text-align: center;
    color: #8a4fff;
    padding-top: 2rem;
    font-size: 0.9rem;
    margin-top: 2rem;
    border-top: 1px solid var(--secondary);
}

.spinner {
    color: var(--primary) !important;
}

.stSpinner > div > div {
    border-top-color: var(--primary) !important;
}

.token-input {
    background: var(--light);
    padding: 1rem;
    border-radius: 15px;
    margin-bottom: 1rem;
}
</style>
""", unsafe_allow_html=True)

# Header with gradient
st.markdown("""
<div class="header">
    <h1>πŸ“š EduQuery</h1>
    <p>Smart PDF Assistant for Students</p>
</div>
""", unsafe_allow_html=True)

# Initialize session state
if "vector_store" not in st.session_state:
    st.session_state.vector_store = None
if "chat_history" not in st.session_state:
    st.session_state.chat_history = []
if "qa_chain" not in st.session_state:
    st.session_state.qa_chain = None

# PDF Processing
def process_pdf(pdf_file):
    with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
        tmp_file.write(pdf_file.getvalue())
        tmp_path = tmp_file.name
    
    loader = PyPDFLoader(tmp_path)
    pages = loader.load_and_split()
    
    text_splitter = RecursiveCharacterTextSplitter(
        chunk_size=800,
        chunk_overlap=150
    )
    chunks = text_splitter.split_documents(pages)
    
    embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
    vector_store = FAISS.from_documents(chunks, embeddings)
    
    os.unlink(tmp_path)
    return vector_store

# Setup QA Chain
def setup_qa_chain(vector_store, hf_token=None):
    # Use free open-source model that doesn't require authentication
    repo_id = "google/flan-t5-xxl"  # Free model that doesn't require token
    
    try:
        if hf_token:
            llm = HuggingFaceHub(
                repo_id=repo_id,
                huggingfacehub_api_token=hf_token,
                model_kwargs={"temperature": 0.5, "max_new_tokens": 500}
            )
        else:
            # Try without token (works for some open models)
            llm = HuggingFaceHub(
                repo_id=repo_id,
                model_kwargs={"temperature": 0.5, "max_new_tokens": 500}
            )
    except Exception as e:
        st.error(f"Error loading model: {str(e)}")
        return None
    
    memory = ConversationBufferMemory(
        memory_key="chat_history", 
        return_messages=True
    )
    
    qa_chain = ConversationalRetrievalChain.from_llm(
        llm=llm,
        retriever=vector_store.as_retriever(search_kwargs={"k": 3}),
        memory=memory,
        chain_type="stuff"
    )
    
    return qa_chain

# Hugging Face Token Input
st.markdown("""
<div class="token-input">
    <h3>πŸ”‘ Hugging Face Token (Optional)</h3>
    <p>For better models like Mistral, enter your <a href="https://huggingface.co/settings/tokens" target="_blank">Hugging Face token</a></p>
""", unsafe_allow_html=True)
hf_token = st.text_input("", type="password", label_visibility="collapsed", placeholder="hf_xxxxxxxxxxxxxxxxxx")
st.markdown("</div>", unsafe_allow_html=True)

# File upload section
st.markdown("""
<div class="upload-area">
    <h3>πŸ“€ Upload Your Textbook/Notes</h3>
""", unsafe_allow_html=True)

uploaded_file = st.file_uploader("", type="pdf", accept_multiple_files=False, label_visibility="collapsed")

st.markdown("</div>", unsafe_allow_html=True)

if uploaded_file:
    with st.spinner("Processing PDF..."):
        st.session_state.vector_store = process_pdf(uploaded_file)
        st.session_state.qa_chain = setup_qa_chain(st.session_state.vector_store, hf_token)
        if st.session_state.qa_chain:
            st.success("PDF processed successfully! You can now ask questions.")

# Chat interface
st.markdown("""
<div class="chat-area">
    <h3>πŸ’¬ Ask Anything About the Document</h3>
""", unsafe_allow_html=True)

# Display chat history
for message in st.session_state.chat_history:
    with st.chat_message(message["role"]):
        st.markdown(message["content"])

# User input
if prompt := st.chat_input("Your question..."):
    if not st.session_state.vector_store:
        st.warning("Please upload a PDF first")
        st.stop()
    
    if not st.session_state.qa_chain:
        st.error("Model not initialized. Please check your Hugging Face token or try again.")
        st.stop()
        
    # Add user message to chat history
    st.session_state.chat_history.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.markdown(prompt)
        
    # Get assistant response
    with st.chat_message("assistant"):
        with st.spinner("Thinking..."):
            try:
                response = st.session_state.qa_chain({"question": prompt})
                answer = response["answer"]
            except Exception as e:
                answer = f"Error: {str(e)}"
        st.markdown(answer)
        
    # Add assistant response to chat history
    st.session_state.chat_history.append({"role": "assistant", "content": answer})

st.markdown("</div>", unsafe_allow_html=True)

# Footer
st.markdown("""
<div class="footer">
    <p>EduQuery - Helping students learn smarter β€’ Powered by Flan-T5 and LangChain</p>
</div>
""", unsafe_allow_html=True)